text:
Q: How to do program keep running with checkpoint is failed I am using SenerityBdd + Java. I have some scenarios with a lot steps. When a step gets failure then my program stopped. It's so difficult when doing debug steps because program always stops with failed checkpoint. I also soft assertion lib of java.
Do you have any idea to mark step FAILED but program keep running when having failed checkpoint?

A: You could use SoftAssertions from assertj library.
Adding on to Szprota21's comment, you would need to handle all exceptions.
Assuming that all exceptions are handled for a failing step, you could use below structure in your step definition class to implement soft assertion using assertj library.
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import net.thucydides.core.annotations.Steps;

public class TestStepDefinitionClass {
    private SoftAssertions softAssertions;

    @Steps
    SomeClass SomeClass;

    // Before hook to initialize SoftAssertions object for every scenario
    @Before(order = 1)
    public void setUp() {
        softAssertions = new SoftAssertions();
    }

    // After hook to call assertAll() to invoke soft assertion for every scenario
    @After(order = 1)
    public void tearDown() {
        softAssertions.assertAll();
    }

    @Given("method1")
    public void method1() {
        // The below validation will fail, but since it is soft assertion, it will move on to the next step.
        softAssertions.assertThat(1).isEqualTo(2);
    }

    @Then("method2")
    public void pass2() {
        // assertion passed
        softAssertions.assertThat(2).isEqualTo(2);
    }

    @Then("method2")
    public void pass3() {
        // assertion passed
        softAssertions.assertThat(3).isEqualTo(3);
    }
}

Link for assertj maven repository
To learn about usages and common mistakes, follow Assertj documentation


text:
Q: Default Query String in .htaccess Bit of an odd question, but I'd like to have a query string set on all of my URLs. If the parameter isn't set (or is empty), then I'd like to redirect to include a default.
For example:
example.com would need to requrect to example.com?param=a

example.com?param would also need to redirect to example.com?param=a

If the param is set and is part of a list of known values, then it should carry on as normal:
example.com?param=(a|b|c|d) would go to the respective page a,b,c or d

Some pages of the site use other parameters to sort and paginate, so the rules cannot assume that this is the only query string.
I've tried a couple of things, but kept getting stuck in a redirect loop. This is trying to set the default param:
RewriteCond %{QUERY_STRING} !(^|&)param=(a|b|c|d)($|&)
RewriteRule ^(.*)$ /index.php?rq=$1&param=a [L,QSA]

