Are ostinatos and motifs essentially the same thing?

Question: I understand that there is a difference between the two, but I'm still confused. Are the terms "ostinato" and "motif" interchangeable?
Comment: An ostinato repeats multiple times *without interruption*. A motif can appear basically at any time in any place.
Comment: Also: "ostinato" has a fairly narrow and concrete definition. "Motif" has a fairly fuzzy and vague one, meaning little more than "a recognizable unit." You could use "motif" in talking about visual art to mean a certain visual element, but you couldn't use "ostinato" except as a metaphor referring to the musical meaning.
Answer: No. An ostinato is a sustained pattern, lasting many bars. A motif is a particular 'musical idea', that may itself last several bars, which keeps re-occurring during a piece.
An ostinato is particularly a rhythmic pattern that is repeated bar after bar, or in two or four bar sequences. A motif will pop up from time to time to remind us of itself.
Comment: I think it would be good of you could make the difference between "sustained pattern" and "keeps re-occuring" more precise. (I have no idea what you mean)
Comment: https://www.youtube.com/watch?v=MmzER7X2424 my personal favorite ostinato.
Comment: @nuggethead - *obstinato* is maybe a better name!
Comment: @nuggethead - seems comments can't be edited after 5 mins. So either scrap that one and write another, or leave it. I quite like it, thought it was quite clever! Somewhat apposite.
Comment: Also, an obstinato brings along the idea that it repeats identically.  But a motif (also called a motive) is often developed and lengthened into a more substantial theme later
Comment: Examples: Beethoven's 5th: motif. Ravel's Bolero: ostinato.
Comment: @Andy that's Beethovens favorite fruit. "Banananaaaa"
Comment: Hi! @nuggethead, even you can find _obstinato_ in a few resources, the right term is ___ostinato___, as it comes directly from the italian word, which does not have any 'b' character. Please check https://www.treccani.it/enciclopedia/ostinato as an example (from Enciclopedia Italiana di Scienze, Lettere e Arti)
Comment: Twas a typo.  I cant seem to edit the comment to fix it
Answer: No. They serve very different purposes.
A motif starting on a different note of the scale or in a different mode is still the same motif. Motives are defined by their melodic contour.
An ostinato repeats without variation, even when it clashes with the underlying harmony.


UICollectionView reorder cells if not fit width

Question: I wonder why my UICollectionView reorder the cells if not fit within CollectionView's width.
After adding the long "XXXXX.." The "Super" cell moved to the right.
p.s After some reading I've found that the issue may be in "minimumInteritemSpacing" as according to its documentation.
...after the number of items is determined, the actual spacing may possibly be adjusted upward.

This is how I set up my layout
// 2 - setup flowlayout
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.minimumLineSpacing = self.tagSpacing
    layout.minimumInteritemSpacing = self.tagSpacing
    layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
    layout.scrollDirection = .vertical

Comment: The layout of the collection view is defined by the `UICollectionViewLayout` implementation that you set on your collectionView. You'll have to show us your implementation of the `UICollectionViewLayout` (e.g., show if you use `UICollectionViewFlowLayout` or your own custom implementation)
Comment: @MilanNosáľ Done!
Answer: The answer was to define my own layout.
import UIKit

class CustomViewFlowLayout : UICollectionViewFlowLayout {
let cellSpacing:CGFloat = 0

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    if let attributes = super.layoutAttributesForElements(in: rect) {
        for (index, attribute) in attributes.enumerated() {
            if index == 0 { continue }
            let prevLayoutAttributes = attributes[index - 1]
            let origin = prevLayoutAttributes.frame.maxX
            if(origin + cellSpacing + attribute.frame.size.width < self.collectionViewContentSize.width) {
                attribute.frame.origin.x = origin + cellSpacing
            }
        }
        return attributes
    }
    return nil
}
}

Thanks to this answer here
Answer: UICollectionViewFlowLayout supports variable sizes of cells, but it aligns the cells as "justified". In your case as you add a new cell that does not fit on the first row, the layout justifies the first row (making it span across the whole row) - so basically it puts the first cell to the left and the second one to the right. And then it continues with the next row. That's the explanation of whats going on.
I guess you want a left aligned flow. However, as far as I know UICollectionViewFlowLayout does not support that. To achieve what you want, either use some 3rd party library (e.g., UICollectionViewLeftAlignedLayout), or go over the answers here and implement your own layout.


How to add Link in Draft-JS (no plugins)

Question: I'm trying to create a button which onClick will give you an option to put link, then this link has to be displayed as  tag in the text field. So far I manage to add and display the plain text but I don't know how to transfrom it to an  tag.
// Link function
  const addLinkFn = (editorState, link) => {
    const contentState = editorState.getCurrentContent();
    const contentStateWithEntity = contentState.createEntity(
      "LINK",
      "IMMUTABLE",
      { url: link }
    );
    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
    const newEditorState = EditorState.set(editorState, {
      currentContent: contentStateWithEntity,
    });
    return AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, link);
  };

  const onAddLink = () => {
    let link = window.prompt("Add link http:// ");
    const newEditorState = addLinkFn(editorState, link);
    setEditorState(newEditorState);
  };

I know that somewhere I must have a "decorator" and "strategy" like this:
const linkStrategy = (contentBlock, callback, contentState) => {
  contentBlock.findEntityRanges((character) => {
    const entityKey = character.getEntity();
    return (
      entityKey !== null &&
      contentState.getEntity(entityKey).getType() === "LINK"
    );
  }, callback);
};

const Link = (props) => {
  const { contentState, entityKey } = props;
  const { url } = contentState.getEntity(entityKey).getData();
  return (

      {props.children}

  );
};

and then declare them like this:
decorators: [
    {
      strategy: linkStrategy,
      component: Link,
    },
  ],

Just I'm not sure how to put everything together to make it works :D
Thank you !
Comment: I think you didn't search well, but anyway check this out https://codesandbox.io/s/simple-link-example-filks
Answer: I figured it out.
The whole component looks like this:
//Add Link Component
import React from "react";
import { CompositeDecorator, EditorState, Modifier } from "draft-js";

const Link = ({ entityKey, contentState, children }) => {
    let { url } = contentState.getEntity(entityKey).getData();
    return (

            {children}

    );
};

const findLinkEntities = (contentBlock, callback, contentState) => {
    contentBlock.findEntityRanges((character) => {
        const entityKey = character.getEntity();
        return (
            entityKey !== null &&
            contentState.getEntity(entityKey).getType() === "LINK"
        );
    }, callback);
};

export const createLinkDecorator = () =>
    new
        CompositeDecorator
([
    {
        strategy: findLinkEntities,
        component: Link,
    },
]);

// call all together
export const onAddLink = (editorState, setEditorState) => {
    let linkUrl = window.prompt("Add link http:// ");
    const decorator = createLinkDecorator();
    if (linkUrl) {
        let displayLink = window.prompt("Display Text");
        if (displayLink) {
            const currentContent = editorState.getCurrentContent();
            const createEntity = currentContent.createEntity("LINK", "MUTABLE", {
                url: linkUrl,
            });
            let entityKey = currentContent.getLastCreatedEntityKey();
            const selection = editorState.getSelection();
            const textWithEntity = Modifier.insertText(
                currentContent,
                selection,
                displayLink,
                null,
                entityKey
            );
            let newState = EditorState.createWithContent(textWithEntity, decorator);
            setEditorState(newState);
        }
    }
};

