Buddypress Templates - how to customize user page?

Question: (in WordPress)I am wondering where to edit the BP templates - should I edit the core template files(in wp-content/plugins/buddypress) or is there a way to somehow make your own BuddyPress theme ?
Thanks.
Answer:
Start by adding a Child Theme if you haven't done so already.
Read the Template Hierarchy link like slaFFik suggested.
Add a directory 'buddypress' to your child theme.
Copy the core template files you want to edit from wp-content/plugins/buddypress/bp-templates/bp-legacy/buddypress/(XXX/YYY/)zzz.php into
themes/yourchildtheme/buddypress/(XXX/YYY/)zzz.php

If you edit the core files directly your changes could be lost when you update BP.
Comment: Thanks, very helpful.  Something I didn't quite get from the notation above, until I did a bunch of trial and error is that one must create all the subdirectories in the path to your desired template under `/bp-legacy/buddypress/`  so if you want to modify `plugins/buddypress/bp-templates/bp-legacy/buddypress/members/registration.php` you need to copy it to `themes/yourtheme/buddypress/members/registration.php`  Just in case anyone else anyone gets confused like I did.
Comment: Thank you @neanderslob , this explanation was very helpful. I was confused by the name Buddypress and I was looking at the wrong folder. I didn't realize it was inside the legacy folder.
Answer: Read this tutorial - Template Hierarchy (Single Member Pages)


JavaScript - função que retona um objeto

Question: Estou tentando passar um desafio e estou tendo dificuldades para passar pelos seguintes tópicos:

Escreva uma função chamada createCars que irá receber três argumentos: nome, estrelas e marca. Esta função deve retornar um objeto. O objeto que retorna deve ter propriedades que também são chamadas de nome, ano e marca. Os valores atribuídos a estas propriedades devem ser os valores que são passados para a função. Além disso, o objeto que createCars retorna deve ter dois métodos:
hasMorestrelasThan - uma função que aceita um objeto "nome" como parâmetro e retorna true se o nome tem mais "estrelas" do que aquele que é passado para ele como um argumento, e falso caso contrário.
sayMarca - uma função que regista o valor da propriedade  "marca" do objeto "nome" para o console.

O que eu tenho para esta primeira etapa:
function createCar(nome, estrelas, marca) {

    myObject.nome = "nome";

    myObject.estrelas = "estrelas";

    myObject.marca= "marca";

    retun Object

}

Eu sou completamente iniciante e estou tentando aprender sozinha. Se alguem puder ajudar, ficarei eternamente grata!
Comment: Bem vindo ao SOpt. Dê uma olhada no [tour](https://pt.stackoverflow.com/tour) para mais informações de como funciona o site. Procure informar qual a dificuldade específica, o erro que ocorre, onde ocorre, etc. :)
Answer: Olá,
Vamos partir do início e criar seu objeto de maneira correta. Veja:
function createCar(nome, estrelas, marca) {
    myObject = {}; // cria o objeto myObject
    retun myObject;
}

Agora vamos as suas adaptações e lógicas. Observe:
function createCar(nome, estrelas, marca, ano) {
    myObject = {};

    myObject.nome = nome;
    myObject.estrelas = estrelas;
    myObject.marca= marca;
    myObject.ano = ano;

    myObject.hasMorestrelasThan = function (stars){
        if(this.estrelas < stars){ // pega estrelas do objeto myObject e compara com a starts (passada para a função)
            return true;
        }else{
            return false;
        }
    };

    myObject.sayMarca = function (){
        console.log(this.marca); // acessa a marca do objeto myObject
    }

    retun myObject;
}

Pelo que eu entendi da sua dúvida era mais ou menos isso que você queria. Espero ter ajudado, abraço!
Comment: Lucas, MUITO obrigada! Você foi o herói do meu dia!
Comment: Entendi, Lucas! Muito obrigada! Vou tentar resolver o desafio todo! :)
Comment: Só uma coisa: não entendi porque você compara com stars. Neste caso, eu poderia comparar com qualquer outra propriedade? Eu realmente estou confusa com isso.
Comment: Olá, neste caso você está comparando o stars (enviado como parâmetro da função myObject.hasMorestrelasThan) com o myObject.estrelas (enviado como parâmetro da função  createCar). Se deseja comparar dois elementos quaisquer, você pode adicionar um parâmetro stars2 na função, por exemplo. E modificar o if para `if(stars > stars2)`... e daí vai


How to plot a shp with holes with ggmap?

Question: I am trying to plot a *.shp file available here ArcGis. Looking at the page where I took the data from, I would expect the colored area to look like this:
.
But when I plot it I get something different (see below). In particular, it seems that some polygons overlap, and some areas are filled with a double layer of blue (alpha is .5), while they should be empty.
library(ggmap)
brMap <- qmap(location = 'baton rouge',  zoom = 10, maptype = 'terrain')

library(rgdal)
indundationArea <- readOGR('dataset/Estimated_Flood_Inundation_Area/Estimated_Flood_Inundation_Area.shp')
ogrInfo('dataset/Estimated_Flood_Inundation_Area/Estimated_Flood_Inundation_Area.shp')
indundationArea <- spTransform(indundationArea, CRS("+proj=longlat +datum=WGS84"))
indundationArea <- fortify(indundationArea)

brMap +
  geom_polygon(aes(x=long, y=lat, group=group), size=.2,color='blue', fill = 'blue', alpha=.5, data=indundationArea)

Comment: What is the issue with what you get as output from ggmap? What are you expecting? If you want something that looks exactly like your first image, you have to adjust the zoom level and use a different basemap.
Comment: You should provide a reproducible example not the code that you ran with the data that you have. Read about how to provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). p.s. this is a potentially good question.
Comment: If it was a duplicate, should zooming out solve the issue? It doesn't for me. Also, part of the code in the answer gives an error: `get_map("new york city", zoom = 10, source = "stamen")`
Comment: @Masoud the data is available at the link I gave, which is a zip file. Is there a function to unzip from an url and pass a single file from the unzipped folder?
Comment: https://stackoverflow.com/questions/3053833/using-r-to-download-zipped-data-file-extract-and-import-data
Comment: @dshkol it's not about the base map, it seems that all the darker light-blue area in the second map should be empty.
Answer: Your problem is caused by polygons with holes. geom_polygon is currently not able plot these correctly. Therefore, you should use ggpolypath::geom_polypath like this:
# continue after fortify
library(ggpolypath)
brMap +
  geom_polypath(data = indundationArea,
               aes(x=long, y=lat, group=group),
               size=.2,
               color='blue',
               fill = 'blue',
               alpha=.5)

Another option might be this one. However, it did not work for me...


What is the relationship between simple linear and multiple linear regression coefficients?

