text:
Q: For every $k>2$, does there exist at least one k-perfect number? For every $k>2$, does there exist at least one number $n$ for which $\sigma(n)=k*n$? What kind of heuristics can be done to shed light on this problem?

A: See Wikipedia's k-perfect numbers:

In mathematics, a multiply perfect number (also called multiperfect number or pluperfect number) is a generalization of a perfect number.
For a given natural number k, a number n is called k-perfect (or k-fold perfect) if and only if the sum of all positive divisors of n (the divisor function, σ(n)) is equal to kn; a number is thus perfect if and only if it is 2-perfect. A number that is k-perfect for a certain k is called a multiply perfect number

$$
\small
    \begin{array}{rrl} \\
    k & \text{Smallest k-perfect number} &  \\
    \hline \\
    2 & 6 & 2 × 3 \\
    3 & 120 & 2^3 × 3 × 5 \\
    4 & 30240 & 2^5 × 3^3 × 5 × 7 \\
    5 & 14182439040 & 2^7 × 3^4 × 5 × 7 × 11^2 × 17 × 19 \\
    6 & \text{(21 digits)} \, 154345556085770649600 & 2^15 × 3^5 × 5^2 × 7^2 × 11 × 13 × 17 × 19 × 31 × 43 × 257 \\
    7 & ... & \\
    \end{array}
$$
See the Wikipedia page linked above for k-perfect numbers up to 11, they are too lengthy to fit on Stack Exchange pages. It's reasonable to expect that there are more but they haven't been discovered yet.
Other references:
Oeis - Multiply-Perfect Numbers
MathWorld - Multiperfect Number

"Moxham (2000) found the largest known multiperfect number, approximately equal to 7.3×10^(1345), on Feb. 13, 2000."

The "The Multiply Perfect Numbers Page" has a gzipped file from 2014 with 5311 MPNs, as of 2018-01-07 no new numbers have been discovered.


text:
Q: Looking for OpenGL ES framework for cross-platform development on Win/Linux/MacOSX/Android/IOS I have to develop a cross-platform multimedia application that will run on Windows, Linux, MacOSX, Android and IOS. This application will have to be able to play audio/video content, display photos and graphs and, probably, show simple 2D animations. After lot of searching, it seems that the "most portable approach" to the problem is to use C++ as language and OpenGL ES as drawing APIs, because both are supported on almost any pair of device/OS, the performance level will be good and the visual appearance should be near the same on each (group of) devices.
Obviously, I know that I'll have to tweak the appearance of the app to "scale" on different devices with different display sizes and resolutions. I also know that it's unrealistic to demand the exact same behavior for any piece of code on such different architectures. I just want to minimize the written code (e.g. the rewrite of a piece of interface first in C++, then in Java must be avoided).
I'm not an expert in OpenGL ES programming, but looking at some samples, it seems that I will need a framework to have some ready-made widget (menus, buttons, textboxes). I'd prefer not to reinvent the wheel.
This is a low-budget project, so I'll need a framework that is completely free and opensource. The latter requirement also gives the freedom to add/modify APIs of the framework when something important is missing or is misbehaving. I'm not asking for a multipurpose framework (such Qt for example), able to handle input, networking, storage, etc., just because I strongly suspect that such a framework doesn't exist for the platforms I mentioned. I just want a sort of OpenGL wrapper able to abstract many of its low level details but also offering some UI widget as Qt would do. I'll handle intput, networking, storage, sensors separately, probably using other cross-platform open source libraries, as suggested here.
I've read a lot of similar questions on Stackoverflow and Gamedev, and I've heard about a lot of frameworks (Unity, Corona SDK, LÖVE, LibGDX, Ogre, Cocos2D-x), mainly created for game development. Ogre and Cocos2D-x, for example seem to match some of my requirements, but if I decide to use one of them I'll have to code almost all my UI elements (not such a big burden, someone might argue).
A few remarks:

*

*the application is 2D, so OpenGL might seem like overkill. However, OpenGL ES has been chosen because of it's very good portability and its high performance level even on old hardware.

*I'm basically a Linux C++ developer, so I'd prefer not to switch to HTML5 (still too young) or .NET/Mono (less efficient) without remarkable advantages in return. Moreover, I couldn't realistically master these languages in the short period.

*I've been impressed with the story in this article. I believe that this could be the right approach: a mix of open source tools and libraries that fit the project needs. But I'm still missing the most important piece: the graphics framework.

*Writing this question, I found this discouraging answer. I hope my requirements doesn't produce an empty set. I really can't affort to maintain n different UIs on n different platform. I really need something that is platform agnostic.

Any help or advice would be greatly appreciated.

A: openframeworks
Does everything you asked.

A: I just stumbled onto this one: GamePlay 3D
Supported platforms are Blackberry, Android, iOS, Windows, Linux and Mac OS X.
You can always do 2D using a 3D framework.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best setup for code promotion and feature branching in Subversion? We're a 4-person team and haven't been far from our comfort zone in several years, but we're growing and would like to catch up to the times.  I have been tasked with finding the best way to implement Continuous Integration (automated builds, branching for code maintenance and new features, etc).  We are looking at switching from SourceSafe 2005 to Subversion to handle our version control.  From what I've read, Subversion is a much better choice for doing code promotion, branches, and merging between branches.  We will probably use the following products:

*

*VisualSVN Server

*TortoiseSVN (for integration with Windows Explorer)

*VisualSVN (for integration with Visual Studio 2005)

*SVNVB6 (for integration with Visual Basic 6)

*FinalBuilder

What is the best way to organize the repository for code promotion and feature branching?  Here is an example of our current SourceSafe structure:

*

*root

*

*Visual Studio 2005 projects

*

*ProjectName

*

*Solution file, project files, and code files here

*\bin

*

*\Release

*

*Compiled release binaries here

*Visual Basic 6 projects

*

*ProjectName

*

*Project files and code files here

*Compiled binaries (.dll, .exe, .ocx) here

*Documentation

*

*Documentation files here

Should we structure like this?

*

*root

*

*branches (each branched from trunk)

*

*Development.FeatureA

*Development.FeatureB

*Test (Built nightly with FinalBuilder ???)

*Production (Built nightly with FinalBuilder ???)

*Production.BugFixA (Reverse Integrate to Production branch, Test branch, and trunk ???)

*tags

*

*Development.v1 (tagged after each successful build)

*Development.v2

*Development.v3

*Test.v1

*Test.v2

*Test.v3

*Production.v1

*Production.v2

*Production.v3

*trunk (Development code - Built nightly with FinalBuilder)

*

*Visual Studion 2005 projects

*

*ProjectName

*

*Solution file here

*ProjectName

*

*Project files and code files here

*Visual Basic 6 projects

*

*ProjectName

*

*Project files and code files here

Since a large part of our software is still COM (VB6) and needs to be registered (using regsvr32), should the binaries be version-controlled?  How should we handle registering/unregistering the components when we need to work on the different branches (possibly with different COM compatibility)?
Are we way off the mark?

A: First off, don't use a top level trunk branches tags, use a per project trunk branches tags like this:
/Projects
  /CashCowProject
    /branches
    /tags
    /trunk
      /vs
      /doc

This means that tracker tools can look at http://svn/Projects/CashCowProject and see ALL activity on that project, and not get any activity on any other project. Also it forces you to control references between projects, meaning that your top-level projects won't change without an entry in trunk.
When projects reference each other, use svn:externals to pull in a tag from the library project you need. Use vendor branches as described in the red-bean book to handle 3rd party libraries, even binaries.
Keeping library binaries in SVN is ok. Might want to consider a separate repository for this, although we don't.
For code promotion, keep a stable branch for a particular version and only ever merge from trunk into that branch, then tag from that branch. This will give you an auditable record of what's in each release.
You can keep COM binaries in there if you're not going to pull in the source and build it. You can write a post-upgrade script for tortoise which will go around registering any COM objects it finds.


text:
Q: Efficient way to compute multiple euclidean distances Matlab I am training my own self organizing map to cluster colorvalues. Now I want to make some sort of a U-matrix to show euclidean distances between the nodes and their direct neighbors. My problem now is, that my algorithm is quite unefficient!! There is certainly a way to compute this more efficiently?
function displayUmatrix(dims,weights) %#dims is [30 30], size(weights) = [900 3],
                                      %#consisting of values between 1 and 0

hold on;
axis off;
A = zeros(dims(1), dims(2), 3);
B = reshape(weights',[dims(1) dims(2) size(weights,1)]);
if size(weights,1)==3
    for i=1:dims(1)
        for j=1:dims(2)
            if i~=1
                if j~=1
                    A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i-1,j-1,:)).^2;
                end
                A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i-1,j,:)).^2;
                if j~=dims(2)
                    A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i-1,j+1,:)).^2;
                end
            end
            if i~=dims(1)
                if j~=1
                    A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i+1,j-1,:)).^2;
                end
                A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i+1,j,:)).^2;
                if j~=dims(2)
                    A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i+1,j+1,:)).^2;
                end
            end
            if j~=1
                A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i,j-1,:)).^2;
            end
            if j~=dims(2)
                A(i,j,:)=A(i,j,:)+(B(i,j,:)-B(i,j+1,:)).^2;
            end
            C(i,j)=sum(A(i,j,:));
        end
    end
    D = flipud(C);
    maximum = max(max(D));
    D = D./maximum;
    imagesc(D)
else
    error('display function does only work on 3D input');
end
hold off;
drawnow;

end
Thanks, Max

A: You can calculate the (squared) distance of each point to its neigbor to the right by:
sum((B(:,1:end-1,:) - B(:,2:end,:)).^2, 3)

Similarly, you calculate the distance of each point to the point below, and on both diagonals. You don't have all those values for points on borders so you pad them with zeros. Then you add the distances and divide them by the number of neighbors a point has to get the average distance to all the neighbors.
Here is my code:
%calculate distances to neighbors
right = sum((B(:,1:end-1,:)- B(:,2:end,:)).^2, 3);
bottom = sum((B(1:end-1,:,:)- B(2:end,:,:)).^2, 3); zeros();
diag1 = sum((B(1:end-1,1:end-1,:)- B(2:end,2:end,:)).^2, 3);
diag2 = sum((B(2:end,2:end,:)- B(1:end-1,1:end-1,:)).^2, 3);

%pad them with zeros to the correct size
rightPadded = [right zeros(dim(1) , 1)];
leftPadded = [zeros(dim(1) , 1) right];

botomPadded = [bottom; zeros(1,dim(2))];
upPadded = [zeros(1,dim(2));bottom];

bottomRight = zeros(dim(1), dim(2));
bottomRight(1:end-1,1:end-1) = diag1;
upLeft = zeros(dim(1), dim(2));
upLeft(2:end,2:end) = diag1;

bottomLeft = zeros(dim(1), dim(2));
bottomLeft(1:end-1,2:end) = diag2;
upRight = zeros(dim(1), dim(2));
upRight(2:end,1:end-1) = diag2;

%add distances to all neighbors
sumDist = rightPadded + leftPadded + bottomRight + upLeft + bottomLeft + upRight;

%number of neighbors a point has
neighborNum = zeros(dim(1), dim(2)) + 8;
neighborNum([1 end],:) = 5;
neighborNum(:,[1 end]) = 5;
neighborNum([1 end],[1 end]) = 3;

%divide summed distance by number of neighbors
avgDist = sumDist./neighborNum;

It is all vectorized, so it should be faster than your version.
If you want the exact U-matrix, you can interleave the average distances with the neighboring distances.


