How do I spell a note when none of the usual rules make a difference?

Question: Let's consider the "black note" between G and A. If this note does not occur in a scale/key, but it nevertheless occurs in a composition based on that scale/key, what are the rules for rendering it G♯ or A♭ if, say, the piece was in C major? I know there are preferences for using the least amount of ink and showing note motion. For example, if the notes which preceded and succeeded it were both G, A♭ would be preferred because it shows the note on a higher line/space and (assuming no A appears later in the measure) a natural is not needed to cancel it. But let's say all things are equal. What rules then govern the spelling of the note?
I chose G♯/A♭ because it occurs as often in flat keys as it does in sharp keys (by contrast, B♭ occurs in every flat key while A♯ doesn't enter the picture until the key signature has 5 sharps) and I chose C major because it has no accidentals in its key signature.
Answer: The point of choosing A♭ over G♯ is not that it saves ink, but that it expresses properly the function the note fulfills: as a cambiata / melodic movement within a single scale. G - G♯ would imply you're building up tension by leaving the old scale, which would most naturally fit as the raised degree of a dominant, i.e. E₇ as the dominant to Am, with the G♯ leading up to A.
So, that's really the main question to ask: what effect does this note have? Would it sound fitting if you resolved it to A? Then it's a G♯. If it sounds more sensible if you resolve it to G or even G♭,† then it's an A♭. (Regardless of whether that actually happens in the piece.)
This, or any other rule, won't work always, but it's IMO the one that gets most to the heart of what those accidentals are really about.

†Of course then the next question would be: is it really G♭? If it resolves to F♯, then the preciding note would again more sensibly be G♯.
Answer: There's a thing called the Harmonic Chromatic Scale, which works on the principle that you leave the tonic and 5th 'clean', every other note occurs twice. But I really wouldn't worry about it!   Write chromatic runs with sharps going up, flats coming down.  Where the harmony is clear, try not to obscure it - e.g. if there's an E7 - Am harmony make the E7 LOOK like an E7 with a G#.   If it's F, Fm, C, give Fm an Ab.
Answer: In addition to Laurence's answer I would like to add something I always taught my piano students, when I was still teaching.  If a black note occurs in a triad or 7 chord, remember that there must be a letter missing between every two notes.  So, if there's a G#/Ab between an E and a B, then the black note must be G#, because you have to skip the F and the A.  (You can't have no letters missing, and you can't have two between two adjacent notes in the chord.)  Likewise, if there's an F below the black note, and a C above it, the black note must be Ab, because you have to skip the G and the B.
The same principle works with 7 chords.  There has to be a letter missing between the 5th and the 7th.  So an Amaj7 chord has to have G# as the 7th tone, because there has to be a letter missing (and only one) between the E and the 7th note.
This works whenever a note in question is part of the harmonic pattern.  If it isn't, use Laurence's solution.
Comment: I'm not sure this helps the OP. Their note doesn't seem to occur in a simple triad or 7th chord, and if it's not then this system fails. It fails in a lot of interesting situations in fact, for instance add2 chords (which may be sure be problematic on inexact instruments like piano, but can sound awesome when e.g. sung in just intonation) have no "letter between the notes", nor do inversions of seventh (possible diminished-seventh) chords. And this scheme might give nonsensical results if you e.g. apply it to a sus4 chord as "B♭ D♯ F", which is just generally bogus.
Comment: I think I covered that in "Where the harmony is clear, try not to obscure it - e.g. if there's an E7 - Am harmony make the E7 LOOK like an E7 with a G#."
Answer: Depends on both the harmony and direction. For example, some hold that the Eb in borrowed V9 of V of c minor, used in C major (that is D-F#-A-C-Eb) is notated as Eb if it goes to D, but as D# if it goes to E. However, some theorists insist that no matter what direction it goes along, the minor-key-borrowed V9 of V is still the same chord, and Eb must always be notated as Eb, as if it is the V of g minor. So the matter is still controversial. Moreover, in a twelve tone composition, the one that is more succinct is used; there, all 12 notes are created equal. So, no, there is no compulsory rule, but convention is what I said.
Comment: 9th note of D9 is E. b9 note of D is Eb. Should it be 'Vb9 of V'?
Answer: The 7th is flat. So it seems pretty natural to make the G#/Ab a flat. But if your just trying to make the augment then you'll just make the sharp because that's the agreed way that it's always done.
Comment: As it stands, this answer seems confusing. It needs expanding upon to make more sense.
Comment: This comment of Tim is not mocking you, it's a try to help you and give an advice.  Your answer is short, but unclear. Yes,  b7 is flat, but on what are you referring? OP doesn't ask about the 7th. He asks why do we differ and decide that the black key is Ab or G#... you're not answering this question.


Silverstripe: ajax search only shows ids

Question: I've got an Event content type that has coupled events. The content type does not have a title. I've defined a searchable_fields private static:
private static $searchable_fields = array(
    'ProjectNumber',
    'EventDate'             => 'PartialMatch',
    'TicketCode'            => 'PartialMatch',
    "Package.Title"         => 'PartialMatch',
);

Searching in the field (see attachment) is working, but I only see the ID, whcih is, to say the least, less than optimal :-). Does anyone know how to override the system in such a way that it shows the TicketCode or EventDate?
Answer: By default, the GridFieldAddExistingAutocompleter displays the $Title of the result. If you don't have Title or Name field, this defaults to #$ID, as you're seeing.
You can either add a getTitle method to your class that returns what you want, or change what gets returned by the component.
You'd do this using something like:
$config->getComponentByType('GridFieldAddExistingAutocompleter')->setResultsFormat('$TicketCode - $EventDate.Nice');

Comment: Thanks! In the end I used the getTitle method.
Answer: Define the fields you'd like to display in the GridField using:
private static $summary_fields = array(
    'TicketCode',
    'EventDate'
);

Documentation here: http://doc.silverstripe.org/framework/en/reference/dataobject#summary-fields


Continuous function of CountDownTimer

Question: I am making an app with a function to start a Timer. However I am facing a very serious problem.
Now suppose I have stared the timer of 10 minutes using CountDownTimer. After 10 minutes it should give me a beep. Now suppose I have pressed the home button thus making an application go on background. CountDownTimer property is that it continues to countDown, thus after 10 minutes I will get a beep.
However this happens if the screen time is not out. If the screen time is out and the screen goes blank/black then the timer still continues but at its finish, nothing in the application runs like app is on pause and once i click any button on mobile to make the mobile active, the application starts running in the background again..
I want to stop this and want the app to run even the screen time is out too.
How can this be possible.
Answer: You will have to get a partial wakelock to keep the CPU running , so that your timer continues to run. Otherwise the device goes to sleep.
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Countdown");
 wl.acquire();

In finish you can do a release.
 wl.release();

Comment: release should be done in onfinish of CountdownTimer. Phone will be awake till timer expires. If expiration time is high, then it is better to go with AlarmManager with WAKEUP flag
Comment: I know this is an old thread but I was trying something similar and in my case the timer still stops working if you place the application in the background (press home and open another app and then switch the screen off). I acquire a PARTIAL_WAKE_LOCK but OnPause and OnStop are both hit and the CountDownTimer stops. Anything I should be on the look-out for?
Comment: where are you releasing the wakelock? onpause and onstop will not stop hitting if you acquire a wakelock
Comment: Releasing the wakelock onPause and onFinish (which ever happens first).
Comment: Thanks for the help. Going to check-out AlarmManager. Only releasing wakelock onFinish but even with an expiration of only 3 minutes, if focus changes to another app and the screen is switched off the timer stops.
Comment: Just for interest. I tried it on HTC with Adroid 2.3.5 and PARTIAL_WAKE_LOCK works but on Samsung Galaxy S III with 4.1.2, it doesn't work when focus changes to another app and the screen is switched off. Going to see if it's 4.1.2 or Samsung Galaxy S III that makes the difference.

Continuous function of CountDownTimer


asp:Textbox type="date" não é preenchido

Question: Estou criando um formulário em asp onde um asp:Textbox deveria carregar a data de validade de um produto, que deveria ser preenchido no page_load() com os dados da banco, e ser livre para alteração, caso necessário
O problema é que, com o type="date" eu não consigo preencher o campo no pageload da pagina:
a data que o banco retorna: {28/02/2020 00:00:00}
TextBox:
<asp:TextBox type="date" id="txtValidade" class="TextBoxSaldo" Width="50%" runat="server" />

Chamada para preencher o campo:
txtValidade.Text = lstValidade[0].DT_VALIDA.ToString("dd/MM/yyyy");

O que eu ja tentei:
Mudar o formato da data:
Nessa outra pergunta, a resposta aceita diz que o problema é no formato da data, então tentei mudar o formato para
lstValidade[0].DT_VALIDA.ToString("yyyy/MM/dd")

e não rolou.
Definir o CultureInfo:
no CodeBihide tentei definir os formatos para "pt-BR"
    Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-BR");
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("pt-BR");

se eu alterar o tipo do input para text, funciona, mas eu perco a função do formato de data
Answer: O formato do atributo value= para o type=date deveria ser este:

<input type="date" value="2020-02-05">

E não isto:

<input type="date" value="02/05/2020">

Veja que o segundo não funciona, aparece dd/mm/aaaa, se o navegador estiver em "portugues do Brasil", logo o problema é o value que você passou, creio que se ajuste assim:
txtValidade.Text = lstValidade[0].DT_VALIDA.ToString("yyyy-MM-dd");

Não pude testar para confirmar porque não tenho asp.net aqui, se falhar me avisa
Comment: @GabrielOliveira foi erro de digitação meu, a intenção era `-` mesmo, como fiz no primeiro HTML, editei, agora deve estar OK
Comment: Funcionou, só a formatação no `ToString("yyyy/MM/dd")` que, como vc disse, é com `-` e não `/`
Answer: Eu fiz algo desse tipo e funcionou, só que tava pegando de um objeto DataTable:
DateTime dtCadastro = Convert.ToDateTime(dt.Rows[0]["DT_Cadastro"].ToString());
txtdtcadastro.Text = dtCadastro.ToString(@"yyyy-MM-dd"); //
Answer: Mas como foi comentado acima, isso tem haver com a mascara aplicada que no caso foi yyyy-MM-dd.
Também fiz algo parecido para um campo textBox do tipo TextMode="Number" e funcionou de boa.
double precoCusto = Convert.ToDouble(dt.Rows[0]["Preco_Custo"].ToString());
txtprecocusto.Text = precoCusto.ToString("F2",CultureInfo.InvariantCulture);


How to cluster polygons with react-leaflet?

Question: I'm looking for a way to cluster polygons using react-leaflet v4 and react-leaflet-markercluster. I have not found any up-to-date examples of how I can achieve this, so I'm hoping I might get some help here.
Any example code to get me started would be a great help!
Comment: Could you explain more of what you want to achieve, do not really get the part with cluster polygons? The problem I see with most react-leaflet extensions is that they are not maintained and hard to adapt to your needs. If you look at the code of most of these extensions its often just 150 lines of code that utilize a real Leaflet plugin.
I often end up copying the code from the react-leaflet plugins and make them work.
Let me know what you need so I can see if my solution matches
Comment: @Disco Thanks for the response. So with react-leaflet-markercluster, each marker will automatically cluster at specific zoom-levels. It will cluster both markers and circles, but not polygons. I've been using polygons as a type of marker in my map, so I'm looking for a way to cluster these together with normal markers and circles.
Comment: It should be possible, I have not done anything with polygons, but I posted the code I use for markerclusters below. Hopefully it points you in the right direction. Best of luck. And If you find a suitable solution, please post it as an answer.
Answer: This will probably not solve your problem directly but hopefully show that using markercluster is rather simple. The only thing you need is to have a createMarkerCluster function.
clusterProps has a field for polygonOptions:
        /*
        * Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster.
        * Defaults to empty
        */
        polygonOptions?: PolylineOptions | undefined;

Since you now use a plain leaflet plugin it opens up for mor information on the internet, these two might help how you should configure polygonOptions
How to make MarkerClusterGroup cluster polygons
https://gis.stackexchange.com/questions/197882/is-it-possible-to-cluster-polygons-in-leaflet
Below is my general code to make clustermarkers work with React:
import { createPathComponent } from "@react-leaflet/core";
import L, { LeafletMouseEventHandlerFn } from "leaflet";
import "leaflet.markercluster";
import { ReactElement, useMemo } from "react";
import { Building, BuildingStore, Circle } from "tabler-icons-react";
import { createLeafletIcon } from "./utils";
import styles from "./LeafletMarkerCluster.module.css";
import "leaflet.markercluster/dist/MarkerCluster.css";
type ClusterType = { [key in string]: any };

type ClusterEvents = {
  onClick?: LeafletMouseEventHandlerFn;
  onDblClick?: LeafletMouseEventHandlerFn;
  onMouseDown?: LeafletMouseEventHandlerFn;
  onMouseUp?: LeafletMouseEventHandlerFn;
  onMouseOver?: LeafletMouseEventHandlerFn;
  onMouseOut?: LeafletMouseEventHandlerFn;
  onContextMenu?: LeafletMouseEventHandlerFn;
};

// Leaflet is badly typed, if more props needed add them to the interface.
// Look in this file to see what is available.
// node_modules/@types/leaflet.markercluster/index.d.ts
// MarkerClusterGroupOptions
export interface LeafletMarkerClusterProps {
  spiderfyOnMaxZoom?: boolean;
  children: React.ReactNode;
  size?: number;
  icon?: ReactElement;
}
const createMarkerCluster = (
  {
    children: _c,
    size = 30,
    icon = <Circle size={size} />,
    ...props
  }: LeafletMarkerClusterProps,
  context: any
) => {
  const markerIcons = {
    default: <Circle size={size} />,
    property: <Building size={size} />,
    business: <BuildingStore size={size} />,
  } as { [key in string]: ReactElement };

  const clusterProps: ClusterType = {
    iconCreateFunction: (cluster: any) => {
      const markers = cluster.getAllChildMarkers();

      const types = markers.reduce(
        (
          acc: { [x: string]: number },
          marker: {
            key: string;
            options: { icon: { options: { className: string } } };
          }
        ) => {
          const key = marker?.key || "";
          const type =
            marker.options.icon.options.className || key.split("-")[0];
          const increment = (key.split("-")[1] as unknown as number) || 1;

          if (type in markerIcons) {
            return { ...acc, [type]: (acc[type] || 0) + increment };
          }
          return { ...acc, default: (acc.default || 0) + increment };
        },
        {}
      ) as { [key in string]: number };
      const typeIcons = Object.entries(types).map(([type, count], index) => {
        if (count > 0) {
          const typeIcon = markerIcons[type];
          return (
            <div key={`${type}-${count}`} style={{ display: "flex" }}>
              {typeIcon}
              {count}

          );
        }
      });
      const iconWidth = typeIcons.length * size;

      return createLeafletIcon(

          {typeIcons}

,
        iconWidth,
        undefined,
        iconWidth,
        30
      );
    },
    showCoverageOnHover: false,
    animate: true,
    animateAddingMarkers: false,
    removeOutsideVisibleBounds: false,
  };
  const clusterEvents: ClusterType = {};
  // Splitting props and events to different objects
  Object.entries(props).forEach(([propName, prop]) =>
    propName.startsWith("on")
      ? (clusterEvents[propName] = prop)
      : (clusterProps[propName] = prop)
  );

  const instance = new (L as any).MarkerClusterGroup(clusterProps);

  instance.on("spiderfied", (e: any) => {
    e.cluster._icon?.classList.add(styles.spiderfied);
  });
  instance.on("unspiderfied", (e: any) => {
    e.cluster._icon?.classList.remove(styles.spiderfied);
  });

  // This is not used at the moment, but could be used to add events to the cluster.
  // Initializing event listeners
  Object.entries(clusterEvents).forEach(([eventAsProp, callback]) => {
    const clusterEvent = `cluster${eventAsProp.substring(2).toLowerCase()}`;
    instance.on(clusterEvent, callback);
  });
  return {
    instance,
    context: {
      ...context,
      layerContainer: instance,
    },
  };
};
const updateMarkerCluster = (instance: any, props: any, prevProps: any) => {};
const LeafletMarkerCluster = createPathComponent(
  createMarkerCluster,
  updateMarkerCluster
);

const LeafletMarkerClusterWrapper: React.FC<LeafletMarkerClusterProps> = ({
  children,
  ...props
}) => {
  const markerCluster = useMemo(() => {
    return <LeafletMarkerCluster>{children}</LeafletMarkerCluster>;
  }, [children]);
  return <>{markerCluster}</>;
};

export default LeafletMarkerClusterWrapper;

Below is my function to create a marker icon from react elements:
import { divIcon } from "leaflet";
import { ReactElement } from "react";
import { renderToString } from "react-dom/server";

export const createLeafletIcon = (
  icon: ReactElement,
  size: number,
  className?: string,
  width: number = size,
  height: number = size
) => {
  return divIcon({
    html: renderToString(icon),
    iconSize: [width, height],
    iconAnchor: [width / 2, height],
    popupAnchor: [0, -height],
    className: className ? className : "",
  });
};


Maximum likelihood and Gumbel distribution. Does the likelihood have a global maximum?

Question: It appears to me that if I move the mode $u$ more to the negative and increase the scale parameter $\alpha$, one can get always a higher likelihood. If this is true, is there a limit of the likelihood?
The Gumbel likelihood is given by
$$\log(L) = \sum_{i=1}^{N}\log \left[\dfrac{1}{\alpha}\exp(-y_i - e^{-y_i}) \right]$$
where $y_i = \dfrac{x_i-u}{\alpha}$
As User Xi'an points out, there appears to be a (local) maximum somewhere. However, I'm more asking about the global maximum and whether one exists.
Answer: I will prove a more general result: if a density is log-concave, then
the log-likelihood of the corresponding location-scale family has a
global maximum. The wanted result then follows,
since the Gumbel density is log-concave.
Consider a univariate density $f^\star(y)$ which is log-concave and
smooth on the real line; the parameterized density using the location $\mu$ and the
scale $\alpha >0$ is
$$
   f(x;\,\mu,\,\alpha) := \frac{1}{\alpha} \, f^\star\left(\frac{x - \mu}{\alpha}\right).
$$
We can use the following alternative parameter vector $[\nu,\,\beta]$
with $\beta >0$
$$
  \beta := 1 / \alpha, \qquad \nu := - \mu / \alpha.
$$
 We have a one-to-one smooth transformation $[\mu,\,\alpha] \mapsto [\nu,\,\beta]$. Using the parameter vector $[\nu,\,\beta]$, the density at $x$ writes as $\beta\,f^\star(\beta x + \nu)$ and the log-likelihood for a sample $X_i$ is
$$
    \log L = \sum_{i=1}^N \log\{ \beta \, f^\star(\beta X_i + \nu) \}.
$$
It is clear that this is a concave function of the vector
$[\nu,\,\beta]$ and hence that a global maximum exists (possibly for
infinite $\nu$ or $\beta$). But this implies that a global maximum
exists as well for the location-scale parameterization
$[\mu,\,\alpha]$.
Comment: Very nice result. Well done. With your answer however, I realized the question I was asking was the wrong one, because from a practitioners perspective the result is a bit disappointing as $\alpha$ and $\mu$ still could be arbitrary large/small. The question I wanted to ask is whether there are values $\alpha$ and $\mu$ where the global max is attained. At least I know now that the Gumbel-Fit with ML has a global maximum.
Comment: Thank you. In practice you only need to find a local maximum using the new parameters: it will be the global maximum. Moreover, a workable alternative can rely on a one-dimensional optimization, see [my answer here](https://stats.stackexchange.com/a/233176/10479).
Answer: Here is the (log-)likelihood surface in $(u,\alpha)$ for a sample of 100 points from a standard Gumbel:

As you can see, the mode is located near $(0,1)$ which is the true value of the parameter. The graph was made by the following R code
<code>library(VGAM)
obs=rgumbel(1e3)
loca=seq(min(obs),max(obs),le=1e2)
scala=seq(.1*sd(obs),10*sd(obs),le=1e2)
like=matrix(0,1e2,1e2)
for (i in 1:1e2)
  for (j in 1:1e2)
   like[i,j]=sum(dgumbel(x=obs,loc=loca[i],scal=scala[j],log=TRUE))
</code>
Comment: I know that there is a at least a local maxima somewhere, but the question deals more with the case whether there is a global maxima. I'll update the question


Any way to get localized term names in node paths

Question: I have a node type "news" with an included term reference field named "newscategory". i18n-module incl. taxonomy-i18n is also installed, vocabulary is translatable and all terms are translated. But for pathauto patterns there is only the token "[node:field_newscategory]" available, which will not be localized depending on the node language.
Is there any trick on achieving this?
Answer: Okay, after 2 more hours of research and development I've finally managed to get the problem solved. I ended up writing a tiny custom module implementing hook_pathauto_alias_alter().
The module has several dependencies:
dependencies[] = taxonomy
dependencies[] = field_extract
dependencies[] = pathauto
dependencies[] = i18n
dependencies[] = i18n_string
dependencies[] = i18n_taxonomy

Here's how I did it (tailored to my special needs, so go on and modify my code)
<?php

  /**
   * Implements hook_pathauto_alias_alter()
   */
  function mymodule_pathauto_alias_alter( &$alias, array &$context ) {
    if ( $context[ 'module' ] == 'node' ) {
      $node = $context[ 'data' ][ 'node' ];
      if ( $node->type == 'news' ) {
        // determine actual context variables
        $language = $context[ 'language' ];
        $pattern = $context[ 'pattern' ];
        $category = field_extract_value( 'node', $node, 'field_newscategory' );

        // translation & preparation
        $category_translated = i18n_string_object_translate( 'taxonomy_term', $category, array( 'langcode' => $language ) );
        $sanitized = pathauto_cleanstring( $category_translated->name, array( 'langcode' => $language ) );

        // re-build the alias
        $alias = explode( '/', $alias );
        $pattern = explode( '/', $pattern );
        foreach ( $pattern AS $index => $part ) {
          if ( $part == '[node:field_newscategory]' ) {
            $alias[ $index ] = $sanitized;
            break;
          }
        }
        $alias = implode( '/', $alias );
      }
    }
  }

?>

Answer: Why don't you try Entity Token - it's part of the Entity module and provides additional tokens for use with i18n. It will make the token tree item for the term ref field expandable and you should see a token like node:field_newscategory:i18-name. This should get you going purely on the UI side.
Although I bet it rocks to be able to wrap one's own piece of code that just works :)
Comment: I would not curse *this* strong ;-) it's not been a wasted time. And after all - you just re-discovered the beauty of http://drupal.stackexchange.com ;-)


UI Router: Multiple Independent Views

Question: I feel like this is a straight forward use case for the ui-router but maybe I'm missing something...
I want to have two separate views next to each other controlled by their own menus.  When I click a ui-sref link on one menu (or $state.go for that matter), I would like to update only one of the views. Additionally, only one of the two views needs to be reflected in the url.
I tried defining a few states:
$stateProvider
.state('home', {
  url: '/',
  views: {
    'viewA': {
      template: "I'm number A!"
    },
    'viewB': {
      template: "It's good to be B."
    }
  }
})
.state('shouldOnlyChangeA', {
  'url': '',
  views: {
    'viewA': {
       template: 'Check out my new shoes!'
     }
  }
})
.state('shouldOnlyChangeB', {
  'url': '/shouldGoToNewUrl',
  views: {
    'viewB': {
       template: "This probably won't work..."
     }
  }
});

Now press $state.go('shouldOnlyChangeA') from your favorite controller and watch it change the crap out of viewB. I'd also like to omit the url definition in this state since the url should only change between the first and third states I've defined.
I have each ui-view sitting next to each other in index.html:
...

...

TL;DR
I want two sibling ui-views to be stateful all on their own; changing one shouldn't necessarily effect the other.
Hopefully I'm just missing something so I didn't bother to throw a plunker together or anything, but if it's more complicated and folks are willing to fiddle I'll whip something up.
Comment: I think that is not possible with angular-ui-router: It is based on the fact that the URL drives the state and each state corresponds to exactly one combination of views.

You could make state A a child state of the home state (".state('home.shouldOnlyChangeA', {..."), then B would still be alive when you navigate to A, but that is still not really what you asked for.
Comment: @StephenFriedrich FYI you can use UI-Router Extras for this. See answer.
Comment: Yup, seems that way: I just found a roadmap https://github.com/angular-ui/ui-router/wiki/Roadmap
where one two bullet points say
* support for independent "components" (re-usable state tree branches) with their own states that can be instantiated multiple times in the global (or a parent component) state hierarchy (See #123 and See #95)
* Orthogonal view routing. Two views who have sub-trees of their own, who's states are automatically serialized to the url. Strongly related to "components" idea above.

Found this in a discussion about future angularjs 2.0 routing.
Comment: This has been my impression as well. I can always use an `ng-include` tied to some `scope` variable for the view that doesn't require `url` updates, but since it really is a view with multiple states I was hoping there was a way.
Comment: Great! Wish I had known about UI-Router Extras earlier - now it's too late to restructure my gui to take advantage of it. Oh well, probably for the next project.
Answer: See this similar question: Independent routing for multiple regions in an AngularJS single page application

I wrote UI-Router Extras - sticky states to accomplish this use case.
View the demo
Check out the demo source code for details.
I wrote UI-Router Extras - sticky states to achieve your goal.
You'll want one named

 for each region.  Then, add sticky: true to the state definition which targets that region's named view.
See this plunk: http://plnkr.co/edit/nc5ebdDonDfxc1PjwEHp?p=preview

...
$stateProvider
.state('home', {
  url: '/'
 })
.state('shouldOnlyChangeA', {
  'url': '',
  sticky: true, // Root of independent state tree marked 'sticky'
  views: {
    'viewA@': {
       template: 'Check out my new shoes!

'
     }
  }
})
.state('shouldOnlyChangeA.substate', {
  'url': '/substate',
  template: 'Lets get some shoes!'
})
.state('shouldOnlyChangeB', {
  'url': '/shouldGoToNewUrl',
  sticky: true,  // Root of independent state tree marked 'sticky'
  views: {
    'viewB': {
       template: "This probably won't work...

"
     }
  }
})
.state('shouldOnlyChangeB.substate', {
  'url': '/substate',
  template: "Golly, it worked"
  }
);

UI Router: Multiple Independent Views


Merge groups if they contain the same value

Question: I have the following table:
+-----+----+---------+
| grp | id | sub_grp |
+-----+----+---------+
|  10 | A2 |       1 |
|  10 | B4 |       2 |
|  10 | F1 |       2 |
|  10 | B3 |       3 |
|  10 | C2 |       4 |
|  10 | A2 |       4 |
|  10 | H4 |       5 |
|  10 | K0 |       5 |
|  10 | Z3 |       5 |
|  10 | F1 |       5 |
|  10 | A1 |       5 |
|  10 | A  |       6 |
|  10 | B  |       6 |
|  10 | B  |       7 |
|  10 | C  |       7 |
|  10 | C  |       8 |
|  10 | D  |       8 |
|  20 | A  |       1 |
|  20 | B  |       1 |
|  20 | B  |       2 |
|  20 | C  |       2 |
|  20 | C  |       3 |
|  20 | D  |       3 |
+-----+----+---------+

Within every grp, my goal is to merge all the sub_grp sharing at least one id.
More than 2 sub_grp can be merged together.
The expected result should be:
+-----+----+---------+
| grp | id | sub_grp |
+-----+----+---------+
|  10 | A2 |       1 |
|  10 | B4 |       2 |
|  10 | F1 |       2 |
|  10 | B3 |       3 |
|  10 | C2 |       1 |
|  10 | A2 |       1 |
|  10 | H4 |       2 |
|  10 | K0 |       2 |
|  10 | Z3 |       2 |
|  10 | F1 |       2 |
|  10 | A1 |       2 |
|  10 | A  |       6 |
|  10 | B  |       6 |
|  10 | B  |       6 |
|  10 | C  |       6 |
|  10 | C  |       6 |
|  10 | D  |       6 |
|  20 | A  |       1 |
|  20 | B  |       1 |
|  20 | B  |       1 |
|  20 | C  |       1 |
|  20 | C  |       1 |
|  20 | D  |       1 |
+-----+----+---------+

Here is a SQL Fiddle with the test values: http://sqlfiddle.com/#!9/13666c/2
I am trying to solve this either with a stored procedure or queries.
This is an evolution from my previous problem: Merge rows containing same values
Comment: will you be able to split the values based on id like one A2 entry will be stored in one table (with A2->primary key value) and other A2 entries will be in another table (A2-> foreign key value). In this way, the context of your problem will be more clear
Comment: I am not sure if this will help, what if there is more than two entries for A2.
Comment: that won't provide a direct solution. If id column is made primary key in one and foreign key in another then that might provide a way to join these two tables and pull up the result you expect
Comment: Please clarify the merging rules. It is not clear why 10/B4 results in 2 while  20/D results in 1 (instead of 3).
Comment: To simplify, there is no rules, just put a random one (1 or 3)
Comment: Isn't this just a simple `group by`?
Comment: There has to be rules. "sharing at least one id" is a rule. Output doesn't make sense to me.
Answer: My understanding of the problem
Merge sub_grp (for a given grp) if any one of the IDs in one sub_grp match any one of the IDs in another sub_grp. A given sub_grp can be merged with only one other (the earliest in ascending order) sub_grp.
Disclaimer
This code may work. Not tested as OP did not provide DDLs and data scripts.
Solution
UPDATE final
SET sub_grp = new_sub_grp
FROM
    -- For each grp, sub_grp combination return a matching new_sub_grp
    ( SELECT a.grp, a.sub_grp, MatchGrp.sub_grp AS new_sub_grp
    FROM tbl AS a
        -- Inner join will exclude cases where there are no matching sub_grp and thus nothing to update.
        INNER JOIN
            -- Find the earliest (if more than one sub-group is a match) matching sub-group where one of the IDs matches
            ( SELECT TOP 1 grp, sub_grp
            FROM tbl AS b
            -- b.sub_grp > a.sub_grp - this will only look at the earlier sub-groups avoiding the "double linking"
            WHERE b.grp = a.grp AND b.sub_grp > a.sub_grp AND b.ID = a.ID
            ORDER BY grp, sub_grp ) AS MatchGrp ON 1 = 1
    -- Only return one record per grp, sub_grp combo
    GROUP BY grp, sub_grp, MatchGrp.sub_grp ) AS final

You can re-number sub groups afterwards as a separate update statement with the help of DENSE_RANK window function.


No results view filtering on newly added field of content type

Question: I have a content type called Parts. I just added a new boolean field called is_accessory with the default value being false. I added a filter on an existing view to show only Parts where is_accessory is false. When I run the view, no parts show up.
If I go to a Part page, select edit, then select save (without changing anything) that part will show up.
Do I need to write a hook_update_N function that loads and saves all the Part records?
Answer: You can set the views filter operation to Is not equal to and the value as true.
This should work for new entities that have the value as false and old entities where it just isn't set.


Do once-punctured torus bundles have integral traces?

Question: Recall that a hyperbolic 3-manifold $H^3/\Gamma$, $\Gamma \subset SL(2, \mathbb{C})$ discrete, is said to have integral traces if for all $\gamma \in \Gamma$, $\mathrm{tr} \gamma$ is an algebraic integer. ([1], Def. 5.2.1).
According to Bass's Theorem ([1], Thm. 5.2.2), a finite volume hyperbolic 3-manifold with non-integral trace contains a closed embedded essential surface.
According to [2], Introduction, an embedding $i: S \to M$ of a closed, orientable connected surface $S$ is called essential if $\pi_1 i: \pi_1 S \to \pi_1 M$ is injective and $(\pi_1 i)(\pi_1 S)$ cannot be conjugated into a subgroup $\pi_1 (\partial_0 M)$ of $\pi_1 M$ where $\partial_0 M$ is a component of $\partial M$.
A once-punctured torus bundle is a hyperbolic manifold which is homeomorphic to a mapping cylinder $M_\phi$ for $\phi: T^2 \setminus \{p\} \to T^2 \setminus \{p\}$ a (hyperbolic) homeomorphism of the once-punctured torus $T^2 \setminus \{p\}$.
The article [3] classifies the connected, orientable, incompressible, $\partial$-incompressible surfaces in a once-punctured torus bundle $M_\phi$ (Theorem 1.1). The only closed surface in this list is the peripheral torus $\partial M_\phi$.
Does it follow from this that once-punctured torus bundles have integral traces? The essentiality requirement from Bass's Theorem seems to exclude the peripheral torus. Wikipedia [4] states that (for proper embeddings) essentiality / algebraic incompressibility implies incompressibility. On the other hand, I do not know what to make of boundary-incompressibility and have no knowledge of the subtleties of low-dimensional geometry.
Related questions:

The same question on Mathoverflow without discussing this specific attempt of proof: https://mathoverflow.net/q/403048/129446
A discussion on the role of closedness in Bass's Theorem: Gap in Maclachlan/Reid's Proof of Bass's Theorem in Hyperbolic Geometry: Closedness?

[1] MacLachlan / Reid: The Arithmetic of Hyperbolic 3-Manifolds, section 5.2.
[2] Cooper / Long/ Reid: Essential Closed Surfaces in Bounded 3-Manifolds.
[3] Floyd / Hatcher: Incompressible Surfaces in Punctured-Torus Bundles.
[4] https://en.wikipedia.org/wiki/Incompressible_surface#Algebraically_incompressible_surfaces
Comment: I do not understand what the issue is with applying the theorem from [1]: Assume that there is a counter-example and then arrive to a contradiction using [1] and [3].
Comment: Yes, that is my hope. But can there be a closed essential surface embedded in the punctured torus bundle that is boundary-compressible? Or that is non-orientable?
Comment: And I am also unsure about switching between the manifold with torus boundary components and the (hyperbolic) interior.
Answer: It seems that Bass's Theorem cannot be used to prove that once-punctured torus bundles have integral traces:
The full version of the theorem [5] provides a "classification" of finitely generated subgroups of $GL(2, \mathbb{C})$ into four (non-exclusive) types. The types (c) and (d) imply integrality of traces. The holonomy groups of once-punctured torus bundles, however, are of type (a) (so we cannot rule out types (a) and (b) to deduce integrality of traces).
[5] Bass, Hyman: Chapter VI Finitely Generated Subgroups of Gl2. Pure and Applied Mathematics Vol. 112, 1984, pp 127-136.
Comment: What you wrote is not really relevant to the question since the general Bass' theorem is about very general subgroups (without discreteness assumptions, etc).
Comment: Cases (a) and (b) belong to HNN extensions and free products with amalgamation. From [1], Thm. 1.5.3, the existence of an incompressible embedded surface follows. So Bass's Theorem indeed only uses Bass-Serre theory for the (abstract) group structure.
Comment: @MoisheKohan (forgot to tag you)


android: requires previous sdk support even if min sdk version is higher?

Question: I am new to Android Development and I tried to import an Android Application in to my Eclipse (ADT).
But , I am getting an error saying :
 Unable to resolve target 'android-8'

But , I checked in the manifest file that , the min sdk and target sdk are set as follows:
  <uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="19" />

Then , why am I having an this error? Why do I require API 8 , even-though the application supports min sdk 11 ? The Application has Facebook and GCM integrated into it?
Is it because of this? Or , are there any classes that require API 8 support?
I am getting confused and not able to find a satisfactory answer.
Thanks.
Comment: check this link , hope it helps you http://stackoverflow.com/questions/13053353/unable-to-resolve-target-android-8
Comment: no , this link does not help me. I have a higher level APIs downloaded and all those APIs that my minSDk and target SDK have mentioned. Why is it asking me to download a lower level API ? API 8 is nowhere  in the picture of my application.
Comment: check  if u have this jar file annotations.jar in android-sdk\tools\support\annotations.jar
Comment: if not try this , copy

..\android-sdk\extras\android\support\annotations\android-support-annotations.jar
and copy it to ..\android-sdk\tools\support\
Comment: I do have Annotations.jar in the specified folder
Answer: You application has set Android 8 as target version. Change it from properties option
Right click the project and click "Properties".
Then select "Android" from  left. You can then select the target version from right side.
Always try to select the highest available target version. Currently go for Android 19 (4.4.2 Kitkat).
Answer: annotations.jar is a 2kb file try to download online if not
copy ..\android-sdk\extras\android\support\annotations\android-support-annotations.jar and copy it to ..\android-sdk\tools\support\
Comment: Does your SDK manager show that Android API level 8 is installed?
Answer: you have to open up SDK manager and simply installed API level 8.
Comment: I know that will solve the problem , my question is WHY? do I have that problem? why if my minsdk version is 11 and target version is 19 ?


How to objectively decide when the value is stable?

Question: Let's say that I've build models using three different values of some parameter (for example Max Tree Depth) in 1500 iterations. Right now, I want to decide after how many iterations the accuracy value stabilize. Visually, I could say that the accuracy stabilize at about 150-200 iteration. But, it's only my opinion. Is there any method to objectively decide when the value is stable?
Comment: A good place to start would be to have an objective definition of stability (perhaps https://en.wikipedia.org/wiki/Stability_%28probability%29), although it might be more useful looking at whether you have reached a local maximum.
Comment: I don't see anything wrong with using the graph as a heuristic decision regarding stability. There are clear changepoints in the shape.
Answer: I would see your question as "after which iteration the data points can be modeled/fitted by an equation of the form Accuracy = a (constant)?". That means starting from iteration 1 and fitting an equation of the form Accuracy = a + b*Iterations until you find that b is not statistically significantly different than 0.
To be more specific:
1) Start from iteration 1 : Get all data
2) Fit a linear model Accuracy = a + b*Iterations
3) Is b coefficient statistically different from zero? (Yes/No)
4) If no you stop, if yes start from iteration 2 (all data apart from 1st data point) and continue as above.
Does it sound reasonable? Let me know if you have any questions and I'll update my answer.