The main CMS rewrite rule is:
RewriteCond %{REQUEST_URI} !^\/*(index\.php|blog|admin\/assets|site\/assets|robots.txt|sitemap(|\-[0-9]+)\.xml|products.xml|favicon\.ico)
RewriteRule ^(.*)$ /index.php?rq=$1 [L,QSA]

Any help would be great!

A: RewriteCond %{QUERY_STRING} !(^|&)param=(a|b|c|d)($|&)
RewriteCond %{REQUEST_URI} !^\/*(index\.php|blog|admin\/assets|site\/assets|robots.txt|sitemap(|\-[0-9]+)\.xml|products.xml|favicon\.ico)
RewriteRule ^(.*)$ $1?%{QUERY_STRING}&param=a [L]

RewriteCond %{REQUEST_URI} !^\/*(index\.php|blog|admin\/assets|site\/assets|robots.txt|sitemap(|\-[0-9]+)\.xml|products.xml|favicon\.ico)
RewriteRule ^(.*)$ /index.php?rq=$1 [L,QSA]

redpajama_set_name: RedPajamaStackExchange


text:
Q: IV weights for binary instrument and discrete treatment Suppose we have we the structural equation where Y is continuous and T discrete. An example could be $Y$ is wages and $T$ is years of schooling
$$ Y = \alpha + \beta T + u$$
We have a binary excluded instrument $Z$ that monotonically increases $T$ with non-zero first stage at each value of $T$
$$ Z = \gamma + \eta Z + e$$
The IV estimator gives a weighted average of local average treatment effects of shifting people from $T$ to $T'$.
How does the Wald estimator aggregate the different LATEs into one effect? How can we find the weight that specific shifts (for example from 6 to 7 years of schooling) receive in the aggregated estimate?


text:
Q: how to extend emotion styled component with typescript How can I extend the props of an emotion button with my own props?
When I create my own props type, it overrides the component props (so disabled is not defined).
type MyProps = { myCustonProp: any }

const MyButton = styled.button<MyProps>`
${ (props) => props.disabled && "..." } // disabled is not defined in props
${ (props) => props.myCustonProp && "..." } // myCustonProp is defined

const MyButton = styled.button`
${ (props) => props.disabled && "..." } // disabled is defined
${ (props) => props.myCustonProp && "..." } // myCustonProp is not defined in props
`


text:
Q: Flask Error not allowed to load local resource I am trying to develop a flusk application which visualize data from mongodb. When I try to open index.html file I receive some errors as following:
Not allowed to load local resource: file:///D:/adil/project/static/lib/css/bootstrap.min.css
index.html:6
Not allowed to load local resource: file:///D:/adil/project/static/lib/css/keen-dashboards.css
index.html:7
Not allowed to load local resource: file:///D:/adil/project/static/lib/css/dc.css
index.html:8
Seems to a web server error but I run web server from "project" directory and these files are in this directory. I don't understand what is the problem?
Here are the references in index.html:
href="D:/adil/project/static/lib/css/bootstrap.min.css">
href="D:/adil/project/static/lib/css/keen-dashboards.css">
href="D:/adil/project/static/lib/css/dc.css">
Any help?

A: I resolved the problem on my own. I changed links as
href="../static/lib/css/bootstrap.min.css"> and it works


text:
Q: Remove Datepicker rendering from a TableView cell (JavaFX8) I have a TableView with 2 columns "Date" (LocalDate) and "FX" (Double). I have enabled the cell editing and following an example I found here (http://physalix.com/javafx8-render-a-datepicker-cell-in-a-tableview/) I have created a custom CellFactory that displays a DatePicker for the cells of column "Date". This solution though renders the DatePciker immediately, so I changed my code to show the DatePicker only when the user double clicks on any of the (non-empty) Date cells. So far so good…
How do I "go back" and remove the DatePicker rendering from the cell after the user has changed the date or cancelled the input? See the pictures as reference. Pic 1 is the initial state of the list. Pic 2 is after double click. How do I go back to Pic 1 status? Let me know if you need to see my specific code.
Reference pictures
This is the code that checks for the double click and then creates the CellFactory
 fxTable.getSelectionModel().setCellSelectionEnabled(true);
    fxTable.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.getClickCount() == 2) {
                TablePosition pos = fxTable.getSelectionModel().getSelectedCells().get(0);
                int col = pos.getColumn();
                if (col == 0) {

                    //The code below creates the DatePicker in the cell using the DatePickerCell class that I created following the example in the code I found
                    tblDateFX.setCellFactory(new Callback<TableColumn<Map.Entry<LocalDate, Double>, String>, TableCell<Map.Entry<LocalDate, Double>, String>>() {
                        @Override
                        public TableCell<Map.Entry<LocalDate, Double>, String> call(TableColumn<Map.Entry<LocalDate, Double>, String> param) {
                            ObservableMap<LocalDate, Double> items = FXCollections.observableMap(myBasket.getEnrtriesCur(curName));

                            DatePickerCell datePick = new DatePickerCell(items);
                            return datePick;
                        }
                    });
                }
            }
        }
    });

This is the DatePickerCell Class
public class DatePickerCell<S, T> extends TableCell<Map.Entry<LocalDate,Double>, String> {

private DatePicker datePicker;
private ObservableMap<LocalDate,Double> curEntries;

public DatePickerCell(ObservableMap<LocalDate,Double> curEntries) {

    super();

    this.curEntries = curEntries;

    if (datePicker == null) {
        createDatePicker();
    }
    setGraphic(datePicker);
    setContentDisplay(ContentDisplay.GRAPHIC_ONLY);

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            datePicker.requestFocus();
        }
    });
}

@Override
public void updateItem(String item, boolean empty) {

    super.updateItem(item, empty);

    if (null == this.datePicker) {
        System.out.println("datePicker is NULL");
    }

    if (empty) {
        setText(null);
        setGraphic(null);
    } else {

        if (isEditing()) {

            setContentDisplay(ContentDisplay.TEXT_ONLY);

        } else {

            datePicker.setValue(LocalDate.parse(item,df));

            setGraphic(this.datePicker);
            setText(item);
            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);

        }
    }
}

@Override
public void startEdit() {
    super.startEdit();
}

@Override
public void cancelEdit() {
    super.cancelEdit();
    setContentDisplay(ContentDisplay.TEXT_ONLY);
    setGraphic(null);
}

private void createDatePicker() {
    this.datePicker = new DatePicker();
    datePicker.setEditable(true);

    datePicker.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            setGraphic(datePicker);
            setText(df.format(datePicker.getValue()));
        }
    });

    datePicker.setOnAction(new EventHandler() {
        public void handle(Event t) {
            LocalDate date = datePicker.getValue();
            int index = getIndex();

            commitEdit(df.format(date));

            if (null != getCurEntries()) {
                System.out.println("Modify value");

            }
        }
    });

    setAlignment(Pos.CENTER);
}

A: Have you tried the function setOnEditCommit to do reverse of your code?
column.setOnEditCommit((TableColumn.CellEditEvent<MyObject, Date> t) -> {
    //modify the rendering of you cell to normal
});

A: After some research I found out that the default rendering of a cell in a TableView is a label. So I tweaked the DatePickerCell class to render a label in the "updateItem" method and render the DatePicker only when the label is clicked (meaning that the user wants to edit the date in the cell).
In terms of "going back" I added a listener for "ESC keypressed" on the DatePicker so when that key is pressed (during the edit) a label is rendered and the edit is therefore cancelled. That works quite well!
I'm still trying to figure out how to do the same when the user tries to cancel the edit by clicking somewhere else on the screen.
--
So here's my stab at the DatePickerEdit class.
This is doing what I need. Renders the cells normally at first, only when the user clicks on the date cell the datepicker is rendered. If the user clicks away from the cell, the cell goes back to its initial rendering (same happens when "ESC" is pressed whilst editing or indeed a new date is picked).
Note that I am passing to the class the Observable list that contains the values shown in the TableView. In this way I can update the value in the list directly in the class. Not sure if this is a good practice or not, this was a "forced solution" though. Originally I used the "setOnEditCommit" method for the TableColumn but after some testing I noticed that this event is not always called after the cell is updated (i.e. the commitEdit() method is called for the cell). Not sure if this is a bug or there's something wrong in my code. For sure it does not always happen. On multiple runs, I would say that 1 out of 3 showed this bugged behaviour.
Here's the code, not sure if it's a "good" code or not. I would appreciate any advice in merit.
public class DatePickerCell<S, T> extends TableCell<FX, String> {

    private DatePicker datePicker;
    private Label lbl;
    private ObservableList<FX> currencies;

    public DatePickerCell(ObservableList<FX> list) {

        super();

        lbl=new Label();
        this.currencies=list;
        if (datePicker == null) {
            createDatePicker();
        }

    }

    @Override
    public void updateItem(String item, boolean empty) {
//        This section here manages the graphic rendering of each cell
//        As I don't want to generate the datepicker graphics immediately I just render a label
        super.updateItem(item, empty);

        if (empty || item == null) {
            setText(null);
            setGraphic(null);
        } else {
            createLabel(item);
        }
    }

    @Override
    public void startEdit() {
        super.startEdit();
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
    }

    private void createDatePicker() {
        this.datePicker = new DatePicker();
        datePicker.setEditable(true);

//        when the user clicks on the label the DatePicker graphics is generated
        lbl.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {

                datePicker.setValue(LocalDate.parse(lbl.getText(),df));
                setGraphic(datePicker);
                setText(lbl.getText());
                setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                datePicker.requestFocus();
            }
        });

//       This listener manages the "lost focus" on the picker
        datePicker.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
//                This combination of OldValue NewValue is generated whenever there is a click outside the DatePicker "graphic area"
//                i.e. the calendar (when open), the text filed, the calendar icon OR when a NEW date is selected in the calendar.
//                 This last case generates the "OnAction" event as well that is managed below.
                if (oldValue && !newValue) {
                    createLabel(df.format(datePicker.getValue()));
                }
            }
        });

//        This is generated when a NEW date is picked
//        it simply commits the new date and changes the graphics back to a label
        datePicker.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                LocalDate date = datePicker.getValue();
                int index=getIndex();

                if (date!=null) {
                    commitEdit(df.format(date));
                    getCurrencies().get(index).setDate(date);
                    createLabel(df.format(date));
                }
            }
        });

//        added this listener in case the user wants to cancel pressing "ESC"
//        when this happens the label graphics is rendered
        datePicker.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                LocalDate date = datePicker.getValue();
                if (event.getCode()== KeyCode.ESCAPE) {
                    createLabel(df.format(date));
                }
            }
        });

        setAlignment(Pos.CENTER_LEFT);
    }

    private void createLabel(String item) {
        lbl.setMinWidth(getWidth());
        setGraphic(lbl);
        lbl.setText(item);
    }

    public ObservableList<FX> getCurrencies() {
        return currencies;
    }
}


text:
Q: Why is the Unity Package Manager unable to download certain packages (with work PC)? I have used Unity at home (personal hobby) for years with no issues, however I was recently asked to do something at work that required Unity, so I installed it on my work laptop. (I work for a large tech company, however I work from home and do not need to VPN in for work). I first tried to create a "3D (URP)" project, however the project itself failed to be created, as it failed to download certain files, giving me errors similar to what is seen below.
After that, I tried to create a "standard" 3D project, and that worked! At least I could get into the editor now, so I tried to go to the Package manager and add the Universal RP package by hand. I also tried to update the test-framework package. Below are the results:
[Package Manager Window] Cannot perform upm operation: Unable to add package [com.unity.render-pipelines.universal@12.1.10]:
  One or more dependencies could not be added to the local file system:
    com.unity.burst: self signed certificate in certificate chain [NotFound].
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

[Package Manager Window] Error adding package: com.unity.render-pipelines.universal@12.1.10.
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

[Package Manager Window] Cannot perform upm operation: self signed certificate in certificate chain [NotFound].
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

[Package Manager Window] Error adding package: com.unity.test-framework@1.1.33.
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

Has anyone run into this problem? I haven't seen much at all about it on the web, although I did see a mention of someone's workplace somehow not allowing self-signed certificates or something like that? Does that ring a bell for anyone?
I'm trying to figure out "What" it is, so that if it turns out to be environmental somehow, I can least point them to a given solution.
Thanks in advance


text:
Q: Adding an exisiting project that is already in TFS/Git to a new solution? I have a set of "utility" projects that I use across many of my projects. These utility projects are stored in TFS/Git.
When I start a new project what is the proper way to add those utility projects to the new solution so that they maintain binding to the original source code?
If I were not making any changes to the utility classes I would just reference the dlls somewhere and not add the project but the utility projects will be modified during the new project too.
I have tried adding the project from the local repo in Visual Studio but the Git bindings do not seem to carry thru.
Any suggestions or pointers to an article or two?

A: If your new project is also tracked by git, this maybe a case where git submodule command is the suitable solution.
Take a look at documentation.


text:
Q: TYPO3 v10: Remove  tags around paragraphs in custom RTE field (CKeditor) I have a RTE field in my custom extension for TYPO3 10.4 with Fluid Styled Content. The RTE CKEditor automatically wraps each paragraph with a p tag. I'd like to get rid of this p tag. It's just a teaser field where I don't need line breaks or paragraphs.
What I tried so far is to create my own parseFunc via TypoScript to solve the problem during frontend output:
lib.parseFunc_my_teaser < lib.parseFunc_RTE
lib.parseFunc_my_teaser.nonTypoTagStdWrap.encapsLines >
lib.parseFunc_my_teaser.nonTypoTagStdWrap.encapsLines {
  encapsTagList = p
  remapTag.P =
}

In my Fluid template I use the parsefunc like this:
{article.data.teaser -> f:format.html(parseFuncTSPath: 'lib.parseFunc_my_teaser')}

This works and p tags are gone.
But I wonder if there is no nicer solution. I think I need to find a solution to tackle this problem either within the CKEditor configuration or via Page TSconfig. Unfortunately I wasn't able to find a proper approach.
By the way, another problem is, that in the "Info" Backend module of TYPO3 in my installation the view for Page TSconfig filtered by RTE. is empty. Any ideas on this?

A: I actually do that directly within an own RTE preset for CKE4 (tested in TYPO3 8, 9, 10 LTS):
editor.config.format_tags: "p"
editor.config.enterMode: 2
editor.config.shiftEnterMode: 2

With that an editor can't write P-tags. Even not in Source-Mode of CKE4.


text:
Q: Is std::construct_at on const member safe? I have a class Obj with a const member i:
class Obj {
    const int i;
    ...
};

But I need to set i to 0 in my move constructor. (Because if i isn't 0, the destructor will delete stuff, and since I moved the object, that will result in a double free)
Is it safe to modify Obj::i in the move constructor like this?
Obj::Obj(Obj &&other) :
    i(other.i)
{
    std::destroy_at(&other.i);
    std::construct_at(&other.i, 0);
}

From how I understand it, it is safe to do this when std::construct_at replaces other.i with a "transparently replaceable object". But I'm not completely sure what the definition means:

(8) An object o1 is transparently replaceable by an object o2 if:

(8.1) the storage that o2 occupies exactly overlays the storage that o1 occupied, and
(8.2) o1 and o2 are of the same type (ignoring the top-level cv-qualifiers), and
(8.3) o1 is not a complete const object, and
(8.4) neither o1 nor o2 is a potentially-overlapping subobject ([intro.object]), and
(8.5) either o1 and o2 are both complete objects, or o1 and o2 are direct subobjects of objects p1 and p2, respectively, and p1 is transparently replaceable by p2.

(https://eel.is/c++draft/basic#life-8)
From my understanding, at least 8.1, 8.2, and 8.3 apply, but I'm not completely sure, and I don't really understand 8.4 and 8.5.
So am I correct in thinking this should work (in C++20), or would this result in undefined behavior?

A: A potentially-overlapping subobject is a base class subobject or a member marked with [[no_unique_address]]. Obj::i is not so 8.4 applies.
If you take p1 and p2 to be the same object, other, then 8.5 probably applies (an object can transparently replace itself), except in that it doesn't apply recursively (e.g., Obj is a base class/[[no_unique_address]] member of some other class, or the complete object it is part of is const and other has been const_cast or is a mutable member). But it will practically always apply.
But consider just not making it a const member, since you do need to modify it here. Your move constructor should also clear out other (e.g., setting any pointers to nullptr, clearing any file handles, zeroing other stuff), so there is no chance for the destructor to accidentally double delete stuff.


text:
Q: Outlines bars in bar graph ggplot I was wondering if there was a way to outline the bars in my bar graph. I wanted to outline the left, top, and right sides of a bar that is out a group of bars and then outline a group of bars that are clumped together. I have tried a bit with this but haven't had much luck. I am not entirely sure it is possible. I will attach some code for my data, graph, and some images of what I hope the graph will look like
library(ggplot2)
ggplot(df, aes(bar,num, fill = group)) +
  geom_bar(stat = 'identity', width = 5) +
  scale_fill_manual(values = alpha(c("blue"), .3))

Here is the data
df <- structure(list(bar = c(17.5, 27.5, 32.5, 37.5, 42.5, 47.5, 52.5,
57.5, 62.5, 67.5, 72.5, 77.5, 82.5), num = c(1L, 7L, 8L, 11L,
22L, 46L, 43L, 60L, 59L, 40L, 17L, 11L, 1L), group = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "A", class = "factor")), class = "data.frame", row.names = c(NA,
-13L))

This is what the graph currently looks like
and this is what I hope to make

A: You can hack geom_step to do this by adding in the zero length bars.
zeroes <- setdiff(seq(min(df$bar), max(df$bar) + 5, by = 5), df$bar)
df2 <- rbind(df, data.frame(bar = min(df$bar), num = 0, group = "A"))
df2 <- rbind(df2, data.frame(bar = zeroes, num = 0, group = "A"))
df2 <- df2 %>% arrange(bar, num)

library(ggplot2)
ggplot(df2, aes(bar,num, fill = group)) +
  geom_bar(stat = 'identity', , width = 5) +
  geom_step(col = 'red', aes(x = bar - 2.5)) +
  scale_fill_manual(values = alpha(c("blue"), .3))


text:
Q: CORS Issue when added OPENID Active Directory Authentication to Azure App service we have two App services in Azure in tenant A
(a) Web APP (Angualr)
(b) API App (.NET Core)
'Web' App service calls 'API' App service to get data. 'Web' & 'API' app authentication is done by OpenID Active Directory Authentication. When we call the 'API' Service from the browser it works fine, but when we call the 'API' App within 'Web' App we are getting a CORS error
Access to XMLHttpRequest at 'https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/authorize?response_type=code&client_id={client-id}&redirect_uri=https%3A%2F%2F{AP%2F.api.azurewebsites.us%2Flogin%2F{auth provider}%2Fcallback&nonce=4&state=redir%3D%252Fapi%252Fbridge&scope=openid+profile+email' (redirected from 'https://api.azurewebsites.us/api/name') from origin 'https://webui.azurewebsites.us' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Have anyone faced any similar issues, can provide some help on this

A: I think you just need to use an application type / platform of Single Page App rather than Web App, as in step 6 of my blog post.
Azure AD will then add the CORS response headers to pre-flight OPTIONS requests, needed by the SPA.


text:
Q: AngularJS: insert directives based on array with directive names Say I have three (element) directives: <x/> <y/> and <z/>.
module.directive('x', function() {
    return {
        restrict: 'E',
        template: '
{{identifier}}
'
    }
});

the directives for <y/> and </z> are similar.
I also have an array of page configuration objects. Each object has a type and an identifier. The type denotes a directive, and the identifier is some data to be shown inside the template of the directive, in the directive fragment above shown as {{identifier}}.
var pageElements = [
{type: 'x',identifier:'123'},
{type: 'z',identifier:'adf'},
{type: 'x',identifier:'qwe'},
{type: 'y',identifier:'4ed'},
{type: 'y',identifier:'576'}
]

In my page I want something like this:

How to set up my directives etc so that the following output will be generated, and be updated when the pageElements array changes?

123

adf

qwe

4ed

576

A: In your controller you would do something like this:
function myController($scope){
    $scope.pageElements = [
        {type: 'x',identifier:'123'},
        {type: 'z',identifier:'adf'},
        {type: 'x',identifier:'qwe'},
        {type: 'y',identifier:'4ed'},
        {type: 'y',identifier:'576'}
    ];
}

Then in your html, as bmleite suggested  you would have:

{{elem.identifier}}

This would generate

123

adf

qwe

4ed

576

In your angular.module(.... you could then wire up the directives to the class. Every time the pageElements array gets updated, the list will either be changed by adding the new, editing the current ones or removing the ones that are no longer there. Angular takes care of that grunt work for you.


text:
Q: $\lim_n \min(q,x_n)$ exists for all $q \in \mathbb{Q}^+$ implies $\lim_n x_n$ exists in $\overline{\mathbb{R}}^+$ The following property was used to verify the convergence of a sequence $(x_n)_n$ in $\overline{\mathbb{R}}^+:$ if for all $q \in \mathbb{Q}^+,(\min(x_n,q))_n$ converges then $(x_n)_n$ converges in $\overline{\mathbb{R}}^+.$
Any idea how to prove this property ?

A: Let $q_{i}>L$ be fixed, where $q_{i}\in\mathbb{Q}^{+}$.
Also let $\limsup x_{n}=\lim_{k}x_{n_{k}}=L$ and $\liminf x_{n}=\lim_{l}x_{m_{l}}=M$, then $L=\min(L,q_{i})=\lim_{k}\min(x_{n_{k}},q_{i})$.
Keep in mind that both $\{\min(x_{n_{k}},q_{i})\}_{k}$ and $\{\min(x_{m_{l}},q_{i})\}_{l}$ are subsequences of the convergent sequence $\{\min(x_{n},q_{i})\}_{n}$, hence $\lim_{k}\min(x_{n_{k}},q_{i})=\lim_{l}\min(x_{m_{l}},q_{i})$. On the other hand, $\lim_{l}\min(x_{m_{l}},q_{i})=\min(M,q_{i})$.
We conclude that $L=\min(M,q_{i})$, taking $q_{i}\downarrow L$ we get $L=\min(M,L)$, this shows that $L\leq M$ and hence $L=M$.


text:
Q: When implementing a statement-level trigger on a table, is it possible to obtain the OLD and NEW records for all affected rows? In Oracle, you can write a row-level trigger by specifying the FOR EACH ROW clause in the CREATE TRIGGER statement:
CREATE TRIGGER MY_FANCY_TRIGGER
  BEFORE UPDATE ON MY_TABLE
  FOR EACH ROW
BEGIN
  IF :OLD.my_id_column > 4 AND :NEW.some_other_column <> 'foo' THEN
    -- ...
  END IF;
END;

Such a trigger allows you to view the before and after versions of each affected row (:OLD and :NEW respectively). For example, the following statement will cause this trigger to execute once for each row in MY_TABLE:
UPDATE MY_TABLE SET some_other_column = 'bar';

By eliminating the FOR EACH ROW clause, the trigger becomes a statement-level trigger. This means that it only be executed once per statement, regardless of how many rows (if any) were affected by the statement. Unfortunately, statement-level triggers do not have the :OLD and :NEW variables available (because the number of affected rows many vary).
Is it possible to obtain the :OLD and :NEW values for all affected rows inside a statement-level trigger? I have some processing that I would prefer to only occur once per statement.

A: Not directly, no.
The standard approach is the "three-trigger solution" (more commonly used when you're trying to work around a mutating table problem)

*

*Create a package that contains a collection of keys to your table

*Create a before statement trigger that initializes the collection

*Create a row-level trigger that inserts the keys into the collection.

*Create an after statement trigger that uses the keys in the collection to do its processing

Obviously, in your case, this probably just adds complexity to the process if your row-level trigger isn't causing a mutating table error.
As josephj1989 points out below, if you happen to be using 11g, you can use compound triggers to simplify this a bit.  You'll still declare a collection, populate the collection in a row-level trigger body, and process the collection in the statement-level trigger.  But there will be just one object to create and manage rather than multiple objects.

A: One approach is the one suggested by Justin Cave to store away information in row level triggers in a separate package collections.
If you are using 11g then the right approach will be to use Compound triggers. This avoids the creation of separate package to hold  the keys collection- it can be done in the trigger itself,


text:
Q: SQL - IN instead of UNION How can I achieve the same result set from the below query using IN instead of UNION?
select course_id
from section
where semester = 'Fall'
  and year = '2009'

union

select course_id
from section
where semester = 'Spring'
  and year = '2010';

A: Start with or:
select course_id
from section
where (semester = 'Fall' and year = '2009') or
      (semester = 'Spring' and year = '2010');

If a course_id could be on more than one row, then use select distinct.  The union does the distinct automatically.
Some databases support a tuple format, allowing you to do:
select course_id
from section
where (semester, year) in ( ('Fall', '2009'), ('Spring', '2010'));

Some, but not all.  So, this may or may not work on the database you are using.


text:
Q: How to parse content of external webpage I need to know a way to create a curl script which can do the following things:

*

*Login to a specific webpage which uses a POST formular

*after the login I need to open and parse a specific url

*on this page I just need the value from a div with a specific known ID.

Is something like this possible with a PHP curl Script? Could someone give me a starting point to get this problem solved?

A: Here's some code to get you started. I have added some comments to let you see what its doing each step of the way:
<?php

// Define the URL and the data you want to send
$url = 'http://stackoverflow.com/';
$myvars = 'myvar1=sometestdata';

// Now try and download the webpage
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

// Create a DOMDocument for parsing the HTML
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($response);

// Find the element with an ID of 'nav-questions'
$data = $dom->getElementById("nav-questions");
echo $data->nodeValue;


text:
Q: How can I center and widen out my JPanel in my JFrame? I am making a copy of the apple calendar application, and I am having trouble aligning the month name and year name with the center of my screen, while aligning the left and right buttons with the left and right sides of the screen. Here is my code:
final JPanel months = new JPanel();
months.setLayout(new BoxLayout(months,BoxLayout.X_AXIS));
months.add(back, BorderLayout.WEST); //back is a JButton
JLabel monthName = new JLabel(this.monthNames[this.month]+" ", SwingConstants.CENTER);
JLabel year = new JLabel("" + this.year, SwingConstants.CENTER);
monthName.setFont(new Font("Helvetica", 0, 24));
year.setFont(new Font("Helvetica", 0, 24));
monthName.setHorizontalAlignment(JLabel.CENTER);
months.add(monthName, BorderLayout.CENTER);
months.add(year, BorderLayout.CENTER);
months.add(front, BorderLayout.EAST);
add(months);

Yet it shows up like this:

A: months.setLayout(new BoxLayout(months,BoxLayout.X_AXIS));

You are using a BoxLayout. A BoxLayout just adds the components horizontally to the panel. The WEST, CENTER, EAST constrains are only used by a BorderLayout so they are ignored by the BoxLayout.
months.add(monthName, BorderLayout.CENTER);
months.add(year, BorderLayout.CENTER);

When using a BorderLayout you can only add a single component to a region of the layout. So if you want to add two components to the CENTER you need to first create a panel and add the components to the panel.
So your basic code might be something like:
JPanel centerPanel = new JPanel();
centerPanel.add(month);
centerPanel.add(year);

JPanel mainPanel = new JPanel( new BorderLayout() );
mainPanel.add(westButton, BorderLayout.WEST);
mainPanel.add(centerPanel, BorderLayout.CENTER);
mainPanel.add(eastButton, BorderLayout.EAST);


text:
Q: Is it possible to support multiple Login Path identity in .net core?
I am using identity in Asp.net Core 3.0. I have two login pages like (/Account/AdminLogin) and (/Account/UserLogin) And two roles Admin and User.

My issue is that when I use [Authorize] tag into the controller when session out it return to me in (/Account/AdminLogin) page because it's set on startup file.

For Admin login it should be after logout URL (/Account/AdminLogin)

For User login it should be after logout URL (/Account/UserLogin)

services.ConfigureApplicationCookie(options =>
                {
                    // Cookie settings
                    options.Cookie.Name = "Cookie";
                    options.Cookie.HttpOnly = true;
                    options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
                    options.LoginPath = "/Account/AdminLogin";
                    options.AccessDeniedPath = "/Account/AccessDenied";
                    options.LogoutPath = "/Account/Logout";
                    options.SlidingExpiration = true;
                });

A: You can overwrite the OnRedirectToLogin event on the options.
Something like this
services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.Name = "Cookie";
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
    options.LoginPath = "/Account/UserLogin";
    options.AccessDeniedPath = "/Account/AccessDenied";
    options.LogoutPath = "/Account/Logout";
    options.SlidingExpiration = true;

    options.Events.OnRedirectToLogin = context =>
    {
        if (IsAdminContext(context))
        {
            var redirectPath = new Uri(context.RedirectUri);
            context.Response.Redirect("/Account/AdminLogin" + redirectPath.Query);
        }
        else
        {
            context.Response.Redirect(context.RedirectUri);
        }

        return Task.CompletedTask;
    };
});

In IsAdminContext you need to distinguish if for the given request you want to forward the user to the normal user login or to the admin login. A possible implementation could look like this. Where for all urls starting with /admin you would forward to the admin login.
private static bool IsAdminContext(RedirectContext<CookieAuthenticationOptions> context)
{
    return context.Request.Path.StartsWithSegments("/admin");
}


text:
Q: Embed Image into video - FFMPEG or JW player? So I thought to embed the image as part of video content while converting the m4a to mp4. The output file has the image as video content and it plays as expected in VLC but when the same was streamed from my CDN using JW player, I do not see the image as video content, still it is black and audio is heard. Not sure what is the issue with embeding. I used the FFMPEG to embed image as video content.
On the other hand is there any posibility with JW player to overlay an image as video content while audio can be heard in back end?

A: You need
to loop
the image
ffmpeg -loop 1 -r 1 -i img.png -i audio.m4a -shortest -filter:v \
  'crop=trunc(iw/2)*2:trunc(ih/2)*2' out.mp4

*

*repeat image over and over

*once per second

*stop video when audio stops

*cut image to even dimensions if necessary


text:
Q: Does $f \mid f(x^{p_1}), f(x^{p_2}) \implies f \mid f(x^{p_1 p_2})$? Hypothesis:

*

*Let $p$ be a prime positive integer.

*$f = a_0 + a_1x + \ldots + a_nx^n \in \mathbb{Z}[x]$

*Suppose that $f \mid f(x^{p_1})$ and $f \mid f(x^{p_2}) \in  \mathbb{Z}[x]$
Question: Does $f \mid f(x^{p_1 p_2})$?


text:
Q: Tool for automatic Windows file sync, no GUI? I'm writing a script on Windows 8 that will set up automatic file syncing between two folders. I am looking for a syncing utility that has the following properties (roughly in order of importance):

*

*can be called from a batch script, has reasonable documentation (doesn't HAVE to be a batch script, the script could be in Python or something, but it cannot use any proprietary software)

*automatic updating (as soon as an item is changed in the source folder it updates in the destination folder)

*free

*incremental updates (does not copy all the files every time)

I've researched a bunch of options, but I mostly seem to find utilities with GUIs or that cannot update automatically. Any thoughts?
Edit
Thanks guys. It looks like there isn't anything that does exactly all these things, but I thought it was worth a shot to avoid reinventing the wheel. I'll look into rsync combined with some sort of folder monitoring utility to get the auto-updating to work.

A: Take a look at Robocopy. I believe it still comes bundled with Windows 8 and can be configured to do what you need.

A: Checkout this answers https://stackoverflow.com/questions/528298/rsync-for-windows. On any unix type system rsync works like a charm

A: You can create a scheduled task from the command line: http://www.howtogeek.com/51236/how-to-create-modify-and-delete-scheduled-tasks-from-the-command-line/
SchTasks /Create /SC DAILY /TN "My Task" /TR "C:RunMe.bat" /ST 09:00

And use the appropriate strings in Robocopy (included in most current versions of windows) to tell it to sync the folders: http://improve.dk/simple-file-synchronization-using-robocopy/
robocopy \\SourceServer\Share \\DestinationServer\Share /MIR /FFT /Z /XA:H /W:5

You could possibly replace the "C:RunMe.bat" line in the SchTasks command with your desired robocopy arguments to fit the whole thing into a single batch file. Though, for management sake, I'd keep them as two separate files just kept together.


text:
Q: How to plot 3D function as 2D colormap in python? Are there any python libraries that will let me plot z = f(x,y) where z is represented as the color in a densely rasterized image (as opposed to the color of a bunch of scatterplot points) ? If so, what function do I use?
It looks like some of the contour functions in matplotlib.pyplot come close to what I want, but they draw contour lines and I don't want that.

A: here's a concrete simple example (works also for functions which can't take matrix arguments for x and y):
# the function to be plotted
def func(x,y):
    # gives vertical color bars if x is horizontal axis
    return x

import pylab

# define the grid over which the function should be plotted (xx and yy are matrices)
xx, yy = pylab.meshgrid(
    pylab.linspace(-3,3, 101),
    pylab.linspace(-3,3, 111))

# indexing of xx and yy (with the default value for the
# 'indexing' parameter of meshgrid(..) ) is as follows:
#
#   first index  (row index)    is y coordinate index
#   second index (column index) is x coordinate index
#
# as required by pcolor(..)

# fill a matrix with the function values
zz = pylab.zeros(xx.shape)
for i in range(xx.shape[0]):
    for j in range(xx.shape[1]):
        zz[i,j] = func(xx[i,j], yy[i,j])

# plot the calculated function values
pylab.pcolor(xx,yy,zz)

# and a color bar to show the correspondence between function value and color
pylab.colorbar()

pylab.show()

A: Take a look at the documentation for pcolor or imshow in matplotlib.
Another good place to start is take a look at the matplotlib gallery and see if there is a plot type that matches what you are looking for and then use the sample code as a jumping off point for your own work:
http://matplotlib.sourceforge.net/gallery.html

A: To give credit where it's due: this is only a slight variation on Andre Holzner's answer. Please upvote him if you must!
import pylab

def f(x, y):
    return pylab.cos(x) + pylab.sin(y)

xx = pylab.linspace(-5, 5, 100)
yy = pylab.linspace(-5, 5, 100)
zz = pylab.zeros([len(xx), len(yy)])

for i in xrange(len(xx)):
    for j in xrange(len(yy)):
        zz[j, i] = f(xx[i], yy[j])

pylab.pcolor(xx, yy, zz)
pylab.show()

The syntax is perhaps easier to read with the strict minimum of array dimensions and indices. It relies on the following point (quoted from the doc).
If either or both of X and Y are 1-D arrays or column vectors, they will be expanded as needed into the appropriate 2-D arrays, making a rectangular grid.

A: To expand my comment above, here are some possible ways of computing a function on a grid
boffi@debian:~/Documents/tmp$ cat grid.py
import numpy as np

def z(x,y):
  return np.sin(np.sqrt(x*x+y*y))

x = np.linspace(-1,1,11)
y = np.linspace(-2,2,21)

# naive

Z0 = np.zeros((len(y), len(x)))
for i, X in enumerate(x):
    for j, Y in enumerate(y):
        Z0[j,i] = z(X,Y)

# trampoline on a double list comprehension,
# it is possibly faster, sure it uses more memory

Z1 = np.array([[z(X,Y) for X in x] for Y in y])

# numpy has meshgrid,
# meshgrid uses twice memory as the result matrix but
# if used _correctly_ it's FAST

X, Y = np.meshgrid(x, y)

# numpy can avoid you explicit looping,
# but if you are so inclined...

Z2 = np.zeros((len(y), len(x)))
for r in range(len(y)):
    for c in range(len(x)):
        Z2[r, c] = z(X[r, c], Y[r, c])

# numpy has ufuncs, and
# t h i s   i s   t h e   w a y   t o   g o

Z3 = z(X, Y)

# numpy has broadcasting (it's slower than Z = z(X, Y), less memory)

Z4 = z(x, y[:,None])

# note that x is still a _row_ of numbers, indexed by _columns_,
# while y[:,None] is now a _column_ of numbers, indexed by _rows_,
# so that Z4[row,column] <-- z(x[column], y[row])

# a bit of testing

# in previous answers, Z2 (i.e., explicit loops)
# is the preferred method --- here we show that the other four
# possible methods give you exactly the same result

print np.all(Z2==Z0)
print np.all(Z2==Z1)
print np.all(Z2==Z3)
print np.all(Z2==Z4)
boffi@debian:~/Documents/tmp$ python2 grid.py
True
True
True
True
boffi@debian:~/Documents/tmp$


text:
Q: Render additional info in cell when row is hovered in ag-grid I am using angular (^8.2.14) and ag-grid-community (^20.1.0).
I try to achieve the following effect: when the user hovers a specific row, one column shows an additional button which may be clicked.
What does work?
The column with the wanted behaviour gets rendered by a custom cell renderer component which implements the ICellRendererAngularComponent interface. There I can inject the ElementRef and on the lifecycle hook AfterContentChecked I check the parents' parent for the css-class 'ag-row-hover' and if it's there, I will show this additional button in the renderer component.
custom-cell.component.ts
@Component({
  selector: 'app-custom-cell',
  template: `
      <ng-container *ngIf="hovered; else notHovered">{{form.value * form.value}}
        <button (click)="doStuff(form.value)">show root</button></ng-container>
      <ng-template #notHovered>{{form.value + form.value}}</ng-template>
  `,
})
export class CustomCellComponent implements ICellRendererAngularComp, AfterContentChecked {
  form: FormControl;
  params: ICellRendererParams;
  hovered = false;

  constructor(private elementRef: ElementRef) {
  }

  doStuff(val) {
    alert(val);
  }

  ngAfterContentChecked() {
    this.hovered = (this.elementRef.nativeElement as HTMLElement)
      .parentElement
      .parentElement
      .classList.contains('ag-row-hover');
  }
}

The source code for this is on github
What do I want to improve?
I want to improve the performance and not having explicit checks for this behaviour. I'd rather have a directive with the css-selector '.ag-row', which I can inject to the ICellRendererAngularComponent and then check for the css class '.ag-row-hover' on every check. Or have a directive with the css-selector '.ag-row-hover' which is there, or is not. Anyone has any ideas how to improve my existing solution?

A: You could actually achieve the desired behavior with CSS only, no need to inject ElementRef or do anything via Angular Lifecycle Callbacks.
That being said, your custom renderer could look something like this:
@Component({
  selector: "app-custom-cell",
  template: `

        {{ form.value * form.value }}
        <button (click)="doStuff(form.value)">show root</button>

{{ form.value + form.value }}

  `
})
export class CustomCellComponent
  implements ICellRendererAngularComp {
  form: FormControl;
  params: ICellRendererParams;

  constructor() {}

  doStuff(val) {
    alert(val);
  }

//... other stuff

}

In your styles.scss (or somewhere it fits better, just make sure the styles apply), just add these rules:
div.visible-on-hover {
  display: none;
}

.ag-row-hover {
  div.visible-on-hover {
    display: block;
  }

  div.hidden-on-hover {
    display: none;
  }
}

Conceptually, the browser rendering engine then does what you did in ngAfterContentChecked().


text:
Q: SQL Query - Row to columns not really a pivot I'm trying to move certain fields of an ID into columns, but it doesn't appear to match all the pivot examples I am finding. All the examples I can find use some form of a grouping on a field value.  I want to use more of a placement regardless of the value in the field. I want to do this in a query without looping via code. Data source example (sorry couldn't figure out how to format a table on the post so I used a code snippet):
+----+--------+--------+
| ID | Field1 | Field2 |
+----+--------+--------+
|  1 | NULL   | NULL   |
|  2 | Jim    | 321    |
|  2 | Jack   | 54     |
|  2 | Sue    | 985    |
|  2 | Gary   | 654    |
|  3 | Herb   | 332    |
|  3 | Chevy  | 10     |
+----+--------+--------+

Result set I'm trying to generate:
+----+------+------+-------+------+------+------+
| ID | Col1 | Col2 | Col3  | Col4 | Col5 | Col6 |
+----+------+------+-------+------+------+------+
|  1 | NULL | NULL |       |      |      |      |
|  2 | Jim  | 321  | Jack  |   54 | Sue  |  985 |
|  3 | Herb | 332  | Chevy |   10 |      |      |
+----+------+------+-------+------+------+------+

A: SQL Fiddle: http://sqlfiddle.com/#!3/a225a/1
;with cte as (
    select id
    , field1
    , field2
    , ROW_NUMBER() over (partition by id order by field1, field2) r
    from @t
)
select c1.id
, c1.field1 col1
, c1.field2 col2
, c2.field1 col3
, c2.field2 col4
, c3.field1 col5
, c3.field2 col6
from cte c1
left outer join cte c2 on c2.id = c1.id and c2.r = c1.r + 1
left outer join cte c3 on c3.id = c1.id and c3.r = c1.r + 2
where (c1.r % 3) = 1

Explanation
ROW_NUMBER() over (partition by id order by field1, field2) r.  This line ensures that we have a column counting up from 1 for each id.  This allows us to distinguish between the multiple rows.
The CTE is used to save typing the same statement for c1, c2 and c3.
The joins ensure that all items in a row have the same id, and that data for col1, col3 and col5 (likewise for col2, col4 and col6) is taken from consecutive rows.  We're using left outer joins because there may not rows in the source table for these columns.
The where statement says to take the first row of each set of 3 for the data in c1 (with c2 and c3 thus being the second and third of each set, thanks to the earlier join).

A: Here's a solution using dynamic sql that works though I'm sure there's a better way to do it. Caution, it's a bit painful. First it builds the list of columns to pivot and select, builds the dynamic sql and runs it.
DECLARE @PivotColumns as varchar(max), @SelectColumns as varchar(max), @sql as varchar(max)

SELECT @PivotColumns = ISNULL(@PivotColumns + ',', '') + ColNum,
       @SelectColumns = ISNULL(@SelectColumns + ',', '') + 'NULLIF(' + ColNum + ', ''NULL'') as ' + ColNum
from (select distinct 'Col' + cast(ROW_NUMBER() OVER (partition by id order by id) as varchar) as ColNum
     from (select id,
                  isnull(field1,'NULL') as field1,
                  isnull(field2,'NULL') as field2
            from weirdpivot) cols
unpivot
(
    value
    for col in (field1, field2)
) unpivoted) DistinctColumns

set @sql = '
select id, + ' + @SelectColumns + '
from (select
        ''Col'' + cast(ROW_NUMBER() OVER (partition by id order by id) as varchar) as colnum
        ,id
        ,value
        from (select id,
                     isnull(field1,''NULL'') as field1,
                     isnull(field2,''NULL'') as field2
              from weirdpivot) cols
unpivot
(
    value
    for col in (field1, field2)
) u) unpivoted
pivot
(
    max(value)
    for colnum in (' + @PivotColumns + ')
) p'

exec (@sql)


text:
Q: Segregating Lists in Prolog I am having a really hard time understanding how to get my code to show my segregated lists consisting of even and odd numbers. I am not even sure what my understanding is lacking. I am new to this language obviously and must use it for school. My imperative and functional mind won't let me know what the hell is going on with this lol.
Now, no I am not asking you to do my homework! I am simply asking you to help me see what my lack of understanding is. I have also looked up similar answers but I cannot convert them to the way I am supposed to write this function.
Please, once more, do not bash me for this like I have previously usually been bashed. Please just help me see what my understanding is lacking. Do not just give me answers and code snippets without explaining it please.
Here it is:
is_even(H) :-
   0 is mod(H, 2).

segregate(List, Even, Odd) :- segregator(List, Even, Odd).

segregator([], [], []).
segregator([H|T], E, O) :-
    is_even(H),
    % I feel here is where I am supposed to build the list,
    % but I have no clue how since Even or Odd has not been unified.
    segregator(T, E, O),
    write('Even is '), write(E), nl.
segregator([H|T], E, O) :-
    % Same here as above.
    segregator(T, E, O),
    write('Odd is '), write(O), nl.

A: A logically pure implementation is very straight-forward, thanks to clpfd:
:- use_module(library(clpfd)).

list_evens_odds([],[],[]).
list_evens_odds([X|Xs],[X|Es],Os) :-
   X mod 2 #= 0,
   list_evens_odds(Xs,Es,Os).
list_evens_odds([X|Xs],Es,[X|Os]) :-
   X mod 2 #= 1,
   list_evens_odds(Xs,Es,Os).

Some sample queries we expect to succeed (with a finite sequence of answers):
?- Xs = [1,2,3,4,5,6,7], list_evens_odds(Xs,Es,Os).
Xs = [1,2,3,4,5,6,7],
Es = [  2,  4,  6  ],
Os = [1,  3,  5,  7] ;
false.

?- list_evens_odds(Ls,[2,4],[1,3]).
Ls = [2,4,1,3] ? ;
Ls = [2,1,4,3] ? ;
Ls = [2,1,3,4] ? ;
Ls = [1,2,4,3] ? ;
Ls = [1,2,3,4] ? ;
Ls = [1,3,2,4] ? ;
no

What about queries we expect to fail?
?- list_evens_odds(Ls,[2,4,5],[1,3]).
no
?- list_evens_odds(Ls,[2,4],[1,3,6]).
no
?- list_evens_odds([_,_,_],[2,4],[1,3]).
no

At last, the most general query:
?- assert(clpfd:full_answer).
yes

?- list_evens_odds(Ls,Es,Os).
Ls = [],   Es = [],   Os = []                              ? ;
Ls = [_A], Es = [_A], Os = [], _A mod 2#=0, _A in inf..sup ? ...

Edit 2015-05-06
Here's another way to do it with logical-purity!
Use the meta-predicate tpartition/4 together with zeven_t/2 or zodd_t/2.
bool01_t(1,true).
bool01_t(0,false).

zeven_t(Z,Truth) :- Z mod 2 #= 0 #<==> B, bool01_t(B,Truth).

%zodd_t(Z,Truth) :- Z mod 2 #= 1 #<==> B, bool01_t(B,Truth).
zodd_t(Z,Truth)  :- Z mod 2 #=         B, bool01_t(B,Truth). % tweaked

zeven_t/2 reifies the evenness of an integer, zodd_t/2 the oddness.
With everything in place, let's run some queries!

?- tpartition(zeven_t,[1,2,3,4,5,6,7],Es,Os).
Es = [2,4,6], Os = [1,3,5,7].
?- tpartition(zodd_t ,[1,2,3,4,5,6,7],Os,Es). % argument order differs
Es = [2,4,6], Os = [1,3,5,7].

Both succeed deterministically. The equivalent query using list_evens_odds/3 does not.


text:
Q: A criterion for real-rooted polynomials with nonnegative coefficients Let $P \in \mathbb{R}[X]$, with $\deg P = n$. Is it true that
$P$ has only real roots $\quad \Longleftrightarrow \quad P\cdot P'' + (\frac{1}{n}-1)P'^2 \leq 0$ ?
The direct implication can be shown by using Cauchy-Schwarz inequality, but I still lack the reverse (if true).

I apologize to those who have already answered, but a new condition arise: what if $P$ has only nonnegative coefficients?

A: Also simply for $P(x)=x^4-1$ we have
$$P\cdot P''+\left(\frac{1}{4} -1 \right)\left(P'\right)^2=-12x^2\leq 0$$
and $P$ has imaginary roots.

The stronger version is also false. Take $P(x)=x^5-x$ which satisfies
$$P\cdot P''+\left(\frac{1}{5} -1\right)\left(P'\right)^2=-12x^4-\frac45<0$$
yet it has complex roots.

A: It seems that inverse fails in general.
In terms of roots $z_1,\dots,z_n$ your inequality $P\cdot P'' + (\frac{1}{n}-1)P'^2 \leqslant 0$ may be rewritten as $\sum_{1\leqslant j<k\leqslant n} (\frac1{x-z_j}-\frac1{x-z_k})^2\geqslant 0$ for real $x$. Try a polynomial with roots $i,-i$, $1$ with multiplicity $m$, $0$ with multiplicity $m$. Then, multiplying by $(x-1)^2x^2$ we get $m^2+O(m)$, since any expression $x(x-1)(\frac1{x-z_j}-\frac1{x-z_k})$ is obviously uniformly bounded on the whole real line. But $m^2+O(m)$ guy is positive if $m$ is large enough.


text:
Q: Missing 'build' directory in Debian 10.6 I'm trying to compile https://github.com/betolj/ndpi-netfilter on Debian Buster 10.6.
In short I get this error:
make[2]: *** /lib/modules/4.19.0-11-cloud-amd64/build: No such file or directory.  Stop.

These are the steps I have done:
apt install libtool libpcap-dev iptables-dev
apt install conntrack libnetfilter-conntrack-dev
cd /home/admin
git clone https://github.com/betolj/ndpi-netfilter
cd ndpi-netfilter
tar -xvzf nDPI.tar.gz
cd nDPI
./autogen.sh
cd ..
NDPI_PATH=/home/admin/ndpi-netfilter/nDPI make

And I get this error:
make -C ipt
make[1]: Entering directory '/home/admin/ndpi-netfilter/ipt'
if test -d ndpi_cpy; then \
    cp /home/admin/ndpi-netfilter/nDPI/src/* ndpi_cpy -R; \
else \
    mkdir ndpi_cpy; \
    cp /home/admin/ndpi-netfilter/nDPI/src/* ndpi_cpy -R; \
fi
make libxt_ndpi.so
make[2]: Entering directory '/home/admin/ndpi-netfilter/ipt'
make[2]: 'libxt_ndpi.so' is up to date.
make[2]: Leaving directory '/home/admin/ndpi-netfilter/ipt'
rm -r ndpi_cpy
make[1]: Leaving directory '/home/admin/ndpi-netfilter/ipt'
make -C src
make[1]: Entering directory '/home/admin/ndpi-netfilter/src'
if test -d ndpi_cpy; then \
    cp /home/admin/ndpi-netfilter/nDPI/src/* ndpi_cpy -R; \
else \
    mkdir ndpi_cpy; \
    cp /home/admin/ndpi-netfilter/nDPI/src/* ndpi_cpy -R; \
fi
cp ndpi_cpy/../../nDPI-patch/src/* ndpi_cpy/ -R;
cp ndpi_cpy/lib/third_party/src/*.c ndpi_cpy/lib -R;
cp ndpi_cpy/lib/third_party/include/*.h ndpi_cpy/lib -R;
cp ndpi_cpy/lib/third_party/include/*.h ndpi_cpy/include -R;
sed -i "s/^\s*void ndpi_free_flow/\/\/void ndpi_free_flow/" ndpi_cpy/include/ndpi_api.h;
make -C /lib/modules/4.19.0-11-cloud-amd64/build M=$PWD;
make[2]: Entering directory '/home/admin/ndpi-netfilter/src'
make[2]: *** /lib/modules/4.19.0-11-cloud-amd64/build: No such file or directory.  Stop.
make[2]: Leaving directory '/home/admin/ndpi-netfilter/src'
make[1]: *** [Makefile:161: all] Error 2
make[1]: Leaving directory '/home/admin/ndpi-netfilter/src'
make: *** [Makefile:6: all] Error 2

What am I missing, please?

A: You need to install the kernel headers (which include the module build infrastructure):
sudo apt install linux-headers-$(uname -r)


text:
Q: JQuery Page Load Event to only run once My problem currently is I have:
require(["jquery"], function ($) {
    jQuery(document).ready(function(){
        $("#update_cart_button").click();
    });
});

However, the button click itself also refreshes to the page to update cart values. Is there a way that I can make this button event fire only once and then when the page loads again from the button click it is not fired a second time? Currently this code causes the page to get stuck in an infinite loop of refreshing the page and pressing the update_cart_button.


text:
Q: How can I make twitter style's transparent square fluid that's going across vertically? Can anyone help me to implement transparent square fluid with bootstrap?(https://twitter.com/ladygaga)
also I'd like to know how to implement rounded square in that transparent square.
Thanks in advance!!

A: It seems they're just using a semitransparent background image on that div to get the glassy texture. The image or background-color(such as RGBA(0,0,0,0.2)) would need to have it's alpha channel set to something other than 100%. Their CSS looks like this.
.wrapper, .wrapper-narrow, .wrapper-permalink {
    position: relative;
    width: 837px;
    min-height: 100%;
    padding: 54px 14px 15px;
    margin: 0 auto;
    background: url(../img/wash-white-30.png);
}

Assuming you were going to use a similar approach. With a 'wrapper' class providing the transparent background, and a 'whitebg' class providing the solid white background:

      content..

with this CSS to give you what you need for your class:
.whitebg {
  background-color:white;
}

A: The transparent DIV (not square :)) is implemented with a PNG image that has an alpha channel, as follows:
.wrapper, .wrapper-narrow, .wrapper-permalink {
    background: url("../img/wash-white-30.png") repeat scroll 0 0 transparent;
    margin: 0 auto;
    min-height: 100%;
    padding: 54px 14px 15px;
    position: relative;
    width: 837px;
}

As far as rounded corners are concerned, on that page, they are implemented as follows:
.module, .promptbird {
    background-clip: padding-box;
    border-radius: 6px 6px 6px 6px;
    line-height: 16px;
    margin-bottom: 10px;
    position: relative;
}

For your requirements in bootstap, merely using the css opacity property for your div, and the border radius property for your inner divs will do the trick.
.transparentDiv { /*make any SQUARE transparent!*/
    background: #fff; /*white*/
    opacity: 0.5 /*will not work in older IE versions, add filter for it!*/
    margin: 0 auto; /* optionally, center it! */
}