Question: For simplicity, let's restrict multiple linear regression case to 2 predictors, $x_1, x_2$. You regress $y$ on each individually and get $\hat{\beta}_1, \hat{\beta}_2$. Now you regress $y$ on both and get $\hat{\gamma}_1, \hat{\gamma}_2$.
So I know if $(x_1 - \bar{x}_1 \perp \bar{x}_2$, then $\hat{\beta}_i = \hat{\gamma}_i$, but if they're not orthogonal, what can be said about the relationship between them?
If in each of the simple linear regression cases, the slope was positive, i.e., $\hat{\beta}_1, \hat{\beta_2} > 0$, can we expect $\hat{\gamma}_1, \hat{\gamma}_2 > 0$?
I just asked a similar question on the math SE (https://math.stackexchange.com/questions/3791992/relationship-between-projection-of-y-onto-x-1-x-2-individually-vs-projecti), but I'm looking to gain more of a linear algebra intuition from answers to that question. Here, I am hoping for a broader intuition (both statistical and theoretical) of the relationship between simple and multiple linear regression coefficients.
Comment: See Frisch–Waugh–Lovell theorem and Simpsons paradox.
Answer: Here is a simple example that provides insight.
<code>y = c(5.8,5.2,4.7,8.7,8.1,7.7,10.2,9.6,9.0)
x1 = c(1,1.5,2,1.8,2.7,3.5,3,4,4.5)
x2 = c(1,1,1,2,2,2,3,3,3)

summary(lm(y~x1))
summary(lm(y~x2))
summary(lm(y~x1+x2))

plot(x1,y,col=x2)
legend("topleft", c("x2=1", "x2=2", "x2=3"), pch=1, col=1:3)
</code>
The simple regressions have significant positive relationships, but the multiple regression shows that the effect of x1 is significant and negative. The graph gives the intuition clearly:

Ignoring x1, there are generally higher values of y for larger x2.  Similarly, ignoring x2, there are generally larger values of y for larger x1. These observations explain the simple regression results.
In the multiple regression model, the slope coefficients are estimates of the effect of one x while the other is held fixed.  And you can easily see in the graph that the values of y are smaller as x1 increases within any of the three groups where x2 is held fixed (at either 1,2, or 3).
Comment: The unmodeled x is definitely not fixed in the simple models.  That's why the slope coefficients are both positive in my example. The reason for the "fixed" concept lies in the model itself: $E(y|x_1,x_2) = \beta_0 + \beta_1 x_1 + \beta_2x_2$ implies that, eg, $E(y|x_1,x_2=1) = \beta_0 + \beta_1 x_1 + \beta_2 (1) = (\beta_0 + \beta_2) + \beta_1 x_1$. So $\beta_1$ in the multiple regression model is the effect of $x_1$ when $x_2$ is fixed (at any value, not just 1.)
Comment: "In the multiple regression model, the slope coefficients are estimates of the effect of one x while the other is held fixed" In the simple linear regression model, isn't the unmodeled $x$ technically fixed too? I don't think I understand what "fixed" entails in this context.
Comment: @dd2205 "fixed" meaning what? I take "fixed" to mean in the sense that we hold other variables fixed when we take partial derivatives in multivariable calculus.
Comment: Yes, you can think of the "held fixed" concept in terms of partial derivatives as well.
Comment: This generalizes to any number of predictors right? For example, if we had $p$ predictors, we can interpret $\beta_1$ as the effect of $x_1$ when $x_2, \ldots, x_p$ are fixed?
Comment: Yes, sure.  If you fix all of $x_2, \dots x_p$, you still get a linear function of $x_1$. All the "held fixed" values become part of the intercept in that linear function.
Comment: Cool, so based on this analysis, basically if $\hat{\beta}_1 > 0$ in the simple linear regression case, there isn't much that we can say about $\hat{\gamma}_1$ in the multiple regression case? For example, you showed that it could be positive in the former case and negative in the latter case.
Comment: Yes, that would be correct. BTW, the case where the signs reverse is an example of "Simpson's paradox."
Comment: @PeterWestfall Thanks. I'll look into that term. What if $x_1, x_2$ were uncorrelated. I don't think I would expect the signs to reverse in that case?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/111834/discussion-between-peter-westfall-and-dd22205).


How to create a memory leak in AngularJS

Question: I'm trying to create a memory leak example in AngularJS. I use ChromeDev Tool but it seems difficult to find. This is one of my demos:
.directive('myDirectiveLeak', function () {
    return {
      replace: 'AE',
      template:'
<input type = "text">
',
      link: function(scope,element){
        element.bind('click',function(e){
          element.datepicker(); /// I add a JQuery plugin
        });
      }
    };

Some websites show this code causes a memory leak. After forced GC, I still didn't see any memory leak. I think AngularJS which is a product of Google has done something to avoid memory leak already. Can you give me a typical example in AngularJS. Thank you!
Comment: @ExpertSystem Because AngularJS team want to improve performance of their product. If you use available events of AngularJS, they will be automatically destroyed when a corresponding scope is destroyed. But if use a Jquery plugin which has its own events, angularjs won't do, so we have to do ourself
Answer: If you use this directive inside an ngRepeat where entries are regularly replaced, you will notice the memory leak. It's caused by the binding to the 'click' event. You have to unbind this event on destroying the directive:
.directive('myDirectiveLeak', function () {
    return {
      replace: 'AE',
      template:'
<input type = "text">
',
      link: function(scope,element){
        var clicked = function(e){
          element.datepicker(); /// I add a JQuery plugin
        };
        element.bind('click', clicked);
        scope.$on('$destroy', function() {
          element.unbind('click', clicked);
        });
      }
    };

Reason is that because of the attached event, your directive stays in memory, although it's been removed within the ngRepeat which would recreate the DOM every time you change the list.'
PS: You could use 'track by' to track changes in an ngRepeat directive. For more info, check the documentation.
Comment: Thanks for your answer. I have read ngRepeat diretive in AngularJS and I have seen it used $destroy() to clean up references and jquery event. So I don't know if we need use element.unbind here?  https://github.com/angular/angular.js/blob/v1.2.0-rc.3/src/ng/directive/ngRepeat.js#L338


A property of fields of characteristic $p$ and their extensions

Question: I am currently stuck on the following problem, taken from Herstein's Topics in Algebra, 2nd ed.. It reads:

If $F$ is of characteristic $p \neq 0$ and if $K$ is a finite extension of $F$, prove that given $a \in K$ either $a^{p^n} \in F$ for some $n$ or we can find an integer $m$ such that $a^{p^m} \notin F$ and is separable over $F$

Herstein defines an element to be separable over $F$ if, and only if, it is the root of a polynomial $p(x) \in F[x]$ with no multiple roots.
I am trying to do this by showing that, if we are not in the first case, we must be in the second case. However, I have no idea where to use that $K$ is a finite extension, and I just can't see why the second case must hold...
A couple of things I think could help are two former exercises from the same chapter. One says that the set $\{a \in K \mid a^{p^n} \in F\}$ is a subfield of $K$ and the other says that the set of separable elements of $K$ over $F$ are a subfield – but note that none of them suppose $K$ to be a finite extension...
I also thought about the fact that the polynomial $x^{p^n} - x$ has no multiple roots, but I don't know how to convert that to this problem.
In short, I am very much stuck and any help is appreciated!
Thanks in advance!
Comment: Where *exactly* in Topics in Algebra is that exercise? Is $\;\Bbb F\;$ supposed to be finite, or that is not a given?
Comment: @DonAntonio It's section 5.6, exercise 12. As far as I see, it does not suppose $F$ to be finite
Comment: EDIT: @DonAntonio I wrote the section wrong - it's. section 5.5
Comment: @Gauus I found it. Hope my answer helps you.
Answer: Some ideas for you: Let $\;a\in K\;$ and let $\;p_1(x)\in F[x]\;$ be its minimal polynomial over $\;F\;$ . If
$\;a\in F\;$  we're done  since then any power of $\;a\;$ is again in $\;F\;$ . So assume $\;a\notin F\;$ . If $\;a\;$ is
separable then we're done, so assume $\;a\;$ isn't separable $\;\implies p_1(x)=g_1(x^p)\;$ (corollay 1), and
of course $\;\deg p_1>\deg g_1\;$.
The above means that $\;a^p\;$ is a root of $\;g_1(x)\;$ , and let $\;p_2(x)\in F[x]\;$ be the minimal polynomial
of $\;a^p\;$ over $\;F\;$ . If $\;a^p\in F\;$ we're thru, so assume $\;a^p\notin F\;$ . If $\;a^p\;$ is separable we're done, so
again assume $\;a^p\;$ is not separable $\;\implies p_2(x)=g_2(x^p)\;$ , and $\;\deg p_1>\deg g_1\ge\deg p_2>\deg g_2\;$
is a root of $\;g_2(x)\;$  and $\;(a^p)^p=a^{p^2}\;$...and continue on.
Since $\;\deg p_1\;$ is finite, the above must stop at some finite step...finish now the argument.


Is it possible to automatically create a .install file for a module?

Question: I have a content type that I want to install as part of a module or install profile. Is there anyway to automatically create all the field_create_field and field_create_instances code that would go in hook_install or do I have to do all that manually?
Is there any other way to capture the settings of a content type so I can migrate it and include it in an install profile?
Answer: If it's just the field and field instances that you want converted ready for an install file (i.e. if Features is too overkill for you or you don't want the extra dependency), then Field Inspector will give you all the code you need for creating your fields in code.

Field inspector provides an administrative user interface for the
  Field Info API. This allows users to select what information,
  formatting, and fields they would like to see, and provides output in
  a manner that can be copied into a module, or install profile into a
  hook_install, or hook_update_N function.
Comment: Last updated ~2011 and only 31 sites using it - is it really stable & usable now?
Comment: Yeah - it's fine. I'd ignore the stats as it's a development level module. Those stats are also pretty flawed in that they only show modules for sites that have Update Manager enabled.
Comment: @molot As an example: Chaos Tools reports 489,224 D7 installs.  But realistically, it has to be on almost every site (cTools really is the *other* Drupal core in my opinion) - so those stats are relatively meaningless :)
Comment: I'm not arguing, just asking. And I'd say above about 1000 reported installs we can pretty much trust at least major bugs are identified, below only experience can help. I'm willing to trust your experience with it once you confirmed you have it ;)
Comment: @Mołot I didn't think you were arguing - I just wanted to back up my statement with a fact :)
Answer: It seems you are looking for Features module:

The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.
Comment: @AndrewWelch Hmmm probably not actually, it'd need to be wrapped up in a module. In which case Features would actually make more sense as it'll create that module for you
Comment: Or (even better IMO) [Configuration Management](https://drupal.org/project/configuration)
Comment: @Clive I'm printing/framing this comment ;-)
Comment: @Chapabu No-one will believe you...
Comment: Hi clive. Is it possible to programmatically include an exported configuration from configuration module into an install profile?
Comment: @Clive I'm shy to suggest anything less stable than beta to people I don't know ;) Configuration Management looks like just as good or better in this case, but we don't know what *else* OP would want to pack. If other configurations, it's better. If some helper modules for his content type, Features wins. And so on. Feel free and invited to edit this into my answer, or post your answer for me to upvote ;)
Comment: @Mołot It's a good module, the admin interface gets a bit sluggish when there's a lot of config (same as features), it's really a cut down version of the same. I've been using it for ages and haven't had any problems. Yet...


iterate over a js array of objects, within each object, check a value in the object against all others for uniqueness, push to new array

Question: What is a good way to iterate over a js array of objects, and then within each object, check a value in the object against all others for uniqueness, and push to a new array.
I have an array of objects:
const weatherArray = [
  {
    dt: 1526871600
    dt_txt: "2018-05-21 03:22:00"
  },
  {
    dt: 1526871600
    dt_txt: "2018-05-22 03:30:00"
  },
  {
    dt: 1526871600
    dt_txt: "2018-05-21 03:50:00"
  },
  {
    dt: 1526871600
    dt_txt: "2018-05-23 03:17:00"
  },
  {
    dt: 1526871600
    dt_txt: "2018-05-23 03:23:00"
  }
]

I need to check each object and if the dt_txt (just date, not time eg: 2018-05-23, 2018-05-21 etc) is unique, push that object into a new array.
Below is what I have been trying, I commented to the code to show my train of thought.
var uniqueDays = []
function getDays(weatherArray) {
  // push first value to new array to compare against other items
  uniqueDays.push(weatherArray[0])
  // get just the yyyy-mm-dd from txt we're comparing against
  let firstDayString = weatherArray[0].dt_txt.split(" ")[0]

  weatherArray.map((day) => {
    let dayString = day.dt_txt.split(" ")[0]

    uniqueDays.map((uniqueDay, index) => {
      // get just the yyyy-mm-dd for new array items
      let unqiueDayString = uniqueDay.dt_txt.split(" ")[0]

      // if the value exists, do nothing
      if (unqiueDayString == dayString) {
        console.log('duplicate');
      } else {
        // otherwise push to new array (this is the issue)
        uniqueDays.push(day)
      }
    })
  })

  return uniqueDays
}

The issue I am having is that pushing to unique day's within it's own map function is causing a recursion issue. I know there has to be a better way to this. Any help or direction would be a big relief, I've been struggling with this for some time.
Answer: You can group objects in an array with .reduce, putting each unique date into an object indexed by date and then getting that object's values:

const weatherArray=[{dt:1526871600,dt_txt:"2018-05-21 03:22:00"},{dt:1526871600,dt_txt:"2018-05-22 03:30:00"},{dt:1526871600,dt_txt:"2018-05-21 03:50:00"},{dt:1526871600,dt_txt:"2018-05-23 03:17:00"},{dt:1526871600,dt_txt:"2018-05-23 03:23:00"}];

const output =
  Object.values(
    weatherArray.reduce((accum, obj) => {
      const date = obj.dt_txt.slice(0, 10);
      if (!accum[date]) accum[date] = obj;
      return accum;
    }, {})
  );
console.log(output);
Answer:

const weatherArray = [
  {
    dt: 1526871600,
    dt_txt: "2018-05-21 03:22:00"
  },
  {
    dt: 1526871600,
    dt_txt: "2018-05-22 03:30:00"
  },
  {
    dt: 1526871600,
    dt_txt: "2018-05-21 03:50:00"
  },
  {
    dt: 1526871600,
    dt_txt: "2018-05-23 03:17:00"
  },
  {
    dt: 1526871600,
    dt_txt: "2018-05-23 03:23:00"
  }
]

const seen = {};
const res = weatherArray.filter(function(dt){
  const date = dt.dt_txt.substring(0, 10);
  if (!seen[date]) {
    seen[date] = true;
    return true;
  }
});

console.log(res);

note that it's not clear how robust you need to parse your dates. Looking at your example all dates are in the format YYYY-MM-DD so I just used substring which would be faster than split or a regular expression.
As for why your code doesn't work it's because you're looping over uniqueDays but also pushing to it inside the loop. That's a no-no.
The code you posted is parsing the dates in uniqueDays every time. For a large collection that would be slow. The solution above only needs to parse the dates once per item so that would be faster.
Your code uses map but map generates a new array from whatever the function passed to map returns. In your case it's generating an array of undefined as in [undefined, undefined, undefined] and then throwing that array away. You probably wanted to use forEach.
I'm assuming you looped because you needed to keep parsing the dates. If you didn't parse the dates you can use someArray.indexOf to find if there is an entry in an array as in
const isInArray = someArray.indexOf(value) >= 0;

You can also use someArray.findIndex which takes a function so you could have used that to parse the dates.
But, finally, looking through an array is slow, checking if a property exists in an object is fast. Because of the differences between arrays and objects the algorithm for finding a property, a hashmap, is O(1) where as to find an value in an unsorted array is O(N/2).
Let me add that @CertainPerformance's solution is also elegant. It's collecting the objects in accum and then has to iterate over that object to generate an array when it calls Object.values. For a large result array that would theoretically be slower than not having that second hidden loop.
Comment: such a beautiful function. thank you for your generous help
Comment: Just studied this again and wanted to say thanks again for taking the time. You really helped me grow here.
Answer:  const newUniqWeatherArray = [];

weatherArray.forEach(x => {
  const date = x.dt_txt.split(' ')[0];

  if(!newUniqWeatherArray.some((x) => x.dt_txt.split(' ')[0] === date)){
    newUniqWeatherArray.push(x);
  }
})

Basically the pseudocode is as below:

Loop thru weatherArray
For each of the child, check if the date exist in new array

If not exist, push this object into the new array
else do nothing


How to solve this nonlinear difference equation $y_{t+1}-y_{t}+ty_{t+1}y_{t}=0$

Question: I need help to solve the following difference equation:
$$y_{t+1}-y_{t}+ty_{t+1}y_{t}=0$$
I start by dividing with $y_{t+1}y_{t}$. Then I get:
$$y_{t}^{-1}-y_{t+1}^{-1}=-t$$
Then I assume $y_{t}=\frac{1}{m^{t}}$ and find general solution to corresponding homogeneous equation:
$$y_t=C_{1}\left ( 1 \right )^{t}+C_{2}t(1)^{t}\quad\Rightarrow\quad y_t=C_{1}+C_{2}t$$
Hoping that the solution is correct so far, I need help in finding a particular solution to nonhomogeneous equation.
Thanks!
Answer: With $z_t=y_t^{-1}$ we get
$$
z_{t+1}-z_t=t.
$$
Summing up for $t=0,\ldots,n-1$ you will get the telescopic sum in LHS and an easy to calculate in RHS. It gives you $z_n$ and, thus, $y_n$.
P.S. Your homogeneous equation would be $z_{t+1}=z_t$, it has only constant solutions, where does the term $...+C_2t$ for $y_t$ come from?


Questions about extensions

Question: Is it appropriate to ask questions about specific third-party extensions?
Or if there are extensions out there that do 'X'?
Also, what about people's experiences with particular extensions?
Answer: These are largely separate issues, so I will answer them one at a time:

Is it appropriate to ask questions about specific third-party extensions?

If third-party extension are an integral part of the Magento landscape, then certainly they should be on topic. As a matter of fact, if the developers of these extensions tend to have communities of their own, we should encourage them to become part of the ecosystem of this site.
We get a lot of requests from project teams about how they can use Stack Exchange to support their communities. I see no reason why this site couldn't provide fantastic technical support for add-on products closely related to the use of Magento. But just like the scope of Magento support provided here, this site should not be used for typical customer support issues for these add-ons (bug reports, feature requests, etc). Magento SE should be but one support option for these add-ons.
This is really no different than the product-specific support we provide on Stack Overflow, and the top two answers from the link below are worth reading:
Is it okay to use Stack Overflow as the support forum for a product or project?

Or if there are extensions out there that do 'X'?

Please see How do I ask a question that may require recommending a product.
Overly general questions asking for product recommendations (e.g. "what's the best smart phone?") are what prompted this blog post — Q&A is Hard, Let's Go Shopping! But seeking a solution to a VERY specific problem doesn't necessarily fall into the problematic "shopping question" often discouraged on these sites.
If the author asking about a well-researched problem which only incidentally needs a specific product to solve, it isn't likely a "problem" shopping question.  That's not really the same thing as asking for a recommendation — "Which add-on is best?" — for which that blog post was written.

Also, what about people's experiences with particular extensions?

Generally, no. These poll-the-community -type questions don't generally work well with our format. Questions are supposed to represent specific, answerable problems where users vet and vote on the solutions and the best answers rises to the top. Asking "what is your experience?" is essentially a discussion. Anyone can contribute and there's no sense that anyone's experience is better than anyone else's. There's nothing inherently wrong with the question itself, but that type of on-going discussion is not a good fit for this site.
Comment: I was drawn to this answer just from my frustration from the volume of growing shopping questions. There is getting to be more and more of people just asking what extensions can do what or what are recommended. Can we draw up a formal answer on these? As the answers given are likely to be out-of-date or irrelevant in months.
Answer: While I agree with most of this answer, I really don't have a clear understanding of what is meant by

If third-party extension are an integral part of the Magento landscape

More over, I'm not sure why there would be any concern about how "integral" or not an extension is to the "Magento landscape".
For me it seems perfectly reasonable that if an extension is developed for use with Magento then asking questions about it here would not in anyway detract from the focus of this community.
The extension is presumably built by developers who understand Magento and questions about the extension by those who employ it surely add to the overall Magento discussion.
Honestly I don't see how the cost (whatever you imagine it is) outweighs the benefit.

Questions about extensions


Why are the commands implemented by a custom module still listed after uninstalling it?

Question: I registered a new command via Drupal Console using drupal generate:command. I associated the command with a custom module, but after uninstalling the module and removing the module folder, the command still appears when issuing a drupal list command. I couldn't find anything in the Drupal Console documentation relating to this.
How do I let Drupal Console know my module is being uninstalled, so that it doesn't list its commands anymore? Does the module needs to implement a specific method for that, or do I need to run a Drupal Console command for this?
Answer: Problem solved. Issuing drupal module:uninstall my_module removes the command from the Drupal Console command list.


While loop not incrementing java

Question: i'm just starting to learn about java. My while loop does not seem to increment. Here's the snippet of my while loop inside a try and catch:
File file = new File("Reservation.txt");
Scanner sc = new Scanner(file);

    sc.useDelimiter(",");
try {
    while (sc.hasNext()) {
        i = 0;

        newRes[i] = readRec;

        fuN2 = sc.next();
        newRes[i].fullName = fuN2;
        readRec.setFirstName(fuN2);
        System.out.println("\n" + newRes[i].fullName);

        cn2 = sc.next();
        newRes[i].contact = cn2;
        readRec.setContact(cn2);
        System.out.println(newRes[i].contact);

        dt2 = sc.next();
        newRes[i].date = dt2;
        readRec.setDate(dt2);
        System.out.println(newRes[i].date);

        pa2 = sc.nextInt();
        newRes[i].pax = pa2;
        readRec.setPax(pa2);
        System.out.println(newRes[i].pax);

        bt2 = sc.next();
        newRes[i].bday = bt2;
        readRec.setBirthday(bt2);
        System.out.println(newRes[i].bday);

        ch2 = sc.nextInt();
        newRes[i].child = ch2;
        readRec.setChild(ch2);
        System.out.println(newRes[i].child);

        se2 = sc.nextInt();
        newRes[i].senior = se2;
        readRec.setSenior(se2);
        System.out.println(newRes[i].senior);

        pr2 = sc.nextInt();
        newRes[i].j = pr2;
        readRec.setPrice(pr2);
        System.out.println(newRes[i].j);

        dpr2 = sc.nextInt();
        newRes[i].k = dpr2;
        readRec.setDisPrice(dpr2);
        System.out.println(newRes[i].k);
        sc.next();
        sc.nextLine();
        i++;
    }

} catch (NoSuchElementException e)
{
    sc.close();
    System.out.println("===============================");

}

Whenever I try to print out the variable 'i', it always prints out 0, but the it always reads the file correctly and in order.
UPDATE: i removed the i declaration from the while loop, the answer should be below.
Comment: If you're referring to the value of `i` that's because you declared it _inside_ your loop
Comment: Please try to reduce your code to a minimal example reproducing the issue! Also, what are all these variables: `i`, `fuN2`, `newRes`, `readRec`, `cn2`, `dt2`, `pa2`, `bt2`, `ch2`, `se2`, `pr2`, `dpr2`? The names do not give away anything and the types are not clear (if they're used only within the loop, you should declare them right where they are used). Make your question easier to understand and you'll have better chances to get an answer!
Comment: @JeroenSteenbeeke No, given that this shall be Java code, `i` has _not_ been declared in that snippet.
Comment: @Amadán thanks for pointing that out. What does happen though is that it gets set to 0 at the start of each iteration.
Comment: *lol* I was so overwelmed by the massed of cryptic abbreviations that I _really_ missed this one. Talking about: "clean code" … :-)
Comment: @JeroenSteenbeeke i removed it now from the while loop, but it just prints 1 when im expecting 3
Comment: Why are you expecting 3? Could you give us a sample of the file you're trying to process?
Comment: @LeonardoDaFishy Frankly, I just do not even understand what your code intends to do. You expect the scanner to give you _9 * n_ items. That's about all I understand. Please add a little explanation what you're trying to do! Renaming those variables to anything meaningful and adding information about their types may help, too.
Comment: @JeroenSteenbeeke im trying to read a text file into an array, and the file contains four  lines, and i separated 9 elements with a comma. so that gives me 9 elements per line in the text file.
Answer: The first thing you do inside the loop is to set i to 0 …
So i is incremented at the end of the loop, but that is reverted at the next cycle.
But when printing i, you should get 1 always, not 0, when you print after the loop's execution.
Try this:
var i = 0;
File file = new File( "Reservation.txt" );
Scanner sc = new Scanner( file );

sc.useDelimiter(",");
try
{
  while (sc.hasNext())
  {
    // i = 0; Get rid of this line!!!

    newRes [i] = readRec;

    fuN2 = sc.next();
    newRes [i].fullName = fuN2;

    …

    dpr2 = sc.nextInt();
    newRes [i].k = dpr2;
    readRec.setDisPrice( dpr2 );
    System.out.println( newRes [i].k );
    sc.next();
    sc.nextLine();
    ++i;
  }
}
catch( NoSuchElementException e )
{
  sc.close();
  System.out.println("===============================");
}

Comment: No upvote? No "right solution" marker?
Comment: @tquadrat I feel old...
Comment: it looks like i got it fixed now, thanks :)
Comment: `var i = 0`? Are you sure this is Java?
Comment: @0009laH - Jepp, that's Java! Not sure when exactly it was introduced (11, I think), but in Java 17 `var` is part of the language, for sure.

While loop not incrementing java


sequence and series, limits

Question: Struck with this expression while solving, can you help me solving this
Answer: You need to show us what you've tried and let us know what is confusing you otherwise we can't really help or interact with you. Please read the community rules. A post should look something like this:
Problem
details...
Attempt
details...
As far as your actual problem goes...
$$\lim_{n \to \infty}n(\frac{\cos(\frac{2n+1)}{n^2+n})\sin(\frac{1}{n^2+n})}{\cos(\frac{2n+3}{(n+1)^2+n+1})\sin(\frac{1}{(n+1)^2+n+1})}-1)$$
Since $n \to \infty$ we really only need to worry about the dominant terms so we can look at
$$\lim_{n \to \infty}n(\frac{\cos(\frac{1}{n})\sin(\frac{1}{n^2})}{\cos(\frac{1}{n})\sin(\frac{1}{n^2})}-1)$$
and that should make the answer fairly clear.
Comment: @Rhythmlnk - i got answer of 2 when i solve it
Comment: Not quite. The limit should be 0. Can you tell me why?
Comment: $\sum _{n=1}^{\infty }\:\cos \left(\frac{2n+1}{n^2+n}\right)\sin \left(\frac{1}{n^2+n}\right)$ actually this the problem @Rhythmlnk
Comment: I don't know what you're asking. Please edit your question so people can understand what you're looking for.
Answer: Considering $$a_n=\cos \left(\frac{2n+1}{n^2+n}\right)\sin \left(\frac{1}{n^2+n}\right)$$ Use the classical expansions of cosine and sine and continue with Taylor series to get
$$\cos \left(\frac{2n+1}{n^2+n}\right)=1-\frac{2}{n^2}+\frac{2}{n^3}+O\left(\frac{1}{n^4}\right)$$
$$\sin \left(\frac{1}{n^2+n}\right)=\frac{1}{n^2}-\frac{1}{n^3}+O\left(\frac{1}{n^4}\right)$$ making $$a_n=\frac{1}{n^2}-\frac{1}{n^3}+O\left(\frac{1}{n^4}\right)$$
$$\frac{a_n}{a_{n+1}}=\frac{\frac{1}{n^2}-\frac{1}{n^3}+O\left(\frac{1}{n^4}\right) }{\frac{1}{(n+1)^2}-\frac{1}{(n+1)^3}+O\left(\frac{1}{n^4}\right) } \approx \frac{(n-1) (n+1)^3}{n^4}=1+\frac 2n+\cdots$$