"Correct" way to send a sequence of UDP datagrams?

Question: I was under the impression that the instability of UDP is a property of the physical layer, but seems that it isn't:
I am trying to send a message over UDP, which is divided into a sequence of packets. Message identification and re-ordering is done implicitly.
I tested this method over two apps that run on the same computer, and expected it to run smoothly. However, even though the data tansfer was entirly between two programs on the same machine, there were packet losses, and quite frequent too. The losses also seem to be quite random: Sometimes the whole message got through, sometimes not.
Now, the fact the losses occur even on the same machine, makes me wonder wether I am doing it right?
Originally, I sent all the peices of the message asynchronously in a single-shot, without waiting for the completion of one peice before sending the next one.
Then, I tried to send the next peice of the message from within the completion routine of the previous one. That did improve the packet-loss ratio, but didn't prevent it altogether.
If I added a pause (Sleep(...)) between the peices, it works 100%.
EDIT:
As the answeres suggested: packets are simply sent too fast, and the OS does minimal buffering. That's logical.
So, if I would like to prevent adding acknowledgement and re-transmission into the system (I could just use TCP then), what should I do? What's the best way to improve the packet-loss ratio, without dropping the datarate to levels that could have been higher?
EDIT 2:
It occured to me that the problem might not be exactly buffer-overfill, rather than buffer-inavailablity.
I am using async WSARecvFrom to receive, which takes a buffer that as I understand, overrides the default OS buffer.
When a datagram is received, it is fed into the buffer, and the completion routine is called wether the buffer is full or not.
At that point, there is no buffer at all to handle incoming data, until WSARecvFrom is re-called from within the completion routine.
The question is if there's a way to create some sort of buffers-pool, so data could be buffered while a different buffer is being processed?
Comment: If you really need 100% garuanteed transmission then why not use TCP?
Comment: I haven't used WSARecvFrom but reading the description, the purpose is to do exactly what your question asks. You have to explicitly manage your buffer-pool. There are 2 parameters in the function call to do that.  You should not be passing in just one buffer, you should be passing in an array of pointers to buffers.  As each buffer is used remove it from the array of available buffers.
Comment: Do you send the packets to 127.0.0.1 or to your external IP address?
Comment: @avakar: localhost, aka 127.0.0.1.
Comment: re your new edit - read http://tools.ietf.org/html/rfc2309
Comment: Why do you try to use UDP if transmission guarantee is important to you? You clearly selected the wrong protocol for the job.
Comment: @Dunk: If you pass in an array of pointers to buffers, you still have a window of time during the execution of your completion routine when there aren't any outstanding I/O requests ready to receive data. Queueing up at least 2 overlapped I/O requests eliminates this window, assuming that you can process them and re-queue them fast enough.
Comment: @bk1e - There shouldn't be a need to overlap IO requests. It doesn't matter if data comes in but no one has called WSARecvFrom yet. The OS should have the data queued up and waiting for you when someone does call WSARecvFrom. If your data is bursty or you process the data slowly then the only thing your receiving task should do is read the received data and push it onto a message queue that can be processed by another application task at its leisure. In that case, your receiving task's sole job is to get data out of the receiving socket and queue it up for processing.
Answer: In your case, you're simply sending the packets too quickly for the receiving process to read them.  The O/S will only buffer a certain number of received packets before it starts discarding them.
The simplest mechanism to avoid this is to have the receiving process send back a minimal ACK packet, but for the transmitting process to carry on regardless if it hasn't received the ACK within a few milliseconds or so.
EDIT - essentially, UDP is "fire and forget".  There's no feedback mechanism built into the protocol like there is with TCP.  The only way to tune the transmission rate is for the far end to tell you that it's not receiving the whole stream.  See also RFC 2309.

