Set usergroup and persmissions ftp folder back to default

Question: I tried to create a new ftp user via the commandline. But I did something wrong and now I can access the server via FTP but I can't see any files. It doesn't make any sense wich user I'm using.
<code>ls -la
drwxr-xr-x 13 root ftp 4096 2012-03-30 09:47 .
drwxr-xr-x  7 web6 ftp 4096 2012-03-26 09:28 ..
drwxr-xr-x  4 web6 ftp 4096 2012-03-26 13:31 actions
drwxr-xr-x  2 web6 ftp 4096 2012-03-26 11:46 bin
-rwxr-xr-x  1 web6 ftp 1520 2012-03-24 23:32 changelog.txt
drwxr-xr-x  2 web6 ftp 4096 2012-03-26 13:30 css
drwxr-xr-x  8 web6 ftp 4096 2012-03-24 22:43 external
-rwxr-xr-x  1 web6 ftp  333 2012-03-26 15:12 .htaccess
drwxr-xr-x  3 web6 ftp 4096 2012-02-27 15:07 images
-rwxr-xr-x  1 web6 ftp 1606 2012-03-26 21:25 index.php
drwxr-xr-x  2 web6 ftp 4096 2012-02-18 13:20 js
drwxr-xr-x  2 web6 ftp 4096 2012-02-03 00:34 layout
drwxr-xr-x  2 web6 ftp 4096 2012-03-29 23:35 library
drwxr-xr-x  2 web6 ftp 4096 2012-03-30 09:47 log
-rwxr-xr-x  1 web6 ftp  396 2012-03-24 15:04 menu.php
drwxr-xr-x  2 web6 ftp 4096 2012-03-30 12:01 python
drwxr-xr-x  2 web6 ftp 4096 2012-03-23 10:51 todo
</code>
I can't see any dirs and files because I changed the groupowner or I the rights of the groupowner of the ftp dir.
How can I set the ownership of the files back to default so I can access the files via FTP again?
Answer: The easiest solution it would be to review history and see what you changed .(history command)
If you haven't applied the rights recursively , then you can see the rights assigned to the files / and ownership and apply them again to the root folders of the FTP .
Alex H


How do I run multiple linear regression with a limited data set for each subject?

Question: I'm trying to use limited data across a range of variables to make predictions. There are ten variables and each subject has three of the ten variables defined. It's approximately random which three variables each subject has defined, but not completely.
If each subject had all ten variables defined I'd know easily how to run a least squares linear regression.
I have one subject who has all ten variables defined - using this data, I could try to fill in what the other seven variables would be for each subject, but it doesn't seem right. What's the best way to calculate the coefficients for a linear regression model in the case where all subjects only have three variables of the ten? Thanks!
Answer: With the variables that were observed or not being pretty much random you should be able to use standard missing data tools.  These include the EM algorithm and Multiple imputation.  There are existing tools that help with Multiple imputation and make a regression analysis fairly straight forward.
Another option is to do a Bayesian regression fit and specifying a prior on each of the missing values.


Desativar Case Sensitive do Filter no Angular

Question: Pessoal tenho um campo na pagina que serve para filtrar uma tabela, porém o filtro esta diferenciando letras maiúsculas de letras minusculas, e gostaria que não acontecesse isso, segue o código:

<input type="text" class="form-control" placeholder="Digite aqui o texto para filtrar" ng-model="filtro" style="height:50px; />

Vi em outro lugar para tentar colocar filter : filtro : false porém não funcionou, se alguém puder me ajudar eu agradeço
Comment: adicione seu filtro na pergunta
Comment: Adicionei o input com o filtro
Answer: É só usar :false depois de filtro, a própria documentação diz isso. Na verdade, só precisa pôr false se quiser explicitar isto, porque ele já o padrão.
De qualquer forma, você pode criar uma função para fazer o trabalho do filtro e garantir que ela faça as comparações case-insensitive (veja o segundo exemplo).

angular.module('app', []).controller('mainController', function($scope) {
  $scope.listaCadParticipante = [{ nome: 'Jeferson' }, { nome: 'Joaquim' }];

  $scope.filtroCs = function(item, index, array) {
    if($scope.filtro2 == undefined)
      return true;

    return item.nome.toLowerCase().indexOf($scope.filtro2.toLowerCase()) !== -1;
  };
});
table, th, td {
   border: 1px solid gray;
   margin: 10px;
}

input {
  margin: 10px;
}

  <input ng-model="filtro" type="text" />

         {{ participante.nome }}

Exemplo usando uma função:

  <input ng-model="filtro2" type="text" />

         {{ participante.nome }}


Flatten Ragged LinkedHashMap

Question: I have a LinkedHashMap where CommonEnum represents a type of byte[] that I want to keep track of.
LinkedHashMap<CommonEnum, byte[]> map = new LinkedHashMap<CommonEnum, byte[]>();

What is the most efficient way in Java to flatten this into a continuous
byte[]
with the same ordering (thats why the HashMap is Linked).
Comment: Why do you have a `Byte[]` instead of `byte[]`?
Comment: Ah.. I didnt think you could use byte[] with generics..My mistake
Comment: You can't use primitive types as type arguments, but array types are reference types in Java (even arrays of primitives).
Answer: If you can use a LinkedHashMap<CommonEnum, byte[]>, it gets easier, and I have no idea why you would use Byte[], so I assume this.
I'm not sure about most efficient, but these two would be what I think about:

create a byte[] large enough (either estimate it or calculate by adding the sizes)
loop through the values, using System.arraycopy for each.
If the array was to long, use Arrays.copyOf to shorten it.

Create a ByteArrayOutputStream
loop through the values, write each byte[] to the stream.
get the array.

By the way, if your CommonEnum values are always of the same order (and you can use this order as the order in the enum definition), you can use an EnumMap instead.
Comment: Definitely the way to do it (+1). I guess not everybody realizes that a byte[] is an Object, which might be an explanation ...
Answer: I'm a fan of ByteArrayOutputStream -- you could iterate through the entries in the map, and for each Byte[] value, iterate through the members, write()ing them to the stream. Then call toByteArray() at the end to get the flat version.
Answer: Depending on the number of elements and the size, the fastest way might be to first calculate the total length, create a new byte array, and copy the values using System.arraycopy. However, using ByteArrayOutputStream is also good.

Flatten Ragged LinkedHashMap


Count the amount of closed contours in an image - MATLAB

Question: I am struggling to find a good contour detection function that would count the number of contour in bw images that I have processed using some previous tools. As you can see, my profile picture is an example of such images,
,
In this image, ideally, I wish to have a function which counts four closed contour.
I don't mind if it also detects the really tiny contours in between, or the entire shape itself as extra contours. As long as it counts the medium sized ones, I can fix the rest by applying area threshold. My problem is that any function I have tried detects only one contour - the entire shape, as it cannot separate it to the su-conours which are connected to one another.
Any suggestions?
Comment: possible duplicate of [Counting number of Blobs via MatLab](http://stackoverflow.com/questions/19586464/counting-number-of-blobs-via-matlab)
Comment: so @GUY TALMOR did you look at my answer?
Answer: Here is my shot at this, although your question might get closed because it's off-topic, too broad or a possible duplicate. Anyhow I propose another way to count the number of contours. You could also do it using bwboundaries as was demonstrated in the link provided by @knedlsepp in the possible duplicate. Just for the sake of it here is another way.
The idea is to apply a morphological closure of your image and actually count the number of enclosed surfaces instead instead of contours. That might end up being the same thing but I think it's easier to visualize surfaces.
Since the shapes in your image look like circle (kind of...) the structuring element used to close the image is a disk. The size (here 5) is up to you but for the image you provided its fine. After that, use regionprops to locate image regions (here the blobs) and count them, which comes back to counting contours I guess. You can provide the Area parameter to filter out shapes based on their area. Here I ask the function to provide centroids to plot them.
Whole code:
clear
clc
close all

%// Read, threshold and clean up the image
Im = im2bw(imread('ImContour.png'));
Im = imclearborder(Im);

%// Apply disk structuring element to morphologically close the image.
%// Play around with the size to alter the output.
se = strel('disk',5);

Im_closed = imclose(Im,se);

%// Find centroids of circle-ish shapes. Youcan also get the area to filter
%// out those you don't want.
S = regionprops(~Im_closed,'Centroid','Area');

%// remove the outer border of the image (1st output of regioprops).
S(1) = [];

%// Make array with centroids and show them.
Centro = vertcat(S.Centroid);

imshow(Im)
hold on
scatter(Centro(:,1),Centro(:,2),40,'filled')

And the output:

So as you see the algorithm detected 5 regions, but try playing a bit with the parameters and you will see which ones to change to get the desired output of 4.
Have fun!
Comment: Very nice my friend. +1.
Comment: thanks @rayryeng I wasn't sure it was a valid approach but that's how I would do it :)


How is a self-signed certificate different from a certificate signing request?

Question: From the wiki page for a Certificate signing request:

In Public Key Infrastructure (PKI) systems, a Certificate Signing Request (also CSR or certification request) is a message sent from an applicant to a Certificate Authority in order to apply for a digital identity certificate.

From the wiki page for a Self-signed certificate:

In cryptography and computer security, a self-signed certificate is an identity certificate that is signed by the same entity whose identity it certifies. This term has nothing to do with the identity of the person or organization that actually performed the signing procedure. In technical terms a self-signed certificate is one signed with its own private key.

So it sounds like one would submit a CSR to a CA to get a digital identity certificate. This digital identity certificate could potentially be of the same format as a self-signed certificate (for example the Public-Key Cryptography Standards 12 format).
The key difference is: the self-signed certificate is signed by the same party that owns the private key, while the digital identity certificate returned by the certificate authority upon receiving the certificate signing request is signed using the certificate authority's private key.
Therefore the self-signed certificate is guaranteed to work for encryption but not identification, while the digital identification certificate from the certificate authority is guaranteed to work for encryption and identification.
Is this right? Would love clarification via examples.
Answer:
the self-signed certificate is signed by the same party that owns the private key, while the digital identity certificate returned by the certificate authority upon receiving the certificate signing request is signed using the certificate authority's private key.

That is correct.

Therefore the self-signed certificate is guaranteed to work for encryption but not identification, while the digital identification certificate from the certificate authority is guaranteed to work for encryption and identification.