sequence and series, limits


Completion heads engraver does not draw stems

Question: I am using completion heads engraver and completion rest engraver as follows:
<code>\new StaffGroup <<
  \override StaffGroup.SystemStartBracket.stencil = ##f
  \new Staff \with {
    \remove "Note_heads_engraver"
    \consists "Completion_heads_engraver"
    \remove "Rest_engraver"
    \consists "Completion_rest_engraver"
  } \relative {
    g'8 ais8 dis2
  }
>>
</code>
This produces the following:

For some reason the stem of the tied note is not drawn. How to fix this?
Answer: The problem here is that usually NoteHeads are not created on Staff level, but on Voice level. And this has a good reason: Note head spacing needs to take into account voice information, and Beaming should happen only within one voice. We could just move everything from Voice to Staff
<code>\new StaffGroup <<
  \override StaffGroup.SystemStartBracket.stencil = ##f
  \new Staff \with {
    \remove "Note_heads_engraver"
    \consists "Completion_heads_engraver"
    \remove "Rest_engraver"
    \consists "Completion_rest_engraver"
  } \relative {
    \time 2/4
    g'8 ais8 dis2
  }
>>

\layout {
  \context {
    \Voice
    \remove Stem_engraver
    \remove Beam_engraver
    \remove Note_heads_engraver
    \remove Rest_engraver
    \remove Auto_beam_engraver
  }
  \context {
    \Staff
    \consists Stem_engraver
    \consists Beam_engraver
    \consists Note_heads_engraver
    \consists Rest_engraver
    \consists Auto_beam_engraver
  }
}
</code>
but you need to be aware that this would create the effect of having only a single voice. Much better would be to do this:
<code>\layout {
  \context {
    \Voice
    \name CompletionVoice
    \alias Voice
    \remove "Note_heads_engraver"
    \consists "Completion_heads_engraver"
    \remove "Rest_engraver"
    \consists "Completion_rest_engraver"
  }
  \context {
    \Staff
    \accepts CompletionVoice
  }
}