Re: Packet sequences - re-ordering doesn't happen because of the physical layer, typically it's because IP networks are "packet switched" as opposed to "circuit switched".
That means that each packet may take a different route through the network, and because those different routes can have different latencies, packets may then arrive out of order.
In practise these days very few packets are lost because of physical layer errors.  Packets are lost because they're sent into a limited throughput pipe at a rate higher than that pipe can accommodate.  Buffering can help this by smoothing out the packet flow rate, but if the buffer fills up you're back to square one.
Comment: I really don't see how is this an answer to what I asked?
I wrote that re-ordering is done implicitly, and is not the issue here. Packet losses are. The question is why do they happen on a single machine "talking" to itself, and how to prevent, or at least minimize, it?
Comment: Read the answer again especially the last paragraph. The bottleneck is probably the buffering + low-level OS handling of packets, which has to be able to keep up.
Comment: @Hammer - BTW, you didn't actually ask any specific question except "am I doing it right?"
Comment: @Alnitak: You're right. Both the first comment and the edit were done before you edited your answeres, sorry. However, as I wrote, I'd like not to use ACK.
Answer: In order to avoid the problem of the OS buffers, you need to implement a rate control system. It can be closed-loop ( the receiver sends back ACKs and information about it's buffers ) or open-loop ( the sender slows itself down, which means you have to be conservative ).
There are semi-standard protocols for UDP to implement both. RBUDP ( Reliable Blast UDP ) springs to mind, and there are others.
Comment: After a moment's googling I've found a useful looking comparison [http://www.csm.ornl.gov/~dunigan/netperf/udp/UDP_RBUDP.html] ...so +1 from me :-)
Answer: If you're using UDP, the only way to detect packet loss as far as I know is going to involve some sort of feedback. If you're on a network with fairly consistent throughput, you could do a training period where you send bursts of data and wait for the receiver to respond and tell you how many packets of from the burst it received (i.e. make the receiver count and after a timeout, respond with the number it got). Then you just step up the amount of data per burst until you hit the limit and drop back down a little just to be sure.
This would avoid acks after the initial evaluation period, but will only work if the load on the network / receiving process does not change.
I've written UDP clients in Python before and the only time I've found any significant packet loss was when the input buffer on the receiving process was too small. As a result, when the system was under heavy load, you'd get packet loss because the buffer would silently overfill.
Answer: If you pass the WSA_FLAG_OVERLAPPED flag to WSASocket(), you can call WSARecvFrom() multiple times in order to queue up multiple receive I/O requests. That way there is already another buffer available to receive the next packet, even before your completion routine queues another I/O request.
This doesn't necessarily mean you won't drop packets. If your program doesn't supply enough buffers fast enough, or it takes too long to process them and re-queue them, then it won't be able to keep up, and that's when some sort of rate limiting may be helpful.
Answer: I suspect the IP layer of your machine cannot transmit as fast as you sended them.
Maybe because the protocol allows dropping of packets, when the other goal - transmitting packets as fast as possible - can otherwise not be achieved.
Different results could be explained by other traffic or cpu eating processes on your machine, did you watch with top (unix) or prcess explorer (nt) during your tests?
Answer: You have to be doing something wrong. The only way you should be losing packets is 1) An unreliable network 2) You are sending data too fast to be handled by your receiving program. 3) You are sending messages that are bigger than the UDP max message size  4) Each device in your network has a max message size (MTU), so you might be exceeding a limit there.
In case #1, since you are sending on the same machine, the network is not even involved so it should be 100% reliable.  You didn't say you had 2 network cards so I don't think this is an issue.
In case #2, you usually have to send a heck of a lot of data before you start dropping data.  From your description, that does not sound like the case.
In case #3, make sure all your messages fall below this limit.
In case #4, I'm pretty certain if you meet the UDP max message size then you should be ok, but there very well could be some older hardware or custom device with a small MTU that your data is going through.  If that is the case then those packets will be silently dropped.
I have used UDP on many applications and it has proven very reliable.  Are you using MFC for receiving the messages?  If you are, then you need to read the documentation very carefully as they clearly state some issues that you need to be aware of, but most people just gloss over them.  I've had to fix quite a few of those gloss overs when people couldn't figure out why there messaging isn't working.
EDIT: You say that your packets are implicitly reordered.  I might begin by verifying that your implicit reordering is really working correctly. That seems like the most likely candidate for your problem.
EDIT#2: Have you tried using a network monitor.  Microsoft has (or at least used to) a free program called Network Monitor that will probably help.
Answer: Looks like the OS buffering is unable to keep up with the less frequent context switches, i.e. more frequent context switches are required for the low level sends. Check if there is a way to optimise the low level send buffer size.
Comment: Hi, if you've lost access to your account you can try the account recovery, or if that doesn't work, contact the Stack Overflow team. See the [help] for details.


