Animation from instantiated object not working

Question: i am trying to make door open when i shoot the target in 2D but as title says it doesnt work.
In specialPipe prefab i got children that is pipe and it has animation to pull down that pipe that acts as a door.
Only first object works but his clones immediately opens door(animation activates immediately instead when its trigered). sorry for bad english.
Target script that has animation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetScript : MonoBehaviour
{

    public Animator anim;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        anim = GameObject.FindGameObjectWithTag("BottomPipe").GetComponent<Animator>();
        anim.enabled = false;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        anim.enabled = true;
        Destroy(gameObject);
    }
}

spawner script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PipeSpawnScript : MonoBehaviour
{
    public GameObject pipe;
    public GameObject specialPipe;
    public float spawnRate = 2;
    private float timer = 0;
    public float heightOffset = 10;
    // Start is called before the first frame update
    void Start()
    {
        spawnPipe();
    }

    // Update is called once per frame
    void Update()
    {

        if(timer < spawnRate)
        {
            timer += Time.deltaTime;
        }else
        {
                spawnPipe();
                timer = 0;
        }
    }

    void spawnPipe()
    {
        float lowestPoint = transform.position.y - heightOffset;
        float highestPoint = transform.position.y + heightOffset;
        float randomNumber = Random.Range(0, 10);

        if(randomNumber < 2)
            Instantiate(pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
        else
        {
            GameObject test = Instantiate(specialPipe, new Vector3(transform.position.x + 10, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
            Animator anim = test.GetComponentInChildren<Animator>();
            anim.Rebind();
        }

    }
}

I googled and found that Animator.rebind() should fix that but it doesnt work for me.
Hope to find answer and ty in advance.
Comment: Since it isn't part of your question/not a problem for you yet, I'll write it here. Move the stuff that you have in your `Update` function of your "TargetScript" to the `Start` function. The way it is right now is needlessly wasteful and will stop your animation one frame in.
Answer:
[FindGameObjectWithTag] returns the first GameObject it finds with the specified tag. [...] there is no guarantee this method will return a specific GameObject.

When you're script is running and searching for a "BottomPipe" tagged object Unity goes down the hierarchy tree checking every object for that tag. If finds the original object and disables the animation. The next instance of your "TargetScript" does the same thing. It always reaches the original object, says "mission accomplished" and peaces out, thus never deactivating your animation when it should.
In your case you should use GetComponentInChildren, since the pipe with the animator component is a child of the object that is running your "TargetScript".
If for some reason you have multiple children with animator components (and this at risk of the first problem occuring again), you can first pick out the child object that you want with Transform.GetChild and then get the component using the classic Component.GetComponent approach.


Image not showing up on pygame screen

Question: I am making my own game with pygame for the first time, and I'm using sprites. I'm trying to blit an image onto the screen but it doesn't work. All it shows is a blank white screen.
Here is the code:
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)
class SpriteSheet(object):
    def __init__(self, file_name):
        self.sprite_sheet = pygame.image.load(file_name).convert()
    def get_image(self, x, y, width, height):
        image = pygame.Surface([width, height]).convert()
        image.blit(self.sprite_sheet, (0, 0), (x, y, width, height))
        image.set_colorkey(BLACK)
        return image

class Bomb(pygame.sprite.Sprite):
    change_x =0
    change_y = 0
    def __init__(self):
        image = pygame.Surface([256, 256]).convert()
        sprite_sheet = SpriteSheet("Bomb_anim0001.png")
        image = sprite_sheet.get_image(0, 0, 256, 256)

pygame.init()
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    screen.fill(WHITE)
    bomb  = Bomb()
    clock.tick(60)
    pygame.display.flip()
pygame.quit()

This is the image:
Click on this link.
Any help will be highly appreciated. Thanks!
Answer: You must blit the image on the screen Surface.
But there is more to be done. Add a rect attribute to the Bomb class:
class Bomb(pygame.sprite.Sprite):

    def __init__(self, x, y):
        super().__init__()
        sprite_sheet = SpriteSheet("Bomb_anim0001.png")
        self.image = sprite_sheet.get_image(0, 0, 256, 256)
        self.rect = self.image.get_rect(topleft = (x, y)
        self.change_x = 0
        self.change_y = 0

Create a pygame.sprite.Group and add the bomb to the Group. draw all the sprites in the Group on the screen:_
bomb  = Bomb(100, 100)
all_sprites = pygame.sprite.Group()
all_sprites.add(bomb)

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    screen.fill(WHITE)
    all_sprites.draw(screen)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

pygame.sprite.Group.draw() and pygame.sprite.Group.update() are methods which are provided by pygame.sprite.Group.
The former delegates the to the update mehtod of the contained pygame.sprite.Sprites - you have to implement the method. See pygame.sprite.Group.update():

Calls the update() method on all Sprites in the Group [...]

The later uses the image and rect attributes of the contained pygame.sprite.Sprites to draw the objects - you have to ensure that the pygame.sprite.Sprites have the required attributes. See pygame.sprite.Group.draw():

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]
Comment: Gives me an error- "self.rect = self.image.get_rect()
AttributeError: 'Bomb' object has no attribute 'image' ". What should I do?
Comment: Haha, can't believe I missed that! But it looks like errors can't leave me alone XD Now I get this: ```File "C:\Users\\AppData\Local\Programs\Python\Python38\lib\site-packages\pygame\sprite.py", line 159, in add_internal
    self.__g[group] = 0
AttributeError: 'Bomb' object has no attribute '_Sprite__g'```
Comment: I had that in my code, but it was giving me errors so I removed it. Can you please give me a brief explanation of what it does? And thank you so very much for your help, I spent hours trying to fix this.
Comment: @PianoPianist It is used to invoke the constructor of the base class `pygame.sprite.Sprite`. See [`super()`](https://docs.python.org/3/library/functions.html#super)

Image not showing up on pygame screen


Can I replace the distribution in Gaussian Process Regression with a different regression?

Question: Sorry for the confusing title. Let me try to clarify:
I have a time series of wind speeds with some missing points here and there. I want to interpolate these points and have tried mainly polynomial and spline interpolation (also weighted interpolation), but for some cases, these just did not work well. Moreover, these interpolation methods do not take into account what a reasonable wind speed value range would be.
Looking into Gaussian Process Regression (GPR), that seems to basically do what I want and uses an underlying Gaussian distribution for the regression / interpolation.
What I am now wondering is if it is possible to use the underlying principle of GPR with a distribution different than Gaussian distribution (e.g. Weibull distribution would make a lot of sense for wind speeds). If I understood it correctly, the used kernel is independant of the distribution, so the kernel should not be a problem here.
So, would it be possible to simply replace the distribution for this method? Or is it simply not possible for some mathematical reason? I have a quite weak mathematical understanding of the GPR, so that is entirely possible. The Wiki article on the topic was pretty hard to understand for me, so I would appretiate it if you could include a simple-to-understand explanation in your answers.
Thanks a lot in advance!
Answer: Disclaimer: This is an unfinished answer which still needs some (mathematical / research / googling) work. Feel free to downvote if there is somebody with more experience concerning Weibull processes...

So, would it be possible to simply replace the distribution for this method? Or is it simply not possible for some mathematical reason?

Let us quickly review how Gaussian Processes work. The first assumption is that there is some space $T$ from which the indices of random variables $(X_t)_{t \in T}$ come. In your case, $T$ is probably a series of times (like $T = \{0,1,2,...\}$) and $X_t$ resembles the windspeed at day/hour/second $t$.
In Gaussian processes one assumes that for any finite subset $t_1, ..., t_n$ of times, $(X_{t_1}, ..., X_{t_n})$ is distributed with a density being a multivariate normal distribution $\mathcal{N}(\Sigma, \mu)$ with covariance matrix $\Sigma = (k(t_i, t_j)_{i,j=1,...,n})$ and mean $\mu = (\mu(t_i))_{i=1,...,n}$. So far there is nothing special about this multivariate distribution (i.e. up until now we could easily replace it by another multivariate distribution).
What is so special about the multivariate normal distribution / why don't people use another one?
Well, the unique property of the multivariate normal distribution is that given a 'new' $t_{n+1}$, we can find an explicit expression for the density
  $$f_{X_{t_{n+1}}|X_{t_1}, ..., X_{t_{n}}}(x_{t_{n+1}}|x_{t_1}, ..., x_{t_{n}}) = \frac{f_{X_{t_{n+1}},X_{t_1}, ..., X_{t_{n}}}(x_{t_{n+1}},x_{t_1}, ..., x_{t_{n}})}{f_{X_{t_1}, ..., X_{t_{n}}}(x_{t_1}, ..., x_{t_{n}})}$$
because using a somewhat involved computation one can show the following:
If the whole covariance matrix of $(X_{t_{n+1}},X_{t_{1}}, ..., X_{t_{n}})$ matrix looks like
$$\Sigma_{\text{all}} = \begin{pmatrix} \Sigma_{n+1,n+1} & \Sigma_{n+1,*}^T \\ \Sigma_{n+1,*} & \Sigma_{*,*} \end{pmatrix} = \begin{pmatrix} k(t_{n+1}, t_{n+1}) & k(t_{n+1}, *)^T \\ k(t_{n+1}, *) & k(*,*)\end{pmatrix}$$
i.e.
$$\Sigma_{n+1,*}^T = (k(t_{n+1}, t_1), ..., k(t_{n+1}, t_n))$$
(the covariance pairing between the 'new' point $x_{t_{n+1}}$ and the 'old'/'known' ones $x_{t_1}, ..., x_{t_n}$)
and
$$\Sigma_{*,*} = (k(t_i, t_j))_{i,j=1,...,n}$$
(the covariance matrix on the 'old'/'known' points $x_{t_1}, ..., x_{t_n}$
and if we write the mean of all variables as
$$\mu = (\mu(t_{n+1}), \mu_*)$$
where $\mu_* = (\mu(t_1), ..., \mu(t_n))$
then
$f_{X_{t_{n+1}}|X_{t_1}, ..., X_{t_{n}}}$ is a multivariate normal distribution again and
$$f_{X_{t_{n+1}}|X_{t_1}, ..., X_{t_{n}}} = \mathcal{N}(\Sigma', \mu')$$
with
$$\Sigma' = k(t_{n+1}, t_{n+1}) - \Sigma_{n+1,*}^T (\Sigma_{*,*})^{-1} \Sigma_{n+1,*}$$
and
$$\mu' = \mu(t_{n+1}) + \Sigma_{n+1,*}^T (\Sigma_{*,*})^{-1}((x_{t_1}, ..., x_{t_n})^T - \mu_*)$$
In one sentence:
What is so special about the multivariate normal distribution / why don't people use another one?
The predictive distribution still belongs to the same class of distributions and given the values $x_{t_1}, ..., x_{t_n}$ and the new point $x_{t_{n+1}}$ we can explicitly compute the parameters (and therefor the distribution itself).
Things you have to do if you want to do this with the Weibull distribution:

First of all make sure that there is a multivariate Weibull distribution. this seems to indicate that there is such a thing and how to compute it.
Carry out the involved computation to verify that f_{X_{t_{n+1}}|X_{t_1}, ..., X_{t_{n}}} is a univariate Weibull distribution with parameters that can be explicitly computed from the values $x_{t_1}, ..., x_{t_n}, x_{t_{n+1}}$ and the parameters of the distribution of $x_{t_1}, ..., x_{t_n}$.

However, this might be math heavy (I did not try it yet) and it might be the case that somebody already did this...
Hope this helps...
PS: Even I do not understand what this Kriging is about and how exactly it is related to Gaussian Processes from the Wikipedia page :-)
Comment: Thanks a lot for the detailed answer! I did not know about these properties of a multivariate normal distribution. I will have to read more into this...

Regarding Kriging, from what I read, it is the same as 'Gaussian Process Regression', and the method was first used a lot in geostatistics and was named after a certain scientist, and I guess later it became clearer that it is basically the same thing as GPR... that's at least how I understood it.


Importing and converting specific attributes of JSON files in R

Question: I have been given a rather large corpus of conversational data with which to import the relevant information into R and run some statistical analysis.
The problem is I do not need half the information provided in each entry. Each line in a specific JSON file from the dataset relates to a particular conversation of the nature A->B->A. The attributes provided are contained within a nested array for each of the respective statements in the conversation. This is best illustrated diagrammatically:
What I need is to simply extract the 'actual_sentence' attribute from each turn (turn_1,turn_2,turn_3 - aka A->B->A) and remove the rest.
So far my efforts have been in vain as I have been using the jsonlite package which seems to import the JSON fine but lacks the 'tree depth' to discern between the specific attributes of each turn.
An example:
The following is an example of one row/record of a provided JSON formatted .txt file:
{"semantic_distance_1": 0.375, "semantic_distance_2": 0.6486486486486487, "turn_2": "{\"sentence\": [\"A\", \"transmission\", \"?\"], \"script_filename\": \"Alien.txt\", \"postag\": [\"AT\", null, \".\"], \"semantic_set\": [\"infection.n.04\", \"vitamin_a.n.01\", \"angstrom.n.01\", \"transmittance.n.01\", \"transmission.n.05\", \"transmission.n.02\", \"transmission.n.01\", \"ampere.n.02\", \"adenine.n.01\", \"a.n.07\", \"a.n.06\", \"deoxyadenosine_monophosphate.n.01\"], \"additional_info\": [], \"original_sentence\": \"A transmission?\", \"actual_sentence\": \"A transmission?\", \"dependency_grammar\": null, \"actor\": \"standard\", \"sentence_type\": null, \"ner\": {}, \"turn_in_file\": 58}", "turn_3": "{\"sentence\": [\"A\", \"voice\", \"transmission\", \".\"], \"script_filename\": \"Alien.txt\", \"postag\": [\"AT\", \"NN\", null, \".\"], \"semantic_set\": [\"vitamin_a.n.01\", \"voice.n.10\", \"voice.n.09\", \"angstrom.n.01\", \"articulation.n.03\", \"deoxyadenosine_monophosphate.n.01\", \"a.n.07\", \"a.n.06\", \"infection.n.04\", \"spokesperson.n.01\", \"transmittance.n.01\", \"voice.n.02\", \"voice.n.03\", \"voice.n.01\", \"voice.n.06\", \"voice.n.07\", \"voice.n.05\", \"voice.v.02\", \"voice.v.01\", \"part.n.11\", \"transmission.n.05\", \"transmission.n.02\", \"transmission.n.01\", \"ampere.n.02\", \"adenine.n.01\"], \"additional_info\": [], \"original_sentence\": \"A voice transmission.\", \"actual_sentence\": \"A voice transmission.\", \"dependency_grammar\": null, \"actor\": \"computer\", \"sentence_type\": null, \"ner\": {}, \"turn_in_file\": 59}", "turn_1": "{\"sentence\": [\"I\", \"have\", \"intercepted\", \"a\", \"transmission\", \"of\", \"unknown\", \"origin\", \".\"], \"script_filename\": \"Alien.txt\", \"postag\": [\"PPSS\", \"HV\", \"VBD\", \"AT\", null, \"IN\", \"JJ\", \"NN\", \".\"], \"semantic_set\": [\"i.n.03\", \"own.v.01\", \"receive.v.01\", \"consume.v.02\", \"accept.v.02\", \"rich_person.n.01\", \"vitamin_a.n.01\", \"have.v.09\", \"have.v.07\", \"nameless.s.01\", \"have.v.01\", \"obscure.s.04\", \"have.v.02\", \"stranger.n.01\", \"angstrom.n.01\", \"induce.v.02\", \"hold.v.03\", \"wiretap.v.01\", \"give_birth.v.01\", \"a.n.07\", \"a.n.06\", \"deoxyadenosine_monophosphate.n.01\", \"infection.n.04\", \"unknown.n.03\", \"unknown.s.03\", \"get.v.03\", \"origin.n.03\", \"origin.n.02\", \"transmittance.n.01\", \"origin.n.05\", \"origin.n.04\", \"one.s.01\", \"have.v.17\", \"have.v.12\", \"have.v.10\", \"have.v.11\", \"take.v.35\", \"experience.v.03\", \"intercept.v.01\", \"unknown.n.01\", \"iodine.n.01\", \"strange.s.02\", \"suffer.v.02\", \"beginning.n.04\", \"one.n.01\", \"transmission.n.05\", \"transmission.n.02\", \"transmission.n.01\", \"ampere.n.02\", \"lineage.n.01\", \"unknown.a.01\", \"adenine.n.01\"], \"additional_info\": [], \"original_sentence\": \"I have intercepted a transmission of unknown origin.\", \"actual_sentence\": \"I have intercepted a transmission of unknown origin.\", \"dependency_grammar\": null, \"actor\": \"computer\", \"sentence_type\": null, \"ner\": {}, \"turn_in_file\": 57}", "syntax_distance_1": null, "syntax_distance_2": null}

As you can see there is a great deal of information that I do not need and given my poor knowledge of R, importing it (and the rest of the file it is contained within) in this form leads me to the following in R:
The command used for this was:
json = fromJSON(paste("[",paste(readLines("JSONfile.txt"),collapse=","),"]"))

Essentially it is picking up on syntax_distance_1, syntax_distance_2, semantic_distance_1,semantic_distance_2 and then lumping all of the turn data into three enormous and unstructured arrays.
What I would like to know is if I can somehow either:

Specify a tree depth that enables R to discern between each of the 'turn' variables

OR

Simply cherry pick the turn$actual_sentence information from the outset and remove all the rest in the import process.

Hope that is enough information, please let me know if there is anything else I can add to clear it up.
Answer: Since in this case you know that you need to go one level deeper, what you can do is use one of the apply functions to parse the turn_x strings. The following snippet of code illustrates the basic idea:
# Read the json file
json_file <- fromJSON("JSONfile.json")
# use the apply function to parse the turn_x strings.
# Checking that the element is a character helps avoid
# issues with numerical values and nulls.
pjson_file <- lapply(json_file, function(x) {if (is.character(x)){fromJSON(x)}})

If we look at the results, we see that the whole data structure has been parsed this time. To access the actual_sentence field, what you can do is:
> pjson_file$turn_1$actual_sentence
[1] "I have intercepted a transmission of unknown origin."
> pjson_file$turn_2$actual_sentence
[1] "A transmission?"
> pjson_file$turn_3$actual_sentence
[1] "A voice transmission."

If you want to scale this logic so that it works with a large dataset, you can encapsulate it in a function that would return the three sentences as a character vector or a dataframe if you wish.
Comment: How do I process a file with multiple lines?

i.e. Is there a specific notation to address each of the 'turns' on a specific line? (e.g. `pjson_file$turn_2$actual_sentance$2` - for the second line actual sentence contents in a given json file?)
Comment: Can you give an example? If the lines are delineated by `\n` then I think you can just split the actual sentence on `\n` and get to whatever line you need. So for example if your actual sentence looked like this: `"My actual sentence line1\nMy actual sentence lin2"`. To get to the second line, split the string on `\n` and get the second item in the vector, as follows: `unlist(strsplit("My actual sentence line1\nMy actual sentence lin2", "\n"))[2]`. In your code, it would look like this: `unlist(strsplit(pjson_file$turn_2$actual_sentance, "\n"))[2]`.


Texto temporário em JLabel

Question: Gostaria de trocar o texto de um JLabel e deixa-lo por apenas alguns segundos, depois voltar o texto anterior. Tenho que executar um método que leva alguns segundos para ficar pronto e gostaria de notificar o usuário de que está sendo executado e deste modo pareceu-me mais simples.
Da forma abaixo não funciona como esperado:
jLabel1.setText("texto);

Comment: Tá usando swing? Se sim, provavelmente vai precisar usar [SwingWorker](http://www.javacreed.com/swing-worker-example/)
Comment: Como assim? Você quer alterar o texto de um jlabel por algum tempo e depois voltar ao texto anterior?
Comment: Exatamente isto !
Comment: No caso tenho que executar um método que leva alguns segundos para ficar pronto e gostaria de notificar o usuário de que está sendo executado e deste modo pareceu-me mais simples. Se você souber alguma outra forma mais simples ou eficiente de fazer isto acontecer eu também ficaria grato em saber.
Comment: Vou pesquisar a respeito, obrigado por ajudar :D
Comment: Foi uma sugestão, mas logo logo alguém responde com um exemplo pratico.
Comment: Por que não troca o texto normalmente (do jeito que você está fazendo) e - quando esse método demorado terminar - você troca de novo exatamente do mesmo jeito? (claro que levando em conta o *thread* certo, seja via `SwingWorker` ou de qualquer outro meio)
Comment: Então, sou novato e não sei como posso fazer isto. Vou procurar algum material sobre Thread pra ver.
Answer: A pergunta é antiga, mas já que ninguém respondeu, resolvi deixar uma solução que desenvolvi por acaso.

É possível fazer esta restauração de texto usando SwingWorker. Lembrando que, caso esse tempo de espera seja para executar algo mais demorado, você pode delegar ao SwingWorker essa atividade também, dentro do método doInBackground(). Veja um exemplo abaixo, onde eu personalizei uma classe que estende JLabel, configurando um método exclusivo para essa finalidade:
import java.awt.*;
import javax.swing.*;

public class JLabelWithTimerTest extends JFrame {

    private static final long serialVersionUID = 1L;
    private CustomLabel label;
    private JButton btn;
    private JPanel pane;

    public JLabelWithTimerTest() {
        setTitle("JLabel with Timer");
        setPreferredSize(new Dimension(300, 200));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pane = new JPanel(new GridBagLayout());
        setContentPane(pane);

        label = new CustomLabel("Texto inicial...");
        GridBagConstraints gbc1 = new GridBagConstraints();
        gbc1.gridx = 1;
        gbc1.gridy = 0;
        gbc1.weightx = 1.0;
        gbc1.weighty = 1.0;
        pane.add(label, gbc1);

        btn = new JButton("disparar");
        btn.addActionListener(e -> label.setTransientText("texto temporario", 2000));

        GridBagConstraints gbc2 = (GridBagConstraints) gbc1.clone();
        gbc2.gridx = 1;
        gbc2.gridy = 3;
        pane.add(btn, gbc2);

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    class CustomLabel extends JLabel {

        private static final long serialVersionUID = 1L;
        private SwingWorker<Void, Void> worker;

        public CustomLabel() {
            super();
        }

        public CustomLabel(String text) {
            super.setText(text);
        }

        public void setTransientText(String text, long duration) {

            if (worker != null && !worker.isDone()) return;

            final String originalText = getText();
            worker = new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                    setText(text);
                    Thread.sleep(duration);
                    return null;
                }

                @Override
                protected void done() {
                    setText(originalText);
                }
            };
            worker.execute();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(JLabelWithTimerTest::new);
    }
}

Funcionando:

O método SetTransientText() recebe o texto temporário e a duração, em milissegundos. No exemplo, o texto dura 2 segundos.
Lembrando que, pelo fato do SwinWorker rodar numa Thread a parte, o Thread.sleep não trava a interface gráfica.

Texto temporário em JLabel


Get (all) post data of specific category into a variabele

Question: I have some problems getting all the data of a post. I have tried several things but can't get it to work. What can I do?
Here is a function I wrote to get the post data:
function wptGetPostData( $sGategory, $sField = null, $iIndex = null )
{
 global $WPT_POST_DATA, $wp_query;

 if( !is_array( $WPT_POST_DATA ))
 {
  var_dump( $sGategory );
  $WPT_POST_DATA = array();
  $oOpt = array(
              'category_name' => $sGategory, // get posts by category name
             'posts_per_page' => -1 // all posts
             );

  query_posts( $oOpt );
  // var_dump( have_posts() );
   while(have_posts())
   {
     var_dump( 'loop' );
     $WPT_POST_DATA[] = $wp_query->get_post_format(); //(array('echo'=>false));
     //echo the_title();
     //echo the_content();
   }
  //var_dump( $wp_query->posts ); die;
   wp_reset_query();
 }
 var_dump( $WPT_POST_DATA );

 // other code here ...

 return null;
}

The $WPT_POST_DATA is a cache and must contain all posts (max 5 elements). Can somebody help me with this?
Answer: Try this:
//     1) Through Title:
//     The function is case insensitive, so we can use lower case
$my_post = get_page_by_title( 'hello world', OBJECT, 'post' );

<?php echo get_the_title( $my_post->ID ); ?>

echo $my_post->post_content;

//     OR to Avoid The Pitfall
echo apply_filters( 'the_content', $my_post->post_content );

//      2) Through Category ID:
<?php query_posts('cat=3&posts_per_page=1'); ?>

<?php while (have_posts()) : the_post(); ?>
    <?php the_content(); ?>
      <?php endwhile; ?>

<?wp_reset_query(); ?>

Thanks.
Comment: Appreciate your answer but is not what I want. I really hate the php4 spaghetti style of coding in Wordpress (but need to use Wordpress for a client) and I use whole templates to format the output. I want to get this in a variable but documentation is not clear how to do this.
Comment: Which things do you want to use through variable...? you have to create post with a category, i think it should be easy way to get all things of post.
Answer: Got it!
function suIsValidString( &$s, &$iLen = null, $minLen = null, $maxLen = null )
{
  if( !is_string( $s ) || !isset( $s{0} ))
   { return false; }

  if( $iLen !== null )
   { $iLen = strlen( $s ); }

  return (( $minLen===null?true:($minLen > 0 && isset( $s{$minLen-1} ))) &&
           $maxLen===null?true:($maxLen >= $minLen && !isset( $s{$maxLen})));
}

// -- ** -- Template functions

function wptGetCategoryIdByName( $sName )
{
 $oTerm = get_term_by( 'name', $sName, 'category' );
 return (is_object( $oTerm ) && isset( $oTerm->term_id ))?$oTerm->term_id:null;
}

function wptGetPostData( $sCategory, $sField = null, $iIndex = null )
{

 global $WPT_POST_DATA;
 $bCategory   = ( suIsValidString( $sCategory ) );
 $bIsInit     = ( is_array( $WPT_POST_DATA ));
 $uIndex      = $bCategory?$sCategory:0;
 $sFieldName  = ( suIsValidString( $sField )?$sField:'content' );

 if( !$bIsInit || !isset( $WPT_POST_DATA[$uIndex] ))
 {
   if( !$bIsInit )
    { $WPT_POST_DATA = array(); }

   // wp_reset_query();
   //$category_query = new WP_Query( array( 'cat' => wptGetCategoryIdByName($sCategory)) );
  $bValid = true;
  $iCategory = null;
  if( $bCategory )
   {
     $iCategory = wptGetCategoryIdByName($sCategory);
     $bValid = ( is_numeric( $iCategory ) && $iCategory >= 0 );
     if( !$bValid )
      { $iCategory = null; }
   }

   $sQuery = 'numberposts=-1'.(($iCategory !== null)?('&cat='.$iCategory):null);
   $WPT_POST_DATA[$uIndex] = $bValid?get_posts( $sQuery ):array();
    /*
   if( $bCategory )
     {
      var_dump( $uIndex );
      var_dump( $WPT_POST_DATA[$uIndex] );  }
   */
   if( !is_array( $WPT_POST_DATA[$uIndex] ))
    {  $WPT_POST_DATA[$uIndex] = array(); }
 }

 if( $sFieldName === 'count' )
  {
    //var_dump( $WPT_POST_DATA[$uIndex] ); die;
    return count( $WPT_POST_DATA[$uIndex] );
 }

$iAutoIndex = 0;
 if( !isset( $WPT_POST_DATA[$uIndex]['autocounter'] ))
  { $WPT_POST_DATA[$uIndex]['autocounter'] = $iAutoIndex; }
 else { $iAutoIndex=(++$WPT_POST_DATA[$uIndex]['autocounter']); }
 if( !is_numeric( $iIndex ))
  { $iIndex = $iAutoIndex; }

 $uResult = null;
 // var_dump( $WPT_POST_DATA[$uIndex][$iIndex]->post_content );
 if( isset( $WPT_POST_DATA[$uIndex][$iIndex])  && is_object( $WPT_POST_DATA[$uIndex][$iIndex] ))
 {
  $sPostPrefixName = 'post_'.$sFieldName;
  if( isset( $WPT_POST_DATA[$uIndex][$iIndex]->$sPostPrefixName ))
   { $uResult = &$WPT_POST_DATA[$uIndex][$iIndex]->$sPostPrefixName; }
  elseif( isset( $WPT_POST_DATA[$uIndex][$iIndex]->$sFieldName ))
   { $uResult = &$WPT_POST_DATA[$uIndex][$iIndex]->$sFieldName; }
 }

 if( suIsValidString( $uResult ))
 {
    $uResult = utf8_decode( $uResult );
    suSpecialCharsToHtml( $uResult );
 }
 //var_dump( $uResult );
 return $uResult;
}

Usage:
  $sMyString = wptGetPostData( 'mycat', 'content' );
  var_dump( $sMyString );

That's it!


Why does LaTeX include padding/margin on the left side of the document by default, and how can I get rid of it?

Question: I have the following LaTeX code:
\documentclass{report}

\usepackage[margin=0cm]{geometry}
\usepackage{lipsum}

\begin{document}

    \begin{minipage}[t]{0.5\textwidth}
        \lipsum
    \end{minipage}
    \begin{minipage}[t]{0.5\textwidth}
        \lipsum
    \end{minipage}

\end{document}

The resulting document looks like this:

The whole document seems to be shifted to the right. There is spacing at the left edge, while at the same time the text is overflowing on the right side. Why is that?
My code is pretty simplistic, I do not see why this spacing should be there, and how I could get rid of it. Thanks in advance for any input on this!
Comment: Non-programming questions about LaTeX are best suited for [TeX & LaTeX SE](https://tex.stackexchange.com/)
Answer: To distinguish between paragraphs, latex by default indents the first line of every new paragraph. You can switch this off either by using \noindent before the paragraph or globally by changing the \parindent.
Also note that your unprotected line endings will act like spaces and this your line with two .5\textwidth minipages is actually wider than the available text width.
\documentclass{report}

\usepackage[margin=0cm]{geometry}
\usepackage{lipsum}

\setlength{\parindent}{0pt}

\begin{document}

    \begin{minipage}[t]{0.5\textwidth}
        \lipsum[2]
    \end{minipage}%
    \begin{minipage}[t]{0.5\textwidth}
        \lipsum[2]
    \end{minipage}%

\end{document}


What's going on with my onclick function for my submit button?

Question: Here's what I'm trying to do for my project. I have a simple content box wrapped in a div tag. There are paragraphs added in and have their own id for rules on their own. I've set the margins, the padding, so on and so on. Then at the bottom, I've added a typical submit button. What I labeled that was show more. With overflow going on inside my content box, I want to increase the height so that it can show the rest of the text. However, when I add in the onclick command with the anonymous function with if/else statements, things get a bit jarring.
Here's the HTML code first.

    var content = document.getElementById('contentbox');
    var button = document.getElementById('showMore');

    button.onclick = function() {
     if(content.className == "open") {
      content.className = "";
     } else {
      content.className = "open";
     }
    };
    body {
     padding:0;
     margin:0;
     font-family:sans-serif;
    }

    #contentbox {
     margin:100px 300px 100px 300px;
     border:1px solid black;
     padding:5px 0px 5px 20px;
     max-height:200px;
     overflow:hidden;
     background:silver;
     border-radius:10px;

    }
    #contentbox.open {
     max-height:1000px;
     overflow:visible;
    }
    #content {
     color:white;
     font-size:20px;
     text-indent:30px;
    }

    #showMore {
     margin-left:auto;
     margin-right:auto;
     display:block;
     background:gray;
     font-size:40px;
     text-transform:uppercase;
     font-family:impact;
     color:silver;
     transition:all 0.5s ease-in-out;
    }
    #showMore:hover {
     color:gray;
     background:silver;
     cursor:pointer;
    }

     <title>Kenneth's new HTML/CSS Exercise</title>
     <meta charset="UTF-8">
     <link rel='stylesheet' type='text/css' href='contentbox.css'>

    this is a bunch of text for you to read and Game of Thrones is an American fantasy drama television series created by David Benioff and D. B. Weiss. It is an adaptation of A Song of Ice and Fire, George R. R. Martin's series of fantasy novels, the first of which is A Game of Thrones. It is filmed at Titanic Studios in Belfast, on location in the United Kingdom, and in Croatia, Iceland, Malta, Morocco, Spain, and the United States. The series premiered on HBO in the United States on April 17, 2011, and its sixth season ended on June 26, 2016. The series was renewed for a seventh season,[1] which is scheduled to premiere on July 16, 2017.[2] The series will conclude with its eighth season in 2018

 Set on the fictional continents of Westeros and Essos, Game of Thrones has several plot lines and a large ensemble cast. The first story arc follows a dynastic conflict among competing claimants for succession to the Iron Throne of the Seven Kingdoms, with other noble families fighting for independence from the throne. The second covers attempts to reclaim the throne by the exiled last scion of the realm's deposed ruling dynasty; the third chronicles the threat of the impending winter and the legendary creatures and fierce peoples of the North.

 Game of Thrones has attracted record viewership on HBO and has a broad, active, international fan base. It has been acclaimed by critics, particularly for its acting, complex characters, story, scope, and production values, although its frequent use of nudity and violence (including sexual violence) has attracted criticism. The series has received 38 Primetime Emmy Awards, including Outstanding Drama Series in 2015 and 2016, more than any other primetime scripted television series. Its other awards and nominations include three Hugo Awards for Best Dramatic Presentation (2012–2014), a 2011 Peabody Award, and four nominations for the Golden Globe Award for Best Television Series – Drama (2012 and 2015–2017). Of the ensemble cast, Peter Dinklage has won two Primetime Emmy Awards for Outstanding Supporting Actor in a Drama Series (2011 and 2015) and the Golden Globe Award for Best Supporting Actor – Series, Miniseries or Television Film (2012) for his performance as Tyrion Lannister. Lena Headey, Emilia Clarke, Kit Harington, Maisie Williams, Diana Rigg, and Max von Sydow have also received Primetime Emmy Award nominations for their performances in the series.

    <input type='submit' value='Show more' id="showMore"></input>

What's going on and what do I have to do to fix it?
Comment: submit buttons submit
Comment: huh? What exactly do you mean?
Comment: submit button submits the page so the state of the page is reset.
Comment: That's not true @epascarello the button on click is not submitting a form.
Comment: @SeanNewell So `type="submit"` does not submit? ``
Comment: It could be true, so your point might be valid in a different context. If the button was in a form tag, then the on click handler should return false so the form does not get submitted. But the submit input is not in a form.
Answer: Try to do this:
var content = document.getElementById('contentbox');
var button = document.getElementById('showMore');

button.onclick = function(e) {
    e.preventDefault();
    //do your logic
    if(content.className == "open") {
        content.className = "";
    } else {
        content.className = "open";
    }
    //
};

In that way you prevent submit event that skip your logic.
But you need to submit form manually after all actions in this case.
Answer: Set it to height not Max height
hope it helps
Answer: Here's what is happening.
The .open styles overflow: visible property makes it so that the text keeps getting drawn by the browser even after the max height of the box. You probably don't want that.
If you do this instead, height will be calculated based on content.
#contentbox.open {
  height: auto;
  max-height: initial;
}