\new Staff \with {
  \defaultchild CompletionVoice
} \relative {
  \time 2/4
  g'8 ais8 dis2
}

\new Staff \with {
  \defaultchild CompletionVoice
} \relative {
  \time 2/4
  <<
    {
      g'8 ais8 dis2
    } \\
    {
      e,8 fis2 gis8
    }
  >>
}
</code>
which defines a new voice-style context CompletionVoice, which contains the necessary changes. Then we can already do <code>\new CompletionVoice ...</code>, and by setting the default child context of a staff from Voice to CompletionVoice we can set this as default behaviour for a whole Staff.
Comment: @kargirwar Hm, the problem here is that `\addlyrics` appears to add a voice context. So instead of using `\addlyrics` you'd need to do `<< \new Staff \new CompletionVoice = "voiceID" ... \new Lyrics \lyricsto "voiceID" ... >>`.
Comment: At this time my \layout block is inside \score. Shall I just replace it ? I got this: warning: cannot create default child context: CompletionVoice
Comment: @kargirwar It should not matter whether you specify this in a global layout or in a score layout (although if you need this more often it would make sense to have this in global layout that can be included on toplevel). The warning message you got should happen if you omit that `\layout { \context { \Voice \name CompletionVoice ... } }` stuff. Maybe you could produce a small failing piece of code so I can check if there is any mistake?
Comment: @kargirwar And if you need this for only a single voice you can simply do `\new Staff \new Voice \with { ... } ...`.
Comment: I have just this inside \score <<>>:  \new Staff \with {
        \defaultchild CompletionVoice
      } \relative {
        g'8 ais8 dis2
      }  and the \layout as above and \midi{}
Comment: @kargirwar The warning you get comes from the midi output. The reason is that we define a new engraver group, but not a new performer group, so the performer group Staff cannot add the default child performer group CompletionVoice. Simply add a score or global midi block containing `\midi {
  \context {
    \Voice
    \name CompletionVoice
    \alias Voice
  }
  \context {
    \Staff
    \accepts CompletionVoice
  }
}` and it should be fine.
Comment: This works as expected untill I add an \addlyrics block. Then it starts generating wrong output. Any ideas?


Non-isomorphic curves with the same genus

Question: I need to show that the curves $y^7=x^2(x-1)$ and $xy^3+zx^3+yz^3=0$ are not isomorphic even if the are both of genus 3. I have tried to show that they are a quartic and a hyperelliptic curve in order to show that they are in two different class of isomorphism.
I have normalized the first one with this sequence of blow-ups and transformations:
$x=x_1y_1, y=y_1     \rightarrow x_1^3y_1-y_1^5-x_1^2=0$
$x_1=x_2y_2, y_1=y_2 \rightarrow x_2^3y_2^2-y_2^3-x_2^2=0$
$x_2=x_3y_3,y_3=y_2  \rightarrow x_3^3y_3^3-y_3-x_3^2=0$
$x_3=\frac{X_3}{Z_3},y_3=\frac{Y_3}{Z_3} \rightarrow X_3^3Y_3^3-Y_3Z_3^5-X_3^2Z_3^4=0$
$y_3'=\frac{Y_3}{X_3}, z'_3=\frac{Z_3}{X_3} \rightarrow (y'_3)^3-(y'_3)(z'_3)^5-(z'_3)^4=0$
$y_3'=y_4z_4, z'_3=z_4\rightarrow y_4^3-y_4z_4^3-z_4=0$
The last one is nonsingular but is almost exactly the other, so what is wrong?
Thanks!
Comment: Do you mean birational instead of isomorphic ? The second one is a projective curve, of the field of rational functions only the constant functions are regular on the whole curve, the first one is an affine curve with $x$ non-constant regular.
Comment: What do you mean by "the last one is...almost exactly the other"? The onslaught of indices is making my head spin, but it looks like you've written it as the intersection of two surfaces in a rational threefold, so I'm not sure what you're trying to say about its relation to a plane curve (and that's not even getting into the affine/projective ambiguities mentioned in the previous comment). But to comment on your strategy, if the first curve is indeed hyperelliptic and the second is indeed smooth, then you will have shown that they are non-birational curves of genus $3$.
Comment: @reuns Yes, birational. I'm considering these two curves as two Riemann Surfaces so I'm thinking always at their projective closure.
Comment: @TabesBridges I mean that I have obtained almost the same equation and then the same Riemann Surface. I have tried to build a nonsingular model for the first with that sequence of birational morphisms and maybe there is something wrong there that I can't find.
Comment: @cartesio But you have multiple equations at the end, no? How are you comparing two curves that are presented in these different ways? And again, what do you mean by "almost the same"? Typically perturbing the equation(s) changes the birational class.
Comment: @TabesBridges oh no! I just edited, there was a little mistake.
Comment: @cartesio I'm not sure what you changed, but if it was the last equation OK, that is indeed birational to the other curve. Assuming that you have been told by a reliable source that this is not the case I would guess that you made a computation error, but this is the sort of thing that's hard to debug without documentation. You haven't indicated where any of your blowups are living, so I'm not sure how you end up with just one equation at the end. Are you repeatedly passing to some open set of the blown up plane which is itself (the open set that is) isomorphic to $\mathbb A^2$?
Comment: @Tabes Bridges, this is an exercise from Geometry of Algebraic Curves by Arbarello. Yes, I have projected each blow up on an affine plane.
Comment: Hmm, well as Sasha has shown apparently the curves *are* birational, so I guess there is a typo in ACGH.
Comment: Your computation looks correct to me. In the first three steps, the singularity is resolved. In the 4th step, you take the closure of the affine curve (defined by the 3rd equation) in $\mathbb P^2$ and in the last two steps, you localized at a different affine chart and resolved the singularity. All of these operations does not change the function field, so you are done! I'm just curious how did you find this sequence (especially step 4~6)?
Comment: @AGlearner I have just tried to resolve the singularity using blow up. I have blown up the same singularity until the affine curve is smooth then I have considered the projective closure to be sure that the points at infinity are not singular. If they are singular I localize there and I repete the same process. I'm doing it with several other curves but somethimes I have found that there are kind of cycles in which you finish without finding the normalization.
Comment: @cartesio In some sense, this process is not canonical. For example, I can close up the curve $y^7=x^2(x-1)$ in $\mathbb P^2$, so there is a singularity at infinity, then I can localize at infinity and resolve the (only) singularity on this chart, then I close up in $\mathbb P^2$ and further resolve the singularity. The resulting curve is smooth and birational to, therefore isomorphic to Klein quartic. I guess the reason that you can easily compare the equation of two curves explicitly is that Klein quartic is a plane curve. I believe this will be hard in general.
Answer: The curve
$$
xy^3 + yz^3 + zx^3 = 0
$$
is the famous Klein quartic, see https://en.wikipedia.org/wiki/Klein_quartic. Its automorphism group has order 168, the maximal among curves of genus 3. In particular, it has an automorphism of order 7.
On the other hand, Theorem 2(a) of [Homma, Masaaki. Automorphisms of prime order of curves. Manuscripta Math. 33 (1980/81), no. 1, 99--109] shows that a curve $C$ of genus $g \ge 2$ with an automorphism $\sigma$ of prime order $2g + 1$ is birational to one of the curves
$$
y^{2g+1} = x^a(x-1)^b,
$$
where $a,b \ge 1$ and $a + b \le g + 1$. Moreover, the proof of Proposition 3.1 in the paper shows that $a + b$ is the degree of a covering $f \colon C \to \mathbb{P}^1$ which is equivariant for $\sigma$.
All this applies easily to the Klein quartic. One can choose the morphism $f$ to be the projection
$$
(x,y,z) \mapsto (x:y),
$$
then its degree is 3, hence $a + b = 3$, hence (after a possible change of coordinates) the Klein quartic is birational to the curve
$$
y^7 = x^2(x-1).
$$


Itálico nos títulos dos painéis no facet_wrap()

Question: Estou com dificuldades em formatar nomes de espécies em itálico no título dos painéis com o argumento facet_wrap no ggplot2. Segue exemplo:
library(ggplot2)
ggplot(mpg, aes(x=displ, y=hwy)) +
  geom_point() +
  geom_smooth(method="lm", se=FALSE, colour="black") +
  facet_wrap(~ trans)

Nesse exemplo temos como resultado 10 painéis, cada um com um título, que são as variáveis em minha tabela original de dados. Como colocar esses títulos em itálico?
Comment: Muuuito obrigado Marcus! Eu mesmo fazendo a pergunta aqui, continuei buscando descobrir, e já tinha achado que o caminho seria pelo strip.text, só não tinha acertado a formatação do código.... Muito obrigado mesmo!!
Comment: É muito bom saber que a minha resposta te ajudou de alguma forma. Por isso, considere [votar e aceitar a resposta](https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta), de modo que, no futuro, outras pessoas que passarem pelo mesmo problema tenham uma referência para solucioná-lo.
Answer: No help da função ggplot2::theme, é possível encontrar o argumento strip.text. A descrição dele é a seguinte: facet labels (element_text(); inherits from text). Portanto, basta alterar a opção de strip.text dentro de theme para obter o resultado desejado:
library(ggplot2)
ggplot(mpg, aes(x=displ, y=hwy)) +
  geom_point() +
  geom_smooth(method="lm", se=FALSE, colour="black") +
  facet_wrap(~ trans) +
  theme(strip.text = element_text(face = "italic"))