text:
Q: PHP MySql Update else Insert Error "Warning: mysql_result()" I'm trying to go threw my table nonbulkmdu and look into r10database to find if there is a duplicate, if there is it will update 4 fields if its not it will insert a new row. I keep getting the error
Warning: mysql_result(): supplied argument is not a valid MySQL result resource in on line 19-23.
What am I doing wrong?
<?php
$username="";
$password="";
$database="";
$link = mysql_connect(localhost,$username,$password);

mysql_select_db($database) or die( "Unable to select database");

$query="SELECT * FROM nonbulkmdu";

if ($result=mysql_query($query, $link)) {
    $num=mysql_numrows($result);

    $i=0;
    while ($i < $num) {
        $address=strtoupper(mysql_result($result,$i,"address"));
        $drops=mysql_result($result,$i,"drops");
        $city=mysql_result($result,$i,"city");
        $citycode=mysql_result($result,$i,"citycode");
        $feature_type=mysql_result($result,$i,"Feature_Type");

        $result = mysql_query("update r10_database
                               set drops=$drops, citycode=$citycode, city=$city, Feature_Type=$feature_type
                               where address=$address;");

        if (mysql_affected_rows()==0) {
            $result = mysql_query("insert into r10_database (address,
                                                             drops,
                                                             city,
                                                             citycode,
                                                             Feature_Type)
                                                     values ($address,
                                                             $drops,
                                                             $city,
                                                             $citycode,
                                                             $Feature_Type);");
        }
        $i++;
    }
} else {
    echo mysql_error();
}
mysql_close();
?>

A: You're missing quotes around the values in the UPDATE and INSERT call:
    $result = mysql_query("update r10_database
                           set drops='$drops', citycode='$citycode', city='$city', Feature_Type='$feature_type'
                           where address='$address';");

    if (mysql_affected_rows()==0) {
        $result = mysql_query("insert into r10_database (address,
                                                         drops,
                                                         city,
                                                         citycode,
                                                         Feature_Type)
                                                 values ('$address',
                                                         '$drops',
                                                         '$city',
                                                         '$citycode',
                                                         '$Feature_Type');")

BTW, if address has a unique key in the table, you can do both queries at once, using INSERT ... ON DUPLICATE KEY UPDATE.


text:
Q: Google Analytics (GA4) transaction data not accurate 1. Background
Using GA4 without GA360
2. Description
When i want to search the records by transactional level (Record by datetime) which will show the detailed record one by one, the event count is varied following by filtered date.
3. Hope to Achieve
I would like to achieve a normal report that will show every event count as 1 by filtering months or longer.
4. Weird Cases

*

*Event count of every record is 1 when filtering 0.5 month, eg 1 Oct to 16 Oct.

*Event count of every record is 2 when filtering 1 month, eg 1 Oct to 30 Oct.

*Event count of every record is 3 when filtering 1.5 month, eg 15 Sep to 30 Oct.

5. Supporting
It is the sampling data from reports.
Heavily Sampled exploration
This report is based on 9.52% of available data. A smaller sample size means that the data in this report is less accurate. Learn More


text:
Q: Morphism between two $K$-schemes restricted to an affine subscheme Suppose that $f:X\longrightarrow Y$ is a morphism between two $K$-schemes. If $U\subseteq X$ is an affine open set,  then can we conclude that $f(U)$ is contained is some affine open subset of $Y$?
Thanks in advance.

A: No. Let $X$ be two points, let $Y$ be $\mathbb{A}^1_K$ with the origin doubled, and let $X \to Y$ be the morphism that picks out the doubled points. Then there is no affine open subset of $Y$ that contains the image of $X$, because every affine scheme is separated.

A: Here is an example with curves.  Let $C$ be the (projective) elliptic curve cut out by (the homogenization of) $y^2 = x^3 -x$.
The map $f:(x,y) \mapsto x$ gives a degree two morphism $C \to \mathbb P^1$.
There are four branch points: $(0,0), (1,0), (-1,0)$, and the point at infinity.
Let $P \in C$ be a non-branch point.  Then $U := C \setminus \{P\}$ is affine, but
$f: U \to \mathbb P^1$ remains surjective.

A: Here is an example with varieties over algebraically closed fields.
The complement $U$ of $y = x^2$ in $\mathbb{A}^2$ is affine -- proof: it is the projection of the set $(x, y, z) \in \mathbb{A}^3$ such that $(y - x^2)z = 1$.
But this complement surjects onto $\mathbb{P}^1$ under the usual map $\mathbb{A}^2 \setminus \{0\} \to \mathbb{P}^1$ (this just says that the parabola does not contain any lines through the origin). Note that we really have to do the silliness with removing a conic to get an example -- removing a line, we no longer surject to $\mathbb{P}^1$ and if we remove nothing we're not affine.

A: Another simple example, which also works with varieties. It suffices to  $X=\mathbb{P}^1\times \mathbb{P}^1$, $Y=\mathbb{P}^1$ and $f\colon X\rightarrow Y$ to be the projection on the first factor.
Indeed, let $C$ be any closed curve in $X$. Since $C$ is ample, then $U=\mathbb{P}^1\times \mathbb{P}^1\setminus C$, is an affine smooth surface. However, $f(U)=\mathbb{P}^1$ is not contained in any affine open subset.


text:
Q: Como descobrir números maiores que X numa lista Como exemplo, esse código aí
N=[1,2,3,4,5]
B= #quantidade de números maiores que 2
print(B)

'B' seria a quantidade de números maiores que 2 presentes na lista, por exemplo.

A: A lógica é exatamente a mesma para filtrar elementos de uma lista:
Filtrar elementos de uma lista em Python
A mais simples e direta é utilizar a compreensão de listas:
B = len([i for i in N if i > 2])

Neste caso, utilizamos a função len para calcular a quantidade de elementos.

Veja funcionando no Ideone.

Outra forma, equivalente a compreensão de lista, é utilizar a função filter:
B = filter(lambda i: i > 2, N)

Porém, o retorno desta função será um gerador, necessitando assim a conversão para lista para obter-se seu comprimento:
B = len(list(filter(lambda i: i > 2, N)))

Mas para esta solução, este método se torna inviável comparado ao primeiro.

Veja funcionando no Ideone.

A: Pra simplificar você pode usar assim:
minha_lista = [1,2,3,4,5]
maior_que = 2

filtrados = [x for x in minha_lista if x > maior_que]

#exibe os elementos
print(filtrados)

#conta os elementos
print(len(filtrados))

A: Aqui uma solução, pode haver mais fácil e menor
lista = [1,2,3,4,5,6,7,8,9,1,23]
X = 0
B = 0 # Armazena a quantidade de números maiores que 2
num_elementos_lista = len(lista)
while(X < num_elementos_lista):
    if lista[X] > 2: # verifica se lista[X] é maior que 2
      B+=1 # Se for incrementa + 1 em B
    X+=1

print(B)

Veja funcionando no repl

A: Se você pretende apenas saber a quantidade de valores maiores do que um determinado valor, que no caso é 2, você pode implementar um laço de repetição e verificar a soma de todos os números maiores que 2.
Para isso você pode implementar o seguinte código...
N = [1, 2, 3, 4, 5]
cont = 0
for c in N:
    if c > 2:
        cont += 1

print(f'\033[32mA quantidade dos números maiores que "2" é: {cont}')

Observe o funcionamento do algoritmo no repl.it.
Observe que neste algoritmo implementei um laço de repetição for, onde ele percorre a lista citada anteriormente ([1, 2, 3, 4, 5]).
Em seguida defini um if onde verificará cada elemento da lista. Se o elemento é maior que 2 a variável contadora será incrementada. E, em seguida, exibe a quantidade de valores maiores que 2.


text:
Q: Using Notes Address Book and Active Directory for Domino authentication concurrently We would like to allow both IBM Notes AND Active Directory authentication to be used for Domino application servers, at least for now. Employees are gradually moving from Notes to O365 (uses AD), for mail, so this will allow both methods to be used for applications in the interim. My question is a bit similar, but more specific, to this question. We basically followed this IBM technote, added the distinguished names to the AD, set up the Directory Assistance (DA), and it is working somewhat. This is what we found:

*

*Once logged in with the AD account, the Domino server correctly matches the AD account with the Notes account, thereby using Domino for authorization. This means that Notes groups, roles, ACLs, etc., work properly. For example, for one application, I logged in with my AD account in one browser and my Notes account in the other. After saving changes in both, I could see the changes in each browser (documents only shown based on @Username). In the back-end, all documents were updated by the same Notes user. So, two ways to authenticate to the same Notes account.

*On a production server (in same Domino domain as the Notes LDAP), logging in with the AD account forces a change password page. Note that the Notes accounts still have their passwords and password expiration policies. I acknowledge that if we remove these, it should work, but it's not something we want to do right now.

*On the production server, logging in with an AD account that is not in Domino is almost immediate. Otherwise, it can take around 10 seconds (which is unacceptable).

*When logging into another Domino server, in a different Domino domain from the LDAP, the login is still slow, as above, but no change password page appears.

*From the Domino server, we can ping the AD, and a trace shows only two hops.

*Changing the order of the AD in the DA doesn't seem to make any difference on the slowness, nor does disabling the Notes directories.

Any idea how we can concurrently use Domino and the AD to authenticate to Domino application servers? Has anybody been able to achieve this? Have you found a way to speed up the authentication process? Also, have you seen the change password page in this example, and if so, what did you do to fix it?
Thank you, in advance.

A: For anyone else who needs help with this, we asked IBM's help, and this is the answer:

*

*In order to remove the "change password" page, clear the value of the "PasswordDigest" field in the person documents.

*To fix the speed, use custom LDAP filters, as per this IBM technote.


text:
Q: Angular 2 - Images not showing on safari My question is about image tag on safari browser.
I have code in angular 2 for displaying images on the page

It works well with other browsers but not on Safari.
On Safari browser it just shows the string img which is alt attribute.
The point is that other images show up.
  {{incident.status || 'N/a'}}

for example above code just works fine in the same file.
Right now I am think may be it's issue with  inside *ngFor but not sure.
Hope anyone can help me on this tricky thing!
Thank you.

A: Try surrounding your statement in brackets (i && i.url != 'null') ? i.url : '' . Also depending on your value if null is not supposed to be hard coded string, leave out quotes.

A: Thank you for your answer, Slobodan.
After days of researching I found the issue.
Actually it was not an issue on Angular but just https / http issue.
The image url saved on backend was http:// while the site was running on https://
It's strange that other browsers (google chrome and firefox) works fine with fetching http images from https but safari was strict.
Hope this would help you later!
Also those parentheses greatly helped me on other page. :)
Thank you again.


text:
Q: Get certain nodes out of a Parse Tree I am working on a project involving anaphora resolution via Hobbs algorithm. I have parsed my text using the Stanford parser, and now I would like to manipulate the nodes in order to implement my algorithm.
At the moment, I don't understand how to:

*

*Access a node based on its POS tag (e.g. I need to start with a pronoun - how do I get all pronouns?).

*Use visitors. I'm a bit of a noob of Java, but in C++ I needed to implement a Visitor functor and then work on its hooks. I could not find much for the Stanford Parser's Tree structure though. Is that jgrapht? If it is, could you provide me with some pointers at code snippets?

A: Here's a simple example that parses a sentence and finds all of the pronouns.
private static ArrayList<Tree> findPro(Tree t) {
    ArrayList<Tree> pronouns = new ArrayList<Tree>();
    if (t.label().value().equals("PRP"))
        pronouns.add(t);
    else
        for (Tree child : t.children())
            pronouns.addAll(findPro(child));
    return pronouns;
}

public static void main(String[] args) {

    LexicalizedParser parser = LexicalizedParser.loadModel();
    Tree x = parser.apply("The dog walks and he barks .");
    System.out.println(x);
    ArrayList<Tree> pronouns = findPro(x);
    System.out.println("All Pronouns: " + pronouns);

}

This prints:
    (ROOT (S (S (NP (DT The) (NN dog)) (VP (VBZ walks))) (CC and) (S (NP (PRP he)) (VP (VBZ barks))) (. .)))
    All Pronouns: [(PRP he)]

A: @dhg's answer works fine, but here are two other options that it might also be useful to know about:

*

*The Tree class implements Iterable.  You can iterate through all the nodes of a Tree, or, strictly, the subtrees headed by each node, in a pre-order traversal, with:
for (Tree subtree : t) {
    if (subtree.label().value().equals("PRP")) {
        pronouns.add(subtree);
    }
}

*You can also get just nodes that satisfy some (potentially quite complex pattern) by using tregex, which behaves rather like java.util.regex by allowing pattern matches over trees.  You would have something like:
TregexPattern tgrepPattern = TregexPattern.compile("PRP");
TregexMatcher m = tgrepPattern.matcher(t);
while (m.find()) {
    Tree subtree = m.getMatch();
    pronouns.add(subtree);
}


text:
Q: Same binding, different presentations? <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <System:DateTime x:Key="d" >2012/7/8</System:DateTime>
    </Window.Resources>
    <StackPanel>
        <ContentControl Content="{Binding}" DataContext="{StaticResource d}" />
        <TextBlock Text="{Binding}" DataContext="{StaticResource d}"/>
    </StackPanel>
</Window>

This code gives me the following window.

Strangely, the identical binding when applies to ContentControl only shows date part and when applies to TextBlock also shows time part.
I'm just curious to know the reason and ask whether it is possible to exchange the presentation, I mean TextBlock only shows date part and ContentControl shows both part.
Thank you.

A: For the ContentControl, use ContentStringFormat. For the TextBlock, use a Binding with a StringFormat:
<ContentControl Content="{Binding}" ContentStringFormat="dd/MM/yyyy HH:mm:ss"/>
<TextBlock Text="{Binding ., StringFormat=dd/MM/yyyy}"/>

In short, the difference comes down to the fact that a ContentControl can show any old object as content (not just a string) whereas TextBlock.Text can only be a string.


text:
Q: Where should the antecedent for "it" be? When I posted a previous question, a contributor to this site amicably corrected my text, explaining that "it" needed and antecedent. Here is my text under consideration:

*

*Finally, the storm ended. Then, the two groups of men reached the centre of the field with their goods to trade. After they did it, each side took what was theirs and went back.
In the above paragraph, "did it" refers to "to trade". Nonetheless, he made a correction which implies that "it" cannot stand on its own in the third sentence but needs to be explicitly mentioned before, i.e., "to trade" in the same sentence. The change resulted in something like this: "After they made their trade, each side…"
However, I incessantly came across a myriad of examples in widely known literary works in which "it" has its antecedent in a previous sentence or even paragraph.
You can read some of them:

*

*'Colonel Brandon is so delicate a man, that he rather wished any one to announce his intentions to Mr. Ferrars than himself.'
'And so you are forced to do it.
(Sense and sensibility, Jane Austen, 1811)

*'Suppose he did all this, what then?' 'What then!' replied Sikes; with a tremendous oath. 'If he was left alive till I came, I'd grind his skull under the iron heel of my boot into as many grains as there are hairs upon his head.' 'What if I did it!' cried Fagin almost in a yell.
(Oliver Twist, Charles Dickens, 1839)

*You only just tell a boy you won't ever have anybody but him, ever ever ever, and then you kiss and that's all. Anybody can do it.
(The Adventures of Tom Sawyer, Mark Twain, 1876)

*Syme was able to pour out for the first time the whole of his outrageous tale, from the time when Gregory had taken him to the little tavern by the river. He did it idly and amply...
(The Man Who Was Thursday, a nightmare, G. K. Chesterton, 1908)

*That's a wrestling hold, in case you don't know, where you get the other guy around the neck and choke him to death, if you feel like it. So I did it.
(The Catcher in the Rye, J.D. Salinger, 1951)
And you can also see it here:

*

*Don't drink the milk. It smells terrible.
(Cambridge Dictionary, 2021)
I would greatly appreciate your help in clarifying this matter.

A:
Finally, the storm ended. Then, the two groups of men reached the
centre of the field with their goods to trade. After they did it, each
side took what was theirs and went back. In the above paragraph, "did
it" refers to "to trade".

No, it does not. By default, it refers to "they reached the centre of the field", i.e.
the two groups of men reached the centre of the field with their goods. After they had done it, each side took what was theirs and went back.
That is why you need to be explicit.  Also "their goods to trade" is a noun phrase where "to trade" acts as an adjective. It means "their trade goods".
Quite apart from the grammar, the sentence is not at all idiomatic.
EDIT I have deleted the last part of this answer to reconsider. There are several problems with your sentence and in my opinion it needs to be substantially rewritten to make sense.


text:
Q: Braintree sends fraud response when Multi Addresses Shipping Enabled We are facing issue with Magento2 Multi-Address checkout.
We have enabled this to allow customers to put through large orders to be sent to multiple addresses.
Even though to the customer it looks to be one payment we know it actually splits the order by address and takes a payment per order. The challenge is we are having customers make large orders for up to 100 addresses and the first 5 orders/payments are going through fine but the subsequent payments for the remaining order are all being rejected by the bank and therefore the rest of the orders are not being created.
We are currently using it on Magento 2.4.2 with Braintree as the PSP.


text:
Q: Hiding channel with Djs12 I need to lock a text channel, so @everyone cannot see that, but message.author can. I have this code, but everyone can see the channel (and in the channel properties everyone hasn't got permission for send messages or send TTS messages, but above that everything is [/])
message.guild.channels.create(desc, {
                    type: 'text',
                    permissionOverwrites: [
                        {
                            id: message.guild.roles.everyone,
                            deny: ['VIEW_CHANNEL', 'SEND_MESSAGES'],
                        },
                        {
                            id: message.author.id,
                            allow: ['VIEW_CHANNEL'],
                        },
                    ],
                })

A: The PermissionOverwrites typedef requires a Snowflake (in this case, a role or user ID). However, RoleManager.everyone returns a Role. There are two ways to solve this issue:

*

*Simply just use the id property of the role

{
 id: message.guild.roles.everyone.id,
 deny: ['VIEW_CHANNEL', 'SEND_MESSAGES'],
},

*

*Use message.guild.id. Fun fact, the @everyone role shares the same ID as the guild it's in

{
 id: message.guild.id,
 deny: ['VIEW_CHANNEL', 'SEND_MESSAGES'],
},


text:
Q: How to clean a string and extract number postfixes in T-SQL I have a string that consists of a name and in most cases it has a postfix with one or two numbers at the end. This number-postfix should be cut off from the name. One number represents a status and should be extracted. If there are two numbers it is the seconde from the right, if there is one number it is the first from the right. These numbers are seperated by an underscore. Underscores can also be used within the name.
The result should be a column with the clearname and the extracted status.
I tried to solve the problem with the standard string functions like Substring, Charindex, Patindex, LEN and son on. But my approach became very bulky quickly and hard to maintain. I wonder if there is an elegant solution with the usual SQl-Server capabilities (if possible without installing extras for regex).
SELECT _data.myStr
    -- , ... AS clearname  /*String cleaned from number_postfixes*/
    -- , ... AS Status     /*second number from the right*/
FROM (
    SELECT 'tree_leafs_offer_2_1' AS myStr  --clearname: tree_leafs_offer; cut off: _2_1; extracted status: 2
        UNION
    SELECT 'tree_leafs_offer_2_10' AS myStr --clearname: tree_leafs_offer_2_10; cut off: _2_10; extracted status: 2
        UNION
    SELECT 'tree_leafs_offer_2_2' AS myStr  --clearname: tree_leafs_offer; cut off: _2_2; extracted status: 2
        UNION
    SELECT 'tree_leafs_offer_1150_1' AS myStr   --clearname: tree_leafs_offer; cut off: _1150_1; extracted status: 1150
        UNION
    SELECT 'tree_leafs_offer_1150_10' AS myStr  --clearname: tree_leafs_offer; cut off: _1150_10; extracted status: 1150
        UNION
    SELECT 'builder_bundle_less_xl_1' AS myStr  --clearname: builder_bundle_less_xl; cut off: _1; extracted status: 1
        UNION
    SELECT 'builder_bundle_less_xl_10' AS myStr --clearname: builder_bundle_less_xl; cut off: _10; extracted status: 10
        UNION
    SELECT 'static_components_wolves_10_4' AS myStr --clearname: static_components_wolves; cut off: _10_4; extracted status: 4
        UNION
    SELECT 'coke_0_boring_components_bundle_grant_1' AS myStr   --clearname: oke_0_boring_components_bundle_grant; cut off: _1; extracted status: 1
        UNION
    SELECT 'coke_0_soccer18_end_1_4h_101' AS myStr  --clearname: coke_0_soccer18_end_1_4h; cut off: _101; extracted status: 101
        UNION
    SELECT 'coke_0_late_downsell_bundle_high_114' AS myStr  --clearname: coke_0_late_downsell_bundle_high; cut off: _114; extracted status: 114
        UNION
    SELECT 'itembundle_mine_bundle_small' AS myStr  --clearname: itembundle_mine_bundle_small; cut off: <nothing>; extracted status: NULL
) AS _data

As-Is Result:
-----------------
myStr:
---------------------------------------
builder_bundle_less_xl_1
builder_bundle_less_xl_10
coke_0_boring_components_bundle_grant_1
coke_0_late_downsell_bundle_high_114
coke_0_soccer18_end_1_4h_101
itembundle_mine_bundle_small
static_components_wolves_10_4
tree_leafs_offer_1150_1
tree_leafs_offer_1150_10
tree_leafs_offer_2_1
tree_leafs_offer_2_10
tree_leafs_offer_2_2

To-Be Result (two new columns):
-------------------
clearname:                              |Status
----------------------------------------------
builder_bundle_less_xl                  |   1
builder_bundle_less_xl                  |  10
coke_0_boring_components_bundle_grant   |   1
coke_0_late_downsell_bundle_high        | 114
coke_0_soccer18_end_1_4h                | 101
itembundle_mine_bundle_small            |NULL
static_components_wolves                |  10
tree_leafs_offer                        |1150
tree_leafs_offer                        |1150
tree_leafs_offer                        |   2
tree_leafs_offer                        |   2
tree_leafs_offer                        |   2

A: To be honest: this format is awful! If this is not a one-time-action you really should try to change this before you have to deal with it.
But - if you have to stick with this - you might give this a try:
EDIT: resolved a bad computation of the status position...
DECLARE  @tbl TABLE(ID INT IDENTITY,myStr VARCHAR(1000));
INSERT INTO @tbl VALUES
 ('tree_leafs_offer_2_1')
,('tree_leafs_offer_2_10')
,('tree_leafs_offer_2_2')
,('tree_leafs_offer_1150_1')
,('tree_leafs_offer_1150_10')
,('builder_bundle_less_xl_1')
,('builder_bundle_less_xl_10')
,('static_components_wolves_10_4')
,('coke_0_boring_components_bundle_grant_1')
,('coke_0_soccer18_end_1_4h_101')
,('coke_0_late_downsell_bundle_high_114')
,('itembundle_mine_bundle_small');

The query
WITH cte AS
(
    SELECT t.ID
          ,t.myStr
            ,A.[key] AS Position
            ,A.[value] AS WordFragment
            ,B.CastedToInt
    FROM @tbl t
    CROSS APPLY OPENJSON(N'["' + REPLACE(t.myStr,'_','","') + '"]') A
    CROSS APPLY(SELECT TRY_CAST(A.[value] AS INT)) B(CastedToInt)
)
SELECT ID
      ,myStr
        ,STUFF(
        (SELECT CONCAT('_',cte2.WordFragment)
        FROM cte cte2
        WHERE cte2.ID=cte.ID
            AND cte2.Position<=A.PositionHighestNonInt
        ORDER BY cte2.Position
        FOR XML PATH('')
        ),1,1,'') AS ClearName
        ,(SELECT cte3.CastedToInt FROM cte cte3 WHERE cte3.ID=cte.ID AND cte3.Position=A.PositionHighestNonInt+1) AS [Status]
FROM cte
CROSS APPLY (
                 SELECT ISNULL(MAX(x.Position),1000)
                 FROM cte x
                 WHERE x.ID=cte.ID AND x.CastedToInt IS NULL
             ) A(PositionHighestNonInt)
GROUP BY ID,myStr,PositionHighestNonInt;

The result
+----+---------------------------------------+--------+
| ID | ClearName                             | Status |
+----+---------------------------------------+--------+
| 1  | tree_leafs_offer                      | 2      |
+----+---------------------------------------+--------+
| 2  | tree_leafs_offer                      | 2      |
+----+---------------------------------------+--------+
| 3  | tree_leafs_offer                      | 2      |
+----+---------------------------------------+--------+
| 4  | tree_leafs_offer                      | 1150   |
+----+---------------------------------------+--------+
| 5  | tree_leafs_offer                      | 1150   |
+----+---------------------------------------+--------+
| 6  | builder_bundle_less_xl                | 1      |
+----+---------------------------------------+--------+
| 7  | builder_bundle_less_xl                | 10     |
+----+---------------------------------------+--------+
| 8  | static_components_wolves              | 10     |
+----+---------------------------------------+--------+
| 9  | coke_0_boring_components_bundle_grant | 1      |
+----+---------------------------------------+--------+
| 10 | coke_0_soccer18_end_1_4h              | 101    |
+----+---------------------------------------+--------+
| 11 | coke_0_late_downsell_bundle_high      | 114    |
+----+---------------------------------------+--------+
| 12 | itembundle_mine_bundle_small          | NULL   |
+----+---------------------------------------+--------+

The idea:

*

*Provide your data in a mockup table

*Use a trick with OPENJSON to get the string split and find parts which can be cast to INT.

*Find the highest non-int fragment. The Status will be the next index

*With v2017 you could use STRING_AGG, but with v2016 we have to use a XML-based trick to concatenate all fragments before the [Status].

A: One possible approach is to use string replacement and JSON capabilities of SQL Server 2016+. Each row is reversed and transformed into a valid JSON array ('tree_leafs_offer_2_1' is transformed into '["1","2","reffo","sfael","eert"]' for example). Then you can easily check if the first and the second items are valid numbers using JSON_VALUE(<json_array>, '$[0]'), JSON_VALUE(<json_array>, '$[1]') and TRY_CONVERT(). This will work if you have maximum two numbers from the right.
Input:
CREATE TABLE #Data (
   myStr varchar(max)
)
INSERT INTO #Data
   (MyStr)
VALUES
   ('tree_leafs_offer_2_1'),
   ('tree_leafs_offer_2_10'),
   ('tree_leafs_offer_2_2'),
   ('tree_leafs_offer_1150_1'),
   ('tree_leafs_offer_1150_10'),
   ('builder_bundle_less_xl_1'),
   ('builder_bundle_less_xl_10'),
   ('static_components_wolves_10_4'),
   ('coke_0_boring_components_bundle_grant_1'),
   ('coke_0_soccer18_end_1_4h_101'),
   ('coke_0_late_downsell_bundle_high_114'),
   ('itembundle_mine_bundle_small')

T-SQL:
SELECT
   LEFT(myStr, LEN(myStr) - CHARINDEX('_', REVERSE(myStr))) as ClearName,
   REVERSE(LEFT(REVERSE(myStr), CHARINDEX('_', REVERSE(myStr)) - 1)) AS Status
FROM (
   SELECT
      CASE
         WHEN
            TRY_CONVERT(int, REVERSE(JSON_VALUE(CONCAT('["', REPLACE(STRING_ESCAPE(REVERSE(MyStr), 'json'), '_', '","'), '"]'), '$[1]'))) IS NULL AND
            TRY_CONVERT(int, REVERSE(JSON_VALUE(CONCAT('["', REPLACE(STRING_ESCAPE(REVERSE(MyStr), 'json'), '_', '","'), '"]'), '$[0]'))) IS NULL
            THEN CONCAT(myStr, '_0')
         WHEN
            TRY_CONVERT(int, REVERSE(JSON_VALUE(CONCAT('["', REPLACE(STRING_ESCAPE(REVERSE(MyStr), 'json'), '_', '","'), '"]'), '$[1]'))) IS NULL AND
            TRY_CONVERT(int, REVERSE(JSON_VALUE(CONCAT('["', REPLACE(STRING_ESCAPE(REVERSE(MyStr), 'json'), '_', '","'), '"]'), '$[0]'))) IS NOT NULL
            THEN MyStr
         ELSE LEFT(myStr, LEN(myStr) - CHARINDEX('_', REVERSE(myStr)))
      END AS myStr
   FROM #Data
) fixed
ORDER BY MyStr

Output:
----------------------------------------------
ClearName                               Status
----------------------------------------------
builder_bundle_less_xl                  1
builder_bundle_less_xl                  10
coke_0_boring_components_bundle_grant   1
coke_0_late_downsell_bundle_high        114
coke_0_soccer18_end_1_4h                101
itembundle_mine_bundle_small            0
static_components_wolves                10
tree_leafs_offer                        1150
tree_leafs_offer                        1150
tree_leafs_offer                        2
tree_leafs_offer                        2
tree_leafs_offer                        2


text:
Q: Use PHP variable in SPARQL? $abc=$_GET["q"];

$store = ARC2::getStore($arc_config);

         $p = '
           SELECT DISTINCT ?property WHERE {
           ${"abc"} ?property ?object .
        }
    ';

I want to retrieve properties whose subject is equal to $abc (PHP variable) via GET method. But I am facing problems.
I am using ARC2 as RDFStore and SPARQL to retrieve and PHP.

A: Common string operations
For example
$p = sprintf('
       SELECT DISTINCT ?property WHERE {
       %s ?property ?object .
    }
', $abc);

or
$p = "
       SELECT DISTINCT ?property WHERE {
       $abc ?property ?object .
    }
";

or
$p = '
       SELECT DISTINCT ?property WHERE {
       ' . $abc . ' ?property ?object .
    }
';


text:
Q: Error 1062 (23000 at line 13192: Duplicate entry 'default-0-payment/stripe_payments/payment_flow' for key 'CORE_CONFIG_DATA_SCOPE_SCOPE_ID_PATH' To migrate Magento2 site to other server, I dump my db and import the db on the new server. But I get this error.
Error 1062 (23000 at line 13192: Duplicate entry 'default-0-payment/stripe_payments/payment_flow' for key 'CORE_CONFIG_DATA_SCOPE_SCOPE_ID_PATH'
I tried remove and reinstall StripeIntegration_Payments module but still get this error.

A: *

*Run the SQL query to get this config value for later reference:
SELECT * FROM `core_config_data` WHERE `path` = 'payment/stripe_payments/payment_flow' AND `scope_id` = '0';

*Run the SQL query to remove this config from the database to prevent the duplicate:
DELETE FROM `core_config_data` WHERE `path` = 'payment/stripe_payments/payment_flow' AND `scope_id` = '0';

*Run bin/magento setup:upgrade command.

*Check and compare the current config with the result in the first step, then edit it manually if needed:
SELECT * FROM `core_config_data` WHERE `path` = 'payment/stripe_payments/payment_flow' AND `scope_id` = '0';

If you see a similar new error, you should use the below solution to work with all Stripe Integration Payments stripe_payments configs:

*

*Run the SQL query to get the config values for later reference:
SELECT * FROM `core_config_data` WHERE `path` LIKE 'payment/stripe_payments/%';

*Run the SQL query to remove the configs from the database to prevent the duplicate:
DELETE FROM `core_config_data` WHERE `path` LIKE 'payment/stripe_payments/%';

*Run bin/magento setup:upgrade command.

*Check and compare the current configs with the result in the first step, then edit them manually if needed:
SELECT * FROM `core_config_data` WHERE `path` LIKE 'payment/stripe_payments/%';


text:
Q: Oracle joins ( left outer, right, etc. :S ) I knew stackoverflow would help me for other than know what is the "favorite programming cartoon" :P
This was the accepted answer by:
Bill Karwin
Thanks to all for the help ( I would like to double vote you all )
My query ended up like this ( this is the real one )
SELECT
    accepted.folio,
    COALESCE( inprog.activityin, accepted.activityin ) as activityin,
    inprog.participantin,
    accepted.completiondate
FROM performance accepted
    LEFT OUTER JOIN performance inprog
        ON( accepted.folio = inprog.folio
            AND inprog.ACTIVITYIN
            IN ( 4, 435 )                    -- both are ids for inprogress
            AND inprog.PARTICIPANTIN != 1  ) -- Ignore the "bot" participant
    LEFT OUTER JOIN performance closed
        ON( accepted.folio = closed.folio
            AND closed.ACTIVITYIN IN ( 10,436, 4, 430  ) )  -- all these are closed or cancelled
WHERE accepted.ACTIVITYIN IN ( 3, 429 )      --- both are id for new
AND accepted.folio IS NOT NULL
AND closed.folio IS NULL;

Now I just have to join with the other tables for a human readable report.

ORIGINAL POST
Hello.
I'm struggling for about 6 hrs. now with a DB query ( my long time nemesis )
I have a data table with some fields like:
table performance(
     identifier varchar,
     activity    number,
     participant number,
     closedate   date,
)

It is used to keep track of the history of ticket
Identifier: is a customer id like ( NAF0000001 )
activity: is a fk of  where the ticket is ( new, in_progress, rejected, closed, etc )
participant: is a fk of  who is attending at that point the ticket
closedate: is the date when that activity finished.
EDIT: I should have said "completiondate" rather than closedate. This is the date when the activity was completed, not necessary when the ticket was closed.
For instance a typical history may be like this:

identifier|activity|participant|closedate
-------------------------------------------
NA00000001|       1|          1|2008/10/08 15:00|
-------------------------------------------
NA00000001|       2|          2|2008/10/08 15:20|
-------------------------------------------
NA00000001|       3|          2|2008/10/08 15:40|
-------------------------------------------
NA00000001|       4|         4|2008/10/08 17:05|
-------------------------------------------

And participant 1=jonh, 2=scott, 3=mike, 4=rob
and activties   1=new, 2=inprogress, 3=waitingforapproval, 4=closed
etc. And tens of other irrelevant info.
Well my problem is the following.
I have managed to create a query where I can know when a ticket was opened and closed
it is like this:
 select
     a.identifier,
     a.participant,
     a.closedate as start,
     b.closedate as finish
from
    performance a,
    performance b
where
    a.activity = 1 -- new
    and b.activity = 4 -- closed
    and a.identifier = b.identifier

But I can't know what tickets are not closed and who is attending them.
So far I have something like this:
 select
     a.identifier,
     a.participant,
     a.closedate as start
from
    performance a
where
    a.activity = 1 -- new
    and a.identifier not in ( select identifier from performance where activity = 4 ) --closed

That is give me all the ones who have an start ( new = 1 ) but are not closed ( closed = 4 )
But the big problem here is that it prints the participant who opened the ticket, but I need the participant who is attending it. So I add the "inprogress" activity to the query.
 select
     a.identifier,
     a.participant,
     a.closedate as start
from
    performance a,
    performance b
where
    a.activity = 1 -- new
    and a.identifier not in ( select identifier from performance where activity = 4 ) --closed
    and b.identifier = a.identifier
    and b.activity = 2  -- inprogress..

But not all the rows that are in "new" are "inprogress" and with that query I drop all of them.
What I need is to show all the "inprogress" participant and if the ticket is not "inprogress", it will show  as empty.
Somthing like

    identifier|activity|participant|closedate
-------------------------------------------
NA00000002|       1|           |2008/10/08 15:00|
-------------------------------------------
NA00000003|       1|           |2008/10/08 15:20|
-------------------------------------------
NA00000004|       1|           |2008/10/08 15:40|
-------------------------------------------
NA00000005|       2|          4|2008/10/08 15:40|
-------------------------------------------
NA00000006|       2|          4|2008/10/08 15:40|

In this case
NA002, NA003 and NA004 are in "new", so no participant is shown
While
NA005 and NA006 are being "inprgress (act = 2 )" and they are being attended by rob ( participant 4 )
So I remember there was this thing called left outer join or something like that but I never ever understand it. What I would like to know is how can I fetch the identifiers that are "inprogress" and "new" and that are not closed.
Probably taking a little rest would help me to clear my mind. If anyone knows how to do it I'll appreciate it.
By the way I've tried:
 select
     a.identifier,
     a.participant,
     a.closedate as start
from
    performance a
    left outer join
    performance b
    on
    b.identifier = a.identifier
where
    a.activity = 1 -- new
    and a.identifier not in ( select identifier from performance where activity = 4 ) --closed
    and b.activity = 2  -- inprogress..

But gives me the same result as the previous ( drop the only in "new" records  )

A: Typically the better way to write those is with EXISTS.  The first one would be:
select * from performance p1
where not exists
    ( select * from performance p2
      where p2.identifier = p1.identifier and p2.activity = 4 )

This way lets you do a keyed lookup on performance.identifier, rather than potentially having to build a massive list of identifiers in (select identifier from performance where activity=4).

A: Try something like this (I haven't tested it):
SELECT p_new.identifier, COALESCE(p_inprog.activity, p_new.activity) AS activity,
  p_inprog.participant, COALESCE(p_inprog.closedate, p_new.closedate) AS closedate
FROM performance p_new
  LEFT OUTER JOIN performance p_inprog
    ON (p_new.identifier = p_inprog.identifier AND p_inprog.activity = 2)
  LEFT OUTER JOIN performance p_closed
    ON (p_new.identifier = p_closed.identifier AND p_closed.activity = 4)
WHERE p_new.activity = 1
  AND p_closed.identifier IS NULL;

I think people believe outer joins are harder than they really are.  For example:
A LEFT OUTER JOIN B ON (...condition...)

This returns all rows from A, whether or not there are any matching rows in B.  If no  rows in B match, treat all columns B.* as NULL in the result set for that row of A.  The join condition can be an expression that the row in B must satisfy, or else it isn't included in the join.  So, more rows in A will be solo.

A: I think this should do it.
The first part gets all records that are new, not closed and not in progress.  The second part gets all in progress records. We then join them together, we can also sort by identifier by wrapping a 'SELECT * FROM' around this query.
select
  a.identifier,
  a.participant,
  a.closedate as start
from
  performance a
where
  a.activity = 1
  and not exists ( select identifier
                   from performance b
                   where b.activity = 4
                   and b.identifier = a.identifier)
  and not exists ( select identifier
                   from performance c
                   where c.activity = 2
                   and c.identifier = a.identifier)
UNION ALL
select
  a.identifier,
  a.participant,
  a.closedate as start
from
  performance a
where
  a.activity = 2
  and not exists ( select identifier
                   from performance b
                   where b.activity = 4
                   and b.identifier = a.identifier);

A: I would suggest that what you want is the earliest record (presumably, but not necessarily the one with activity=1) and the most recent record (regardless of activity number).  If the activity of the most recent record is 4 then the ticket is closed. otherwise, the participant is the current holder of the ticket.  There is a potential bug introduced by just matching on activity = 4 if the ticket can be re-opened.
Actually, based upon your example, you may not even need the earliest record.  How about the following:
SELECT
        identifier,
        activity,
        participant,
        closedate
    FROM
        performance a
    WHERE
        (a.identifier, a.closedate) in
            (select b.identifier, max(b.closedate)
                from performance b
                group by b.identifier
            )
;

A: How about this:
SELECT * FROM (
  SELECT identifier,
         MAX(activity) activity,
         MAX(participant) KEEP (DENSE_RANK LAST ORDER BY activity)
    FROM performance
    GROUP BY identifier
)
WHERE activity in (1,2)

The inner query gives the latest activity for each ticket and its corresponding participant.  The outer query filters this down to the ones where the activity is either "new" or "in progress".
I love the DENSE_RANK functions.

A: Firstly, you may have a design issue if you can have a customer with multiple tickets open at the same time. You should ideally have a ticket_id, and then you can perform Andy's query by using ticket_id instead of identifier.

A: What tickets are not closed:
select identifier as closed_identifier
  from performance where identifier not exists
  (select identifier from performance where activity=4)

Tickets that are being attended:
select identifier as inprogress_identifier, participant performance
  from performance where activity=2

Unclosed tickets, with the participant of that are being attended:
select * from
  (select identifier as notclosed_identifier
    from performance where identifier not exists
    (select identifier from performance where activity=4)) closed
left join
  (select identifier as inprogress_identifier, participant performance
    from performance where activity=2) attended
on notclosed_identifier=inprogress_identifier

A: May be you can use this kind of query as a starting point.
select x.identifier,
       max(x.p_1) as new_participant, max(x.c_1) as new_date,
       max(x.p_2) as inprogress_participant, max(x.c_2) as inprogress_date,
       max(x.p_3) as approval_participant, max(x.c_3) as approval_date,
       max(x.p_4) as closing_participant, max(x.c_4) as closing_date
  from (
        select a.identifier,
               decode (activity, 1, participant, null) as p_1,  decode (activity, 1, closedate, null) as c_1,
               decode (activity, 2, participant, null) as p_2,  decode (activity, 2, closedate, null) as c_2,
               decode (activity, 3, participant, null) as p_3,  decode (activity, 3, closedate, null) as c_3,
               decode (activity, 4, participant, null) as p_4,  decode (activity, 4, closedate, null) as c_4
          from performance a
        ) x
 group by x.identifier

The idea is to serialize your table from row into field, and create a view based on it.
You can create report based on this view.
Regards,

A: Just a quick idea that others might build on (untested, but I hope the idea comes across):
First, select all not yet closed activities (as posted by others):
select id
from performance p1 where identifier not exists
  (select * from performance p2 where activity=4 and p1.id=p2.id)

Then, you can add the person attending the activity by adding a subquery in the select clause:
select id,
 (select participant
  from performance p3
  where p3.activity=3 and p1.id=p2.id)
from performance p1 where identifier not exists
  (select * from performance p2 where activity=4 and p1.id=p2.id)

If there is no activity 3 record for this id, the subquery returns null which is exactly what we need.
Hope this helps - please expand if necessary.


text:
Q: Beginner JavaScript/HTML Frame Communication One of my assignments for my Web Design class is to create a page in which two frames communicate using JavaScript. There are four links on the lower frame (lower2.html) and when clicked, they're supposed to change the image in the upper frame (upper1.html) to the respective image but don't. Here's what I have:
File name: js-seventeen.html. This is the one I execute.

<TITLE>HTML and JavaScript</TITLE>

<FRAMESET ROWS="140,*">
<FRAME NAME="upperFrame" SRC="upper1.html">
<FRAME NAME="lowerFrame" SRC="lower2.html">
</FRAMESET>

File name: upper1.html. This is the upper frame that displays the images.

<TITLE>HTML and JavaScript</TITLE>

File name: lower2.html. This is the lower frame that contains the links that should change the images, but don't. No matter what I click, it stays on the default lions.gif.

<TITLE>HTML and JavaScript</TITLE>

IMAGE LIST

1: LIONS.GIF

2: TIGERS.GIF

3: BEARS.GIF

4: OHMY.GIF

I've looked through the book and as far as I can tell, I've done everything properly. Thanks in advance for your help.

A: JavaScript mostly works in IDs.
top gives you the main window.
Add ID attributes to frame and image tags
<frame id="upperFrame" name="upperFrame" >

You can also access frame by index
 top.frames[0].document.  ,,,

Read www.w3schools.com stuff. Also frameset has been done away with in HTML5 so consider learning about iframes
Assign IDs to the frame and image as well, make ID same as name and try something like this
 top.frames["upperFrame"].document.getElementById["imageIdNotName"].src = 'new value';


text:
Q: Typescript mixin with protected access I have the following mixin setup. A mixin called Activatable that needs access to the protected members of User.
type Constructor<T = {}> = new (...args: any[]) => T;

function Activatable<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    isActivated = false;

    activate() {
      this.isActivated = true;
      this.deactivate();
    }

    deactivate() {
      this.isActivated = false;
    }

    /**
     * In order to access the protected members of User, I needed to
     * add `this` to the args
     */
    test(this: User) {
      this.me = "bo";
      // this method cannot access any other method in the mixin
    }
  };
}

class User {
  name: string;
  protected me: string;

  constructor(name: string) {
    this.name = name;
    this.me = "hi";
  }
}

const ActivatableUser = Activatable(User);

// Instantiate the new `ActivatableUser` class
const user = new ActivatableUser("John Doe");

// Initially, the `isActivated` property is false
console.log(user.isActivated);

// Activate the user
user.activate();
user.test();

// Now, `isActivated` is true
console.log(user.isActivated);

In order for me to access the protected and private members (see test()), I needed to use this:User as part of the signature. The disadvantage of the approach is test() can not longer access the other methods of the Activatable mixin.
I would prefer to not have to give the returned class expression a name and use as to convert the this to an instance of the mixin.
Since I know this mixin will be used only for the User class, is there a way I can incorporate that information as part of the definition of Activatable? So I don't have to use this:User as part of the method signature?
See Playground Link
Thanks everyone

A: In my project, I have gone through three stages when using mixin. Your problem happens to be my problem in the third stage, so I provide my three-stage solution, hoping to help you.
The first stage: I just need a simple mixin, and I don't care what target class it will be added to. There is no requirement for the specification of the target class, So the code is very simple:
type Constructor<T = {}> = new (...args: any[]) => T;

function ActivatableMixin<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    isActivated = false;
    activate() {
      this.isActivated = true;
      this.deactivate();
    }
    deactivate() {
      this.isActivated = false;
    }
    test() {
      console.log(this.isActivated ? 'activated' : 'not activated');
    }
  };
}

class User {
  name: string;
  me: string;
  constructor(name: string) {
    this.name = name;
    this.me = "hi";
  }
}

const ActivatableUser = ActivatableMixin(User);

// Instantiate the new `ActivatableUser` class
const user = new ActivatableUser("John Doe");

// Initially, the `isActivated` property is false
console.log(user.isActivated);

// Activate the user
user.activate();
user.test();

// Now, `isActivated` is true
console.log(user.isActivated);

The second stage: I need to be able to access some members (properties or methods) of the target class in the mixin, so I also require that the target class must contain these members. If a class does not contain these members, don't expect to use my mixin. This requires adding some specifications to the first stage code:
type Constructor<T = {}> = new (...args: any[]) => T;

/**
 * the target class must fit the Activatable Interface to use the mixin
 */
interface Activatable {
  me: string
}

/**
 * Note that the mixin target class specification is specified here
 * <TBase extends Constructor<Activatable>>
 * instead of
 * <TBase extends Constructor>
 */
function ActivatableMixin<TBase extends Constructor<Activatable>>(Base: TBase) {
  return class extends Base {
    isActivated = false;
    activate() {
      this.isActivated = true;
      this.deactivate();
    }
    deactivate() {
      this.isActivated = false;
    }
    test() {
      // with target class specification we can access members form specification
      console.log(this.me)
      console.log(this.isActivated ? 'activated' : 'not activated');
    }
  };
}

class UserNoMe {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

// UserNoMe does not fit Activatable so can not be mixied
const ActivatableUserNoMe = ActivatableMixin(UserNoMe); // ts2345 error

class UserHasMe {
  name: string;
  me: string;
  constructor(name: string) {
    this.name = name;
    this.me = "hi";
  }
}
// UserHasMe fits Activatable so can be mixied
const ActivatableUser = ActivatableMixin(UserHasMe);

// Instantiate the new `ActivatableUser` class
const user = new ActivatableUser("John Doe");

// Initially, the `isActivated` property is false
console.log(user.isActivated);

// Activate the user
user.activate();
user.test();

// Now, `isActivated` is true
console.log(user.isActivated);

The third stage: I need to access the protected members in the target type in mixin. At this time, my first idea is to change the members into protected mode in the specification interface. However, the members of the interface can not use the protected modifier (which is contrary to the responsibilities of the interface), so other methods are needed. Finally, I use the following methods to achieve this:
type Constructor<T = {}> = new (...args: any[]) => T;

/**
 * The protected members that need to be accessed both in the class
 * and in the mixin are extracted into this class. This class does not
 * contain any implementation. In fact, it acts as an interface (because
 * the interface cannot contain protected members). Next, the mixin
 * specification and the target class should inherit this class.
 *
 */
class ProtectedMembersCrossClassAndMixin {
  protected me: string;
  protected saySomething() {
    throw new Error('must be implement by ')
  }
}

/**
 * the target class must fit the Activatable Interface to use the mixin
 * with protected menmbers derived from ProtectedMembersCrossClassAndMixin
 */
interface Activatable extends ProtectedMembersCrossClassAndMixin {
  you: string
}

/**
 * Note that the mixin target class specification is specified here
 * <TBase extends Constructor<Activatable>>
 * instead of
 * <TBase extends Constructor>
 */
function ActivatableMixin<TBase extends Constructor<Activatable>>(Base: TBase) {
  return class extends Base {
    isActivated = false;
    activate() {
      this.isActivated = true;
      this.deactivate();
    }
    deactivate() {
      this.isActivated = false;
    }
    test() {
      // with target class specification we can access members within specification
      console.log(this.you)
      // alse access protected members
      console.log(this.me);
      console.log(this.isActivated ? 'activated' : 'not activated');
    }
    /**
     * also access or override protected method members
     */
    saySomething() {
      super.saySomething();
      console.log('hello activatable mixed');
    }
  };
}

class UserNo {
  name: string;
  you: string;
  protected me: string;
  constructor(name: string) {
    this.name = name;
  }
  protected saySomething() {
    console.log('oh my');
  }
}

// UserNo does fit Activatable
// but not derive from  ProtectedMembersCrossClassAndMixin
// so can not be mixied
const ActivatableUserNoMe = ActivatableMixin(UserNo); // ts2345 error

// this one can be mixed
class UserHas extends ProtectedMembersCrossClassAndMixin {
  name: string;
  you: string;
  protected me: string;
  constructor(name: string) {
    super();
    this.name = name;
    this.me = "hi";
  }
  /**
   * typescript will not warn you if you forget to implement this method
   * because typescript thought it's implemented in  ProtectedMembersCrossClassAndMixin
   * which is not really
   */
  protected saySomething() {
    console.log('hello');
  }
}
// UserHas fits Activatable so can be mixied
const ActivatableUser = ActivatableMixin(UserHas);

// Instantiate the new `ActivatableUser` class
const user = new ActivatableUser("John Doe");

// Initially, the `isActivated` property is false
console.log(user.isActivated);

// Activate the user
user.activate();
user.test();

// Now, `isActivated` is true
console.log(user.isActivated);

Caveats for ProtectedMembersCrossClassAndMixin:

*

*The code of the class is different from that of the interface. It will still exist after compilation, so we should keep the class minimized,So don't include any implementation code.

*Only those that really need to be protected are put into this class, and others are still put into the interface

*There is another level of inheritance.

*Don't forget: both sides of base class and mixin specification interface should extend this class

*Subclasses that inherit from this class may forget to implement those inherited members

*Use it when you really know you need it and understand the defects

A: After long research and testing a lot of typescript mixins/traits libraries on Github I bumped into this library and it's really great.
https://github.com/michaelolof/typescript-mix
It turns out it solves all the issues reported in those solutions https://stackoverflow.com/a/65418734/8552565
It allows to access private and protected properties of the base class which is so cool.
...and it's pretty neat with its way of using decorators and types merging.


text:
Q: External @EJB injection return null with RESTeasy and JBoss I'm developing a RESTful Web Service on JBoss 6 Final with RESTeasy.
I have an external EJB and I want inject EJB on Web Service.
This is the code of EJB
BeanLocalInterface.java
@Local
public interface BeanLocalInterface {
  public String sayHello();
}

Bean.java
@Stateless
@LocalBinding(jndiBinding = "BeanLocal")
public class Bean implements BeanLocalInterface {

  @Override
  public String sayHello() {
    return "Hello!";
  }
}

In another project I have a WS:
@Path("/ws")
public class HelloWorldResource {

    @EJB(mappedName="BeanLocal")
    private BeanLocalInterface bean;

    @GET
    @Path("/hello")
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello() {
        return bean.sayHello();
    }
}

MyRESTApplication.java
public class MyRESTApplication extends Application {

    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> empty = new HashSet<Class<?>>();
    public MyRESTApplication(){
         singletons.add(new HelloWorldResource());
    }
    @Override
    public Set<Class<?>> getClasses() {
         return empty;
    }
    @Override
    public Set<Object> getSingletons() {
         return singletons;
    }
}

bean is alwasy null!
I have tried this solution:

*

*I have put @Stateless on HelloWorldResources

*I have create beans.xml in WEB-INF

*I have change MyRESTApplication with
@ApplicationPath("wsapp")
public class MyRESTApplication extends Application {
}
Can you help me?
PS: I don't have EAR e I don't want use it

A: I have managed to solve this. Firstly, remove all settings from web.xml regarding RESTeasy. You only need one adnotation --> @ApplicationPath
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("api")
public class MyRESTApplication extends Application {
//nothing required here, leave this empty

}

This is your session bean interface.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("MyEJB")
public interface BeanInterface {

@Path("{username}")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayHello(@PathParam("username") String username);

}

This is your session bean.
import javax.ejb.Stateless;

@Stateless
public class EJB implements BeanInterface{

@Override
public String sayHello(String username) {

    return "Hello, "+username;
}

}

With JBOSS 7.1
Usage: http:// localhost:8080 /YOURAPPNAME/api/MyEJB/Fabio
Output:Hello, Fabio
Hope this helps.


text:
Q: Is there a way to query or modify the history of a single tab with a Chrome Extension? I'm looking through the Chrome Extension API documentation about chrome.history, and I can't seem to find a way to query or modify the history of a single tab. That is to say, the back/forward menu contents of a tab. Everything in the docs seems to treat Chrome's history as if it was one large amalgam.
So, is there a way to query or modify Chrome history on a tab-by-tab basis? If so, how?

A: There is not. Jasper's suggestion is valid though, injecting a content script would allow access to the history of the tab.


text:
Q: find text and replace text excel word vba I have the following  codes
  Sub DocSearch()
Dim wdApp As Object, wdDoc As Object
Set wdApp = CreateObject("word.application")
wdApp.Visible = True
Set wdDoc = wdApp.Documents.Open("C:\Documents and Settings\Owner\My Documents\downloads\work\M-F-380.1.doc")
With wdDoc.Content.Find
  .Text = "Date:"
  .Replacement.Text = "Datetest"
  .Wrap = wdFindContinue
  .Execute Replace:=wdReplaceAll
End With
Set wdApp = Nothing: Set wdDoc = Nothing
End Sub

The above works fine and i  have added  the following in the  above vba codes and its not working
With wdDoc.Content.Find
  .Text = "Date:"
  .Replacement.Text = "Datetest"
   Text = "Prime Lending Rate"
  .Replacement.Text =" Repo Rate"
  .Wrap = wdFindContinue
  .Execute Replace:=wdReplaceAll

Your  help will be highly appreciated
Thanks

A: You need to have:
.Execute Replace:=wdReplaceAll

between each set of F/R expressions, thus:
Sub DocSearch()
Dim wdApp As Object, wdDoc As Object
Set wdApp = CreateObject("word.application")
wdApp.Visible = True
Set wdDoc = wdApp.Documents.Open("C:\Documents and Settings\Owner\My Documents\downloads\work\M-F-380.1.doc")
With wdDoc.Content.Find
  .Wrap = wdFindContinue
  .Text = "Date:"
  .Replacement.Text = "Datetest"
  .Execute Replace:=wdReplaceAll
  .Text = "Prime Lending Rate"
  .Replacement.Text = " Repo Rate"
  .Execute Replace:=wdReplaceAll
End With
Set wdApp = Nothing: Set wdDoc = Nothing
End Sub


text:
Q: How can I fix the slide navigation I working on this sliding menu. It can slide fine, but have problem to close it by clicking x.

let openNav = document.querySelector(".slideOpen");
    let closeNav =  document.querySelector(".slideClose");
    document.addEventListener("click", () => {
        openNav.style.width = "250px";
    });
    document.addEventListener("click", () => {
        closeNav.style.width = "0";
    });
.slideOpen { height: 100%; width: 0; position: fixed; z-index: 1;     top: 0; left: 0; background-color: #111; overflow-x: hidden;   transition: 0.5s; padding-top: 60px; }

.slideOpen a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; color: #818181; display: block; transition: 0.3s; }

.slideOpen a:hover { color: #f1f1f1; }

.slideOpen .slideClose { position: absolute; top: 0; right: 25px;  font-size: 36px;  margin-left: 50px; }

☰ open

 ×

 About

 Services

 Clients

 Contact

A: You need to add actionListeners on buttons(links) rather than on document.

let slide = document.querySelector(".slide");
let slideOpen = document.querySelector(".slideOpen");
let slideClose =  document.querySelector(".slideClose");
    slideOpen.addEventListener('click', function(event) {
        slide.style.width = "250px";
    });
    slideClose.addEventListener("click", () => {
        slide.style.width = "0";
    });
.slide { height: 100%; width: 0; position: fixed; z-index: 1;     top: 0; left: 0; background-color: #111; overflow-x: hidden;   transition: 0.5s; padding-top: 60px; }

.slide a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; color: #818181; display: block; transition: 0.3s; }

.slide a:hover { color: #f1f1f1; }

.slide .slideClose { position: absolute; top: 0; right: 25px;  font-size: 36px;  margin-left: 50px; }

☰ open

 ×

 About

 Services

 Clients

 Contact

A: You are making addEventListener to the whole document instead make to particular element (open and close)..
Changes:
Added a new class openMenu in the open menu element like,

☰ open

Then added a new variable to store the element like,
let open = document.querySelector(".openMenu");

Then modified document.addEventListener with open and closeNav respectively like,
open.addEventListener("click", () => {
    openNav.style.width = "250px";
});
closeNav.addEventListener("click", () => {
    openNav.style.width = "0";
});

And the changed snippet looks like,

    let openNav = document.querySelector(".slideOpen");
    let open = document.querySelector(".openMenu");
    let closeNav =  document.querySelector(".slideClose");
    open.addEventListener("click", () => {
        openNav.style.width = "250px";
    });
    closeNav.addEventListener("click", () => {
        openNav.style.width = "0";
    });
.slideOpen { height: 100%; width: 0; position: fixed; z-index: 1;     top: 0; left: 0; background-color: #111; overflow-x: hidden;   transition: 0.5s; padding-top: 60px; }

.slideOpen a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; color: #818181; display: block; transition: 0.3s; }

.slideOpen a:hover { color: #f1f1f1; }

.slideOpen .slideClose { position: absolute; top: 0; right: 25px;  font-size: 36px;  margin-left: 50px; }

☰ open

 ×

 About

 Services

 Clients

 Contact


text:
Q: row count with condition count r when its comes after c enter image description here
Event   Value       Need value as
c   0                   0
c   0                   0
c   0                   3
r   1                   0
r   1                   0
r   1                   0
c   0                   0
c   0                   0
c   0                   1
r   1                   0
c   0                   0
c   0                   2
r   1                   0
r   1                   0
count number of occurrent r when its comes after c and print the value in the last row of c


text:
Q: Can you run a 4k monitor at 30hz with a late 2011 MBA? Is it possible to run an external display connected to a late 2011 MacBook Air at 3840x2160@30Hz.
I realize having this resolution at 60hz exceeds the bandwidth limitation of a Thunderbolt 1 port. This is why I am asking specifically about 30hz.
Hardware: Late 2011 MBA running 10.9.3
Monitor: Samsung U28D590D, connected to MBA with Mini DP to DP cable
This isn't a duplicate question. The other related asked-and-answered questions all point out that this impossible for 4k@60hz. I am inquiring about 3840x2160@30hz specifically.

A: No, this is not possible. As Apple states, the only models capable of supporting 4k resolutions (3850x2160 UHD) at 30 or 60 Hzs are the late 2013 Mac Pros and late 2013 Macbook Pros:

"You can use 4K displays and Ultra HD TVs with your MacBook Pro
  (Retina, Late 2013) or Mac Pro (Late 2013) computer. You can use these
  displays at the following resolutions and refresh rates with the
  built-in HDMI port
3840 x 2160 at 30 Hz refresh rate"

In fact, this is the default configuration.
Though these two models also are capable of supporting 4k @ 60 Hz refresh, multi stream transport must be enabled on the external display.
The same applies to your Thunderbolt port. Thunderbolt 1 is not capable of driving 4K displays. Thunderbolt 2 is.


text:
Q: Inequality on probability distributions I would like to know if the following inequality is satisfied by all probability distributions (or at least some class of probability distributions) for all integer $n \geq 2$.
$\int_0^{\infty} F(z)^{n-1}(1-\frac{F(z)}{n})\left[zF(z)^{n-2} - \int_0^z F(t)^{n-2}dt\right]f(z)dz$
$\leq \int_0^{\infty} F(z)^{n-1}\left[zF(z)^{n-1} - \int_0^z F(t)^{n-1}dt\right]f(z)dz $
Some comments follow:
1) F(z) is the cumulative distribution function of any probability distribution over positive real numbers. The outer integral runs over the entire support of the distribution, thus, in general, from zero to infinity. f(z) is the probability density function.
2) I will be happy even if this is proved for bounded support distributions, in which case, the outer integral runs from 0 to some upper limit H.
3) Note that both the LHS and the RHS are always non-negative. This is because of the special form of what is inside the square brackets. For both the LHS and the RHS, the second term in the square bracket (i.e. the negative integral from 0 to z), when replaced by its value at the upper limit throughout the region of integration from 0 to z, gives precisely the first term in the square bracket. Thus the term in the square bracket is always non-negative, for both the LHS and the RHS.
4) Also note the obvious similarity in the structure between the LHS and the RHS. The only differences are the difference in exponent for what is inside the square brackets, and the LHS having an extra factor of  $1 - \frac{F(z)}{n}$.
5) Note that for $n=2$, this inequality is definitely true since the LHS evaluates to zero owing to the term in the square bracket in the LHS becoming zero, and the RHS is always non-negative, as mentioned in point 3 above.
6) It is easy to work out that for all $n \geq 2$, this inequality is true for uniform [0,1] distributions, i.e., the distribution with support [0,1] and $F(z) = z$.
7) I tried evaluating this integral for small values of $n$ (till 50) using Maple for exponential distribution,  and the positive half of the normal distribution and found it to be true. I am guessing that this inequality is true for at least some large class of probability distributions if not all distributions.
8) For instance, would a monotone hazard rate condition help? Monotone hazard rate means that $\frac{f(z)}{1-F(z)}$ is non-decreasing.

A: The inequality holds for every $n\ge2$ (integer or not) and every probability distribution. Here is a proof. We begin with two easy facts.
Fact 1: For every $z\ge0$ and every $k\ge1$,
$$
zF(z)^k-\int_0^zF(t)^k\mathrm{d}t=k\int_0^ztF(t)^{k-1}f(t)\mathrm{d}t.
$$
Fact 2: For every $t$ and every $k\ge0$,
$$
(k+1)\int_t^{+\infty}F(z)^kf(z)\mathrm{d}z=1-F(t)^{k+1}.
$$
(Fact 1 is an integration by parts. Fact 2 is trivial.)
Now to the proof.
Replace the brackets on the LHS and on the RHS by integrals over $t$ in $(0,z)$ thanks to Fact 1. This yields expressions of the LHS and of the RHS as double integrals. Interchange the order of integration. The inner integrals over $z$ in $(t,+\infty)$ can both be evaluated thanks to Fact 2. One gets that the difference between the RHS and the LHS is
$$
A_n=n^{-1}\int_0^{+\infty}tf(t)F(t)^{n-3}P_n(F(t))\mathrm{d}t,
$$
where
$$
P_n(x)=(n-1)x(1-x^n)-(n-2)(1-x^n)+(n-2)(1-x^{n+1})/(n+1).
$$
Hence
$$
A_n=n^{-1}\int_0^{+\infty}Q_n(F(t))\mathrm{d}t,\qquad\mbox{with}\quad
Q_n(x)=\int_x^1u^{n-3}P_n(u)\mathrm{d}u.
$$
The proof that $A_n\ge0$ for every probability distribution is complete if $Q_n\ge0$ over $(0,1)$. Some easy calculus of variation will do the job.
Namely, over $(0,1)$, the second derivative $P''_n$ is positive then negative, hence the first derivative  $P'_n$ is increasing then decreasing. Since $P'_n(0)>0$ and $P'_n(1)<0$ (expressions omitted), $P'_n$ is positive then negative, hence $P_n$ is increasing then decreasing. Since $P_n(0)<0$ and $P_n(1)=0$, $P_n$ is negative then positive.
This shows that $Q_n$ is increasing then decreasing over $(0,1)$. Since $Q_n(1)=0$, it remains to prove that $Q_n(0)\ge0$. This last fact follows from the explicit computation of the integral over $(0,1)$ defining $Q_n(0)$, which yields, unless I am mistaken, that $Q_n(0)=(n-2)/(2(n-1)(2n-1))$. Since this quantity is nonnegative for every $n\ge2$, we are done.


text:
Q: Installing JRE from .tar.gz I am following the following instructions https://docs.oracle.com/javase/8/docs/technotes/guides/install/linux_jre.html#CFHIEGAA to install JRE 9. I downloaded the .tar.gz file moved it to the /usr/ directory and extracted it. However running java -version gives error "Command java not found"

A: The java binary isn't in your PATH. The quickest way to fix this would be to check what directory the .tar.gz file extracted to - there will be a java binary inside there. Create a link to that binary in /usr/bin (which is almost certainly in your PATH
ln -s /usr/java/jre-whatever/bin/java /usr/bin/java
You should then be able to run the command as you described.


text:
Q: How to choose the navbar logo in orbeon 4.5? In Orbeon Forms 3.9, there was an option to choose the logo just above the "Application Title". But I couldn't find that option in Orbeon 4.5.
Is there any way to choose the logo in Orbeon 4.5?

A: The option disappeared in Orbeon Forms 4.0, as we thought this would be better done as a global or a per-app setting. However that setting hasn't been implemented yet.
So at this point there is no direct way to pick a logo via Form Builder.
This custom CSS can be used to hide the Orbeon logo:
.navbar .container img {
    display: none;
}

You should be able to add your own logo with CSS along the lines of:
.navbar .container {
    background-image: url(my-logo.png)
}

Some other CSS tweaks might be needed, but it's doable.
UPDATE:
I forgot about this property, which you can override:
<property
  as="xs:anyURI"
  name="oxf.fr.default-logo.uri.*.*"
  value="/apps/fr/style/orbeon-navbar-logo.png"/>


text:
Q: Any suggestion for a reliable video format for industrial applications? I am currently using videos encoded in MPEG4 (h264). This makes the content of the frames rely on the content of other frames.
In my case this is undesirable as I often need to quickly split video files without re-compressing or altering the content and seek many times trough the video.
The video format that I need needs to be reliable and the frames need to be independent from each other.
Any idea on which video format might be best for these requirements?
Maybe there is a sub-type of MPEG4 encoding that allows to reach this result?

A: H.264 with the intra flag will encode to a video stream where each frame can be independently decoded.
ffmpeg -i in.mp4 -c:v libx264 -g 1 -c:a copy out.mp4

-g 1 sets GOP size to 1 frame, hence each frame is intra-coded. Of course, the video bitrate will increase - in some cases, quite a bit - relative to omitting this flag.


text:
Q: Harvest a collection from a external repository i'm trying harvest a collection from a external repository by OAI service, but when i try ping the url by terminal  or test the configurations harvest in module xmlui:
By xmlui, testing the configurations of collection return this:

* OAI server could not be reached.

By terminal:

C:\dspace5\bin>dspace harvest -g -a https://repositorioaberto.uab.pt/oai/request -i all

Using DSpace installation in: C:\dspace5

Testing basic PMH access:  8967 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - requestURL=https://repositorioaberto.uab.pt/oai/request?verb=Identify
23544 [net.sf.ehcache.CacheManager@6d167f58] DEBUG net.sf.ehcache.util.UpdateChecker  - Update check failed: java.net.ConnectException: Connection timed out: connect
invalidAddress: OAI server could not be reached.

Testing ORE support:  31598 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - requestURL=https://repositorioaberto.uab.pt/oai/request?verb=Identify
invalidAddress: OAI server could not be reached.
52641 [main] DEBUG net.sf.ehcache.CacheManager  - CacheManager already shutdown

By terminal returning status: 200 OK!:

Other test with other url oai service:

Using DSpace installation in: C:\dspace5
Testing basic PMH access:  38726 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - requestURL=https://demo.dspace.org/oai/request?verb=Identify
40198 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - responseCode=200
40205 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - contentEncoding=null
41265 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - requestURL=https://demo.dspace.org/oai/request?verb=ListMetadataFormats
41278 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - responseCode=200
41284 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - contentEncoding=null
41292 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - requestURL=https://demo.dspace.org/oai/request?verb=ListMetadataFormats
41350 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - responseCode=200
41398 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - contentEncoding=null
OK

Testing ORE support:  41541 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - requestURL=https://demo.dspace.org/oai/request?verb=Identify
41555 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - responseCode=200
41555 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - contentEncoding=null
41557 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - requestURL=https://demo.dspace.org/oai/request?verb=ListMetadataFormats
41566 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - responseCode=200
41570 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - contentEncoding=null
41573 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - requestURL=https://demo.dspace.org/oai/request?verb=ListMetadataFormats
41591 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - responseCode=200
41591 [main] DEBUG ORG.oclc.oai.harvester2.verb.HarvesterVerb  - contentEncoding=null
OK

41604 [main] DEBUG net.sf.ehcache.CacheManager  - CacheManager already shutdown

This is related with proxy of my dspace application or the application oai service collected?
My proxy configurations are sett correctly:
http.proxy.host= http://myproxy.org
http.proxy.port = 8080
I tested too, in others environments dspace without proxy and including in the demo.dspace.org/xmlui. it returns the same error:

*

*OAI server could not be reached.

I honestly am not able to see the problem or how to solve this

A: If I open up your OAI landing page at https://repositorioaberto.uab.pt/oai/request?verb=Identify
I see that the links for the OAI verbs do not conform to the original URL
http://repositorioaberto.uab.pt/oaiextended/request?verb=ListSets
Can you explain why "oaiextended" is part of the path?  Could this be the source of the problem?


text:
Q: How do we execute .SQL file in snowflake? How do we execute multiple .SQL files in snowflake? Lets say I have multiple .SQL files and I want to execute in snow SQL how do we do it?
What if have have single .SQL file and I want to execute? how to do that?

A: If you have SnowSQL installed, and you have multiple script files to run, you can create a master script file that has !load command for individual scripts and save that as a file
!load path/file1.sql
!load path/file2.sql
!load path/file3.sql

You can then run the master script file like below
!load path/master_file.sql


text:
Q: Operator= overloading So we are assigned a project in the class that I am taking right now, and I am stuck trying to figure out how to properly deep copy an array of Cards. Below I will post the entire .cpp and .h for the class I am working on, I am fairly certain that it's in the operator= function, but all I am really looking for is just some tips on how to fix it. vector is not allowed to be use, nor are strings. This is a beginner class and so we do not know too much. The main error I'm receiving is a _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) Please and thanks in advance.
//.h
#pragma once
#include "stdafx.h"
#include "Card.h"