Then you have to attach it to the editor toolbar (if you have one:
import { onAddLink } from "./Link";
<button
    onClick={() => onAddLink(props.editorState, props.setEditorState)}
>
    link
</button>

Then refer the deocrator in the display part of the editor so it knows how the link looks like:
import { createLinkDecorator } from "./Components/Link";
const decorator = createLinkDecorator();
const editorState = props.postData
    ? EditorState.createWithContent(convertFromRaw(props.postData),
        // add the decorator after the state
        decorator
    )
    : EditorState.createEmpty();


Pulse icon or element color for one minute with javascript/angularjs

Question: I would create a pulse color effect with a max duration of one minute. To have this effect with css I can do something like this:
@-webkit-keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

@-moz-keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

@-o-keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

@keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

.element {
  width: 50px;
  height: 50px;
  background: #ed8c55;
  -webkit-animation: pulse 3s infinite; /* Safari 4+ */
  -moz-animation:    pulse 3s infinite; /* Fx 5+ */
  -o-animation:      pulse 3s infinite; /* Opera 12+ */
  animation:         pulse 3s infinite; /* IE 10+, Fx 29+ */
}

But in this one I can't control the time. Particularly, I would make this effect in an icon inside a button
<md-button aria-label="Info" id="info" title="info" ng-click="openInfo()" class="md-icon-button">

</md-button>

That  element should pulse for max one minute in red color. Is this possible do it with angularjs or simply javascript?
Comment: `But in this one I can't control the time` Yes you can, use [`animation-iteration-count`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-iteration-count). As your animation takes 3 seconds, give it a value of `20`. It's not a good idea to  use JS as a crutch for CSS.
Comment: @RoryMcCrossan good to know! Nice, thank you
Comment: No problem. I added it as an answer for you
Answer:
But in this one I can't control the time

You can by using animation-iteration-count. As your animation takes 3 seconds you can give it a value of 20:
.element {
  width: 50px;
  height: 50px;
   background: #ed8c55;
  -webkit-animation: pulse 3s 20; /* Safari 4+ */
  -moz-animation:    pulse 3s 20; /* Fx 5+ */
  -o-animation:      pulse 3s 20; /* Opera 12+ */
  animation:         pulse 3s 20; /* IE 10+, Fx 29+ */
}


How to solve $E((X+1)^2)$ if $X$ follows a Poisson distribution

Question: Assume that a policyholder is five times more likely to file exactly four claims as to file exactly two claims. Assume also that the number $X$ of claims of this policyholder is Poisson. Determine the expectation $E((X+1)^2)$.
I solve for Poisson and got $\lambda=\sqrt{60}$ but don't really understand where to go from there.
Comment: $E((X+1)^2) = Var(X) + [E(X)+1]^2$. Do you know the formula for the variance of a Poisson random variable? Also mention how you got $\lambda = \sqrt{60}$.
Comment: P(x=4)=5P(x=2) and then plug in the formula for Poisson on both sides. Right?
Comment: Yes, that is correct.
Answer: Just use the linearity of the expectation, plus the facts that $Var(X)=E[X^2]-E[X]^2$ and, for the Poisson distribution, $Var(X)=E[X]=\lambda$:
$$
E[(X+1)^2]=E[X^2]+2E[X]+1=Var(X)+E[X]^2+2E[X]+1=\lambda^2+3\lambda+1
$$
Comment: did you mean lambda^2+2lambda+1?
Comment: No. I meant $\lambda^2+3\lambda+1$ because $Var(X)=\lambda$ too.


typeError: 'module' object is not callable

Question: Eu estou tentando adicionar layers pra janela do meu jogo, então tentei usar sprite groups, mas tem esse erro que eu não entendo porque persiste:

TypeError: 'module' object is not callable

Eu pesquisei e parece que acontece quando uma função e uma variável tem o mesmo nome, mas no meu código não existe nenhuma função ou variável com o mesmo nome.
sprite = pygame.sprite.Group()
green = (0, 255, 0)

class Block (pygame.sprite.Sprite):
    def __init__ (self, color, width, height):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.surface((width, height))
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = x/2
        self.rect.y = y/2
quadrado = Block(green, 50, 50)
sprite.add(quadrado)

Eu estava tentando importar uma imagem, mas deu esse problema e resumi pra rect.
Comment: Não tem como clocar no código um comentário indicando a linha onde que interpretador aponta o erro. E no caso da mensagem de erro ser mais verbosa anexar toa a mensagem.
Answer: É na linha pygame.surface - esse é o nome do módulo - você deve usar pygame.Surface (com "S" maiúsculo) - para criar uma instância da classe Surface.
Isso é comum em alguns projetos de médio para grande porte em Python:
os nomes dos módulos e subpacotes do projeto - que são os arquivos ".py" que o projeto usa internamente, aparecem para quem vai usar o projeto - mesmo que seja um uso mais ou menos simples. Ao mesmo tempo, o projeto precisa deixar disponível as classes e funções criadas nesses módulos.
É o caso da classe Surface - que pode ser usada diretamente como  pygame.Surface  - mas o pygame também tem um arquivo surface.py onde (muito provavelmente) está definida a classe Surface mesmo, com o comando class Surface... .
Em um projeto meu, eu tenho um atributo context , uma classe Context e preciso definir tudo em um arquivo  - que chamei de contexts.py - então os usuários vão ver os 3 nomes.


Do USA J-1 visa questions belong on Expatriates or Travel.SE?

Question: As of today, Expatriates has 49 questions tagged J-visa while Travel.SE has 57 questions tagged J1-visas.
Now, some J-1 visa questions are obviously about travel (eg those relating to airport transfers) and some are obviously about expats (eg those relating to waivers of the 2 year home residency requirement).  But what about the gray areas?
I'm asking because I saw this question was migrated from Expatriates to Travel:
Where to buy US repatriation and evacuation insurance.  The comment about the migration says:

This isn't an expats question - J1 is a non-immigrant short-term visa. Moving to travel.

The comment implies that all J-1 visa questions should migrate to Travel. So my questions:

Which site is more appropriate for these questions?
What is the guideline for migrating them?

EDIT: Another example -- Health insurance for J visa has been put on hold at Travel for being off-topic.
More examples: 1
Answer: The problem with J-1 is that it includes a lot of categories ranging from short-term visits to long-term employment, so it doesn't completely fit into either Travel or Expatriates.
Here's what I propose:

Allow any and all J-1 questions on Expatriates.  Rationale: Almost any valid question about J-1 can be relevant to long-term uses, even if the original poster's situation is short-term.  Also, Expatriates is generally intended to have a broader scope than Travel, so it makes sense to allow the full spectrum of gray area to exist here.
Also allow short-term J-1 questions on Travel.  Rationale: Although there can be overlap, Travel says it is for questions about short-term trips that don't involve study or employment. Since the site says they are allowed, such questions should be allowed even if they involve a J-1 visa.
For long-term J-1 question on Travel, don't close without migrating to Expatriates. Corrolary: don't close J-1 questions on Travel unless you have the system permission to migrate it. Rationale: It is unrealistic to expect new users to correctly identify where their J-1 question belongs based on the stated guidelines of the two sites. Closing without migrating effectively rejects the question, and few closed questions actually get reposted on the other site. On the other hand, migrating still lets the question be answered, and gives a relatively seamless experience to the end users.
Answer: I'd say go ahead and post your question and it will be handled as best as we can. In those 'gray area' type of questions, either site likely has the knowledge base to deal with the topic, though Travel probably gets a bit more traffic.


Add xml subelement with different namespaces than root element using lxml

Question: This is a simplified version of the xml I'm trying to build:
<BizData xmlns="urn:iso:std:iso:20022:tech:xsd:head.003.001.01"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:n1="urn:iso:std:iso:20022:tech:xsd:head.001.001.02"
  xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.003.001.01 head.003.001.02_DTCC.xsd">
  <Hdr>
   <AppHdr xmlns="urn:iso:std:iso:20022:tech:xsd:head.001.001.02"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.001.001.02 head.001.001.02.xsd">
   </AppHdr>
  </Hdr>
 </BizData>

Python Code
from lxml import etree as etree

if __name__ == '__main__':
attr_qname = etree.QName('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')
nsmap = {None: 'urn:iso:std:iso:20022:tech:xsd:head.003.001.01',
         'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
         'n1': 'urn:iso:std:iso:20022:tech:xsd:head.001.001.02'
        }
root = etree.Element('BizData',
                     {attr_qname: 'urn:iso:std:iso:20022:tech:xsd:head.003.001.01 head.003.001.02_DTCC.xsd'},
                     nsmap)

hdr = etree.Element('hdr')
attr_qname = etree.QName('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')
nsmap = {None: 'urn:iso:std:iso:20022:tech:xsd:head.001.001.02',
         'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
         }

app_hdr = etree.Element('AppHdr',
                {attr_qname: 'urn:iso:std:iso:20022:tech:xsd:head.001.001.02 head.001.001.02.xsd'},
                nsmap)
hdr.append(app_hdr)
root.append(hdr)

When printing hdr before appending to the root I get the correct output:
<Hdr>
 <AppHdr xmlns="urn:iso:std:iso:20022:tech:xsd:head.001.001.02"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.001.001.02 head.001.001.02.xsd">
 </AppHdr>
</Hdr>

But after appending to root the namesspaces xmlns and xmlns:xsi disappear:
<BizData xmlns:n1="urn:iso:std:iso:20022:tech:xsd:head.001.001.02"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="urn:iso:std:iso:20022:tech:xsd:head.003.001.01"
 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.003.001.01 head.003.001.02_DTCC.xsd">
 <hdr>
  <AppHdr xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.001.001.02 head.001.001.02.xsd"/>
 </hdr>
</BizData>

I tried using the set function to set xmlns:xsi but this causes the error ..not a valid attribute...
Does anybody has an idea?
Comment: `xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"` is declared on the root element. It is in scope for the whole document and the declaration won't be repeated on any other elements. It is not illegal to repeat it, but I don't think you can force lxml to do that.
Comment: You want two declarations for the `urn:iso:std:iso:20022:tech:xsd:head.001.001.02` namespace; first bound to the `n1` prefix on the `BizData` root element and then as the default namespace on `AppHdr`. Why? Having it this way in an XML document is not forbidden as far as I know, but it seems odd.
Comment: @mzjn I agree with you that it is in scope for the whole document, unfortunately I was given this template by the authorities and have to stick to its (unusual) design. Do you know a different/better library than lxml or a way to force this double declaration?
Comment: The XML that you want to create is a bit odd, but it is not breaking any rules as far as I can tell. However, I don't think it is possible to force lxml to output that exact markup. You may have to create the markup "by hand" and treat it as plain text.
Answer: DIRTY WORKAROUND

Create Envelope (BizData), Header (Hdr) and Payload (Pyld) as individual etree.Element's
Transfer them to strings
Combine the strings
Write to xml file

This is ignoring any sort of validation but doesn't mess with the namespace. Not ideal, but does the job.


Cannot connect to local DynamoDB

Question: I cannot connect to DynamoDB that is running local using cli.
aws dynamodb list-tables --endpoint-url http://localhost:8000

Could not connect to the endpoint URL: "http://localhost:8000/"

This doesn't work either:
aws dynamodb list-tables --region local
Could not connect to the endpoint URL: "http://localhost:8000/"
I tried using a different port and that didn't help. I disabled all proxies too.
I am able to connect to DynamoDB using an application like this so I know it's not a dynamodb issue:
aws dynamodb list-tables --endpoint-url http://dynamodb.us-west-2.amazonaws.com --region us-west-2

{
"TableNames": [
"Music"
]
}
Comment: I followed the instructions here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html.    I aso get this in my logs: Caused by: java.lang.UnsatisfiedLinkError: no sqlite4java-osx-x86_64 in java.library.path: [.]
Comment: Actually "Could not connect to the endpoint URL" may happen in various cases, even if no service is listening on host:port (e.g. dynamodb not running or running on different port), so definitely need to run with `aws dynamodb` with `--debug` to see the actual error.
Comment: How are you starting up the DynamoDb running locally?
Comment: which java version are you using ?
Comment: java version "14.0.1" 2020-04-14
Answer: When you run

java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb

command from your terminal make sure output will be like below and no service will be running on port 8000:
Initializing DynamoDB Local with the following configuration:
Port:   8000
InMemory:       false
DbPath: null
SharedDb:       true
shouldDelayTransientStatuses:   false
CorsParams:     *

It means, this service running successfully on port 8000.
DynamoDB requires any/fake credentials to work.
AWS Access Key ID: "fakeMyKeyId"
AWS Secret Access Key: "fakeSecretAccessKey"

then try below command to list tables.
aws dynamodb list-tables --endpoint-url http://localhost:8000

Comment: The output after running java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb is just like above. I have configured my credentials using cli configure and provided the key and secret key. Running aws dynamodb list-tables --endpoint-url http://localhost:8000 fails
Comment: Caused by: java.lang.UnsatisfiedLinkError: no sqlite4java-osx-x86_64 in java.library.path: [./DynamoDBLocal_lib]
Comment: have a look here: https://github.com/aws-samples/aws-dynamodb-examples/issues/22
Answer: The error in your logs is the key here  Caused by: java.lang.UnsatisfiedLinkError: no sqlite4java-osx-x86_64 in java.library.path: [.]
This means that the specific dependency cannot be located.
The link that Saranjeet provided has a few solutions. I prefer this solution for testing:
First, you need to download the zip file from offcial website. Unzip the file, copy all the *.dll, *.dylib, *.so to a folder under your project root. Say, src/test/resources/libs.
Then, add the code

System.setProperty("sqlite4java.library.path", "src/test/resources/libs/");
before you initialize a local instance of AmazonDynamoDB.

Cannot connect to local DynamoDB


ApplicationContext events never been thrown

Question: I'm trying to have ContextEventListener on all ContextXXXEvent
I created a listener for each event type as following (the ContextRefreshedEvent is an Example):
@Component
public class MyApplicationRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {

  @Override
  public void onApplicationEvent(ContextRefreshedEvent event) {
    logger.info(getClass(), "Event source [{}]", event.getSource());
  }

}

Both ContextRefreshedEvent and ContextClosedEvent were caught and their listeners did the expected job.
I tried to do the same for ContextStartedEvent and ContextClosedEvent but both of these two events listeners were not caught.
The event.getSource printed (in the refreshed and closed events):
Event source [Root WebApplicationContext: startup date [Tue May 09 10:07:51 IDT 2017]; root of context hierarchy]

Is there any difference between (started and stopped) and (refreshed and closed)?
Is it because my application context is WebApplicationContext (as the event.getSource() shows?)
Comment: refresh() is called implicitly during the creation of a concrete ApplicationContext, start is always explicit using the start() method
Comment: "I tried to do the same for ContextStartedEvent and ContextClosedEvent.....". You have already specified that you are able to successfully catch ContextClosedEvent. But in the next line you say that you were not able to catch the ContextClosedEvent. Can you please correct the question?
Answer: I have gone through spring code. I will discuss about ContextStartedEvent. Similar explanation can be given for stopped event.
Explanation:
ContextStartedEvent is emitted only from start() method of AbstractApplicationContext and nowhere. Since you are not able to catch the ContextStartedEvent, if we can know who calls or doesn't call this method we can find the answer.
In spring, applicationContext can be started in two ways. One, we explicitly call this method start() which will trigger the initialisation of beans in the context and rest of the context initialisation. The other way is for spring to take care of the context initialisation. In other words, we don't deal with context start and stop this way. Almost all of us unknowingly use the second way of initialisation. For example, you must be using xml files to load bean definitions which uses ClassPathXmlApplicationContext. This is inherited from AbstractRefreshableApplicationContext.
Hence I think ContextStartedEvent and ContextStoppedEvent are emitted only if you start and stop (manage) the ApplicationContext manually. There are another set of ApplicationContext implementations which you can use to manage ApplicationContext on your own. I haven't tried them out personally. I will update the answer if I am successfully able to do this.
A similar explanation can be given to ContextStoppedEvent.
Update: This is inline with the definitions of the events provided in the spring docs (as well as the other answer to this question by @coolgirl)
Comment: @Marwan Jaber, do you consider this answer? or is there something else you are expecting?


Diagonalizable matrix and Zariski topology

Question: Identify  the  set  of   square  matrices  of  order  two defined   over  $ \mathbb{C}$   with  the   affine  space $A^4$.  What  can  you  tell   about   the set   of diagonalisable matrices?  I  noticed  that  it   corresponds
   to  a union  of an open   Zariski   set   and   a  closed  Zariski   set.  It  is  this  set  open  or   closed?
Comment: I'd say it is neither. Certainly not closed.
Comment: @G.Sassatelli How  can  I   prove  that?
Comment: It is not closed because it's interior is non-empty and not all matrices are diagonalisable. For (Zariski) open, let's see...
Answer: It is neither.

Since it contains a non-empty Zariski open set (for instance, the set of matrices with $n$ dinstinct eigenvalues), it is dense in $\Bbb A^4$, but not all matrices are diagonalisable.
The set of non-diagonalisable matrices is not Zariski closed, because it isn't euclidean-closed. For instance $$\begin{pmatrix}1&\varepsilon&0&0\\ 0&1&0&0\\0&0&0&0\\0&0&0&0\end{pmatrix}\stackrel{\varepsilon\to0}\longrightarrow \begin{pmatrix}1&0&0&0\\0&1&0&0\\0&0&0&0\\0&0&0&0\end{pmatrix}$$
Comment: Sorry, I understood that par
Comment: Open Zariski sets are euclidean-open and closed Zariski sets are euclidean closed. I gave you an example of a sequence of non-diagonalisable matrices which converge, in the euclidean metric, to a diagonalisable matrix. Hence, the set of non-diagonalisable matrices is not euclidean closed. So it is not Zariski closed. Therefore, its complementary is not Zariski open. The set of diagonalisable matrices **is** dense in $\Bbb A^4$ (both euclidean and Zariski) because it contians a nonempty open Zariski set (and, in fact, I said it).
Comment: can you explain each one of the assertions?
Comment: What are you unfamiliar with?
Comment: Why the set of diagonalisable matrices is dense in $\mathbb{A^4}$?
Comment: I have a question. Why the set isn't open? By your explanation I understand that the set of diagonalisable matrices couldn't be dense in $\mathbb{A^4}$. The  proof of this fact is obviously?
Comment: Thank you for the above details. Now, I understand why the  diagonalisable matrices is not a Zariski closed set. And why it can't  be open?
Comment: If the set of diagonalisable matrices is Zariski open then is complementary is Zariski closed. Then the set of matrices which are not diagonalisable is also closed in Euclidian topology. But I can find a sequence of matrices which are not diagonalisable, but converges at a diagonalisable matrix, contradiction. It is correct my argument?
Comment: That's what I wrote, just said backwards.


PHP string to object name

Question: Ok I have a string...
$a_string = "Product";

and I want to use this string in a call to a object like this:
$this->$a_string->some_function();

How the dickens do I dynamically call that object?
(don't think Im on php 5 mind)
Comment: Have you tried that code?.. Also, `echo phpversion();` will show you if you're on PHP 5.
Comment: why dont you use call_user_func (or call_user_func_array)?
Answer: So you the code you want to use would be:
$a_string = "Product";
$this->$a_string->some_function();

This code implies a few things. A class called Product with the method some_function(). $this has special meaning, and is only valid inside a class definition. So another class would have a member of Product class.
So to make your code legal, here's the code.
class Product {
    public function some_function() {
        print "I just printed Product->some_function()!";
    }
}

class AnotherClass {

    public $Product;

    function __construct() {
        $this->Product = new Product();
    }

    public function callSomeCode() {
        // Here's your code!
        $a_string = "Product";
        $this->$a_string->some_function();
    }
}

Then you can call it with this:
$MyInstanceOfAnotherClass = new AnotherClass();
$MyInstanceOfAnotherClass->callSomeCode();

Answer: I seem to have read this question differently from everyone else who's responded, but are you trying to use variable variables?
Answer: EDIT: You need to be running PHP5 in order to do any method chaining. After that, what you have is perfectly legal.
Comment: But this isn't true. What you can't do in PHP4 is chaining method calls like this: `$obj->method1(10)->method2(42);` (that, and `public/private/static` properties and methods)
Comment: You do not need to be running PHP 5.x to do any object oriented programming. There is an OO model in older versions as well.
Answer: In the code you've shown, it looks like you're trying to call a function from string itself. My guess is that you want to call a function from a class with the same name as that string, in this case "Product."
This is what that would look like:
$this->Product->some_function();

It seems you might instead be looking for something like this:
$Product = new Product();
$Product->some_function();

Answer: Let's see if I got your intentions correctly...
$some_obj=$this->$a_string;
$some_obj->some_function();

Answer: So you've got an object, and one of it's properties (called "Product") is another object which has a method called some_function().
This works for me (in PHP5.3):
<?PHP

class Foo {
     var $bar;
}

class Bar {
      function some_func(){
           echo "hello!\n";
      }
}

$f = new Foo();
$f->bar = new Bar();

$str = 'bar';

$f->$str->some_func(); //echos "hello!"

I don't have PHP4 around, but if it doesn't work there, you might need to use call_user_func() (or call_user_func_array() if you need to pass arguments to some_function()

PHP string to object name


Why is vCenter 5.1u1 exiting hosts from maintenance mode?

Question: This vCenter server was just upgraded to 5.1 update 1.  I'm going through hosts and bringing firmware up to date, then upgrading them from various versions of 5.0 to 5.1u1.
vCenter 5.1u1 seems to have an interesting new behavior: it's removing hosts from maintenance mode when they reconnect after being disconnected -- but very inconsistently, I've seen it maybe 4 or 5 times on ~25-30 host reboots.  I've only seen it happen on 5.0 hosts that have not yet been upgraded to 5.1.

In the image, I placed the host in maint mode and rebooted it into the HP SPP DVD's automatic update mode.  After its usual ~40 minute update process, the host came back online.. and 7 seconds before even logging that the host had reconnected, vCenter had sent the host a task to exit maintenance mode.

In my understanding, the only time vCenter should drop a host out of maintenance mode is when vCenter put it into maintenance mode itself (such as a VUM upgrade task).
Why would this vCenter be unilaterally exiting a host from user-initiated maintenance mode?
Edit, additional info:
I ran the firmware upgrades on 5 more hosts, all at the same time.  Two of them exited maint mode after reconnecting, three did not.  The common factor of those exiting maint mode seems to be how long they were offline; the two that took a few tries to boot to the virtual media are the two that got knocked out of maint mode.

esx31 (image above): 45 minutes unresponsive
esx19 (exited maint): 87 minutes unresponsive
esx24 (stayed in maint): 32 minutes unresponsive
esx29 (stayed in maint): 39 minutes unresponsive
esx32 (stayed in maint): 30 minutes unresponsive
esx34 (exited maint): 70 minutes unresponsive

Edit:  The disconnect time idea seems to have been a red herring, as it's not happening consistently.
Additionally, in the vpxd.log the exit maint mode task initiation seems to always immediately follow this vim.EnvironmentBrowser.queryProvisioningPolicy SOAP call.  Here's the lines, slightly trimmed for clarity:
15:27:49.535 [info 'vpxdvpxdVmomi'] [ClientAdapterBase::InvokeOnSoap] Invoke done (esx31, vim.EnvironmentBrowser.queryProvisioningPolicy)
15:27:49.560 [info 'commonvpxLro'] [VpxLRO] -- BEGIN task -- esx31 -- HostSystem.exitMaintenanceMode --

Note that on the nodes that don't get the exit task, the vim.EnvironmentBrowser.queryProvisioningPolicy event still occurs.  I'm not seeing any other differences in events before or after this in the reconnect process, aside from the extra events caused by exiting maintenance mode.
Given the log's mention of provisioning policies, looking for autodeploy-related maintenance mode issues turns up complaints about similar behavior (though I'm not using autodeploy at all).
Comment: You might wish to contact the VMware customer support line....or ask in one of the vmware groups.  This could possibly be a bug in the programming.
Comment: Also, which vCenter approach are you using? Appliance? Running on Windows?
Comment: @ewwhite Running on Windows.
Comment: Hmm... [Possibly related to this](http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1012473)? -- I'd say it definitely *shouldn't do that*...
Comment: What kind of hardware are you using for your hosts?  Our UCS was causing a similiar problem in that when a host was rebooted, some of them like to reboot twice, where as other ones (same blade type same firmware, same esx updates) would only reboot once.  When I talked to Cisco about it they said "it's a known issue"
Comment: @MoSiAc HP hosts - not sure if they rebooted twice as I wasn't watching the console, though I don't think they should have.  Do you see this happening whenever they reboot twice?
Answer: I've seen this happen with ESXi 4.1 hosts after a patch accidentally wacked the /tmp/scratch folder. You might want to check if that directory still exists on the hosts that exited maintenance mode automatically.
If they're missing, you'll want to mkdir to create it. Also, you'll want to check if persistent scratch is setup correctly on each host by following this VMware KB article:
VMware KB: Creating a persistent scratch location for ESXi 4.x and 5.x


Custom code snippet not showing before first "using" statement

Question: This custom code snippet used to show up when typing CR at the top of a
C# source file in Visual Studio 2013:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">

            <Title>Insert a Copyright notice</Title>
            <Shortcut>CR</Shortcut>
            <Description>Code snippet for the Copyright notice comment</Description>
            <Author>Pierre Arnaud</Author>
            <SnippetTypes>
              <SnippetType>Expansion</SnippetType>
            </SnippetTypes>

        <Snippet>

                <![CDATA[//  Copyright © 2015, EPSITEC SA, CH-1400 Yverdon-les-Bains, Switzerland$end$]]>

        </Snippet>
    </CodeSnippet>
</CodeSnippets>

In Visual Studio 2015, the code snippet CR does not show up in the
suggestion if I place the cursor before the first using statement.
The only suggestions which show up are the two Visual Studio provided
extern and using snippets.
Any idea if I have to update the XML of this snippet for this to work
again?
EDIT: I opened an issue on Microsoft Connect.
Comment: So I am not the only one experiencing this issues and explains why my devs not following practice.
Comment: check here: https://stackoverflow.com/questions/3956638/custom-code-snippets-in-intellisense
Comment: @StefanW. I am not using ReSharper in my case...
Answer: One work around I did discover is to move the cursor to the top of the code file and then press Ctrl+K, Ctrl+S (the surround with snippet shortcut).  This brings up the code snippets, including the Copyright one I have locally.  This can be selected.  Not a great solution but it works until a fix is in place.


Retrieve newly updated article without refreshing the page

Question: I'd like to make a edit link to update the article when it's clicked,
In the template, it's structured as:

post-text

article-content
article-form

post-menu

I hide "article-form" in first place as
 until edit link is clicked.

        {{article.content}}

    <form class="form-horizontal" action="/article/edit/{{ b.id }}" method="POST">

                <textarea class="form-control" id="editContent" name="content" rows="10" cols="30">
                    {{form.content.value}}
                </textarea >

                <button type = "submit" class = "btn btn-success btn-sm" id = "saveEditBtn"> Save Edits </button>

    </form>

        edit

        delete

After updating is completed and submit is cliked, send data to backend using Ajax, hide "article-form" and show "article-content".

My problem is that in ajax success,
$postText.find(".article-content").show() still display the non-updated article,
How could I retrieve the updated without refreshing the page?
Comment: You mean after send ajax request, want to update article from edited form?
Comment: For simply, it's impossible. Because django render context when sending response, but your page is not loaded after ajax request. For doing this, you may have to send other rendered response from ajax request and add that in your html directly
Comment: Also, you have option to use frontend framework like vue or react. If using them, you can simply bind data after ajax for your articles
Comment: I don't get it... If you can send the edited version to server... You have the new content! Update the `.article-content` with it then show.
Comment: Yes after sending Ajax request, `$postText.find(".article-content").show();` to show the edited data @seuling
Comment: oh, I got it,change textarea.val(), thank you. @LouysPatriceBessette could you please transmit your comment unchanged to answer.
Comment: @LouysPatriceBessette It's simple answer, but it's trick - not change all data from updated one. If the form data have many one, you can't updated all value from changed form.
Answer: If you can send the edited version to server... You have the new content! Update the .article-content with it then show.
Here is what I think it is...
//capture the button submitting event
$(".article-form button").on("click", function(e){
  var content = $postText.find("textarea").val();
  $.ajax({
    type:"POST",
    url: ,
    data:,  // <-- There is something missing here... I assume it's content.
    success: function(){
      //if saved successfully
      $postText.find(".article-content").html(content).show();  // update before the show!
      $postText.find(".article-form").hide();
    },//success
  })//ajax post request
});


java: convert int to object of type T

Question: so I have a class called ExpandableArrayList that implements ListInterface. This ArrayList is filled with instances of type Item (it represents my generic type T). class Item implements Comparable , and has the following attributes : String itemNo, String itemName, double price, and int quantity.
A method called CheckLimit In class ExpandableArrayList is supposed to check if any entry in the list is having a quantity below the given limit or not. If it is, it removes it and inserts it at the front of the list.
I already defined compareTo for class Item based on item quantity,
and this is my current implementation for checklimit :
 public void checkLimit (int limit){

/*Type conversions, change limit from int to Object and then to T,
   in order to use CompareTo: */
 Object limitObj = (Integer)limit;
 T limitT = (T)limitObj;
 for ( int i=0 ; i< length ; i++ ) {
    if ( limitT.compareTo(list[i]) > 0){

        /* ....... Remove and insert at front ......  */

    } // end if
    } // end for
 } // end checkLimit

It compiles correctly but causes a runtime Exception
Exception in thread "main" java.lang.ClassCastException:
 Item cannot be cast to java.lang.Integer

I then tried to add the following method to class item
 /* Added method ConvertToTypeT :
this method is called by method checkLimit in class
ExpandableArrayList. it receives an integer and creates a temporary
Item Object having this integer as its quantity for comparision purpose only*/

public Item convertToTypeT(int limit) {
  Item converted = new Item (" "," ",0.0,limit);
  return converted;                 }

and changed checklimit to be :
 public void checkLimit (int limit){
    for ( int i=0 ; i< length ; i++ ) {

    T  limitT =list[i].convertToTypeT(limit);
    if ( limitT.compareTo(list[i]) > 0){

        /* ....... Remove and insert at front ......  */

    } // end if
    } // end for
 } // end checkLimit

but did not work even after I changed the public Identifier
ExpandableArrayList.java:255: error: cannot find symbol
    T  limitT =list[i].convertToTypeT(limit);
                      ^
symbol:   method convertToTypeT(int)
location: interface Comparable<CAP#1>
where T is a type-variable:
T extends Comparable<? super T> declared in class ExpandableArrayList
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: T from capture of ? super T

so is there a proper way to perform such a comparison ?  considering that the header of checkLimit was given in the question and it should not be changed (it should always have an int argument ).
many thanks in advance.
Comment: An `Item` and an `Integer` are completely different kinds of objects. Why are you trying to cast an `Integer` to an `Item`? Note: Casting does not somehow automatically convert an object into a different kind of object.
Comment: And another subtlety: you also cant cast your primitive "int limit" to "Integer".
Comment: @Jesper  yah , I did realize that , thats why I used the second way above ( adding a method that creates an item with limit being as its attribute).
Comment: @pbabcdefp Uups; you are correct. I guess the compiler is replacing the cast with some new Integer() or Integer.valueOf() ... interesting. Thanks for pointing that out!
Comment: @EddyG it's done by [autoboxing](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html).
Comment: @javastudent If all you know about `T` is that it implements `Comparable` then you don't have a way to get at `quantity` in class `Item`, and then it's going to be hard!
Comment: @Jesper 'Autoboxing' denotes the process that the compiler does "something". I was referring to the "implementation" that makes "something"  possible.
Answer: The bug is here in your checkLimit method:
T limitT = (T)limitObj;

In this line you are trying to cast limitObj, which is an Integer, into type T, which is Item. You can't do this - an Integer is a completely different kind of object than an Item, there's no way to cast an Integer to an Item (and why do you think you need to do this?).
If you want to check the quantity value of your Item objects, do this:
public void checkLimit(int limit) {
    for (int i = 0; i < length; i++) {
        if (list[i].quantity < limit) {
            // do whatever you need to do with list[i]
        }
    }
}

(list has to be a list of Item objects for this to work).
Comment: well, I should not customize the class ExpandableArrayList for type Item only (by writing list [i].quantity) , the class should work for any type of list entries , since it was written by the author of the book I am studing  and I am only asked to used it in my program. thanks though..

java: convert int to object of type T


Proof of existence of infinitely many primes that divide the sequence $\{S(k)\}=\sum_{i=1}^{n} a_i^k$ where $\{a_i\}_{i=1}^{n}$ forms an AP

Question: For the sake of a mathjax solution and because of finding an error in my previous solution (which I had posted here for correction), I have edited the whole document

Let $a_i$ for $1 \leq i \leq n$ be a non constant Arithmetic Progression.
Define: $$S(k)=\sum_{i=1}^{n} a_i^k$$
Prove that there are infinitely many primes which divide the sequence  $\{ S(k) \} _{k\in \mathbb{N}}$ where $S(k)$ doesn't remain constant.

The term: infinitely many primes which divide the sequence  $\{ S(k) \} _{k\in \mathbb{N}}$ is a bit messy to understand.
Clarification of the statement:
The sequence $\{S(k)\}$ has infinitely many terms different terms since it's not constant. Now the terms are not restricted to being divisible by only a certain number of primes. Like suppose, consider a set of primes: $\mathcal{P}=\{p_1, p_2, \cdots, p_m\}$. Then there will exist a term in the sequence of $\{S(k)\}_{k=1}^{\infty}$ which will get divided by a prime $p_j$ such that $p_j \notin \mathcal{P}$.

Doubt:
Here (below in the form of images) I have provided half of the solution, as best I could.
I think I'm not wrong.
May I get some guidance to complete the second case?
Solution:
First, let us assume to the contrary and let $\mathcal{P}=\{p_1, p_2, \cdots, p_m\}$ denote the set of primes that ONLY divide $S(k)$ and suppose $\text{GCD}(a_1, a_2, \cdots, a_n)=d$.
Then we get $a_i=db_i$ such that $\text{GCD}(b_1, b_2, \cdots, b_n)=1$
Choose $p > n$ which means $p \nmid n$.
Fix a prime $p \in \mathcal{P}$ and show that there exists a prime $p \mid S(k)$ such that $p \notin \mathcal{P}$ leading to a condration and hence proving the inexistence of finitely many primes that divide the sequence.
We get two cases:
Case 1: $p \nmid d$
If $p \mid S(k)$, then, $p \mid  d^k \sum_{i=1}^n b_i$ and since $p \nmid d$, we see $p \mid \sum b_i$.
Set $k=\prod (p_i-1); ~ p \in \mathcal{P}$
From Euler's theorem (the one that uses Totient\Phi function), we get that $b_i \equiv \{0,1\} \pmod p \implies \sum b_i \not\equiv 0 \pmod p$ and hence we get the desired contradiction.
Case 2: $ p \mid d$
(Could not solve)
Comment: No, simply no. Your main idea looks somewhat promising, but your work is really hard to read. If you want someone here to check it, turn it into a nice to read form... Two short comments from the first page: The question talks about an arithmetic progression $a_i$ and you use some $b_i$ that don't have a common divisor; why?
Comment: Take $n=1$ and you only get finitely many primes. Take $n = 2$ and $a_1 = 0, a_2 = 1$ and you will get no primes at all. I'm sure there are other counter examples. Thus, the first step should be to state the question correctly. Then you might want to ask a single question regarding your proof, not just give three pages and say "please read"...
Comment: For a prime $p$ and a sequence $\{S_k\}_{k\in\Bbb N}$ what is the meaning of "$p$ divides the sequence $\{S_k\}_{k\in\Bbb N}$"? I would understand it as $\forall k\in\Bbb N\colon p\mid S_k$, but that won't make sense here ...
Comment: Bumping the topic, can anyone check my proof? Is there any loophole?
Comment: I have initially shown that irrespective of the sequence being in AP, just if all terms are distinct and have GCD=1, then we'll get infinitely many primes dividing the sequence. And then, I have have considered the AP (having GCD=d). It's like a lemma that I have used initially
Comment: @DirkLiebhold The AP and value of $S(k)$ is non-constant. And in your first case, the AP becomes constant. Hence it won't work. And in the second case, $S(k)=1$ which makes it constant.
Comment: I understand that the question is a bit messy and even I had problems understanding it initially. The sequence $\{S(k)\}$ has infinitely many terms. Now the terms are not restricted to being divisible by only a certain number of primes. Like suppose, consider a set of primes: $\mathcal{P}=\{p_1, p_2, \cdots, p_m\}$. Then there will exist a term in the sequence of $\{S(k)\}_{k=1}^{\infty}$ which will get divided by a prime $p_j$ such that $p_j \notin \mathcal{P}$. This is the best I can make my question clear.
Comment: Is the question clear now?
Comment: The proof is poorly written in the sense that it is not at all clear how anything you're saying leads to a proof. Explain what you are proving, and how this helps to prove the final result. Also your notation is often convoluted; in stead of writing $b_1^k\equiv1\pmod{\mathcal{P}}$, write $b_1^k\equiv1\pmod{p}$ for all $p\in\mathcal{P}$. This is just one example, there are many. It kept me from finishing even the first page.
Comment: I'm bumping the topic since it's edited a few minutes ago.
Answer: Let us assume that the prime divisors of $S(k)$ belong to $\{p_1,p_2,\ldots,p_m\}$ for any $k\geq 0$. By Van Der Waerden's theorem, there are arithmetic progressions $k_1,k_2,k_3,\ldots,k_\eta$ of arbitrary length such that $S(k_1),S(k_2),\ldots,S(k_\eta)$ are multiples of some $p_\mu$, and we may assume without loss of generality $k_\eta>p_\mu$. Newton's identities then imply that $a_1,a_2,\ldots,a_n$ are multiples of $p_\eta$. We may define $\tilde{a}_j = a_j/p_\eta$ and repeat the same argument, but since $\mathbb{Z}$ is a UFD an infinite descent is not allowed and the claim is proved.
Comment: @Mathbg: of course, just give me some time. Can you convert your work into MathJax?
Comment: The idea is clear but I'm bothered if there is any fallacy/loophole/trivial errors in the proof since these won't be considered strong/rigorous in Olympiads. Sir, you may take your time to get it checked. I would be grateful to you!
Comment: @Mathbg: in your case $2$, just replace $a_i$ with $a_i/p$ and restart, like I do at the end of my proof.
Comment: (+1) for the solution. Can my solution be checked?
Comment: Sure sir, I can give you enough time for checking it. But since I'm not a pro at typing, it would take me enough time to type out the whole thing. I am sorry for the inconvenience. Thanks for helping!
Comment: @Mathbg: at first sight, your solution looks correct. The idea of considering specific exponents of the form $A(p_1-1)\cdots(p_m-1)$ and exploit Fermat's little theorem is slick. It is a pity a less constructive approach like mine leads to a much shorter solution :D
Comment: True indeed. Yes, that was my idea to construct and exploit using Euler's theorem (stronger than FLT) but I'm afraid my proof maybe hard to read.
Comment: @Mathbg: well, the main idea is clear and efficient. Details can be boring to outline, but they are secondary.
Comment: Sir, I have converted my work into MathJAX. Can you help me now?
Comment: Sir, I have done that myself. But I didn't know how to inform that here. I am trying to close down the topic now. Thanks for your constant help, though


Erro na criação de chave estrangeira no MariaDB

Question: Ao tentar criar a tabela brinquedo, aparece o seguinte erro:

ERROR 1005 (HY000): Can't create table brinquedos.brinquedo
  (errno: 150 "Foreign key constraint is incorrectly formed")

Segue o código:
CREATE TABLE IF NOT EXISTS categoria (
  categoria_id SERIAL,
  categoria_nome VARCHAR(80) NOT NULL,
  PRIMARY KEY (categoria_id),
  UNIQUE INDEX categoria_nome_UNIQUE (categoria_nome ASC));

CREATE TABLE IF NOT EXISTS brinquedo (
  brinquedo_id SERIAL,
  brinquedo_descricao VARCHAR(180) NULL DEFAULT NULL,
  brinquedo_imagem_url VARCHAR(180) NOT NULL,
  brinquedo_preco DECIMAL(9,2) NOT NULL,
  brinquedo_detalhes VARCHAR(180) NULL DEFAULT NULL,
  brinquedo_categoria_id BIGINT NOT NULL,
  brinquedo_marca VARCHAR(45) NULL DEFAULT NULL,
  PRIMARY KEY (brinquedo_id),
  UNIQUE INDEX brinquedo_imagem_url_UNIQUE (brinquedo_imagem_url ASC),
  CONSTRAINT fk_brinquedo_categoria
    FOREIGN KEY (brinquedo_categoria_id)
    REFERENCES categoria (categoria_id)
    ON DELETE CASCADE
    ON UPDATE CASCADE);

Essa query funcionava no mysql, criei a meses atrás em um trabalho da faculdade, mas agora estou usando o MariaDB e está dando esse erro!
Eu não entendo muito das peculiaridades do MySQL e do MariaDB. No MySQL eu usava a engine default InnoDB. Na documentação do MariaDB a engine default é InnoDB também, então estou usando InnoDB (eu acho).
Desde já agradeço a quem me ajudar.
Comment: SERIAL é do PostgreSQL
Comment: Chegou a testar o que foi respondido abaixo de por `brinquedo_categoria_id BIGINT` **`UNSIGNED`** `NOT NULL` ?
Comment: SERIAL funciona no MariaDB, a primeira tabela é criada com sucesso!
Comment: UNSIGNED, funcionou!
Answer: Falta um UNSIGNED em brinquedo_categoria_id já que na tabela original foi definido SERIAL, que também não pode ser negativo.
Comment: Opa! Eu demorei para responde porque tive que fazer outras coisas aqui, mas sua solução funcionou: brinquedo_categoria_id BIGINT UNSIGNED NOT NULL.
Era esse o problema, obrigado! Eu não sei porque tem um voto negativo na sua resposta!


How to find or get random records or documents in a mongodb using Mongoose

Question: I have tried finding a way of getting random records/documents in a MongoDB using mongoose without success.
The solution I found here failed which is four(4) years ago didn't solve my problem because it tends to skip some documents based on the generated random number.
The problem is that if you have 3 documents in the db and the random number generated is 3, doing the  following as specified here:
User.findOne().skip(random).exec(
    function (err, result) {
      // Tada! random user
      console.log(result)
    })

...will make .skip(3) to skip the whole three documents and return [] ( 404 error).
What I wanted was to shuffle record any time I do User.find()
Answer: This is how I solved this problem
const users = await User.find().limit(50); // limit can be any number, each time you make a request, values will always be returned if have records is in your MongoDB

const randomUsers = users.sort(() => Math.random() - 0.5);

return res.status(200).send({ success: true, message: 'success: random users', data: randomUsers });

Any time you make a request, you are sure of getting a record but shuffled, reordered, or randomised the list based on the random number generated.
Trust this sovled a similar problem for you!


What are the differences between the Power Forward and Center positions?

Question: What are the differences between the Power Forward (PF) and Center (C) positions?
Several PF/C players, such as Tim Duncan, have been considered a power forward and/or a center. Based on the differences between the positions, which position best defines players like Tim Duncan?

ORIGINAL
On the Dan Patrick Show: http://msn.foxsports.com/topics/m/video/57663322/dan-patrick-show-karl-malone.htm At the 11:15 mark, Karl Malone calls Tim Duncan a center; however, Duncan is usually considered to be a power forward. Often times, he is called the "greatest power foward of all time" by such media as the following:

Bleacher Report: http://bleacherreport.com/articles/1442888-ranking-tim-duncan-with-the-best-power-forwards-of-all-time/page/11
ESPN: /page/5-on-5-110728/power-forwards-ratings">http://espn.go.com/nba/story//page/5-on-5-110728/power-forwards-ratings

What is the difference between the two positions? And considering Tim Duncan's style of play, which position is a better label for him?
Answer: I would like to add a bit to @DSeita's answer; in many cases the old PG-SG-SF-PF-C categorization of players is a bit outdated. Historically the roles would be defined something like this (simplified of course):

PG: play-maker, distributes the ball, typically the best player with the "in-game intelligence" and the very high dribbling skills (an old school example for text-book PG would be John Stockton)
SG: "the sniper", very high shooting accuracy, often focused on punishing bad matchups with sinking 3-pts. (e.g. Reggie Miller or Ray Allen)
SF: these players are typically the most athletic players, playing a physically demanding role both in offense and in defense. They need to be competent enough in shooting, dribbling and driving in to basket. (e.g. Scottie Pippen)
PF: "the vanguard", these guys would typically be the heavy hitters, fighting constantly in the inside, still competent from mid-range. Blocks and rebounds would typically vital stats for these guys (many examples for stereotypical PFs; but I happen to think of Karl Malone first)
C: king-of-the-hill, hill being the basket. These guys almost exclusive work under or around the basket. I guess the most typical example I can think of would be Shaq. He's as pure of an traditional center as I can think of.

You might realize that I have left some very obvious names out of my list, for instance Michael Jordan, or Kobe Bryant... or Tim Duncan. The reason behind this is that these players (and many other famous players of today) transcend the original roles. Both MJ and Kobe are originally SGs but I would go on to say that both have played like a point guard, both have played like a small forward. It's perhaps their flexibility that allowed them to penetrate the defense in a way they did.
No matter how you look at it, Tim Duncan has one of the most remarkable careers amongst the league's big boys. He started playing with David "Admiral" Robinson who was, as @DSeita put it, an established C at the time. Which led him to play a role that can co-exist with another player of his size and caliber.
Long story short, Tim Duncan is neither a typical PF nor a typical C. He's both. I think the 5-position categorization is dying out in its essence. As the game develops the players use their strengths to their advantages and the roles change. For instance, you have 7-foot Dirk Nowitzki that is essentially a SG, or at least made a career out of sinking shots, instead of dunking/blocking. I think we shouldn't try and put labels to players, but instead understand and appreciate what they have to give to the game.
Comment: +1 for ,, appreciate what they have to give to the game" ... I'm tall and everyone forces me to play C, but I hate it, I have good dribbling and love to assist.
Comment: Sounds familiar; back in high school I was forced to play as a guard, since I am not that tall. I was arguably the strongest player however and I would have much rather played PF/C which would have suited my play style. On the other hand when the other kids grew taller I wasn't which meant that I had a growing disadvantage for an inside player :(
Answer: This question has been asked numerous times, so I'll try to explain just the things that immediately pop in my  mind when I think of center or power foward.
The center is typically designated as a team's tallest and/or biggest (though often both) player on the floor at a time. An ideal center may stay close to the rim, play defense, block shots, rebound well, take jump balls, and score near the basket (possibly using post moves). Many well-known centers were also notorious for their poor free throw shooting. Nowadays, of course, we're seeing more and more centers extending their skill set to include long-range jumpers and thus playing more perimeter-oriented.
The term power foward invokes, in my mind, a player that's a smaller version of a center who doesn't spend as much time near the basket. What he may lack in size or strength, the power forward may make it up with increased mobility and a better midrange game.
Obviously, many of my explanations have a whole list of exceptions, but I think they generally hold true among fans when they try to describe what an ideal center or power forward would be. For instance, I'm sure most NBA players labeled as centers in their careers have been at least 6'9'', but Wes Unseld was 6'7''. I'm also sure that it's rare to see an NBA player taller than 7'0'' consistently labeled as a power forward.
Duncan is an interesting case as he started his career playing with an established center in David Robinson, which may have played a role in people viewing him as a power forward. I wouldn't try to force a label on him, especially when categories like this aren't easily  nor rigorously defined.
Comment: And even those heights may be inflated for Wallace and Barkley, which may make their accomplishments even more impressive.
Comment: Good read. C Ben Wallace is 6'9". PF Charles Barkley is 6'6", the same height as SG Michael Jordan and SG Kobe Bryant, but we know Barkley was definitely built during his playing days.
Answer: Even though this question already has an accepted answer, I'd like to add mine.
These days, basketball positions are generally defined both by a player's role and their size relative to their four teammates on the court.  So out of the five players from a given team currently on the court, the PG is usually the shortest, followed by the SG, then the SF, then the PF, and finally the C is the tallest.   That is the reason these positions are often respectively labelled the 1, the 2, the 3, the 4, and the 5: they have an order, and that order is player height.
With that said, the issue of the player's role on the court can overrule their relative height, because positions are of course directly defined by the player's role, while height is just one factor (though arguably the most important factor) that can help players fill that role.
The PF and C positions are similar in requiring size and strength for the purposes of rebounding, blocking shots, and scoring close to the basket.  However, traditionally speaking the PF is somewhat shorter, lighter and more athletic than the C, and is therefore more likely to drive (a short distance) past their defender to attempt a shot at the rim, and more dependent on their explosiveness (as opposed to their size) to block shots and grab rebounds.  Their lesser height also means it is more important for them to have some shooting ability, since they cannot rely quite as much on dunks, hook shots and layups for scoring.  This is why PFs will often flash a nice little midrange jumper; they need one more than a Center does.
As the accepted answer mentions, many of the most successful players in history have achieved that success precisely because they've blended the size of one position with the skills of another.  Perhaps the most extreme example of this was Magic Johnson--the tallest, and many argue the best, PG in history.  At 6'10", Magic was at least 6-8 inches taller than most players at his position, but he was quick enough on his feet and good enough with his hands to run, dribble, shoot, and (most importantly) pass like a PG.  Tall enough to see, pass, or shoot over most of his defenders, but quick enough to drive right past those defenders' taller teammates, Magic was an unstoppable offensive force due to his unique combination of size and skill.  Today, LeBron James, being only two inches shorter than Magic was but with much greater athleticism and similar skills, is terrorizing the league using the exact same principles (his superior athleticism offers him an even greater advantage on defense, allowing him to easily guard every position on the court except C).
So how does this all relate to good ol' Timmy?  Well, it's as the others have suggested in their answers:  Tim Duncan can play the PF and C positions equally well precisely because he has the skills of a PF combined with the size of a C.  So which is he?  It depends on who else is on the court!  When Duncan played with the Admiral, he was always going to be a PF because Robinson was taller, Robinson was already one of the best Cs ever, and Robinson couldn't play PF as well.  But after Robinson retired, and whenever he was the biggest guy for his team on the court, Duncan often played the position of Center, and was pretty darn good at it.  Furthermore, in today's NBA, where teams are increasingly playing "small-ball", the scenario of PF-turned-C simply by virtue of being his team's biggest player on the court has become even more common.  But from what I've read, Duncan has always considered himself a PF first and foremost, so my guess is he's happiest when Tiago Splitter is around to claim the 5.
Answer: My answer is a bit shorter and very simplistic.  PF is a more offensive Center and a Center is a more defensive PF. Now, there are obvious exceptions to this, since some center have great offensive skills, and PFs, defensive skills. PFs tend to have better ball handling, and this could be the main difference.  If you can create your own shot, you usually are a PF, if you can't, you're a Center.  Again, this is not every case, but by and large.


How to handle network calls in Microservices architecture

Question: We are using Micro services architecture where top services are used for exposing REST API's to end user and backend services does the work of querying database.
When we get 1 user request we make ~30k requests to backend service. We are using RxJava for top service so all 30K requests gets executed in parallel.
We are using haproxy to distribute the load between backend services.
However when we get 3-5 user requests we are getting network connection Exceptions, No Route to Host Exception, Socket connection Exception.
What are the best practices for this kind of use case?
Comment: Seems like you are hit by the fallacies of distributed computing: The network is reliable, Latency is Zero, Bandwidth is infinite, etc.
Reading this sounds more like a layered architecture where it takes multiple layers to get to the data.
Comment: 30k requests means at least 30,000 bits of information being requested from the back end (response orientated data) or being pushed into the back end (logging data).  What sort of a website are you providing which requires that amount of data movement for a single user request?  It sounds like the architecture and approach is broken and needs to be revisited imho...
Comment: I have little experience in this, but 30k request to the backend sound too much.
Answer: Well you ended up with the classical microservice mayhem. It's completely irrelevant what technologies you employ - the problem lays within the way you applied the concept of microservices!
It is natural in this architecture, that services call each other (preferably that should happen asynchronously!!). Since I know only little about your service APIs I'll have to make some assumptions about what went wrong in your backend:
I assume that a user makes a request to one service. This service will now (obviously synchronously) query another service and receive these 30k records you described. Since you probably have to know more about these records you now have to make another request per record to a third service/endpoint to aggregate all the information your frontend requires!
This shows me that you probably got the whole thing with bounded contexts wrong! So much for the analytical part. Now to the solution:
Your API should return all the information along with the query that enumerates them! Sometimes that could seem like a contradiction to the kind of isolation and authority over data/state that the microservices pattern specifies - but it is not feasible to isolate data/state in one service only because that leads to the problem you currently have - all other services HAVE to query that data every time to be able to return correct data to the frontend! However it is possible to duplicate it as long as the authority over the data/state is clear!
Let me illustrate that with an example: Let's assume you have a classical shop system. Articles are grouped. Now you would probably write two microservices - one that handles articles and one that handles groups! And you would be right to do so! You might have already decided that the group-service will hold the relation to the articles assigned to a group! Now if the frontend wants to show all items in a group - what happens: The group service receives the request and returns 30'000 Article numbers in a beautiful JSON array that the frontend receives. This is where it all goes south: The frontend now has to query the article-service for every article it received from the group-service!!! Aaand your're screwed!
Now there are multiple ways to solve this problem: One is (as previously mentioned) to duplicate article information to the group-service: So every time an article is assigned to a group using the group-service, it has to read all the information for that article form the article-service and store it to be able to return it with the get-me-all-the-articles-in-group-x query. This is fairly simple but keep in mind that you will need to update this information when it changes in the article-service or you'll be serving stale data from the group-service. Event-Sourcing can be a very powerful tool in this use case and I suggest you read up on it! You can also use simple messages sent from one service (in this case the article-service) to a message bus of your preference and make the group-service listen and react to these messages.
Another very simple quick-and-dirty solution to your problem could also be just to provide a new REST endpoint on the articles services that takes an array of article-ids and returns the information to all of them which would be much quicker. This could probably solve your problem very quickly.
A good rule of thumb in a backend with microservices is to aspire for a constant number of these cross-service calls which means your number of calls that go across service boundaries should never be directly related to the amount of data that was requested! We closely monitory what service calls are made because of a given request that comes through our API to keep track of what services calls what other services and where our performance bottlenecks will arise or have been caused. Whenever we detect that a service makes many (there is no fixed threshold but everytime I see >4 I start asking questions!) calls to other services we investigate why and how this could be fixed! There are some great metrics tools out there that can help you with tracing requests across service boundaries!
Let me know if this was helpful or not, and whatever solution you implemented!
Comment: Oh, then use the HTTP body of the request! The URI is the wrong place to send this kind of data!
Comment: Thank you for the detailed explanation.
The assumption you made perfectly describes what we are trying to do, i would like to add few more details here group service uses Elastic Search (query flexibility) and Article service uses Cassandra for storage(large volume data).
Creating one more REST endpoint in article service to accept list of id's sounds feasible, this way we will be reducing the no of article service call.
However URLs have a size limitation and we cant pass all 30K ids to one article service call.
Please share your views on this.
Comment: Yes we can do that, but that way we wont be able to achieve the parallelism we want
i.e. when we get 1 group request only one article service will be active while other instances of article service doing nothing.
Instead of sending all ids to article service in one call, we can send fixed no of id's in multiple article service call.
However this violates the rule of thumb you mentioned in answer.
Comment: True, but lets take a step back: querying 30'000 records from a DB takes as little as < 50ms if indexed correctly, plus some network overhead - I hope you have more serous problems than this! If you need it faster I recommend you look into some other industry leading tools like MemCached or something like this! Sending the 30k records over a single HTTP request is much more efficient than paying the request/response/networklatency cost for 300 (100 records / request) http requests. Another plus is that the response could be cached! My recommendation: Keep it simple - scale it when you need it!
Comment: yes, that's true for typical REST application, but in our case one request steam ~2 million records for 1 min time window and session last at-least for 180 second, so i believe its lot of overhead on only one article service.
also caching so much data is not feasible.
Can we implement Micro services architecture without sacrificing the parallelism and performance with minimal network calls.
Comment: Well there is a good reason, that typical REST applications don't do that; It's bad practise/archtecture! If a response keeps a resource busy for 180 sec. per request, this resource can only process a very small number or requests (4-36 depending on your processors Architecture) so overloading your system is very much a guarantee! Usually these kinds of usecases call for paging the result sets! Like that you could also do loadbalancing again!!
Comment: All this goes way off the original topic of your question. What I'd like to suggest to you is, that you keep reading up on microservices architectural style, all the goodies and badies, that come with it and the new challenges you will face. I get the feeling you're currently in over your head and need some more time to sketch out your architecture and ask some important questions like what kinds of loads will you get and how can you make them actually manageble, what kinds of balancing methods to use, what bounded contexts to draw etc. The list goes on and on!
Comment: Microservices are a wonderfull kind of architecture but come at a severe price in development scaling, orchestration and operational complexity. It's not for faint-hearted; are you absolutely sure, it's the way to go for you and your product?!?


how to set the same height as the parent element

Question: I would like to know to align the text in a p element to be vertically centered.
Here is my code:

p.task{font-family: Arial,Helvetica Neue,Helvetica,sans-serif; font-weight: 700;  display: table-cell; vertical-align: middle;}
span.label {float: left; width: 60px; color: red}
span.text {float: left; width: calc(100% - 60px);}
<link href="https://email@example.com/dist/katex.css" rel="stylesheet"/>

  2
  Vypočtěte jednu třetinu z \( 3^{3k+3} \) , kde \( k \space \epsilon \space Z \).

Comment: You can use ... to align your text
Answer: add vertical-center class to the p.
.vertical-center {
    display: flex;
    align-items: center;
}

or can add the above 2 style-rules within the task class.
.task {
    font-family: Arial,Helvetica Neue,Helvetica,sans-serif;
    font-weight: 700;
    display: flex;
    align-items: center;
}

Comment: Flex is great. But you need to check if all the browsers you want to support can handle it. Check out https://caniuse.com/#feat=flexbox


Lifting of a tangent bundle

Question: I have a problem with Kuranishi's theorem in deformation theory. I'll try to formulate it in general terms, and then describe the particular situation.
Let $\pi : M \to S$ be a smooth fiber bundle - i.e. $M$ and $S$ are smooth manifolds, and $\pi$ is a surjective submersion. There is an associated surjective morphism of vector bundles $ \pi_* : T_M \to \pi^* T_S$. I want to find a lifting of $\pi^* T_S$ into $T_M$.
Suppose I can find a smooth map $f : S \to M$ which satisfies $\pi \circ f = id_S$. This induces an injective map $T_S \to f^*T_M$. Can I lift this to a map $\pi^* T_S \to T_M$? How about if some extra data is given, like a metric on $S$, or a family of metrics $g_s$ on the fibers $T_M |_{M_s}$ (where $s$ is a parameter in $S$)?
Basically I'm trying to use Kuranishi's theorem to get something like Siu's canonical lifts. In this situation $M$ is the product of a fixed smooth manifold and the space of its complex structures, and $S$ is a complex manifold (open ball, even). The map $\pi$ is the passing to the quotient by the action of the group of diffeomorphisms. If we fix a hermitian metric $h$ on $M_0$, then Kuranishi gives a map $f : S \to M$ which satisfies the above hypothesis. I'm told that Kuranishi should induce a lifting of $\pi^*T_S$ into $T_M$, but I can't seem to figure out how.
Comment: I'm a bit confused. A map $\pi^* T_S\to T_M$ splitting the map $T_M\to\pi^*T_S$ is called an Ehresmann connection on $M\to S$. Ehresmann connections are sections of an affine $A$ bundle over $S$ (modeled by the vector bundle $\pi^* T_S^* \otimes K$, where $K$ is the kernel of $\pi^*$). Hence a $C^\infty$ Ehresmann connection always exists, and you can also extend a section of $A$ from a submanifold. Is $C^\infty$ not good enough?
Comment: Sure, $C^\infty$ is good enough, but there are lots of smooth splittings $T_M \to \pi^*T_S$ (any metric on $M$ gives one) and I want one induced by the map $f : S \to M$ somehow. Can we use $f$ to construct a specific Ehresmann connection?
Answer: Perhaps now you no longer need an answer, and I am not sure to have really understood your question, but anyway I tried.
My notations
In this paragraph I briefly review my notations and definitions, so that you can easily check if and how they are in agree with yours.
Given a vector bundle $\pi:E\to P$, and a smooth map $f:M\to E$, with the pull-back of $\pi$ through $f$ I mean a vector bundle $f^\ast\pi:f^\ast E\to E$ together with a smooth bundle map $\pi^\ast f$ from $f^\ast\pi$ to $\pi$ over $f$, which solve the following universal mapping problem:

if $\rho:F\to N$ is a vector bundle, $g:N\to M$ is a smooth map and $\phi$ is a smooth bundle map from $\rho$ to $\pi$ over $f\circ g$ then  there exists a unique smooth map $h:F\to f^\ast E$ with the property that $(f^\ast\pi)\circ h=g\circ\rho$ and $(\pi^\ast f)\circ h=\phi$.

The answer
When $f:M\to N$ is a smooth map, we construct $(f^\ast\tau_N,\tau_N^\ast f)$, the pullback through $f$ of $\tau_N$, the tangent bundle over $N$. From the commutative diagram $\tau_N\circ(Tf)= f\circ\tau_M$ and the previous universal property of vector bundle pullbacks we find that there exists a unique smooth map $f_\ast:TM\to f^\ast(TN)$ such that $$(\tau_N^\ast f)\circ f_\ast=Tf\ \mathrm{and}\ (f^\ast\tau_N)\circ f_\ast=\tau_M.$$
Analogously when $g:N\to M$ is another smooth map we make the same construction, and, combining commutative diagrams, it is easy to realize that $$(\tau_N^\ast f)\circ f_{\ast}\circ(\tau_M^\ast g)\circ g_\ast=T(f\circ g).$$
Now from this we conclude that:

if $f$ is a left inverse of $g$ then $(\tau_N^\ast f)\circ f_{\ast}\circ(\tau_M^\ast g)$ is a left inverse of $g_\ast$.

Lifting of a tangent bundle


Chain of map operations in Spark performance

Question: My Spark job contains a chain of map operations
JavaRDD<Row> rowRDD = raw
            .javaRDD()
            .mapPartitions(new CustomPartitionMapper())
            .map(new DataSpecialMapper(config))
            .map(new CsvFormatMapper(config))
            .map(new ReportCounters());

From the programming point of view code more readable and testable.
The question is about performance.
Will be the chain of mappers interpreted by Spark as one mapper operation and will be performed in the same executor or not? If not what may be the performance impact?
Thanks
Answer:
Will be the chain of mappers interpreted by Spark as one mapper
  operation and will be performed in the same executor or not?

Spark will optimize multiple narrow transformations into a single stage, this means that the multiple map tasks will be ran subsequently under the same task umbrella. (See this blog post for more)
But, you are still going to be iterating each of these partitions 4 * O(n) times, which is still O(n) but may at a given input size effect performance, which is always something to keep in mind.


how to make radio buttons be one under the other on drupal contact form

Question: by default the radio buttons on my drupal contact form come out next to each other and the title is very far from the actual button.
with CSS alone it doesnt work.  I seem to need to be able to edit the html which I cant do since its a drupal form. https://stackoverflow.com/questions/26432418/how-to-line-up-radio-buttons-and-text/26432623#26432623
Thanks
Comment: Hello and welcome. This is purely CSS question, I'm afraid, and it is totally dependent on the theme you are using. Simply put, you need to find the CSS part that made your radios horizontal and alter it. The rest is totally dependant on your setup.
Comment: Which theme do you use?
Comment: Can you add the html code of the form here so we can help?
Comment: the html is too long.  can I upload it somehow?
Comment: using the omega theme
Comment: Just the portion that has the radio buttons to understand the structure of your code.
Comment: this is related to drupal, because it seems to involve changing the html, which I cant do because its a drupal form http://stackoverflow.com/questions/26432418/how-to-line-up-radio-buttons-and-text/26432623#26432623
Answer: add this to each of the select button wrapper display: block; also it's not a drupal issue, you should ask these kind of question on stackoverflow
Comment: I cant add anything to the select button wrapper since the contact webform doesnt give me the option to modify the html, its created automatically
Comment: you dont have to edit the HTML, each radio button has a class associated with it, inspect the element, find the class and add the style to your CSS file
Comment: I added that, yet the words are coming out under the radios now instead of next to them.  this is what I added .form-radio{
    display: block;
}
Comment: I can't help you anymore than this unless I can see some HTML or a live demonstration of your project


My guitar plays out of tune on the high e on fretted notes up the neck

Question: I have a 1980 Washburn prairie song custom. I seem to remember it playing perfectly when I first started taking lessons, but about 2 years ago my guitar teacher gave me some strings, and after I replaced the old strings with the new ones he gave me, the high e string started playing out of tune the higher up the fretboard I go, and buzzes when I play around the 12th fret. Is this issue because of the string gauge?
Thanks!
Comment: I asked my Piano Tutor (Who also teaches Guitar) about this and He said that I'll have to adjust the truss rod. He also said that this might've happened because I keep my guitar leaning on the Wall rather than a stand or a wall mount.
Answer: Yes, that sounds like a string gauge issue: the new set is probably significantly lighter. Therefore it doesn't put as much force on the neck, which is thus bent convex by the truss-rod, the strings can't vibrate freely when you're playing in the midde of the neck, and this ruins intonation and sound.
Either release the truss-rod tension, or put on heavier strings again.
Answer: First I should mention that I change my strings every 6 months on guitars that I rarely play and every month or two on the ones that I play often.  Even strings that are not played will lose tone due to oxidation of the metal strings.
If your high e string stays in tune when played open, but plays out of tune when fretted, then you most likely have something going on that is affecting your guitars intonation.  Proper intonation is what makes a guitar's strings play in tune as you fret different notes on the fret board.  Intonation revolves around changes in the strings length when it is pressed against a fret.  The amount of change in the string length determines the amount of change in the pitch when the string is played.
To check the intonation, use a digital tuner and play the open string and be sure it is in tune.  Then play the same string on the 12th fret (same note one octave higher).  If the 12th fret note is flat or sharp, your intonation is off.
On most electric guitars you can adjust the intonation for each string individually at the bridge.  However, an acoustic guitar does not offer an intonation adjustment device for individual strings.  Acoustic guitars ideally are adjusted for intonation at the factory and most acoustic guitars have a compensated saddle that is also tilted to account for the need for the thinner strings to be slightly shorter in overall scale than the fat strings in order to maintain intonation. Unfortunately, it's difficult to achieve perfect intonation on an acoustic, but it sounds like your guitar has some significant problems.
There are several possible things that might be contributing to your intonation issue. And some would also explain the fret buzz.  Here are some things to check:
A significant change in string gauge can affect intonation to some extent as well as contribute to fret buzz.  When the guitar was originally set up in the factory, the intonation was set as best as the design of the guitar would allow.  Saddle compensation, neck relief and the action (string height above fretboard) have been set for a particular gauge string.  A string with a different amount of tension can contribute to intonation problems.
Too much or too little neck relief will change your intonation.  Neck relief is the amount of bow in the neck and can be adjusted by the truss rod.  Changing string gauge will usually necessitate a truss rod adjustment due to the change in overall string tension exerted on the neck.  Going to heavier strings will exert more pressure and without an adjustment to the truss rod to compensate, will create more neck relief.  In other words the neck will be bowed more.  Going to lighter strings will allow the neck to straighten more due to decreased tension.  If the neck is too flat or has a back bow, you will get fret buzzing as well as poor intonation.  Intonation is affected by the amount of change in the string length when your fret a note.  The neck relief affects how far you have to move the string to reach the fret and thus is related to intonation.
A loose or leaning saddle can change the length of the string and affect intonation.  Be sure that the saddle is properly positioned in the slot in the bridge and not leaning either way.  If you take all the strings off at once to re-string, it is possible for the saddle to change position.
Grooves in the saddle can also change the length of the string and affect intonation. Some saddles are plastic and easily develop grooves, particularly under the plain steel b and e strings.
Grooves in the frets can also change the length of the string and affect intonation. They can also cause fret buzz. The more you play, the more likely you are to begin wearing grooves in some of your frets.  This is particularly problematic on the frets under the plain steel b and e strings because the friction of steel against the softer nickel frets eventually wears grooves in the frets. Another thing that happens is some frets can become worn and lose their crown.  Frets are crowned to provide a small isolated contact point to aid with proper intonation.  If the frets become worn and flat, your string length will change because the contact point on the fret has changed and your intonation will be off.   If you have some deep grooves, or some of your frets are worn down, you may need to have the frets dressed, and re-crowned. Eventually if you play your guitar often enough, you will wear the frets down to the point where you need to have them all replaced (known as a re-fret).
These are a few things to check and there may be more than one of the above issues that can be contributing to your particular problem.  One other thing you might consider is to simply change the strings again and see if that helps. It's possible that you could have a defective string.
The best advice I can give you is to not only get another set of good quality new strings, but to take your guitar to a luthier or qualified guitar repair technician for a proper set up based on the string gauge you choose.  During the set up, most of the issues discussed above will be addressed or discovered.  And if there is something more serious going on (such as improper saddle compensation), they will be able to tell you what needs to be done.
Good luck.
Comment: Not applicable here since the question indicates new strings, but a couple of times over the years I've had a high e string start fretting way out of tune when it gets very corroded and old, and replacing it with a new string fixed the problem.  I have yet to understand how the age of a string would cause such a thing, but my guess is that it was somehow caused by uneven corrosion along the length of the string.
Answer: Last reply was from 2015, now we live in 2021, so i don't know if anybody will read this or is it just a message in a bottle drifting on the www.
Anyways,  problems might be caused by the thickness of the strings and being too thick for the nut groove. The string will not set to the bottom of the groove but slightly higher,  with increased action.
So first start with carefully measure string action at fret 1 and deepen and/or broaden the groove.  Than (luiters secret! ) add a minute amount of petroleum jelly on the string in the groove so the string will move smoothly.
Next, check left hand finger technique ( ;)): don't press in the middle between the frets but close to or against the fret. This will reduce vertical displacement on the pressure point and reduce string lengthening.
Answer: You'll probably find all of your strings slip out of tune more readily since you replaced the strings. There's various tricks for trying to improve this, but here's the one that's worked for me.
Pull the strings outwards, be brave, really pull it away from the fretboard. If it's gone flat compared to where it's started, retune it and start again. When pulling the string away no longer sends it flat, move on to the next string. Doing this takes the slack out of the strings around the machines. This will probably improve the situation for you.
Comment: That's great advice for stretching in your new strings.  But the question is about the high e-string playing out of tune as you move up the fret board fretting higher notes.  Sounds more like an intonation issue than a tuning issue.


How to save code snippets (vb/c#/.net/sql) to sql server

Question: I want to create a code/knowledge base where I can save my vb.net/c#.net/sqlserver code snippets for use later.
I've tried setting the ValidateRequest property to false in my page directive, and encoding the value with HttpUtility.HtmlEncode (c#.net), but I still get errors.
thoughts?
Answer: The HttpUtility.HtmlEncode will happen too late, assuming you are getting the exception on postback of code from the client. You can run some javascript on the client to pre-encode the server Postback.
See the following link for a quick example: Comparing escape(), encodeURI(), and encodeURIComponent()


Firefox fast version changes

Question: Why did Firefox main versions start to grow so fast after 2011 april (FF4)?
It is version 13 now and rapidly growing.
I read the Wikipedia article about it, which says that they wanted that users always have an up-to-date version of Firefox. But why are minor versions not appropriate? Like 4.1, 4.14, etc.
Answer: It was to keep up with chromes naming scheme for their updates, essentially uses naturally thinking bigger changes were made with a major revision change vs. a minor one.

Firefox fast version changes


CodeIgniter - Error de sintaxe com select e where

Question: Em um projeto preciso que aparece apenas as publicações ativas na página principal estou usando Codeigniter, usei as seguintes linhas de código:
Model:

$this->db->select('*');
$this->db->from("publicacoes");
$this->db->where('ativacao' == '1');
$data = $this->db->get()->result_array();

return $data;

Porém quando deixo essa linha "descomentada" a aplicação "quebra"
$this->db->where('ativacao' == '1');

Comment: Só uma dica, em vez de você usar a linha do from, já pode colocar o nome da tabela dentro do get ficando assim: $this->db->get('publicacoes')->result_array();
Answer: Altere $this->db->where('ativacao' == '1'); para $this->db->where("ativacao = '1'");
Comment: Obrigada! Funcionou +1
Answer: Segundo a documentação no site do Codeigniter, a forma "ideal" de se fazer isso seria assim:
$this->db->where('ativacao' , '1');

e quando você for usar um where <> aí fica
$this->db->where('ativacao <>' , '1');

Comment: +1 Muito Obrigada pela informação


tensorflow 2 api regression tensorflow.python.framework.ops.EagerTensor' object is not callable

Question: I am trying to implement a multivariate regression using tensorflow 2 api.
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'A': np.array([100, 105.4, 108.3, 111.1, 113, 114.7]),
                   'B': np.array([11, 11.8, 12.3, 12.8, 13.1,13.6]),
                   'C': np.array([55, 56.3, 57, 58, 59.5, 60.4]),
                   'Target': np.array([4000, 4200.34, 4700, 5300, 5800, 6400])})

X = df.iloc[:, :3].values
Y = df.iloc[:, 3].values

plt.scatter(X[:, 0], Y)
plt.show()

X = tf.convert_to_tensor(X, dtype=tf.float32)
Y = tf.convert_to_tensor(Y, dtype=tf.float32)

def poly_model(X, w, b):
    mult = tf.matmul(X, w)
    pred = tf.add(tf.matmul(X, w), b)
    return pred

w = tf.cast(tf.Variable(np.random.randn(3, 1), name='weight'), tf.float32)
b = tf.Variable(np.random.randn(), name='bias')

model = poly_model(X, w, b)

cost = tf.reduce_sum(tf.square(Y - model))

train_op = tf.optimizers.SGD(0.001)

train_op.minimize(cost, var_list=[w])

At the last line it throws me:
tensorflow.python.framework.ops.EagerTensor' object is not callable
Also, I am a bit confused:
1) How to proceed without using Session.
Just do something like : output = train_op(X)?
2) Do I need to use tf.GradientTape() as tape or this is only for graphs?
-- error trace --
TypeError                                 Traceback (most recent call last)
<ipython-input-1-ffbbbe1a3709> in <module>()
     32 train_op = tf.optimizers.SGD(0.001)
     33