Rational solutions to a quadratic-type equation.

Question: For any fixed rational $t$, are there any nonzero rational solutions to the equation
$$y^{2} = (1-t^2)x^2 + \frac{1}{4} \text{ ?} $$
My attempt: consider the line $L$ whose gradient is $m$ and passes through the point $(0, \frac{1}{2})$. Then equation of $L$ is $y=mx + 1/2$, then consider its intersection with the quadratic in question and simplify. However, i'm yet to find any idea beyond this stage.
Answer: Using your idea, we get
$$\left(mx+\frac 12\right)^2=(1-t^2)x^2+\frac 14,$$
i.e.
$$x(m^2x+m-x+t^2x)=0$$
Since $x\not=0$, we get
$$x=\frac{m}{1-m^2-t^2},\quad y=mx+\frac 12=\frac{m^2+1-t^2}{2(1-m^2-t^2)}$$
where $m\in\mathbb Q$ has to satisfy $1-m^2-t^2\not=0,m\not=0$ and $m^2+1-t^2\not=0$.
Answer: To simplify, rewrite the original equation as $(2y)^2+4(t^2-1)x^2=1$ and substitute $2y$ with $2mx+1$:
\begin{align}&(2mx+1)^2+4(t^2-1)=4(m^2+t^2-1)x^2+4mx+1=1\\
\iff & 4x\bigl((m^2+t^2-1)x+m\bigr)=0,
\end{align}
so the non-zero solution is
$$x=\frac{m}{1-m^2-t^2},\qquad y=\frac{m^2}{1-m^2-t^2}+\frac12=\frac{1+m^2-t^2}{2(1-m^2-t^2)}.$$


Mean of highest exponent in prime factorization of all integers ≥ 2

Question: For any natural number $n > 1$, define $E(n)$,to be the highest exponent to
which a prime divides it. For instance, $E(12)=E(36)=2$. Show that $$\lim_{N \to \infty} \frac{1}{N} \sum\limits_{n=2}^{N} E(n)$$ exists and find its value
Comment: That sounds very sloppy. Coming up with a useful title is one of the few tokens of respect you can give to would-be answerers.
Comment: Can you give a title that is more specific next time you ask a question? The title is used for searching so it's important be precise.
Comment: As with all your questions: (1) where is this question from, (2) why you want to know? If you provide more personal context and motivation, I suspect more people will feel like trying/answering.
Comment: @Kenny TM: hi, i can only give the title which comes to my mind at that time. In case you don't like it then please be free to edit it. Sorry
Comment: @J.Mangaldan:- I agree.
Comment: @Shreevatsa: I want to know this because i couldn't solve it. By the way have you looked at this problem: http://math.stackexchange.com/questions/1860/comparing-sums-of-reciprocals
Answer: Here are some suggestions to approximate the limit.
Consider F(n) to be the greater of 1 and the highest power of 2 that appears in the prime factorization of n.  Show what the limit of the average over n of F(n) is as n gets large.
Let G_p(n) be defined like F(n), except replace 2 by an arbitrary prime p.
Note that F(n) <= E(n), and that E(n) = max(G_p(n) over all primes p), so that if limit
of the average over n of E(n) exists, you can bound it using a sum of limits involving G_p.
For more accurate estimates, consider inclusion-exclusion.
Comment: Paseman: Could please Tex it out so that the result is more tangible for the viewers. Also i would like you to elaborate it more.


Adding an integer value into a database table error

Question: I am creating a flight application in java and one of the things it is supposed to do is to add a new flight to the database. I am able to add the flight name with no issues, but I am having issues adding in the number of seats the flight has to the database. The database table is set to take in the number of seats as an integer value. In my code, my function that adds this value in from the user interface to the database takes a value as an integer argument. Then, in my event handler code for the actual button that adds a new flight, I convert the value from a string(this is what is accepted as a string from the text box) to an integer, so that the value can be entered into the database. However, when I run my code, I get an error saying the number of seats cant be accepted as a null value. Basically, the database is taking in the value as null. I am not sure what I am doing wrong in my code.
public class Flight extends Customer {
        private static ArrayList<String> FlightNames;
        private static ArrayList<Integer> Seats;
        private static PreparedStatement getFlightnames;
        private static PreparedStatement getFlightSeats;
        private static PreparedStatement addFlightName;
        private static PreparedStatement addSeats;
        private static ResultSet fresult;
        private static ResultSet sresult;

        public static ArrayList <String> getFlightnames(){
            //recieve flight names from database
            try{
                FlightNames = new ArrayList();
                getFlightnames = getConnection().prepareStatement("select name from flight ");
                fresult = getFlightnames.executeQuery();
                while(fresult.next()){
                    FlightNames.add(fresult.getString(1));

                }

            }
            catch(SQLException result){
                result.printStackTrace();
            }
            return FlightNames;

        }
        public ArrayList<Integer> getFlightSeats(){
            try{
            Seats = new ArrayList();
            //getFlightSeats = getConnection().prepareStatement("SELECT * FROM Flight WHERE Seats LIKE ?");
            getFlightSeats = getConnection().prepareStatement("select seats from flight ");
            sresult = getFlightSeats.executeQuery();
                while(sresult.next()){
                    Seats.add(sresult.getInt(1));

                }
            }

            catch(SQLException result){
                result.printStackTrace();
            }
            return Seats;
        }
        public void addFlight(String flight){
            try{
                addFlightName = getConnection().prepareStatement("insert into bookings (flight) values(?)");
                addFlightName.setString(1, flight);
                addFlightName.executeUpdate();

            }
            catch(SQLException result){
                result.printStackTrace();
            }
        }
        public void addNumber(String flightNumber){
            try{
                addFlightName = getConnection().prepareStatement("insert into flight (name) values(?)");
                addFlightName.setString(1, flightNumber);
                addFlightName.executeUpdate();

            }
            catch(SQLException result){
                result.printStackTrace();
            }
        }
        public void addSeats(int seats){
            try{
                addSeats = getConnection().prepareStatement("insert into flight (seats) values(?)");
                addSeats.setInt(1, seats);
                addSeats.executeUpdate();

            }
            catch(SQLException result){
                result.printStackTrace();
            }
        }

}

private void AddFlightButtonActionPerformed(java.awt.event.ActionEvent evt) {
        Flight addnumber = new Flight();
        Flight addseats = new Flight();
        addnumber.getConnection();
        addseats.getConnection();
        String flight = FlightTextBox.getText();
        String seats = SeatsTextBox.getText();
        int seatsInt = Integer.parseInt(seats);
        addnumber.addNumber(flight);
        addseats.addSeats(seatsInt);

        AddFlightStatusLabel.setText("The flight " + flight + " has been added with " + seats + " seats" );
        BookFlightComboBox.setModel(new javax.swing.DefaultComboBoxModel(Flight.getFlightnames().toArray()));
        StatusFlightComboBox.setModel(new javax.swing.DefaultComboBoxModel(Flight.getFlightnames().toArray()));
        WaitFlightComboBox.setModel(new javax.swing.DefaultComboBoxModel(Flight.getFlightnames().toArray()));
    }