This gets kinda tricky.  The CA signed cert is only trusted for identification because the CA is include in the pre-populated certificate store built into browsers/OS.  If I didn't have a pre-populated certificate store neither of them would be trusted.
If I downloaded and verified certificate of that self-signed key and added it to my certificate store, then I could trust it for all purposes.
So from the point of view of the technology the only difference is that your self-signed cert wouldn't be built into my browser/OS.
Answer: well, as long as you "trust" the CA who signed a certificate, you can ensure that the situation is safe.
and you usually do this by installing the CA certificates (signers) in your environment, so that it auto-recognizes the certificates signed by this CA and consider them as "trusted".
(sorry but i cannot comment yet so i had to use the reply button)
as a concreet example, in my company, we do have our own CA, and we have CA certificates installed in every web browser (wether it's IE, firefox etc.), when the CA "signs" our SSL certificates (used in the intranet, applications etc.. listening in SSL/TLS), and we access these applications, they are automatically recognized as safe and you don't need to click on a specific warning banner saying that the certificates being used are not trusted (because they are either self-signed, or signed by an unknown CA, or a CA we do not trust)
Answer: the CA is what is used to sign a certificate
a CSR is a request you send to a CA so that they can sign you a certificate
usually without having the key.
for example you would go to a CA and ask a certificate they would ask you what info and they generate a key and a cert with a CSR the key is the same they just generate a new cert. with diffrent attributes sometimes like validity dates etc...


DB2 SQL - Inner Join get last row

Question: I am trying to get the last record from table @POA with the same PO # and Line # in table HPOL07. The records in @POA have a sequence number. So I am trying to get the record with the last sequence number. I am not sure how to do this?
EXEC SQL Declare RSCURSOR cursor for
SELECT HPOL07.*, @POA.*
FROM HPOL07
INNER JOIN @POA ON PORD = @POA.POAPON  AND PLINE = @POA.POALNO
WHERE PORD = :NBR AND PID <> 'PZ';

EXEC SQL  Open RSCURSOR;

EXEC SQL SET RESULT SETS Cursor RSCURSOR;

Answer: Won't swear this works on DB2 400, but I think it will.
    SELECT HPOL07.*, @POA.*
    FROM HPOL07
    INNER JOIN @POA ON PORD = @POA.POAPON  AND PLINE = @POA.POALNO
    WHERE PORD = :NBR AND PID <> 'PZ'
    ORDER BY @POA.<SEQUENCE NUMBER> DESC
FETCH FIRST 1 ROWS ONLY

Comment: The ORDER BY and FETCH you added, are they for the HPOL07 table or @POA table?
Comment: The fetch is for the result of the entire query.  For the order by is for whatever table.column is your sequence number.
Comment: Thank you Andrew, it worked. I am still confused with the ORDER BY and FETCH. Would you mind clarifying? The ORDER BY would work with both tables? What about the FETCH. How does it know what table to use?
Comment: Both the order by and fetch apply to the result set of the query.  Order by sorts by the specified column in the result set, which in turn allows the fetch first N rows to pick the desired rows.
Comment: Andrew, after further testing this only bring one result sets. I need to return multiple records from table HPOL07 with one result from the @POA table. Do I need to do a subquery?
Comment: That's hard to answer without more information and sample data, but you can use the fetch first 1 rows in a subquery, yes.
Answer: This query can be used to get all records from HPOL07 and match to one record in @POA
SELECT HPOL07.*, @POA.*
FROM HPOL07

CROSS JOIN LATERAL (
SELECT @POA.*
FROM @POA
WHERE PORD = @POA.POAPON  AND PLINE = @POA.POALNO
ORDER BY @POA.<SEQUENCE NUMBER> DESC
FETCH FIRST 1 ROWS ONLY
) @POA

WHERE PORD = :NBR AND PID <> 'PZ'

DB2 SQL - Inner Join get last row


Rating system for many-to-many competitions

Question: I have some abstract sport, where for each player his/her rating (some number) is known. Then players participate in competition, and the scoreboard is made, placing each player at some place. I need to develop or find any system that can recalculate rating for each player based on his/her previous rating and their place at competition. I know about Elo rating system, but I can't come up with an idea to make it suit my need (Elo rating is for competitions where players compete head-to-head). Is there anything to adapt for me or any ideas I can use?
Comment: How players compete against each other if not head-to-head? Is it like racing, where number of participants compete against each other and then finish in certain positions? I think the dynamics and the nature of the abstract sport you are mentioning is important for us to answer this question.
Comment: i think that question is too abstract. What is exactly wrong with Elo, and what do you want to achieve with your rating system? Also, take a look at F1 points system. It just gives number of points for positions at the end of each race
Answer: If you're interested in use (more than in development), you should give a try to rankade, our skill based ranking system.
Opposite to Elo and Glicko  (here's a comparison), rankade can manage any kind of match (one-on-one, faction vs. faction (two teams, which may be asymmetrical),
multiplayer, multi-faction, cooperative games, single player games, and so on), so you can insert one match with Alice 5, Bob 4, Chris 3 (an more, up to 30 factions) output.
Comment: Is the rankade algorithm, or anything similar, open source or with a similar licence? I need to use it for a separate program I am running as a project
Comment: The service is free but the algorithm is not in public domain, for the time being.


Proof of the set identity $(A \cap B) \cup C=A \cap(B \cup C) \iff C \subseteq A$

Question: I am sorry if this question might be too trivial, but this is the first time I have to do a set identity proof.
 Prove that : $$(A \cap B) \cup C=A \cap(B \cup C) \iff C \subseteq A$$
My attempt:
Lets assume the left side as true. In order to prove $C \subseteq A$ we need to prove that if $x \in C     \Rightarrow x\in A $
Let $ x\in C$. Therefore $x \in (A \cap B) \cup C$. From $(A \cap B) \cup C=A \cap(B \cup C)$ follows that $x\in A \cap(B \cup C) \Rightarrow x \in A.$
I am not sure if that's correct though, I would appreciate feedback.
For the other way we assume that $C \subseteq A.$
Now $(A \cap B) \cup C=(A \cup C) \cap (B \cup C) $ But $C \in A \Rightarrow (A \cup C)=A \Rightarrow (A \cap B) \cup C=A \cap(B \cup C)$.
Comment: That's perfect. No arguments on that one. What about the other way? Have you thought about it?
Comment: $(A\cap B)\cup C=(A\cup C)\cap(B\cup C)$.
Comment: Fei Li means that $(A\cap B)\cup C = (A\cup C)\cap (B\cup C)$ by distribution, and $A\cap (B\cup C)=(A\cap B)\cup(A\cap C)$ likewise.  We also know that $C\subseteq A$ means both $A=A\cup C$ and $C=A\cap C$.  So if $C\subseteq A$, then....
Comment: Much of elementary set theory is analogous to simple claims in logic. Notice that the 'or' and 'and' symbols look kind of like set unions and intersections, but pointy. Try reading these in words, and see if it helps.
Answer: $\wedge$ stands for "and".
Let $C \subseteq A$. We will first show that $(A \cap B) \cup C \subseteq A \cap (B \cup C)$, then  we will show that $A \cap (B \cup C) \subseteq (A \cap B) \cup C$. This will prove the equality.
Then note that if $x \in (A \cap B) \cup C$, then either $x \in A \wedge x \in B$, or $x \in C$.
If $x \in A \wedge x \in B$, then $x \in A \wedge x \in B \cup C$, so $x \in A \cap (B \cup C)$.
If $x \in C$, then $x \in A$, so $x \in A \wedge x \in C$, hence $x \in A \wedge x \in B \cup C$, so $x \in A \cap (B \cup C)$.
Either way,$(A \cap B) \cup C \subseteq A \cap (B \cup C)$.
The other way, note that if $x \in A \cap (B \cup C)$, then $(x \in C \text{ or } x \in B) \wedge x \in A$.
If $x \in C$, then $x \in (A \cap B) \cup C$.
If $x \in B$, then $x \in A \wedge x \in B$, hence $x \in (A \cap B) \cup C$.
Either way,$ A \cap (B \cup C) \subseteq (A \cap B) \cup C $.
Hence the proposition follows.
An easier way is to notice that $(A \cap B) \cup C =  (A \cup C) \cap (B \cup C)$, and see that $A \cup C = A$ if $C \subseteq A$.
Answer: Your argument in the forward direction looks good! Now for the backward direction try using some of the distributive identities of intersections and unions.
Comment: I added the backward in my post
Comment: Looks good. Good job.
Answer: Following is an alternative proof using Boolean algebra and the Indicator functions $a, b, c$ of sets $A, B, C$. The equality on the left hand translates to:
$$
\begin{align}
a \times b + c - a \times b \times c & = a \times (b + c - b \times c) \\
& = a \times b + a \times c - a \times b \times c
\end{align}
$$
or, after canceling out the identical terms:
$$
c = a \times c
$$
which is equivalent to $c \leq a$ which is in turn equivalent to $C \subseteq A$.
Answer: Algebraic Proof
Let $1_X$ be the indicator function of a set $X$; that is, $1_X(x)=1$ if $x\in X$, and $1_X(x)=0$ otherwise.  We have $$1_{(A\cap B)\cup C}=1_{A\cap B}+1_C-1_{A\cap B\cap C}=1_A\cdot 1_B+1_C-1_{A}\cdot 1_B\cdot 1_{ C}$$
and
$$1_{A\cap(B\cup C)}=1_A\cdot 1_{B\cup C}=1_A\cdot\left(1_B+1_C-1_{B\cap C}\right)=1_A\cdot \left(1_B+1_C-1_B\cdot 1_C\right)\,.$$
Hence, $(A\cap B)\cup C=A\cap(B\cup C)$ if and only if
$$1_A\cdot \left(1_B+1_C-1_B\cdot 1_C\right)=1_A\cdot 1_B+1_C-1_{A}\cdot 1_B\cdot 1_{ C}\,,$$
or $$1_{A\cap C}=1_A\cdot 1_C=1_C\,.$$
However, the last condition is equivalent to saying that $A\cap C=C$, which is the same as $A\supseteq C$.
P.S.  Just found out that dxiv offered the same solution.


Issue while package reset on xcode 13

Question: Showing Recent Errors Only
email@example.com:XXX/iOS_Freestyle_Crew_SDK.git: The remote repository could not be accessed. Make sure a valid repository exists at the specified location and that the correct credentials have been supplied.
Answer: Issue got resolved after providing permissions to the git account for that particular folder or group.

Issue while package reset on xcode 13


Issue with content access and multilingual system

Question: I have a multilingual website using English, Arabic and French. 2 days ago I noticed that anytime when I clicked on node/add/* for the English section, it returns an access denied page. And that is just for English (the other languages are fine and nothing wrong with them).
I use the Content Access module but even after I uninstalled it the issue remains the same.
I'm using Drupal version 7.32 and I18n 7.x-1.11.
Does anyone have an idea about this issue?
Comment: What's the language-decision priority in your environment?  Path-prefix based or else?  Are all the languages treated equally or not?  For example, in default, the path-prefix for the default language is null and so is different from the others.
Comment: What exactly do you mean with "clicked on node/add/* for the english section"? Can you edit your question to better explain which links or urls you use to add an English translation for some existing node?
Answer: I see 2 possible explanations for your issue, as further detailed below. Consider checking both of them to see if either one of them apply in this case.
Cookie problem
It is possibly an issue with a cookie. So try the same scenario usiing another browser. If with that browser the problem does not occur, then it is probably a cookie problem. In that case, just delete the session cookie in the browser where the problem occurs. Then check if the issue is resolved.
Site may be hacked
Since the version of this Drupal site is 7.32, it might simply be that your site was hacked. Refer to SA-CORE-2014-005 (posted a week before this question was asked ...) for some more details.
For way more details about that, and possible approaches to do more research on that, refer to Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?, which also suggests to use the Drupalgeddon module.


How to create custom nameserver that points to another name server?

Question: Example I use amazon Route 53
Amazon gives me DNS such as
ns-111.awsdns-36.net
ns-222.awsdns-13.org
ns-333.awsdns-53.co.uk
ns-444.awsdns-20.com

But I want to create my own custom nameserver alias, such as...
ns1.mydomain.com -point to-->  ns-111.awsdns-36.net
ns2.mydomain.com -point to-->  ns-222.awsdns-13.org
ns3.mydomain.com  -point to-->  ns-333.awsdns-53.co.uk
ns4.mydomain.com -point to -> ns-444.awsdns-20.com

I would then add these custom name server to my registry.
Is this possible?
Comment: Route 53 doesn't currently support vanity / branded name servers.
Answer: No, you really don't want to do this. Nameservers mentioned in NS records are not allowed to resolve to CNAMEs, so you will have to create glue records that point to amazon's IP addresses. Which they can change at any time, breaking your domain completely.
Answer: AWS now allows this.

In AWS, create a hosted zone.
Get the IPs of each name server (dig ns-1954.awsdns-52.co.uk - > 220.127.116.11)
Create/Register your 4 name servers with your registrar
Each domain should point to the aws ip (ns1.example.com -> 22.214.171.124)
Next change the name server that the domain itself is pointing to. Use your new ones (ns1.example.com and so on)
In AWS, edit the NS record set. Delete the 4 aws name servers and put yours (ns1.example.com and so on)


Symfony3/Doctrine2 : subquery with InnerJoin using QueryBuilder

Question: In a catalog, I have products and articles. Articles are variants of products.
In a catalog, products are sorted in categories and a product can be one or many times in a catalog.
I'd like to get articles of a catalog, but my articles aren't assigned directly to the catalog, only products are.
I'd like to construct the following SQL using Doctrine's query builder:
SELECT a.code, a.productCode, a.name
FROM Article a
INNER JOIN (
    SELECT p.code
    FROM Product p
    WHERE p.catalogCode = 'MYCODE'
    GROUP BY p.code
    ORDER BY p.code ASC
) AS results ON results.productCode = a.productCode

This query works in MySQL. I tried to do it in the Repository of my entity, but I have an error :
public function findArticlesByCatalog($catatlogCode)
{
   return $this->getEntityManager()
        ->createQuery(
            'SELECT a.code, a.productCode, a.name
                FROM AppBundle:Article a
                INNER JOIN (
                    SELECT p.code
                    FROM AppBundle:CatalogProduct p
                    WHERE p.catalogCode = :code
                    GROUP BY p.code
                    ORDER BY p.code ASC
                ) AS results ON results.productCode = a.productCode'
        )
        ->setParameter('code', $catatlogCode)
        ->getResult();
}

Error (just after INNER JOIN) :
[Semantical Error] line 0, col 81 near '(
SELECT': Error: Class '(' is not defined.

So, I'd like to construct it using Doctrine's query builder in my Controller.
I started something but I don't know to finish it...
$repository = $em->getRepository('AppBundle:Article');

$qb = $repository->createQueryBuilder('a');
$qb->select(array('a.code', 'a.productCode', 'a.name'))
    ->innerJoin(
        'AppBundle:CatalogProduct', 'p',
        'WITH',
        $qb->select('p.code')
           ->where(
              $qb->expr()->eq('p.catalogCode', ':code')
           )
           ->setParameter('code', $catCode)
           ->groupBy('p.code')
           ->orderBy('p.code', 'ASC')
    )
// ...

How to specify the rest of the query ?
AS results ON results.productCode = a.productCode'

Thanks for your help !
Comment: oldie, but goldie: http://stackoverflow.com/questions/6637506/doing-a-where-in-subquery-in-doctrine-2
Comment: @LBA Thanks but I don't understand very well compared to my query. Should I create a second query builder with CatalogProduct repository and get its DQL ? I've updated my post. I have trouble with `AS` and `ON` part of my query... Can you write me something please ?
Answer: I found the right way to do this.
I rewrote my SQL to do the same that my first one in order to do it easily with query builder.
So, my first SQL :
SELECT a.code, a.productCode, a.name
FROM Article a
INNER JOIN (
    SELECT p.code
    FROM Product p
    WHERE p.catalogCode = 'MYCODE'
    GROUP BY p.code
    ORDER BY p.code ASC
) AS cat_art ON cat_art.productCode = a.productCode

...has the same results that this one :
SELECT DISTINCT a.code, a.productCode, a.name
FROM Article a
JOIN Product p ON a.productCode = p.code
WHERE p.code IN (
    SELECT p.code
    FROM Product p
    WHERE p.catalogCode = 'MYCODE'
    GROUP BY p.code
    ORDER BY p.code ASC
)

With query builder, we should write 2 queries with 2 different query builders :
# It is very important here to name it "p2", not "p" because,
# in the main query, there is already "p"
$qb2 = $em->getRepository('AppBundle:CatalogProduct')->createQueryBuilder('p2');

$subQuery = $qb2->select('p2.code')
    ->where(
        $qb2->expr()->eq('p2.catalogCode', ':code')
    )
    ->groupBy('p2.code')
    ->orderBy('p2.code', 'ASC');

# main query
$qb = $em->getRepository('AppBundle:Article')->createQueryBuilder('a');

$query = $qb->select(array('DISTINCT a.code', 'a.productCode', 'a.name', 'p.code AS productCode'))
    ->join('AppBundle:CatalogProduct', 'p', 'WITH', 'a.productCode = p.code')
    ->where(
        $qb->expr()->in(
            'p.code',
            $subQuery->getDQL()
        )
    )
    // Parameter used in subquery must be set in main query.
    ->setParameter('code', $catCode)
    ->getQuery();


Two dimensional discrete uniform distribution

Question: I was wondering... Is there any formula for a two dimensional discrete uniform distribution? I've googled a little bit but I don't seem to find anything... I hope that somebody can help!
Answer: I assume you have an $m \times n$ grid of points and you want a PMF (probability mass function) which gives the probability of  drawing a certain point.  Since you have $m\cdot n$ points in total and you want the mass function to be uniform that means for each $i \in \{1,\dots,m \}$ and $j \in \{1,\dots,n \}$,
$$
P(X = x_{i,j}) = \frac{1}{m \cdot n}.
$$


Create a pager between fields

Question: I have a content type that has no limit on how many body fields it can have.
You can say that each body field represents a page in a book. You are supposed to switch page to see the next body field.
The client I am developing this site for needs to support visitors that have javascript disabled.
Is there a solution that makes it possible to add a pager for these fields using PHP?
Answer: If you can use Views, it'll be simple.
Views can provide each field's value as a row. Set it up to display fields, add your multivalue body field, filter by node id, and you can set up views pager to show one row per page.
Then, use Pathauto to create nice addresses for nodes of that type, like /multibody/[nid]. In views, use the same address and voila - node pages got overriden with your view. Use Global Redirect to redirect from /node/[nid] to /multibody/[nid] to make sure users will not end up reading whole node at once.
Comment: The big question is - *can* you override this content type's display with view? When there already is a tool to do what you need, developing it anew seems pretty useless to me.
Comment: I am unfortunately not using a view though. The node is  displayed as usual.
Answer: It is always better to check for contributed modules: The Smart Paging module seems like your solution.

Provides splitting up long Drupal content into sub pages by number of characters/words or by a placeholder HTML tag for node, user and taxonomy term entities.
Features

Smart Paging feature can be applied only to CCK fields (with text format) of node, user and taxonomy term entities. (Note: "Description" field of taxonomy term is not a CCK field.)
URL for sub pages is made more SEO friendly and works even for aliased URL path.
The user has more control over Smart Paging configuration. An option is provided at "Manage Display" page of an entity type whether to control Smart Paging display behavior during content editing or at "Manage Display" page itself.
Weight and visibility of Smart Paging can be controlled at "Manage Display" page of an entity type (bundle).
It integrates with the WYSIWYG module.
URL appended query argument ?nopaging=1 to display Smart Paging split pages as one page.
It provides additional page SEO.
It provides pagination with rel="next" and rel="prev".
It provides support for the Token module.
Comment: I believed it was only able to paginate one field, dividing it by `` and leaving other ones intact. Can it really paginate field by field?
Answer: I managed to solve my own question.
I add a GET-parameter to the template to check what 'page' you want to view and print that out.
$chapter = $_GET['chapter'];
print $content['body']['#items'][$chapter]['safe_value'];

This is not necessarily the 'Drupal' way (Add dozens of modules to get it to work) of doing this but it works and it's lightweight!

Create a pager between fields


git checkout slns between old and new csproj formats

Question: We recently ran the csproj migration tool on our solution with 156 projects:
dotnet tool install --global Project2015To2017.Migrate2019.Tool

This worked very well although we had to do a few modifications. However it has caused a problem where switching between branches before and after the change causes problems with the assemblyinfo.
The error is:
Duplicate 'global::System.Runtime.Versioning.TargetFrameworkAttribute' attribute [PROJECTNAME]

I believe this is because the new format is putting an assemblyinfo.cs and the old style csproj is somehow picking this up? You can see this here where it takes issue with a file:
PROJECTNAMEe\obj\x64\Debug\.NETFramework,Version=v4.7.2.AssemblyAttributes.cs

This can be fixed by running:
1.  Close Visual studio/Rider
2.  git clean -xfd
3.  Get-ChildItem . -Include obj, .vs -Recurse -force | Remove-Item -Recurse -Force
4.  Rebuild solution

Now this works but it's irritating that we constantly have to remind ourselves to do this.   Is there a way to modify our new csprojs to make it not do this?
Answer: In the new project style, the assembly info related properties are defined in the .csproj project file, whereas the old style has this in the AssemblyInfo.cs file.
At build time, these go into an auto generated .cs file;
here that .NETFramework,Version=v4.7.2.AssemblyAttributes.cs file.
Since that file is outside of the project, it doesn't get cleaned up when switching project styles (via branche switches).
This ends up in these CS0579 errors because of the conflicts with the info in the AssemblyInfo.cs files in your old project styled projects.

You can prevent the new style projects from auto generating such AssemblyAttributes.cs files, by adding the below setting in the .csproj file.
This then does mean that you have to restore these AssemblyInfo.cs files  in the already converted projects.
<PropertyGroup>
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
 </PropertyGroup>

If possible, you might run the migration again and apply the keep-assembly-info flag.

keep-assembly-info instructs the migrate logic to keep the assembly info file.

Alternatively (in case these old project style branches are rather temporary and for time being), you might also consider to clone the repository a second time to a separate path when working on these branches. Doing so they don't share the same output folders.


Gap after removing header of website in UIWebView

Question: Hello I'm opening a website which has header in UIWebView. I'm removing that header with below code. It's removing header but It doesn't move next item to top. It shows a blank padding in the place of headers view.
func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.scrollView.contentInset = UIEdgeInsets.zero
    webView.stringByEvaluatingJavaScript(from: "$(document).ready(function() { $('div.header').remove(); })")
}

Answer: I solve it by sending another javascript code to webpage;
webView.stringByEvaluatingJavaScript(from: "document.getElementsByClassName('wrapper')[0].style.paddingTop = '0px';")


Count ObservableCollection

Question: I have the below observevale collection which works perfectly:
        Persons = new ObservableCollection<Person>();
        foreach (string line in lines)
        {
            var column = line.Split(',');
            var name = column[0];
            int score = int.Parse(column[1].ToString());
            var person = Persons.FirstOrDefault(x => x.Name == name);

            if (person == null)
            {
                var newPerson = new Person(name, score);
                Persons.Add(newPerson);
            }

            else
            {
                person.Score += score;
            }

            datagrid.ItemsSource = Persons;
        }

What I am doing here is that I am first reading from a CSV file which has two columns, name and score. And what I want to do is go through the CSV file and get the sum of the score of the names that are similar.
so for example, my CSV is like the below table:
   Name, score
   Jo,1
   Hannah,2
   Sara,1
   Jo,2
   Sara,3
   Fred,1

When I run my code, I get the below result which is exactly what I want:
    Jo,3
    Hannah,2
    Sara,4
    Fred,1

The other thing I am trying to do is to count how many "Jo" we have, how many "Hannah" we have, how many "Sara" we have and how many "Fred" we have. And I know since the names are stored in the ObservableCollection, Persons, so I want to count how many elements are in the ObservableCollection given that the I only count the names that are the same. So to do this, I used the count property for the ObservableCollection. So I did this:
   Persons.Count;

But this keeps returning 1. I thought maybe I need to place it outside of the loop, but I am getting the same thing.
My question is, why is the count behaving this way? Am I using it wrong? Shouldn't Count count all the elements in the ObservableCollection?
Comment: ObservableCollection returns count of elements that it has.Where do you get element count from `Persons`? Can you put it to question's code?
Comment: You're showing what works, that's cool. Can we see the code you have issues with?
Answer: To get count of persons in your CSV file you can use Count():
var personName = "Jo";

var count = lines.Count(l => l.Split(',')[0] == personName);

Now you have count of "Jo" in your file;
Answer:
Why is the count behaving this way?

Count is suppose to return the number of items in the collection.

Am I using it wrong?

Based on your expectations, yes.

Shouldn't Count count all the elements in the ObservableCollection?

Yes it does. You are adding the grouped items to the collection so there would only be one of each name.
Using linq for demonstration purposes.
Assuming lines holds
Name, score
Jo,1
Hannah,2
Sara,1
Jo,2
Sara,3
Fred,1

The following returns anonymous object that hold the parsed data
var data = lines.Skip(1).Select(line => {
    var column = line.Split(',');
    var name = column[0];
    int score = int.Parse(column[1]);
    return new { name, score };
});

Grouping that data would provide the ability to aggregate the scores and how many of each name exists
var groupedData = data.GroupBy(p => p.name)
    .Select(g => new { name = g.Key, score = g.Sum(p => p.score), count = g.Count() });

//eg
//Jo,3,2
//Hannah,2,1
//Sara,4,2
//Fred,1,1

From there you should be able to create your desired objects including how many of each name exists.
 var persons = groupedData.Select(p => new Person(p.name, p.score) { Count = p.count });

persons can now be added to collection.
foreach (var person in persons) {
    Persons.Add(person);
}
datagrid.ItemsSource = Persons;

Count ObservableCollection


SQL query (in indicator) for talend DQ

Question: In Talend Open Studio for Data Quality, User defined indicators, Can we write an sql query involving 2 tables?
This is the scenario, I have 2 tables :

dbo.test, having column dept.
dbo.role, having column dept.

The following query is used to extract those records from dbo.test, whose dept values are not in  dbo.role.
Use [BigData]select dept from dbo.test
where dept not in (Select dept from dbo.role).

While executing, it gives the following error:
An exception stack trace is not available.

How do I resolve this and what is the correct approach to write this query ?
Comment: Downvotes should be followed by an explanation comment. I don't see any particular reason for the downvote
Answer: I think it will better for you to create a view by writing your query
(select dept from dbo.test where dept not in (Select dept from dbo.role))
in database
and then use that view in talend component as table :)

SQL query (in indicator) for talend DQ


nosql wishlist models - Struggle between reference and embedded document

Question: I got a question about modeling wishlists using mongodb and mongoose. The idea is I need a user beeing able to have many different wishlists which contain many wishes, each wish making a reference to a single article
I was thinking about it and because a wishlist only belong to a single user I thought using embedded document for that.
Same for the wish beeing embedded to a wishlist.
So I got something like that
<code>var UserSchema = new Schema({
...
   wishlists: [wishlistSchema]
...
})

var WishlistSchema = new Schema({
...
    wishes: [wishSchema]
...
})
</code>
but my question is what to do with the article ? should I use a reference or should I copy the article's data in an embedded document.
If I use embedded document I got an update problem. When the article's price change, to update every wish referencing this article become a struggle. But to access those wishes's article is a piece of cake.
If I use reference, The update is not a problem anymore but I got a probleme when I filter the wish depending on their article criteria ( when I filter the wishes depending on a price, category etc .. ).
I think the second way is probably the best but I don't know how if it's possible to build a query to filter the wish depending on the article's field. I tried a lot of things using population but nothing works very well when you need to populate depending on a nested object field. ( for exemple getting wishes where their article respond to certain conditions ).
Is this kind of query doable ?
Sry for the loooong question and for my bad English :/ but any advice would be great !
Answer: In my experience in dealing with NoSQL database (mongo, mainly), when designing a collection, do not think of the relations. Instead, think of how you would display, page, and retrieve the documents.
I would prefer embedding and updating multiple schema when there's a change, as opposed to doing a ref, for multiple reasons.

Get would be fast and easy and filter is not a problem (like you've said)
Retrieve operations usually happen a lot more often than updates and with proper indexing, you wouldn't really have to bother about performance.
It leverages on NoSQL's schema-less nature and you'll be less prone restructuring due to requirement changes (new sorting, new filters, etc)
Paging would be a lot less of a hassle, and UI would not be restricted with it's design with paging and limit.
Joining could become expensive. Redundant data might be a hassle to update but it's always better than not being able to display a data in a particular way because your schema is normalized and joining is difficult.

I'd say that the rule of thumb is that only split them when you do not need to display them together. It is not impossible to join them back if you do, but definitely more troublesome.
Comment: Thank you for your answer, I started using mongodb thinking it was the ultimate weapon for data but actually it's a trade off compare to an sql database. Anyway I slowly understand the spirit of nosql and the document way to handle data. I will do like you suggest and find a way to update in the most efficient way the embedded article. Thx


How to calculate this dependent probability (marbles without replacement)?

Question: I present the question in two steps:
First:
Let there be 100 bags. A person puts 5 marbles into 5 separate, randomly selected, bags. You are now to collect the contents of the bags, one by one. If you have collected 3 marbles, you stop. What is then the expected number of bags to open for a 50% chance of getting 3 marbles?
I suspect that this is some kind of binomial distribution, but I can't really phrase the exact solution.
Second:
Let there be 99 bags, and 500 marbles of 100 different colors, so that there exists 5 marbles of each color. For each of the 100 colors, a person takes all 5 marbles of that color and puts them into 5 separate, randomly selected, bags. I.e. each bag contains on average 5.05 marbles, and no bag contains more than 1 marble of the same color.
You are now to collect the contents of the bags, one by one. If you have collected 3 marbles of the same color, you stop. What is then the expected number of bags to open for a 50% chance of getting 3 marbles of the same color?
This second problem feels more like the birthday problem, but with multiple birthdays.
How do I calculate these expected values?
Comment: These problems are *hypergeometric* in nature.  They don't concern "expected values" in the usual statistical sense: you appear to ask for thresholds (minimal quantities) rather than expectations.
Comment: The goal is indeed to get 3 marbles by opening as few bags as possible. The more bags you open, the higher the probability of success. What would then be a better way of phrasing the question? In the real world scenario I am dealing with, there is a "cost" to opening the bags, but I have left that out for a cleaner question. I am interested in learning what methods can be used to calculate these kind of probabilities, and then compare the probabilities of success to the cost of opening the bags.
Answer: Let's generalize both questions so we don't have to solve them twice:

Let there be $n\ge 0$ bins indexed $1,2,\ldots, n.$  Suppose there are $C\gt 0$ different colors of marbles and $0\le k\le n$ marbles of each color.  Distribute each set of $k$ marbles into $k$ distinct bins randomly.  Collect all marbles from bin $1,$ then bin $2,$ and so on until you first obtain $m\ge 0$ (and $m\le k$) of at least one color.  Let $I$ be the index of the bin you last emptied.
What is the distribution of $I?$  Specifically, what is its 50th percentile?

This abstract rephrasing suggests some useful simplifications:

Each color $c$ determines a simple random sample (without replacement) of the bins.  Sorting the bin indexes, we may express this sample as the indexes $1 \le X^{(c)}_1 \lt X^{(c)}_2 \lt \cdots \lt X^{(c)}_k \le n.$

Therefore, $X^{(c)}_m$ (which is the $m^\text{th}$ order statistic of this sample) is the index at which we will have first collected $m$ marbles of color $c.$

Consequently, $I$ is the minimum over all colors of $X^{(c)}_m.$  The specifications of the problem imply these random variables are identically distributed and independent (iid).

That reduces the question to two simpler subproblems.  First (dropping the superscript $(c)$), find the distribution of $X_m.$  Second, find the distribution of the minimum of $C$ iid variables.
First subproblem
Let $1\le i\le n$ be a possible value of $X_m.$  Compute the distribution function $F_{m;\,n,k}$ of $X_m$ from its definition,
$$F_{m;\,n,k}(i) = \Pr(X_m \le i) = \Pr(\text{the sample includes at least } m \text{ bins in }\{1,2,\ldots, i\}).$$
Partitioning the event "at least $m$" into the disjoint events "exactly $m,$" "exactly $m+1,$" and so on enables us immediately to express this in terms of Binomial coefficients as

$$F_{m;\,n,k}(i) = \frac{1}{\binom{n}{k}}\sum_{j=m}^k \binom{i}{j}\binom{n-i}{k-j},$$

a hypergeometric tail probability.
Second subproblem
Let $F$ be any distribution on the integers $\{1,2,\ldots, n\}.$  The distribution of the minimum of $C$ iid samples $X_1, \ldots, X_C$ of $F$ is
$$\begin{aligned}
F^{(C)}(i) &= \Pr(\min(X_c)\le i) \\
&= 1 - \Pr(X_1\gt i)\Pr(X_2\gt i)\cdots\Pr(X_C\gt i) \\
&= 1 - (1 - F(i))^C.
\end{aligned}$$
The distribution of $I$
Applying this to the previous result shows

$$\Pr(I \le i) = F^{(C)}_{m;\,n,k}(i) = 1 - (1 - F_{m;\,n,k}(i))^C.$$

Solution to the original problem
The second question asks for the smallest $i$ for which $F^{(100)}_{3;\,99,5}(i) \ge 50\%.$
We may find that by a direct search: the value is $11,$ just barely: $F^{(100)}_{3;\,99,5}(10) = 0.4963\ldots$ while $F^{(100)}_{3;\,99,5}(11) = 0.6059\ldots$ .
Simulation
As a check, I simulated 10,000 independent repetitions of the process described in the second question (which, because it distributes balls into bins a million times, takes a few seconds).
Here are plots of the empirical distribution of $X_3$ (in black) compared to its probability function $f$ and distribution function $F$ (in red):

The answer to question #2, by the way, is found by inspecting the red points in the right hand plot (showing the distribution of $X^{(C)}_m$) to find the leftmost one at a height of $0.5$ or greater.  Because the height at $10$ is almost exactly $0.5,$ it's necessary to look at its value (slightly less than $0.5$) to discover the correct answer must be $11.$
The agreement between simulation and theory is excellent, as confirmed by a $\chi^2$ test (df = 21, p = 0.57) as well as this "rootogram" comparing the empirical frequencies by plotting the difference in their roots against their expected square root:

All residuals (but one, near the left) are small and display no trend.  Repeated simulations confirm there is no systematic problem.
Code
This R code implements the formula for $F$ (efficiently) and generates the simulation and figures.  You may use it to study the first question.
#
# Sample randomly from a process.
#
rcolor <- function(N, n, k, m, C=1) {
  replicate(N,
            min(replicate(C, {
              x <- sample.int(n, k)
              x[order(x)[m]]
            })))
}
#
# Compute the distribution function.
#
pcolor <- function(i, n, C, k, m) {
  i <- pmin(n-1, i+1)
  1 - exp(C * phyper(m-1, i, n-i, k, log.p=TRUE))
}
#
# Create the simulation.
#
n <- 99
m <- 3
k <- 5
C <- 100
set.seed(17)
x <- rcolor(1e4, n, k, m, C)
#
# Create figure 1.
#
y <- tabulate(x, n)
y <- y / sum(y)
p <- diff(P <- pcolor(0:n, n, C, k, m))
i <- seq(min(x), max(x)) # Limits plots to the observed values

par(mfrow=c(1,2))
plot(i, y[i], type="h", xlab=bquote({X^{(.(C))}}[.(m)]), ylab="Relative Frequency",
     main=bquote({f^{(.(C))}}[list(.(m), .(n), .(k))]))
points(i, p[i-1], col="Red", cex=1)

plot(ecdf(x), xlab=bquote({X^{(.(C))}}[.(m)]), ylab="Relative Frequency",
     main=bquote({F^{(.(C))}}[list(.(m), .(n), .(k))]))
points(i, P[i], col="Red", cex=1.25)
par(mfrow=c(1,1))
#
# Create figure 2.
#
x.tot <- tabulate(x, max(i))[i]
P[max(i)] <- 1
prob <- diff(P[c(min(i)-1, i)])  # The probability function `f`.
plot(sqrt(prob * length(x)), sqrt(x.tot) - sqrt(prob * length(x)), type="h",
     main="Rootogram",
     ylab="Residual", xlab=expression(sqrt(expected * phantom(0) * frequency)))
abline(h=0, col="Gray", lwd=1)
#
# Formally compare the simulation to the theory.
# (Ignore the warning: the few small-expectation bins don't harm the chi-squared
# approximation used to compute the p-value.)
#
chisq.test(x.tot, p=prob)


In caret what is the real difference between cv and repeatedcv?

Question: This is similar to question Caret re-sampling methods, although that really never answered this part of the question in an agreed upon way.
caret's train function offers cv and repeatedcv.  What is the difference in say doing:
MyTrainControl=trainControl(
    method = "cv",
    number=5,
    repeats=5
)

vs
MyTrainControl=trainControl(
   method = "repeatedcv",
   number=5,
   repeats=5
)

I understand cv breaks the set into k-folds (parameter number), and then starts over and runs it parameters repeats number of times.
The only thing I could think of is that maybe regular cv with repeats uses the same exact indexes for the folds each time? essentially running the cv on the same exact folds each time, vs perhaps repeatedcv selects new folds each times?
Can someone clarify?
Comment: I wonder there are some more methods as well.. need some basic level understanding of each, is there anywhere I could find that? thanks.
Comment: In create multi fold, code iterates over multiple times (given by repeats in train `Control()` syntax in R) for each of the k cross fold (given by number). In cross fold, while using CV, it is a one time process on each of the fold (set by using numbers in train `control()`).
Answer: According to the caret manual(see "reference manual"), the parameter repeats only applies when the method is set to repeatedcv, so no repetition is performed when the method is set to cv. So the difference between both methods is indeed that repeatedcv repeats and cv does not.

Aside: Repeating a crossvalidation with exactly the same splitting will yield exactly the same result for every repetition (assuming that the model is trained in a deterministic manner), which is not only inefficient, but also dangerous when it comes to comparing the validation results for different model algorithms in a statistical manner. So be aware of this if you ever have to program a validation yourself.
Comment: broken link, now it's https://cran.r-project.org/web/packages/caret/vignettes/caret.pdf

also, it's on page 4 now.  just search for 'repeatedcv'
Comment: the PDF link is no longer working.  The following URL seems to be the replacement.   https://cran.r-project.org/web/packages/caret/vignettes/caret.html
Answer: Admittedly, this is a VERY old post, but based on the code snippets provided by user3466398, the difference is that repeatedcv does exactly that: it repeatedly performs X-fold cross-validation on the training data, i.e. if you specify 5 repeats of 10-fold cross-validation, it will perform 10-fold cross-validation on the training data 5 times, using a different set of folds for each cross-validation.
The rationale for doing this, I presume, is to allow one to have a more accurate and robust accuracy of the cross-validation testing, i.e. one can report the average CV accuracy.
Comment: But is it nested cross-validation?
How can we use it to tune parameters?
Answer: The actual code behind these parameters can be found in the selectByFilter.R and createDataPartition.R (formerly createFolds.R) source files in the `caret/R/' folder of the package.
See these files for e.g. here and here (beware these permalinks may eventually point to older version of the code).  For convenience the relevant snippets (as of version 6.0-78 c. Nov 2017) are show below
In selectByFilter.R c. line 157
sbf <- function (x, ...) UseMethod("sbf")
...

"sbf.default" <-
  function(x, y,
           sbfControl = sbfControl(), ...)
  {
    ...

    if(is.null(sbfControl$index)) sbfControl$index <- switch(
      tolower(sbfControl$method),
      cv = createFolds(y, sbfControl$number, returnTrain = TRUE),
      repeatedcv = createMultiFolds(y, sbfControl$number, sbfControl$repeats),
      loocv = createFolds(y, length(y), returnTrain = TRUE),
      boot =, boot632 = createResample(y, sbfControl$number),
      test = createDataPartition(y, 1, sbfControl$p),
      lgocv = createDataPartition(y, sbfControl$number, sbfControl$p))
...

In createDataPartition.R c. line 227
createMultiFolds <- function(y, k = 10, times = 5) {
  if(class(y)[1] == "Surv") y <- y[,"time"]
  prettyNums <- paste("Rep", gsub(" ", "0", format(1:times)), sep = "")
  for(i in 1:times) {
    tmp <- createFolds(y, k = k, list = TRUE, returnTrain = TRUE)
    names(tmp) <- paste("Fold",
                        gsub(" ", "0", format(seq(along = tmp))),
                        ".",
                        prettyNums[i],
                        sep = "")
    out <- if(i == 1) tmp else c(out, tmp)

  }
  out
}

Comment: Could you please give more context in your answer? Links are good, but we try to avoid answers that won't stand on their own -- links can disappear.
Comment: take a look at their functions....https://github.com/tonglu/caret/blob/master/pkg/caret/R/createFolds.R#L63


Changing the view in the library DhtmlX

Question: I'd like to use the library DHTMLX : i'd like to use this view : Time Line View
so i change my view index.cshtml to this one :
<!DOCTYPE html>

    <title>DHXScheduler initialization sample</title>

       @Html.Raw(Model.Render())

i'd like to see as a result this view
but i have this view :
So what is the problem in the snippet? How can i change it to get a good result?
Answer: scheduler.Initialview="viewname";

Changing the view in the library DhtmlX


Find the smallest integer n such that the expression $40! \cdot 5^n$ has the maximum number of trailing zeros.

Question: Find the smallest integer n such that the expression $$40! \cdot 5^n$$ has the maximum number of
trailing zeros.
Comment: $\text {Ans}=\lfloor \frac {40}{2} +\frac {40}{4} +\frac {40}{8} +\frac {40}{16} +\frac {40}{32} \rfloor-\lfloor \frac {40}{5} +\frac {40}{25} \rfloor$
Comment: @MohammadZuhairKhan Shouldn't the floor function arguments be kept separate before addition? It doesn't make a difference in this case, but it might in general.
Answer: Hint: Legendre's theorem
can be used to find the largest powers of $2$ and of $5$ that divide $40!$.
Answer: Basically, you need to count the number of factors $2$ and $5$ in the factorial $40!$:
$$\begin{align}40!&=\color{red}1\cdot 2\cdot \color{red}3\cdot 4\cdot \color{red}5\cdots 38\cdot \color{red}{39}\cdot 40=\\
&=2^{20}\cdot (\color{blue}1\cdot 2\cdot \color{blue}3\cdots \color{blue}{19}\cdot 20)\cdot (\color{red}1\cdot \color{red}3\cdot \color{red}5\cdots \color{red}{37}\cdot \color{red}{39})=\\
&=2^{20}\cdot 2^{10}\cdot (1\cdot 2\cdot 3\cdots 9\cdot 10)\cdot (\color{blue}1\cdot \color{blue}3\cdots \color{blue}{19})\cdot (1\cdot 3\cdot 5\cdots 37\cdot 39)=\\
&=2^{20}\cdot 2^{10}\cdot 2^5\cdot  (1\cdot 2\cdot 3\cdot 4\cdot 5)\cdot (1\cdot 3\cdots 9)\cdot (1\cdot 3\cdots 19)\cdot (1\cdot 3\cdot 5\cdots 37\cdot 39)=\\
&=2^{20}\cdot 2^{10}\cdot 2^5\cdot 2^3\cdot (1\cdot 3\cdot 5)\cdot (1\cdots 9)\cdot (1\cdots 19)\cdot (1\cdots 39)=\\
&=2^{38}\cdot (5A)\cdot (5B)\cdot (5^2C)\cdot (5^5D)=\\
&=2^{38}\cdot 5^9E. \end{align}$$
Hence, the minimum $n$ in $40!\cdot 5^n$ is: $38=9+n\Rightarrow n=29$.


Theming the node edit forms  to open them within Lightbox

Question: I'm trying to display all the node edit forms neatly within Lightbox, without any of the excess content I don't want: no sidebars, footer, header, nothing but just the content. So I created a page-node-edit.tpl.php file.
I have two problems daunting me, but for now I'll only mention the first since its more important.
From any page, clicking on the "edit" link for the node doesn't activate the Lightbox like it should; instead, it clicks through the link as normal.
With jQuery in the header I added a "del" attribute for the Lightbox to the links, but the box still doesn't activate. I tested the Lightbox on a link I hardcoded into the page, and it activated just fine. For elements generated by Drupal, like the node edit link/button the problem seems to be timing.
I think the "del" attribute needs to be built with the page, with the link, rather than appended onto it. The catch is, the link lacks an id and class, so I don't see how the hook_alter_link() function can help me.
I'm willing to try anything. Perhaps someone has opened a node/edit form within Lightbox before.
Answer: If installing one or 2 additional module is an option then you can check Popups API (Ajax Dialogs). When I last checked, the module had functionality of opening forms in popups, which you can theme. I also feel that, in the way Drupal form API works, there is more to done then just adding classes and JavaScript to make Drupal forms work in Lightbox.
Answer: Seems like you just need to disable the default action for that link, i.e. force the link to return FALSE.
$("a").click(function() {
  $(this).lightbox;
  return false;
});

Obviously, you'll need to change the target from "a" to the specific edit link.
Comment: Thanks so much for trying to help me, MikeNGarret. I truly appreciate it.
Unfortunately, when I implemented the your solution, the lightbox refused to activate. I think it requires that click-thru behavior to work. I've been investigating to find a way to get around this, but nothing yet. I'm not giving up, so please keep the continue to pass along any suggestions you may have if you have any free time to spare. Thank you.
Comment: I did some research and I think I steered you the wrong direction. Lightbox isn't really meant to support this type of interaction. I'd use shadowbox, thickbox, or colorbox instead. Or you can do what @Dipen suggests below.
Answer: If you have Theme developer enabled, Lightbox will not work.
Theme developer should not be kept enabled, but enabled when necessary to get the necessary information; once you don't need it, you should disable it.
Some versions of the Devel module, had a link to enable or disable that module; I didn't check the latest version of Devel, and the link could not be present anymore.


ListBox Selected Item Background

Question: I'm trying to change the background of the selected item in a WPF ListBox.
I have attempted to implement a style for it, but for some reason it's not being applied. I still get a blue background. Can anyone see why?
<UserControl x:Class="Thumbnails"
         xmlns:local="clr-namespace:ContentPresenter"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="350" d:DesignWidth="800">
<UserControl.Resources>
    <local:ThumbImageHeightConverter x:Key="HeightConv" />
    <local:ThumbImageWidthConverter x:Key="WidthConv" />
    <local:InnerGridHeightConverter x:Key="InnerGridHeightConv" />
    <local:ReflectWidthConverter x:Key="ReflectWidthConv" />
    <local:ReflectCenterYConv x:Key="ReflectCenterYConv" />

    </Style>

</UserControl.Resources>

    <UserControl.DataContext>
        <ObjectDataProvider ObjectType="{x:Type local:ThumbImageLoader}" MethodName="LoadImagesv2" IsAsynchronous="True"  />
</UserControl.DataContext>

<Grid x:Name="ThumbListBoxGrid">
    <ListBox x:Name="ThumbListBox" ItemsSource="{Binding}" VerticalAlignment="Top" Height="{Binding ElementName=ThumbListBoxGrid, Path=ActualHeight}" IsSynchronizedWithCurrentItem="True"  />
</Grid>

Anyone see what's wrong here?
Answer: You specify the SelectedItem Background for a ListBox with the SystemColors.HighlightBrushKey (focused) and SystemColors.ControlBrushKey (not focused)

</Style>

Comment: can u please tell me where should i put these code to work. i means which file
Answer: For anyone searching for this in the future, the accepted answer doesn't actually apply the colour when control is not focused for me. The following should be used instead which appears to work as intended.

</Style>

Comment: Only just seen this @PranavJDev sorry!. It can go in any resource that the control you are using has access to. This applies it to the default style for the control though so you may think of putting it in a local resource if you do not wish the style to be applied everywhere. So if using in the OP's example you could put it in the following tag:
`

`

ListBox Selected Item Background


How to prove that $(u-v)^+\in W_0^{1,2}(\Omega)$, if $u\in W_0^{1,2}(\Omega)$, $v\geq 0$.

Question: Let $\Omega$ denote a open subset of $\mathbb{R}^n$, and $W^{1,p}(\Omega)$ the Sobolev space of weakly differentiable functions $u\in L^p(\Omega)$ (that is, for which $D_iu$ exists and belongs to $L^p(\Omega)$ as well, for every $i\in\left\{1,\ldots,n\right\}$).
I'm studying boundary regularity of a solution of the Dirichlet problem for the circle $D\subseteq\mathbb{R}^2$, and the weak maximum principle is needed. For that, we need to give a proper meaning for $u\leq v$ in $\partial\Omega$ (the boundary of $\Omega$), where $u,v\in W^{1,2}(\Omega)$. The definition is:
$u\leq v$ in $\partial\Omega$ iff $(u-v)^+\in W_0^{1,2}(\Omega)$, where:

$w^+=\max(w,0)$ denotes the positive part of $w$; and
$W_0^{1,2}(\Omega)$ is the closure (in Sobolev norm) of $C_0^\infty(\Omega)=\left\{w\in C^\infty(\Omega):\text{supp}(w)\text{ is compact}\right\}$

Now, a lot of statements relating to that concept need the following lemma (or something similar), which I'm unable to prove:

Lemma: Let $u\in W_0^{1,2}(\Omega)$, $v\in W^{1,2}(\Omega)$ such that $v\geq 0$ pointwise. Show that $(u-v)^+\in W_0^{1,2}(\Omega)$.

Intuitively, that should be true. If we think of continuous functions $u$ and $v$ such that $u\in C_0(\Omega)$, then $(u-v)^+\in C_0(\Omega)$, since $|(u-v)^+|\leq|u|$ (where $C_0(\Omega)$ denotes the set o compactly supported continuous functions from $\Omega$ to $\mathbb{R}$). Using mollifiers, it's easy to see that $C_0(\Omega)\subseteq W_0^{1,2}(\Omega)$, and the lemma is true in that case. I tried to give the following proof:
The case $u\in C_0^\infty(\Omega)$ is easy enough. Now, let $\left\{u_n\right\}_{n\in\mathbb{N}}\subseteq C_0^\infty(\Omega)$ be a sequence converging in $W^{1,2}(\Omega)$ to $u$. Taking subsequences if necessary, I tried making pointwise convergence (almost everywhere in $\Omega$) of $(u_n-v)^+$ and $D_i(u_n-v)^+$ to $(u-v)^+$ and $D_i(u-v)^+$, respectively, so I'd apply Lebesgue's Dominated Convergence Theorem, and conclude convergence in $W^{1,2}(\Omega)$, hence proving the lemma. The problem is exactly with the derivatives:
Since $Dw^+(x)=0$ if $w(x)\leq 0$ and $Dw^+(x)=Dw(x)$ if $w(x)>0$ ($\forall w\in W^{1,2}(\Omega)$: this follows from the weak chain rule), we cannot garantee pointwise convergence if $u(x)=v(x)$.
Any idea would be of great value. Even if one must assume $\Omega$ bounded and/or $v\in C^\infty(\Omega)\cap C^0(\overline{\Omega})$, it would suffice for what I need.
Thank you in advance.
Answer: I found a nice elementary proof for this: All the equalities are meant to hold a.e..

Lemma: Let $u\in W^{1,p}(\Omega)$ and $N=\left\{x\in\Omega:u(x)=0\right\}$. Then $D_iu=0$ a.e. in $N$.

Proof: Let $u^+=\max(u,0)$ and $u^-=\min(u,0)$. By the chain rule, $u^+,u^-\in W^{1,p}(\Omega)$ and $D_iu^+(x)=D_iu(x)$ if $u(x)>0$ and $D_i u^+(x)=0$ otherwise, and $D_i u^-(x)=D_iu(x)$ if $u(x)<0$ and $D_iu^-(x)=0$ otherwise. Since $D_iu(x)=D_i(u^++u^-)(x)=D_iu^+(x)=D_iu^-(x)$, the lemma holds.$\square$
Proof of the statement in the question: First suppose $u\in C_0^\infty(\Omega)$. Then $\text{supp}(u-v)^+\subseteq\text{supp}(u)$, and a sequence of mollificationsof $(u-v)^+$, converging to it in $W^{1,p}(\Omega)$ will eventually be in $C^\infty_0(\Omega)$, and the statement holds.
Now suppose $u\in W_0^{1,p}(\Omega)$. Let $\left\{u_n\right\}_{n\in\mathbb{N}}$ be a sequence of $C_0^\infty(\Omega)$ functions converging to $u$. Taking subsequences if needed, we can assume $u_n\rightarrow u$ and $D_iu_n\rightarrow D_iu$ a.e. in $\Omega$.
Then $(u_n-v)^+\rightarrow (u-v)^+$ a.e. pointwise (for $x\in\Omega$, consider the cases $u(x)>v(x)$, $u(x)<v(x)$ and $u(x)=v(x)$), and the dominated convergence theorem implies that $(u_n-v)^+$ converges to $(u-v)^+$ in $L^p(\Omega)$.
Now, let $x\in\Omega$ (such that $D_iu_n(x)\rightarrow D_iu(x)$). If $u(x)>v(x)$ or $u(x)<v(x)$, use the chain rule to see that $D_i(u_n-v)^+(x)\rightarrow D_i(u-v)^+(x)$. If $u(x)=v(x)$, by the lemma we can assume that $D_iu(x)=D_iv(x)$, and it's easily verified that $D_i(u_n-v)^+(x)\rightarrow D_i(u-v)^+(x)$. Again by dominated convergence, $D_i(u_n-v)^+\rightarrow D_i(u-v)^+$ in $L^p(\Omega)$. That means that $(u_n-v)^+\rightarrow(u-v)^+$ in $W^{1,p}(\Omega)$. Since $(u_n-v)^+\in W_0^{1,p}(\Omega)$, which is closed, the result follows.$\square$
Answer: Going through fine pointwise properties of Sobolev functions and associated nonlinear potential theory looks like doing it the hard way. Here is another approach.
Claim. Let $1< p<\infty$. If $u\in W_0^{1,p}(\Omega)$, $w\in W^{1,p}(\Omega)$, and $0\le w\le u$, then $w\in W_0^{1,p}(\Omega)$.
We need a standard truncation lemma. Here $u^+=\max(u,0)$.
Lemma 1 If $u \in W^{1,p}(\Omega)$, then $u^+ \in W^{1,p}(\Omega)$ and $|\nabla u^+|\le |\nabla u|$ almost everywhere.
Proof. Use the ACL characterization of $W^{1,p}$. Note that
$$|u^+(a)-u^+(b)|\le |u(a)-u(b)|,\qquad a,b\in \Omega \tag1$$
Since $u$ is absolutely continuous on almost every coordinate-parallel segment, so is $u^+$ —  just look at the definition of absolute continuity and at (1). Therefore, $u^+$ on such segments $u^+$ is differentiable a.e. Again, (1) implies that its partial derivatives cannot exceed the partial derivatives of $u$.  $\Box$
Corollary 2. If $u,v \in W^{1,p}(\Omega)$, then $\min(u,v) $ and $\max(u,v)$ are in $W^{1,p}(\Omega)$ and their gradients are bounded by $|\nabla u|+|\nabla v|$.
Proof. Apply Lemma 1 to $\dfrac{u+v}{2}\pm \dfrac{(u-v)^+}{2}$. $\Box$
Proof of the Claim: Let $(w_n)$ and $(u_n)$ be smooth approximations to $w$ and $u$ in the Sobolev norm, with $u_n$ compactly supported in $\Omega$. Then $f_n:=\min(w_n^+,u_n)$ is a sequence of Lipschitz compactly supported functions. By construction, $f_n\to w$ a.e.
From Lemma 1 and Corollary 2 we see that $(f_n)$ is a bounded sequence in $W^{1,p}$ norm. Therefore, it has a subsequence $f_{n_k}$ that converges to some $g\in W^{1,p}_0(\Omega)$ weakly in $W^{1,p}$ and strongly in $L^p$ (the latter by Rellich-Kondrachov). Recalling that $f_n\to w$ a.e., we conclude that $g=w$. Thus, $w\in W^{1,p}_0(\Omega)$. $\Box$
Notice how the "soft" tools of functional analysis save us the headache of dealing with boundary values. The set $W^{1,p}_0(\Omega)$ is closed in $W^{1,p}(\Omega)$ by definition, and is also convex. From functional analysis, it's weakly closed — and this is how we get $g\in W^{1,p}_0(\Omega)$, not from pointwise analysis of boundary values.
Comment: Just for reference: this nice fact is contained in Lemma 1.25 (ii) from [Heinonen, Kipelainen, Martio, "Nonlinear potential theory of degenerate elliptic equations"].
Answer: There is a characterization of $W_0^{1,2}$ in terms of pointwise traces: a function $u \in W^{1,2}(\Omega)$ belongs to $W_0^{1,2}(\Omega)$ if and only if
$$
\lim_{r \to 0^+} \int_{B(x,r) \cap \Omega} |u(y)| \, dy = 0
$$
for $(1,2)$-quasievery point $x \in \partial \Omega$. Since you assume $u \in W^{1,2}_0(\Omega)$ and point out that $|(u-v)^+| \le |u|$, you can conclude that $(u-v)^+ \in W^{1,2}_0(\Omega)$ also.
Comment: What does it mean "*for (1,2)-quasievery point $x\in\partial\Omega$*", and, if possible, where can I find the proof if this fact?


Algorithms for predicting a couple points in the future

Question: I'm familiar with supervised learning algorithms like regression and neural networks which look at a bunch of input points and learn a function which outputs a value (the value varying depending on whether the algo is a classifier, logistic regression, or standard regression)..but I am facing a problem now where each observation I have is a couple of data points (TAQ data), and then after a fixed amount of these chronologically sorted events there is a spike and what appears to follow an exponential decay mean reversion. Every such instance described here is one of my observations and my goal is to predict/model this exponential decay mean reversion.
What type of algorithms would do something like this? time series models a-la ARCH/GARCH followed by a prediction look-ahead of N steps after training them or what else?
Thank you, any type of suggestions or advice/references are greatly appreciated.
Comment: What does "TAQ" mean?  Trade-and-quote?  DNA polymerase?  The Twitter tag?
Comment: You're referring to Kaggle [Algorithmic Trading Challenge](http://www.kaggle.com/c/AlgorithmicTradingChallenge/) competition, right?
Answer: To predict "a couple of points in the future" summarizes the singular focus of my life's work. To make a prediction I believe you must have a trusty signal. To me a trusty signal is one that is the result of separating signal from noise. The "proof of noise" allows one to state the signal has neither too many or too few statistically significant parameters. Neural Networks in my opinion is "regression without ethics" as it fits rather than constructs valid likelihood ratio tests to augment/simplify a current candidate model.On the other hand the identification of Pulses , level Shifts , Seasonal Pulses and local time trends are conducted using formal likelihood ratio tests for detection and retention . There are a number of requirements for an error series to be "proven" to be white noise. Failure of one or more of these assumptions leads directly to model augmentation prior to usage. Some of those augmentation strategies include forming a minimally sufficient ARIMA model, validating that the mean of the errors does not differ significantly from zero for all intervals , validating that the error process is homogeneous and thus free of deterministic change points , dependence of the expected value and the variability of the process and finally a lack of ARIMA structure needed to coax the variance to stability. I would suggest that you post one of your actual time series data sets and let the list readers pursue this problem at "ground zero" . A comparison or bake-off between different approaches would I believe be of interest to all.


Nginx Node Proxypass Result to Variable

Question: I want create some rewrite with nginx (5 million links), I read nginx have the option to save it in a map file but need ages to reload + ram usage when I do it this way.
My Idea was now User -> Nginx -> Node(which gives the link) -> Save the link in a Variable of nginx -> Nginx rewrite to the file
I tryt to supply file direct over node with express but have already 50% usage with 300 connections.
Is this posible or im on the completly wrong way?
thanks
Answer: You can have the Node server return the link as an X-Accel-Redirect header and Nginx will rewrite the request to whatever link your backend server gives it.
Comment: seems nice, https://stackoverflow.com/questions/23904521/nginx-x-accel-redirect-not-working-with-node-js have asked the same things, nice to know when u know what u have looking for

Nginx Node Proxypass Result to Variable


Odoo 13 error in xml file while upgrading the module

Question: I am getting this error while upgrading my custom module in odoo13 while upgrading it , the error is within this xml file.
File "/odoo/odoo-server/addons/gunalan_demo/views/views.xml", line 31
lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: form line 9 and field, line 31, column 16
<?xml version="1.0" encoding="utf-8"?>
<odoo>
  <data>

    <record id ="request_form" model ="ir.ui.view">
      <field name="name">view.demo.form</field>
      <field name="model">car.request</field>
      <field name="arch" type="xml">
        <form string ="Car Request Form">
          <sheet>

                <field name="name" placeholder="Request Demo"/>

            <group>
              <group>
                  <field name="date_from"/>
                  <field name="date_to"/>
              </group>
              <group>
                <field name="emplyoee_id"/>
                <field name="car_id"/>

              </group>
            </group>

          </sheet>
      </field>
    </record>

    <record id='request_tree' model='ir.ui.view' >
        <field name='name'>view.demo.tree</field>
        <field name='model'>car.request</field>
        <field name='arch' type='xml'>
            <tree string='Car Request Tree'>
                <field name="name"/>
                <field name="emplyoee_id"/>
                <field name="car_id"/>
                <field name="date_from"/>
                <field name="date_to"/>
            </tree>
        </field>
    </record>

    <record id="action_request_views" model="ir.actions.act_window">
      <field name="name">Car Request</field>
      <field name="type">ir.actions.act_window</field>
      <field name="res_model">car.request</field>
      <field name="view_mode">tree,form</field>
      <field name="help" type="html">

          Car Request

          Click here to add

      </field>
    </record>

    <menuitem id="menu_car_request_root" name="Car Request" sequence="10"/>
    <menuitem id="menu_car_request_categ" name="Car Request" parent="menu_car_request_root" sequence="1"/>
    <menuitem id="menu_car_request" name="Car Request" parent="menu_car_request_categ" action="action_request_views" sequence="1"/>
  </data>
</odoo>

Answer: You know the error message is already telling you everything? You've opened the form tag but never closed it.


Chromatic parallel six-three chords

Question: I am trying to follow Aldwell and Schachter's analysis of Chopin's Impromptu, Op. 29.  I wanted to learn about chromatic voice leading techniques, but I ended up getting stuck simply with their analysis of the diatonic framework in Chopin's piece.  They identify the progression in Example 31-1 (please see attached image) as I-II6-V7; I am having trouble seeing these chords the same way, however.  Either I am misunderstanding a concept, misreading notation (lots of accidentals), or I've misinterpreted the chords within the larger harmonic framework at play.  Can you please look at my notes and clue me in on what the progression really is here?  The reduction I came up with, while not the I-II-V7 I was expecting (but rather various extended chords?) is actually really pretty, and I would like to know if this [I-?-?] is a progression that I should be familiar with.
Thank you!
286642
Comment: A hint: to read and play easier the chromatic Passage just play the r.h. as 6th chords ( 1st inversion) reading Ab-E-Eb-D, Db-D-Db-C, B-C-B-Bb, Eb ...
Comment: unluckily you don't poste us the continuation of p. 563 and the copy you've posted is bad readable! (But the book of **Aldwells und Schachter** looks very interesting. I'll try to get this too.
Answer: For the ii6 chord in the third bar of ex. 31-1, the bass is Db3. The flat on it is a courtesy accidental it is not double flatting the Db of the key signature. The next chord the V with the 6/4 5/3 figures (or maybe it says 8/3, it's hard to read) uses an Ab - with a flat - not an A natural.
I think you're misreading the accidentals.
Beyond that, the point of the text book is to say the main, functional chords are I on beat 1 of the first bar, ii6 on beat 1 of bar 4, and V on beats 3 and 4 of bar four, while all the chromatic movement on the 11 beats between I and ii6 is just chromatic elaboration.
That's actually a pretty common concept. I think you can generalize the concept into something like I ... <some kind of cadence> where the ellipse means proceed from the tonic (or maybe the dominant) with a whole lot of latitude about what the harmony is and it can be rendered tonally sensible if ended with a formulaic cadence.
I'm overstating the case on purpose. You can't get away with musical gibberish in the middle of a phrase and there are conventions for the structure of cadences. But, between some tonally clear start and ending there is a lot of harmonic flexibility. This textbook lesson is showing chromatic descending movement as a possibility and you don't need to put Roman numeral analysis on anything but the main, functional chords.
One other thing: I notice in your notes your wrote...

...placing Bb in the bass, but the score has Eb in the bass and the textbook analysis is...

The progression is a cadential 6/4 movement, or using older figure bass terminology, a double cadence.
The modern view is one of chord inversions where 6/4 means second inversion, but old figured bass is about intervals above a bass.
Modern analysis is I6/4 V I where Eb Ab C is viewed as second inversion of an Ab major chord.
Figured bass (notation not analysis) is a notated Eb with a 6/4 figure above it meaning play a sixth and fourth above the Eb bass.
If you get picky and philosophical about the identity of chords, the two views are very different. One is a tonic chord the other is a dominant chord. It's like saying up is down and down is up! How can we not tell the difference between a tonic and dominant chord?!?
The textbook labels Eb Ab C as V6/4 ...a dominant chord in the vein of old figured bass. Your label is I6/4 a second inversion tonic chord.
This isn't a matter of right or wrong and personally I switch mentally between the two all the time. In a progression like I V6/4 I6 I definitely think of V6/4 as a second inversion dominant, but in I6/4 V I I think of I6/4 in the old figured bass way and consider the chord to be a suspension over a dominant.
I thought it might help you to point out the difference in how that chord can be labeled in different music theory systems.
Answer: You are correct: ii = Bb,Db,F and ii6 = Db,F,Bb (like the chord in the last measure (posted).
But you are wrong: I46 = Eb,Ab,C (I think a mistake), and the flattened note in the middle line of bass clef is Db not C.
The last error is V46 in the last bar of your poste. You think 46 means the inversion of the dominant. But it is a dominant Eb with a suspended 4th (Ab) and suspended 6th (C). This suspension  Eb, Ab, C which is usually  functional interpreted as 2nd inversion of the tonic (Ab,C,Eb) => Eb,Ab,C and notated also as I46.
This has has always lead to great discussions and may be confusing as V4 means sus4 and I6 means inversion. And V46 means suspension while I46 means inversion.
Edit:
another error I haven't noticed yet:
The b7 of Eb is Db - and not Gb.

This Gb is wrong!
Now my error:
I have overseen the title of your question:
Chromatic parallel six-three chords
and didn't understand that the sentence

"I am having trouble seeing these chords the same way."

is referring to these chromatic passage. Well, in this case I wouldn't imagine the enharmonic chords. (What I use to do is to transpose a piece in another key with less accidentals e.g. C or even her A major. But this won't help a lot as you will have anyway a lot of accidentals because it goes chromatic half step down.)
The chromatic passage is surely not a ii-V7 progression but if we consider this chromatic passage like e.g. E7-Eb7-D7-Db7-C as a chain of secondary dominants fifth fall sequence)  with tritone substitutions Eb7~A7, Db7~G7 you can explain the chromatic downward progression as V7/V7/V7 .... (secondary dominants).
Answer: I have now found a proper download of your unreadable copy:
It says: Filling in the space between the I and the II6  is a series of descending parallel     6     3 's. The passage is similar to those discussed in Unit 19 in all respects except a most important one—it is chromatic instead of diatonic. The reduction following the excerpt (Example 32-1b) shows its diatonic basis (half notes) and its chromatic elaboration (black noteheads). We can readily see that the chromaticism of this passage involves procedures already familiar to us: specifically, the use of mixture and of chromatic passing tones. The 5-6 motion that introduces the descending     6     3 's is altered by mixture so that the first     6     3   is expressed as an F∫-major chord instead of an F-minor one. And the other chromatics can be understood as passing tones. One other aspect of this excerpt deserves attention, for it is characteristic of all sorts of chromatic passages—not just those based on parallel     6     3 's. Note that all the     6  3   chords are  major  except for the goal II6. Obviously, if a succession of chords is parallel and chromatic, all the chords will have the same quality. The major triad represents a preferred sonority, so composers have tended to favor it in such passages.
This means A.&S. interpret the non diatonic chord as passing tones (black dots).
They don't see that
Fb=E => substitution of  Bb = V7/Eb
D => substitution of Ab
etc.
and we have a sequence of secondary dominants. The 3 concepts of V/V, circle of 5ths and the tritonus substitution (chords with enharmonic exchanged common tones in the interval of a dim. 5th to the secondary dominant) make this progression more plausible than the explanation of passing tones which looks to me rather like an excuse or false argument for not understanding what happens.
(I don't mean it is really false but there are better arguments.)

Chromatic parallel six-three chords


Salvar imagem com webservice

Question: Eu já tenho um webservice para o qual eu passo um imagem (Base64) e ele salva no meu servidor. Até aqui ele está funcionando perfeitamente.
Na minha tela tem esse código :
function salvar() {
        var dados = {};

        //Utilizar o toDataURL para converter em Base64
        var base64 = document.getElementById("myCanvas").toDataURL("image/png");

        dados.base64 = base64.substr(base64.indexOf(',') + 1, base64.length);

        var WPath = "face1";

        $.ajax({
            type: 'POST',
            //Chamar o webmethod SalvarImagem em webservice.asmx
            url: "SalvarImagem.asmx/SalvarImagemX",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: JSON.stringify(dados, WPath),
            success: function (data) {
                alert(data.d);
            }
            , error: function (xmlHttpRequest, status, err) {
                alert("Ocorreu o seguinte erro:" + xmlHttpRequest.responseText)
            }
        });
    }

E o meu webservice está assim :
public class SalvarImagem : System.Web.Services.WebService
{

    [WebMethod]
    public string SalvarImagemX(string base64, string WPath)
    {
           //MemoryStream com o base64 recebido por parâmetro
        using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
        {
            //Criar um novo Bitmap baseado na MemoryStream
            using (Bitmap bmp = new Bitmap(ms))
            {
                //Local onde vamos salvar a imagem (raiz do site + /canvas.png)
                //string path = Server.MapPath("/" + WPath + "/canvas.png");
                string path = Server.MapPath("/face2/canvas.png");

                //Salvar a imagem no formato PNG
                bmp.Save(path, ImageFormat.Png);
            }
        }

        return "Imagem foi salva com sucesso";
    }
}
}

Meu problemas está que : Como eu disse ele funciona enquanto eu passo somente um paramentro que é a string DADOS. Mas eu preciso passar também outra string que contem a pasta onde deve ser gravado a imagem...
Quando eu coloquei segundo parâmetro (WPath) eu passei a receber a mensagem de erro abaixo... Alguem sabe me dizer o que tem de errado ....??
Ocorreu o seguinte erro:

{"Message":"Invalid web service call, missing value for parameter:
  \u0027WPath\u0027.","StackTrace":"   at
  System.Web.Script.Services.WebServiceMethodData.CallMethod(Object
  target, IDictionary2 parameters)\r\n   at
  System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object
  target, IDictionary2 parameters)\r\n   at
  System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext
  context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n
  at
  System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
  context, WebServiceMethodData
  methodData)","ExceptionType":"System.InvalidOperationException"}
Answer: Está dando erro porque não é assim que se usa o JSON.stringify para o que você está pretendendo.
Você passou dois parâmetros pra ele, aqui:
JSON.stringify(dados, WPath)
Segundo a documentação, o segundo parâmetro do JSON.stringify é o replacer:

replacer: A function that alters the behavior of the stringification
  process, or an array of String and Number objects that serve as a
  whitelist for selecting/filtering the properties of the value object
  to be included in the JSON string.

Em uma tradução livre, o replacer seria "Uma função que altera o comportamento do processo de transformação em string, ou um array de String e Number que servem como uma lista para selecionar e filtrar as propriedades do objeto a ser transformado em string".
Eu ia te mostrar como usar o segundo parâmetro, mas não foi essa a pergunta, então vou deixar uma possível solução para o seu AJAX. Troque o código que eu mencionei a cima, pelo seguinte:
data: '{"base64":"' + dados + '","WPath":"' + WPath + '"}'

Espero que te ajude, qualquer dúvida coloca aí nos comentários
Answer: A quem interessar possa o problema era porque estava faltando colocar o complemento da variavel, estava assim :
data: '{"base64":"' + dados + '","fileName":"' + nomearq + '"}',

Mas o certo é assim : data: '{"base64":"' + dados.base64 + '","fileName":"' + nomearq + '"}',
Fica o registro para futuros sofredores.
Abs.
Answer: Obrigado Diego...
Nãotenho muito experiência com AJAX ei fiz o que você sugeriu mas está dando um erro de sintaxe que eu não consigo identificar... segue imagem..

Comment: Ok.. já descobri... faltava uma ',' no final...
Comment: Olá, não poste dúvidas adicionais como resposta, em vez disso, coloque um comentário em uma resposta que gerou a dúvida. A minha resposta ajudou? Então marque-a como aceita. Você também pode votar em outras perguntas e respostas no site
Comment: Ola fiz o que você sugeriu e passou a dará esse erro...Ocorreu o seguinte erro:{"Message":"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

Salvar imagem com webservice


Ping: "Destination Host Unreachable" even though ARP request succeeds

Question: I have a wired interface with a static IP configured. Pinging the gateway results in "Destination Host Unreachable".
<code>PING 10.3.3.246 (10.3.3.246) 56(84) bytes of data.
From 10.3.3.8 icmp_seq=1 Destination Host Unreachable
From 10.3.3.8 icmp_seq=2 Destination Host Unreachable
From 10.3.3.8 icmp_seq=3 Destination Host Unreachable
From 10.3.3.8 icmp_seq=4 Destination Host Unreachable
From 10.3.3.8 icmp_seq=5 Destination Host Unreachable
^C
</code>
I wireshark I can see the ARP request being replied to immediately. The ARP request is retried every second and every time it gets an immediate reply.
It seems that the ARP reply is not accepted for some reason. Anyone have an idea what could be going on?
Comment: A firewall can either reject or silently drop. Not related to the arp table.
Answer: The problem turned out to be that the ARP replies arrived with a VLAN tag (when no VLAN tagging was expected at all.) There was a problem with the switch.
Posting this an answer so people know to check for unexpected VLAN tags in situations like these.


Is $f(C)$ a convex set if $f$ and $C$ are convex?

Question: The complete claim is,

Let $F$ be an ordered field and $\bar F=F\bigcup\{+\infty,-\infty\}$. Let $f:A \to \bar F$ be a convex map from affine space $(A,V)$ to affine space $(F,F)$, then $f(C)$ is a convex set if $C$ is convex.
Here $F$ can be treated as $\Bbb R$ except for that we do not use its topology and metric. $A$ is a point set, and $V$ is a vector space.

A convex function is defined using epigraph,

$f$ is a convex set if its epigraph $\text{epi} f=\{(x,y)\in A\times F:y\ge f(x)\}$ is a convex set.

I am not sure if this claim is right but it seems so. I find difficulty in proving it. The following is an attempt, but no contradiction is found.

If $f(C)$ is not convex, then there exists $y_1,y_2\in f(C)$ st. $y_1>y_2$ and $\theta y_1 + (1-\theta) y_2 \notin f(C)$ for some $\theta \in (0,1)$. Let $y_3=\theta y_1 + (1-\theta) y_2$, and suppose $f(x_1)=y_1, f(x_2) = y_2$ for some $x_1,x_2\in C$. Let $x_3 =\theta x_1 + (1-\theta) x_2)$, then $(x_1,y_1),(x_2,y_2)\in \text{epi} f \Rightarrow (\theta x_1 + (1-\theta) x_2, \theta y_1 + (1-\theta) y_2) = (x_3,y_3) \in \text{epi} f \Rightarrow y_3 > f(x_3)$

The last inequality $y_3>x_3$ does not contradict with Jensen's inequality.
I need help with this. If it is not comfortable to deal with affine space, we might just assume $f:\Bbb R^n \to \Bbb R$, and just try not to use topology information (such like continuity) and metric in the proof. I add "real analysis" as a tag of this question for this reason.
Again, note the claim might not be true. If it is not true, hope someone could come up with a counterexample.
Thank you!
Comment: The characteristic function $\chi_C$ of any convex set $C$ is convex and has image $\{0,\infty\}$, defined by $\chi_C(x) = 0$ for $x\in C$ and $=\infty$ otherwise.
Comment: @Tom in the question, $f$ is supposed to be scalar valued.
Comment: @Tom the _epigraph_ is a convex set, not the graph.
Comment: @MichaelGrant the question isn't about the epigraph, but the graph.
Comment: Ah, then really, I should be directing that comment to the OP :-)
Comment: @MichaelGrant convex epigraph is used as definition for convex function. The question is about whether a convex function has a convex graph. Have I misunderstood something?
Comment: I don't think you've misunderstood anything. My point was the same as yours: that a graph and an epigraph are not the same thing.
Comment: @user251257 I think it's about the *image* not the *graph.*
Comment: @quid yeah. No Idea why I wrote graph.
Comment: Hi, guys. Thanks for your discussion. This seems to be a tougher question than it looks.
Comment: @Tony no. It is wrong. See my first comment.
Answer: At least for $F=\mathbb R$ and $A=V=\mathbb R^n$ it is pretty simple.
If you allow $\infty$, then the statement is not true in general. The characteristic function $f=\chi_C$ of any convex set $C\subseteq A$, defined by
$$f(x) = \begin{cases}
0, & x\in C, \\
 \infty, & x\notin C,
\end{cases}$$
is convex and has image $f(A)=\{0,\infty\}$.  Obviously the image isn't convex.
If you only allow finite values, then it is true.
On a finite dimensional space, a convex function $f$ is continuous on the interior of its proper domain. Since $\mathbb R^n$ is open, the image $f(C)$ must be connected for any connected $C\subseteq A$. Notice that convex sets are also connected. Now, the connected subsets of $\mathbb R$ are the intervals and thus are convex.


Adjusting for age and gender in ANOVA

Question: I am performing an ANOVA to compare the means of three groups. However, I need to adjust for the effects of age and gender in the ANOVA. I'm not quite sure how to go about it in R.
Conventionally, I would use this command in R
model <- aov(y ~ x1)

x1 is categorical with 3 levels.
Answer: You would do regression with your categorical variables coded $(0,0)$ for category $1$, $(1,0)$ for category $2$, and $(0,1)$ for category $3$, plus the age and gender variables, so m_full <- lm(y ~ c2 + c3 + age + gender), with c1 omitted since it is all $0$s. You then compare to the model that lacks your categorical features: m_reduced <- lm(y ~ age + gender) via anova(m_full, m_reduced).
This does an F-test of the two models the same way that an ANOVA F-test compares the model with the categorical features to a model that only has an intercept (which is what ANOVA does).
ANOVA is just a particular type of regression. If you want to add covariates, feel free.
You can condense the categorical variable into one lm input by calling it with as.factor, such as m_full <- lm(y ~ as.factor(categorical_variable) + age + gender).
Comment: @Dave: R will create the dummys for you if you remember to declare a **factor** variable: ` categorical <- factor(categorical)` Care to edit?
Comment: If I understand you well, you mean I should create dummy variables from the categorical variable and use those dummy variables to fit the linear regression
Comment: Yes, that's what ANOVA is.
Comment: Thank you very much Dave!
Answer: You might find this rundown helpful: https://conjugateprior.org/2013/01/formulae-in-r-anova/
It covers some subtleties / annoyances when it comes to expressing nesting and error terms in formulae and offers some further reading.

Adjusting for age and gender in ANOVA


Prove $\frac{a(b+c)}{b^2+bc+c^2} \geqslant \frac{8a^2+2a(b+c)-(b-c)^2}{3(a^2+b^2+c^2+ab+bc+ca)}.$

Question: Let $a,\,b,\,c$ are non-negative such that $ab+bc+ca>0.$ Prove that
$$\frac{a(b+c)}{b^2+bc+c^2} \geqslant \frac{8a^2+2a(b+c)-(b-c)^2}{3(a^2+b^2+c^2+ab+bc+ca)}. \quad (1)$$
Note. Because
$$\sum \frac{8a^2+2a(b+c)-(b-c)^2}{3(a^2+b^2+c^2+ab+bc+ca)} = 2.$$
So, from $(1)$ we get know inequality of Darij Grinberg
$$\frac{a(b+c)}{b^2+bc+c^2}+\frac{b(c+a)}{c^2+ca+a^2}+\frac{c(a+b)}{a^2+ab+b^2} \geqslant 2.$$
My proof use sum of squares method.
Comment: @Nguyenhuyen_AG It's obvious that the Darij's inequality is a linear inequality of $w^3$ and $uvw$ kills it immediately.
Comment: @MichaelRozenberg There are many ways to prove it, $ uvw $ is the fastest =))
Comment: So you've shown the sum of three terms is greater than the sum of three others.. .that might not imply each term is bigger than the other?
Comment: @Dhanvi Sreenivasan You can find counterexamples?
Comment: Take 3,4,1 and 2,2,2. 3+4+1 > 2+2+2, but 1 < 2
Answer: Thank @Michael Rozenberg :D We write inequality as
$$f(a) = 3(b+c)a^3-(5b^2+2bc+5c^2)a^2+(b+c)(b^2+bc+c^2)a+(b^2+bc+c^2)(b-c)^2 \geqslant 0.$$
But
$$\left(a+\frac{7b+7c}{4}\right) \cdot f(a)=\frac{3}{4}(b+c)(2a^2-b^2-c^2-ab+2bc-ca)^2+\frac{5bc(b+c)(b-c)^2}{4}$$
$$+\frac{17abc[(a-b)^2+(a-c)^2]}{4}+\frac{25a(b^2+c^2-ab-ca)^2}{8}+\left(\frac{a}{8}+b+c\right)(b-c)^2(b+c-a)^2.$$
So $f(a) \geqslant 0.$
Comment: Nice! +1. But it's very hard to find this solution without computer. By the way, my solution is by hand.
Comment: @RiverLi It's not strong, many problems can not find SOS. Ji Chen SOS or szl6208 SOS is better than
Comment: Yes. So I posted here to find a simple solution =))
Comment: What is your idea to get it?
Comment: @Nguyenhuyen_AG   I saw you obtained simple SOS often (I will get complicated SOS usually). If you use some solvers to get the SOS, how powerful are your solvers? Did you try harder SOS problems?
Comment: @Nguyenhuyen_AG Thanks. Hope to see more SOS challenge problems in MSE.
Comment: May I know this program?
Answer: BW helps!
We need to prove that:
$$3(b+c)a^3-(5b^2+2bc+5c^2)a^2+(b+c)(b^2+bc+c^2)a+(b-c)^2(b^2+bc+c^2)\geq0.$$
Thus, since our inequality is symmetric respect to $b$ and $c$, we have two cases only:

$a=\min\{a,b,c\}$, $b=a+u$ and $c=a+v$.

Thus, $u\geq0$, $v\geq0$ and we need to prove that:
$$3(u^2+v^2)a^2+(u+v)(4u^2-5uv+4v^2)a+(u-v)^2(u^2+uv+v^2)\geq0,$$ which is obvious;

$b=\min\{a,b,c\}$, $a=b+u$ and $c=b+v$.

Thus, we need to prove that:
$$3(2u^2-2uv+v^2)b^2+(6u^3-3u^2v-5uv^2+4v^2)b+v(3u+v)(u-v)^2\geq0,$$ which is obvious again.
Comment: I think BW is the simple way to prove without computer!
Answer: We have$:$
$$48\, \left( b+c \right) ^{2} \left( {b}^{2}+bc+{c}^{2} \right)
 \left( {a}^{2}+ab+ac+{b}^{2}+bc+{c}^{2} \right)
\cdot (\text{LHS}-\text{RHS})$$
$$=48\,a ( b+c )  \Big[b^2+c^2-a(b+c)\Big] ^{2}+4\,(b-c)^2 \Big[ 2\, a(b+c)-(2b^2+bc+2c^2) \Big] ^{2}$$
$$+4\,bc \left( 8\,{b}^{2}+7\,bc+8\,{c}^{2} \right)  \left( b-c \right) ^
{2} \geqq 0.$$
Comment: Simple SOS solutions are beautiful.
Comment: @RiverLi Thank you, I really hope to see your program to help you SOS.
Comment: I found that the equality cases are important. If an inequality holds with equality at only one point, sometimes it is not so difficult. If an inequality holds with equality at multiple points (even many points), it is often difficult.
Comment: @RiverLi I agree. And you can SOS for almost inequality, huh?
Comment: No. I can't.  It is too difficult.
Comment: @RiverLi What program you use to get SOS? I use Maple but I can only use it to factor the expression and get equality from two expression.
Comment: Sorry, I know little about SOS. You may search the internet.