class Player
{

private:

// Needed for unit tests
// DO NOT REMOVE OR RENAME
char* m_name;           // Can change size of array if needed

Card* m_hand;       // Can change size of array if needed

int m_numCards;     // The number of cards the player is currently holding
int m_maxCards;     // The number of cards the player can store (the number of elements in Hand)
int m_score;

public:

Player(const char* _name = "Player", int _maxCards = 5);

Player(const Player& _cpy);

virtual ~Player();

Player& operator=(const Player& _assign);

const char* GetName() const { return m_name; }

bool GetCard(int, Card&) const;

int GetNumCards() const { return m_numCards; }

int GetMaxCards() const { return m_maxCards; }

int GetScore() const { return m_score; }

/*MUTATORS*/

void SetName(const char* _name);

void AddToScore(int addScore);

bool AddCard(Card);

bool Discard(int index, Card&);

void Clear();

virtual void Show() const;

// Needed for unit tests
// DO NOT REMOVE
friend class CTestManager;

};

//.cpp
#include "Player.h"

Player::Player(const char* _name, int _maxCards){
m_name = NULL;
SetName(_name);
m_hand = NULL;

m_hand = new Card[_maxCards];

m_maxCards = _maxCards;
m_numCards = 0;
m_score = 0;
}

Player::Player(const Player& _cpy)
{
    m_name = NULL;
    SetName(_cpy.m_name);
    m_hand = NULL;
    m_hand = new Card(*_cpy.m_hand);

m_maxCards = _cpy.m_maxCards;
m_numCards = _cpy.m_numCards;
m_score = _cpy.m_score;
}