Working jsfiddle
The overflow property shouldn't be changed unless you want to change scroll behavior (usually). The max-height initial will override the maximum height.
If you want a scroll bar instead, do this:
#contentbox.open {
  overflow: auto;
}

And you can change the max-height if you wanted to still.
Hope that was a good explanation.

Other users have pointed out that your button is a submission button. That may cause problems because it could trigger a page load, nullifying anything you're trying to do. On the previous jsfiddle link the button does not submit a form, so the code works as is (without returning false, changing the button type, or stopping propagation).
But you might want to change your click handler to return false if you are not submitting a form, like this paste bin shows (which is an all-in-one solution just like the jsfiddle).
Or, you could remove the type='submit' from your button, I think that would work too.
Comment: It didn't work at all for some reason. Any other thing that might work?
Comment: That worked for me on a jsfiddle. Look in the debugger (F12) and inspect the element to see computed styles. Something might be overriding it. I'll get a js fiddle of the working solution.
Comment: Added ze fiddle.
Comment: I see where you're coming from now. I actually did this the good ole fashion way and tried this out on sublime text and then opened it through my browser on explorer and chrome. Both aren't working.
Comment: Yeah you'll have to do some hunting in chrome's dev tools. I'll try it in a single file with sublime and chrome and see if I can find the issue too.
Comment: @KennethMcAusland Sorry about the previous link, switched to trusty pastebin. Here is a [all-in-one html file](http://pastebin.com/KrDVaKNy) that works on my chrome. Made it in sublime.
Comment: I'll get on top of it sometime tomorrow afternoon. Work is coming up. If you can, try to get back at me sometime around 3pm central.


Can we send body to any route like http post request with payload?

Question: I have a scenario, I want to hit a route i-e /app/access and with body and i want to access that body like
activeRoute.getBody() in ngOninit.
can we do exactly like this? or any other way to send post params to route and access by active route ?
Answer: No we can't. Because every route is HTTP Get and we can't send body / payload to HTTP GET request.
we can't convert the route of angular to POST from GET because this is default behavior of request.
simple we can said that we can't send HTTP Post request to any route or convert any route to HTTP POST route.
If we want to achieve, we have wrap the application to some server side language like Scala and Java or induct any middle wear servlet.


Jogo de dois dados em Python

Question: Não consegui fazer uma função que simula um jogo de dois dados e conta quantas vezes os dados foram
jogados até que sair numeros repetidos.
def dados():
dado1 = [random.randint(1,6)]
dado2 = [random.randint(1,6)]
if dado1 == dado2:
    return

Meu problema foi não saber o que retornar pra contar o numero de vezes que os daodos foram jogados até sair numeros repetido.
Comment: Se a resposta resolveu o seu problema e não restou nenhuma dúvida, marque-a como correta/aceita ao clicar no "✅" que está ao lado dela, o que também marca a sua pergunta como resolvida. Se ainda te resta alguma dúvida ou gostaria de maiores esclarecimentos, fique a vontade para comentar.
Answer: Olá, primeiro vou reescrever um pouco sua função:
import random  # biblioteca com funções prontas para gerar valores aleatórios

def lancar_dados():
   cont = 0  # aqui vamos contar quantas vezes os dados foram lançados
   while True:
      dado1 = [random.randint(1,6)]
      dado2 = [random.randint(1,6)]
      cont += 1
      if dado1 == dado2:
          return cont

if __name__ == "__main__":
   print(lancar_dados())

A função irá repetir até encontrar os valores iguais em dado1 e dado2. E retorna a quantidade de vezes que os dois dados foram lançados.
Comment: você poderia adicionar o `import random`, pois alguns usuarios podem só copiar e colar e dar erro, assim fica mais facil para as outra pessoas :)