SQL Fill in blank data based on previous rows

Question: I have a SQL Table that is similar to the following:
ID, Date,   D1, D2, D3
1   1/1/13  0   X   A
2   1/2/13
3   1/3/13  1
4   1/4/13          B
5   1/5/13

that I need to update to the following:
ID, Date,   D1, D2, D3
1   1/1/13  0   X   A
2   1/2/13  0   X   A
3   1/3/13  1   X   A
4   1/4/13  1   X   B
5   1/5/13  1   X   B

Basically filling in all the nulls with the value before it. This is only going to be performed once. Would a loop be the best option? Or is there something that would be more effective?
Comment: What rdbms are you using?
Comment: Are you defining previous as "With the next lowest `ID` value"? Or "With the next lowest `Date` value"? Or do you have some other definition you want to use? Tables are inherently unordered. If you're wanting to do something that involves order, you have to give us an explicit rule to define that order.
Answer: Presuming that you're using SQL-Server you can use this common-table-expression:
WITH cte
     AS (SELECT T1.id,
                T1.date,
                d1 = COALESCE(T1.d1, (SELECT TOP 1 d1
                                      FROM   dbo.tablename T2
                                      WHERE  T2.id < T1.id
                                             AND d1 IS NOT NULL
                                      ORDER  BY id DESC)),
                d2 = COALESCE(T1.d2, (SELECT TOP 1 d2
                                      FROM   dbo.tablename T2
                                      WHERE  T2.id < T1.id
                                             AND d2 IS NOT NULL
                                      ORDER  BY id DESC)),
                d3 = COALESCE(T1.d3, (SELECT TOP 1 d3
                                      FROM   dbo.tablename T2
                                      WHERE  T2.id < T1.id
                                             AND d3 IS NOT NULL
                                      ORDER  BY id DESC))
         FROM   dbo.tablename T1)
