Create Google Cloud Managed SSL Certificate for a subdomain

Question: I have my main domain www.example.com hosted on Route 53 on AWS.
I've created the custom domain on Google Cloud sub.example.com and set the appropriate NS records.
What I want to do now is create a new managed SSL certificate for this subdomain as shown below:

Is this possible? Is it good practice given that I want to continue adding more subdomains like sub1.example.com and creating a certificate for each one? Since I am keeping example.com hosted at Route 53, I don't think I can create a single managed SSL certificate for all of the possible subdomains that I may have on Google Cloud?
Comment: This post seems like a duplicate of the following [post](https://stackoverflow.com/questions/54915707/create-google-cloud-managed-ssl-certificate-for-a-subdomain)
Answer: Answer already posted here by John H. Re-posting as a community wiki.

I have my main domain www.example.com hosted on Route 53 on AWS.

Good choice. Route 53 is a very good service for DNS. If your services will be hosted in AWS even better. If your services will be hosted in Google Cloud, consider changing the Name Servers to Google DNS. All depends on which services you plan to use and where they are located (e.g. cloud vendor, not geo location).

I've created the custom domain on Google Cloud sub.example.com and set
  the appropriate NS records.

I hope you mean that you changed NS records at the registrar and not within Route 53.

What I want to do now is create a new managed SSL certificate for this
  subdomain as shown below: Is this possible?

Depends. Google Managed SSL certificates can only be used with Google services such as load balancers. However, the backend services can be anywhere provided that they have public IP addresses. AWS also offers managed SSL certificates for their services such as load balancers, CloudFront, etc. If your goal is to use Google Managed SSL certificates directly on your compute instances, etc. you cannot. Google does not provide the private key that is required for installation and setup of SSL.

Is it good practice given that I want to continue adding more
  subdomains like sub1.example.com and creating a certificate for each
  one?

Depends. For Google self-managed SSL certificates you can create a single SSL certificate with wildcards and / or specific domain names. If you are a typical user, wildcard certificates are fine (*.example.com). Multiple names are also fine (site1.example.com, site2.example.com, etc.). You can also create individual SSL certificates for each domain name. For the www domain name, typically you want to create a certificate with two names (example.com and www.example.com). For financial institutions, etc. usually EV (Extended Validation) certificates are used (which Google does not offer).
Google Managed SSL certificates have limitations over standard SSL certificates:

Wildcards are not supported.
Only DV (Domain Validation) SSL certificates are issued.
Single hostname per certificate.
Load balancers support up to 10 certificates.

Since I am keeping example.com hosted at Route 53, I don't think I can
  create a single managed SSL certificate for all of the possible
  subdomains that I may have on Google Cloud?

Route 53 had no impact on your choice or stategy for SSL certificates. Route 53 is a DNS server that resolves dns names. SSL (TLS / HTTPS) is a protocol that is not affected by or managed by Route 53.
Google Managed SSL certificates are limited to one name per certificate. Google Self-managed SSL certificates can have multiple names per certificate.


How can I show children in the taxonomy teaser views of parent/grandparent terms?

Question: Lets assume we have a Taxonomy called Region
Asia - Thailand - Bangkok
If a post is tagged with Bangkok, would it show up in the teaser view on following pages:
/region/
/region/asia/
/region/asia/thailand
or would it only show here?
/region/asia/thailand/bangkok
If later is the case, what's the best way to show it in parent terms teaser views?
Thanks for your help in advance.
Answer: You can try adding taxonomy as a hierarchical structure like
Term 1
Term 1-1
Term 1-2
Term 1-3

Term 2
Term 2-1

Then you can get the display using either

Taxonomy Menu Trails

And css as you wish.
Good Luck.
Comment: Taxonomy Treemenu is unmaintained and should not be considered except as a last resort. http://drupal.org/node/874060


Processing My sprite wont move

Question: could you help me to make my sprite walk left and right ? i just cant see where the problem is.
I've spend 3 hours looking at the code but i just cant see where i've made mistake ...
class Player {

  PImage playerr;
  PVector position;
  PVector velocity;
  float direction;
  float speed;
  float ground = 600;
  float left;
  float right;

  Player()
  {
    playerr = loadImage("sir1.png");
    position = new PVector(400, ground);
    direction = 1;
    speed = 4;
    velocity = new PVector(0, 0);
  }

void update()
{
    velocity.x = speed * (left + right);
    PVector nextPosition = new PVector(position.x, position.y);
    pushMatrix();
    translate(position.x, position.y);
    scale(direction, 1);
    image(playerr, 0, 0);
    popMatrix();
}

void keyPressed()
{
  if (key == RIGHT)
  {
    right += 5;
    direction = -1;
  }
  if (key == LEFT)
  {
    left -= 5;
    direction = 1;
  }
}

void keyReleased()
{
  if (key == RIGHT)
  {
    right = 0;
  }
  if (key == LEFT)
  {
    left = 0;
  }
 }

}

and that's the main program
int stage;
PFont startfont;
PFont normalfont;
PImage gameplan;

boolean[] keys = new boolean[526];

ArrayList knight;

void setup()
{
  size(800,800);
  frameRate(60);
  stage = 1;
  knight = new ArrayList();
  smooth();
}

void draw()
{
  switch(stage)
  {
    case 1:
      splash();
      break;
    case 2:
     game();
      break;
    case 3:
      help();
      break;
    case 4:
      help();
      break;
   }

}

void game()
{
  gameplan = loadImage("background.png");
  gameplan.resize(800,800);
  background(gameplan);
  knight.add(new Player());
  for(int i = 0; i <knight.size(); i++)
  {
     Player p = (Player) knight.get(i);
     p.update();

  }

}

void splash()
{
    background(0);
    startfont = createFont("start.ttf",40);
    normalfont = createFont("start.ttf",25);
    textFont(startfont);
    text("Zombie Destruction",100,300);
    textFont(normalfont);
    text("Press Space to start",200,400);
    text("Press H for help",250,500);
    if(keyPressed)
    {
      if(key == 'h' || key == 'H')
      {
        stage = 4;
      }
    }
    if(keyPressed)
    {
      if(key == ' ')
      {
        stage = 2;
      }
    }
}
void help()
{
    background(0);
    startfont = createFont("start.ttf",40);
    normalfont = createFont("start.ttf",25);
    textFont(normalfont);
    text("Zombie Destruction",100,300);
    textFont(normalfont);
    text("Press Space to go back",200,400);
    if(keyPressed)
    {
      if(key == 'b')
      {
        stage = 1;
      }
      else
      {
        stage = 4;
      }
    }
}

Comment: It is preferable that you do not input your whole executing code, but rather a [SSCCE](http://www.sscce.org). Please consider updating your code to help others to help you.
Comment: You should also tell *what* the problem is, ie. what the program actually does versus what you want it to do.
Comment: @hyde im sorry for the gramar mistakes. my brain doesnt work anymore. Basically it is a simple game with a splash screen. I want the player to move. i've placed the sprite into array list and the used the game() function to output the sprite. The problem is that the sprite is printed but it doesn't move. Im guessing there is something wrong with the player class but im not sure what.
Comment: Well, first thing to do is narrow the problem down by adding debug prints or setting breakpoints and examining variable values with debugger. Does the code get keypresses? Are relevant variables updated with keypresses? What actual numeric results do your calculations produce? Etc.
Answer: I believe the problem is in the Player class's update() method. It looks like you're calculating the updated velocity, but you never add that velocity to the player's position. A simple
position.x += velocity.x;

should do the trick.

Processing My sprite wont move


Can $R/I$ be $R$-flat if $R$ is a domain?

Question:
Let $R$ be a domain and $I$ a nonzero proper ideal of $R$. Can $R/I$ be flat?

For example, I can show if $R$ is Noetherian no such ideal $I$ exists. To see this, if $R/I$ is flat than by considering the injective map $I\to R$ and applying $\otimes R/I$ gives an injective map $I\otimes R/I\to R\otimes R/I$ and applying the isomorphism that $M\otimes R/I = M/I $ shows that $I/I^2\to R/I$ is injective so $I=I^2$. This cannot occur if $I$ is finitely generated.
Answer: Let $i \in I$ be non-zero and consider the injective map $R \to R$ given by multiplication with $i$. If we tensor this with $R/I$, we get the zero map, which is not injective.


Minimize the sum of distances between a circle and two fixed points

Question:

$\textbf{Question:}\ \ $Find a point D that lies on the circle O and the sum $\dfrac12\,BD+AD$ is minimal
(The radius of the circle is $4$)

$\ $
I have solved this question algebraically by constructing equations, and the answer is $2\sqrt{10}$
However, the calculation involves many radicals, which becomes too complicated.
So could anyone provide some hints of finding an easier $\textbf{geometric}$ approach?
Thanks in advance :)
Comment: Do you have the radius of the circle? Is it $\frac{1}{2}(BD+AD)$?
Comment: @CYKwong Oops, sorry for this mistake. The radius is 4, and I just edited it into the question.
Answer: Given two points $P$ and $Q$, the locus of points $T$ such that $TP/TQ$ is constant is a circle. In particular, the given circle is the locus of points $D$ such that $BD/B'D=2$, where $B'$ is on $OB$ and $OB'=2$.
The question can then be rephrased as follows: find $D$ on the circle such that the sum $B'D+AD$ is minimal. But this is easy, because $B'$ is inside the circle and $B'D+AD$ is minimal when $B'$, $D$ and $A$ are aligned.
In that case, from Pythagoras' theorem we get $B'D+AD=B'A=2\sqrt{10}$.
Comment: Nice! This is exactly the "easy" geometric solution I am looking for, thanks


Error Input shape is not the one expected

Question: I've seen a lot of posts about this kind of input shape error with Keras but I still don't get it.
I am trying to resolve a classification problem with Keras. My x_data (for 1 example!) is an array of arrays (4 arrays of length 40). The number of classes to predict at the end is 5.
There is a mismatch between what the first input layer expect and what I give.
Here is my model:
self.model = Sequential()
self.model.add(Dense(32,input_shape=(4,40)))
self.model.add(Dense(5, activation='softmax'))

I think the shape should be (4,40) because I give an array of 4 arrays of length 40. I think the output dimension of the last layer should be 5 because I have 5 possible classes.
Here is the format/type/shape of 1 X :
listVecteursStackBuffer:  [[ 0.05371463  0.03648512 -0.01680853      0.06098862    0.01041014  0.02132057
0.06100727 -0.06400045  0.04484718  0.00590606 -0.03110709  0.02772235
0.0506371   0.01413589 -0.00423097 -0.03948138  0.01807033 -0.03295397
0.0076106  -0.01106769 -0.06772092 -0.03330935  0.03172214  0.03577476
-0.01993138  0.02483661  0.02799152  0.02824581 -0.03390008  0.04535389
0.04143018  0.06847147 -0.02706441 -0.01303677 -0.03396893 -0.02202406
-0.05207641 -0.00764029 -0.02636093  0.05962789]
[ 0.05371463  0.03648512 -0.01680853  0.06098862  0.01041014  0.02132057
0.06100727 -0.06400045  0.04484718  0.00590606 -0.03110709  0.02772235
0.0506371   0.01413589 -0.00423097 -0.03948138  0.01807033 -0.03295397
0.0076106  -0.01106769 -0.06772092 -0.03330935  0.03172214  0.03577476
-0.01993138  0.02483661  0.02799152  0.02824581 -0.03390008  0.04535389
0.04143018  0.06847147 -0.02706441 -0.01303677 -0.03396893 -0.02202406
-0.05207641 -0.00764029 -0.02636093  0.05962789]
[ 0.27279449  0.17842792 -0.63197666  0.27222419 -0.35665196  0.65482062
-0.04437634 -0.02701205  0.05825038  0.52313662 -0.47016799  0.66000813
-0.10626637  0.44926745  0.57915986  0.17286475  0.17684783 -0.30725989
0.61364847  0.0497554   0.00937996 -0.10325015  0.27216262  0.06826591
-0.58873838  0.46360832  0.39356059  0.31463432 -0.00937746  0.53426528
0.06023555 -0.08230764 -0.51719254 -0.45349783 -0.38294923 -0.29791942
0.01553993 -0.02182218 -0.06228495 -0.01348175]
[0.09909084  0.06724796 -0.02498062  0.14459084  0.09951171  0.04242199
0.0788445  -0.11882415  0.06127726 -0.10427625 -0.14457461  0.10393921
0.08281568 -0.02970352 -0.08088119  0.04706496  0.13566148 -0.06522857
0.05304977 -0.1190851  -0.13986765  0.02461384 -0.04025699 -0.02088463
-0.07833831  0.10640202  0.01630253  0.17543195  0.04066397  0.09964696
-0.05360637  0.1918643  -0.02574791  0.04924118  0.05970795  0.03912469
-0.180988    0.07615147  0.01991141  0.01771036]]
taille listVecteursStackBuffer:  4
type listVecteursStackBuffer:  <class 'numpy.ndarray'>
shape listVecteursStackBuffer Tensor("Shape:0", shape=(2,), dtype=int32)

1er élément listVecteursStackBuffer:  [ 0.05371463  0.03648512 -0.01680853    0.06098862  0.01041014  0.02132057
0.06100727 -0.06400045  0.04484718  0.00590606 -0.03110709  0.02772235
0.0506371   0.01413589 -0.00423097 -0.03948138  0.01807033 -0.03295397
0.0076106  -0.01106769 -0.06772092 -0.03330935  0.03172214  0.03577476
-0.01993138  0.02483661  0.02799152  0.02824581 -0.03390008  0.04535389
0.04143018  0.06847147 -0.02706441 -0.01303677 -0.03396893 -0.02202406
-0.05207641 -0.00764029 -0.02636093  0.05962789]
taille 1er element listVecteursStackBuffer:  40
type 1er element listVecteursStackBuffer <class 'numpy.ndarray'>
shape 1 elelistvSB Tensor("Shape_1:0", shape=(1,), dtype=int32)

I get an error with this line of code:
self.model.predict(config_repr)

This is the error:
Traceback (most recent call last):
File "arc_eagerTagger.py", line 818, in <module>
p.static_train2(depTreeList[1:2900]) # p.dynamic_train( treebank,   step_size = 1, max_epochs = 10)
File "arc_eagerTagger.py", line 683, in static_train2
derivation =  self.static_oracle_derivation(dtree,listVecteurs,dictionnaireMots)
File "arc_eagerTagger.py", line 260, in static_oracle_derivation
C = self.shift(C,sentence,listVecteurs,dictionnaireMots)
File "arc_eagerTagger.py", line 283, in shift
return (S +  (w0,),B[1:],A,score+self.score(configuration,ArcEagerTransitionParser.SHIFT,tokens,listVecteurs,dictionnaireMots))
File "arc_eagerTagger.py", line 392, in score
return self.model.predict(config_repr)[0][index_action]
File "/home/netbook/anaconda3/lib/python3.6/site-packages/keras/models.py", line 909, in predict
return self.model.predict(x, batch_size=batch_size, verbose=verbose)
File "/home/netbook/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1499, in predict
check_batch_axis=False)
File "/home/netbook/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 128, in _standardize_input_data
str(array.shape))
ValueError: Error when checking : expected dense_1_input to have 3   dimensions, but got array with shape (4, 40)