Jogo de dois dados em Python


Bass sine wave on an acoustic instrument

Question: Is there an instrument that can produce a sub bass sine wave like tone, that also has a lot of volume? Something that would sound a bit like an 808 bass.
I've listened to some contrabass type flutes but it sounds very breathy and there are too many overtone sounds.
I know that an ocarina produces a tone that comes close to a sine wave. Here is an example of a giant bass ocarina which comes close, but sounds a bit soft and underwhelming.
Comment: Honestly, it sounds like what you want is a synthesiser. Why not use one?
Comment: For recording? E.g. microphone placement and lowpass filter can eliminate the breathiness and most of the overtones; gating and compression can give a faster attack, set the bass level where you want it relative to the rest, perhaps EQ and sidechain compression to make it stand out against other instruments. Or for live unamplified play in a large room?
Comment: What exact frequency range are you after?  But if you really want a sine wave,  use a synth
Answer: There really is no such thing as a sub bass sine like tone with a lot of volume.  There are some organs with 32" subbass flutes (which produce a comparatively sine-like tone).  They are monstrous in size and move a lot of air, but due to the limits of human hearing, the audible volume is not all that large.  You feel their effect a lot more than you hear it.
It's one reason that motor bass/subbass speakers have been prohibited for concert use: they don't have a lower frequency limit like cone speakers, and people exposing themselves to excessive subbass noise have actually died of spleen rupture.
So the closer you get to your "sine wave" ideal, the more certain it is that you'll find the results "a bit soft and underwhelming".  Actually "strong" bass instruments almost invariably have significant amounts of overtones.  And since it is the overtone interaction that makes for the bass functioning as a harmonic foundation, really low sine tones tend to be harmonically arbitrary: if you are off by a tone or so, it doesn't really register all that much in terms of being disharmonious.
Comment: I can't readily find a source evidencing the claim that low-frequency sounds could cause a person's spleen to rupture. What is the supposed mechanism for this?
Comment: "There really is no such thing as a sub bass sine like tone with a lot of volume."  Not true, this is easily disprovable with a good bass amp and a synthesizer that can play sine waves.  In fact, the sine wave bass is a staple of certain EDM genres, and those bass lines are plenty loud.
Comment: To clarify, I'm talking about the "EDM" sub bass range, which starts around about C#1, 34.6Hz, and extends upward 1-2 octaves, consistent with the video.  Your answer would be accurate if we were generating 20Hz tones.
Answer: What do you mean by sub bass?  Are you referring to a sub harmonic of the instrument?
I will assume you are asking whether an instrument can produce a pure sine wave.
It would be very unlikely to get a pure sine wave from a musical instrument.  Even a function generator will produce transient harmonics due to being "switched on".  Without getting into the details of the math and physics, the specific harmonic spectrum of the instrument depends on (1) what overtones are supported by the physics of the instrument construction and (2) how the instrument is attacked, or how sound is excited in the instrument.  Additionally, the harmonic spectrum can depend on time.  It may be bright at first then decay, leaving mostly the fundamental (which would be as close as possible to a pure sine wave).  The guitar and other plucked instruments have this property.
If you pluck a guitar string close to the center you excite more fundamental but you still do not have a pure sine wave.  I would say that it is very unlikely that any instrument and player could produce this.  At the very least there would be harmonics for a short time due to starting the sound.
As a side note, the human ear is non-linear and creates aural harmonics.  So, even if you use a function generator as an input the signal to the brain will be "corrupted" with harmonics.
If you are referring to an instrument producing a true sub-harmonic.  I is possible but most so called examples of a sub-harmonic are false.  They are the result of changing boundary conditions in the attack and people completely misunderstand the physics of what's going on.
Comment: That was my third guess.  I think that there were three ideas expressed in your question in such a way that, at least for me, implied more than one question.
Comment: The question was more from a producers frame of reference. I thought I was clear enough to the point without going into the semantics of it all. Guess not. What I mean is, is there an acoustic instrument  that can produce sounds that approximate this type of sound