UPDATE T
SET    T.d1 = C.d1,
       T.d2 = C.d2,
       T.d3 = C.d3
FROM   dbo.tablename T
       INNER JOIN cte C
               ON T.id = C.id
WHERE  T.d1 IS NULL
        OR T.d2 IS NULL
        OR T.d3 IS NULL

DEMO
Edit Since you have mentioned in the comments that you have '' instead of null, here is a modified version that supports both:
WITH cte AS
        (SELECT T1.id,
                T1.date,
                d1 = CASE WHEN COALESCE(T1.d1, '') <> '' THEN d1
                       ELSE(SELECT TOP 1 d1
                            FROM   dbo.tablename T2
                            WHERE  T2.id < T1.id
                                   AND COALESCE(T2.d1, '') <> ''
                            ORDER  BY T2.id DESC) END,
                d2 = CASE WHEN COALESCE(T1.d2, '') <> '' THEN d2
                       ELSE(SELECT TOP 1 d2
                            FROM   dbo.tablename T2
                            WHERE  T2.id < T1.id
                                   AND COALESCE(T2.d2, '') <> ''
                            ORDER  BY T2.id DESC) END,
                d3 = CASE WHEN COALESCE(T1.d3, '') <> '' THEN d3
                       ELSE(SELECT TOP 1 d3
                            FROM   dbo.tablename T2
                            WHERE  T2.id < T1.id
                                   AND COALESCE(T2.d3, '') <> ''
                            ORDER  BY T2.id DESC) END
         FROM   dbo.tablename T1)
UPDATE T
SET    T.d1 = C.d1,
       T.d2 = C.d2,
       T.d3 = C.d3
FROM   dbo.tablename T
       INNER JOIN cte C
               ON T.id = C.id
WHERE  COALESCE(T.d1, '') = ''
        OR COALESCE(T.d2, '') = ''
        OR COALESCE(T.d3, '') = ''

DEMO
Comment: Out of curiosity, why `T2.id <= T1.id - 1` rather than `T2.id < T1.id`?
Comment: @Damien_The_Unbeliever: Yes, that was a leftover from my first version which didn't use `<=` but `=` and also didn't have the `WHERE` + `ORDER BY`. (Edited)
Comment: Works, except my nvarchar columns are actually '' and not null. Is there any way to modify this to work for that? I could run an update script before this to change the ''s to actual NULLS I suppose.
Comment: @Shawn: you have mentioned nulls in your question. However, in general it is better to use null if a value is undefined. Im on the road now, so I cannot show you a different way.
Comment: @Tim Schmelter Agreed, I didn't realize they were empty strings until this point. I'll try to work on it.
Comment: Just ran a quick update statement to change the ''s to nulls before running an expanded version of this. Works great, thanks.
Comment: @Shawn: Wait a minute and i'll show you an approach that works with `''` **and** `nulls`. (... done)
Comment: @Tim Thanks, I appreciate your thoroughness.
Answer: Assuming we're using the ID column to determine order, you can do it without loops.
Whether you want to do this is another matter - it doesn't look pretty:
declare @t table (ID int, Date date,   D1 int, D2 char(1), D3 char(1))
insert into @t(ID, Date,   D1, D2, D3) values
(1,'20130101',0,'X','A'),
(2,'20130201',null,null,null),
(3,'20130301',1,null,null),
(4,'20130401',null,null,'B'),
(5,'20130501',null,null,null)

update a
set
    a.D1 = COALESCE(a.D1,d1.D1),
    a.D2 = COALESCE(a.D2,d2.D2),
    a.D3 = COALESCE(a.D3,d3.D3)
from
    @t a
        left join
    @t D1
        on
            D1.ID < a.ID and
            D1.D1 IS NOT NULL
        left join
    @t D1_anti
        on
            D1_anti.ID  D1.ID
        left join
    @t D2
        on
            D2.ID < a.ID and
            D2.D2 IS NOT NULL
        left join
    @t D2_anti
        on
            D2_anti.ID  D2.ID
        left join
    @t D3
        on
            D3.ID < a.ID and
            D3.D3 IS NOT NULL
        left join
    @t D3_anti
        on
            D3_anti.ID  D3.ID
where
    D1_anti.ID is null and
    D2_anti.ID is null and
    D3_anti.ID is null

select * from @t

Basically, we perform joins to try to find earlier rows which may be applicable, and then perform the _anti joins to make sure that each found earlier row is the latest such row that exists.


Missing piano sounds

Question: My daughter practices at home on digital piano casio cdp-230r. She has to learn from page 38:  Op.849 (Czerny, Carl). Her problem is that she thinks that the piano "is missing some sounds" for a part of notes

Question: is it possible that the piano is not good or should we make some configurations?
Comment: Sounds like she might be noticing the quality difference between the school and home pianos. You might look at saving up for a better piano, involve her in the selection process, make it a gift to her for a holiday or birthday, and/or engage with her on having a job or doing chores to raise money for a better piano. It might help you to have a conversation with her and her piano teacher about her complaint and what can be done about it. The teacher should be able to "translate" the musical concepts for you.
Comment: It's probably in 2b, and is a simple chromatic run up from C>C initially. Every single white and black key, sequentially, an octave  higher than it looks like on the stave (8va). What exactly is she missing?
Comment: She says that she does not finds those sounds on digital piano - they do not sount at all like classic piani. At school it has classic piano, and those notes do not sound like home (using the same keys). Sorry but I have no experience with piano or music
Comment: Do you know what kind of piano you have at home, make and model? Do you know if you can change the sounds on the piano?
Comment: Piano Casio CDP-230R
Answer: According to https://www.casio-intl.com/asia/en/emi/products/cdp230r/spec/ the unit has 48 notes maximum polyphony which I can only assume applies to both the keyboard buttons and the sound engine inside. So all the notes should sound. (Some very low end keyboards might only be able to play one or two or three notes at the same time. Yours can do much better so that shouldn't be the problem here.)
Does the PIANO/ORGAN button toggle to a better sound? There are many more piano sound options available through the TONE button as well. They are listed in the "Appendix" PDF available https://support.casio.com/en/manual/manualfile.php?cid=008006005 if you no longer have the manual.
Your keyboard you have does a have many other settings that could be affecting the sound. If your daughter can explain a little more what is wrong with the sound she hears, that might help us troubleshoot better.
Comment: She complains that, "a specific block of notes" in the right side of the piano are "too high" comparing with the classic piano
Comment: @user237329 - That sounds like a broken digital piano to me.
Comment: @user237329 Okay, thanks. Does pressing the "Split" button fix it by any chance?

Missing piano sounds


mysql_fetch_array() não mostra todos os registros

Question: Olá, eu estou com problemas, em minha tabela da base de dados tenho 3 registros, uso o código abaixo para buscá-los:
public function buscarMateriaProva($codigoProva){
    $query  = " SELECT  codigoMateria, codigoProva, quantidadeQuestao
                FROM    materiasProvas
                WHERE   codigoProva = ".$codigoProva;

    //se for executado
    if($res = mysql_query($query)){
        $row    = mysql_fetch_row($res);
        $nr     = (int)mysql_num_rows($res);

        #se houver registro povoa o obj, senão retorna falso
        if($nr === 0){
            return false;
        } else {
            return $res;
        }

    } else {
        return false;
    }
}

Neste caso, o $nr tem valor 3, pois são 3 registros, até ai tudo bem.
O valor retorna para o meu arquivo onde monto a estrutura utilizando mysql_fetch_array():
$resMateriaProva = $materiaProva->buscarMateriaProva($codigo);
while($arrayMateriaProva = mysql_fetch_array($resMateriaProva)){
    print_r($arrayMateriaProva);
}

Ele retorna os 3 registros, normal, mas só exibe os 2 últimos, ignorando o primeiro registro.
Alguém sabe qual o erro?
Desde já, obrigado!
Comment: Mysql é suscetível a invasões, porque você não atualiza para pdo ou mysqli?
Answer: Porque você não substitui o mysql_fetch_array por mysql_fetch_row.
ficaria assim:
while($arrayMateriaProva = mysql_fetch_array($resMateriaProva)){
print_r($arrayMateriaProva);
}

e você não precisa desta linha
$row    = mysql_fetch_row($res);

Pelo visto você não está utilizando a variável, e bem provável que seja ela que esta removendo o primeiro resultado. Tenta comentar ela e testa, se der certo nem precisa trocar o mysql_fetch_array. Isso porque o mysql_fetch_row pega uma linha por vez, e ao utiliza-lo você já remove o primeiro resultado e retorna o resto da consulta. Como você não utiliza a variável $row você não percebe que recebeu o primeiro resultado. Espero ter sido claro.
Comment: Valeu, funcionou, obrigado pela ajuda!
Comment: Que bom que pude ajudar, foi um prazer. Mas trago outra sugestão, da uma olhadinha em PDO, ele facilita muito na parte de gerenciamento com o banco de dados e já trata os parâmetros.


Aggregate uploaded files for simplified download