I tried to change the input shape, I tried to concatenate the arrays to have one array of length 160 to facilitate the problem (and change the input shape with input_dim=160) but I still get errors.
Comment: What is the shape of your output?
Answer: Try this (batch_input_shape instead of input_shape):
self.model.add(Dense(units=32, batch_input_shape=[4, 40]))

See also this answer.
Answer: The problem is not in the input_shape, but in the shape of the array that you give to model.predict.
model.predict takes a batch of examples, meaning that in order to receive a single example, its shape (in your case) should be (1, 4, 40). You can do this using numpy.expand_dims:
self.model.predict(np.expand_dims(config_repr, axis = 0))


Can I set up my electric guitar with a 11-14-18-38-49-64 string-gauge set up? Could that damage my guitar?

Question: So I bought D'Addario NYXL 11-64 strings for the 7 string electric guitar. The Gauges go as follows:
11-14-18-28-38-49-64
I have a 6-string electric guitar and I was looking for strings that would let me play in tunings from Drop-D to Drop-A without my bottom string flopping at the lower tunings. However, I like the sound of lower gauge for my higher strings. So I was wondering if stringing my guitar as
11-14-18-38-49-64 could cause any problems for my guitar or would it be fine?
Answer: I believe you're asking two different questions here. No, omitting one string should not damage your guitar.
Now as far as gauges and tunings go, you simply will not find a set that will play reasonably from drop-D to drop-A. Depending on what kind of guitar your have and its scale length, the 64 will probably be too loose still for drop-A.
I'd stick with a normal set of 10's for drop-D, and then use the top 5 strings from a set of 13's and find a 72 single string for the 6th string. What kind of guitar are you planning on doing this with?
Answer: Hardly this will damage an electric guitar, (a cheap acoustic one, instead, might suffer, although acoustic use bigger gauges in the first place) but it might sound out of tune, or simply not stay in tune, as much as it used to.
You will lose sustain, though.
People generally go to bigger gauges to gain more durability out ot their mute (thin strings last less) and/or  drop the tuning lower. But .011 is a pretty standard gauge, not an extreme one, so you'll probably be fine on all accounts.
If problems arise, you might have to adjust the action or the neck, (octaves should be left alone) or simply switch back to a lighter gauge.
Answer: You can use this string tension calculator: https://tension.stringjoy.com/ to see what the approximate resulting tension will be with your scale length, string gauge, and pitch.
One thing you should avoid is putting much more tension on the neck. Especially with an acoustic guitar, this can damage the soundboard and/or bridge.
Note that this calculator is for the Stringjoy brand strings, so different materials and manufacturing processes of other brands may differ slightly. Although I think it's safe to assume the biggest changes will be due to gauge and whether the string is wound or plain.
Answer: In standard tuning, .11 is a nice fat sounding gauge, and this also works for drop D, open E and open A
For crazy stuff like drop C, get a guitar all set up for that. I like to keep thinner strings at least 4 pts apart(thickness)


Best Linux distro for load-balancers?

Question: I wanted to try HAProxy/Linux Virtual Server like front-end load-balancers, but as far I know, they're Linux-based software. I don't have any experiences with Linux yet. so there're quite many questions to ask:

What is the best Linux distro(s) for load-balancing?
I plan to use VirtualPC to run some virtual machines. How much RAM is the best for each machine run that distro? I want to simulate a load-balancer which can handle about 100 hits/second, is it possible?