https://en.wikipedia.org/wiki/Sub-bass


Hammer-on, technique, callus or both

Question: I'm trying to get back into playing guitar after many many years, but this time learning extra techniques like hammer-ons. I'm currently playing Where did you sleep last night by Nirvana. I can play the song, but learning the intro. In the unplugged version (from what I can see and observe from the concert video), Kurt plays the sixth string open, moves to the second fret, plays that and then moves to the third fret and plays that. I'm getting this to work and it sounds as it should
In this video tutorial and in many online tabs, the sixth string should be played open, then the second and third frets are hammered on which should have the same sound affect as the way that Kurt plays it
My problem is, I cannot get my hammer-ons to sound correct. I am trying to get my technique to work, but being the age I am and not playing for over a decade, my fingers are still very stiff and stupid. I have tried just a basic hammer-on, trying to hit the string as hard with the tip of my finger as I can, but the sound I'm getting back is quite damped and dull.
My question is, is this down to pure technique and exercise to get a proper sound, or does the callusses on your finger tips (which I'm still building, mine is still soft) plays a role in getting a proper sound from a hammer-on
Comment: Your guitar setup and build quality may make a difference to how easy it is to keep a note sounding during a hammer-on. It may be worth taking your guitar to a shop and asking if they can lower the action (how far the strings are from the fretboard. Also, you didn't mention if you are playing electric or acoustic guitar, if it's electric, a little extra gain might help to cover slightly dulled notes while you are improving your technique.
Answer: Callous or no callous, be firmer with the hammer on. That's why it's called that! Try to hit the string just behind the fret wire, not in the middle of the fret, and keep the finger pressed down after contacting the string. Callouses probably make little difference, but having played for years, I don't have any. If you have, maybe the action has taken its toll on the tips.
Answer: Speed and strength are the key, make sure you hit the hammer-on string with speed and be firm; tips of fingers are best rather than the flatter part. A callus may make a slight difference. Try working on a pull-off, this will mean the string will actually be plucked and ring louder.
Comment: Since the tune apparently uses open 2nd and 3rd frets, how will a pull-off (from a higher fret) help?
Answer: The key to an effective hammer on is speed.  The velocity of your finger as it strikes the string is the important thing.  If you strike the string with insufficient velocity, you will mute the string before the note rings out.
Think about hitting a nail with a hammer.  If you slowly press the hammer onto the head of the nail, the nail will not go into the wood no matter how much force you apply.  In order to get the nail to penetrate, you need to generate a certain amount of speed with the head of the hammer.  Same principal applies with guitar playing.  Strength will not make up for lack of sufficient speed.
It does take some practice to develop the necessary finger speed for effective hammer ons.
Also it is important to get your finger as perpendicular to the string as possible using only the tip top of the finger (close to the fingernail).  It is almost impossible to generate a clean sounding hammer on using the side of your finger. Again using the hammer an nail analogy, if you hit the side of the nail it will not work.
To develop the necessary finger speed, practice by striking any open string without playing the string at all (the string is motionless until you hit it with your fretting finger).  Once you can do this and hear the note ring out, you have it.
To get a feel for what you are shooting for, try using the first finger of your picking hand and strike an open still string while the guitar is lying in your lap with the strings facing the sky.  Try to emulate a birds beak attempting to peck through the fretboard - concentrating on speed.  You should easily generate the effect and sound you will be shooting for when you practice with your fretting hand fingers.
Keep working on it.  You will get it eventually.  Good luck!
Comment: Adding to this good answer is that the SPEED of the hammer-on is important, but don't translate that into hammering-on as quickly as you can after the last note played. Lots of people think that if the hammer-on doesn't get played as soon as possible, it won't work. Untrue! You don't even need to play a note prior to have an effective hammer-on. That note before has NO bearing on the hammer-on working.
Comment: @Tim  Absolutely correct Tim.  Note that the exercise I suggest for developing the finger speed is to hammer on a silent motionless string until you can make the note ring out.
Answer: You may want to get a lighter string gauge and have the action of your guitar lowered. If you have high action and thicker strings, it would be harder to play a hammer-on than if you have lower action with lighter strings.
Finger callous shouldn't really play into whether or not you can play a hammer on.

Hammer-on, technique, callus or both


ivy:buildnumber fails against Artifactory if file extension/type is not .jar

Question: I am experimenting with Ivy 2.3.0, Artifactory 3.0.3 and Ant. The problem is that I cannot set ivy:buildnumber to work against a Artifactory repo if the extension of the file I have using is not .jar. It works fine against my local one. When I try it against Artifactory if fails to set the buildnumber. Running Ant with -debug I get the following output:
Setting project property: ivy.version -> 2.3.0
[ivy:buildnumber]       using oe to list all in ${http://localhost:8081/artifactory/repo/com/testorg/testmod
[ivy:buildnumber]       using oe to list all in http://localhost:8081/artifactory/repo/com/testorg/testmod/
[ivy:buildnumber] ApacheURLLister found URL=[http://localhost:8081/artifactory/repo/com/testorg/testmod/20130814190841/].
[ivy:buildnumber] ApacheURLLister found URL=[http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml].
[ivy:buildnumber] ApacheURLLister found URL=[http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml.md5].
[ivy:buildnumber] ApacheURLLister found URL=[http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml.sha1].
[ivy:buildnumber]               found 4 resources
[ivy:buildnumber]       using oe to list all in http://localhost:8081/artifactory/repo/com/testorg/testmod/20130814190841
[ivy:buildnumber] ApacheURLLister found URL=[http://localhost:8081/artifactory/repo/com/testorg/testmod/20130814190841/testmod-20130814190841.pl].
[ivy:buildnumber] ApacheURLLister found URL=[http://localhost:8081/artifactory/repo/com/testorg/testmod/20130814190841/testmod-20130814190841.pl.md5].
[ivy:buildnumber] ApacheURLLister found URL=[http://localhost:8081/artifactory/repo/com/testorg/testmod/20130814190841/testmod-20130814190841.pl.sha1].
[ivy:buildnumber]               found 3 urls
[ivy:buildnumber]               0 matched http://localhost:8081/artifactory/repo/com/testorg/testmod/20130814190841/[artifact]-20130814190841.jar
[ivy:buildnumber]       using oe to list all in http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml
[ivy:buildnumber] HTTP response status: 404 url=http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml/
[ivy:buildnumber] CLIENT ERROR: Not Found url=http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml/
[ivy:buildnumber] problem while listing resources in http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml with oe:
[ivy:buildnumber]   java.io.IOException The HTTP response code for http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml/ did not indicate a success. See log for more detail.
[ivy:buildnumber]       using oe to list all in http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml.md5
[ivy:buildnumber]               found 0 urls
[ivy:buildnumber]               0 matched http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml.md5/[artifact]-ivy-20130814190841.xml.md5.jar
[ivy:buildnumber]       using oe to list all in http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml.sha1
[ivy:buildnumber]               found 0 urls
[ivy:buildnumber]               0 matched http://localhost:8081/artifactory/repo/com/testorg/testmod/ivy-20130814190841.xml.sha1/[artifact]-ivy-20130814190841.xml.sha1.jar
Setting project property: ivy.new.revision -> 0
Setting project property: ivy.new.build.number -> 0
Property "ivy.build.number" has not been set
  [echo] new.rev: working@Win7Dev 0 ${ivy.build.number} 0

Critical line seems to be:
[ivy:buildnumber]               0 matched http://localhost:8081/artifactory/repo/com/testorg/testmod/20130814190841/[artifact]-20130814190841.jar

If the file is a .jar file this says '1 matched...' and the buildnumber is set. If, on the other hand, it is something else, such as .zip, it fails, as shown above.
The definition of the item in the ivy.xml file is:
<publications>
  <artifact name="testmod" ext="zip" type="zip"/>
</publications>

In Artifactory I created a repo with a maven-2-default layout and contains testmod.
My Ant target contains:
<ivy:info/>

<ivy:buildnumber resolver="oe" organisation="${ivy.organisation}" module="${ivy.module}"/>

<echo>new.rev: ${ivy.revision} ${ivy.new.revision} ${ivy.build.number} ${ivy.new.build.number}</echo>

The oe resolver is defined as follows:
<url name="oe" m2compatible="true" >
  <ivy pattern="${http://localhost:8081/artifactory/repo/[organisation]/[module]/ivy-[revision].xml"/>
  <artifact pattern="http://localhost:8081/artifactory/repo/[organisation]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"/>
</url>

The debug output and result is the same if I use an ibiblio resolver defined as follows:
<ibiblio name="oe1" m2compatible="true" root="http://localhost:8081/artifactory/repo" useMavenMetadata="false"/>

The module in the Artifactory repo got there using a Jenkins Artifactory plugin. This using:
Ivy pattern: [organisation]/[module]/ivy-[revision].xml
Artifact pattern: [organisation]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]

Comment: Thanks for posting this. I was stuck on the same problem. Looks like I'll be going with a workaround with separate ivy settings for non-jar artifacts so that I can hard code the extension. That seems to work.
Answer: it seems that extensions with 2 chars are not picked by artifactory, it has to have at least 3 chars.... I also do not understand why.


Upgrade Windows Server 2008 to R2

Question: I'm trying to in-place upgrade my Windows Server 2008 SP1 (64bit) to 2008 R2.
Is this supported? Where can I find more information on this process?
Answer: This is a supported upgrade path.
If you did a web search for "Upgrade to 2008 R2", you would inevitably have seen this link which has all of the considerations and known-issues with in-place upgrading to 2008 R2.

Upgrade Windows Server 2008 to R2


Compute expectation given probability

Question: Problem
This question arises from a paper I am reading now. The original reasoning could be translated into following
$$
\Pr[X>\alpha+\beta+t] \leq f(t) \Rightarrow \mathbb{E}[X] \leq \alpha+\beta + \int_{t}f(t)dt
$$
where $x$ is a random variable and $\alpha, \beta$ are constants.
It seems that the author tries to do integration on both sides and somehow remove the probability sign and replace it with expectation. But to my understanding, I need pdf of $X$ to compute its expectation and $\Pr[X>\alpha+\beta+t] \leq f(t)$ is not enough.
So could someone help me with the reasoning the author uses here?
Comment: Are you familiar with the equality $\mathbb EX=\int_0^{\infty}P(X>t)dt$ for nonnegative random variable $X$? See [here](https://math.stackexchange.com/q/64186/75923) for instance. No PDF or PMF needed.
Comment: @drhab First time I have seen something like this. Quite useful result! Thank you so much.
Comment: You are welcome. Also note that in the answer of Kavi it is not used actually that $X$ is nonnegative.
Answer: Indeed, you can derive this using the formula given by drhab above: If $X$ is nonnegative, you have
\begin{eqnarray}\mathbb{E}[X]&=&\int_0^\infty\mathbb{P}(X>t)~\mathrm{d}t\\&=&\int_{-\alpha-\beta}^\infty\mathbb{P}(X>\alpha+\beta+t)~\mathrm{d}t\\&\leq& \int_{-\alpha-\beta}^0 1~\mathrm{d}t+\int_{0}^\infty\mathbb{P}(X>\alpha+\beta+t)~\mathrm{d}t
\\&\leq& \alpha+\beta+\int_{0}^\infty f(t)~\mathrm{d}t.
\end{eqnarray}
Edit: Based on the other contributors' comments, I add a solution without the nonnegativity assumption: Let $Y:=X-\alpha-\beta$. Then
$$\mathbb{E}[Y]\leq \mathbb{E}[Y^+]=\int_0^\infty\mathbb{P}(Y^+>t)~\mathrm{d}t= \int_0^\infty\mathbb{P}(Y>t)~\mathrm{d}t\leq \int_0^\infty f(t)~\mathrm{d}t.$$
Plugging in the definition of $Y$ immediately tells us
$$\mathbb{E}[X]\leq\alpha+\beta+\int_0^\infty f(t)~\mathrm{d}t.$$
Comment: Not necessary to assume that $X$ is non-negative.
Comment: @KaviRamaMurthy I'm not sure: If $\alpha+\beta<0$ we don't necessarily know that $P(X^+>\alpha+\beta+t)\leq f(t)$. More precisely: If $\alpha+\beta+t<0$, clearly $P(X^+>\alpha+\beta+t)=1$ while we may have $P(X>\alpha+\beta+t)\leq f(t)<1$.
Comment: BY considering $X-\alpha -\beta$ the proof reduces to the case $\alpha =\beta=0$ so we don't have to worry about $\alpha +\beta <0$.
Answer: $EX \leq EX^{+} = \int_0^{\alpha +\beta} P(X^{+} >t)\, dt +\int_{\alpha +\beta}^ {\infty}  P(X^{+} >t)\, dt \leq \alpha +\beta +\int_0^ {\infty} f (s)\, ds$.
Actually, by considering $Y=X-\alpha -\beta$ we can reduce to the proof to the case $\alpha =\beta =0$.
Comment: No need of "nonnegative" here.

Compute expectation given probability


Programmatically enter edit mode TextField

Question: I got a Editable textfield inside my uitableviewcell and want the user to be able to edit the content of the textfield. This works when the user clicks the small textfield but i want to enter that editing mode when clicking on the tableviewcell.
So in the tableview didselect row delegate I need to programmatically enter edit mode for that textfield but I can't find any method to do this. Is this even possible?
Answer: <code>[textField becomeFirstResponder];
</code>
Here is an example on how to use this method:
<code>   - (void)tableView:(UITableView *)tblView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
          UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
          [cell.textField becomeFirstResponder];
    }
</code>


Automatically insert the login name when new row created in postgres

Question: In Postgres 10, is it possible to automatically insert the name of the login role when creating a new row?
i.e. I'm already using a timestamp to track the date that a row was created. It would also be useful to see which user created the row.
Thanks!
Answer: Yes. Just make the column's default session_user. (It's a pseudo-variable, not a function call).
If you want to prevent a user from overriding it, you should also make sure to GRANT write permissions to the table on a per-column basis, not to the table as a whole, and make sure the regular operating user is not the table owner.
Or alternately, have a BEFORE INSERT OR UPDATE trigger that sets NEW.the_column := session_user.


The continuous function $f(t)=\sin(1/t)$ it is not uniformly approachable by polynomials?

Question: The continuous function $f: (0,1) \to \mathbb{R}$,  $f(t)=\sin(\frac{1}{t})$
it is not uniformly approachable by polynomials. Why?
Any suggestions would be great!
Comment: what is the definition you are using for uniformly approachable by polynomials?
Comment: @MathsWizzard that we can find a polynomial $p$ such that for all $x\in (0,1)$, $\|f(x)-p(x)\|<\epsilon$
Answer: Assume that $|P(x)-f(x)| < \frac{1}{2}$ for $x\in (0, 1)$. If $P(0)=\alpha$, what can you say about $P(x)$ in some neighborhood of $0$?
Answer: It is not difficult to show that, if $f_n:[a,b]\rightarrow \mathbb{R}$ is a sequence of continuous functions, such that $f_n\rightarrow f$ uniformly on the open interval $(a,b)$, then the convergence is uniform on $[a,b]$. This is a consequence of continuity and the Bolzano-Cauchy criteria for uniform convergence. Thus, the function $f$ must be continuous on $[a,b]$.
Recall the polynomials are continuous everywhere, in particular they are continuous on $[0,1]$. So, if you have a sequence $\{p_n\}$ of polynomials approximating $f(t)=\sin\frac{1}{t}$ uniformly on $(0,1)$ you will deduce that $\{p_n(0)\}$ converges to $f(0)$. But this is impossible, because
$$\lim_{x\rightarrow 0^+}\sin\frac{1}{t}$$
doesn't exist.


Fibrations that are not fiber bundles

Question: I noticed that this question has been asked before, but I haven't been able to find a good answer for it, so here goes. For a course project I am learning about fibre bundles and fibrations, and now I am looking into some examples of both. Now, I would like to find an example of a fibration (either Hurewicz or Serre) that is not a fibre bundle. So far, I have only found the following (incomplete) example:
Let $E := [0, 1]^2 /l$, where $l$  is the line $\{\frac{1}{2}\} \times [0,1]$, and let $B = [0,1]$. Then a fibration $\pi: E \to B$ is not a fibre bundle.
However, I do not know how to define such a fibration $\pi$ explicitly, nor do I know how I would prove that it is a fibration (and whether it is Hurewicz or Serre). Moreover, I would not know how to prove that such a fibration is not a fibre bundle.
Therefore, I was wondering if anyone would have any hints regarding the aforementioned problems I have with this example. I would also like to know whether anyone knows any other examples of fibrations that are not fibre bundles. Thanks in advance for your help!
Comment: Have a look at Hatcher's Algebraic Topology book, exercises 4.3.8 & 4.3.9.
Answer: Let me give you another example with an explicit map:
Consider the subspace $E = \lbrace (x,y) \in \mathbb{R}^2 \mid \vert y \vert \leq \vert x \vert \rbrace \subset \mathbb{R}^2$. I claim that the projection onto the $x$-axis $$\text{pr} \colon E \rightarrow \mathbb{R}, (x,y) \mapsto x$$
is not a fiber bundle, but a (Hurewicz-)fibration. First of all, let me draw you a picture of the situation:

$\bullet$ Why is this not a fiber bundle?
Fiber bundles have homeomorphic fibers. Do you see where this fails?
$\bullet$ Why is this a fibration?
Let me give you a hint and leave the rest to you. I claim that the inclusion $E \hookrightarrow \mathbb{R}^2$ is a retraction and that this retraction allows you to steal the homotopy lifting property from the trivial fiber bundle $\mathbb{R}^2 \rightarrow \mathbb{R}$ (also the projection onto the first component).

Fibrations that are not fiber bundles


Let $G$ be the group defined by $G = \{A \in \mathrm{GL}(2,\Bbb R) \mid A^tA=r^2I, r>0,\det A >0\}.$ Find the Lie algebra of $G$.

Question:
Let $G$ be the group defined by $$G = \{A \in \mathrm{GL}(2,\Bbb R) \mid A^tA=r^2I, r>0,\det A >0\}.$$ Find the Lie algebra of $G$.

I've managed to figure out that the elements of $G$ take the form $$A=\begin{pmatrix}a&-b\\ b&a\end{pmatrix}, \ a^2+b^2=r^2$$ by some elementary trigonometry.
I'm having difficulties figuring out what $T_IG$ should be. If $X \in T_IG$ and $c:(a,b) \to G$ is a smooth path with $c(0)=I$ and $c'(0)=X$, then $c(t) \in G$ and we have two conditions $$c(t)^Tc(t)=r^2I, \ \det c(t)>0.$$
From $\det c(t) >0$ we get that $$\operatorname{tr} X >0$$ so the elements of the diagonal on $X$ should have a positive sum. Can I apply the product rule to $c(t)^Tc(t)=r^2I$? That is $$(c(t)^T)'c(t)+c(t)^Tc'(t)=0?$$ This would give that $X^T+X=0$ i.e. that $X$ is skew-symmetric?
Comment: I'm trying to do this exactly by figuring out how $X$ should behave. It would seem to be that at least $-a_{12} = a_{21}$ if $a_{ij}$'s are the entries of the matrix, but I don't think that $\begin{pmatrix}a_{11}&-a_{12}\\ a_{21}&a_{22}\end{pmatrix}$ fully characterizes $X$ yet since $a_{11} + a_{22}$ could be zero or negative. @MarianoSuárez-Álvarez
Comment: Can you elaborate what do you mean by equations? For the entries of a matrix in $G$ we have $a_{11} - a_{22} = 0$ and $a_{12} + a_{21} = 0$. @MarianoSuárez-Álvarez
Comment: Note that $G$ contains rescaled orthogonal matrices.
Comment: @MarianoSuárez-Álvarez This is a very precise estimate!
Answer: I think you have misunderstood the definition of $G$: $r$ is not a fixed value, but a free parameter (indeed, if $r$ was fixed, it could only be $1$ since $I_2$ must belong to $G$, as a subgroup of $GL_2(\Bbb R)$).
From your computation, it appears that
$$
G = \left\{\begin{pmatrix} r\cos \theta & -r\sin \theta \\ r\sin \theta & r \cos \theta \end{pmatrix} \mid r \neq 0, \theta \in \Bbb R \right\}.
$$
The Lie algebra of $G$ is given by the tangent space at $I_2$.
Let $$c(t) = \begin{pmatrix} r(t)\cos \theta(t) & -r(t)\sin \theta(t) \\ r(t)\sin \theta(t) & r(t) \cos \theta(t) \end{pmatrix} = r(t)\begin{pmatrix} \cos \theta(t) & -\sin \theta(t) \\ \sin \theta(t) &  \cos \theta(t) \end{pmatrix}$$
be a curve with $c(0) = I_2$, i.e $r(0) = 1$ and $\theta(0) = 0 \pmod 2\pi$.
Leibniz rule yields
$$
c'(t) = r'(t)\begin{pmatrix} \cos \theta(t) & -\sin \theta(t) \\ \sin \theta(t) &  \cos \theta(t) \end{pmatrix}
+ r(t) \theta'(t) \begin{pmatrix} -\sin \theta(t) & -\cos \theta(t) \\ \cos \theta(t) &  -\sin \theta(t) \end{pmatrix}
$$
and at $t=0$, this yields
$$
c'(0) = r'(0) I_2 + \theta'(0)\begin{pmatrix}0 & -1 \\ 1 & 0 \end{pmatrix}.
$$
One then sees that all these tangent vectors at $I_2$ have the form
$$
\begin{pmatrix}
a & -b \\ b &a
\end{pmatrix}
$$
for some $a,b \in \Bbb R$, without any further restriction.
Comment: So $\theta$ is also a function of $t$? @didier
Comment: @NathanielJohonson For a curve $c\colon (a,b) \to G$, of course.


How to save custom commerce_profile_reference field widget data

Question: Description:
My drupal commerce line-item's have extra "add-to-cart form" fields attached to the line-item type.
One of the fields is a field-collection that contains 2 fields:

A customer_profile_reference field with a custom widget (basically the same as an address field)
A custom field for time-window

When I loop through the line-items on "Checkout:Complete" with a rule action, I get the field value in the field collection as the field collection entity id, which I suppose is fine. When I now load the field_collection_item i get this:

Problem:
The field_delivery_profile, which is the customer_profile_reference field, does not show a value, and now I find out that the values aren't stored.
For the custom field + custom field widget I've created, everything works as intended.
The field widget for the custom customer_profile_reference field is basically a select list with profile_id's as the value, and I'm not sure now do I have to somehow specifically write some sort of a save hook? Because for the custom field + field widget module, all I've done is a presave for the field.
By default this field stores only an id (for the profile to reference) and shouldn't need anything extra.
Or is there a specific way I have to build the options list?
Currently the options list gets built like this:
foreach (commerce_customer_profile_load_multiple($profiles) as $profile) {
        $options[$profile->profile_id] =
            $profile->commerce_customer_address["und"][0]["name_line"].", ".
            $profile->commerce_customer_address["und"][0]["thoroughfare"].", ".
            $profile->commerce_customer_address["und"][0]["postal_code"].", ".
            $profile->commerce_customer_address["und"][0]["country"];
    }

And implemented as the element like this:
$element['select_address'] = array(
            '#type' => 'select',
            '#options' => $options,
            '#default_value' => $default,
            '#title' => t('Address'),
            '#required' => TRUE,
            '#id' => $element_id,
        );

Edit:
I have found out, that at one point it used to work, and has values in the db, however I've no way of pinpointing what has changed. Comparing the older versions of the module file, I see that they're essentially same, and even when reverting back to the older one, it doesn't seem to store data. What else could be causing this?
Edit 2:
Added a custom validation function to the widget element, and the $element['#value'] exists and is proper. I am however clueless as to why it's not being stored to the database.
Edit 3:
I've been struggling with this issue now for 3 days without any clear idea what could be causing it. I've debugged everything I can think of, and yet the code from when it was working does not differ by much, and even using the old code doesn't seem to remedy the situation.
This is the $element array from a validation function:
function _validate_cosmobutler_address($element, &$form_state, $form) {
    dpm($element);
}

As can be seen, it has the value of a profile id, as it's supposed to.
Also the database table commerce_profile_reference field created when first creating the field is the following:
Table: field_data_field_delivery_profile
Columns:
   entity_type varchar(128) PK
   bundle varchar(128)
   deleted tinyint(4) PK
   entity_id int(10) UN PK
   revision_id int(10) UN
   language varchar(32) PK
   delta int(10) UN PK
   field_delivery_profile_profile_id int(10) UN

I've also tried changing the element creation from:
$element['select_address']

to:
$element['value']

But that didn't seem to help either.
Edit 4:
I've deducted that the problem must come somewhere from the custom widget implementation, as the same field with a different widget stores data well.
The complete widget code can be found here:
http://kopy.io/5unZS
TL;DR Summary:
I'm unable to store data for customer_profile_reference field from a custom field widget. The storeable data should only require an id (of the profile), which are my select list options values anyway. The code for both options list and element implementation is above. The field seems to have stored values in the past but isn't any longer, so I'm hoping someone can give me more debuging insights or maybe can pinpoint the issue based on these descriptions.
Hope someone has a solution I may have overlooked.
Best,
Alari
Answer: So, finally overpowered the issue.
Apparently for the commerce customer_profile_reference field the widget for the field element has to be created with "profile_id" as the array key (name).
I'm having difficalty understanding why exactly as the default core select options widget does not have this but in the end the following code for implementation worked:
$element['profile_id'] = array(
            '#type' => 'select',
            '#options' => $options,
            '#default_value' => $default,
            '#title' => t('Address'),
            '#required' => TRUE,
            '#id' => $element_id,
        );

Hopefully, if anyone is ever tackled by the same issue, this is of help.


Does an adjustable bridge need to be parallel to the frets?

Question: The other day I was working on my guitar (Line 6 Variax JTV-89) that had some intonation issues.
I noticed that I couldn't move the saddles in a position that would be satisfying (I was at the minimum position available on some saddles), but as the bridge can be moved, I used the screws to move the "high e" side a bit closer to the pickup.
So now my bridge is not parallel to the frets but has a slight angle (not much).
Will this be a problem ? Can anything be damaged (neck, bridge, ...) ?
Here's an example of what a JTV-89 bridge looks like (this is not a JTV-89 but the bridge is the same). There are small horizontal screws that you can see on the left and right, near the vertical bridge height screws.
So mine is slightly angled, the right part being closer to the pickup that the left part.
Answer: It shouldn't damage anything.  However, it will make the strings slightly closer together and it may cause additional wear at the point the string goes over the saddle, since you are now causing a slight sideways angle.  If you go through a few sets of strings and aren't breaking an unreasonable amount of strings because of it, you should be fine.   A tiny drop of high grade grease will usually fix any break problems from something like this.
I had an Ibanez tele that I would have loved to be able to adjust the bridge this way.  My low E string saddle needed to be probably half a centimeter farther back then I could put it to have proper intonation.
Answer: I doubt if you've turned the bridge by even one degree, so it won't hurt anything. On some guitars, the individual saddle can be unthreaded and turned through 180 degrees, to give more adjustment back or forth for intonating.Particularly those with triangular shaped saddles.Is it not possible to move the whole bridge assembly forward so that it is parallel again, then adjust all saddles back?
Comment: No, because on my guitar, to have a correct intonation the left saddle needs to be at minimum and the right one needs to be at maximum :). So if I move the bridge to be parallel again, the intonation will be incorrect for one of the E strings.
Answer: No, in fact it's a fairly common adjustment to make for bridges that do not individual saddle height adjustments.


Qual a diferença entre JavaScript e jQuery?

Question: Penso no Jquery como um Framework JavaScript com intuito de otimizar a escrita, o Ajax é um bom exemplo.

Além da escrita facilitada, existe diferença entre ambos?
Quais as vantagens e desvantagens em usar jQuery?
Comment: Relacionada: https://i.stack.imgur.com/Bzawb.gif
Comment: Relacionado: https://pt.stackoverflow.com/questions/17501/qual-%C3%A9-a-diferen%C3%A7a-de-api-biblioteca-e-framework
Comment: JavaScript vs jQuery - Tudo o Que Você Precisa Saber http://programadorobjetivo.co/jquery-vs-javascript-tudo-o-que-voce-precisa-saber/
Comment: `otimizar a escrita` Nem sempre.....
Comment: Se você não for fazer um grande framework, ou sistema complexo, ou um site gigante, considere usar Javascript puro.
Comment: @LeoCaracciolo Gostei muito do arquivo que você postou aqui no comentario. Postei está dúvida, porque algumas pessoas me questionaram sobre o assunto e foi o que eu sabia até o momento sobre.
Comment: a resposta foi aceita muito rápido.
Comment: @MarceloBoni tem algum caso em que o `Javascript` é mais simples?
Comment: @Marconi, pelo menos **um bom** [exemplo](http://youmightnotneedjquery.com/#get_outer_html)
Comment: @MarceloBoni eu vi na resposta do Sergio esse link mesmo. O innerHTML por sinal é o que mais uso.
Answer: jQuery é JavaScript.
Ou seja jQuery é uma biblioteca escrita/construida com a linguagem JavaScript.
Existem duas razões principais para ter uma biblioteca como jQuery:

poder simplificar a vida ao programador, com menos linhas de código para fazer coisas que em JavaScript nativo seria preciso mais linhas
ter uma API que é igual em todos os browsers que essa biblioteca suporta

Pensando na biblioteca jQuery como uma ferramenta para facilitar a vida ao programador, a ideia é poupar trabalho, em extensão de código necessário escrever e minimizar possiveis erros.
Por exemplo uma chamada ajax para ir buscar um JSON seria assim em jQuery:
$.getJSON('/o/meu/url', function(data) {

});

para fazer o mesmo em JavaScript nativo seriam precisas mais linhas:
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // tudo correu bem!
    var data = JSON.parse(request.responseText);
    // aqui é o mesmo que o interior do exemplo com jQuery
  } else {
    // este pedaço é corrido se houver algum erro

  }
};

request.onerror = function() {
  // este pedaço é corrido se houver algum erro
};

request.send();

Na prática o jQuery tem essas linhas todas escritas na sua biblioteca (no ficheiro JavaScript que temos de carregar com a página) mas mostra ao programador somente os métodos que constrói e simplificam as coisas como mostrei no primeiro exemplo.
jQuery nem sempre é preciso, aliás já não é tão importante como foi em tempos. Um site interessante com funcionalidades comuns que se fazem bem em JavaScript nativo hoje em dia: http://youmightnotneedjquery.com/
Quando programamos uma aplicação, e os utilizadores usam o nosso programa em browsers diferentes corremos o risco de o JavaScript que escrevermos não funcionar em alguns browsers. Isto porque cada um implementa as coisas com ligeiras diferenças, ou porque uns são mais modernos que outros. O papel de bibliotecas como o jQuery é criar uma camada de abstração para só usarmos a sua API, e não JavaScript nativo. Assim, dentro da biblioteca, fazem-se as correções e ajustes necessários para um código jQuery como $(document).on('click', ... seja decomposto no JavaScript que um dado browser entende e proporcionar a mesma funcionalidade.
Um exemplo clássico é a maneira de amarrar auscultadores de eventos nas versões antigas do Internet Explorer.
A maneira moderna é elemento.addEventListener mas o IE tinha elemento.attachEvent. Para evitar escrever uma data de código como este (fonte):

//addEventListener polyfill 1.0 / Eirik Backer / MIT Licence
(function(win, doc){
 if(win.addEventListener)return;  //No need to polyfill

 function docHijack(p){var old = doc[p];doc[p] = function(v){return addListen(old(v))}}
 function addEvent(on, fn, self){
  return (self = this).attachEvent('on' + on, function(e){
   var e = e || win.event;
   e.preventDefault  = e.preventDefault  || function(){e.returnValue = false}
   e.stopPropagation = e.stopPropagation || function(){e.cancelBubble = true}
   fn.call(self, e);
  });
 }
 function addListen(obj, i){
  if(i = obj.length)while(i--)obj[i].addEventListener = addEvent;
  else obj.addEventListener = addEvent;
  return obj;
 }

 addListen([doc, win]);
 if('Element' in win)win.Element.prototype.addEventListener = addEvent;   //IE8
 else{  //IE < 8
  doc.attachEvent('onreadystatechange', function(){addListen(doc.all)});  //Make sure we also init at domReady
  docHijack('getElementsByTagName');
  docHijack('getElementById');
  docHijack('createElement');
  addListen(doc.all);
 }
})(window, document);

usamos jQuery, que tem mais ou menos isso dentro do seu ficheiro .js e usamos a sua camada de abstração (API) que fica somente:
$(elemento).on('nome-do-evento', ...

Mais informação:

sobre conceitos como API, Framework, Biblioteca aqui: (link)
a wiki da tag JavaScript aqui no SO.pt
a wiki da tag jQuery aqui no SO.pt
Comment: Gostei do exemplo do `addEventListener`. Eu achava que a maneira que as empresas de Browsers escrevem seus `js` seguiam um padrão. Então posso dizer que o jQuery é mais do que necessário?
Comment: @Marconi sim, exato. jQuery ou outra biblioteca é importante se precisares de usar muito js em browsers diferentes.
Comment: Como hoje em dia não sabemos qual dispositivo o usuario possa estar, podemos dizer que não usar um biblioteca como jQuery é altamente arriscado seu código não funcionar?
Answer: JavaScript é uma linguagem, enquanto jQuery é uma biblioteca focada na manipulação de elementos do DOM. Bibliotecas são feitas com base em uma linguagem e frameworks são feitos geralmente com base em uma biblioteca.
O que acontece é que o javascript é uma linguagem antiga e o desenvolvimento com ela é um pouco trabalhosa e as vezes é necessário escrever muito código. Então o jQuery é um framework, ou seja, é o próprio javascript redefinido de uma maneira mais moderno, simples de usar e com o uso de menos código.
Uma diferença que deve ser destacada é de que o JavaScript roda nativamente no browsers enquanto que para o jQuery deve ser adicionada uma referência a sua biblioteca no HTML.Por exemplo:

Vantagens de usar jQuery:

Acesso direto a qualquer componente do DOM, ou seja, não há
necessidade de várias linhas de código para acessar determinados
pontos no DOM.
O uso de regras de estilo não sofre qualquer tipo de limitação devido
as inconsistências dos navegadores. Mesmo os seletores CSS3 podem ser
usados sem qualquer restrição.
Manipulação de conteúdos, sem limitações, com algumas poucas linhas
de código. Suporte para toda a gama de eventos de interação com o
usuário sem limitações impostas pelos navegadores.
Possibilidade de inserir uma grande variedade de efeitos de animação
com uma simples linha de código.
Uso simplificado e sem restrições com AJAX e linguagens de
programação, como PHP e ASP.
Simplificação na criação de scripts.
Emprego cross-browser.
É possível selecionar elementos com maior facilidade, maior
compatibilidade, e com menos código. Veja um exemplo de um codigo em JavaScript e do mesmo em jQuery:
- Em JavaScript:

var botao = document.getElementById("botao");

if (botao.attachEvent) {
    botao.attachEvent("onclick", function(event) {
        alert("Você clicou no botão, usuário do IE!");
    });
} else if (botao.addEventListener) {
    botao.addEventListener("click", function(event) {
        alert("Você clicou no cabeçalho!")
    }, false);
}
<button type="button" id='botao'>Clique</button>

- Em jQuery:

$("#botao").click(function (event) {
  alert("Você clicou no botao!");
});

<button type="button" id='botao'>Clique</button>

Note como a sintaxe do jQuery é bem menor.
Desvantagens ao ultilizar jQuery

jQuery tem perda de performance. Esse tipo de perda é inerente a  quaisquer abstrações, mas é acentuado pela quantidade de recursos extras envolvidos.
A implementação em si também é menos otimizada quando comparada a
implementações que já vem do próprio core do Javascript. É bom evitar a
utilização de jQuery, pelo menos, em loops muito extensos ou    aninhados
onde uma penalidade de performance pode se multiplicar ou    até crescer
exponencialmente.
jQuery é uma biblioteca, então possui outros concorrentes. Se você
estiver usando um framework como o Angular que possui o seu próprio
jqLite, não haverá necessidade de usar jQuery. Saber JavaScript,
entretanto, sempre será útil.

Referências:

Introdução à jQuery
JavaScript vs jQuery - Tudo o Que Você Precisa Saber
jQuery
Comment: Boa resposta, `+1`
Comment: O que é bom é que te deste ao trabalho de procurar e (provavelmente) leste esses artigos. Aí seria interessante escreveres algo teu, com o conhecimento que leste lá. Como está não pode ficar. Deixo um comentário para saberes o que penso. Vou pensar mais sobre isso, [que já tem sido discutido no meta](https://pt.meta.stackoverflow.com/q/5430/129). De resto gosto muito de ver novos programadores como tu a participar no site, e espero que continues com respostas deste nível, que sejam tuas.
Comment: [1º parágrafo](http://programadorobjetivo.co/jquery-vs-javascript-tudo-o-que-voce-precisa-saber/) - [2º parágrafo](http://www.perguntaria.com.br/curso-preparatorio-para-o-enem-e-supletivo.aspx/diferenca-entre-as-tecnologias-ajax-jquery-e-javascript.aspx) - [A lista de vantagens](http://www.linhadecodigo.com.br/artigo/2068/introducao-a-jquery.aspx) -
 [A lista de desvantagens](http://programadorobjetivo.co/jquery-vs-javascript-tudo-o-que-voce-precisa-saber/)
Comment: AlíciaTairini: como referi em cima achei a resposta boa. Lendo com mais atênção, e como outros repararam, vejo que o conteúdo não é teu. A resposta como está é plágio de outros artigos. Na verdade não encontrei uma frase na resposta que fosse tua. O @Marconi editou e mudou nome de variáveis (não percebo bem porquê) mas até o código é copiado. Isso não é ok.
Comment: @jbueno Sou novata em programação e a pergunta me chamou a atenção, e como não conhecia do assunto resolvir pesquisar sobre e colocar aqui a resposta para ajudar pessoas futuras que possam vim ter essa mesma duvida. Como vc percebeu não me contentei com apenas uma fonte e pesquisei em uma segunda para elaborar de forma mais clara a resposta. Reconheço a minha falha de n ter colocado as referências, mas como vc tbm pode constadar ja corrigir isso.
Comment: @AlíciaTairini Excelente resposta para uma novata. Espero que responda mais e mais perguntas com essa qualidade :)
Comment: @Sergio Críticas são sempre bem vindas. Nas minhas próximas resposta farei o possível para colocar com minhas proprias palavras!
Comment: @AlíciaTairini Não precisa se explicar pra mim, eu só coloquei as referências.
Comment: @Sergio eu só deixei como código executável.
Comment: @Sergio é porque tinha eventos de `click` e era pra fazer mais sentido!
Comment: @Marconi ok. Bom ter ficado executável, isso foi bom.
Comment: @Marconi o que eu não percebi porquê foi mudar as variáveis de `cabecalho` para `botao`.


How to write $a|b \wedge ((a=0 \wedge b=0) \vee (a\ne0 \wedge b\ne0))$

Question: How can I write the expression
$$a|b \wedge ((a=0 \wedge b=0) \vee (a\ne0 \wedge b\ne0))$$
concisely and clearly in English? A direct translation yields

$a$ divides $b$ and either {$a$ and $b$ are both zero} or {$a$ and $b$ are both nonzero},

but it seems like there should be a shorter way to say that. Also, that wording is unclear without the brackets.
The following is shorter, but is still unclear without brackets:

$a$ divides $b$ and {$a=0$ if and only if $b=0$}
Answer: Use the fact that $a \wedge (b \vee c) \iff (a \wedge b) \vee (a \wedge c)$:
Either $a|b$ and $a = b = 0$, or $a|b$ and $a, b \neq 0$. Notice how the use of the word 'either' gets the reader in the mindset that they need to wait for at least two possibilities. Hope this helps a little!
Edit: got rid of some useless stuff.
Comment: Hm, "$a|b$ and either $a=b=0$ or $a,b\ne0$" actually looks okay. I guess I really just needed to shorten the zero/nonzero parts to make the emphasis clear. Thanks for the inspiration!
Answer: $a\mid b \land ((a=0 \land b=0)\lor(a\neq 0 \land b\neq 0))$
This reads: "'a' divides 'b' and either both are zero or neither is zero."
Answer: Either $\frac{b}{a}$ is a non zero integer or both are zero.


Accessing internal websites through VPN on iPad using SSO

Question: We are having an iOS issue with users trying to access our internal websites through a VPN connection.
We use SSO to access these sites and everything works for a Windows user as the Domain is Windows-based.
However, when iPad users access sites through a VPN (when they are offsite) they are prompted with a login box. As you can imagine this makes a few of them angry.
We are trying to figure out the best way to remove the need to ask for login details once the iOS user has connected using VPN.
So, my question is, can this be done by configuring the IIS server to use VPN details to help solve this problem?
Comment: Sounds like you should invest in some surface tablets that can be domain-joined.
Answer: You can't, as they are not domain joined. (as iis send the current logged on credential to the remote site, thus it fail and ask a login)
A workaround would be to invest to use a broker (xenapp or rdp) to publish the website link. As after the first connection you can allow in the local client in the ipad to save the credential used after the first login. Be aware if the password change the user need to resave the new credential anyhow. (or do like EEAA told, use a surface tablet)
Comment: @user367677 no, thus you have not much choice there. (please comment there, not in another awnser!)
Comment: Thanks for the replay, xenapp/ rdp sounds a bit overkill for us. Would it be possible to join the iPads to the domain once the user has connected through the VPN? Something like SSL VPN? Surface tablets are tempting at the moment - its never easy mixing devices from apple with microsoft!
Comment: @user367677 a side note, a sslvpn in radius mode with a html portal could work, but you ask your user to log on a site to save the other site login...


Do some mail servers rewrite envelope-to in response to a CNAME?

Question: In DNS, I have service.example.com. CNAME box.example.com.  When sending email automatically to about 10,000 adresses (no worries, nothing sinister), I set envelope-from to firstname.lastname@example.com.  Of the bounces that come back, about 70% have envelope-to set to firstname.lastname@example.com (which is what I would expect), but about 30% have envelope-to to email@example.com.
What is going on here?  Do some MTAs change envelope-to when they discover a CNAME?  Which MTAs?
Is it a good idea to use an A record instead of a CNAME for service.example.com.?
Answer: Yes, some MTA rewrite addresses, usually sendmail with custom macros that are trying to consolidate multiple internal (formerly external) domains into one consistent external domain.
Your bounce percentages might also be explained by the level at which the bounce came back. For example, a bounce from your edge MTA might well look different than a bounce from someone else's MTA.
Answer: I cannot speak for the exact performance in your situation due to lack of details.
The Return-Path: header is specified by the MDA, which uses the address identified in the MAIL FROM command.
The MTA typically defaults the MAIL FROM as the user sending the mail.  For example, calling qmail-inject with the -f flag can change the Return-Path to the specified e-Mail address.
For example, my username is warner on the awesomebox(.awesomedomain.org) server.  If I send an e-Mail using mutt and specify the From: header as email@example.com, the MTA (QMAIL) is going to default to specifying the MAIL FROM as firstname.lastname@example.com.
The same performance would apply to CGI running via Apache, it would default the Return-Path to the user Apache runs as.
Answer: According to RFC 1123 your MX record must point to a hostname with an A record (and/or AAAA for IPv6), and never to one with a CNAME!
Comment: There is no MX record involved here, only a CNAME (service.example.com) pointing to an A record (box.example.com).
Comment: Well, you **must** have an MX record.  There is an old RFC that states that in absence of an MX record the A record should be used instead, but that was only meant as a temporary fallback until all admins had implemented the MX record, and in both cases it specifically asks for a canonical hostname (so no CNAME).  (Some anti-spam systems probably give mail from your server a negative marking for the fact that you don't have an MX record, and a second one for only having a CNAME...)
Comment: So to answer your question: make an MX record that points to a hostname with an A record.  The hostname can be whatever mailserver you want to use to receive mail for `@service.example.com` (and of course, the mailserver must also be configured to accept mail for that domain).


About Drupal interact with Android

Question: Requirements:~

Android app post json data to a certain url.
Drupal can  receive the json data and then verify the json data and return result data in json format.

My question is on receive Json data and return Json data steps. What module or api can I use?
It would be greater help if you can share a sample.
Comment: I always wrote my own custom module for stuff like that. You can use [drupal_json_decode](http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_json_decode/7) and [drupal_json_encode](http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_json_encode/7) when reading and printing data from/to the mobile device.
Answer: Services module is what you are looking for. It supports json data. More about the module:

A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

It also has an extensive documentation.

About Drupal interact with Android


Groovy; Annotation type cannot be inner

Question: I create my validator interface to validate two bean properties are matched using following code :
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE )
@Constraint(validatedBy = FieldMatchesValidator.class)
@Documented

 @interface FieldMatches {

    String fieldName();

    String dependFieldName();

    String message() default "{FieldMatches.message}";

    Class<?>[] groups() default [];

    Class<? extends Payload>[] payload() default [];

   @Retention(RetentionPolicy.RUNTIME)
   @Target(ElementType.TYPE )
   @Documented
    @interface List {
       FieldMatches[] value();
   }

}

In annotations, I'd expect something like:
 @FieldMatches.List([
        @FieldMatches(
                fieldName = "pass",
                dependFieldName = "confpass1"),
        @FieldMatches(
                fieldName = "pass",
                dependFieldName = "confpass1")
    ])

With this, i receive the following error:
Annotation type cannot be inner

Thanks in advance for your help.
Comment: Do you have a full stack trace? Does it make a difference if you add the 'public' keyword?
Answer: You need to move @interface List { ... } into its own class - it can't be a nested class.

Groovy; Annotation type cannot be inner


Encoding a PNG with JavaScript

Question: I have some arbitrary pixel data that I want to save as a PNG. How can I encode a PNG with JavaScript to accomplish this?
The data is a series of 1's and 0's that I want to use to create a QR code. It's QR code arbitrary data
I'm not using the DOM, so jQuery and createElement's are out.
Comment: Titanium Appcelerator actually
Comment: Do you _really_ have to do this via JavaScript?
Comment: Why not use google chart tools to create the qr on their servers?
Comment: Can you elaborate "pixel data" part? "A series of 1's and 0's" doesn't ring a bell here.
Comment: I'd just generate an SVG, since it's easy, but I'm lazy. :-)
Comment: Can I do that with Appcelerator?
Comment: Yes... since I'm creating a mobile app with Appcelerator
Answer: http://www.xarg.org/2010/03/generate-client-side-png-files-using-javascript/
Answer: Or encode it directly to a PNG with pure javascript (no canvas required):
https://github.com/IjzerenHein/pnglib-es6
Answer: EDIT: As the other answer states and links to there's a javascript explanation of the PNG format. Hooray!
If you want to create an image file in PNG format your question is basically asking, "What is the file format for PNG? And how do I convert a QR code grid into an image that is a QR code image, given that I can define that QR code by a sequence of 1s and 0s."
You will need to consider LZW compression if you want to use PNG. Why not look at uncompressed GIFs or bitmaps? Use Titanium to create the file, hard code a header for your image format of choice then use the appropriate coding to programmatically create your image.
But if you simply want to display a QR code to the screen why not use a Titanium Webview canvas? Or if you are concerned that it is too slow (it won't be for drawing black boxes), use the titanium+plus Paint for iOS.
A 'hack' may be to use the UI elements with absolute positioning to construct your QR code image by drawing it with UI elements. Cool hack.
Or you could just use the SVG format in a webview. Personally, I think the easiest if you need a file is use a bitmap with a hardcoded header as I said above, or a GIF if you can't use a bitmap.
If you just need the image I would try using one of the Appcelerator drawing methods.
Good luck!
Answer: If I understand you correctly, you could use this library to generate qrcodes:
http://www.onlineqrlab.com/js_doc.php
Haven't tried it, but it seems well documented
Edit: This is a very old answer (9yrs+! O.o), so the link above now returns a 404. See web.archive.org: https://web.archive.org/web/20201029134734/http://onlineqrlab.com/js_doc.php
See also the qrcoder npm package for generating QR codes.

Encoding a PNG with JavaScript