Comment: show your create table query as well
Answer: Looks like you're using wrong table to add seats or wrong index for your table.
Edit:
After checking your table columns you need to add query like this for both functions but it's recommend to use only single method like this:
public void addFlightDetail(String flightNumber, int seats){

  addFlightName = getConnection().prepareStatement("insert into flight (name, seats)
  values(?,?)");
  addFlightName.setString(1, flightNumber);
  addFlightName.setInt(1, seats);
}

Comment: My tables were created by hand using NetBeans. The flight name and the number of seats are in the same table. The flight name is column 1 and the number of seats is column 2. Again, the flight name is accepted as a varchar and the number of seats is accepted as an integer. When I tried to change the index to 2 for the flight seats, it gave me an error and basically said it should be 1.
Comment: Ah, I see what I did. I tried to input the flight name and the number of seats as separate functions when I needed to do it as 1. That way, I can set the indexes as 1 and 2, as they should be in the table. Thanks for the input.


Numerically equivalent set differences

Question: I am studying for an exam, one of the practice questions is as follows

Let $S$ and $T$ be two sets. Prove that if $|S - T| = |T - S|$, then $|T| = |S|$.

The given answer shows that since a bijection exists between $|S-T|$ and $|T-S|$, we prove a bijection exists between $|T|$ and $|S|$ and therefore QED.
Is this really necessary though? Cant I just say

Let $V = S \cap T$, therefore
  $S-T = S-V$, $T-S = T-V$, let $w = |V|$, it follows that $|S-T| = |S-V| = |S| - w$,
      so on for $|T-S|$ and subtract $w$ from both sides and QED

This seems too simple, where am I making a mistake?
Comment: Assume that S AND T means the intersection of S and T, S $\cap$ T
Answer: It is too simple, and wrong. If you want to use cardinal arithmetic in a proof then you need to read up on it and understand it.
You assert that |S - V| = |S| - |V|.
For infinite sets subtraction of cardinalities is genrally not defined. You can see why with the following example....
Consider Z the set of integers and N the set of positive integers.
They have the same cardinality, i.e. |Z| = |N|, but |Z - N| is the set of non-positive integers and its cardinality is the same as N (and Z), so we have |Z - N| = |N| (and  = |Z|). On the other hand N - Z = {} and |N - Z| = 0.
Comment: The actual proof is very short. It relies on the fact that if you can establish bijections between the partitions of two sets (same number of partitions for both) then there is a bijection between the two sets (trivial proof for this). Then S is partitioned {S-T, S$\cap$ T} and T is partitioned {T-S, S$\cap$ T}. Since |S-T| = |T-S| there is a bijection between them, and S$\cap$ T is the same set in both partitions.

Numerically equivalent set differences


Capturing Macros in Scheme

Question: What's the simplest way to define a capturing macro using define-syntax or define-syntax-rule in Racket?
As a concrete example, here's the trivial aif in a CL-style macro system.
(defmacro aif (test if-true &optional if-false)
    `(let ((it ,test))
        (if it ,if-true ,if-false)))

The idea is that it will be bound to the result of test in the if-true and if-false clauses. The naive transliteration (minus optional alternative) is
(define-syntax-rule (aif test if-true if-false)
    (let ((it test))
       (if it if-true if-false)))

which evaluates without complaint, but errors if you try to use it in the clauses:
> (aif "Something" (displayln it) (displayln "Nope")))
reference to undefined identifier: it

The anaphora egg implements aif as
(define-syntax aif
  (ir-macro-transformer
   (lambda (form inject compare?)
     (let ((it (inject 'it)))
       (let ((test (cadr form))
         (consequent (caddr form))
         (alternative (cdddr form)))
     (if (null? alternative)
         `(let ((,it ,test))
        (if ,it ,consequent))
         `(let ((,it ,test))
        (if ,it ,consequent ,(car alternative)))))))))

but Racket doesn't seem to have ir-macro-transformer defined or documented.
Answer: Racket macros are designed to avoid capture by default. When you use define-syntax-rule it will respect lexical scope.
When you want to "break hygiene" intentionally, traditionally in Scheme you have to use syntax-case and (carefully) use datum->syntax.
But in Racket the easiest and safest way to do "anaphoric" macros is with a syntax parameter and the simple define-syntax-rule.
For example:
(require racket/stxparam)

(define-syntax-parameter it
  (lambda (stx)
    (raise-syntax-error (syntax-e stx) "can only be used inside aif")))

(define-syntax-rule (aif condition true-expr false-expr)
  (let ([tmp condition])
    (if tmp
        (syntax-parameterize ([it (make-rename-transformer #'tmp)])
          true-expr)
        false-expr)))

I wrote about syntax parameters here and also you should read Eli Barzilay's Dirty Looking Hygiene blog post and Keeping it Clean with Syntax Parameters paper (PDF).
Comment: When you truly need capture, or want capture for the sake of capture, you can use `datum->syntax` as I'd mentioned. With it, all things are possible, good or bad. But to back up: I wouldn't use `aif` for real code. I think a better idea would be something like `if-let`, where you supply the id. Usually it's clearer and more-dependable when users of the macro supply the identifier. (Obviously there are exceptions like `struct`, but at least that introduces names prefixed by a user-supplied id.)
Comment: TBH, the blog post is not really relevant since the paper covers it more nicely and with more examples...
Comment: @ThrowawayAccount3Million As the last paragraph [here](http://blog.racket-lang.org/2008/02/dirty-looking-hygiene.html) explains: "The resulting macro does not break hygiene. For example, `(let ([it 3]) (if #t it))` evaluates to `3`, because it shadows the global `it` that `if` changes. This is a change from a real unhygienic macro — but that's the whole point: we (the macro author) do not interfere with scopes in the user code."
Comment: Yeah, I know that some people have that reaction -- it's just that the beginning parts in that paper are very accessible...  But yeah, it does make a little value in having just a blog post...
Comment: @EliBarzilay Although I wanted to include the blog post for anyone who might be "OMG PDF!" or "OMG Research Paper!", I agree the paper is best.
Comment: It's broken: `(let ((it 'BAD)) (aif 'show-it (displayln it) 'other-thing))` displays `BAD` instead of `show-it`. The macro fails to capture `it`. What you're doing instead is relying on the equivalent of a global variable.
Comment: @GregHendershott So you and Eli are already aware that it's broken. That doesn't mean it's not broken. Sometimes we *want* to interfere with scope. That's the whole point of capturing macros. As it happens, since my previous comment I've found a way to write a real capturing macro in Racket that involves walking down the syntax tree and stripping the scope (via `datum->syntax` composed with `syntax->datum`) from any identifier that has the same name as the one you want to capture.
Comment: [Example `if-let`](https://github.com/greghendershott/rackjure/blob/master/rackjure/conditionals.rkt#L10-L12).
Comment: I agree that it's *usually* clearer and less bug-prone not to inject bindings into the scope of a user's code. In fact, that's easily 99% of the time. But I don't agree with the extremes to which R6RS has gone in this regard, where even the word `else` in a `cond` or `case` form is a bound identifier that `cond` can't see if there's a local binding named `else`. Every now and again you run into a situation where it's more convenient to be able to inject an identifier, and IMO `aif` is one of those cases. I'd have no qualms with using it in production code.
Answer: See Greg Hendershott's macro tutorial. This section uses anaphoric if as example:
http://www.greghendershott.com/fear-of-macros/Syntax_parameters.html
Comment: In which Greg Hendershott ultimately refers to Eli Barzilay's blog post and paper... thank goodness we have tail elimination... :)
Comment: Or better yet, see [Greg Hendershott's answer](http://stackoverflow.com/a/20055079/1281433). :)
Answer: Although the answer above is the accepted way to implement aif in the Racket community, it has severe flaws. Specifically, you can shadow it by defining a local variable named it.
(let ((it 'gets-in-the-way))
     (aif 'what-i-intended
          (display it)))

The above would display gets-in-the-way instead of what-i-intended, even though aif is defining its own variable named it. The outer let form renders aif's inner let definition invisible. This is what the Scheme community wants to happen. In fact, they want you to write code that behaves like this so badly, that they voted to have my original answer deleted when I wouldn't concede that their way was better.
There is no bug-free way to write capturing macros in Scheme. The closest you can come is to walk down the syntax tree that may contain variables you want to capture and explicitly strip the scoping information that they contain, replacing it with new scoping information that forces them to refer to your local versions of those variables. I wrote three "for-syntax" functions and a macro to help with this:
(begin-for-syntax
 (define (contains? atom stx-list)
   (syntax-case stx-list ()
     (() #f)
     ((var . rest-vars)
      (if (eq? (syntax->datum #'var)
               (syntax->datum atom))
          #t
          (contains? atom #'rest-vars)))))

 (define (strip stx vars hd)
   (if (contains? hd vars)
       (datum->syntax stx
                      (syntax->datum hd))
       hd))

 (define (capture stx vars body)
   (syntax-case body ()
     (() #'())
     (((subform . tl) . rest)
      #`(#,(capture stx vars #'(subform . tl)) . #,(capture stx vars #'rest)))
     ((hd . tl)
      #`(#,(strip stx vars #'hd) . #,(capture stx vars #'tl)))
     (tl (strip stx vars #'tl)))))

(define-syntax capture-vars
  (λ (stx)
     (syntax-case stx ()
         ((_ (vars ...) . body)
          #`(begin . #,(capture #'(vars ...) #'(vars ...) #'body))))))

That gives you the capture-vars macro, which allows you to explicitly name the variables from the body you'd like to capture. aif can then be written like this:
(define-syntax aif
  (syntax-rules ()
       ((_ something true false)
        (capture-vars (it)
           (let ((it something))
            (if it true false))))
       ((_ something true)
        (aif something true (void)))))

Note that the aif I have defined works like regular Scheme's if in that the else-clause is optional.
Unlike the answer above, it is truly captured. It's not merely a global variable:
 (let ((it 'gets-in-the-way))
     (aif 'what-i-intended
          (display it)))

The inadequacy of just using a single call to datum->syntax
Some people think that all you have to do to create a capturing macro is use datum->syntax on one of the top forms passed to your macro, like this:
(define-syntax aif
  (λ (stx)
     (syntax-case stx ()
       ((_ expr true-expr false-expr)
        (with-syntax
            ((it (datum->syntax #'expr 'it)))
            #'(let ((it expr))
                (if it true-expr false-expr))))
       ((_ expr true-expr)
        #'(aif expr true-expr (void))))))

Just using datum->syntax is only a 90% solution to writing capturing macros. It will work in most cases, but break in some cases, specifically if you incorporate a capturing macro written this way in another macro. The above macro will only capture it if the expr comes from the same scope as the true-expr. If they come from different scopes (this can happen merely by wrapping the user's expr in a form generated by your macro), then the it in true-expr will not be captured and you'll be left asking yourself "WTF won't it capture?"
You may be tempted to quick-fix this by using (datum->syntax #'true-expr 'it) instead of (datum->syntax #'expr 'it). In fact this makes the problem worse, since now you won't be able to use aif to define acond:
(define-syntax acond
    (syntax-rules (else)
        ((_) (void))
        ((_ (condition . body) (else . else-body))
         (aif condition (begin . body) (begin . else-body)))
        ((_ (condition . body) . rest)
         (aif condition (begin . body) (acond . rest)))))

If aif is defined using the capture-vars macro, the above will work as expected. But if it's defined by using datum->syntax on the true-expr, the the addition of begin to the bodies will result in it being visible in the scope of acond's macro definition instead of the code that invoked acond.
The impossibility of really writing a capturing macro in Racket
This example was brought to my attention, and demonstrates why you just can't write a real capturing macro in Scheme:
(define-syntax alias-it
  (syntax-rules ()
     ((_ new-it . body)
      (let ((it new-it)) . body))))

(aif (+ 1 2) (alias-it foo ...))

capture-vars cannot capture the it in alias-it's macroexpansion, because it won't be on the AST until after aif is finished expanding.
It is not possible at all to fix this problem, because the macro definition of alias-it is most probably not visible from the scope of aif's macro definition. So when you attempt to expand it within aif, perhaps by using expand, alias-it will be treated as a function. Testing shows that the lexical information attached to alias-it does not cause it to be recognized as a macro for a macro definition written out of scope from alias-it.
Some would argue that this shows why the syntax-parameter solution is the superior solution, but perhaps what it really shows is why writing your code in Common Lisp is the superior solution.
Comment: Downvoting not because of the silly flamewar you're trying to get into, but because it is just not an answer to the original question.  There are three fundamental problems in your answer (and maybe in your understanding).  This will be long so I'll split it into several comments.
Comment: (A) Yes, using a syntax parameter means that the binding can be shadowed -- the reason that this *is* desirable is that the `it` syntax parameter is viewed not as a global, but as *part of the `aif` macro* -- so shadowing `it` is equivalent to shadowing `aif`, and that will (obviously) break it.  (Note btw that `it` should be defined wherever `aif` is defined -- which means that it's as global as `aif` which, in racket, usually means that it's defined in some module (ie, it's still not "global").)  This means that your criticism of syntax parameters is misplaced.
Comment: (B) Your "writing a real capturing macro is impossible" conclusion is wrong.  You can probably fix it by first expanding the input forms (eg, use `local-expand`).  Doing that won't be new though: see the text on syntax parameters which mentions stripping all lexical information (and CL not keeping it in the first place).  Also see Racket's `define-macro` which makes the simple CL-like `aif` definition work fine, and it should also work when used in `acond` and even with `alias-it`.  (`define-macro` is doing what you're essentially trying to do, only in a more organized and methodical way.
Comment: (C) Finally, the main problem is, again, that it's really not answering the question.  If you really insist on this direction, point people at `define-macro` and be done with it.  As for your long post, you should look into this more, phrase it better, and post it somewhere where such discussions are proper.  The Racket mailing list is one such place -- and if you stick to the details instead of being offended, the result is surely going to be better.  SO is just not a good place for such discussions, by design.  This is also why these "comment-discussions" are hard to do, so I'll stop here.
Comment: I'll look into it more, but I've had problems getting `define-macro` to do this kind of thing in the past, which is why I didn't mention it. The same kind of problems I mentioned in the answer, where the macro works only as long as it's not part of another macro. I gave up on it back when lists were still mutable.
Comment: Regarding the appropriateness if this site as a forum, I don't see anybody talking about capturing macros anywhere but here, and I'm only writing about them because the subject came up.
Comment: One possible problem wrt these macros is if you want to combine them with regular ones.  My guess is that in case of macros-using-macros you'll want the whole chain done with `define-macro`.  As for the discussion, there have been countless such discussions, on newsgroups, mailing lists, and blogs.  The whole anaphoric macros thing is a very well chewed-up subject.  That also applies to the realization that `it` is much better considered part of the anaphoric macro syntax rather than a new name that the macro injects, which makes syntax parameters work so well.

Capturing Macros in Scheme


Why are subnet masks specified in full dot notation, rather than just a number?

Question: Subnet masks for IPv4 (dunno about v6) are specified in full dot notation, e.g. 255.255.255.0.  This means that the lower eight bits can be used to assign IP addresses to devices on a LAN (if I understand correctly).  Why write out the full subnet when I can just say 8, i.e. the number of 0 bits in the mask (since they're all on the lower end)?
Comment: It depends on the context. some software was originally written before CIDR notation, and there are also circumstances where odd masks are useful, but many cases use the CIDR notation. IPv6 only uses CIDR notation, and really only `/64` for subnets (there are a few corner cases where you may use `/127` or `/128`).
Comment: It seems to me the premise of this question is invalid, since specifying a netmask as a number of bits is the standard way to do it with IPv6 and in the case of IPv4 it is supported in most places where a netmask is needed.
Answer: There are netmasks that can be defined in dotted notation that can't be defined in CIDR notation. You should avoid using non CIDR netmasks in real life. Example is:
    10.0.0.0 255.254.255.0

Note that there's a bit flipped in the second octet. This turns into two ranges of ip addresses that's defined in a single network + subnet. If I can find a pencil and paper I'll say what two ranges that equals.
Comment: 10.0.0.1-254 and 10.1.0.1-254 I think
Comment: Non-continuous masks are purely theoretical, even sophistic. They cannot be used, because they exclude some host in them. There's no mechanisms of routing and announcing such bogus prefixes, so only continuous masks are used, and if more discretion is needed, subnet is splitted to smaller subnets.
Comment: There's no good reason for it not to work, the netmask is mainly for separating the lan from the stuff that needs to go through the gateway.
Comment: I - implementation. You have nothing behind you except a theory. Prove it in a production envirnment.
Comment: Supported by openbsd, therefore non theoretical: https://www.youtube.com/watch?v=QsUlySdtqaw
Comment: OpenBSD userbase and wildlife incidence is purely hypothetical. I'd say it's limited to the environments of the openbsd.org infrastructure itself.
Comment: Good point, I guess until someone actually uses OpenBSD for something it IS theoretical.
Answer: Because it's more meaningful to indicate the number of bits set in the mask, rather than the number of bits unset. That would be /24. That is, in turn, because masks are more often used to answer the question "Is the destination in the same network as I am ?", and the answer would depend on bitwise AND between the mask and IP address. If the result of such operation on the source IP and mask and the destination IP and same mask will be identical, this means that they are in the same network, so no gateway interaction is needed.
And yes, slash notation is more handy, but it's also more complex to understand, because it requires the understanding of mask/prefix purpose. Lots of people lack this  understanding, so it's easier for them to use the usual IP notation they are familiar with. That is the main reason of such notation.
Comment: When it comes to networking equipment like routers, most of the software was originally written before CIDR notation. The vendors haven't changed to CIDR notation where it existed before because it would break all the existing configurations. I have seen vendors new to the game, and vendors which add something new, using the CIDR notation. For instance, IPv6 is new and is only using CIDR notation. I have also seen some IPv4 stuff added to Cisco which uses CIDR notation, but Cisco can't change that interface addresses use dotted-decimal notation because it will break customer configurations.
Comment: Could you elaborate on the first sentence, I don't really see how it relates to the two options in the question. The two options presented are: specifying the exact mask in its entirety (eg 255.255.252.0) or saying that the mask is a prefix of length n with all bits set to 1 (eg /22).  Being able to specify a non-consecutive mask (eg 255.254.255.0, as described by Some Linux Nerd in another answer) is of course theoretically flexible but it's not very useful for most practical applications.
Comment: As for someone who does not understand the purpose of the netmask/prefix, I doubt that they would make sense of either and entering a single number that you don't understand instead of four dot-separated numbers that you don't understand wouldn't make much difference, if anything it would probably be easier to just enter the single number.
Comment: Non-continuous masks are sophistic. This is sort of mind joke or internet trolling. See my comment to that local genius.


Skip diff dialog while using p4vc

Question: I would like to compare two p4 files from command line without it opening diff dialogI'm using p4vc
Command: "p4vc diff fileA#1 fileB#2"
This initially opens diff dialog box asking to confirm the files and versions and when I click Diff, it then shows the differences. Is there any way to bypass or skip this intermediate step?
I know I can use other diff tools as default but would prefer to use inbuilt p4 diff tool. Is there anyway to force diff or option to not show the dialog?
Answer: You can use the p4 command line client if you want to use Perforce's built-in diff logic and don't want to see any UI:
p4 diff2 fileA#1 fileB#2

Comment: I want to see the differences in the diff tool without another prompt asking me to confirm the files to compare. Command line diff is not very readable/flexible when comparing huge files
Comment: Check out this thread on forums.perforce.com, sounds like someone else has a similar need and they gave a few more details: https://forums.perforce.com/index.php?/topic/5990-bypass-dialog-during-p4vc-diff/#entry24535
Comment: That is posted by me :)
Answer: I couldn't find a better way to bypass the dialog box using p4vc. From the response I received from perforce forum https://forums.perforce.com/index.php?/topic/5990-bypass-dialog-during-p4vc-diff/, a user suggested using p4merge.
Steps:

p4 print -o fA fileA#1
p4 print -o fB fileB#2
p4merge fA fB

This will bring up the p4 diff tool for comparison. The limitation with p4merge is that it can only compare local files which requires the p4 files to be printed into local files and compare them. Network bandwidth can cause slight delays fetching the files from p4.

Skip diff dialog while using p4vc


Meu código para o enigma das jarras não está funcionando

Question: Em primeiro lugar, quero agradecer todos os que lerem esse meu pedido de ajuda. Sou bem novato na linguagem C e tenho mais que certeza que errei e não foi pouco nesse código. Passei o dia todo me empenhando em escrevê-lo mas não consigo achar o erro. Creio que seja algum uso inadequado de ponteiros na função swap() ou alguma outra coisa boba que eu fiz. Enfim, aí está. Por favor, perdoem as noobagens, fiz tudo com meu melhor. O programa até aceita alguns movimentos, mas a maioria não. Estou a utilizar o Ubuntu na sua última versão.
Edit1: O problema das jarras é o seguinte:
Você tem três jarras numa mesa a sua frente. A primeira comporta três litros, a segunda cinco litros e a última, comporta oito, e é a única que está cheia. Seu objetivo é separar quatro litros nas jarras b e c, e o único movimento que você pode fazer é o de trocar o líquido de uma jarra para a outra, até que ela atinja o limite da jarra que recebe, ou até o líquido da jarra que despeja acabar.
Edit2: Fiz algumas pequenas modificações e o programa acerta algumas respostas com precisão, por exemplo:
State:
a = 0, b = 0, c = 8
>3 1
State:
a = 3, b = 0, c = 5

Porém transferir de c para b não retorna o esperado:
State:
a = 3, b = 0, c = 5
>3 2
State:
a = 3, b = 3, c = 2

Obrigado desde já.
Edit3: Código comentado para melhor compreensão.
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#define MAXA 3 //Defino o maximo da variável a, e etc;
#define MAXB 5
#define MAXC 8

int a = 0, b = 0, c = 8; //Defino que só a terceira está cheia.
void swap(int *po, int *pd) //Função de troca, aceita dois ponteiros para inteiros,
{                           // Mas não sei se estou a usar corretamente;
  int maxor, maxdes; //Defino duas variáveis que comportarão o máximo da origem e destino.
  if(po != &a && po != &b && po != &c || pd != &a && pd != &b && pd != &c || po == pd) //Caso for inválido,
    return; //quebre.
  if(po == &a) //Se o ponteiro recebido apontar para a, máximo da origem é MAXA, etc...
    maxor = MAXA;
  if(po == &b)
    maxor = MAXB;
  if(po == &c)
    maxor == MAXC;
  if(pd == &a)
    maxdes = MAXA;
  if(pd == &b)
    maxdes == MAXB;
  if(pd == &c)
    maxdes == MAXC;
  int d = maxdes - *pd; //Variável que define o quanto o destino comporta, e o quanto a origem fornecerá.
  *pd += d;
  *po -= d;

}
int main()
{
  int *pa = &a; //Defino os ponteiros para as respectivas variáveis.
  int *pb = &b;
  int *pc = &c;
  while(b != 4 && c != 4) //Enquanto não houver quatro litros em b e c;
  {
    int (*alfa), (*beta); //Ponteiros que eventualmente apontarão pra escolha do usuário.
    int cho, chos; //Inteiros de escolha de origem e destino.
    printf("State:\na = %i, b = %i, c = %i\n>", a, b, c); //Imprime o estado atual.
    scanf("%i %i", &cho, &chos);
    if(cho == 1) //Caso cho seja 1, o ponteiro alfa aponta para a, e etc.
      alfa = &a;
    if(cho == 2)
      alfa = &b;
    if(cho == 3)
      alfa = &c;
    if(chos == 1)
      beta = &a;
    if(chos == 2)
      beta = &b;
    if(chos == 3)
      beta = &c;
    swap(alfa, beta); //Realize a troca entre alfa e beta;
  }
}

Comment: Em sua função swap, primeiro if, você quer mesmo comparar o endereço das variáveis? Não vejo sentido nisso, creio que deveria comparar o conteúdo destas variáveis.
Answer: Acredito que seu programa poderia ter muitas de suas características re-pensadas, como a necessidade de ter variáveis globais e a necessidade de fazer uso de tantos ponteiros, visto que existem apenas três potes. Porém, não vou tratar disso na resposta, visto que você pediu para tal.
O problema principal pode ser corrigido apenas olhando os warnings que o compilador retorna (preferencialmente compilando com a opção -Wall). Embora tenha sido mais de um, vou omitir os semelhantes, sobrando os da seguinte forma:
testeC.c:19:11: warning: equality comparison result unused [-Wunused-comparison]
    maxor == MAXC;
    ~~~~~~^~~~~~~
testeC.c:12:27: warning: '&&' within '||' [-Wlogical-op-parentheses]
  if(po != &a && po != &b && po != &c || pd != &a && pd != &b && pd != &c || po == pd) //Caso for inválido,
     ~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~ ~

O primeiro warning mostra que você se confundiu o operador de atribuição =, com o operador de comparação ==. Em algumas linhas você utilizou maxor==MAX_ quando deveria ter utilizado maxor=MAX_. Este é o caso das linhas 19, 23 e 25.
Além disso, o outro warning te alerta sobre algo que deve sempre ser feito no caso de if's lógicos como o seu. Você deve sempre utilizar parênteses para explicitar ao compilador a ordem que você quer que ele realize as operações. Na dúvida sobre a precedência dos operadores, minha sugestão é pecar pelo exagero e pela leitura facilitada do código.
Com essas modificações o código parece funcionar:
State:
a = 0, b = 0, c = 8
>3 1
State:
a = 3, b = 0, c = 5
>3 2
State:
a = 3, b = 5, c = 0

Por último, acredito que você esqueceu de verificar no final da função swap, se o jarro de origem possui conteúdo suficiente para fazer a transição. Você verifica apenas a capacidade no destino. Isso gera o seguinte engano:
State:
a = 0, b = 0, c = 8
>3 1
State:
a = 3, b = 0, c = 5
>3 2
State:
a = 3, b = 5, c = 0
>1 3
State:
a = -5, b = 5, c = 8

Como foram poucas modificações, acredito não ser necessário re-colocar o código completo aqui, mas se você precisar ou tiver alguma dúvida adicional basta pedir.
Comment: Muito obrigado, agora está funcionando perfeitamente.
Comment: De nada! Não se esqueça de marcar a resposta como aceita, para a pergunta ficar como resolvida, e ajudar eventuais buscas no site.


Colunas no Bootstrap não está funcionando

Question: Estou tentando colocar a logomarca da empresa do lado esquerdo e o título do lado direito com Bootstrap, mas não está funcionando. Quando coloco o código abaixo, fica um embaixo do outro. Estou usando a versão 4.0. Vejam:

Nossa História

Answer: Você esqueceu de inserir o .row, então ficaria deste modo:

Nossa História

Ilustração de como ficará (do modo que pediu)
Comment: Perfeito Thiago. Funcionou. Tentei dar como aceite sua resposta, mas tenho que esperar 5 minutos. Assim que passar esse tempo, marcarei como a resposta correta. Obrigado!
Comment: @Fox.11 tudo bem, fico no aguardo. Obrigado você!


matlab for loop in brute force

Question: hi I am working with the brute force method that I have shown in the code below.
the size of PV_supply, WT_supply and Demand are all 48x1.
what I am tying to do is calculate the "hourly_deficit" equation for n = 1:24 and n = 25:48 separately so as to output 2 "sets" of "hourly_deficit"
My code is
for number_panels = 0:5
    for number_turbines = 0:3
      for n = 1:24:48 % number of hours per day

  hourly_deficit(number_panels + 1, number_turbines + 1, n) =...
 Demand(n) - (PV_supply(n)*number_panels) - (WT_supply(n)*number_turbines);

end
 end
  end

I was hoping on some help with how I should adapt the for loop so as to get the results as I am looking for. As it stands, the for n = 1:24:48 only actually goes up to n = 24
Thank you
Comment: possible duplicate of [sum 3dimensional matrix - Matlab Brute force](http://stackoverflow.com/questions/11484039/sum-3dimensional-matrix-matlab-brute-force)
Answer: 1:24:48 means "from 1 by increments of 24 until 48": The values therefore would be 1 25 49... if you kept the series going.  Since 49 is outside the bounds you defined, it stops at 25.
One solution for doing what you want would be the following:
for n = 1:24 % 1 by 1 to 24

    hourly_deficit_1(...,..., n)= Demand(n)-(PV_supply(n)... %# truncated
    n=n+24;
    hourly_deficit_2(...,..., n)= Demand(n)-(PV_supply(n)... %# truncated

end

To generalize for any number of days, add a 4th dimension to the matrix.  Third dimension would be hour (1:24), 4th would be day.
for h=1:24 %# hours
    for d = 1:num_days %# which day
        n = h + 24*(d-1);
        hourly_deficit_1(...,..., h, d)= Demand(n)-(PV_supply(n)... %# truncated
    end
end

Comment: thanks that works - since I am trying to add another 8760 n's is there any way of doing this code to deal with this large data set?
Comment: since the hourly_deficit will go up to hourly_deficit_365?
Comment: Edited in response to comment.
Comment: nice thank you ! do you think it is easier to work with a 365x24 matrix rather than with a 8760x1 matrix (reshaped) or is it effectively the same?
Comment: Just to confirm - there is a for loop for an "n" number of hours 1:24 and "h" 1:24 as well?
Comment: No.  Loop for `h`(hours) and `d`(days). Calculate `n` inside the loop.

matlab for loop in brute force


An example with Brownian Motion

Question:
I wonder why here in the solution above, Why P{Y(1/2)> - segema} becomes P{ Y(1/2)/segema/ square root of2}
Thanks
Comment: Hi cynthiaaaaii, thanks for posting the question. Can you copy the text in your image to the description because this will make the problem easy to find later.
Answer: We divide each side of the inequality by $\sigma/\sqrt{2}$, which is how we get from the first circled step to the next.
If you're asking why we're dividing, it's because we want to make the random variable on the left-hand side of the inequality a standard normal random variable. This way, we can use the normal cumulative distribution function to finish our calculation.

An example with Brownian Motion


convert to date in R using abbreviated month

Question: I'm new to R and trying to load some time series data but I'm stuck at the first hurdle.
I have a dataframe with a date column called Date. The date format of the data is: 23-May-16 (it appears like this in the R console when I print df). To read as date I'm trying:
df$Date <- as.Date(df$Date, "%dd-%bbb-%yy")

as per guidance here
which produces the value <NA> when it reads the data.
Comment: You are just using the wrong format and you should really read the docs of `?as.Date` or `?strptime` which have similar examples. factors have nothing to do with this.
Comment: `df$Date <- as.character.Date(df$Date)` or use `strptime` or the package `anytime` and list goes on and on. Or you can provide a reproducible example.
Comment: is "df$Date" a `character`? Try `str(df)` ?
Comment: apparently `df$Date` is a factor... `ï..Date: Factor w/ 251 levels`
Comment: may be the first thing is to convet the factor to char first.  [here](http://stackoverflow.com/questions/2851015/convert-data-frame-columns-from-factors-to-characters#2851213). You can do `options(stringsAsFactors=FALSE)` and reread your `data.frame` as well. Then @agerom solution seems fine. Cheers!
Answer: Try:
as.Date(df$Date,format="%d-%b-%y")
Comment: glad it helps. As a separate note bear in mind that 'lubridate' package's magic. Give it a shot
Answer: You only need to list those once:
as.Date("23-May-16", "%d-%b-%y")


Cron job failed without a reason

Question: I am in a situation where I have a CRON task on google app engine (using flex environment) that just dies after some time, but I have no trace WHY (checked the GA Logs, nothing, tried try/catch, and explicitly log it - no error).
I have explicitly verified that if I create a cron task that runs for 8 minutes (but doesn't do much - just sleeps and updates database every second), it will run successfully. This is just to prove that CRON jobs can at least run 8 minutes if not more. & I have set up the Express & NodeJS combo up correctly.
This is all fine, but seems that my other cron job dies in 2-3 minutes, so quite fast. It is hitting some kind of limit, but I have no idea how to control for it, or even what limit it is, so all I can do is speculate.
I will tell more about my CRON task. It is basically rapidly querying MongoDB database where every query is quite fast. I've tried the same code locally, and there are no problems.
My speculation is that I am somehow creating too many MongoDB requests at once, and potentially running out of something?
Here's a pseudocode (just to describe what kind of scale data we're talking about - the numbers and flow are exactly the same):
function q1() {
      return await mongoExecute(async (db) => {
        const [l1, l2] = await Promise.all([
            db.collection('Obj1').count({uid1: c1, u2action: 'L'}),
            db.collection('Obj1').count({uid2: c2, u1action: 'L'}),
        ]);

        return l1+l2;
    });
}

for(let i = 0; i < 8000; i++) {
   const allImportantInformation = Promise.all([
       q1(),
       q2(),
       q3(),
       .....
       q10()
   ])

   await mongoDb.saveToServer(document);
}

It is getting somewhere around i=1600 before the CRON job just dies without any explanation. The GA Cron Job panel clearly says the JOB has failed.
Here is also my mongoExecute (which is just a separate module that caches the db object, which hopefully is the correct practice in order to ensure that mongodb pooling works correctly.)
import { MongoClient, Db } from 'mongodb';

let db = null;
let promiseInProgress = null;

export async function mongoExecute<T> (executor: (instance: Db) => T): Promise<T | null> {

    if (!db) {
        if (!promiseInProgress) {
            promiseInProgress = new Promise(async (resolve, reject) => {
                const tempDb = await MongoClient.connect(process.env.MONGODB_URL);
                resolve(tempDb);
            });
        }

        db = await promiseInProgress;
    }
    try {
        const value = await executor(db);
        return value;
    } catch (error) {
        console.log(error);
        return null;
    }
}

What would be the solution? My idea is to basically ensure less requests are made at once (so all the promises would be sequential, and potentially add sleep between each cycle in the FOR.
I don't understand because it works fine up until some specific point (and quite big point, it's definitely different amount, sometimes it is 800, sometimes 1200, etc).
Is there any "running out of TCP connections" scenario happening? Theoretically we shouldn't run out of anything because we don't have much open at any given point.
It seems to be working if I throw 200ms wait between each cycle & I suspect I can figure out solution, all the items don't have to be updated in the same CRON execution, but it is a bit annoying, and I would like to know what's going on.
Is the garbage collector not catching up fast enough, why exactly is GA silently failing my cron task?
Comment: My guess is the `MongoClient.connect()` code is being called in rapid-fire manner thus the job is eating too much TCP connection, since `connect()` in the node driver creates a connection pool containing 5 connections by default. This could explain why putting a 200ms wait makes it work, since the code found that the `db` is not null anymore, thus it's not rapid-firing the `connect()` method and properly uses the existing connection pool. Essentially without the wait, the code quickly creates a lot of connection pools. With the wait, it creates only one connection pool.
Comment: You can check if this is indeed the case by moving the `MongoClient.connect()` code outside of `MongoExecute` into the main part of the code. Pass in the `db` object into each `q()` functions. This is best practice anyway, `MongoClient.connect()` is supposed to be called only once per app execution, since it creates a connection pool instead of a single connection to the database.
Comment: That's an interesting theory, although to my understanding the execution going on in the CRON job is single threaded (because JS is single threaded), which means there is no race condition (and MongoClient.connect should be called only once). However, it doesn't really hurt to actually test it so I will give it a try. Thanks
Comment: @KevinAdistambha I tried it, but it is like expected: the mongoExecute() only ever creates single connection at apps lifetime, no matter how fast mongoExecute() is being executed. I also fixed the issue by updating mongodb driver.
Answer: I discovered what the bug is, and fixed it accordingly.
Let me rephrase it; I have no idea what the bug was, and having no errors at any point was discouraging, however I managed to fix (lucky guess) whatever was happening by updating my nodejs mongodb driver to the latest version (from 2.xx -> 3.1.10).
No sleeps needed in my code anymore.

Cron job failed without a reason


NCO: Copying data from one netcdf file into another only for a specific area

Question: I have two NetCDF files with the exact same dimensions (time,lat,lon). Below is the header of one of the files.
netcdf file1 {
dimensions:
        lon = 360 ;
        lat = 177 ;
        time = 360 ;
variables:
        double lon(lon) ;
                lon:units = "degrees_east" ;
                lon:long_name = "Longitude" ;
        double lat(lat) ;
                lat:units = "degrees_north" ;
                lat:long_name = "Latitude" ;
        double time(time) ;
                time:long_name = "Time" ;
                time:units = "months since 1989-05-01 00:00" ;
        double tmp(time, lat, lon) ;
                tmp:_FillValue = -999000000. ;
}

I would like to copy values from one file into the other, but only for a small region determined by lat1,lat2 and lon1,lon2. Both files have the same time coordinates.
Something like: (lon1<lon<=lon2) & (lat1<lat<=lat2) file1 = file2
I was wondering if I could do that with NCO.
Any help will be appreciated.  Thank
Answer: Read the manual section on the ncap2 where function. It describes how to use where on a hyperslab. That will do it:
*var_tmp=var2(:,0,:,:);
where (var1 < 0.5) var_tmp=1234;
var2(;,0,:,;)=var_tmp;

Comment: Thank you, Charlie for answering my question.  So for your suggestion to work i would need to combine both file1 and file2 into one third file, and change one of the variables name in that 3rd file.  Right?


Add images to blog with ImageField?

Question: Using drupal 5.x.  I have a content type I created called "Blog Entry"  it has no fields other than the standard title and body.  Now I want to be able to place images at arbitrary points in the body of the blog entry and have them appear.  I already have ImageField and ImageCache installed for use with another content type.  Is there a way I can use those two modules to achieve my goal or do I need to install something like the Image module?
Answer: I found this article which describes one method of doing this.  Looks promising not sure if it's the best way.   For one I'm not immediately sure how to handle multiple images.  How To: Inline Images with ImageField and ImageCache using HTML
UPDATE
Yes I can confirm this works.  You can use a single ImageField and check the "Multiple values" checkbox when creating the image field to support multiple images.  I named my field "blog_images".  Then on the "Display Fields" tab I set the label, teaser, and Full values to all be <code>"<hidden>"</code>

Add images to blog with ImageField?