Thank you very much!
Answer: The best distro for anything is the one with which you have the most experience configuring and administering.  Beyond that, they're all pretty similar.
I'd say use something like Ubuntu server LTS release, or CentOS 5.4.  Both good stable distributions, with good community support, and a regular release pattern.
You should probably look at a better virtualization solution than VirtualPC.  If you're already using linux, then KVM is a pretty natural choice.
As for RAM utilisation, think about how much you want for the base system (2-4G), then add how much you want for however many virtual machines you want (say, 4 VMs, 2G each => 8G additional RAM)
I've just re-read your question, and notice that you don't have any linux experience so far.  In this case, you'll probably find Ubuntu the most easy to get started with, it has the most comprehensive forums, IRC Channels and HowTo pages.  I've been using Ubuntu for a good number of years on desktops and servers and still find apt-get package management hard to beat.
Comment: I expected a small-fast distro, because they not actually run the web server. Can you suggest me more? :)
Comment: Ubuntu or CentOS can be small fast distros.  I can get ubuntu to boot in less than a minute, by carefully tuning the configuration not to include any unnecessary packages.
Answer: For a load balancer, debian installed off the netinst sources, minimal installation.  Install ssh, ipvs and configure.
Answer: Though I don't have any experience with it yet, for someone who is complete new to Linux and has no idea how to set this stuff up from the ground up, I've heard good things about the Zen Load Balancer which is a debian based distro that has web management and all that. Again, I haven't used it but you can find more info about it at http://www.zenloadbalancer.com/
Answer: Load balancing in most cases is done in kernel space and controlled via tc command from iproute2 package.
Any distro would do. If you have no experience with Linux go with something mainstream like Debian
Answer: The choice of the best Linux distribution for load balancers depends on various factors, including your specific needs, expertise, and preferences. However, some popular and widely used Linux distributions for load balancers are:
Ubuntu Server: Ubuntu is known for its user-friendly interface and extensive community support. It has a robust server edition optimized for performance and scalability, making it a popular choice for load balancers.
CentOS: CentOS is a stable and reliable distribution based on Red Hat Enterprise Linux (RHEL). It is well-suited for server deployments and provides long-term support, which is crucial for load balancers.
Debian: Debian is a versatile and stable Linux distribution with a focus on free and open-source software. Its solid reputation for stability makes it a good option for load balancers.
Red Hat Enterprise Linux (RHEL): RHEL is a commercial Linux distribution that offers excellent support and security features. For organizations that prioritize enterprise-level support, RHEL can be a top choice.
Fedora Server: Fedora is a cutting-edge distribution that serves as a testing ground for features later incorporated into RHEL. If you want to stay on the leading edge of technology, Fedora can be a suitable option.
OpenSUSE: OpenSUSE is a community-driven distribution known for its stability and versatility. It has server editions that can be tailored for load balancer deployments.
Alpine Linux: If you need a lightweight and minimalist Linux distribution for your load balancers, Alpine Linux can be a good fit. It is designed for efficiency and security, making it suitable for resource-constrained environments.
Remember that the effectiveness of a load balancer relies not only on the Linux distribution but also on the software you choose to handle the load balancing, such as Nginx, HAProxy, or others. Additionally, configuring load balancers properly and considering your specific requirements are crucial in making the best choice for your load balancing needs.
Comment: Looks like a completely useless generic post from  a spam profile
Comment: SpamGPT rules :( We see more and more of that.

Best Linux distro for load-balancers?


smtp relay shows temporary lookup failure

Question: We deploy a new smtp relay server in ubuntu. When send test email from the root the mail flows properly. But when we use it as relay server it shows "temporary lookup failure"
Where should we need to config in the postfix. Need some help. Here is our postfixs main.cf file
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no
# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
mydomain = efftelsolutions.net
myhostname = netexsmtp.efftelsolutions.net
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = $myhostname, smtp.solutions.net, localhost.solutions.net, , localhost
relayhost =
mynetworks = 127.0.0.0/8 184.108.40.206/27 18.104.22.168 126.96.36.199/27
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all

Answer: you have error in mynetworks section, you need to specify correct network addresses (beginig of the range, not gateway address)
mynetworks = 127.0.0.0/8 126.96.36.199/27 188.8.131.52 126.96.36.199/27

Comment: Thanks for the feedback. Corrected the network address and it works.


Views: Display number of nodes published by author on profile

Question: Using Views, I can create a list of authors, and show the number of nodes that they have published. I've done this using aggregation. The part I can't figure out is how to filter the output based on the user profile that you're viewing. For example, if you're viewing user/1, I want you to see the number of nodes that user 1 has published.
I've tried using different uid contextual filters. In this example, I'm using "User: Uid" as the filter, and I'm trying to pull the uid from the URL by selecting "'Provide default value' > 'Use ID from URL'" in the filter's options. Since aggregation settings are on, you have to apply an aggregation type to the filter, and I'm not sure what that should be set on.
Any feedback would be appreciated. By the way, I'm using Display Suite to build the profile layout, so if there's an easier way to get want I need, I'm open for suggestions. Thanks in advance.
EDIT: For anyone attempting to do this, keep in mind that your output will not show up in the Views preview. I was forced to navigate to a user profile in order to test this. This issue seems to sprout from the combination of aggregation and contextual filters.
Comment: 1. Are you using D7? 2. As your title described `Views: Display number of nodes published......` Are you just want to display Numbers or Titles. 3. Are you wan to make views as Block view?
Comment: 1. Yes. 2. In the example, I have the author field, but only for testing. The final product will only output the number of articles published by each user on their profile page. 3. Yes, I'm outputting the View as a block. That will allow me to bring it into DS as a custom field.
Comment: *I'm using Display Suite to build the profile layout,* as you have described this way to change the layout, Have tried by yourself, whether it is working? Why I am asking this all, because already I am working on User profile page altering since some day. But the issue is, User profile page is generated by default, Now, Does display suit allow to make the change on that page without playing with that original path?
Comment: Display Suite simply overwrites the default Drupal profile page. It doesn't alter the path to the profile.
Comment: Ok, that is the good, I will try on my trial site and will update you, if I achieve.
Answer: In my opinion, You do not need Display suite to achieve this. You can do this in very Simple Drupal way .
1. Your views configuration if perfectly fine. I am just posting my one for reference purpose, Where I did two changes, (1) In the pager setting, I have set the pager item to 1. (2) I removed the User: name as it is not needed.
Note: You do not need to anything with aggregation setting at filter level.

2. From your views it is visible that you have created block.
3. Now, What you need to do is put that block in your user profile, so it looks like as a one of the field of user profile.
4. How to do that:
4.1 Place that Block under  Main page content in Content region on as shown in following image.

4.2 Set the display rule for this block as shown in following image. So what happens, the block are visible only on the user profile page.

4.3 Set the Role permission for the User Role, so other user can see teh profile page of other's Or anonymous users also can see teh profile page of other's: I am sure you are aware of all this.
5. Output Image: As you can see, I have tried in my Bartik theme. I have just given block title,  So it can distinguished in the image. Note: I have removed User:name field from the views, as it is not necessary. The views will automatically detect from the url.

**Other example from other login **

Hence, this way without using any other display help, you can add the new field in the User profile. So you do not have to much play with the User profile page.
Comment: **Additional Note:** If you want you can put this block through Display Suit or Using Panel module, the way you want. This Block view should work with all three, as this block takes ID from url. So it should work Provided that url will have the `User ID`
Answer: Not the best approach, aggregation could get ugly if user creates 100 or 1000 nodes.
You're better off adding/creating a numeric field in User Manage Fields.

Use Content Access module to hide the field from edit view, so only admins can see it in the user edit form (Edit own content only ☑ Administrator).
With Rules when node is added/deleted, you +1/-1 the user numeric field.
Similarly to +1 user field after comment is made
Comment: I may be able to hide the field using Display Suite. I'll do some testing tomorrow with Rules to see if I can achieve the desired result. Thanks for the tip! I'll follow up on whether or not this works.
Comment: Following CodeNext's directions, I was able to achieve the desired output. You mentioned that aggregation could get ugly if a user creates 100 or 1000 nodes? Is there something about aggregation that I should worry about before I proceed with using it as the solution?
Comment: Lets just say my method will always give you the optimal performance. What do you think is faster, to count how many nodes user x has? or have someone give you the answer?


Glassfish admin console faile

Question: I use glassfish 3.0.1 on windows 2003 with JDK 6u24.
When I start the server and try to login to the admin console (4848) I will receive this error message:
[#|2011-02-24T12:59:37.578+0330|INFO|glassfish3.0.1|javax.enterprise.system.std.
com.sun.enterprise.v3.services.impl|_ThreadID=25;_ThreadName=http-thread-pool-48
48-(2);|Cannot refresh Catalog : Connection timed out: connect|#]

Update
[#|2011-02-24T12:58:51.343+0330|INFO|glassfish3.0.1|null|_ThreadID=24;_ThreadNam
e=Thread-23;|The Admin Console is already installed, but not yet loaded.|#]

[#|2011-02-24T12:58:51.343+0330|INFO|glassfish3.0.1|null|_ThreadID=24;_ThreadNam
e=Thread-23;|The Admin Console is loading...|#]

[#|2011-02-24T12:58:52.296+0330|INFO|glassfish3.0.1|javax.enterprise.system.cont
ainer.web.com.sun.enterprise.web|_ThreadID=24;_ThreadName=Thread-23;|Created HTT
P listener http-listener-1 on port 80|#]

[#|2011-02-24T12:58:52.296+0330|INFO|glassfish3.0.1|javax.enterprise.system.cont
ainer.web.com.sun.enterprise.web|_ThreadID=24;_ThreadName=Thread-23;|Created HTT
P listener http-listener-2 on port 8181|#]

[#|2011-02-24T12:58:52.296+0330|INFO|glassfish3.0.1|javax.enterprise.system.cont
ainer.web.com.sun.enterprise.web|_ThreadID=24;_ThreadName=Thread-23;|Created HTT
P listener admin-listener on port 4848|#]

[#|2011-02-24T12:58:52.343+0330|INFO|glassfish3.0.1|javax.enterprise.system.cont
ainer.web.com.sun.enterprise.web|_ThreadID=24;_ThreadName=Thread-23;|Created vir
tual server server|#]

[#|2011-02-24T12:58:52.343+0330|INFO|glassfish3.0.1|javax.enterprise.system.cont
ainer.web.com.sun.enterprise.web|_ThreadID=24;_ThreadName=Thread-23;|Created vir
tual server __asadmin|#]

[#|2011-02-24T12:58:53.531+0330|INFO|glassfish3.0.1|javax.enterprise.system.cont
ainer.web.com.sun.enterprise.web|_ThreadID=24;_ThreadName=Thread-23;|Virtual ser
ver server loaded system default web module|#]

[#|2011-02-24T12:58:54.671+0330|INFO|glassfish3.0.1|javax.enterprise.system.core
.security.com.sun.enterprise.security|_ThreadID=24;_ThreadName=Thread-23;|SEC100
2: Security Manager is OFF.|#]

[#|2011-02-24T12:58:54.937+0330|INFO|glassfish3.0.1|javax.enterprise.system.core
.security.com.sun.enterprise.security|_ThreadID=24;_ThreadName=Thread-23;|Securi
ty startup service called|#]

[#|2011-02-24T12:58:54.953+0330|INFO|glassfish3.0.1|javax.enterprise.system.core
.security.com.sun.enterprise.security|_ThreadID=24;_ThreadName=Thread-23;|SEC114
3: Loading policy provider com.sun.enterprise.security.provider.PolicyWrapper.|#
]

[#|2011-02-24T12:58:55.062+0330|INFO|glassfish3.0.1|javax.enterprise.system.core
.security.com.sun.enterprise.security.auth.realm|_ThreadID=24;_ThreadName=Thread
-23;|Realm admin-realm of classtype com.sun.enterprise.security.auth.realm.file.
FileRealm successfully created.|#]

[#|2011-02-24T12:58:55.062+0330|INFO|glassfish3.0.1|javax.enterprise.system.core
.security.com.sun.enterprise.security.auth.realm|_ThreadID=24;_ThreadName=Thread
-23;|Realm file of classtype com.sun.enterprise.security.auth.realm.file.FileRea
lm successfully created.|#]

[#|2011-02-24T12:58:55.062+0330|INFO|glassfish3.0.1|javax.enterprise.system.core
.security.com.sun.enterprise.security.auth.realm|_ThreadID=24;_ThreadName=Thread
-23;|Realm certificate of classtype com.sun.enterprise.security.auth.realm.certi
ficate.CertificateRealm successfully created.|#]

[#|2011-02-24T12:58:55.078+0330|INFO|glassfish3.0.1|javax.enterprise.system.core
.security.com.sun.enterprise.security|_ThreadID=24;_ThreadName=Thread-23;|Securi
ty service(s) started successfully....|#]

[#|2011-02-24T12:58:56.687+0330|INFO|glassfish3.0.1|javax.enterprise.resource.we
bcontainer.jsf.config|_ThreadID=24;_ThreadName=Thread-23;|Initializing Mojarra 2
.0.2 (FCS b10) for context ''|#]

[#|2011-02-24T12:58:58.546+0330|INFO|glassfish3.0.1|javax.enterprise.system.cont
ainer.web.com.sun.enterprise.web|_ThreadID=24;_ThreadName=Thread-23;|Loading app
lication __admingui at /|#]

[#|2011-02-24T12:58:58.546+0330|INFO|glassfish3.0.1|null|_ThreadID=24;_ThreadNam
e=Thread-23;|Loading __admingui Application done is 7203 ms|#]

[#|2011-02-24T12:58:58.546+0330|INFO|glassfish3.0.1|null|_ThreadID=24;_ThreadNam
e=Thread-23;|The Admin Console application is loaded.|#]

[#|2011-02-24T12:59:02.515+0330|INFO|glassfish3.0.1|javax.enterprise.system.tool
s.admin.org.glassfish.server|_ThreadID=25;_ThreadName=http-thread-pool-4848-(2);
|AMX ComplianceMonitor: ValidationLevel = full, UnregisterNonCompliant = false,
LogInaccessibleAttributes = true|#]

[#|2011-02-24T12:59:02.828+0330|INFO|glassfish3.0.1|javax.enterprise.system.tool
s.admin.org.glassfish.server|_ThreadID=26;_ThreadName=Thread-24;|AMX config read
, domain config registered as amx:pp=/,type=domain|#]

[#|2011-02-24T12:59:03.046+0330|INFO|glassfish3.0.1|javax.enterprise.system.tool
s.admin.org.glassfish.server|_ThreadID=27;_ThreadName=Thread-27;|J2EEDomain regi
stered at amx:pp=/,type=J2EEDomain,j2eeType=J2EEDomain,name=amx|#]

[#|2011-02-24T12:59:03.046+0330|INFO|glassfish3.0.1|javax.enterprise.system.tool
s.admin.org.glassfish.server|_ThreadID=25;_ThreadName=http-thread-pool-4848-(2);
|AMXStartupServiceNew: AMX ready for use, DomainRoot = amx:pp=,type=domain-root|
#]

[#|2011-02-24T12:59:10.843+0330|WARNING|glassfish3.0.1|javax.enterprise.system.c
ontainer.web.com.sun.web.security|_ThreadID=25;_ThreadName=http-thread-pool-4848
-(2);|Web login failed: Login failed: javax.security.auth.login.LoginException:
Failed file login for admin.|#]

[#|2011-02-24T12:59:10.843+0330|WARNING|glassfish3.0.1|org.apache.catalina.conne
ctor.Request|_ThreadID=25;_ThreadName=http-thread-pool-4848-(2);|PWC4011: Unable
 to set request character encoding to UTF-8 from context , because request param
eters have already been read, or ServletRequest.getReader() has already been cal
led|#]

[#|2011-02-24T12:59:16.093+0330|INFO|glassfish3.0.1|org.glassfish.admingui|_Thre
adID=25;_ThreadName=http-thread-pool-4848-(2);|admin console: initSessionAttribu
tes()|#]

[#|2011-02-24T12:59:37.578+0330|INFO|glassfish3.0.1|javax.enterprise.system.std.
com.sun.enterprise.v3.services.impl|_ThreadID=25;_ThreadName=http-thread-pool-48
48-(2);|Cannot refresh Catalog : Connection timed out: connect|#]

[#|2011-02-24T13:08:09.015+0330|INFO|glassfish3.0.1|org.glassfish.admingui|_Thre
adID=28;_ThreadName=http-thread-pool-4848-(1);|admin console: initSessionAttribu
tes()|#]

[#|2011-02-24T13:08:30.125+0330|INFO|glassfish3.0.1|javax.enterprise.system.std.
com.sun.enterprise.v3.services.impl|_ThreadID=28;_ThreadName=http-thread-pool-48
48-(1);|Cannot refresh Catalog : Connection timed out: connect|#]

[#|2011-02-24T13:14:16.546+0330|WARNING|glassfish3.0.1|com.sun.grizzly.config.Gr
izzlyServiceListener|_ThreadID=17;_ThreadName=Thread-13;|Interrupting idle Threa
d: http-thread-pool-4848-(2)|#]

Comment: can you please put some more stacktrace
Comment: sure, I will update the question...
Answer: It seems that Glassfish has a lot of trouble recently caused by the new version 3.1. The admin console tries to look for new updates at start-up. If the update server will not respond in a certain time, the update count fails or take a long time.
You could first try to choose a different update server with glassfishs update tool. You will find it in glassfish/bin folder.
If this doesn't work, you could disable the update module of the glassfish admin console by renaming the file console-updatecenter-plugin.jar in the folder glassfish/glassfish/modules.
You could also disable network access from the admin console by adding the following to the JVM-Options of your domain.xml:

-Dcom.sun.enterprise.tools.admingui.NO_NETWORK=true

Glassfish admin console faile


Find records from table A that have certain JOINS into table C on the other side of pivot B, but not others

Question: I have 3 tables products, product_stores and stores. There's only a few entries in the stores table, and product_stores records basically means we know a certain products are carried at certain stores.
What we want to find is a set of products that are carried in stores 2, 3, 4, 5, but NOT in store 9.
Here's what I've got so far, unsure I'm on the right track, but it looks kind of close. I've got all the records where we know a product exists, but can't get the stores where the product isn't carried JOIN(ed) in...
SELECT s.id AS store_id, ps.id AS product_store_id, p.id AS product_id
FROM stores s
LEFT JOIN product_stores ps ON ps.store_id = s.id
RIGHT JOIN products p ON p.id = ps.product_id AND p.id = 8
HAVING store_id IN (2, 3, 4, 5, 9)

This produces
+----------+------------------+------------+
| store_id | product_store_id | product_id |
+----------+------------------+------------+
|        2 |           178455 |          8 |
|        3 |                8 |          8 |
|        4 |           178454 |          8 |
|        5 |           178453 |          8 |
+----------+------------------+------------+

What I want to see instead is this
+----------+------------------+------------+
| store_id | product_store_id | product_id |
+----------+------------------+------------+
|        2 |           178455 |          8 |
|        3 |                8 |          8 |
|        4 |           178454 |          8 |
|        5 |           178453 |          8 |
|        9 |             NULL |          8 |
+----------+------------------+------------+

Or since I really just want a unique list of product_id(s), something that flattens it out into a result set with unique product_id(s).
We're using MySQL. You should be able to see the relationships between the tables from my current query, but LMK if you need additional info. The AND p.id = 8 is only there to limit the result set for testing purposes.
Comment: have you a fiddle example ? you have 5k and you didnt give fiddle ?
Comment: A fiddle? I've never used fiddle before...
Comment: http://www.sqlfiddle.com/
Answer: Inner joins should be fine for this:
SELECT ps.product_id
FROM stores s INNER JOIN
     product_stores ps
     ON ps.store_id = s.id
GROUP BY ps.product_id
HAVING SUM(store_id = 2) > 0 and
       SUM(stored_id = 3) > 0 and
       SUM(stored_id = 4) > 0 and
       SUM(stored_id = 5) > 0 and
       SUM(stored_id = 9) = 0;

Each condition in the having clause tests that the product is in one of the stores.  The sum() calculates the number of rows in the store and the > 0 says there is at least one for stores 2-5.  The = 0 means that the product is not in store 9.


UITableView with custom class

Question: I have created a derived class from UITableView which will contain some custom logic. But I am not sure how to get it to populate cells.
h. file:
@interface MetricsView : UITableView {
    @private
    NSMutableArray *_items;
}
@end

m. file:
    @implementation MetricsView

    //this gets called
    - (id)initWithCoder:(NSCoder *)aDecoder
    {
        self = [super initWithCoder:aDecoder];
        if (self) {
            _items = [[NSMutableArray alloc]initWithObjects:@"Name:", nil];
        }
        return self;
    }

//this never gets called??
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }

    //this never gets called??
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [_items count];
    }

//this never gets called??
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        NSString *cellIdentifier = @"MetricsViewCell";

        MetricsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

        [cell setupWithName:[_items objectAtIndex:0] withData:[_items objectAtIndex:0]];
        return cell;
    }

    @end

I created MetricsView on top of my ViewController. Here's what storyboard looks like:

Do I need to add some custom initialization code inside ViewController.m?
Thanks.
Answer: //this never gets called??
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

That and the other methods are data source methods. They will not be called unless you set this class as the table view's data source.
Oddly, you have put this code inside the UITableView subclass itself. Okay, that's weird and it violates MVC, but you can do it if you really want to. But then you must set the UITableView subclass as its own data source (and, presumably, its own delegate). That isn't going to happen all by itself; you must do it.
LATER EDIT: However, in general I would cast doubt on the need and desirability of subclassing UITableView in the first place. It's hard for me to think of a situation where this would be useful to do. Just put your table view in the interface, hook its delegate and datasource outlets to the View Controller, and you're done. Now the view controller gets the numberOfSectionsInTableView: and other calls, as rightly it should.
Comment: I think he just didn't figured yet the difference between the UITableView subclass itself and the delegate/data source.
Comment: @Nicolas I vaguely understand it. Just started learning Objective C.
Comment: do I add  to my MetricsView interface and then link it via storyboard somehow?
Comment: you can add  to any custom class you want. What you need is to set your tableview.delegate = customClass and your tableview.dataSource = customClass so that your tableview know where to look for data
Comment: @MikhailNaumov Here are the relevant sections of my book: [Delegate](http://www.apeth.com/iOSBook/ch11.html#_delegation) — [Data source](http://www.apeth.com/iOSBook/ch11.html#_data_sources) — [Table view data in general](http://www.apeth.com/iOSBook/ch21.html#_table_view_data)
Answer: Well let's put things straight. Your UITableView is the view. You can indeed subclass it but it does not seems to be what you want. What I feel you're trying to do is create your custom UITableView delegate and dataSource. Meaning a custom class that does obey to those two protocol. You don't need to subclass your UITableView but you need to set your custom class to be the delegate of your UITableView. And in this class you will be able to implement the method you're trying to implement (-cell for row at index path, -number of row in section, -number of section). What you need is to subclass the well where your tableview will get the water (water being info on what to put in the cell and how many cell to create). I hope this will help!
Comment: so now I receive "malloc: *** error for object 0x75610453: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug" after I call setDataSource. My MetricsView is no longer a custom class, just default UITableView. Do I need to call metricsView alloc myself?

UITableView with custom class


How do the eigenpairs of a matrix change after some matrix multiplication?

Question: I am interested to know if there is a way to find the eigenpairs of matrix $AT$ or $TA$ from $A$, where $A$ is an arbitrary matrix and $T$ is some transform matrix.
Edit
$$AV = \lambda V$$
$$(TA)V_1 = \lambda_1 V_1$$
$$(AT)V_2 = \lambda_2 V_2$$
Is there a relation between $V,V_1,V_2$ using $T$?
Comment: No, in general both the eigenvalues and the eigenvectors change except in some particular cases such as when $T$ is diagonal matrix, or when $T$ has the same eigenvectors of $A$, in which cases the eigenvalues may change while the eigenvectors remain the same.
Comment: Consider the case of a nonsingular matrix $A$ and $T=A^{-1}$. Consider also the case of $T=JA^{-1}$ where $J$ is any Jordan block.
Comment: Your reasoning does not hold, $(TA)v = \lambda (Tv)$ does not mean that $Tv$ is an eigenvector of $TA$.
Comment: What is "the transform matrix"? Any arbitrary matrix? Or do you mean one that corresponds to change of basis?
Comment: If $T$ corresponds to some change of basis, then the eigenvalues will be unchanged, and the eigenvectors will be transformed by the same change of basis matrix.
Comment: Sorry, I think I might have misread the question, my original claim isn't true because $TA$ is not actually the same linear transformation under change of basis. For your second question, it is in fact the case that $TAT^{-1}$ can be thought of as the same linear transformation after a change of coordinates described by $T$. In this case if $Av=\lambda v$ then $TAT^{-1}(Tv) = TAv = \lambda(Tv)$ so $Tv$ is an eigenvector of $TAT^{-1}$. This is not true for $TA$ because e.g. take $A$ the identity and $T$ a rotation of $\mathbb R^2$, which has no eigenvectors. Not sure what $P$ is supposed to be.
Comment: I could expand this into an answer if you wish. Are you interested in the general case or just for rotations of $\mathbb R^2$?
Comment: @HoseinJavanmardi To answer those questions, you can just pick up examples. But, in general everything changes.
Comment: @YiFan What happens if $T$ is a special matrix?
Comment: @Paul Yes, I have edited accordingly.
Comment: @YiFan Interesting. This is what I meant. If possible, please provide an example using rotation matrices in 2-D basis (including proof) so I can accept your answer.
Comment: @YiFan, I had another question if you had time. some transforms are in the form of $T^{-1}AT$, or $P^{-1}AT$. how about them?
Comment: @YiFan These are all very interesting. yes please just stick to $\mathbb R^2$ so I can better understand. I would appreciate if you could explain anything related in answer. and about rotation, I had the idea that since only angle is sufficient to describe eigenvectors (if normalized), rotation would transform them to any vectors.
Comment: @KBS What happens when $T$ is diagonal (with non identical entries)?
Answer: Matrix multiplication essentially corresponds to composing linear transformations on some vector space. For this reason, there is no reason to expect that there would be a nice relationship between eigenvectors and eigenvalues after the transformation. For example, let $A,T\colon\mathbb R^2\to\mathbb R^2$ where $$A=\begin{bmatrix}1&0\\ 0&1\end{bmatrix}, T=R_\theta=\begin{bmatrix}\cos\theta & \sin\theta \\ -\sin\theta & \cos\theta\end{bmatrix}$$
so $A$ is the identity, and $R_\theta$ is rotation counterclockwise by angle $\theta$. Now, if $\theta$ is a generic angle like, say, $\pi/3$, then $T$ has no eigenvectors, because everything is rotated and nothing is fixed in direction. This shows we cannot have some kind of relation between the eigenvectors of $A$ and $TA$, nor between $A$ and $AT$, because eigenvectors might not even exist in the first place!
On the other hand, there is something meaningful to be said about $TAT^{-1}$. Notice that, algebraically, $TAT^{-1}(Tv)=TAv = T\lambda v = \lambda(Tv)$ given any eigenvector $Av=\lambda v$. Thus the eigenvectors are transformed by $T$, and eigenvalues remain fixed. This is conceptually because any expression of the type $TAT^{-1}$ can be interpreted as a change of basis according to $T$, and $Tv$ is simply the expression for the vector in terms of the new coordinates. This holds whenever $T$ is invertible.


spring integration dsl filter instead filter method annotation

Question: How can I switch from filter annotation method to Spring integration java DSL filter. how can I call filter method?
IntegrationFlows.from("removeSession")
                // remove chat session from user sessions map
                .handle("sessionLogService", "removeChatSession")
                // continue and remove user from ehcache only if user have no more opened sessions.
                .filter(/* what's going here? */)
                .get();

instead Filter annotation.
@Filter(inputChannel = "userGoOfflineFilter", outputChannel = "userGoOffline")
    public boolean notifyOnlyIfLastConnectionClosed(SecureUser secureUser) {
        ChatUser user = sessionUtils.getChatUser(secureUser.getId());
        if(user == null || user.getChatSessionIds() == null || user.getChatSessionIds().isEmpty())
            return true;
        LOGGER.debug(secureUser.getFirstName()+": Offline message not sent yet");
        return false;
    }

Answer: There are several overloaded .filter() methods on IntegrationFlowDefinition. Take a look at the javadocs, but
filter("expression");

takes a SpEL expression. It could be a bean reference, such as
.filter("@myFilter.notifyOnlyIfLastConnectionClosed('payload')")

or you can use a GenericSelector...
.filter(SecureUser.class, u -> u == null || u.getChatSessionIds() == null || u.getChatSessionIds().isEmpty())

(java 8 lambda) or
.filter(new GenericSelector<SecureUser>() {
                    @Override
                    public boolean accept(SecureUser u) {
                        return u == null || u.getChatSessionIds() == null || u.getChatSessionIds().isEmpty();
                    }
                })

(java 6/7).
etc.
Comment: Thank you very much this .filter("@myFilter.notifyOnlyIfLastConnectionClosed('payload')") work perfect and I like it. :)


What's the right stats test?

Question: Could anyone tell me what would be a suitable stats test to look at relationships between 4 continuous IVs and 1 continuous DV between 2 groups each of which has 2 levels i.e. male - female and internet users - non internet users?
Comment: Depends what the dependent variable is.  A suitable regression may be able to handle it
Comment: I started out wanting to do a multiple regression but since there's 2 groups (gender and user vs non user) I thought that meant I'd need to do a moderated multiple regression, which seemed clumsy. The DV is stress (continuous scale)
Answer: There are several approaches, depending on what you hope to understand and what you expect out of your continuous IVs. One approach would be a split-plot or mixed ANOVA where each case yields a single point (mean, for instance) for the DV, each IV, and a categorical label for male/female and user/not user. You'll then get main effects and interactions for each combination of 6 IVs (4 continuous, 2 nominal) on the DV.
Comment: That looks really interesting thanks. I hadn't heard of it (I have no business being on this website!). I'm very new to stats so I really appreciate your advice! I'm going to go read up on that test :)
Comment: Consult a statistician!  There's are more ways to do this incorrectly than correctly and most software won't tell you.
Comment: Heitz I don't actually have to do the test at all so software's not a problem. I only have to say what stats test I would hypothetically use to look at the relationship between the 4 IVs and the 1DV in those 2 groups. It's for a proposal ... but I won't be doing the study after :)
Answer: Among the other possibilities that @Heitz alludes to are:
a) "Regular" regression with dummy variables and interactions between the dummies and the continuous variables. (I believe this is mathematically equivalent to the ANOVA he recommends, but the output will look different). This produces one regression equation, but interpretation is a little tricky if you are not use to looking at interactions.
b) Stratifying on the categorical variables. This would produce four different regressions, which is simpler to look at that than 1) but it won't produce statistics for the interactions so you won't know things like p values and effect sizes and standard errors for those (or for the main effects of the categorical variables themselves).
c) Regression trees and their offshoots (forests etc.)

What's the right stats test?


Problema na função supre

Question: Estou aqui com um problema nesta função int supre    (char s1[ ], char s2[  ]) , que calcula o tamanho do maior sufixo de s1 que é prefixo de s2. Por exemplo se tiver supre ("batota" , "totalidade") deve retornar 4, uma vez que a string "tota" é sufixo de "batota" que é prefixo de "totalidade".
Tentei fazer esta função com o auxilio da função strrev ( ) para comparar carater a carater , mas não deu grande sucesso ..
Se houver alguma função que me ajude , qual devo usar? E é possivel fazer sem ajuda de funções auxiliares?
Comment: Coloque o que você já fez para a gente ter uma ideia do que está tentando fazer. Mesmo que tenha problemas e esteja incompleto.
Comment: eu fazia uma solução tipo recursiva que vai testando substrings de `s1` cada vez mais pequenas: eg ... 1) `"batota"` não é sufixo de `"totalidade"` 2) `"atota"` não é sufixo de `"totalidade"` 3) `"tota"` é sufixo de `"totalidade"`
Comment: @OP, você deseja uma maneira para resolver o problema ou quer dicas para resovê-lo?
Answer: Esse é um porbleminha que embora simples, não tem mágica pra resolver:
é um algoritmo simples, que a gente consegue pensar e entender como resolver "manualmente" - e o caminho é entender o algoritmo, e depois transcrever para C.
Você tem um conjunto de ferramentas que são as funções par amanipulação de string da biblioteca padrão do C,e  a verificação direta dos caractéres.  Você também pode escrever suas funções se não houver alguma.
Mas então - perceba que é um algoritmo em "etapas" - não é uma coisa de 3 ou 4 linhas - por que você vai ter que no mínimo achar o ponto inícial de busca, e comparar os caracteres a partir dali.
Então, o pseudo-algoritmo em portugues, poderia começar assim:

prepare uma string vazia de resposta S3.
achar se há,e a posição N do primeiro caractere de S2 dentro de S1;
Se não houver N, retorne dizendo que o sufixo é a string vazia
crie um contador i = 0;
checkpoint
copie o caractere S1[N] para a string de resposta S3
Incremente o valor de i
se o caractere em S1[N+i] é o final da string (caractere '\x00') - a resposta é o que temos em S3: acresente um mcarcador de final de string em S3 e  retorne S3 (faça o mesmo se chegou ao final de S2)
compare o caractere  N + i em S2 com o caractere na posição (0 + i) de S2;
se são diferentes, zere a string S3, e retorne um sufixo vazio (** mas veja a nota abaixo)
retorne para "checkpoint"

Poronto -agora você traduz isso para "C" - e perceba que na descriçao em portugues surge naturalmente o que será um laço "for" ou "while' em linguagem de programação.
** - ha uma pegadinha nesse algoritmo aí - se a primeira letra da segunda palavra ocorrer mais de uma vez na primeira palavra, a descrição acima não dá conta.  (por exemplo: "batota",  e "tarifa" -
ele vai achar o primerio "t" de "batota", mas vai parar a busca no "o" - quando o sufixo está após o segundo "t") - ou você repete a busca por "t", ou- pra começar tudo, procura pela primeira letra de S2 em S1, mas da direita para a esquerda -  essa segunda alternativa é muito mais fácil, mas acho que você não terá uma função pronta na stdlib de C para isso - então vai fazer sua própria funçãozinha pra isso (acredite, vale a pena):

procure pela letra X em S1 a partir do final:
faça i igual o comprimento total de S1
heckpoint`verifique se o caractere S1[i] é X - se sim, retorne i
decremente i
se i for menor que zero, retorn i (e aproveite o
retorno de -1 como indicação de que a letra não existem em S1)
vá para checkpoint

--Pronto agora você já tem onde começar. Não é o propóstio do S.O. dar respostas prontas - então tente traduzir isso para C.

Problema na função supre


Script não aparece ao carregar em Section

Question: Tenho uma Section chamada Scripts (a que vem configurada por padrão):
<code>@RenderSection("scripts", required: false)
</code>
E estou tentando carregar o Plugin TinyMCE da seguinte maneira:
<code>@section Scripts {
    <script src="~/email@example.com()" type="text/javascript"></script>
    <script type="text/javascript">

        tinymce.init({
            mode: "textareas",
            plugins: "table",
            content_css: "css/content.css",
            style_formats: [
                { title: 'Bold text', inline: 'b' },
                { title: 'Red text', inline: 'span', styles: { color: '#ff0000' } },
                { title: 'Red header', block: 'h1', styles: { color: '#ff0000' } },
                { title: 'Example 1', inline: 'span', classes: 'example1' },
                { title: 'Example 2', inline: 'span', classes: 'example2' },
                { title: 'Table styles' },
                { title: 'Table row 1', selector: 'tr', classes: 'tablerow1' }
            ],
            formats: {
                alignleft: { selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'left' },
                aligncenter: { selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'center' },
                alignright: { selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'right' },
                alignfull: { selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'full' },
                bold: { inline: 'span', 'classes': 'bold' },
                italic: { inline: 'span', 'classes': 'italic' },
                underline: { inline: 'span', 'classes': 'underline', exact: true },
                strikethrough: { inline: 'del' },
                customformat: { inline: 'span', styles: { color: '#00ff00', fontSize: '20px' }, attributes: { title: 'My custom format' } }
            }
        });
    </script>
}
</code>
Entretanto ele não carrega o Plugin, apenas se eu der F5 na página, aí carrega.
O que há de errado?
Answer: Possivelmente está inicializando o plugin antes de terminar a carga da página.
Experimente verificar quando a página está carregada para carregar o plugin:
<code>@section Scripts {
    <script src="~/email@example.com()" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {
           tinymce.init({ ... });
        }
    ...
}
</code>
Comment: Não funciona dessa forma também, o que fiz, foi colocar aquele bloco de configuração do plugin em uma function, e usar setTimeout para chamar essa função, aparentemente deu certo, funciona, mas não sei se é correto fazer isso


Alter user's entity label method

Question: By default the label() method of the user entity returns the username. So everywhere on the website where user references are used, the username is displayed.
I need to alter this method so everywhere the user name is displayed it will use my custom function. So instead of "custom_user_name" will display "Firstname Lastname" for example.
Any idea on how to achieve this? Thanks.
Comment: Along with Clives answer, another simple way to do this would be to get RealName module. It will let you construct a username based on tokens from the UI. https://www.drupal.org/project/realname
Answer: I'm not sure if there's a shortcut for that, but if not the steps are still quite minimal:

Sub-class the \Drupal\user\Entity\User class in a custom module, and override its label() method:
mymodule/src/Entity/User.php
namespace Drupal\mymodule\Entity;

use Drupal\user\Entity\User as CoreUser;

class User extends CoreUser {

  public function label() {
    return 'something new';
  }

}

Implement hook_entity_type_alter() to set the class for the User entity type:
function MYMODULE_entity_type_alter(&$entity_types) {
  $entity_types['user']->setClass(\Drupal\mymodule\Entity\User::class);
}

Rebuild the cache
Answer: The above example is not something you probably want to do, it may not work the way you want it to work. For example, default user listing will show you usernames with class override.
Also overriding the user class may not be even possible in some cases.
There is shortcut to edit the label with hook;
/**
 * Implements hook_user_format_name_alter().
 */
function MYMODULE_user_format_name_alter(&$name, \Drupal\Core\Session\AccountInterface $account) {
  $user = $account instanceof \Drupal\user\UserInterface ?
    $account :
    \Drupal::entityTypeManager()->getStorage('user')->load($account->id());
  $name = $user->get('my_field')->value;
}

Alter user's entity label method


Combining auto.arima() and ets() from the forecast package

Question: I've been using the ets() and auto.arima() functions from the forecast package to forecast a large number of univariate time series.  I've been using the following function to choose between the 2 methods, but I was wondering if CrossValidated had any better (or less naive) ideas for automatic forecasting.
auto.ts <- function(x,ic="aic") {
    XP=ets(x, ic=ic)
    AR=auto.arima(x, ic=ic)

    if (get(ic,AR)<get(ic,XP)) {
        model<-AR
    }
    else {
        model<-XP
    }
        model
}

/edit: What about this function?
auto.ts <- function(x,ic="aic",holdout=0) {
    S<-start(x)[1]+(start(x)[2]-1)/frequency(x) #Convert YM vector to decimal year
    E<-end(x)[1]+(end(x)[2]-1)/frequency(x)
    holdout<-holdout/frequency(x) #Convert holdout in months to decimal year
    fitperiod<-window(x,S,E-holdout) #Determine fit window

    if (holdout==0) {
        testperiod<-fitperiod
    }
    else {
        testperiod<-window(x,E-holdout+1/frequency(x),E) #Determine test window
    }

    XP=ets(fitperiod, ic=ic)
    AR=auto.arima(fitperiod, ic=ic)

    if (holdout==0) {
        AR_acc<-accuracy(AR)
        XP_acc<-accuracy(XP)
    }
    else {
        AR_acc<-accuracy(forecast(AR,holdout*frequency(x)),testperiod)
        XP_acc<-accuracy(forecast(XP,holdout*frequency(x)),testperiod)
    }

    if (AR_acc[3]<XP_acc[3]) { #Use MAE
        model<-AR
    }
    else {
        model<-XP
    }
    model
}

The "holdout" is the number of periods you wish to use as an out of sample test.  The function then calculates a fit window and a test window based on this parameter.  Then it runs the auto.arima and ets functions on the fit window, and chooses the one with the lowest MAE in the test window.  If the holdout is equal to 0, it tests the in-sample fit.
Is there a way to automatically update the chosen model with the complete dataset, once it has been selected?
Answer: The likelihoods from the two model classes, and hence the AIC values, are not comparable due to different initialization assumptions. So your function is not valid. I suggest you try out the two model classes on your series and see which gives the best out-of-sample forecasts.
Comment: As I keep saying, use out-of-sample performance on a large set of series. You can't easily compare in-sample performance of the two model classes.
Comment: I've edited my question to include a function I wrote to do that.  Does my new function make sense?
Comment: If holdout=0, it is using insample fit which will favour the model with more parameters. But if holdout>0, it makes sense, although you need quite a large holdout sample for the method to select the best model reliably. In general, I would choose the model to use based on other considerations rather than only consider the out-of-sample forecast performance on a short holdout sample from one series. For example, you could consider the out-of-sample performance across the whole ensemble of series (rather than one series at a time), and select the best model class that way.
Comment: thanks for the suggestion, I'll start to move in that direction.  In the case where my holdout equals zero what if I introduced some kind of penalty for parameters?
Comment: Ok, thanks for all the advice.  I'll use out-of-sample performance on the whole ensemble to choose a model class.


could not resolve plugin artifact o.fabric:io.fabric.gradle.plugin Kotlin DSL

Question: I am getting the following error when trying to build the project.
The only difference is the gradle script is in Kotlin DSL.
could not resolve plugin artifact 'io.fabric:io.fabric.gradle.plugin:1.25.4')

Below is my entire build.gradle.kts file
https://gist.github.com/nksaroj/483f3f07df8e04c72040ea4c055459d6
Or https://github.com/nksaroj/xDemo is the full project.
Comment: Some work around. Just move the class path to the root level build.gradle. this is not solution because this works locally but fails in the CI server. Let me know if you found any better solution. Thanks
Comment: I have the same issue.
Did you solve this problem?
Answer: Use applying plugin in build block:
https://docs.gradle.org/current/userguide/plugins.html#sec:applying_plugins_buildscript
For io.fabric:
buildscript {
    repositories {
        maven("https://maven.fabric.io/public")
    }

    dependencies {
        classpath("io.fabric.tools:gradle:1.25.4")
    }
}


Change of basis matrix with different dimensions

Question: Let's say I have 2 bases $A$ from $R^x$ and $B$ from $R^y$.
Is it possible to compute the change of basis matrix from $A$ to $B$ if $x \ne y$ ?
If $x = y$, it's easy, but if it is possible for $x \ne y$, how can I do it?
Answer: There does not exist an invertible linear transformation between two vector spaces of different dimension. Otherwise, this would be a homeomorphism, and two vector spaces (of finite dimension) are homeomorphic if and only if their dimension is the same. A change of basis matrix must be invertible by its definition (recall, you need to conjugate your matrix with the change of basis matrix, requiring that the change of basis matrix has an inverse: that's one way to see it), so it is impossible to construct a change of basis matrix between these vector spaces.
You can certainly create noninvertible maps between these two vector spaces which are invertible when restricted to a subspace of the larger vector space, allowing a "change of basis" between the subspace of the larger vector space and the smaller one by forcing the transformation to be between two vector spaces of the same dimension. You would do this in the same way as you would when $x = y$, but only defining your transformation on a restricted domain.


Como usar o Include para objetos que estão dentro de uma lista

Question: Tenho os seguintes objetos em meu contexto EF6.
public class Produto
{
    public Guid Id {get;set;}
    public string Nome {get;set;}
}

public class VedaItem
{
    public int Item {get;set;}
    public float Valor {get;set;}
    public Guid ProdutoId {get;set;}

    public virtual Produto Produto {get;set;}
}

public class Venda
{
    public DateTime DataVenda {get;set;}
    public string Numero {get;set;}
    public List<VendaItem> Itens {get;set;}

}

Eu não uso LazyLoading, logo preciso de usar Include para acessar os relacionamentos com Venda para gerar um relatório.
Preciso de acessar os dados de Produto que estão em VendaItem.
Tentei fazer o include da seguinte forma.
var relatorio = contexto.Set<Venda>()
     .Include(v => v.Itens.Produto);
     .Select(v => new
     {
        NomeProduto = v.Itens.Produto.Nome
     });

Porem o VisualStudio nem me permite digitar isso: v => v.Itens.Produto.
Como eu faço para conseguir acessar os dados da entidade Produto?
Answer: Seria dessa forma:
 var relatorio = contexto.Set<Venda>()
                 .Include(v => v.Itens.Select(p=> p.Produto));

Vai retornar a lista de vendas, com os itens e produtos carregados.
Comment: Obrigado! vou testar


(Js puro) função que filtre array de maneira que retorne arrays unicos com elementos distintos

Question: var list =[
[3,4,7,9,4],[3,4,7,9,5],[3,4,7,9,6],[3,4,7,9,7],
[3,4,7,9,8],[3,4,7,9,9],[3,4,8,3,3],[3,4,8,3,4],
[3,4,8,3,5],[3,4,8,3,6],[3,4,8,3,7],[3,4,8,3,8],
[3,4,8,3,9],[3,6,4,6,7],[3,6,4,6,8],[3,6,4,6,9],
[3,6,4,7,3],[3,6,4,7,4],[3,6,4,7,5],[3,6,4,7,6],
[3,6,4,7,7],[3,6,4,7,8],[3,6,4,7,9],[3,6,4,8,3],
[3,6,4,8,4],[3,6,4,8,5],[3,6,4,8,6],[3,6,4,8,7],
[6,7,8,8,7],[6,7,8,8,8],[6,7,8,8,9],[6,7,8,9,3],
[6,7,8,9,4],[6,7,8,9,5],[6,7,8,9,6],[6,7,8,9,7],
[6,7,8,9,8],[6,7,8,9,9],[6,7,9,3,3],[6,7,9,3,4],
[6,7,9,3,5],[6,7,9,3,6],[6,7,9,3,7],[6,7,9,3,8],
[6,7,9,4,5],[6,7,9,4,6],[6,7,9,4,7],[6,7,9,4,8],
[6,7,9,4,9],[6,7,9,5,3],[6,7,9,5,4],[6,7,9,5,5],
[6,7,9,5,6],[6,7,9,5,7],[6,7,9,5,8],[6,7,9,5,9],
]

Ex: os arrays abaixo todos seriam eliminados pois possuem elementos repetidos dentro
[3,4,7,9,4]
[3,6,4,7,7]
[6,7,9,4,9]
[6,7,9,5,6]

Nos casos abaixo os elementos são distintos porem eles se repetem com posicionamento diferente em um outro array, nesse caso um seria eliminado e outro permaneceria se tornando unico dentro do array principal
[3,6,4,7,9]
[3,4,7,9,6]

[3,6,4,8,7]
[3,6,4,7,8]

Comment: Já ouvi falar em Expressões Regulares?
Answer: Acho que isso resolve o seu problema:

var list =[
[3,4,7,9,4],[3,4,7,9,5],[3,4,7,9,6],[3,4,7,9,7],
[3,4,7,9,8],[3,4,7,9,9],[3,4,8,3,3],[3,4,8,3,4],
[3,4,8,3,5],[3,4,8,3,6],[3,4,8,3,7],[3,4,8,3,8],
[3,4,8,3,9],[3,6,4,6,7],[3,6,4,6,8],[3,6,4,6,9],
[3,6,4,7,3],[3,6,4,7,4],[3,6,4,7,5],[3,6,4,7,6],
[3,6,4,7,7],[3,6,4,7,8],[3,6,4,7,9],[3,6,4,8,3],
[3,6,4,8,4],[3,6,4,8,5],[3,6,4,8,6],[3,6,4,8,7],
[6,7,8,8,7],[6,7,8,8,8],[6,7,8,8,9],[6,7,8,9,3],
[6,7,8,9,4],[6,7,8,9,5],[6,7,8,9,6],[6,7,8,9,7],
[6,7,8,9,8],[6,7,8,9,9],[6,7,9,3,3],[6,7,9,3,4],
[6,7,9,3,5],[6,7,9,3,6],[6,7,9,3,7],[6,7,9,3,8],
[6,7,9,4,5],[6,7,9,4,6],[6,7,9,4,7],[6,7,9,4,8],
[6,7,9,4,9],[6,7,9,5,3],[6,7,9,5,4],[6,7,9,5,5],
[6,7,9,5,6],[6,7,9,5,7],[6,7,9,5,8],[6,7,9,5,9],
]

// Eliminando arrays com elementos repetidos
let withoutDuplicates = list.filter(l => (new Set(l)).size === l.length)

// Função diff (traz a diferença entre 2 arrays)
Array.prototype.diff = function (a) {
  return this.filter((i) => a.indexOf(i) === -1)
}

let duplicatedKeys = []

// Percorrendo os arrays restantes
withoutDuplicates.forEach((a, i) => {
  // Fazendo outro loop para percorrer os arrays restantes novamente
  withoutDuplicates.forEach((b, x) => {
    // Checando se os elementos comparados não são o mesmo elemento
    // e checando se a diferença entre eles é igual a 0 (se for significa
    // que eles possuem os mesmo valores, mesmo em posições diferentes)
    if(i !== x && a.diff(b).length === 0) {
        // Verifica se o elemento a e b não foram incluídos no array duplicatedKeys
        if(duplicatedKeys.indexOf(a) === -1 && duplicatedKeys.indexOf(b) === -1) {
            // Armazena o elemento no array duplicatedKeys
            duplicatedKeys.push(a)
        }
    }
  })
})

// Removendo as chaves duplicadas que foram armazenadas no array duplicatedKeys
withoutDuplicates = withoutDuplicates.filter(a => duplicatedKeys.indexOf(a) === -1)

console.log(withoutDuplicates)

Quando chegar em casa edito e tento explicar melhor o que foi feito...
Comment: Ainda não. Ex: esses dois array são iguais [[6,7,8,9,5],  [6,7,9,5,8]], tem que ficar pelo menos um deles para ser único dentro do array principal, aqui nesse site tem uma breve explicação no exemplo 2 onde fala sobre combinações
Comment: o site era esse aqui https://brasilescola.uol.com.br/matematica/arranjo-ou-combinacao.htm . Agora sim está funcionado perfeitamente, obrigada pela ajuda e pela atenção.
Comment: nao está funcionando corretamente,[ 6,7, 9, 5, 8 ] [ 6,7,8,9, 5 ] esse dois por exemplo teria que ficar somente 1 deles
Comment: @LucasMota acho que agora tá funcionando, dá uma olhada
Comment: @LucasMota Acho que agora sim deu certo, dá uma olhada!
Comment: @LucasMota Editei os comentários, acho que ficará um pouco melhor para entender agora!
Answer:

var lista = [
  [3,4,7,9,4],[3,4,7,9,5],[3,4,7,9,6],[3,4,7,9,7],
  [3,4,7,9,8],[3,4,7,9,9],[3,4,8,3,3],[3,4,8,3,4],
  [3,4,8,3,5],[3,4,8,3,6],[3,4,8,3,7],[3,4,8,3,8],
  [3,4,8,3,9],[3,6,4,6,7],[3,6,4,6,8],[3,6,4,6,9],
  [3,6,4,7,3],[3,6,4,7,4],[3,6,4,7,5],[3,6,4,7,6],
  [3,6,4,7,7],[3,6,4,7,8],[3,6,4,7,9],[3,6,4,8,3],
  [3,6,4,8,4],[3,6,4,8,5],[3,6,4,8,6],[3,6,4,8,7],
  [6,7,8,8,7],[6,7,8,8,8],[6,7,8,8,9],[6,7,8,9,3],
  [6,7,8,9,4],[6,7,8,9,5],[6,7,8,9,6],[6,7,8,9,7],
  [6,7,8,9,8],[6,7,8,9,9],[6,7,9,3,3],[6,7,9,3,4],
  [6,7,9,3,5],[6,7,9,3,6],[6,7,9,3,7],[6,7,9,3,8],
  [6,7,9,4,5],[6,7,9,4,6],[6,7,9,4,7],[6,7,9,4,8],
  [6,7,9,4,9],[6,7,9,5,3],[6,7,9,5,4],[6,7,9,5,5],
  [6,7,9,5,6],[6,7,9,5,7],[6,7,9,5,8],[6,7,9,5,9],
]

// 1º Passo - Remover os arrays com itens repetidos.
lista = lista.filter(function (sublista) {
  return sublista.every(function (item, indice) {
    return sublista.indexOf(item) == indice
  })
})

// 2º Passo - não é possivel comparar dois Objetos por valor no JavaScript.
// desta forma, [1, 2, 3] != [1, 2, 3]. porém como se trata de um array de numeros,
// é possivel converter o mesmo para uma string de base64 com a função btoa
// para que que a string base64 para arrays com os mesmos numeros seja igual,
// devemos ordenar os arrays com a função sort, antes de obter a string base64.
// por exemplo, [3, 4, 5, 7, 9] será convertido para "Myw0LDUsNiw4"
var indices = {}
var binarios = lista.map(function (sublista, indice) {
  return { indice: indice, binary: btoa(sublista.sort()) }
})

// 3º Passo - obtendo o indice da primeira ocorrencia de cada array,
// assim como a quantidade de ocorrencias de arrays com os mesmo elementos.
binarios.forEach(function (item, indice) {
  if (indices[item.binary]) {
    indices[item.binary].total++
  } else {
    indices[item.binary] = { indice: indice, total: 1 }
  }
})

// 4º Passo - Filtrar os arrays, para exibir apenas os arrays cujo a conjunto numerico é unico.
lista = Object.values(indices).filter(function (item) {
  return item.total == 1
}).map(function (item) {
  return lista[item.indice]
})

console.log(lista)
Comment: Não está funcionando corretamente.  Amostra : o array  [6,7,9,3,5] não foi incluído.
Answer: Ao fazer o teste de mesa, resulta nas seguintes arrays:
[3,4,7,9,5]
[3,4,7,9,8]
[3,6,4,7,5]
[3,6,4,8,5]
[3,6,4,8,7]
[6,7,9,3,4]
[6,7,9,3,8]
[6,7,9,4,8]
[6,7,9,5,3]
[6,7,9,5,4]
[6,7,9,5,8]

O código abaixo filtra da forma que deseja, substituindo a array original list com os elementos filtrados:

var list =[
[3,4,7,9,4],[3,4,7,9,5],[3,4,7,9,6],[3,4,7,9,7],
[3,4,7,9,8],[3,4,7,9,9],[3,4,8,3,3],[3,4,8,3,4],
[3,4,8,3,5],[3,4,8,3,6],[3,4,8,3,7],[3,4,8,3,8],
[3,4,8,3,9],[3,6,4,6,7],[3,6,4,6,8],[3,6,4,6,9],
[3,6,4,7,3],[3,6,4,7,4],[3,6,4,7,5],[3,6,4,7,6],
[3,6,4,7,7],[3,6,4,7,8],[3,6,4,7,9],[3,6,4,8,3],
[3,6,4,8,4],[3,6,4,8,5],[3,6,4,8,6],[3,6,4,8,7],
[6,7,8,8,7],[6,7,8,8,8],[6,7,8,8,9],[6,7,8,9,3],
[6,7,8,9,4],[6,7,8,9,5],[6,7,8,9,6],[6,7,8,9,7],
[6,7,8,9,8],[6,7,8,9,9],[6,7,9,3,3],[6,7,9,3,4],
[6,7,9,3,5],[6,7,9,3,6],[6,7,9,3,7],[6,7,9,3,8],
[6,7,9,4,5],[6,7,9,4,6],[6,7,9,4,7],[6,7,9,4,8],
[6,7,9,4,9],[6,7,9,5,3],[6,7,9,5,4],[6,7,9,5,5],
[6,7,9,5,6],[6,7,9,5,7],[6,7,9,5,8],[6,7,9,5,9],
];

var list2 = list.map(function(v){ return v.join('') });

for(var item in list2){
   list2[item] = list2[item].split('').sort().join('')+" "+item;
}

for(var item in list2){
   var m = list2[item].match(/^\d+/)[0];
   for(var x=0; x<m.length; x++){
      var r = m.match( new RegExp(m[x], 'g') ).length;
      if(r > 1){
         list2[item] = list2[item].replace(m+' ','');
         break;
      }
   }
}

var list2_str = list2.join(); // converto para string

for(var item of list2){
   var padrao = item.match(/^\d+\s/);
   var m = list2_str.match( new RegExp(padrao, 'g') );
   if(m){
      for(var x=1; x<m.length; x++){
         list2_str = list2_str.replace(m[x], '');
      }
   }
}

list2_str = list2_str.split(','); // converto para array

list2_str.filter(function(v){
   if(v.length < 7) list[v] = null;
});

list = list.filter(function(v){ return v; });

// daqui pra baixo apenas para mostrar na div
var div = document.querySelector("#resultado");

for(var item in list){
    div.innerHTML += item+": ["+list[item]+"]
";
}

Comment: esse também está funcionando! muito obrigado pela ajuda


How to find list view checkbox checked count in android

Question: I am placed check box in custom list view I have to take selected check box value  can anybody tell how to do
Thanks
Answer: use OnCheckedChangeListener in ur adapter and maintain avariable which will tracks ur checked counter.
if(ischecked)
  counter++;
else c
   counter--;
it helps u...
Answer: save the value of checkbox when it is checked ..for this use getView() method of your adapter..


Radio not disabling due to loop

Question: This is my radio disabling function.

And I will call it when the page is loaded!

And the radio button is displayed through loop..!
echo '<form method="post" action="trainingserver.php">';
$i = 1;
while($i <= $num_rows)
{
echo '<input type="radio" id="dis"'.$i.'"" name="select" value="'.$i.'" />';
echo  $poke[$i]."
";
echo 'Level:'.$level[$i]."
";
echo 'Health:'.$health[$i]."
";
$i++;
}
echo '<input type="submit" name="submit" value="Select Pokemon!" />';
echo '</form>';

So the radio ids would be like: dis1,dis2 ... dis6
But its not disabling it...! I think its because of the while loop, I used..! what should I do..?
Comment: Have you tried any debugging? `console.log()` is your friend.
Comment: Sorry, never used it..can i tell me how should I do it?
Comment: In Chrome press F12 and click console. In your JS `console.log(something);` where something is an array, a string, an object, etc. Firefox has Firebug extension.
Comment: Can you show the outputted HTML, not the PHP that generates it?
Comment: I wonder why you aren't using a for loop, but regardless your code looks solid. Try posting dis_value for us to see since it seems that is the only thing that could be wrong...
Answer: this line:
echo '<input type="radio" id="dis"'.$i.'"" name="select" value="'.$i.'" />';

should be (note the removed quotes from id):
echo '<input type="radio" id="dis'.$i.'" name="select" value="'.$i.'" />';

Radio not disabling due to loop


What makes Beethoven's False Picardy Third so convincing?

Question: So, there's one aspect of Beethoven's style that I personally, haven't been able to write convincing examples of. That would be the False Picardy Third. To clarify, this is what I mean by False Picardy Third:

A harmonic motion to the parallel major that sounds like a Picardy Third and is followed by an extensive passage in that key, only to be suddenly switched back to the parallel minor as if to say "You thought I was going to end in major, didn't you. Well I'm not. I'll end it in minor."

This is something that Beethoven does often in his minor key pieces, especially those that are in C minor. I could use any work, but to keep things short for the listener, I will use the Pathetique Sonata rondo as an example of the False Picardy Third.

At 2:42, the motion to C major starts. Then at 2:50, C major is confirmed and it lasts until 3:15, when the F#dim7 brings us back to C minor in just 1 chord. This whole section from 2:42 to 3:15 is the False Picardy Third.
Now, I have tried to use this concept myself of the False Picardy Third, but it doesn't sound convincing when I try to use it. And I'm wondering why. I mean, when I try to use it, I have the motion to the parallel major and the extensive major key passage. I even have the sudden switch back to minor. And yet, Beethoven does it convincingly and I don't. I can only think of 1 difference between my use and Beethoven's use. I tend to stray away from the diminished seventh in favor of the dominant seventh in major keys whereas in minor, I often use the diminished seventh as the one and only dominant function chord in a passage.
Could this use of the diminished seventh be so crucial to the False Picardy Third, that trying to use a dominant seventh instead is like trying to use the vi chord as a tonic chord without a preceding modulation to the vi in that it just won't work in the majority of cases?
Comment: No, it doesn't. A Picardy Third generally speaking is at the very end of a minor piece. Not a long way from the end. Usually the last bar or two. By moving to the minor earlier, there's no Picardy anything.
Comment: 'False Picardy Third'? Hasn't it just modulated into its parallel key?
Comment: But the resolution to the major key + the extensive passage in the parallel major sounds like a Picardy Third doesn't it? And doesn't it sound even more like a Picardy Third in another example, the recapitulation of Beethoven's Fifth? So, when it flips back to minor, I know that it is a False Picardy Third.
Answer: First off, as Tim notes in comments, this has nothing to do with Picardy thirds (false or otherwise).  I suppose if Beethoven had actually returned to the major form of the theme in a final refrain of the Rondo, maybe you could think of it as a false move into major, but he doesn't.
This is an episode, which frequently modulates to other keys in a rondo.
It sounds convincing partly because it's a common thing to do in rondo forms, sometimes known as a maggiore couplet or episode.  Rondo forms typically have forms like ABACA or ABACABA, and the B and C sections (known as episodes or couplets) frequently move into parallel major or parallel minor (minore couplets).  These sorts of episodes are all over rondos by Haydn, Mozart, Beethoven, etc.  While the first episode in a minor rondo frequently goes to the relative major (III), later ones sometimes go to the parallel major.
And the return is convincing because it's part of the form and returns to the home key along with the refrain, which is pretty much the definition of what a rondo form does.
As for the details of why your particular attempt at a similar modulation doesn't work, I have no idea without seeing it.  But Beethoven's example partly works because it's the very kind of thing he might be expected to do in a section like that.

P.S. I do not intend this answer to sound flippant at all.  But you've asked quite a few questions relating to form here, and I might recommend you take a look at a serious textbook on form to try to understand how classical pieces work if you're going to use them as models.  I might recommend William Caplin's Classical Form (or perhaps the more student-oriented version Analyzing Classical Form by the same author).
Answer: I don't believe the diminished 7th matters - playing the dominant 7th twice in the Beethoven is still convincing. But then I would find it still convincing if the minor theme came in immediately after the C cadence at 3:11. Perhaps it is because I have heard the piece often. Perhaps it is convincing because Beethoven has now used the theme several times and established it in the listener's mind, so there will be a sense of familiarity and rightness when it returns (in the minor key). Perhaps it is because the first 3 notes of the theme still allow ambiguity about whether it is major or minor. Or a combination, or something else I haven't thought of!
Do ask somebody else you trust about whether they find your work convincing, as sometimes we are our own harshest critics.

What makes Beethoven’s False Picardy Third so convincing?


Significance of different mean values for two processes

Question: I have an experiment that produces one measurement every time it is run. I can change something in the experimental setup, and I want to test if this change in the setup results in a change of the measured value. I am repeating the measurement multiple times for each setup, but only one measurement with one setup can be done at a time. I assume that the change in the setup is not changing the standard deviation of the measurements (but I do not know what the deviation is), and that the measurements in both setups are normally distributed around a true value.
My hypothesis is that the true values for the two processes will be different, and I would like to test this hypothesis. However, having gathered the data and found the means to be different, I am unsure how much confidence I should assign to the result. After all, the mean values could be different by chance and the true values actually identical.
What is the best way to evaluate this?
Calculating the standard deviation of the mean seems like a good start. The further the two means +/- their standard deviations are apart, the more confident I can be. But I would like to make this a bit more quantitative.
My idea is that I need to calculate the probability of getting two different mean values if I perform two times N measurements. The lower the probality, the more confidence I can have in my result. But how do I do this calculation? To me this looks like a textbook problem where I just have to know the right formula, but apparently I haven't taken the corresponding course.
(Note: no quantum physics here, everything is classical)
Comment: An important phrase here *"the standard deviation of the mean"* which is *not* the same as the standard deviation of the distribution.
Comment: (1) Are the processes and their measurements physically independent or not? (2) Are the processes perhaps simultaneously measured, so that there is a one-to-one correspondence (determined by measurement time) between the sets of measurements?
Answer: Without more details about your processes I don't know for sure, but you probably want to compute the distribution for the sum of the difference in sampled values.
If $X^1(t) \sim N(\mu_1t,\sigma^2t)$ and $X^2(t) \sim N(\mu_2t,\sigma^2t)$ then the statistic would be
$w = \frac{1}{n} \sum_{i=1}^n (X^1(t_i) - X^2(t_i))$
Which under the null hypothesis ($\mu_1 = \mu_2$) would have mean 0 and variance $v = \frac{2\sigma^2}{n}\sum_i \Delta t_i$. This is assuming that $X^1$ and $X^2$ are not correlated. If you are estimating $\sigma$ from the data you compare the standardized statistic $z = \frac{w - 0}{\sqrt{v}}$ to a $t$-distribution with $n-1$ df.
EDIT: (response to comment) If you are sampling at different intervals and processes are independent then the following SDE approach might be reasonable,
$dX_t^i = \mu_idt + \sigma dW_t, \quad i=1,2$
with $W_t$ standard Brownian Motion. This model assumes a constant drift in each process and same level of volatility. The MLE estimate for $\mu_i$ would solved by considering
$
\begin{equation}
\log(\mathbf{P}(X^i_{t_{i_1}},X^i_{t_{i_2}}\ldots,X^i_{t_{i_n}})) = \sum_{k=1}^n \log(\mathbf{P}(X^i_{t_{i_{k+1}}}|X^i_{t_{i_k}})) \propto -\sum_k (\Delta X^i_{t_{i_{k+1}}} - \mu_i \Delta t_{i_{k+1}})^2
\end{equation}
$
so optimizing for $\mu_i$ yields $\hat{\mu}_i = \frac{\sum_k \Delta X^i_{t_{i_{k+1}}}}{\sum_k \Delta t_{i_{k+1}}}$, where $\Delta$ is the adjacent difference operator.
The variance of $\hat{\mu}_i$ is just $v_i = \frac{\sigma^2}{\sum_k \Delta t_{i_{k+1}}}$, so you can just do a two-sample $t$-test with statistic $(\hat{\mu}_1 - \hat{\mu}_2) / \sqrt{v_1 + v_2}$.
Comment: I don't see where there's a Brownian motion here. Along with the OP, I see a textbook example calling for an unpaired t-test based on the data, not their differences.
Comment: Just extended the original question with more details. I believe (1) processes are uncorrelated, (2) not simultanously measured.
Comment: I think what needs explaining is *why* this is the appropriate null hypothesis to use.  The appearance of the multiple $t$ in your model is a puzzle, though: why such a formulation?
Comment: I'm happy to describe the process in more detail - but what details do you need?
Comment: @whuber I agree without further information these might be poor assumptions. The description the OP gave seemed to indicate a BM with drift type model sampled at identical times.
Comment: The details (1) and (2) @whuber asked should be enough. Do you have a specific distribution for each process in mind? Are the two processes correlated?
Comment: Hmm. Could you give a reference where I can learn more about your answer? (doesn't need to be online). With the exception of $\mu$ and $\sigma$, I don't know what any of the variables in your formulas mean. I'm especially confused about the $t$, since there is no time dependence anywhere in my problem.
Comment: If there is no time dependence in your problem then disregard my answer, and go with @whuber suggestion; a simple unpaired t-test (+1 from me for seeing the simpler problem first). I was confused by your wording "processes".
Comment: @whuber: I read up on the unpaired t-test, and it seems to be just what I need. Thanks! Can you post your comment again as an answer, so I can accept it?
Answer: I think if means of two process are $\mu_1$ and $\mu_2$ then you can test the null hypothesis $H_0:\mu_1-\mu_2=0$ against alternative hypothesis $H_1=\mu_1-\mu_2\neq0$ and if your sample reject the null hypothesis then your statement will be true.This hypotesis can be tested but you need more information to test this.First you need to know if this two processes are correlated or not.Next though you say that  the standard deviation is the same for both processes you also need whether standard deviation is known to you or not.If that is not known you need to estimate that.


Inserting field or field collection into body field

Question: I've created a content type called "News" with the following fields:

Body
Image (using Insert module to allow user to insert picture into the body)
Body Sidebar (a field collection, surrounded by a  with the following fields)

Body Sidebar has two fields:

BS Title
BS Text

I want to be able to give the content creators an easy way to insert the sidebar into the body in a similar way they can with the image field. As far as I know the Insert module can't be used to do that.
Is there any way to allow users to insert the Body Sidebar div into the Body field? If not, is there a way to do this programmatically?
Apologies if this is elementary, I'm very new to Drupal.
Comment: I have programmatically solution,why you do not that in form_submit?
Answer: You might be able to use the EVA: Entity Views Attachment module to attach the data to the node, but I'm not sure.

"Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.
Comment: I haven't used EVA, but the issue with using that is (I assume) the user actually needs to create a view for this method to work. I want them to be able to enter data into the Body Sidebar collection fields, and use that div in the body without having to create a view as well.
Answer: You can do it with Block Inject module easily, you can watch the video Demo here.

You can create any number of regions to inject as well as select as
  many node types you would like these regions to be injected in. The
  blocks you assign to these regions will then appear in the middle of
  the body field of these node types if the number of paragraphs is
  bigger than 2.

with this module you can achieve your requirement easily by creating a view block with the required field and assign that block to the region it will render your block inside the body field.
Answer: There are already some good suggestions here. Additionally, I would like to recommend taking a look at the module field injector field formatter widget maintained by Dave Reid. It enables you, for example, to insert any view list via the views field module and can be set to where exactly the injection should happen. After the first or the second or before the last paragraph. This is the most flexible way in my opinion and enables you to even reuse this in another view showing the content with the injected view in the body again.
Answer: I recommend using views if you are not using that module already.  Views gives you the ability to render content form 1 or more nodes in a block.
Add the sidebar title and sidebar summary fields to your content type, then create a block that displays these fields using views.
You should only have to create one view, which will render the information if the information is provided by your users.
You can set this view block to appear in the content section on in a sidebar by rearranging you blocks on the block settings page.
Answer: just edit the contenttypes node.tpl.php file (like node--news.tpl.php),
if you want that field in the sidebar, use views, create a views-block displaying the two fields with the actual node as contextual filter and put that block in the desired region.


Explain example in Python with class

Question: Can anyone explain me the following example?
How does this gets all the elements from the for loop and not only the last one?
class Deck:
    def __init__(self):
        self.cards = [Card(SUITS[i], RANKS[j])
                      for i in range (0, len(SUITS))
                      for j in range (0, len(RANKS))]

Comment: The more pythonic version would be `[ Card(suit, rank) for suit in SUITS for rank in RANKS]`.
Comment: It's worth noting that this is a really terrible way to do this - looping by index is slow, inefficient, and hard to read. What you really want is `[Card(suit, rank) for suit, rank in itertools.product(SUITS, RANKS)]`.
Comment: a crappy python way of looping
Answer: You have a list comprehension with nested loops. It can be translated to:
self.cards = []
for i in range(0, len(SUITS)):
    for j in range(0, len(RANKS)):
        self.cards.append(Card(SUITS[i], RANKS[j]))

It could be simplified further though, by looping over SUITS and RANKS directly:
self.cards = [Card(suit, rank) for suit in SUITS for rank in RANKS]

or you can use itertools.product() to replace the nested loops:
from itertools import product

self.cards = [Card(suit, rank) for suit, rank in product(SUITS, RANKS)]

Comment: @Lattyware: This is from a learning Python book (Dive into Python, IIRC), so `itertools.product()` is perhaps getting a little advanced, but I added it anyway.
Comment: Hmmmm Did I get the loop backwards? Or does it not matter?
Comment: @qwertynl: It matters; list comprehension loops are executed as if nested from left to right. The order of the cards in your version will differ.
Comment: I would recommend using [`itertools.product()`](http://docs.python.org/3/library/itertools.html#itertools.product) over nested loops. (`[Card(suit, rank) for suit, rank in itertools.product(SUITS, RANKS)]`). It's both more efficient and readable.
Comment: A function call is more advanced than multi-loop list comps? I find those indecipherable at the best of times.
Comment: @Lattyware: I mean that it deviates further from what the book is covering at that time.
Comment: @MartijnPieters Fair enough.
Answer: It is a little confusing but it translates to this pseudocode:
self.cards = [];
for i in range (0, len(SUITS))
   for j in range (0, len(RANKS))
        self.cards.append(Card(SUITS[i], RANKS[j]));

Basically a loop within a loop.
It is much easier to read in my example.
Answer: This is a list comprehension. It's basically a couple nested for loops:
class Deck:
    def __init__(self):
        self.cards = []
        for i in range(0, len(SUITS):
            for j in range(0, len(RANKS):
                self.cards.append(Card(SUITS[i], RANKS[j]))

Explain example in Python with class


Why is a learning curve necessary to determine if a neural network has high bias or variance?

Question: In Andrew Ng's machine learning course it is recommended that you plot the learning curve (training set size vs cost) to determine if your model has a high bias or variance.
However, I am training my model using Tensorflow and see that my validation loss is increasing while my training loss is decreasing. It's my understanding that this means my model is overfitting and so I have high variance. Is there still a reason to plot the learning curve?
Answer: Yes, there is, but it's not for spotting overfitting only. But anyway, plotting is just fancy way to see numbers, and sometimes it gives you insights. If you are monitoring loss on train/validation simultaneously – you're looking at same data, obviously.
Regarding Andrew's ideas – I suggest looking into Deep Learning course by him, he clarifies that in modern applications (DL + a lot of data, and I believe, this is your case) bias is not an opposite of variance.


Android: How to register a content observer without an activity?

Question: I need to listen all incoming and outgoing sms and store it in a text file. For this I am using broadcast listener to listen all incoming messages. This works fine. But for outgoing sms, how to register content observer without activity? I don't want any activity in my application. Now the broadcast receiver listens even after reboot, will content observer too listen even after reboot? How to merge these two functions?
Here is part of my manifest.xml
<receiver class="map" android:name=".map" android:enabled="true">

            <intent-filter>

                <action android:value="android.provider.Telephony.SMS_RECEIVED"                   android:name="android.provider.Telephony.SMS_RECEIVED" />

            </intent-filter>

        </receiver>

Here, the class that extends broadcast receiver
public class map extends BroadcastReceiver {
    /** Called when the activity is first created. */
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
    public void onReceive(Context context, Intent intent)
    {
                  // Here I store the sms in text file

    }

Any help is appreciated. Thanks.
Answer: You'll need a http://developer.android.com/reference/android/app/Service.html . Create one of those, set it to run on boot and register your content observer from in there.