---> 34 train_op.minimize(cost, var_list=[w])

~/anaconda3/envs/dpl/lib/python3.6/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py in minimize(self, loss, var_list, grad_loss, name)
    294     """
    295     grads_and_vars = self._compute_gradients(
--> 296         loss, var_list=var_list, grad_loss=grad_loss)
    297
    298     return self.apply_gradients(grads_and_vars, name=name)

~/anaconda3/envs/dpl/lib/python3.6/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py in _compute_gradients(self, loss, var_list, grad_loss)
    326     with backprop.GradientTape() as tape:
    327       tape.watch(var_list)
--> 328       loss_value = loss()
    329     grads = tape.gradient(loss_value, var_list, grad_loss)
    330

TypeError: 'tensorflow.python.framework.ops.EagerTensor' object is not callable

Comment: Have you tried enabling `eager execution`? tf.enable_eager_execution() # requires r1.7 https://www.tensorflow.org/tutorials/eager/eager_basics
Comment: @ScottSkiles:I am using tensorflow 2.0 as I said, in which the eager is enabled by default.If I check if it is enab;ed , it is true.
Comment: Ah did not realize that. Will follow up
Comment: Can you add more of the stacktrace leading up to the error message?
Comment: @ScottSkiles:I updated the question with the trace.
Answer: 2) You definitely need to use GradientTape.
Check out the Effective TF2 Guide
1)Something like this:
import tensorflow as tf
import numpy as np

print("TensorFlow version: {}".format(tf.__version__))
print("Eager execution: {}".format(tf.executing_eagerly()))

x = np.array([
    [100, 105.4, 108.3, 111.1, 113, 114.7],
    [11, 11.8, 12.3, 12.8, 13.1, 13.6],
    [55, 56.3, 57, 58, 59.5, 60.4]
])

y = np.array([4000, 4200.34, 4700, 5300, 5800, 6400])

class Model(object):
    def __init__(self, x, y):
        # Initialize variable to (5.0, 0.0)
        # In practice, these should be initialized to random values.
        self.W = tf.Variable(tf.random.normal((len(x), len(x[0]))))
        self.b = tf.Variable(tf.random.normal((len(y),)))

    def __call__(self, x):
        return self.W * x + self.b

def loss(predicted_y, desired_y):
    return tf.reduce_sum(tf.square(predicted_y - desired_y))

optimizer = tf.optimizers.Adam(0.1)
# noinspection PyPep8Naming
def train(model, inputs, outputs):
    with tf.GradientTape() as t:
        current_loss = loss(model(inputs), outputs)
    grads = t.gradient(current_loss, [model.W, model.b])
    optimizer.apply_gradients(zip(grads,[model.W, model.b]))
    print(current_loss)

model = Model(x, y)

for i in range(10000):
    # print(model.b.numpy())
    train(model,x,y)

Comment: I am not sure..It doesn't state anywhere that is mandatory.Only recommended.
Comment: From what I understand, that's how gradients are calculated and applied with eager execution
Comment: This page may help https://www.tensorflow.org/alpha/tutorials/eager/custom_training_walkthrough
Comment: @DecentGradient: Nice one!for a great answer it would be really helpful if you explained how to fix the problem using GradientTape!
Comment: Also, I don't see anything in your link? Can you link to something more specific than the entire 2.0 change notes?
Comment: I will look into doing the rewrite tomorrow
Comment: @DecentGradient:Ok, thanks for the help. (If you use the `train_op.minimize(cost, var_list=[w])` though throws the error message)