Player::~Player(){
delete[] m_name;
delete[] m_hand;
}

Player& Player::operator=(const Player& _assign)
{
if (this != &_assign)
{

    delete[] m_name;
    SetName(_assign.m_name);

    delete[] m_hand;
            //enter implemented deep copy here//

    m_maxCards = _assign.m_maxCards;
    m_numCards = _assign.m_numCards;

    m_score = _assign.m_score;
}
return *this;
}

bool Player::GetCard(int index, Card& _Card) const{
if (index < m_numCards && index >= 0){
    _Card = m_hand[index];
    return true;
}
return false;
}

/*MUTATORS*/

void Player::SetName(const char* _name){
delete[] m_name;
int len = strlen(_name) + 1;
m_name = new char[len];
strcpy_s(m_name, len, _name);
}

void Player::AddToScore(int addScore){
m_score += addScore;

}

bool Player::AddCard(Card _addCard){
if (m_numCards != m_maxCards){
    m_hand[m_numCards++] = _addCard;
    return true;
}
return false;
}

bool Player::Discard(int discardIndex, Card& _discardCard){
if (discardIndex >= m_numCards){
    return false;
}
else{
    _discardCard = m_hand[discardIndex];
    for (int i = discardIndex; i < m_maxCards - 1; i++){
        m_hand[i] = m_hand[i + 1];
    }
    m_numCards--;
    return true;
}
}