.roundedDiv {
    border-radius: 3px 3px 3px 3px; /* 3px looks way cool! */
}

usage:

I see through you baby!

Love makes the world go round!

A: Use a transparent color for your background-color using an rgba color value. That's how you get the transparency.
For the rounded corners, make it easy by using border-radius.
Here's a fiddle containing all the stuff you want - http://tinkerbin.com/j5A3fKHl


text:
Q: ForEach Error: Thread 1: Fatal error: Index out of range I have a foreach loop for the amount of some textfields.
Every thing works but the only thing that is not working is when I send a form.
I get the error:
Thread 1: Fatal error: Index out of range

But when I restart the app the information that I put in wil go to the Firestore database.
I think that I mis something in the foreach loop.
The code from the foreach loop is:
@Published var boxNumberIdentificatie: [String] = [""]

let aantal = routesData.boxNumberIdentificatie.count

ForEach(0...aantal, id: \.self){i in
       Section(header: Text("BoxIdentificatie (\(i))")) {
         TextField("", text: $routesData.boxNumberIdentificatie[i])
         .font(isMacOS() ? .title3 : .body)

         }
    }

The error is in this line:
TextField("", text: $routesData.boxNumberIdentificatie[i])

I hope that somebody can help me..
Thanks a lot.

A: ForEach(0...aantal, id: \.self){i in

This is counting one-past the end of the list. You meant:
ForEach(0..<aantal, id: \.self){i in


text:
Q: R using my own model in RFE(recursive feature elimination) to pick important feature Using RFE, you can get a importance rank of the features, but right now I can only use the model and parameter inner the package like: lmFuncs(linear model),rfFuncs(random forest)
it seems that
caretFuncs

can do some custom settings for your own model and parameter,but I don't know the details and the formal document didn't give detail, I want to apply svm and gbm to this RFE process,because this is the current model I used to train, anyone has any idea?

A: I tried to recreate working example based on the documentation. You correctly identified use of caretFuncs, you can then set your model parameters in rfe call (you can also define trainControl object etc).
# load caret
library(caret)

# load data, get target and feature column labels
data(iris)
col_names = names(iris);target = "Species"
feature_names = col_names[col_names!=target]

# construct rfeControl object
rfe_control = rfeControl(functions = caretFuncs, #caretFuncs here
                     method="cv",
                     number=5)

# construct trainControl object for your train method
fit_control = trainControl(classProbs=T,
                        search="random")

# get results
rfe_fit = rfe(iris[,feature_names], iris[,target],
             sizes = 1:4,
             rfeControl = rfe_control,
             method="svmLinear",
             # additional arguments to train method here
             trControl=fit_control)

If you want to dive deeper into the matter you might want to visit links below.
rfe documentation with basic code snippets:
https://www.rdocumentation.org/packages/caret/versions/6.0-80/topics/rfe
caret documentation on rfe:
https://topepo.github.io/caret/recursive-feature-elimination.html
Hope this helps!


text:
Q: How to determine which register a count uses Suppose there is
\newcount\c@mycountera
\newcount\c@mycounterb
\newcount\c@mycounterc

Each \newcount uses \alloc@ and that has \wlog{\string#5=\string#2\the\allocationnumber}. Thus to determine which register mycountera uses I can look into the .log file for the (e.g.) \c@mycountera=\count123.
But how can I determine the number of the used register inside of LaTeX automatically? (Something like \registernumber{\c@mycountera} expanding to 123.) After \newcount\c@mycountera it is \the\allocationnumber, but when there is an unknown number of counts created between \newcount\c@mycountera and the time when I need the information this does not help. (I cannot use \xdef\myallocationnumber{\the\allocationnumber} immediatly after \newcount\c@mycountera, because it is defined inside of a package.)
(I suspect that the answer is usable with e.g. \dimen, \box,... too.)

A: Here is one that works also for box registers:
\makeatletter
\def\showregister#1{\expandafter\extract@number\meaning#1\showregister}
\def\extract@number#1{%
  \ifx#1\showregister
     \expandafter\@gobbletwo
  \else
     \if\string"#1#1%
       \expandafter\expandafter\expandafter\@firstoftwo
     \else
       \ifnum`#1<`0 \else \ifnum`#1>`9 \else #1\fi\fi
       \expandafter\expandafter\expandafter\@secondoftwo
     \fi
  \fi
  \extract@rest\extract@number}
\def\extract@rest#1\showregister{#1}

\def\showcounter#1{\expandafter\showregister\csname c@#1\endcsname}
\makeatother

\newcount\AAA
\showregister\AAA

\newdimen\AAB
\showregister\AAB

\newlength\AAC
\showregister\AAC

\newsavebox\AAD
\showregister\AAD

\newcount{AAE}
\showcounter{AAE} % or \expandafter\showregister\csname c@AAE\endcsname

Box register numbers will be in hexadecimal form, preceded by "
The output should be (if starting without any package)

79
  102
  41
  "1A
  80

(Moved additional code to this other answer)
Here's a LaTeX3 version:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\showcounter} { m }
  { \exp_args:Nc \showregister { c@#1 } }
\DeclareExpandableDocumentCommand{\showregister} { m }
  {
   \tl_map_function:fN { \cs_meaning:N #1 } \showreg_scan:n
  }
\cs_generate_variant:Nn \tl_map_function:nN { f }
\cs_new:Npn \showreg_scan:n #1
  {
   \bool_if:nT
     {
      (  \int_compare_p:n { `#1 >= `0 } && \int_compare_p:n { `#1 <= `9 } )
      ||
      \int_compare_p:n { `#1 = `" }
      ||
      ( \int_compare_p:n { `#1 >= `A } && \int_compare_p:n { `#1 <= `F } )
     }
     { #1 }
  }
\ExplSyntaxOff

\def\test#1{\edef\x{\showregister#1}\message{\x\space = \meaning#1}}

\test\fboxsep

\newbox\mybox

\test\mybox

The output on the terminal will be
36 = \dimen36
"23 = \char"23

A: This is too long for a comment. As per the OP the counter number is to be used
for checking the order of packages loaded. This is highly unlikely that it can be a full
proof technique.
LaTeX2e, stores all the counters allocated in an \@elt list called  \cl@@ckpt.
The following MWE will display all counters allocated and the name of the
counter i.e., the part after c@. As you will observe by running the example, hyperTexies like Heiko will fiddle the system. Mostly though, it will predict order of loading:
% See all the counters in LaTeX2e
% and their allocation numbers
\documentclass{book}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage{verse}
\usepackage{hyperref}
\usepackage{caption}
\newcounter{ZZZ}
\begin{document}
\makeatletter
\def\Z{%
   \def\@elt##1{%
       \expandafter\meaning
       \csname c@##1\endcsname
       \space = ##1,\par
    }%
   \cl@@ckpt%
}
All counter in article class plus one!
Expand list.

\Z

\section{Test}
\ifcsname c@section@level\endcsname
   hyperef package has been loaded
    \else
   not loaded
\fi
%\expandafter\let\csname c@section@level\endcsname\undefined
\the\count118

\the\c@section@level

\end{document}

A better way to check for file order is to check the @filelist.
\documentclass{book}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage{verse}
\usepackage{hyperref}
\usepackage{caption}
\newcounter{ctr}
\makeatletter
\let\afilelist\@filelist
\begin{document}
% Just to see files
\@for\next:=\afilelist\do{%
 \next, \par
}
% Command factory
\stepcounter{ctr}
\@for\next:=\afilelist\do{%
      \expandafter\edef\csname @\next\endcsname{\thectr}
     \stepcounter{ctr}
}

% Define macro to check order
\def\checkpkgorder#1#2{%
   \edef\X{\csname @#1\endcsname}
    \edef\Y{\csname @#2\endcsname}
    \expandafter\ifnum\X\expandafter<\Y
      Yes loaded earlier \X, \Y
     \else
      No loaded later \X, \Y
   \fi
}

\checkpkgorder{book.cls}{ifxetex.sty}
\end{document}

A: You can use the fact that \meaning will print something like \countXXX for a register:
\def\registernumber#1{%
  \expandafter\registernumberauxi\meaning#1\halt\stop
}
\def\registernumberauxi#1#2\stop{%
  \ifx\halt#1%
    \expandafter\gobbletwo
  \else
    \expandafter\registernumberauxii
  \fi
    {#1}{#2}%
}
\def\registernumberauxii#1#2{%
  \ifnum`#1<48\else\ifnum`#1>57\else#1\fi\fi
  \registernumberauxi#2\stop
}
\def\gobbletwo#1#2{}
\def\halt{\halt}
\newcount\mycount
\registernumber\mycount
\bye

I've used a simple loop to remove the type of register from the front of the number here. There are perhaps better ways to do that, but if proves the principal. The loop uses the fact that \char48 is 0 and \char57 is 9, so anything outside of this range is not a number.


text:
Q: How to run LLVM's Pass with new Pass Builder on IR by calling the LLVM API in program? By using opt, we can run a custom pass, or run a -O1 -O2 -O3 pass pipeline on a foo.ll file, but it all happens on the command line, and the IR is a file form.This is not conducive to some optimization of IR in the form of memory (each IR file is a module in memory form)in your own project. By the way of opt just like this:
 opt -O2 foo.ll -o foo2.ll
Then we can get an optimized IR file foo2.ll.
Now, I want do the optimization in the program. I have compiled some custom passes into libraries outside the source tree. How to organize passes into pipelines by using the API interface of the new pass manager, and apply thepipline in an IR module?
My goal is :
①load the local pass's libraries in the program with a certain LLVM data structure(I am not sure which data structure it is)
②Register the passes which loaded into the program as sequential piplines
③Finally, apply Pass Pipline to an IR Module and return a new IR Module optimized by this Pipline
If doing this outside the source tree, by linking the static library to call the API, which API should I start with? Are there some examples to refer to? For example, how to use the new pass manager outside the source tree, and how to load the natively compiled pass library into memory

A: Passes are run by a pass manager; opt is basically a small program that loads a module from a file, configures and runs a pass manager and writes the module at the end.
The pipeline you mention is much of what the pass manager is/does.
I'm not quite clear on what exactly you're trying to do, but the general direction is clear enough. All the tasks in that direction involve using the pass manager.  You configure the pass manager to use your custom passes and probably some/many that are included in LLVM, then you tell the pass manager to do its work on a module, and it calls your passes as necessary. The module is the in-memory data structure you want, it can be read or written as a .bc or .ll file.


text:
Q: NSDateFormatter to parse TimeZone from multiple locales Any suggestions on how to parse date strings from older files using CET, and PDT style time zone from multiple locales? The file can be parsed in any locale and seems to mix formats for locales and includes both US and European 3 alpha time zones (CET, PST, etc).
I create the formatter like so:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-M-d h:m:s a zzz];

If I set the GB Local on it I get null for strings with US Time zones. And if I set nothing (Im in US) I get US time zones but not the European ones. Any thoughts on a solution?


text:
Q: Correct ReST URI design I have the following (hypothetical) scenario:
Application to report on students in classes in schools.  I have 3 tables school, class, student.  Class has a FK school_id and student has a FK class_id.
I have my Entities all set up and ready to go and I am about to expose them via a Rest interface.
Should my URIs look like this:
Schools - list of schools
Schools/{id} - specific school
Schools/{id}/classes - list of classes
Schools/{id}/classes/{id} - specific class
Schools/{id}/classes/{id}/student - list students
Schools/{id}/classes/{id}/student/{id} - specific students
Even though in the case of specific student I will be ignoring the I will be ignoring the school id and the class id as all I care about for my query is the student id.
Should I just have:
Schools/student/{id} - for specific students.

A: There's no problem with exposing a resource from multiple locations (though it's a good idea to specify the canonical url if there are multiple locations*).
Thus it may make sense to provide all the following URIs:
lists:

student
classes/{id}/student
schools/{id}/classes/{id}/student

specific:

student/{id}
classes/{id}/student/{id}
schools/{id}/classes/{id}/student/{id}

In your case the relationship between entities is not an entity itself. If this were the case (eg. if you had the resource class-student with an attribute specifying how long the student had been in the class) then the URIs that include both class and student ids become more important as they provide a good place to expose the attributes of the relationship itself.
*to best provide the canonical url to the client you can send it as the value of the "Content-Location" in the response headers.

A: Also, it is useful to have a convention for using plural/singular names.
Some people like only singular names, some (like Ruby folks) using both and a conversion tool.
For example, in Ian's answer student list URL must be students.


text:
Q: A common problem in Combinatorial Analysis Please help me prove the fact below:
$$
\sum_{n=1}^N \frac{N!}{n!(N-n)!}\frac{(-1)^{n-1}n}{n+x} = \frac{N!}{\prod_{n=1}^N (n+x)}.
$$
I think this problem is common, but it is really hard for me to solve.

A: It is a straightforward consequence of the residue theorem. The rational function:
$$ f(x) = \frac{1}{\prod_{n=1}^{N}(x+n)} $$
has simple poles in $x=-1,-2,\ldots,-N$, hence:
$$ f(x) = \sum_{j=1}^{N} \frac{c_j}{x+j} $$
where:
$$ c_j = \operatorname{Res}\left(f(z),z=-j\right).$$

A: Alternatively to Jack's answer, multiply both sides by $\dfrac{\prod_{n=1}^N (x+n)}{N!}$ and you get an equality of polynomials of degree at most $N$, and show that the equality is true for $x=0,-1,-2,\dots,-N$.
The cases $x=-1,\dots,-N$, the left hand side is zero for all but one term. which you can check easily.
The case $x=0$ reduces to the binomial theorem for $(1+(-1))^N$, specifically:
$$1-\left(1+(-1)\right)^N = 1$$
A possible inductive proof would write the left hand side as $f_N(x)$ and then you'd get that you want to show that:
$$f_N(x) = \frac{N}{N+x} f_{N-1}(x)$$

A: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$

$\ds{\sum_{n\ =\ 1}^{N}{N! \over n!\pars{N - n}!}\,
     {\pars{-1}^{n - 1}\,n \over n + x}
     ={N! \over \prod_{n\ =\ 1}^{N}\pars{n + x}}:\ {\large ?}}$.

\begin{align}&\color{#66f}{\large%
\sum_{n\ =\ 1}^{N}{N! \over n!\pars{N - n}!}\,{\pars{-1}^{n - 1}\,n \over n + x}}
=-\sum_{n\ =\ 0}^{N}{N \choose n}\,{\pars{-1}^{n}}
+x\sum_{n\ =\ 0}^{N}{N \choose n}\,{\pars{-1}^{n} \over n + x}
\\[5mm]&=-\bracks{1 + \pars{-1}}^{N}
+x\sum_{n\ =\ 0}^{N}{N \choose n}\pars{-1}^{n}\int_{0}^{1}t^{n + x - 1}\,\dd t
=x\int_{0}^{1}t^{x - 1}\sum_{n\ =\ 0}^{N}{N \choose n}\pars{-t}^{n}\,\dd t
\\[5mm]&=x\int_{0}^{1}t^{x - 1}\pars{1 - t}^{N}\,\dd t
=x\,{\Gamma\pars{x}\Gamma\pars{N + 1} \over \Gamma\pars{x + N + 1}}
={N! \over \Gamma\pars{x + 1 + N}/\Gamma\pars{x + 1}}
={N! \over \pars{x + 1}^{\rm\pars{N}}}
\\[5mm]&=\color{#66f}{\large{N! \over \prod_{n\ =\ 1}^{N}\pars{n + x}}}
\end{align}

$\ds{\pars{a}^{\rm\pars{m}}}$ is one of the Pochhammer Symbols: The raising factorial.


text:
Q: Excel VBA - How to add number of rows based on two cell values and copy/keep data from the third? I have created this sample below to illustrate and explain my need. I want to complete the number range between A and B (including A and B) with the result in column A, and keep the data from C for each new row created.
Current Table:
   A    |    B     |    C
-------------------------------
0010    |  0015    |   0312
0020    |          |   3500
0029    |  0031    |   4000

Desired result:
   A    |    B     |    C
-------------------------------
0010    |          |   0312
0011    |          |   0312
0012    |          |   0312
0013    |          |   0312
0014    |          |   0312
0015    |          |   0312
0020    |          |   3500
0029    |          |   4000
0030    |          |   4000
0031    |          |   4000

Note: The result does not need to be rendered in the same sheet.
Any suggestions?
EDIT:
Someone almost solved it but removed their post and I managed to mess it up in the meantime. Can anyone spot the error for me?
Sub Macro1()

Dim num, i, j, x, lastRow

Dim sh1 As Worksheet
Dim sh2 As Worksheet
Set sh1 = ThisWorkbook.Sheets("Sheet1")
Set sh2 = ThisWorkbook.Sheets("Sheet2")

lastRow = sh1.Cells(Rows.Count, "A").End(xlUp).Row

x = 1
For i = 2 To lastRow
    num = (sh1.Cells(2, 2) - sh1.Cells(2, 1))
        For j = 0 To num - 1
            x = x + 1
            sh2.Cells(x, 1) = sh1.Cells(i, 1) + j
            sh2.Cells(x, 3) = sh1.Cells(i, 3)
        Next j
Next i

End Sub

When the above is fixed, the only thing that's missing the last value in column A.
When running this on my example the result in A is:
0010
0011
0012
0013
0014

It should be:
0010
0011
0012
0013
0014
0015

A: This is assuming your data is on a sheet called "Sheet1" in Columns A, B and C, with your data starting from row 2 downward. It will generate your output on "Sheet2":
Sub Macro1()

Dim num, i, j, x, lastRow

Dim sh1 As Worksheet
Dim sh2 As Worksheet
Set sh1 = ThisWorkbook.Sheets("Sheet1")
Set sh2 = ThisWorkbook.Sheets("Sheet2")

lastRow = sh1.Cells(Rows.Count, "A").End(xlUp).Row

x = 1
For i = 2 To lastRow
    If sh1.Cells(i, 2) = "" Then
        num = 0
    Else
        num = (sh1.Cells(i, 2) - sh1.Cells(i, 1))
    End If
    For j = 0 To num
        x = x + 1
        sh2.Cells(x, 1) = sh1.Cells(i, 1) + j
        sh2.Cells(x, 3) = sh1.Cells(i, 3)
    Next j
Next i

End Sub

A: First you cells format change to the text and you use this code
Sub test()
Dim a, rw, b As Long
rw = 1
For a = 1 To Sheet1.Cells(1048576, 1).End(xlUp).Row
    If Sheet1.Cells(a, 2) = "" Then
        Sheet2.Cells(rw, 1) = Sheet1.Cells(a, 1)
        Sheet2.Cells(rw, 3) = Sheet1.Cells(a, 3)
        rw = rw + 1
    ElseIf Sheet1.Cells(a, 2) <> "" Then
        For b = Val(Sheet1.Cells(a, 1)) To Val(Sheet1.Cells(a, 2))
            Sheet2.Cells(rw, 1) = Format(b, "0000")
            Sheet2.Cells(rw, 3) = Sheet1.Cells(a, 3)
        rw = rw + 1
        Next
    End If
Next

End Sub


text:
Q: Android: How to check if a rectangle contains touched point? I would try to develop an application in which I can draw a planimetry. So, each room has got its own ID or name and, if I touch a room, I want to show a Toast Message with that ID or name. The problem is how check if and which path is touched!!
I saw a lot of topic discussions that talked about this problem. Someone says to use the getBounds method and, after, contains method for checking if touched point is in Rect. But, I guess getBounds returns the smallest Rect that contains path, right?
So, rooms have different custom geometric forms and, for this reason, if I get bounds about 2 close rooms, method could return a shared set of points. Bad! Each room has got only their area points. How can I solve this problem?
In iOS i could use PathContainsPoint method, but, unfortunaly, Android Path doesn't have something similar.

A: Ok i solved my problem. I post the example code:
Path p;
Region r;

@Override
public void onDraw(Canvas canvas) {

    p = new Path();

    p.moveTo(50, 50);
    p.lineTo(100, 50);
    p.lineTo(100, 100);
    p.lineTo(80, 100);
    p.close();

    canvas.drawPath(p, paint);

    RectF rectF = new RectF();
    p.computeBounds(rectF, true);
    r = new Region();
    r.setPath(p, new Region((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom));

}

public boolean onTouch(View view, MotionEvent event) {

    Point point = new Point();
    point.x = event.getX();
    point.y = event.getY();
    points.add(point);
    invalidate();
    Log.d(TAG, "point: " + point);

    if(r.contains((int)point.x,(int) point.y))
        Log.d(TAG, "Touch IN");
    else
        Log.d(TAG, "Touch OUT");

    return true;
}

A: Here's a thought: create a new path which is a tiny square around the point that was touched, and then intersect that path with your path to be tested using path.op() and see if the result is empty.

A: As Edward Falk say, best way is to use path.op() becouse Region is square. And one point can be in 2 or 3 Regions.
For example:

All regions will contain blue point, but on fact only path4 contains this point.
int x, y;
Path tempPath = new Path(); // Create temp Path
tempPath.moveTo(x,y); // Move cursor to point
RectF rectangle = new RectF(x-1, y-1, x+1, y+1); // create rectangle with size 2xp
tempPath.addRect(rectangle, Path.Direction.CW); // add rect to temp path
tempPath.op(pathToDetect, Path.Op.DIFFERENCE); // get difference with our PathToCheck
if (tempPath.isEmpty()) // if out path cover temp path we get empty path in result
{
    Log.d(TAG, "Path contains this point");
    return true;
}
else
{
    Log.d(TAG, "Path don't contains this point");
    return false;
}

A: Go through the path and check if the position on the path is near to the touched point. Following method worked for both linear paths and the complex paths.
fun Path.doIntersect(x: Float, y: Float, width: Float): Boolean {
    val measure = PathMeasure(this, false)
    val length = measure.length
    val delta = width / 2f
    val position = floatArrayOf(0f, 0f)
    val bounds = RectF()
    var distance = 0f
    var intersects = false
    while (distance <= length) {
        measure.getPosTan(distance, position, null)
        bounds.set(
            position[0] - delta,
            position[1] - delta,
            position[0] + delta,
            position[1] + delta
        )
        if (bounds.contains(x, y)) {
            intersects = true
            break
        }
        distance += delta / 2f
    }
    return intersects
}

A: Region and path.op() approaches work well, but suffer from a lack of precision. After some tests, it seems like they define a zone at the segment level of the path, like so: image segment zone. Another approach is to work with polygons. While giving better results, it still registers some unexpected touches, and misses obvious ones. But there is another solution, which consists in retrieving a set of points along the path, and registering touches inside an area surrounding them. For that, we can use PathMeasure class to get the desired number of points, and store them in a List<Float>:
PathMeasure pathMeasure = new PathMeasure(path, false);
List<Float> listFloat = new ArrayList<>();
for (float i = 0; i < 1.1; i += 0.1) {
    float[] pointCoordinates = new float[2];
    pathMeasure.getPosTan(pathMeasure.getLength() * i, pointCoordinates, null);
    listFloat.add(pointCoordinates[0]);
    listFloat.add(pointCoordinates[1]);
}

Then, we need to loop over the List<Float> and check if a touch event is inside a defined zone surrounding these points. Here, a zone covers a tenth of the path length, since we collected ten points:
float areaLength = pathMeasure.getLength() / 20; // since we collect ten points, we define a zone covering a tenth of path length
for (int i = 0; i < listFloat.size() - 1; i += 2) {
    if (touchX > listFloat.get(i) - areaLength
     && touchX < listFloat.get(i) + areaLength
     && touchY > listFloat.get(i+1) - areaLength
     && touchY < listFloat.get(i+1) + areaLength) {
        Log.d(TAG, "path touched");
    }

}

These successive zones capture touch events with a better precision, following more closely the path: image points zone.
This method can be improved, by working with Rect class to ensure that these zones are not overlapping each other, and also to bound the start and end point with a better precision.


text:
Q: How to divide a SQL table into two tables such that sum of their sizes of 2 tables is nearly equal I have a table which has two columns table_name and table_size. I want to divide this table into two halfs such that the difference of sum of table sizes is min.
Let Table(table_name char(25), table_size int)
Select * from Table gives
   T1  110
   T2  80
   T3  70
   T4  60
   T5  40
   T6   20
   T7   10

So I want to partition it into two tables Table1 and Table2
such that
Table1 should contain now (T1, T7, T2)
     Total sum = 110+ 10+ 80 = 200

Table2 should contain now (T3,T4,T5, T6)
    Total sum = 70+60+40 + 20 = 190

How to do this with a SQL query ? If a general case solution is there i. e. Divide this table into m partitions and create corresponding m tables or can store tables of each partition in a list or something.
Output which I got while running query.
select t.*,
       (case when seqnum % 4 in (1, 4) then 1 else 2 end) as grouping
from (select t.*,
             row_number() over (order by table_size desc) as seqnum
      from t
     ) t

table_name                 table_size               seqnum grouping
------------------------- ----------- -------------------- --------
T1                                100                    1        1
T2                                 80                    2        2
T3                                 70                    3        2
T4                                 60                    4        2
T5                                 40                    5        1
T6                                 20                    6        2
T7                                 10                    7        2
(7 rows)

A: This is actually a very hard problem -- I think it is NP-complete, which is a very hard class of problems that basically requires that you search through all possible combinations.
There are approximate solutions that should work pretty well.  For instance, if you divide the rows into groups of 4 and take the 1/4 in one group and 2/3 in another that should be pretty good.
In your case:
select t.*,
       (case when seqnum % 4 in (1, 4) then 1 else 2 end) as grouping
from (select t.*,
             row_number() over (order by table_size desc) as seqnum
      from t
     ) t

For this particular data, the two groups are 110 + 60 + 40 and 80 + 70 + 20 + 10 -- not quite perfect but pretty close.


text:
Q: Diophantine equation $x^2+y^2=z^2+t^2$? I would like to find some source books or articles which discuss the Diophantine equation
$$
x^2+y^2=z^2+t^2,\qquad |y-z|=1
$$
for which $x,z$ are odd positive and $y,t$ are even positive integers.
Any brief explanation is also welcome and appreciated.
Thanks!

A: Is not so hard. $x^2-t^2=z^2-y^2 $, so $(x-t)*(x+t)=(z-y)*(z+y)$. Now suppose that$ z=y+1$.So $ (x-t)*(x+t)=y+z=2y+1$. Now it's so easy, you must to keep account by initial conditions.

A: What to do is just substitute your conditions on your equations. Since $x,z$ are odd and $y,t$ are even and $|y-z|=1$, then,
$$(2m-1)^2+(2u)^2 = (2u-1)^2+(2n)^2\tag1$$
Expanding, you can see that $2$nd powers of $u$ will cancel, so you'll only have a linear equation in $u$. Letting Walpha do the work, we get the condition,
$$u = -m^2+m+n^2$$
which makes $(1)$ true for any $m,n$.


text:
Q: How to count characters I have few text files and I'm looking to count characters in those files but not all the characters. I have to only count how many times letter a, b and c have occurred in those files. I'm very new to Pig. Any help would be appreciated. Thanks!

A: Load all the files using wildcard character * into field of type chararray.Split the line into words and then into letters and count them.
A = LOAD '/path/text*.txt' AS (lines:chararray);
B = FOREACH A GENERATE FLATTEN(TOKENIZE((chararray)lines)) AS words;
C = FOREACH B GENERATE FLATTEN(TOKENIZE(REPLACE(words,'','|'), '|')) AS letters;
D = FILTER C BY (letters matches '.*(a|b|c).*');
E = GROUP D BY letters;
F = FOREACH E GENERATE group,COUNT(D);
DUMP F;


text:
Q: Program outputs code from multiple methods instead of just one method I have a Java program that troubleshoots common problems with phones. To do this I have set up a scanner that reads the user input for any keywords. If one of these keywords is found, a method will output from a text file a solution to the problem suggested by that keyword.
My problem is that when I run the program, all the lines from the text file are outputted, from every method, disregarding my input.
Here's the code:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Scanner;

    public class task2 {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("What is your problem?");
    String input =  scan.nextLine();
    String[] problems = {"screen", "display", "broken", "cracked", "camera", "flash", "ports"};
    String[] solutions = input.split("broken");

    for(int x=0; x < problems.length; x++){
        if(input.contains("broken")){
            if(input.contains("screen")){
                brokenScreen();
            } else{

            }
            if(input.contains("display")) {
                brokenDisplay();
            } else{

            }
            if(input.contains("camera")) {
                brokenCamera();
            } else{

            }
            if(input.contains("flash")) {
                brokenFlash();
            } else{

            }
            if(input.contains("ports")) {
                brokenPorts();
            } else{

            }
        }
            else{

            }

        if(input.contains("cracked")) {
            if(input.contains("screen")) {
                crackedScreen();
            } else{

            }
        }
        if(input.contains("water")) {
            waterPhone();
        }
        else{
        }
    }

    brokenScreen();
    brokenDisplay();
    crackedScreen();
    brokenCamera();
    brokenFlash();
    brokenPorts();
    waterPhone();
    noSolution();

    }

public static void noSolution() {
    String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; //Location of the text file
    try {
        FileReader filereader = new FileReader(file);
        BufferedReader bufferedreader = new BufferedReader(filereader);
        while((file = bufferedreader.readLine()) != null){
            System.out.println(file);
    }
        bufferedreader.close();
        } catch (IOException e) {
        e.printStackTrace();
    }

}
public static void waterPhone() {
    String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt";     try {
        FileReader filereader = new FileReader(file);
        BufferedReader bufferedreader = new BufferedReader(filereader);
        while((file = bufferedreader.readLine()) != null){
            System.out.println(file);
    }
        bufferedreader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public static void brokenPorts() {
    String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt";     try {
        FileReader filereader = new FileReader(file);
        BufferedReader bufferedreader = new BufferedReader(filereader);
        while((file = bufferedreader.readLine()) != null){
            System.out.println(file);
    }
        bufferedreader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
public static void brokenFlash() {
    String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt";     try {
        FileReader filereader = new FileReader(file);
        BufferedReader bufferedreader = new BufferedReader(filereader);
        while((file = bufferedreader.readLine()) != null){
            System.out.println(file);

    }
        bufferedreader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
public static void brokenCamera() {
    String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt";     try {
        FileReader filereader = new FileReader(file);
        BufferedReader bufferedreader = new BufferedReader(filereader);
        while((file = bufferedreader.readLine()) != null){
            System.out.println(file);
    }
        bufferedreader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
public static void crackedScreen() {
    String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt";     try {
        FileReader filereader = new FileReader(file);
        BufferedReader bufferedreader = new BufferedReader(filereader);
        while((file = bufferedreader.readLine()) != null){
            System.out.println(file);
    }
        bufferedreader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
public static void brokenDisplay() {
    String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt";     try {
        FileReader filereader = new FileReader(file);
        BufferedReader bufferedreader = new BufferedReader(filereader);
        while((file = bufferedreader.readLine()) != null){
            System.out.println(file);
    }
        bufferedreader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public static void brokenScreen() {
    String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt";     try {
        FileReader filereader = new FileReader(file);
        BufferedReader bufferedreader = new BufferedReader(filereader);
        while((file = bufferedreader.readLine()) != null){
            System.out.println(file);
    }
        bufferedreader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
}

Can anyone please solve this issue? Any help would be greatly appreciated.

A: Remove
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();

at the end of your main method (after the for loop).


text:
Q: No message when data entry success The following code successfully submits data to a mysql database. However, the form does not show error when fields are blank and it will not populate the div with the success message when it successfully inserted the data. The php file below shows that if insert is a success the result variable is set to 1 which is reflected in the condition in the if else conditions for the ajax.

jQuery AJAX Post method example with php and MySQL

Please fill in the form and click save.

    <form name='form1'>

              First Name:

              <input type='text' placeholder='First Name' name='first_name' id= 'first_name' required >

                Last Name:

              <input type='text' placeholder='Last Name' name='last_name' id='last_name' required >

              Email:

              <input type='email' name='email' placeholder='Email' id='email' required >

              <input class='btn' type="button" id = "saveusers" value = "Save" />

    </form>

saverecords_ajax.php file
<?php

$host         = "localhost";
$username     = "root";
$password     = "password";
$dbname       = "testing";
$result = 0;

/* Create connection */
$conn = new mysqli($host, $username, $password, $dbname);
/* Check connection */
if ($conn->connect_error) {
     die("Connection to database failed: " . $conn->connect_error);
}

/* Get data from Client side using $_POST array */
$fname  = $_POST['first_name'];
$lname  = $_POST['last_name'];
$email  = $_POST['email'];
/* validate whether user has entered all values. */
if(!$fname || !$lname || !$email){
  $result = 2;
}elseif (!strpos($email, "@") || !strpos($email, ".")) {
  $result = 3;
}
else {
   //SQL query to get results from database
   $sql    = "insert into users (first_name, last_name, email) values (?, ?, ?)  ";
   $stmt   = $conn->prepare($sql);
   $stmt->bind_param('sss', $fname, $lname, $email);
   if($stmt->execute()){
     $result = 1;
   }
}
echo $result;
$conn->close();


text:
Q: Enumerate through Grid cell in WPF I have Grid with 10 rows and 10 column, and I want in code behind get to every of this grid cell to change this background or add image to cell, How can I do it ?

A: Grid, in WPF, doesn't really have "cells".
Instead, individual child controls of the grid are "decorated" with the Grid.Row and Grid.Column attached property.
If you want to change the color of a "cell", there will need to be some UIElement that is marked with that row and column, and is a child of the Grid.  You can search the grid's Children for the specific control in that row and column (by using Grid.GetColumn(child), etc), then set the color of that UIelement.


text:
Q: Key value coding failure So I have some json in a file like so
{
"address": {
    "home": {
        "street": "A Street"
    }
}

}
I pull out the json string like so
NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

I want to change a value on the fly, using a key path, so I need to make a deep mutable copy of the structure. So I am doing it like so
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
data = [NSKeyedArchiver archivedDataWithRootObject:json];
json = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Using breakpoints I can see the json and it all looks fine.  However, I get a crash on this line
[json setValue:@"Different Street" forKeyPath:@"address.home.street"];

The compiler suggested there isn't a key at this key path that conforms to key-value coding.
Annoyingly, this line works fine and returns the street string
id value = [json valueForKeyPath:@"address.home.street"];

Why can't I set a value like this?

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryI 0x1741bb580> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key pan.'

A: Use NSJSONReadingMutableContainers when reading your JSON.  By default your containers are read in as immutable containers.
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:nil];