Question: I have a content type that users are uploading a lot of files into, and the client would like to be able to download all of the attached files with a single click. It seems that a server-side compression of all the files would be a good solution, something like Stephen.Colson is trying to do here stephen.colson's sandbox.
I haven't found anything appropriate, though. Is anyone aware of a good solution for aggregating file downloads?
Answer: Take a look at the pclzip suite of modules ZipCart.
Comment: PCLZip is an excellent suggestion and pretty much what I needed. It was not, however, that straightforward, as the instructions are a bit lacking. For anyone following in my footsteps, here are some good things to know:
Comment: 1. This is actually a cluster of modules and you'll need at least one of these others to make it work:

 * [pclzip_zipfolder](http://drupal.org/project/pclzip_zipfolder)
 * [pclzip_zip_node_files](http://drupal.org/project/pclzip_zip_node_files)
 * [pclzip_zip_content_files](http://drupal.org/project/pclzip_zip_content_files)

2. I used the `pclzip_zip_node_files` and it adds a get_zip part to the URL, so to download all of the files, you need the `baseurl.com/node/nid/get_zip`


General solution to a Growth equation

Question: I'd like to compute a formula that describes a population growth. The population starts with $N(t=0)$ individuals. At each time step there are births and deaths. The number of births at time $t$ is given by $N(t-1)f$, where $f$ being the fecundity. The number of deaths is given by $N(t-ls)$, where $ls$ being the lifespan. Therefore the recursive equation is:
$$
N(t)=N(t-1)+N(t-1) f-N(t-ls)
$$
which also equals:
$$
N(t)=N(t-1) (f+1)-N(t-ls)
$$
What is the general solution? I mean an equation that gives the value $N(t)$ in function  of $ls$, $f$ and $N(0)$ only.
Step-by-step solution is more than welcome.
UPDATE:
$ls$ and $t$ are integers.
Comment: Some methods from [this wiki article](http://en.wikipedia.org/wiki/Recurrence_relation) might be useful for you.
Comment: Are $t$ and $ls$ integers?
Comment: @TZakrevskiy Thanks.
Comment: @AviSteiner. Yes they are.
Comment: This is very closely related to a differential equation, so I'd consider (if the growth is not exponential) the term $N(t)$ as substituted by $\mathrm{d}N/\mathrm{d}t$. The only reason I won't post this as an answer is that I'm not sure if it is the shortest way to obtain a correct $N(t)$.
Answer: In principle, this is a simple constant-coefficient difference equation.  The problem is that $ls$ can be any positive integer, and this makes the equation difficult to solve specifically.  To wit, assume that the solution $N(t) = A r^t$, where $A$ is some constant and $r$ a growth rate.  Then we may find $r$:
$$r^t-(f+1) r^{t-1} +r^{t-ls}=0$$
or
$$r^{ls}-(f+1) r^{ls-1}+1=0$$
In general, this equation may be solved numerically for $r$, and produces $ls$ distinct values of $r$ i.e., $r_1, r_2, \ldots r_{ls}$.  Then the solution is
$$N(t) = \sum_{k=1}^{ls} A_k r_k^t$$
where the $A_k$ are found from, e.g., initial conditions.
Answer: Since your equation is a recurrence relation of order $ls$ (unless $ls=0$, in which case it's of order $0$, but I'll assume that that's not the case), the general solution is going to have $ls$ arbitrary constants (including $N_0$, but not including $f$). I kind of doubt you'll be able to get a "nice", explicit solution, but what I can get you is a "nice" ordinary generating function.
To make notation easier, I'll write $n$ instead of $t$, $N_n$ instead of $N(t)$, $r$ instead of $f+1$, and $a$ instead of $ls$. Then the recurrence relation is
$$N_n-rN_{n-1}-N_{n-a}=0.$$
Define $F(x):=\sum_{n=0}^\infty N_nx^n$ to be our ordinary generating function for $N_n$. Multiplying everything in the above equation by $x^n$ and summing from $n=a$ to $\infty$, we get
$$\begin{aligned}
0 &=\sum_{n=a}^\infty N_nx^n - r\sum_{n=a}^\infty N_{n-1}x^n + \sum_{n=a}^\infty N_{n-a}x^n\\
&= F(x)-(N_0+N_1x+\cdots + N_{a-1}x^{a-1})\\
&\quad{}-rx(F(x)-(N_0+N_1x+\cdots + N_{a-1}x^{a-2}))\\
&\quad{}+x^aF(x)\\
&= (1-rx+x^a)F(x) -(N_0+c_1x+c_2x^2+\cdots+c_{a-1}x^{a-1}),
\end{aligned}$$
where $c_1,\cdots,c_{a-1}$ are arbitrary constants. Then
$$ F(x)=\frac{N_0+c_1x+c_2x^2+\cdots+c_{a-1}x^{a-1}}{1-rx+x^a}.$$
Returning to the original notation, we get
$$ \sum_{t=0}^\infty N(t)\,x^t = \frac{N(0)+c_1x+c_2x^2+\cdots+c_{ls-1}x^{ls-1}}{1-(f+1)x+x^{ls}}.$$
Answer: Generating functions are your friend.
I will show how to get your generating function
from the recurrence.
I changed your notation a little.
You have
$n(t) = a n(t-1)-n(t-m)$,
or
$n(t+m) = a n(t+m-1)-n(t)$
.
Let
$f(x)
=\sum_{t=0}^\infty n(t) x^t
$.
$x^m f(x)
=\sum_{t=0}^\infty n(t) x^{t+m}
=\sum_{t=m}^\infty n(t-m) x^{t}
$
and
$x f(x)
=\sum_{t=0}^\infty n(t) x^{t+1}
=\sum_{t=1}^\infty n(t-1) x^{t}
$,
so
$\begin{align}
f(x)-ax f(x)+x^m f(x)
&=\sum_{t=0}^\infty n(t) x^t
-a\sum_{t=1}^\infty n(t-1) x^{t}
+\sum_{t=m}^\infty n(t-m) x^{t}\\
&=\sum_{t=0}^{m-1} n(t) x^t
-a\sum_{t=1}^{m-1} n(t-1) x^{t}
+\sum_{t=m}^\infty (n(t)-an(t-1)+n(t-m)) x^{t}\\
&=\sum_{t=0}^{m-1} n(t) x^t
-a\sum_{t=1}^{m-1} n(t-1) x^{t}\\
&= g(t)\\
\end{align}
$
where
$g(t)
=\sum_{nt0}^{m-1} n(t) x^t-a\sum_{t=1}^{m-1} n(t-1) x^{t}
=n(0)+\sum_{t=1}^{m-1} (n(t)-an(t-1)) x^t
$
is a polynomial of
degree $m-1$ that incorporates the
initial conditions of the $n(i)$.
Therefore
$f(x)
=\dfrac{g(x)}{h(x)}
$
where
$h(x) = 1-ax+x^m$.
The properties of the $n(i)$
thus depend on the initial conditions
(incorporated in $g(x)$)
and the roots of
$h(x)$.
In particular,
if $h(x)$ has no real roots,
the $n(i)$ will oscillate.
If $h(x)$ has positive real roots,
the $n(i)$
will grow
(unless there are special initial conditions)
like
$c/r^i$,
where $r$ is the root of $h$
of smallest value.
I will now try to determine what I can
about the roots of $h$.
I will assume that $a > 0$.
$h(0) = 1$.
Since $h'(x)
=-a+mx^{m-1}
$,
$h'(x)=0$
for
$x=x_0
=(a/m)^{1/(m-1)}
$,
so
$h'(x) < 0$
for
$0 \le x < x_0$
and
$h'(x) > 0$
for
$x > x_0$.
Therefore $h$ has a minimum at $x_0$.
To see if $h$ has any real root,
we need to see if
$h(x_0) < 0$.
If not,
$h$ has no real roots.
$\begin{align}
h(x_0)
&=1-ax_0+x_0^m\\
&=1-x_0(a-x_0^{m-1})\\
&=1-x_0(a-a/m)\\
&=1-(a/m)^{1/(m-1)}a(1-1/m)\\
&=1-(a/m)^{1+1/(m-1)}(m-1)\\
&=1-(a/m)^{m/(m-1)}(m-1)\\
\end{align}
$.
Therefore
$h(x_0) < 0$
if
$(a/m)^{m/(m-1)}(m-1) > 1$
or
$a > m/(m-1)^{(m-1)/m}$.
Therefore,
for any $m$,
if $a$ is large enough,
the $n(i)$
will grow exponentially.
Note that if $a = m/(m-1)^{(m-1)/m}$,
$h$ has a double root at $x_0$,
and the $n(i)$ will grow differently.
I'll take this a little further and leave it at that.
Let's see what happens for moderately large $m$.
$m/(m-1)^{(m-1)/m}
=\dfrac{m}{m-1}(m-1)^{1/m}
$.
$(m-1)^{1/m}
=e^{\ln(m-1)/m}
\approx 1+\ln(m-1)/m
$
and
$\dfrac{m}{m-1}
=\dfrac{1}{1-1/m}
\approx 1+1/m
$,
so
$m/(m-1)^{(m-1)/m}
\approx (1+\ln(m-1)/m)(1+1/m)
\approx 1+(1+\ln(m-1))/m
$.
Therefore
$a$ does not have to be
too large
for $h$ to have real roots.
That's enough for now.

General solution to a Growth equation


SQL Server : cannot resolve collation conflict for equal to operation

Question: In SQL Server 2012 I have this query:
select *
from InquiryLog i
left join Employee e on i.QueriedByEmployeeName = (e.Firstname + ' ' + e.LastName)

but I get this error

Cannot resolve collation conflict for equal to operation.

How do I fix this?
Thanks
Comment: The types really need to be the same or that query is going to be really inefficient... everything should be varchar or everything should be nvarchar (and preferably the same maximum lengths as well). You can see what the collations are if you SELECT * FROM INFROMATION_SCHEMA.COLUMNS WHERE TABLE_NAME IN (N'InquiryLog', N'Employee') … the collation will be listed in the results for each column in those two tables. Or you could choose DATABASE_DEFAULT as your collation (the one SQL Server was installed with).
Comment: You solve it using the `COLLATE` keyword.  Learn about it here: https://learn.microsoft.com/en-us/sql/t-sql/statements/collations?view=sql-server-2017.
Comment: You can just add a COLLATE [YourCollationHere] to one of the columns. This happens when you are trying to join on two columns and the collation of those columns is incompatible. You have to help it know how to resolve the collation.
Comment: what do I COLLATE  it to?
Comment: both are text columns
Comment: Actually there are three columns there. And hopefully you aren't using the text datatype and you said text but the real datatype is varchar.
Comment: no its like nvarchar and varchar
Answer: Using your query as an example you need to use the COLLATE keyword. Not sure what collations you have but something close to this should work for you.
select *
from InquiryLog i
left join Employee e on i.QueriedByEmployeeName = (e.Firstname + ' ' + e.LastName) COLLATE SQL_Latin1_General_CP1_CI_AS

Comment: either that or you can simply say COLLATE DATABASE_DEFAULT and it should work
Comment: @Harry true. Ideally the columns in a join would use the same collation and datatype (in this case the OP stated that one is nvarchar and the other is varchar).


Double free or corruption (!prev) Aborted (core dumped) Error in C language

Question: int get_rates(Date start_at, Date end_at,unsigned n_currencies, char *currencies[], Rate *result){
    char link[1024];
    char * simbolos=envirgular(currencies,n_currencies);
    char * linkp=link;
    snprintf(link, sizeof(link),  "https://api.exchangeratesapi.io/history?start_at=%d-%d-%d&end_at=%d-%d-%d&symbols=%s"
    ,start_at.year,start_at.month,start_at.day,end_at.year,end_at.month,end_at.day,simbolos);
    start_at.day++;
    size_t datasize;
    char *a=http_get_data(linkp,&datasize);
    int numerodedias=getnumberofdays(a);
    result=realloc(result,numerodedias*sizeof(Rate));
    Date datas[numerodedias];
    char * info=strstr(a,"rates");
    char * data=malloc(10*sizeof(char));
    char * year=malloc(4*sizeof(char));
    char * day_month=malloc(2*sizeof(char));
    char * value=malloc(6*sizeof(char));
    for(int j=0;j<numerodedias;j++){
        result[j].values=calloc(n_currencies,sizeof(char*));
        result[j].names=calloc(n_currencies,sizeof(char*));
        info=strstr(info,"-");
        info=info-4;
        strncpy(data,info,10);
        strncpy(year,data,4);
        datas[j].year=atoi(year);
        data=data+5;
        strncpy(day_month,data,2);
        datas[j].month=atoi(day_month);
        data=data+3;
        strncpy(day_month,data,2);
        datas[j].day=atoi(day_month);
        for(int i=0;i<n_currencies;i++){
            info=strstr(info,currencies[i]);
            info=info+5;
            strncpy(value,info,6);
            result[j].values[i]=value;
            result[j].names[i]=currencies[i];

    }
    for(int i=0;i<2;i++){
    printf("\nValor%s\nMoeda%s\n",result[j].names[i],result[j].values[i]);}
    result[j].data.day=datas[j].day;
    result[j].data.month=datas[j].month;
    result[j].data.year=datas[j].year;
    //printf("\nDia:%d-%d-%d   %s=%s    %s=%s\n",result[j].data.day,result[j].data.month,result[j].data.year,result[j].names[0],result[j].values[0],result[j].names[1],result[j].values[1]);
        }

    return 0;
}

typedef struct Data{
    int year;
    int month;
    int day;

}Date;

typedef struct SingleRate{
    Date  data;
    char **names;
    char **values;
}Rate;

Hello Stack Overflow community,I'm learning C language in my class and i was asked to make this little project that searches in a website using libcurl for some info about certain currencies and values in a determined day.
I got to a point that i can continue due to this error,i've been searching on the internet for answers of the same error but i didnt seem to find where it was
Would be glad if someone could explain to me what im doing wrong
Thanks.
Comment: I don't see any calls to `free` or `realloc`. Or any direct buffer overflows (but that's hard to see with that wall of code). Please try to create a [**Minimal**, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve) to show us.
Comment: Also, please [learn how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). And that will be much simpler with simpler code. Try to scale back and remove as much as you possible can. Test it. Then add a ***small*** piece of code, test it. Add another *small* piece of code. Test it. And so on. That will help finding problems and debugging considerable.
Comment: Also I can see trough some printf's that the problem seems to be with the values array
Comment: Please make a [mcve] out of it.
Comment: Ok i will try to,thank you :)
Comment: @Someprogrammerdude There is `realloc`, but not `free`.
Comment: After using `strncpy` you must make sure that the target array is teminated with a `'\0'` to make it a proper string.
Comment: @EugeneSh. Ah yes there was. And that's probably the problem here: Joao, you pass the `result` pointer ***by value***, meaning the local variable `result` is a ***copy***. Assigning to `result` will modify this local copy, and *only* this local copy. The original pointer you used when calling the function will *not* be changed by that assignment.
Comment: If _valgrind_ available in your OS use it to detect your illegal accesses and more
Comment: Why are you allocating `data,year,day_month` and _values_ ? That seems useless, just use array in stack
Comment: And there are so many other problems and flaws in your code that it would take a very long answer to list them all. To begin with you have memory leaks, you should never assign back to the pointer you pass to `realloc`, there's no null-pointer checking or error handling of any kind, or possibilities of having unterminated strings, just to list a few issues. And that's besides the one problem that was the probable cause for your crash. A *lot* of possibilities for [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior).
Comment: Lastly, the *only* good thing that I see in your code, is the use of `snprintf` to format the string in `link`.
Comment: @Someprogrammerdude I used malloc to allocate my result pointer in main and i did used realloc to update the result outside this fuction
Comment: @WeatherVane I went on debug mode to check if all the strings were fine
Comment: @JoaoBarata Please read my comment about passing `result` by value again. The result of that `realloc` is assigned to the ***local*** variable `result`. You never pass that back to the calling function. Do some research about *emulating pass by reference in C* to learn how to do it.
Comment: @JoaoBarata In short: After calling the function you show, the pointer you pass for `result` is no longer valid. You can't use it for anything at all.
Comment: @Someprogrammerdude I cant use the result to put thing's to have acess outside this function? But it seemed to work on the debbuger as i exit this function
Comment: As I said, that pointer used in the call is lost. Or rather, it will still point to the *old* memory. When you try to use it in `realloc` again, or in `free`, then you will get the crash you ask about.
Answer: Warning :
char * year=malloc(4*sizeof(char));
...
strncpy(year,data,4);
datas[j].year=atoi(year);

year has no place for the ending null character and it is missing in that case, atoi has an undefined behavior
Same for day_month
char * day_month=malloc(2*sizeof(char));
...
strncpy(day_month,data,2);
datas[j].month=atoi(day_month);

Other probable problem when :
        result[j].values[i]=value;

you always copy the same char * in a loop, if you suppose you will have different values this is false. There is a risk it has no ending null character because set through strncpy. May be also you will free it later (char * value=malloc(6*sizeof(char));). So, you probably have to strdup it but warning with the missing null char
Comment: Well that really depends on the length of the string in `data`. If it's only three respective one character then it's okay. But that's probably not the case.
Comment: @Someprogrammerdude yes not the case here year on 4 chars and risk for 2 chars for the day from the 10
Comment: @bruno in that line result[j].values[i]=value;  that you mention  i did in fact wanted different values,what can i do to correct that problem??
Comment: @JoaoBarata as I said you need to _strdup_, but again warning with the perhaps missing null char
Comment: @bruno yeah that worked wonders,thank you ^^
Now I need to find that double free or corruption and core dumped
Comment: @JoaoBarata Did you also correct my other remarks ? Can you use _valgrind_ ? This is a fantastic tool, you do not need to make a special compiling, just compile in debug mode to have the debug info, and rather than to do `progname arg1 ... argn` just do `valgrind progname arg1 ... argn`
Comment: @bruno I probably cant as im using a virtual machine of linux and i'm correcting your other remarks rn because as soon as i delete the line:strncpy(data,info,10);
the errors seem to vanish xD
Comment: @JoaoBarata if you are under a Linux even virtualized you can use _valgrind_


For $D\subset R \rightarrow R$, $f$ is log concave iff $f''f\leq (f')^2$ for all $x\in D$

Question: So I know that a function $f: D\subset R^n \rightarrow R$ is called log-concave if $f(x)>0$ for all $x\in D$ and $log f$ is concave.
I'm stuck on showing that for $D\subset R \rightarrow R$, $f$ is log concave iff $f''f\leq (f')^2$ for all $x\in D$.
Comment: Take the 2nd derivative of $\log f$.
Answer: $\log f$ is concave iff $(\log f)''\le0$ with
$$
(\log f)'' = \frac d{dx} \frac f{f'} = 1 - \frac {ff''}{(f')^2}
$$


Identifying C syntax

Question: So I was studying some tutorial code for a BLE implementation, and I came across this syntax which I have never seen before.
<code>&p_ble_evt->evt.gatts_evt.params.write;
</code>
It is the &foobar-&baz part i'm unsure of.
I tried 'googleing' the code part, then tried running it through https://cdecl.org/.
But without getting an understanding for what this code does/is.
<code>/**@brief Function for handling the Write event.
 *
 * @param[in]   p_midi_service   LED Button Service structure.
 * @param[in]   p_ble_evt        Event received from the BLE stack.
 */
static void on_write(ble_midi_service_t * p_midi_service, ble_evt_t const * p_ble_evt)
{
    ble_gatts_evt_write_t * p_evt_write = (ble_gatts_evt_write_t *) &p_ble_evt->evt.gatts_evt.params.write;

    if ((p_evt_write->handle == p_midi_service->data_io_char_handles.value_handle) &&
        (p_evt_write->len == 1) &&
        (p_midi_service->evt_handler != NULL))
    {
      // Handle what happens on a write event to the characteristic value
    }

    // Check if the Custom value CCCD is written to and that the value is the appropriate length, i.e 2 bytes.
    if ((p_evt_write->handle == p_midi_service->data_io_char_handles.cccd_handle)
        && (p_evt_write->len == 2)
       )
    {
        // CCCD written, call application event handler
        if (p_midi_service->evt_handler != NULL)
        {
            ble_midi_evt_t evt;

            if (ble_srv_is_notification_enabled(p_evt_write->data))
            {
                evt.evt_type = BLE_DATA_IO_EVT_NOTIFICATION_ENABLED;
            }
            else
            {
                evt.evt_type = BLE_DATA_IO_EVT_NOTIFICATION_DISABLED;
            }

            p_midi_service->evt_handler(p_midi_service, &evt);
        }
    }
}

</code>
So if some kind soul would help enlighten me that would  be much appreciated.
Thank you.
Comment: Doesn't speak very well for the tutorial if they haven't ever tried following it themselves to see that the code copypasted from it doesn't work, since it has that HTML escape fail… You need to replace `&` with `&` and `>` with `>`.
Comment: Thanks @Arkku, my knowledge of HTML just increase ever so slightly :)
Answer: Looks like xml/html escape sequences, should read:
<code>&p_ble_evt->evt.gatts_evt.params.write;
</code>
Comment: That makes a lot of sense - Thanks for the help Alan. I was super confused because I do know my basic C syntax, so I thought it was some very memory optimized code in a weird way I have never seen before. but the end line statements in the middle made it all crumble
Comment: @Sorenp: at least you didn't have to deal with [trigraphs](https://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C).

Identifying C syntax


Check if Int `mod` every element of a list == 0

Question: I'm writing a (Literate) Haskell code that bruteforces the lcm (least common multiple) of a list of Ints.
I already thought about a strategy, but I'm not that good with Haskell syntax and don't know a lot of functions.
This is the function so far:
> bruteforceLCM :: [Int] -> Int -> Int
> bruteforceLCM xs n = if EVERYELEMENTOFTHELIST `mod` n == 0
>                        then n
>                        else (bruteforceLCM xs (n+1))

Where xs is the list of all Ints and n is the current Int that gets checked for being the lcm.
The first call would be bruteforceLCM xs 2, because n=0 would be not divisible and n=1 would always return true, these cases are solved with pattern matching earlier.
What would I have to replace "EVERYELEMENTOFTHELIST" with to achieve my goal?
Greeting, Joe
EDIT: Here is the whole code now, thanks to dfeuer!
> bruteforceKGV :: [Int] -> Int -> Int
> bruteforceKGV xs n = if all p xs then n else (bruteforceKGV xs (n+1))
>   where p x = n `mod` x == 0

Comment: It does what? Where does this `n` come from?
Comment: Added an explanation for both arguments, thanks for pointing out I forgot that.
Answer: Can you write down a function f :: Int -> Bool that checks if an Int is 0 modulo n? I'll leave this first step to you.
So now you have a function f :: Int -> Bool and a list of Ints, and you want to see if f x is True for every x in the list. We ask Hoogle, and it tells us about all. You'll use f as the first argument of all to do what you want.
Comment: To check if an Int modulo another Int (since both vary) would require me to give in both Ints as an input, which would make it `f :: Int -> Int -> Bool`. Can I handle that with `all`?
Comment: Sure. For ease of notation, let's say that the thing you mod by is the first argument to `f :: Int -> Int -> Bool`, i.e. that `f n m` checks if `m` is zero modulo `n` (however unpleasant that may be to read). Partial application means that `f n` is a new function with signature `Int -> Bool`. This is the function that checks if its (single!) argument is zero modulo n, and it (i.e. `f n`) is precisely the function you pass to `all`.
Comment: Trying to do that gives me a "not in scope" for m, which was kinda what I expected since I'm telling f to know n but not m while using both in `f n = m 'mod' n == 0`, how can I bypass that? Signature is `f :: Int -> Bool` now. I'M sorry for these basic questions, but I really don't understand where `all` would take the other Int from and how `f` could work alone.
Answer: You're starting out with
bruteforceLCM :: [Int] -> Int -> Int
bruteforceLCM xs n = if EVERYELEMENTOFTHELIST `mod` n == 0
                       then n
                       else (bruteforceLCM xs (n+1))

When you say EVERYELEMENTOFTHELIST `mod` n == 0, what you really mean is "For each element, x, of xs, x `mod` n == 0".
Let's write a predicate expressing what that says about an element of the list:
p x = x `mod` n == 0

Now we can use all, which takes our predicate and tells us if it's true for all elements of the list.
But now we might want to clean things up a bit at a higher level. Because Haskell is lazy, we don't need to be so explicit about the recursion. We can do something like this instead:
bfLCM xs = fromJust $ find SOMETHING [2..]

Unfortunately, running this leads to a lot of infinite loops, because your math actually turns out to be a little bit wrong. Can you figure out where your mistake is?
Comment: Shouldn't `p x = x `mod` n == 0` also give a "not in scope" error for n? And I'm sorry, but as a complete beginner I am having trouble with your last line of code. The $ is a dividing symbol between arguments that are meant to be in different brackets, right? Is this equivalent to `bfLCM xs = fromJust (find SOMETHING [2..])`? And if so, where do you specify if a number fits the scheme (in this case being a mod 0 of x)?
Comment: @JoeCocker, ``p x = x `mod` n == 0`` will give a "not in scope" error for `n`, yes, *unless* you put that definition in a place where `n` is in scope, using a `let` expression or a `where` clause. `$` is the function application operator, so `fromJust $ find SOMETHING [2..]` does indeed mean `fromJust (find SOMETHING [2..])`.
Comment: By the way, you can type backticks in inline code by using *double* backticks to surround that code.
Comment: Yeah I actually knew you could use backticks here to escape some characters, I just did not see I produced an imcomplete code in my last comment and time ran out to fix it. Anyway, I implemented the code using `if all p xs` and ``where p x = x `mod` n == 0`` and I ran into your predicted infinite loop while testing. Can you give any lead why this happens? From my point of view the math actually seemed fine, I check every whole number from 2 onwards until it fits the scheme ``[m] `mod` n == 0``, is there a logical mistake or just a wrong implementation?
Comment: Well actually my initial question was "How can I check if every element of a list mod n equals 0", which got solved by you right now, so I should ask for more help in a new thread according to the guidelines for asking questions. Thank you!
Comment: @JoeCocker, think about what LCM means again. You'll get there.
Comment: oh wow, i implemented a solution to find the smallest shared divisor if there exists one and go in an infinite loop if there is none! well, thank you for pointing that out, i think i wouldn't have seen such an obvious mistake because i was too sure with my code... so i'll just have to swap some things out now that i know how i can approach the problem
Comment: @JoeCocker, you only need to swap exactly two variables. Think about what divides what.
Comment: yes, I now swapped x and n in my where statement and changed it in my initial post. Interesting though that you get the least common divisor and least common multiple by just swapping out what divides what, I never thought of that by just looking at it.


Valores que sofrem calculos, se armazena o valor com os calculos no banco de dados?

Question: Estou desenvolvendo um sistema onde um produto sofre 3 alterações antes de chegar em seu valor final:
Desconto individual, Bonus de Venda e Desconto geral
Quero saber se, eu devo armazenar apenas o valor original do produto na base de dados ou se eu já faço todos os calculos relacionado a esse produto e então salvo o valor final dele.
Em meu caso, ainda se faria os calculos por diarias. Funcionaria como se fosse quantidade. Produto * diarias.
Por normalização de banco de dados, como seria o procedimento correto para persistir esses dados?
Comment: É informação , armazene separado.
Answer: Você escolhe, se seu sistema está arquitetado para ter um processamento de banco de dados, então você pode já armazenar o valor final do produto, mas isso vai te impedir de saber quais foram os descontos logo de primeira (Você teria que desfazer os cálculos para isso).
Se você executar o cálculo antes de armazenar o valor e no final já armazenar ele descontado, você precisaria criar um campo na tabela para armazenar o valor original. Enquanto que se você armazenar o valor original você pode exibir o valor do desconto em uma view, mas o processo pode ser o inverso também.
Enfim, depende da sua arquitetura, o que você se sente mais confortável? Armazenar o valor original e depois descontar? Ou o contrário?
Comment: Ai minha questão vira outra. No caso de armazenar o valor original e os devidos descontos na base de dados, todas as vezes que eu precisar apresentar o valor desse produto, precisarei fazer os calculos na minha aplicação?
Comment: Então, depende do que você está usando, eu aconselharia o uso de views, elas pegariam os valores reais do produto e adicionariam em novas colunas nas quais o valor final seria calculado.


Definition of minor key

Question:
Minor key music uses the harmonic minor scale as the basis for its
  harmony and the melodic minor scale for the melody. If the music uses
  nothing but the natural minor scale it IS NOT in a minor key (that
  implies tonality, and tonal music requires the leading tone). It is
  modal Aeolian music.

I find this weird. Is this even true? If so, what does the quote mean by "harmony" and "melody"?
Comment: I don't find it "weird" so much as "sad". Second-rate musicologists spend their lives trying to play catch-up with first-rate musicians. Third-rate musicians spend their lives trying to follow the rules invented by second-rate musicologists. Of course **good** musicology does have a use, but that is to provide **insight**, not rules.
Comment: I think that [this answer](http://music.stackexchange.com/questions/16248/understanding-minor-key-harmony/16254#16254) also contains some relevant information.
Answer: I would take this as a means to interpret what the author intended when writing the rest of the book. For example, if you play in a rock band and the band leader says a new piece you'll be learning is in D minor, there's no reason to assume that the piece is strictly functional harmony with no modal content. It could be in Dorian or Phrygian for all your band leader cares. It starts with a D minor chord and stays in that area for the whole song. It's all terminology. Changing what a piece of terminology means doesn't change how you expect the music to behave. So in this case, as reading through the rest of this text, just keep in mind that the author uses minor and modal terminology exclusively for specific contexts.
In common practice music, song in minor keys tended to use a major V chord rather than a minor v chord that the natural minor scale would harmonize to. V-i has a much more resolute feel than a v-i. That leading tone gives us an authentic cadence, which was the popular sound and is still one of the most powerful progressions in music. In A minor, that would be E-G#-B to A-C-E. The G# is altered from the natural minor harmony to give the E chord that leading tone. That's the harmonic portion. Only the seventh is raised for harmonic material. As for the melodic material, when melodies were written over this sort of progression, it was found that the interval between the minor sixth and the leading tone was too dissonant. It was, in fact, an augmented second. To correct this, the minor sixth was raised to a major sixth and the interval was much more pleasant. Typically, this melodic minor scale only has the sixth and seventh raised when ascending. Descending lines would use the natural minor.
So again, discrepancies in terminology are rampant in music because of mixed traditions, reusing terminology to mean different things, and lack of standardization. I don't know anyone who would lash out at you for calling a piece minor even though it uses modal melody and doesn't always contain a leading tone of the V chord. If the meaning gets across, that's what's important. This author knows what he means and makes it explicit, although he certainly seems to think that this meaning is more absolute than I'd agree with.
Answer: It is quite true and understandably very confusing wording at first.
The first thing you have to understand is how classic music theory defines tonality. It's very specific in that tonality is defined by the tonic - dominant relationship (V(7) - I or V(7) - i) which heavily depends on what is known as the leading tone. The leading tone is the note that is a semitone below the tonic and this gives us the major third in a V chord or a root in a viio.
Let's look at the A natural minor, A harmonic minor, and A melodic minor(ascending) scales.

A natural minor:
A  B  C  D  E  F  G

A harmonic minor:
A  B  C  D  E  F  #G

A melodic minor(ascending):
A  B  C  D  E  #F  #G

The leading tone of any A related key is G#. In natural minor, this simply does not exist. We're not able to naturally build a dominant chord to perceive A as tonic as defined above. Using the harmonic minor scale however, we can now build two dominant chords using harmonic minor (E(7) and G#o(7)) which can be used to imply tonality as classic music theory defines it. Melodic minor also takes advantage of this while smoothing out the stepwise motion.
I'll link some more information about this in general.
Comment: Black Magic Woman uses D minor, but there are lots of A minors  there as well, so I guess it's in 'D natural minor'?
Comment: @Tim our modern definition of a key is a lot different then the classic definition. While we use the tonic - dominant relationship  a lot it doesn't define our definition of tonality  so in many case what we would consider the key to be is not how it will classically be defined.
Answer: I think what the author may want to tell you is that the natural minor form is specific to a melodic minor scale descending. It is not a scale in the strict sense of the word but rather what happens to the melodic minor scale when it descends. (The Sub Mediant and Leading Tone are lowered.)
Comment: @NeilMeyer: "Twinkle twinkle little star" or any of the variants thereof use the first six scale degrees; "The little drummer boy" uses a lowered seventh scale degree, but always follows it with the sixth.  Are those not good melodies?
Comment: Natural minor keys also have leading tones they are just not raised. Leading Tones are just the seventh scale degree of a minor / major scale.
Comment: [A minor 7th is not a leading tone](http://www.musictheory.net/lessons/23).
Comment: G is the leading tone of any scale that begin on A regardless of the interval.
Comment: But is it correct that a melody must contain at least one leading tone to be in a minor key?
Comment: I cannot imagine a good melody not having the leading tone minor or otherwise.
Comment: Surely a lot of melodies using the natural minor exclusively exist?
Comment: We may have to take this to chat. Mods don't like conversations in the comments.
Comment: https://en.wikipedia.org/wiki/Leading-tone. @Tim: Is there a difference?

Definition of minor key


Accessing content variables through the page variable

Question: I have a template that extends the page.html.twig base template. I wish to render a field variable from the node as a heading in other parts of the page template.
I've tried {{dump(page.content)}} but the variable does not seem to be there, it is already rendered into HTML.
What's the syntax - if it exists - for accessing a node variable from the page.content variable?
For example, at the node level, I can access {{ content.field_heading }}.
At the page level, what can I use? ({{ page.content.??? }})
Answer: Per the docs on the core page.html.twig:
 \* Page content (in order of occurrence in the default page.html.twig):
 \* - messages: Status and error messages. Should be displayed prominently.
 \* - node: Fully loaded node, if there is an automatically-loaded node
 \*   associated with the page and the node ID is the second argument in the
 \*   page's path (e.g. node/12345 and node/12345/revisions, but not
 \*   comment/reply/12345).

The node variable is available in page.html.twig. If you need to access one its fields you can use {{ node.field_myfield.value }} to print it out.
Comment: Correct but note that this does not include the rendered fields that are available as content in the node template. You can only access the raw values. You can use the view() API method on the fields to prepare rendered fields yourself or you can use an entity view block, e.g. provided by the ctools module to display some fields somewhere in a block.
Comment: When I try print out a field consisting of a taxonomy term: eg `{{ node.field_tax_term.value }}` I get a user error: `User error: "target_id" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).` If I print it out on the node the same field works fine. Do taxonomy terms behave differently?
Comment: I still do not have a working solution for this. Shawn Conn's answer does not work all the time and often triggers the error I outlined above.