void Player::Clear(){
m_numCards = 0;

}

void Player::Show() const{

}

If there is any tips that anyone can give me I would be greatly appreciative :D Thanks again.

A: Use std::vector and be done with it. It supports assignment. The question (as I'm writing this) does not indicate a prohibition against using std::vector.

A: sounds more like a codereview kind of question but anyway here are some "tips":
your copy constructor Player(const Player& _cpy) does not copy the array properly, you need to loop through the _cpy.m_hand and copy each element, what you are doing is basically just copying the first card and also making m_hand point to a single heap element and not an array. this will cause an error when you later delete it since you are assuming m_hand being an array in the dtor (delete [] m_hand).
Player& Player::operator=(const Player& _assign) here you need to first allocate an array to hold the copy, then do a for loop and copy each card to the new array.
e.g.
m_hand = new Card[_assign.m_maxCards];
for (int i = 0; i < _assign.m_numCards; ++i)
{
  m_hand[i] = _assign.m_hand[i];
}
m_maxCards = _assign.m_maxCards;
...

Important: The way you copy cards depends on how you implement the Card class but you haven't provided a declaration of Card so I just assume it is a POD type. If it contains more complicated structures then you would need some method to clone its contents.
as a side note: when you declare a class, put the public parts first in the class, the implementation details are normally better kept out of view and are often not (should not be) particularly interesting for the user of the class.
if you must use these old C-style strings then it could be a good idea to create a small helper function which simulates strdup()
char* newdup( const char* str )
{
  char* ret = NULL;
  if ( str != NULL )
  {
    ret = new char[strlen( str ) + 1];
    strcpy_s( ret, len, str );
  }
  return ret;
}

A: You have to copy each member in the Player class , So implement a method in Card class by overloading = operator which does the deep copy in the card class. Then you can just use = operator in the Player's method just by adding
m_hand = _assign.m_hand;


text:
Q: Custom Swift UIGestureRecognizer does not call assigned action I have a UIViewController with a custom UIGestureRecognizer added to one of its views. The problem is that i get all the touch printlines from my DialGestureRecognizer but the handleDial action is never called. (iOS 8 / Xcode 6.1.1) What did i do wrong? Any help appreciated.
@IBOutlet var dialView:UIView?

override func viewDidLoad() {
    super.viewDidLoad()

    if let _dialView = dialView? {
        let recognizer = DialGestureRecognizer(target:self, action:"handleDial:")
        _dialView.addGestureRecognizer(recognizer)
    }

    func handleDial(recognizer:DialGestureRecognizer) {
        println("handleDial")
    }
}

The custom (stripped down) UIGestureRecognizer looks like this
class DialGestureRecognizer:UIGestureRecognizer {
    func touchesBegan(touches:NSSet!, withEvent event:UIEvent!)  {
        println("touchesBegan")
    }

    func touchesMoved(touches:NSSet!, withEvent event:UIEvent!) {
        println("touchesMoved")
    }

    func touchesEnded(touches:NSSet!, withEvent event:UIEvent!) {
        println("touchesEnded")
    }
}

A: You have to trigger the selector from inside the gesture recogniser.
To trigger the selector, you have to modify the state property of the UIGestureRecognizer. This property is readonly.
For modifying that you have to add a BridgingHeader as follows.
You need to have or create a -Bridging-Header.h file to import Objective C headers such as the one you want.
If you don't already have a bridge header file in your app, the easiest way to get one is to add an objc class to your project, and xcode will ask if you want one, then creates the file and ties it into the settings for you. You can then delete the objc class.
Add the next line to the Bridging Header file.
#import <UIKit/UIGestureRecognizerSubclass.h>

Then you can modify the self.state property to get the events fired.
override func touchesBegan(touches:NSSet!, withEvent event:UIEvent!)  {
    println("touchesBegan")
    self.state = UIGestureRecognizerState.Began
}

For more information read
http://www.raywenderlich.com/76020/using-uigesturerecognizer-with-swift-tutorial


text:
Q: How to Filter a Map to retain only specific keys in Java I have been using map.keySet().retainAll(<set of keys>) for this purpose , but just came across a scenario where this is not working as expected.
See the sample code below. I am expecting object1 map to be returned with keys (key1 and key2) after filter, but this gives me blank output. Note: if I uncomment the line that adds key3 to object1 , it is working fine (returning map with key1 and key2). Why? How to fix this issue? Is there any alternative approach?
public class Demo {

    public static void main(String args[]){

        Map<String,Object> object1 = new HashMap<>();
        object1.put("key1","One");
        object1.put("key2","Two");
        //object1.put("key3","Three");

        List<Map<String,Object>> objects = new ArrayList<>();
        objects.add(object1);

        Set<String> attributes = new HashSet<>();
           attributes.add("key1");
           attributes.add("key2");

        System.out.println("Objects before filter:"+objects);

        System.out.println("Objects after filter:"+objects.stream().filter(map -> map.keySet().retainAll(attributes)).collect(Collectors.toList()));

    }

}

A: This is because the filter map.keySet().retainAll(attributes)  returns false as the set was not changed:
Set#retainAll()'s javadoc:

@return true if this set changed as a result of the call

Are you looking for Set#containsAll() instead?

Returns true if this set contains all of the elements of the specified collection.

A: Since you don't actually care if the map was retained or not, try calling it like this:
System.out.println("Objects after
filter:"+objects.stream().filter(map ->
{
  map.keySet().retainAll(attributes); // Modify your map
  return !map.keySet().isEmpty(); // Include sets with data
}
).collect(Collectors.toList()));