Verificar se o dia x cai em um Sabado ou Domingo

Question: Estou fazendo um sistema que será uma Agenda, nesse sistema tem uma opção de repetir o compromisso salvo quinzenalmente, ou seja eu salvo o compromisso e o sistema irá me notificar a cada 15 dias. Porém esse compromisso não pode cair no sábado ou domingo. Como posso fazer essa verificação?
Por exemplo como é quinzenal se eu adicionar um compromisso hoje ele irá salvar o dia de hoje e incrementar mais 15 dias, se o resultado cair em um sábado ou domingo ele pula e salva o compromisso na segunda feira. Ou seja, pra verificar se o dia da semana é sábado ou domingo tenho que passar uma data(data futura) como parâmetro e em cima dessa data fazer a verificação
Comment: já trabalhou com calendar? ele possui DAY_OF_MONTH você poderia subtrarir do seus dia atual ou fazer por semana  DAY_OF_WEEK -2 que seria o dia 6 e 7 da semana.
Comment: Está usando o Java 8? Se sim, existe a classe LocalDate que tem um método chamado getDayOfWeek, através dele você pode validar qual é o dia da semana. Caso esteja trabalhando com Java 7 pode usar a dica do @WellingtonAvelino.
Comment: Beleza, vou tentar usar as duas e ver qual se encaixa melhor. Mas é possível com essas classes descobrir qual é o dia da semana do mês que vem por exemplo?
Comment: editei a pergunta para explicar um pouco melhor o que eu estou tentando fazer
Answer: Dá pra usar Calendar mesmo.
Demo (obviamente, metade do código pode ser removido pois é de System.out.println...e também utilizar SWITCH, enfim...é só para efeito de demonstração)
Main.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main
{
    public static void main(String[] args)
    {
        try
        {
            Calendar data = Calendar.getInstance();
            //data.set(2015, Calendar.JULY, 5); // ou neste neste formato ao invés de usar o simpleFormat abaixo
            SimpleDateFormat simpleFormat = new SimpleDateFormat("dd/MM/yyyy");

            data.setTime(simpleFormat.parse("06/07/2015"));

            System.out.println("Data antes: " + simpleFormat.format(data.getTime()));
            data = checaFDS(data);
            System.out.println("Data apos: " + simpleFormat.format(data.getTime()));
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * Verifica se data á sábado ou domingo e acrescenta dias conforme necessário p/ retornar dia de semana.
     *
     * @param   data        Um objeto Calendar
     * @return  Calendar
     */
    public static Calendar checaFDS(Calendar data)
    {
        // se for domingo
        if (data.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
        {
            data.add(Calendar.DATE, 1);
            System.out.println("Eh domingo, mudando data para +1 dias");
        }
        // se for sábado
        else if (data.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)
        {
            data.add(Calendar.DATE, 2);
            System.out.println("Eh sabado, mudando data para +2 dias");
        }
        else
        {
            System.out.println("Eh dia de semana, mantem data");
        }
        return data;
    }

}

Sábado (04/07/2015)

Domingo (05/07/2015)

Dia de semana (06/07/2015)
Comment: haha, minha ideia era exatamente essa, mas to sem tempo de colocar exemplos :(
Comment: Muito obrigado, implementei sua ideia em meu sistema e funcionou perfeitamente.
Comment: Imagina Techies ! (Pois é @WellingtonAvelino kkkk)
Answer: O segredo é utilizar o u no padrão do SimpleDateFormat, como no código:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ProximoDiaDaSemana {

    private static DateFormat DIA_DA_SEMANA = new SimpleDateFormat("u");

    private static long MILISEGUNDOS_EM_UM_DIA = 24 * 60 * 60 * 1000;

    private static int DOMINGO = 7;

    private static int SABADO = 6;

    private static int diferencaSabadoOuDomingo(int diaDaSemana) {
        if (diaDaSemana == DOMINGO) {
            return 1;
        }
        if (diaDaSemana == SABADO) {
            return 2;
        }
        return 0;
    }

    private static Date obterDataProximoCompromisso(Date dataInicial, int dias) {
        Date daquiXDias = new Date(dataInicial.getTime() + dias * MILISEGUNDOS_EM_UM_DIA);
        int diferencaSabadoOuDomingo = diferencaSabadoOuDomingo(Integer.valueOf(DIA_DA_SEMANA.format(daquiXDias)));
        if (diferencaSabadoOuDomingo > 0) {
            return new Date(daquiXDias.getTime() + diferencaSabadoOuDomingo * MILISEGUNDOS_EM_UM_DIA);
        } else {
            return daquiXDias;
        }
    }
}

Assim, ao executarmos um teste:
    private static DateFormat EXIBICAO = DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());

    public static void main(String[] args) {
        Locale.setDefault(new Locale("pt-BR"));
        Date hoje = new Date();
        System.out.println("Hoje: " + EXIBICAO.format(hoje));
        for (int i = 1; i <= 15; i++) {
            System.out.println("Se agendar para daqui " + i + " dias cairá em: "
                    + EXIBICAO.format(ProximoDiaDaSemana.obterDataProximoCompromisso(new Date(), i)));
        }
    }

Temos o resultado desejado:

Hoje: Sexta-feira, 10 de Julho de 2015
Se agendar para daqui 1 dias cairá em: Segunda-feira, 13 de Julho de
  2015
Se agendar para daqui 2 dias cairá em: Segunda-feira, 13 de Julho de
  2015
Se agendar para daqui 3 dias cairá em: Segunda-feira, 13 de Julho de
  2015
Se agendar para daqui 4 dias cairá em: Terça-feira, 14 de Julho de
  2015
Se agendar para daqui 5 dias cairá em: Quarta-feira, 15 de Julho de
  2015
Se agendar para daqui 6 dias cairá em: Quinta-feira, 16 de Julho de
  2015
Se agendar para daqui 7 dias cairá em: Sexta-feira, 17 de Julho de
  2015
Se agendar para daqui 8 dias cairá em: Segunda-feira, 20 de Julho de
  2015
Se agendar para daqui 9 dias cairá em: Segunda-feira, 20 de Julho de
  2015
Se agendar para daqui 10 dias cairá em: Segunda-feira, 20 de Julho de
  2015
Se agendar para daqui 11 dias cairá em: Terça-feira, 21 de Julho de
  2015
Se agendar para daqui 12 dias cairá em: Quarta-feira, 22 de Julho de
  2015
Se agendar para daqui 13 dias cairá em: Quinta-feira, 23 de Julho de
  2015
Se agendar para daqui 14 dias cairá em: Sexta-feira, 24 de Julho de
  2015
Se agendar para daqui 15 dias cairá em: Segunda-feira, 27 de Julho de
  2015
Comment: Obrigado pela resposta


Why can't the Java compiler find my JARs?

Question: I made a GitHub repo to help explain my issue: https://github.com/matthiasdenu/jacoco-bug. But basically, I don't understand why javac -cp lib/ test/* doesn't work and fails with an error saying it can't find classes (that are in the JARs on the classpath I tried to specify)
denu:jacoco-bug denu$ javac -cp lib/ test/*
test/TestClass.java:2: error: package org.junit does not exist
import static org.junit.Assert.assertTrue;
                       ^
test/TestClass.java:2: error: static import only from classes and interfaces
import static org.junit.Assert.assertTrue;
^
test/TestSuite.java:1: error: package org.junit does not exist
import org.junit.ClassRule;
                ^
test/TestSuite.java:2: error: package org.junit.runners does not exist
import org.junit.runners.Suite;
                        ^
test/TestSuite.java:4: error: cannot find symbol
@RunWith(Suite.class)
 ^
  symbol: class RunWith
test/TestSuite.java:5: error: package Suite does not exist
@Suite.SuiteClasses({
      ^
test/TestClass.java:7: error: cannot find symbol
  @Test
   ^
  symbol:   class Test
  location: class TestClass
test/TestSuite.java:4: error: cannot find symbol
@RunWith(Suite.class)
         ^
  symbol: class Suite
8 errors
denu:jacoco-bug denu$

Comment: I don't see any JARs mentioned in your classpath, only a directory.
Answer: Try this:
javac -cp lib/*;test/*

Why would this work?

The ; (or : on some operating systems) is the path-separator. You need this because -cp only accepts one argument (which can be multiple paths separated by the path separator).
The lib/* should match all jars in the lib folder.
The test/* should match all jars in the test folder.
Comment: 1) I don't thing the OP wants `test/*` to match JAR files.  I think that is supposed to match source files.  2) Using regular pathname expansion (globbing) won't generate a valid classpath.  You need to use the special classpath wildcard mechanism.
Comment: It works for me [in this .sh file](https://github.com/kiegroup/optaplanner/blob/main/build/optaplanner-distribution-internal/src/main/assembly/scripts/runExamples.sh#L9), for Linux and Mac, and similarly in the .bat file for windows. Your mileage may vary.
Answer: Ivy downloads the dependencies (JARs) to the lib/ directory. My source files were in the src/ and test/ directories.
As mentioned in Geoffrey De Smet's answer, the classpath option takes one argument.
$ java -cp lib/junit-4.13.2.jar src/* test/* partially solves my problem.
To add all of the JARs in the lib/ I would need to add every *.jar file to the classpath argument, separated by path separators.
Ant allows you to do this with a fileset.
    <target name="build" depends="ivy" description="--> compile and build this test project">
        <mkdir dir="out/classes" />

        <path id="classpath">
            <fileset dir="lib" includes="*.jar"/>
        </path>

        <javac classpathref="classpath" destdir="out/classes" includeantruntime="false">
            <src path="src"/>
            <src path="test"/>
        </javac>
    </target>

GitHub commit: https://github.com/matthiasdenu/jacoco-bug/commit/a57fb5957bcc43c9c05a304a61b6ea956e1cca00
Comment: *"To add all of the JARs in the lib/ I would need to add every *.jar file to the classpath argument, separated by path separators."* - There is a better way.  Classpath wildcards.  See my answer.  But I agree that using a build tool such as Ant is even better ... though I would recommend Maven or Gradle as better tools.
Answer: Assuming that test/* was intended to match only *.java files, what you need is one of the following:
javac -cp lib/something.jar test/*.java

This puts one JAR file on the classpath
javac -cp lib/something.jar;lib/another.jar test/*.java  # Windows
javac -cp lib/something.jar:lib/another.jar test/*.java  # linux or Mac

This puts two JAR files on the classpath.  Note that different classpath separators are used on Windows versus other platforms.
javac -cp 'lib/*.jar' test/*.java

This is using a classpath wildcard to match all of the JAR files in the lib directory.  Notice that I quoted 'lib/*.jar' from attempting to do "globbing" on the argument.  The *.jar needs to be handled by javac itself.
For more information on setting the classpath, see https://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html

However, I strongly recommend that you don't do your builds by running javac from the command line or from clunky shell scripts or barch files.  Instead learn a Java build tool such as Maven, Gradle, Ant and so on.  Maven and Gradle understand how to retrieve your dependencies from a remote repository, and they will take care of assembling the classpaths for you.


GAME_WIDTH, GAME_HEIGHT and gameWidth, gameHeight

Question: I am learning how to make games with Vanilla JS. The instructor is using GAME_WIDTH, GAME_HEIGHT at the index.js; and gameWidth, gameHeight at the paddle.js. When he uses the latter, I see that there is an explanation pop-up near the latter one saying that it is considered GAME_WIDTH, GAME_HEIGHT when he hovers over gameWidth, gameHeight.
But when I try to hover over gameWidth, gameHeight; it says any. Could anyone explain the difference?
By the way the instructor uses Sandbox, I am using VS Code if that has anything to do with it.
index.js
import Paddle from './paddle.js';

let canvas = document.getElementById('gameScreen');
let ctx = canvas.getContext('2d');

const GAME_WIDTH = 800;
const GAME_HEIGHT = 600;

let paddle = new Paddle(GAME_WIDTH, GAME_HEIGHT);

paddle.js
export default class Paddle {
  constructor(gameWidth, gameHeight) {
    this.gameWidth = gameWidth;
    this.width = 150;
    this.height = 20;

    this.maxSpeed = 7;
    this.speed = 0;

    this.position = {
      x: gameWidth - 100 - this.width - 100,
      y: gameHeight - this.height - 10,
    };
  }

Answer: the capitalized constants (GAME_WIDTH) are the actual data containers that exist in the global scope.
the camel-case variables are function arguments and only live within the function's lifetime.
the script first sets the constants as default.
Then later it uses them to initiate the Paddle's constructor. But he could send any number to that constructor really.
As such there's no relation between the constants and the variables outside this one usage (afaics)
edit: the relation between them in your instructors editor is most likely a feature of said editor.


JNA: how to deal with unkown structs?

Question: If I'm not mistaken, a JNA Structure builds the struct by relying on the public fields of its corresponding Java class, which should extend Structure. My problem is that I need to pass a struct whose declaration is not known beforehand (let's say it's known at runtime). I just have a list of Objects, which the C library expects as a (reference to a) struct. Can I still use the Structure class or must I build a Memory object by hand, dealing with sizes, alignments/packing myself?
For example:
 /* native code */
 typedef struct mystruct {
     int x;
     float y;
 }  mystruct;

 void dosomething(mystruct * s) {
     s->y += s->x;
 }

And in Java:
 ...
 callFunctionWithSt("dosomething",
     new Object[]{Integer.valueOf(2),Float.valueOf(3.0)});
 ...

 void callFunctionWithSt(String funcName, Object[] structVals) {
     NativeLibrary nl = ...
     Pointer arg = ...  // or Memory ... or Structure
     // build structure
     for (Object objJava  : structVals) {
         valJna = convertFromJavaToJnaObject(objJava);
         // fill structure
     }
     f.invoke(arg);
 }

 Object convertFromJavaToJnaObject(Object) {
     // assume we know how to do this
 }

Comment: Can you provide native API examples?  If your native code uses opaque `struct`, it can do so only if all operations are performed on `struct*`, in which case you can use `Pointer` or `PointerType` and ignore the memory behind it.
Comment: I need to do exactly what it's usually done when passing a struct by reference. The native code is not opaque, is just that  I don't know at compile time the struct.
Answer: If you don't know the content of the struct, then it is referred to as "opaque".
For opaque struct *, you can use com.sun.jna.Pointer to represent the structure address.
Comment: I know the content, it's only that I know it at runtime. To use a Pointer (should rather be Memory, I think), I would need to do myslef all the calculations of fields alignments that a Structure does.
Comment: If you only know the content and runtime, doesn't that imply that you have to calculate where stuff is on the fly?  Or are you talking about polymorphism?
Comment: Can you provide an example of how to use `Pointer` with an opaque `struct *`? In particular, how would you create the `Pointer`?
Answer: You can still use Structure. Define your interface method like this:
interface SomeLib {
    public static final SomeLib INSTANCE =
        (SomeLib) Native.loadLibrary("SomeLib", SomeLib.class);

    Pointer getSomeStruct();
}

Then when you call it, you just do this:
Pointer someValue = SomeLib.INSTANCE.getSomeStruct();
// do something here to determine what type it is
SpecificStructure struct = new SpecificStructure(someValue);

Comment: This assumes that the struct is being returned directly, but what if it is returned by reference? E.g. `int getSomeStruct(struct *s)`. That seems to be what the OP is talking about, since he mentions "passing a struct by reference".
Comment: Nope, the code I posted is for doing it by reference, which is why there is a pointer here. I'm not entirely sure how to handle it if it's returned directly, but I'm guessing making a ByValue subclass of the struct is the hint you'd need to do that.
Comment: Okay, well I'm not very familiar with the C lingo, but I meant "as a parameter." Maybe I misunderstood the OP. At any rate, I've asked another question [here](http://stackoverflow.com/questions/44036223/dealing-with-opaque-structs-in-jna?noredirect=1&lq=1) on this subject; if you know how to do it as a parameter, please share there.
Comment: Ah, as a parameter you can put `Pointer` in the parameter. Since it's an opaque struct, you must have got it from somewhere else, probably another function, which would have returned it as a pointer as well, so you just keep it and pass it as-is into another. In our actual production code, though, what we do is subclass PointerType with a name better matching what the library's headers called it, and then put that on all the methods. That way, it's harder to mess up and pass in the wrong thing.
Comment: No, I mean that the function I'm trying to call returns via a parameter and I need to somehow create the pointer without knowing anything about the struct. In C you would do something like `malloc(sizeof(SomeStruct))` (again, not a C programmer), but I'm not sure how to do this in Java. See the question I linked.
Comment: Usually what I've seen for that kind of API, I have had to pass a pointer to a pointer, and they allocate the structure and put a pointer to it in the location referred to by my pointer. If you're expected to pass a pointer to pass a struct back by value (?), I have no idea how that would work. I wouldn't even expect sizeof to work for opaque structs. If you do somehow know the size though, you can pass a Memory.
Comment: Well, in the usage example for the API, they create it as `SomeStruct x = NULL` and pass it as `&x`. But I can't do that in Java since I can't map `SomeStruct`, as it is opaque.
Comment: Which API is this? I don't get how that could work without somehow knowing the size... (There are questions about how to do it in C on Stack Overflow too.) If there is a way to get the size you'd just pass a Memory or something.
Comment: It's Apple's `Security.h`. I've added more information to my question here: http://stackoverflow.com/questions/44036223/dealing-with-opaque-structs-in-jna?noredirect=1&lq=1

JNA: how to deal with unkown structs?


How can I get the $delta of block created using UI?

Question: I have a created a block using UI .I want to change the content of the block programmatically.
For this I am using hook_block_view_alter(&$data, $block) for it as follows:
I have just created a block using UI and I am going to assign certain pages which will be able to see that view..
function hook_block_view_alter(&$data, $block) {
if ($block->delta == 'HOW CAN I GET THE $DELTA here') {
$data['#markup'] = 'Google';

}

}

Comment: Why not create the block also in code?
Comment: @ЕлинЙ. That's the real question ;) The delta for custom blocks is the block ID (check the URL when you edit the block), you'll also want to check that `$block->module == 'block'` so you don't get collisions with other modules. But really, implementing `hook_block_info()` and `hook_block_view()` yourself would be a much more reusable solution
Comment: Is it a custom or module-provided block? If module, which module?
Comment: I have just created a block using UI and I am going to assign certain pages which will be able to see that view..
Comment: yes I want to codify the block any ideas?
Answer: If you go to admin/structure/block and mouseover the "configure" link you'll see something like this for blocks added through UI:
/admin/structure/block/manage/block/1/configure
something like this for blocks created with views:
/admin/structure/block/manage/views/81e6b321879efa58ba9e546521c14467/configure
something like this for blocks created with webform:
/admin/structure/block/manage/webform/client-block-50/configure
something like this for blocks created by the system (core):
/admin/structure/block/manage/system/main/configure
I've bolded the deltas and italicized the modules in each example.
Comment: Don't forget different modules can define the same delta, so it's important to check `$block->module` as well as the delta or you might end up addressing the wrong one
Comment: good point Clive
Answer: Find the block on the Blocks configuration page, and click the "configure" link.
Look at the URL. The URL path tells you both the module that is responsible for the block, and the delta assigned to it. Here's the URL pattern:
/admin/structure/block/manage/ MODULENAME / DELTA /configure
So if your URL path is "/admin/structure/block/manage/block/5/configure", then that particular block is maintained by the "block" module, and the delta for the block is "5".
Comment: Scott beat me by 2 minutes!
Answer: You can always get the delta by quering your DB (handy in cases where custom blocks are generated automatically and the delta is dynamic)
  $result = db_select('block_custom', 'b')
     ->fields('b', array('bid'))
     ->condition('info', '<ADMIN TITLE OF THE BLOCK>')
     ->execute()
     ->fetchAssoc();

  // if $result['bid'] exists..

  $delta = db_select('block', 'b')
     ->fields('b', array('delta'))
     ->condition('bid', $result['bid'])
     ->execute()
     ->fetchAssoc();

  $delta = $delta['delta'];


Missing five core module folders and one enabler

Question: In Drupal 7.36, the "Administration > Modules" page (/admin/modules) lists 44 core modules. However, the folder "...\htdocs\admin\modules\" has subfolders for 40 modules, which include those 44, except Field SQL storage, List, Number, Options, and Text, plus Profile.
In other words, there are five core modules that do not have a folder in the core modules folder and there is one core module (Profile) that is not available for enabling on the "Administration > Modules" page.
Does anyone here know why that is?
The Profile doc page says to "enable in admin/build/modules". That URL on my installation just takes me to the main Administration page. So how does one actually enable this module?
Comment: @AlyssaGono, no, "Profile" is not disabled. It just does not appear in the list at all. See the explanation by Christoph below and my follow-up question to him.
Comment: Your Core Module "Profile" is disabled and you want to enable it? Have you found "Requires:" word right after the module? If yes, enable first the modules stated after the word "Requires:"  before you can enable the core module Profile.
Answer: The field submodules are inside the field module folder:
./modules/field/modules/number/number.module
./modules/field/modules/list/list.module
./modules/field/modules/text/text.module
./modules/field/modules/field_sql_storage/field_sql_storage.module
./modules/field/modules/options/options.module

The D7 module overview is at admin/modules. admin/build/modules was in Drupal 6; a lot of the community docs pages are badly outdated, unfortunately.
Finally, the Profile module is deprecated in Drupal 7, and therefore hidden by default.
modules/profile/profile.info:

; The Profile module is deprecated, and included in Drupal 7 for legacy
; purposes only. By default, the module will be hidden from the UI unless you
; are upgrading a site that uses the Profile module to extend user profiles.
; See user_system_info_alter().
hidden = TRUE

It's only there to provide an upgrade path for D6 sites; it can't be enabled on a new D7 site without commenting out that line.
(The reason the module is deprecated is probably that the Fields API has taken over what it used to do, so it's obsolete.)
Comment: Thank you for your helpful answer. However, note, I went ahead and submitted a core issue on "Profile". They responded that it is depricated and subsumed into "Users". Does that conflict with what you say about the Fields API?
Comment: It really comes to the same thing: Fields drives everything related to extensible content structures ("entities"). It's a bit of an abstraction layer. Then the other modules like Node and User declare their stuff to be entities which fields can be added to.
Comment: Thanks. Still working on sorting out fields, entities, types, etc.


How do instruments with discrete tuning play chords alongside those with continuous tuning?

Question: I was taught that when playing a triad, the third should be played sharper and the fifth flatter than the notes would sound on an instrument tuned to equal temperament, such as the piano. However this intonation adjustment is not possible on all instruments, even though these instruments may be playing together in the same orchestra/group.
How should members of an orchestra deal with this?

should those who can adjust intonation refrain from doing so, to avoid sounding out of tune with those who can't?
do those who can't adjust intonation have some technique to compensate?
is the adjustment of pitch minor enough that the different intonations are not noticeable, whilst the benefit of the adjustment is?
do the composers/arrangers consider this limitation when assigning the parts to instruments?
or something else?

Explanation of terms used in the title
By discrete tuning I'm referring to instruments such as the piano, where the intonation cannot be adjusted whilst playing.
By continuous tuning I mean instruments such as 'cello or trombone, where you can easily adjust the intonation of a note whilst playing (i.e. outside of tuning the instrument).
I'm aware that some instruments fall into a grey area; e.g. the trumpet has discrete tuning, but players of moderate ability can bend notes to adjust the intonation.
Comment: You've got the pitch directions reversed -- presuming you're looking at this from the perspective of a variable-intonation instrument like violin. 3rds would be _lowered_ from equal temperament so they are in tune with the harmonic series.
Answer: For a classical orchestra the priority is, to be in tune with your voice group e. g. first violins. A voice group consists of same instruments, so no problem, they play as you've been teached. The instruments with discrete tuning are only a few (piano, celesta, marimbaphone, xylophone, organ come to my mind) and these are unlikely to have prominent sustained notes in common with one of the continuous tuning instruments, so that this effect will seldom be noticable. Note that while your "moderate ability trumpet player" is able to adjust, this is viable for chords distributed to several voices, not for 32th sequences. So according to my experience: the musicians with continuous tuning do what they always do: they produce a tone and adjust minimally to what they hear from their own and adjacent instruments. If the result is not sufficiently reliable, for the few critical places remaining the conductor will announce, which instruments should add a sign marking "lower" or "higher" as appropriate to their sheets and that's it.
Comment: *Almost* all fixed-pitch instruments in the orchestra (harps, xylophones, piano) don't produce sustained notes, which makes the difference even less noticeable. The one exception is the rarely-used pipe organ, and you do in fact often hear discrepancies with a prominent organ part if you listen closely.
Answer: I was taught that when playing a triad, the third should be played sharper and the fifth flatter than the notes would normally sound.
Uh, no?  "Would normally sound" is usually used to describe the equally tempered scale whereas "playing a triad" implies a tendency towards pure intervals.
A perfect major third is about 386 cents (14 cents flat from a tempered third), and a perfect fifth is about 702 cents (2 cents sharp from a tempered fifth).  If you are tuning an organ, say, you lay the reference octave by first tuning a perfect fifth to the first two notes, then taking off just the bit from the upper note that leaves you with the beating appropriate for the interval.
So if you don't have the auditory skills to adjust into the "does not beat" direction, you are better off not modifying the tempered intervals at all rather than guessing.
Comment: This is correct information, but the question is about how "discrete" and "continuous" tuning instruments should play in an ensemble with one another.


Using Markov's Inequality to show that $E(X_i) \rightarrow 0$ implies $P(X_i=0) \rightarrow 1$

Question: I am trying to use Markov's inequality to show that for a sequence of positive random variables $X_1, X_2, ....$ with values in $N=\left\{0,1,2,...\right\}$ and $\lim_{i\rightarrow\infty}E[X_i]=0$, it holds that $\lim_{i\rightarrow\infty}P[X_i=0]=1$.
Intuitively, I understand this concept due to the law of large numbers, since as $i$ approaches infinity the expected value converges to the true mean 0, and the probability that $X_i$ equals the true mean converges to 1.
However, I am stumped as to how to use Markov's Inequality, $P(X\geq c)=E(X)/c$, to prove this. Any help is appreciated.
Comment: Using markov's inequality to show $\sum_i P(|X_i| > \epsilon) < \infty$ for all $\epsilon > 0$ would prove the result, by the first Borel-Cantelli Theorem. Perhaps the fact $E[X_i] \to 0$ can be used to do that combined with Markov's.
Comment: Are you told $E[X_i]$ is strictly decreasing in $i$? As I think it would make the proof easier.
Comment: No, the above information is all that is given. Not sure I understand how to use that inequality to prove the result... how is it helpful if $\varepsilon$ must be greater than 0? And what is the purpose in summing the probabilities across i?
Comment: A direct consequence of Borel Cantelli theorem says that if that summation is finite for any positive $\epsilon$ then $X_i$ converges to 0 almost surely.
Comment: @xiaomi - This has nothing to do with sums, it's about limits.  There are no sums in the problem statement.  (I misread it at first too!)  - OP: Note that since $X_i$ is on the integers, setting $c = 1$ and showing that $P(X_i \geq 1) \rightarrow 0$ does the job; look at the r.h.s. of the Markov expression and substitute.
Answer: Since $X_1,X_2,X_3,...$ are non-negative random variables, for all $n \in \mathbb{N}$ you have:
$$\mathbb{E}(X_n) = \sum_{k=1}^\infty \mathbb{P}(X_n \geqslant k)  \geqslant \mathbb{P}(X_n \geqslant 1) = 1-\mathbb{P}(X_n=0).$$
(This is Markov's inequality with $c=1$.)  Re-arranging this inequality, and imposing the upper bound of one on probabilities, gives you:
$$1 - \mathbb{E}(X_n) \leqslant \mathbb{P}(X_n=0) \leqslant 1 \quad \quad \quad \text{for all } n \in \mathbb{N}.$$
We can now establish the desired result by using the squeeze theorem, by taking the limit of this sequence of inequalities.  In particular, since $\lim_{n \rightarrow \infty} \mathbb{E}(X_n) = 0$ we get the squeezed limit:
$$1 \leqslant \lim_{n \rightarrow \infty} \mathbb{P}(X_n=0) \leqslant 1,$$
which establishes that $\lim_{n \rightarrow \infty} \mathbb{P}(X_n=0) = 1$.  $\blacksquare$


How to check a function is positive definite?

Question: I recently learned about characteristic functions and in particular the Bochner Theorem which helps us ascertain when a given function is a characteristic function for some probability distribution.
The standard version of Bochner's theorem from Wikipedia states that:
For any normalized continuous positive definite function $f$ on $G$ (normalization here means $f$ is $1$ at the unit of $G$), there exists a unique probability measure on ${\displaystyle {\widehat {G}}}$ such that
$${\displaystyle f(g)=\int _{\widehat {G}}\xi (g)d\mu (\xi )}$$
i.e. $f$ is the Fourier transform of a unique probability measure $\mu$ on ${\displaystyle {\widehat {G}}}$. In other words, any continuous positive-definite function on the real line is the Fourier transform (characteristic function) of a (positive) finite measure.
Another version, which combines Khinchine's theorem is stated as follows:
Let $\phi: \mathbb{R} \to \mathbb{C}$ be a continuous function with $\phi(0) =1$. Then $\phi$ is a characteristic function $\iff$ $\forall n \in \mathbb{N}, t_i \in \mathbb{R}$ and $\lambda_i \in \mathbb{C}$ for $i = 1, \dots, n$, we have
$$\sum_{i, j =1}^n \phi(t_i - t_j) \lambda_i \overline{\lambda_k} \geq 0$$
Wikipedia notes that the trouble with these theorems is that computational verification of the positive-definiteness is not easy. I'm curious to learn whether there is an effective/efficient way to check for positive definiteness of a function (or the condition in the second version provided below) because based on the definition of positive-definiteness for functions, it seems like we would have to prove the square matrices for all sizes and possible permutations are Hermitian.
I am also aware of Polya's criterion as an alternative to deal with the problem motivating Bochner's theorem but are there any easy ways to verify that there exists a distribution such that a given function corresponds to the characteristic function for it. Until now, I have defined appropriate random variables to solve relatively direct problems (convex combinations of characteristic functions and square of the absolute value of a characteristic function also define characteristic functions).
Comment: As far as I know there is no simple way of determining  if a given function is positive definite. If such a method existed it would have made the job determining which distributions are infinitely divisible an easy one, but this job is not easy.
Comment: I have run into this same problem as you a long time ago... I came up with the fact that given a bell-shape function, we know whether it's definite positive or not by looking at its derivative near zero. The problem with bell-shape function is it might not decrease fast enough near zero. If the derivative of the bell shape near the right side of zero is concave up you can say that the function will be positive definite. You can test it out yourself...
Answer: I think that the answer to your question will be heavily dependent on the group $G$. In the case of finite cyclic groups $G = \mathbb{Z}/n\mathbb{Z}$ you can apply the Fast Fourier Transform to get the Fourier coefficients of $\phi$ with a computational cost of $O(n \log n)$ and then you only have to check the positivity of $\hat\phi$. The same method will work for finite Abelian groups.
I do not think there is short answer for $G$ infinite.


Barlines in proportional notation disappear

Question: Some time ago, I reached out to the lil mailing list seeking assistance with creating a Csound to LilyPond converter. The goal was to improve the readability and presentation of Csound scores using LilyPond.
For context, the Csound score format I'm dealing with is relatively straightforward and consists of the following fields: instrument_name, onset, duration, dynamic, frequency (at least).
\context Staff = MY_INSTR \new Voice \after 4*##eMY_ONSET { MY_NOTE 4*##eMY_DUR \- _"MY_CENT¢" } <>
It works well, but as I'm working on more complex compositions, I've encountered some inconsistencies.
The first system doesn't display bar lines marking the seconds in this code.
Bar lines also do not appear in the last measure of the system.
I'm wondering if this approach is the right one to achieve the desired result. Any guidance or suggestions would be greatly appreciated!
\version "2.24.0"

\paper {
#(set-paper-size "a4landscape")
print-page-number = ##t
system-separator-markup = \slashSeparator
}

\layout {
\context {
\Score
proportionalNotationDuration = #(ly:make-moment 1/48)
\override SpacingSpanner.uniform-stretching = ##t
\override TimeSignature.stencil = ##f
\override TextScript.font-size = #-9
}
\context {
\Voice
\remove Stem_engraver
\remove Dots_engraver
\override NoteHead.duration-log = 2
}
}

<<
%===================================
\new RhythmicStaff = timeline
\new Staff = "org"
\new Staff = "senot"
\cadenzaOn
%===================================
\context Staff = "org" \new Voice \after 4*##e0.333 { f,, 4*##e1.324 _"+1.96¢" } <>
\context Staff = "org" \new Voice \after 4*##e0.333 { \clef "bass_8" } <>
\context Staff = "org" \new Voice \after 4*##e0.663 { cis,, 4*##e1.318 _"-11.73¢" } <>
\context Staff = "org" \new Voice \after 4*##e13.655 { bes,, 4*##e1.112 _"+3.91¢" } <>
\context Staff = "org" \new Voice \after 4*##e13.655 { \clef "bass_8" } <>
\context Staff = "org" \new Voice \after 4*##e13.933 { cis,, 4*##e1.108 _"-11.73¢" } <>
\context Staff = "org" \new Voice \after 4*##e13.933 { \clef "bass_8" } <>
\context Staff = "org" \new Voice \after 4*##e14.21 { f,, 4*##e1.105 _"+1.96¢" } <>
\context Staff = "org" \new Voice \after 4*##e14.21 { \clef "bass_8" } <>
\context Staff = "org" \new Voice \after 4*##e14.487 { c, 4*##e1.101 _"0.0¢" } <>
\context Staff = "org" \new Voice \after 4*##e14.487 { \clef "bass_8" } <>
\context Staff = "org" \new Voice \after 4*##e14.762 { fis,, 4*##e1.097 _"-9.78¢" } <>
\context Staff = "org" \new Voice \after 4*##e14.762 { \clef "bass_8" } <>
\context Staff = "org" \new Voice \after 4*##e15.036 { f,, 4*##e1.094 _"+1.96¢" } <>
\context Staff = "org" \new Voice \after 4*##e15.036 { \clef "bass_8" } <>
\context Staff = "senot" \new Voice \after 4*##e14.486 { bes, 4*##e1.101 _"+3.91¢" } <>
\context Staff = "senot" \new Voice \after 4*##e14.486 { \clef "bass_8" } <>
\context Staff = "senot" \new Voice \after 4*##e14.762 { f,, 4*##e1.097 _"+1.96¢" } <>
\context Staff = "senot" \new Voice \after 4*##e14.762 { \clef "bass_8" } <>
\context Staff = "senot" \new Voice \after 4*##e15.036 { cis,, 4*##e1.094 _"-11.73¢" } <>
\context Staff = "senot" \new Voice \after 4*##e15.036 { \clef "bass_8" } <>
\context Staff = timeline \new Voice \after 4*##e1 { s1 ^\markup"1" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e2 { s1 ^\markup"2" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e3 { s1 ^\markup"3" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e4 { s1 ^\markup"4" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e5 { \break } <>
\context Staff = timeline \new Voice \after 4*##e6 { s1 ^\markup"6" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e7 { s1 ^\markup"7" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e8 { s1 ^\markup"8" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e9 { s1 ^\markup"9" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e10 { \break } <>
\context Staff = timeline \new Voice \after 4*##e11 { s1 ^\markup"11" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e12 { s1 ^\markup"12" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e13 { s1 ^\markup"13" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e14 { s1 ^\markup"14" \bar "!"  } <>
\context Staff = timeline \new Voice \after 4*##e15 { \break } <>
\context Staff = timeline \new Voice \after 4*##e16 { s1 ^\markup"16" \bar "!"  } <>
>>

Answer: You are not getting some barlines as
s1^"text" \bar "!"

will insert the bar line after the skip, which is in your case in a random position later. Rather do
\bar "!" s1^"text"

to have the bar line at the exact position you specify. Alternatively you may do
<>^"text" \bar "!"

or
\bar "!" <>^"text"

Some more details:
\new Staff \new Staff ...

creates contexts within contexts. I'd rather do
\new Staff $(empty-music)

instead to create an empty context.
Also \after x m1 m2 is equivalent to << m2 sx m1>>. So instead of
\after 4*##e0.333 { f,, 4*##e1.324 _"+1.96¢" } <>

you can directly do
s4*##e0.333 f,, 4*##e1.324 _"+1.96¢"

etc.
So this could look like this:
\version "2.24.0"

\paper {
  #(set-paper-size "a4landscape")
  print-page-number = ##t
  system-separator-markup = \slashSeparator
}

\layout {
  \context {
    \Score
    proportionalNotationDuration = #(ly:make-moment 1/48)
    \override SpacingSpanner.uniform-stretching = ##t
    \override TimeSignature.stencil = ##f
    \override TextScript.font-size = #-9
  }
  \context {
    \Voice
    \remove Stem_engraver
    \remove Dots_engraver
    \override NoteHead.duration-log = 2
  }
}

<<
  %===================================
  \new RhythmicStaff = "timeline" $(empty-music)
  \new Staff = "org" $(empty-music)
  \new Staff = "senot" $(empty-music)
  \cadenzaOn
  %===================================
  \context Staff = "org" \new Voice { s4*##e0.333 f,, 4*##e1.324 _"+1.96¢" }
  \context Staff = "org" \new Voice { s4*##e0.333 \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e0.663  cis,, 4*##e1.318 _"-11.73¢" }
  \context Staff = "org" \new Voice { s4*##e13.655  bes,, 4*##e1.112 _"+3.91¢" }
  \context Staff = "org" \new Voice { s4*##e13.655  \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e13.933  cis,, 4*##e1.108 _"-11.73¢" }
  \context Staff = "org" \new Voice { s4*##e13.933  \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e14.21  f,, 4*##e1.105 _"+1.96¢" }
  \context Staff = "org" \new Voice { s4*##e14.21  \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e14.487  c, 4*##e1.101 _"0.0¢" }
  \context Staff = "org" \new Voice { s4*##e14.487  \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e14.762  fis,, 4*##e1.097 _"-9.78¢" }
  \context Staff = "org" \new Voice { s4*##e14.762  \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e15.036  f,, 4*##e1.094 _"+1.96¢" }
  \context Staff = "org" \new Voice { s4*##e15.036  \clef "bass_8" }
  \context Staff = "senot" \new Voice { s4*##e14.486  bes, 4*##e1.101 _"+3.91¢" }
  \context Staff = "senot" \new Voice { s4*##e14.486  \clef "bass_8" }
  \context Staff = "senot" \new Voice { s4*##e14.762  f,, 4*##e1.097 _"+1.96¢" }
  \context Staff = "senot" \new Voice { s4*##e14.762  \clef "bass_8" }
  \context Staff = "senot" \new Voice { s4*##e15.036  cis,, 4*##e1.094 _"-11.73¢" }
  \context Staff = "senot" \new Voice { s4*##e15.036  \clef "bass_8" }
  \context Staff = "timeline" \new Voice { s4*##e1  <> ^\markup"1" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e2  <> ^\markup"2" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e3  <> ^\markup"3" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e4  <> ^\markup"4" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e5  \break }
  \context Staff = "timeline" \new Voice { s4*##e6  <> ^\markup"6" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e7  <> ^\markup"7" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e8  <> ^\markup"8" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e9  <> ^\markup"9" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e10  \break }
  \context Staff = "timeline" \new Voice { s4*##e11  <> ^\markup"11" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e12  <> ^\markup"12" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e13  <> ^\markup"13" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e14  <> ^\markup"14" \bar "!"  }
  \context Staff = "timeline" \new Voice { s4*##e15  \break }
  \context Staff = "timeline" \new Voice { s4*##e16  <> ^\markup"16" \bar "!"  }
>>

But I wouldn't really do the counters as separate markups in the first place, but add them to the bar line stencil, e.g. do something like
\new RhythmicStaff = "timeline" \with {
  \override BarLine.stencil =
  #(grob-transformer
    'stencil
    (lambda (grob orig)
      (let ((text (ly:text-interface::print grob)))
        (ly:stencil-add
         orig
         (ly:stencil-translate text '(0.6 . 0.6))))))
  \override BarLine.font-size = #-8
  \override BarLine.font-series = #'bold
} $(empty-music)

and then
\context Staff = "timeline" \new Voice { s4*##e1  \once\override Staff.BarLine.text = "1" \bar "!"  }

(a similar effect could be achieved by doing \override Score.BarNumber.break-visibility = ##(#t #t #t)).
But this number could be derived automatically from the current bar number if we do not use \cadenzaOn:
\version "2.24.0"

\paper {
  #(set-paper-size "a4landscape")
  print-page-number = ##t
  system-separator-markup = \slashSeparator
}

\layout {
  \context {
    \Score
    proportionalNotationDuration = #(ly:make-moment 1/48)
    \override SpacingSpanner.uniform-stretching = ##t
    \override TimeSignature.stencil = ##f
    \override TextScript.font-size = #-9
    measureBarType = "!"
  }
  \context {
    \Voice
    \remove Stem_engraver
    \remove Dots_engraver
    \override NoteHead.duration-log = 2
  }
}

#(define (bar-number-engraver context)
   (make-engraver
    (acknowledgers
     ((bar-line-interface engraver grob source-engraver)
      (ly:grob-set-property!
       grob
       'text
       (number->string (1- (ly:context-property context 'currentBarNumber))))))))

<<
  %===================================
  \new RhythmicStaff = "timeline" \with {
    \consists #bar-number-engraver
    \override BarLine.stencil =
    #(grob-transformer
      'stencil
      (lambda (grob orig)
        (let ((text (ly:text-interface::print grob)))
          (ly:stencil-add
           orig
           (ly:stencil-translate
            (ly:stencil-aligned-to text X RIGHT) '(-0.6 . 0.6))))))
    \override BarLine.font-size = #-8
    \override BarLine.font-series = #'bold
  } $(empty-music)
  \new Staff = "org" $(empty-music)
  \new Staff = "senot" $(empty-music)
  \time 1/4
  %===================================
  \context Staff = "org" \new Voice { s4*##e0.333 f,, 4*##e1.324 _"+1.96¢" }
  \context Staff = "org" \new Voice { s4*##e0.333 \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e0.663  cis,, 4*##e1.318 _"-11.73¢" }
  \context Staff = "org" \new Voice { s4*##e13.655  bes,, 4*##e1.112 _"+3.91¢" }
  \context Staff = "org" \new Voice { s4*##e13.655  \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e13.933  cis,, 4*##e1.108 _"-11.73¢" }
  \context Staff = "org" \new Voice { s4*##e13.933  \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e14.21  f,, 4*##e1.105 _"+1.96¢" }
  \context Staff = "org" \new Voice { s4*##e14.21  \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e14.487  c, 4*##e1.101 _"0.0¢" }
  \context Staff = "org" \new Voice { s4*##e14.487  \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e14.762  fis,, 4*##e1.097 _"-9.78¢" }
  \context Staff = "org" \new Voice { s4*##e14.762  \clef "bass_8" }
  \context Staff = "org" \new Voice { s4*##e15.036  f,, 4*##e1.094 _"+1.96¢" }
  \context Staff = "org" \new Voice { s4*##e15.036  \clef "bass_8" }
  \context Staff = "senot" \new Voice { s4*##e14.486  bes, 4*##e1.101 _"+3.91¢" }
  \context Staff = "senot" \new Voice { s4*##e14.486  \clef "bass_8" }
  \context Staff = "senot" \new Voice { s4*##e14.762  f,, 4*##e1.097 _"+1.96¢" }
  \context Staff = "senot" \new Voice { s4*##e14.762  \clef "bass_8" }
  \context Staff = "senot" \new Voice { s4*##e15.036  cis,, 4*##e1.094 _"-11.73¢" }
  \context Staff = "senot" \new Voice { s4*##e15.036  \clef "bass_8" }
  \context Staff = "timeline" \new Voice { s4*##e5  \break }
  \context Staff = "timeline" \new Voice { s4*##e10  \break }
  \context Staff = "timeline" \new Voice { s4*##e15  \break }
>>

Finally we could automatize a lot of the stuff going on, essentially storing the content as a table of context, time and something to do. This can then be nicely parsed into music by a function:
\version "2.24.0"

#(define (bar-number-engraver context)
   (make-engraver
    (acknowledgers
     ((bar-line-interface engraver grob source-engraver)
      (ly:grob-set-property!
       grob
       'text
       (number->string (1- (ly:context-property context 'currentBarNumber))))))))

parseTable =
#(define-music-function (table) (list?)
   (define (impl t)
     (if (null? t)
         '()
         (let* ((line (car t))
                (ctx (first line))
                (time (second line))
                (what (third line))
                (args (cdddr line)))
           (cons
            #{
              \context Staff = #ctx
              \new Voice
              { s4*$time
                #(cond ((ly:music? what) (ly:music-deep-copy what))
                       ((procedure? what) (apply what args))
                       (else (begin
                              (ly:warning
                               (format #f "Unknown argument at time ~a" time))
                              (empty-music))))
              }
            #}
            (impl (cdr t))))))
   (make-music 'SimultaneousMusic 'elements (impl table)))

makeNote =
#(define-music-function (p dur alt)
   ((lambda (p) (or (ly:pitch? p) (string? p))) number? (markup? #f))
   (if (string? p)
       (set! p (ly:parse-string-expression (ly:parser-clone) p)))
   (if alt
       #{ $p 4*$dur _$alt #}
       #{ $p 4*$dur #}))

table =
#(list
  (list "org"       #e0.333 makeNote "f,," #e1.324 "+1.96¢")
  (list "org"       #e0.333 clef "bass_8")
  (list "org"       #e0.663 makeNote "cis,," #e1.318 "-11.73¢")
  (list "org"      #e13.655 makeNote "bes,," #e1.112 "+3.91¢")
  (list "org"      #e13.655 clef "bass_8")
  (list "org"      #e13.933 makeNote "cis,," #e1.108 "-11.73¢")
  (list "org"      #e13.933 clef "bass_8")
  (list "org"      #e14.21  makeNote "f,," #e1.105 "+1.96¢")
  (list "org"      #e14.21  clef "bass_8")
  (list "org"      #e14.487 makeNote "c," #e1.101 "0.0¢")
  (list "org"      #e14.487 clef "bass_8")
  (list "org"      #e14.762 makeNote "fis,," #e1.097 "-9.78¢")
  (list "org"      #e14.762 clef "bass_8")
  (list "org"      #e15.036 makeNote "f,," #e1.094 "+1.96¢")
  (list "org"      #e15.036 clef "bass_8")
  (list "senot"    #e14.486 makeNote "bes," #e1.101 "+3.91¢")
  (list "senot"    #e14.486 clef "bass_8")
  (list "senot"    #e14.762 makeNote "f,," #e1.097 "+1.96¢")
  (list "senot"    #e14.762 clef "bass_8")
  (list "senot"    #e15.036 makeNote "cis,," #e1.094 "-11.73¢")
  (list "senot"    #e15.036 clef "bass_8")
  (list "timeline"  #e5     break)
  (list "timeline" #e10     break)
  (list "timeline" #e15     break)
)

\paper {
  #(set-paper-size "a4landscape")
  print-page-number = ##t
  system-separator-markup = \slashSeparator
}

\layout {
  \context {
    \Score
    proportionalNotationDuration = #(ly:make-moment 1/48)
    \override SpacingSpanner.uniform-stretching = ##t
    \override TimeSignature.stencil = ##f
    \override TextScript.font-size = #-9
    measureBarType = "!"
  }
  \context {
    \Voice
    \remove Stem_engraver
    \remove Dots_engraver
    \override NoteHead.duration-log = 2
  }
}

<<
  %===================================
  \new RhythmicStaff = "timeline" \with {
    \consists #bar-number-engraver
    \override BarLine.stencil =
    #(grob-transformer
      'stencil
      (lambda (grob orig)
        (let ((text (ly:text-interface::print grob)))
          (ly:stencil-add
           orig
           (ly:stencil-translate
            (ly:stencil-aligned-to text X RIGHT) '(-0.6 . 0.6))))))
    \override BarLine.font-size = #-8
    \override BarLine.font-series = #'bold
  } $(empty-music)
  \new Staff = "org" $(empty-music)
  \new Staff = "senot" $(empty-music)
  \time 1/4
  %===================================
  \parseTable \table
>>

Comment: Thank you very much!! That's amazing it's really clear and it works like a charm. Can I ask you where did u study lilypond. I struggle a bit finding a good way to deeply understand basis.


Substituting $x = by$ in a differential equation

Question: In my textbook, we have the differential equation (some constants omitted)
$$\frac{d^2 \psi}{dx^2} + (1-x^2)\psi = 0$$
and the author introduces the new variable $y$ which is related to $x$ by
$$x = by$$
for some $b$ and, feeding the above into the differential equation, we arrive at
$$\frac{d^2 \psi}{dy^2} + b^2 \psi - b^4 y^2 \psi = 0.$$
What exactly are the steps we take when we "feed" $x= by$ into the differential equation? In particular, how is $\frac{d^2 \psi}{dx^2}$ related to $\frac{d^2 \psi}{dy^2}$?
Answer: See, you have to apply chain rule. $$ \frac{d\psi}{dy}=\frac{d\psi}{dx}\frac{dx}{dy}=b\frac{d\psi}{dx}$$. Similarly, we can do find out derivative again using the same method and substitute in the above differential equation.


android intent giving nullpointer exception

Question: package com.org.myOxygen.activities;

import java.util.Stack;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;

public class ApplicationTabActivityGroup extends ActivityGroup{

private static Stack<String> stack;

 @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (stack == null) stack = new Stack<String>();

    //start default activity
    push("Search Activity", new Intent(this, ApplicaitonActivity.class));

  }

  @Override
  public void finishFromChild(Activity child) {

          pop();
  }

  @Override
  public void onBackPressed()
  {

          pop();
  }

  public void push(String id, Intent intent)
  {
    Window window = getLocalActivityManager().startActivity(id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
    if (window != null) {
      stack.push(id);
      setContentView(window.getDecorView());
    }
  }

  public void pop()
  {
    if (stack.size() == 1) finish();
    LocalActivityManager manager = getLocalActivityManager();

    manager.destroyActivity(stack.pop(), true);

    if (stack.size() > 0)
    {
      Intent lastIntent = manager.getActivity(stack.peek()).getIntent();
      Window newWindow = manager.startActivity(stack.peek(), lastIntent);
      setContentView(newWindow.getDecorView());
    }
  }

}
I am getting error on line
Intent lastIntent = manager.getActivity(stack.peek()).getIntent();

The error is NullPointerException.
What might be wrong there?
edit - 1
  11-26 14:58:57.256: E/AndroidRuntime(557): FATAL EXCEPTION: main
11-26 14:58:57.256: E/AndroidRuntime(557): java.lang.NullPointerException
11-26 14:58:57.256: E/AndroidRuntime(557):  at com.org.myOxygen.activities.SearchTabActivityGroup.pop(SearchTabActivityGroup.java:59)
11-26 14:58:57.256: E/AndroidRuntime(557):  at com.org.myOxygen.activities.SearchTabActivityGroup.onBackPressed(SearchTabActivityGroup.java:36)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.app.Activity.onKeyUp(Activity.java:1888)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.view.KeyEvent.dispatch(KeyEvent.java:1061)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.app.Activity.dispatchKeyEvent(Activity.java:2068)
11-26 14:58:57.256: E/AndroidRuntime(557):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1643)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:788)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:788)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:788)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.widget.TabHost.dispatchKeyEvent(TabHost.java:275)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:788)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:788)
11-26 14:58:57.256: E/AndroidRuntime(557):  at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1667)
11-26 14:58:57.256: E/AndroidRuntime(557):  at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1102)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.app.Activity.dispatchKeyEvent(Activity.java:2063)
11-26 14:58:57.256: E/AndroidRuntime(557):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1643)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2471)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2441)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1735)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.os.Looper.loop(Looper.java:123)
11-26 14:58:57.256: E/AndroidRuntime(557):  at android.app.ActivityThread.main(ActivityThread.java:4627)
11-26 14:58:57.256: E/AndroidRuntime(557):  at java.lang.reflect.Method.invokeNative(Native Method)
11-26 14:58:57.256: E/AndroidRuntime(557):  at java.lang.reflect.Method.invoke(Method.java:521)
11-26 14:58:57.256: E/AndroidRuntime(557):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-26 14:58:57.256: E/AndroidRuntime(557):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-26 14:58:57.256: E/AndroidRuntime(557):  at dalvik.system.NativeStart.main(Native Method)

Here is the stack trace!
Comment: You probably need to update your post with the actual stacktrace.
Answer: By looking at your code I have found one reason which can create the NullPointerException and that is,
may be you are using method "public void push(String id, Intent intent)" with the same id(String) for diffrent activity.
reason why it creates null pointer exception is, when you call push method with same id(String) and Android mamory managemnt destroy the old activity associated with that name and during your pop method it returns null.
Hope this answer helps to solve bug.
Cheers,
Viraj
Answer: The javadoc states that getActivity will return

the associated Activity object, or null if the id is unknown or its
  activity is not currently instantiated

Maybe you activity is not instanciated or it has been destroyed by android.
You should then consider starting it.
Regards,
 Stéphane
Comment: well..to be honest, your point makes sense...but couldnt figure out why is it destroying the object.
Comment: activities are destroyed when the system needs memory on android. You don't decide but your program should be ready to handle this kind of cases.. It s much better to my mind than having to preoccupate about memory leaks.


Access Kafka installed on a minikube cluster on Windows 10

Question: I'm trying to install Kafka with Strimzy on a local munikube cluster running on Windows 10, to test the impact of different parameters (especially the TLS configuration). Before moving to TLS, i'd simply like to connect to my cluster :)
Here is my yaml configuration :
apiVersion: kafka.strimzi.io/v1beta1
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    version: 2.3.0
    replicas: 1
    listeners:
      external:
        type: nodeport
        tls: false
    config:
      offsets.topic.replication.factor: 1
      transaction.state.log.replication.factor: 1
      transaction.state.log.min.isr: 1
      log.message.format.version: "2.3"
    storage:
      type: persistent-claim
      size: 1Gi
  zookeeper:
    replicas: 1
    storage:
      type: persistent-claim
      size: 2Gi
      deleteClaim: false
  entityOperator:
    topicOperator: {}
    userOperator: {}

For the listener, I firstly started with plain: {} but this only gives me services of type ClusterIP, not accessible from outside minikube (i really need to connect from outside).
I then moved to a listener of kind external.
You can fin below the configuration of the cluster:
kubectl get all -n kafka
NAME                                             READY   STATUS    RESTARTS   AGE
pod/my-cluster-entity-operator-9657c9d79-8hknc   3/3     Running   0          17m
pod/my-cluster-kafka-0                           2/2     Running   0          18m
pod/my-cluster-zookeeper-0                       2/2     Running   0          18m
pod/strimzi-cluster-operator-f77b7d544-hq5pq     1/1     Running   0          5h22m

NAME                                          TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
service/my-cluster-kafka-0                    NodePort    10.99.3.204      <none>        9094:30117/TCP               18m
service/my-cluster-kafka-bootstrap            ClusterIP   10.106.176.111   <none>        9091/TCP                     18m
service/my-cluster-kafka-brokers              ClusterIP   None             <none>        9091/TCP                     18m
service/my-cluster-kafka-external-bootstrap   NodePort    10.109.235.156   <none>        9094:32372/TCP               18m
service/my-cluster-zookeeper-client           ClusterIP   10.97.2.69       <none>        2181/TCP                     18m
service/my-cluster-zookeeper-nodes            ClusterIP   None             <none>        2181/TCP,2888/TCP,3888/TCP   18m

NAME                                         READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/my-cluster-entity-operator   1/1     1            1           17m
deployment.apps/strimzi-cluster-operator     1/1     1            1           5h22m

The IP address of the minikube cluster is 192.168.49.2 (given by minikube ip)
For the while, is everything correct on my configuration ? I cannot connect on the cluster with a producer (i get a timeout error when i try to publish data).
I tried to connect to 192.168.49.2:32372 & 192.168.49.2:30117 and I always get the same timeout error. I also tryed to run

minikube service -n kafka my-cluster-kafka-external-bootstrap

and

minikube service -n kafka my-cluster-kafka-0

and i still get the same error.
What is wrong in what i'm trying to do?
Thanks!
Comment: If you're trying to connect from CMD/powershell, you'll need to forward ports out of the hypervisor using netsh commands
Comment: I'm connecting from a java application (actually i've a java producer and a java consumer).

I never used netsh. Should I use it like this : netsh interface portproxy add v4tov4 listenaddress=127.0.0.1 listenport= connectaddress= connectport=32372 ?

And then use 127.0.0.1: on my producer ?
Comment: try localhost:32372 0r 127.0.0.1:32372 , without doing additional changes
Comment: Some command like that, if you don't run the java code from WSL2 terminal, yes. You might have more luck containerizing the java applications and deploying to the cluster using the jkube maven plugin, for example. Your apps are meant to run in the cluster, anyway, right, not always external?
Comment: Actually yes my app will run inside the cluster. I wanted to make the exercise from outside the container to make sure i understand how minikube works. Thanks for the explanation, I don't have my code anymore with me, I'll try to finish this on monday. If I cannot, I'll deploy my app in the cluster.
Comment: Ok, I got it. I changed the type of the service to LoadBalancer and started "minikube tunnel".
Then I can access the cluster at 127.0.0.1:9094 (127.0.0.1 is the external IP of the minikube cluster).
Answer: Ok, I got the answser.
I changed the type of the service to LoadBalancer and started minikube tunnel
One other point, as I'm running this on windows, I noticed that if I run everything using powershell it works, if I used an other command line tool (like Moba) it does not work, I don't explain this.


D7: file_create_url() usable in node.tpl.php?

Question: Can you use file_create_url() inside node.tpl.php? Should I assume you can only use it in the template.php?
$img_src = render($content['field_image']);
$bgimage = file_create_url($img_src);

Using the following code, I am only getting public://science-of-rock_background.png from $img_src.
Is there any reason why it would be blank?
print $img_src;
print $bgimage;

Edit made to avoid confusion:
In my tpl page for this field I am generating the uri.
field--field_image.tpl.php
<?php foreach ($items as $delta => $item) : ?>
  <?php
  print $item['#item']['uri'];
  ?>
<?php endforeach; ?>

Answer: file_create_url takes a uri, such as public://science-of-rock_background.png
The revised:
$img_src = $content['field_image'];
$bgimage = file_create_url($img_src);
Would work if your field is only returning the URI.
And, for best practices, should set that up in preprocess_node, otherwise will work in node.tpl.php
Comment: The content of the field is available as `$field_image`; `$content['field_image']` is always a rendering array, which is not what the OP wants.
Comment: The file's URI is available within the render array, and the code was shortened based on OP stating: I am only getting public://science-of-rock_background.png from $img_src
Comment: Sure, it is available, but you need to access it more directly than with `$content['field_image']`. It is then an error to use the render array when the field content is already available.
Comment: And you are completely correct. Was trying to keep in context of original post - I know this is exactly how i started, and then moved into proper format
Answer: I'd first suggest to dpm($img_src)  -- You'll need the devel module for that to work. See what is actually inside that field. It's odd that it would be a file path though.
I'd never put logic like that inside a template file anyway. Use a preprocess function anyway:
template_preprocess_node(&$variables) {

}

inside template.php (replace template with your theme name)
Comment: Interesting. Silly question. How would I directly pull the field into this? render($content['field_image']); doesn't work. Would it be the full array?
Comment: Another question, on using dpm(). Can you 'only' use it in a function in the template.php?
Comment: (Cliché -- there are no silly questions!)
The field values will be inside that $variables array. Use dpm($variables) and hopefully you'll see a yellow box that contains the values of that array.

2. You can use dpm anywhere there is a messages region in your theme. An alternative is kpr. That basically does the same thing but injects the debug text at the top of the page.
Comment: Got it. 1 and 2 both worked. Thanks a ton for the help!
Answer: The error is that render() returns HTML output, while file_create_url() is expecting a URI or a file path. In node.tpl.php, the content of a field is available as variable; so, the field you are trying to access is available as $field_image, basing on the following note.

Field variables: for each field instance attached to the node a corresponding variable is defined; for example, $node->body becomes $body. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language; for example, $node->body['en'], thus overriding any language negotiation rule that was previously applied.


What are the venues where FC Barcelona used to play in its early days?

Question: I was reading about history of Camp Nou on the official website of FC Barcelona. First paragraph reads:

In the early days, the club constantly switched between different grounds. In the second stage, the club was consolidated by finding a permanent home at Les Corts. And the third stage, and the construction of the Camp Nou, reflects the expansion and grandeur of the club on a global scale.

Searching on the web found only two venues Camp de la Indústria and Camp de Les Corts before Camp Nou. As the website says they switched between different grounds before construction of Les Corts.
What are the other venues where FC Barcelona used to play in its early years of existence?
Answer: The three stadium Camp de la Indústria, Camp de Les Corts, and Camp Nou are the major ones but before FC Barcelona moved to Camp de la Indústria in 1909 they played in five different stadiums. Those five stadiums were Velódromo de la Bonanova, Campo del Hotel Casanovas, Campo de la Plaza de las Armas, Campo de la Carretera de Horta, Campo de la Calle Muntaner.
Source: estadiosdeespana.com


How do modern performers harmonize Hindustani classical music?

Question: Interested to know how modern performers harmonize Hindustani classical music. Like, I heard a beautiful piano performance in Raga Shuddh Sarang. Was wondering what would be the left hand playing - what kind of chords, or arpeggios, notes etc? Is there any contrapuntal concept?
Any practitioner's perspective with some easy examples, in ragas like Bhairavi, Yaman, etc?
Comment: Interested in the fundamentals. Didn't understand the meaning of "style".
Comment: Are you more interested in style or in the actual harmony/theory used to generate the accompaniment?
Answer: A lot of my answer will be gross simplification and please take it with a grain of salt. There are notable counterexamples here.
So the closest thing to harmonization in a raga is a concept called melharmony. https://en.wikipedia.org/wiki/Melharmony
An extremely simple example of melharmony (and this is a really special case), you could just play thirds from a given note (much like how you harmonize a major scale, Shankarabaranam in carnatic and the bilawal thaat in hindustani) while you play the melody.
The important thing to understand about melharmony is that unlike most of western harmony (where harmony dictates a framework on which melodies are played like say bebop improvisation), melharmony inverts the role (the melody is the driving force and the harmonization is an enrichment, similar to how chord melodies are constructed in jazz).
While counterpoint is possible, its was not the original intent of melharmony and was later added in by Western Composers (notably Robert Morris).
Its important to note that melharmony is avant garde music. In the more classical traditional sense, harmony (at least harmonic motion) is non existent in both forms of Indian classical music.
There are more adhoc treatments of harmony. For instance if you play on a raga from the Bilawal thaat (aka the major scale) or the Asavari thaat (aka the minor scale) all the theory of functional harmony should be accessible.
Comment: There are at least three YouTube channels/playlists devoted to Melharmony, including both performances and lectures: [Melharmony Music](https://www.youtube.com/channel/UCPUa1JeaTa0lnl0FxvGNp2w), [Melharmony playlist](https://www.youtube.com/playlist?list=PLIHLvSncfsVVGXPy5ZC299xW_HIFvzqYu), and [Sangeeta Rasika](https://www.youtube.com/channel/UCe6w44KRB9WZ4XAJ-FL4KDw)
Answer: The following can be said to be the typical left hand patterns:
To generate the chikari effect in alap, jod and jhala, and even in the later sections.
Watch here how the left hand is harmonizing the reference notes
Use in melodic sections by completing the melody with both hands. Even if one distant note comes from the left hand, it can bring some relief to the right hand, especially if the right hand wants to move in the opposite direction. Watch here how both hands are participating in the melodic patterns
For speedy completion of long taans spanning multiple octaves.
To double up the sound by playing exactly the same notes that the right hand plays. Watch here how notes are doubled up
Left hand is being used quite commonly on the organ accompaniment in Natya Sangeet. Watch here how
Comment: A notation sample may be helpful. At least for other site visitors - like myself - who are not familiar with the specifics like chikari, taan, etc.
Comment: .. will add pointers into youtube links to visually see some of these at work. Hope that will do. Otherwise to explain in detail and to add scores or notations, it will require a much longer article.
Comment: Neither chikari nor taans are examples of western harmonies. A chikari say on a standard sitar would be tuned to either D or C# major (or some tonic in between with its third and fifth) and only that chord. There is no harmonic motion. A taan is a virtuosotic melodic style of playing sections of a performance of a raga (in the sense its still melodic and does not represent harmonic motion). Plus this answer is centered on specific instruments like Sitar or Sarod, and theory is decoupled from instruments (i.e it independently exists outside of instrumental context).
Comment: Khalian, didn't get you. Did you see those links which are about piano not sitar. There are common instrumental techniques which can be adapted into one another. In vocal concerts, a harmonizing instrument (harmonium!, sarangi, violin etc) is used mainly to track what the vocalist sings and improvises. In instrumental solo classical music, you hardly have any harmonizing accompaniment (except for "duets"). So the harmony comes from some of these instrumental techniques.


Circular trajectory speed

Question: An object moves clockwise around a circle centered at the origin with radius 5m begnning at the point (0, 5).  Find a position function $\vec{r}$ that describes the motion if it occurs with speed $e^{-t}$
My attempt:
I know that $r(t) = (5\sin t, 5\cos t)$ for the general path of the function.  But I don't know exactly how I would change the speed of the function.
All I know is its going to result in changing the function sin and cos from $f(t)$ to $f(g(t))$.
Answer: Ok ill give it a go, but I might be misinterpreting. The particle in question can be described by the vector function $\mathbf{r}(\theta(t)) = (x,y) = [5\cos \theta(t), 5\sin \theta(t)]$ where $x,y$ are the coordinates in the plane, $\theta$ is the angle position of the particle at a particular time.
\begin{align}
\frac{d\mathbf{r}}{dt} = \left( -5\frac{d\theta}{dt}\sin \theta(t), 5\frac{d\theta}{dt}\cos \theta(t) \right)
\end{align}
The speed is the magnitude of this vector which is easily simplified using basic trig to $|\frac{d\mathbf{r}}{dt}| = |5\frac{d\theta}{dt}|$ which equals $e^{-t}$ according to you. Hence $\theta(t)= C+\frac{e^{-t}}{5}$ in the equation above. I believe this is consistent with the fact that the particle is slowing down as it moves clockwise around the circle. Now we must find the value of $C$ using the initial condition that at $t=0$, $y = 5$. Hence we require that $\theta(t=0) = \pi/2$ which means that $C = \pi/2 -1/5$.

Circular trajectory speed


Followup: HP System Management Email manager

Question: A follow up question from this:
HP System Management Email notification Linux
How can I receive emails from the server? Is there some software that allows you to receive, sort and filter these emails making it easy to pick up emails from many servers, either web based or client based?
Answer: Yes, you can use an established email address with a standard email client like Microsoft Outlook, Mozilla Thunderbird, Apple Mail or even Eudora. This software will receive the incoming mail from the servers to your inbox and allow you to sort and filter by date, subject, etc.
The alert messages from these servers aren't frequent. You should direct them to an email address or (ideally) distribution group that people will actually check regularly.
A typical message from an HP server looks like:
<code>To: <firstname.lastname@example.com>
Subject: HP Insight Management Agents Trap Alarm

Trap-ID=3046

Physical Drive Status Change: Slot 0 Port 1I Box 1 Bay 1.
Status is now Failed.
</code>


Definindo parametros e filtrando arquivo .TXT

Question: Tenho um arquivo com separador | em arquivo .txt, gostaria de transformá-lo em arquivo .xls e então trabalhar com ele por meio de filtragem e substituição de valores em python3.
E possível ?!
Segue um modelo do arquivo ".txt":
|0000|005|0|||01072019|31072019|MODELO|15684294000195|SP|5107040||00|2|
Comment: Você pode utilizar a biblioteca pandas para fazer isso. Não seria preciso mudar o tipo do arquivo para realizar filtros e tudo mais, só no final você iria escolher a saída.
Answer: Para trabalhar com dados tabulados você pode utilizar a bibliotecas pandas.
utilize o comando abaixo para instala-la, caso não tenha.
python3 -m pip install --upgrade pandas

E como um exemplo:
import pandas as pd

tabela = pd.read_fwf("seuArquivo.txt", delimiter="|")
tabela.to_excel('salvarArquivo.xlsx', 'Sheet1')

Comment: Obrigado Murilo, o que me diz de jogar uma formula de EXCEL no script para que ao converter o arquivo .TXT ja vir editado no arquivo output ?
Comment: @IvanAlmeida não entendi, vc fala de colocar uma formula no seu arquivo txt, assim na hora que converter para planilha já vir com a fórmula? É uma boa ideia, eu particularmente nunca precisei utilizar assim, na teoria da certo, você poderia fazer um teste! Obs: se a resposta lhe ajudou não esqueça de marcar como correta para ajudar outras pessoas com a mesma dúvida
Comment: Segue o passo a passo que eu faco sem o script.
Comment: 1 - Importo o arquivo .TXT para o EXCEL definindo o delimitador " | " . 2- Verifico informacoes que nao sao relevantes no arquivo convertido para EXCEL. 3- Apos a indentificacao utilizo formula no excel para subistituir por dados que sao relevantes. 4-Salvo o arquivo e envio para um sistema de validacao no qual verificara se esta no formato adequado de leitura e compilacao. 5- Acaso esteja, ele aceitara e validara sem erros. OBS: Desculpas a acentuacoes, utilizo teclado em modo USA e desculpas por ter esquecido de marcar como correta !
Comment: Sendo assim, como e padrao Murilo gostaria que o script em Pyhton fizesse isso de forma automatica sem precisar ficar exportando/importando. Convertesse, Editasse, Verificasse se a dados invalidos (se houver, subistituisse por dados validos [ que eu acrecentaria ] utilizando a formula que tenho), e apresentasse no arquivo de saida. Se possivel Murilo qualquer ideia e valida. Obrigado !
Comment: Obs: Nao precisa ser necessariamente em Python : )
Comment: @IvanAlmeida entendi, da pra procurar por esses dados inválidos e já tratar antes de converter para Excel, mas para criar essa validação precisaria que você passasse um exemplo dos dados inválidos e pelo que você os substituí
Answer: Existem algumas maneiras de fazer parsing em arquivos, e cada uma funciona para uma finalidade.
i. A mais simples é user o open, que é nativo do Python.
my_file = []
openfile = open('file.txt')
lines = openfile.readlines()
for i in  lines:
    temp = i.split(sep="|")
    my_file.append(temp)

**O método readlines é muito bom porque retorna um chunk com todas as linhas, a partir daí você pode transformar em lista ou qualquer outro tipo. Se for um arquivo grande, você vai precisar ler as linhas uma a uma.
ii. Outra opção é usar o Numpy, que retorna um array, que possibilita várias funcionalidades no que diz respeito a manipulação de números.
import numpy as np
my_np_file = np.loadtxt('file.txt',delimiter = '|', dtype=str)

iii. Uma terceira seria o Pandas, que já foi descrito acima. Ele é muito bom pois você pode trabalhar com séries temporais e indexação de linha e coluna.
**O Numpy e o Pandas tem problemas com arrays muito grandes(~ > 2gb ), então se esse for o caso, possivelmente você tenha que escolher entre outras soluções mais específicas para esse tamanho de arquivo.
Comment: Obrigado David, o que me diz em manipular para que fique em arquivo EXCEL e no script python jogar uma formula de EXCEL para que seja editado assim que convertido ?
Comment: Cara. Eu diria pra você ficar com o python enquanto puder. Se você for mexer com o Excel mesmo, compensaria tu usar VBA. Notadamente, há uma curva de aprendizado usando o Python pra fazer essas, coisas. No entando, usando o excel no meio tu vai (i)Quebrar o fluxo de tarefas(se precisar refazer vai ser chato) e (ii)Deixar de usar as ferramentas do Python, que são muito eficientes pra isso. Se a curva de aprendizado for um problema, eu recomendo tu usar o debugger do spyder. Ele tem inspeção de variáveis, e poupa bastante paciencia pra quem ta desenvolvendo esse tipo de código procedural.


Java spring-mongo-data Mongodb query for group and projection logic

Question: I have below 3 sample records:
    {
      "_id" : "0cc5c468-2105-11ee-ad68-15d467e62by4d",
      "storeId" : "3070",
      "paymentType" : "cash",
      "total" : {"$numberDecimal": "100"}
    },
{
      "_id" : "1111111-2105-11ee-ad68-15d467e62by4d",
      "storeId" : "3070",
      "paymentType" : "cash",
      "total" : {"$numberDecimal": "100"}
    },
    {
      "_id" : "0cc5c468-2105-11ee-ad68-15d467e62by4d",
      "storeId" : "3070",
      "paymentType" : "creditCard",
      "total" : {"$numberDecimal": "50"}
    }

I am trying to write some grouping and projection logic in which the desired output from above sample data should be as below:
StoreId | Cash Payment | Card Payment | Total Amount Cash + Card
3070        200               50                250

The last column can ofcourse be ignored but i need this kind of output from mongodb in java.
I have tried many things and below is the code I have so far which is not giving desired output, it gives me two separate records for card payment and cash payment types.
GroupOperation groupingLogic() {
        return group("storeId", "paymentType")
                .first("storeId").as("storeId")
                .first("paymentType").as("paymentType")
                .sum(TOTAL).as(TOTAL);
    }

I am not sure how to get output as expected above with java mongodb code .
Please someone help.
Answer: Explanation:

We need to group by 2 parameters (storeId + paymentType) and sum paymentType's total amount.
We sum total amount for all paymentTypes for each storeId.
We need to use $arrayToObject to pivot each paymentType into field.
With other operators we assamble expected result.

{
   "Total Amount": NumberDecimal("250"),
   "cash": NumberDecimal("200"),
   "creditCard": NumberDecimal("50"),
   "storeId": "3070"
}

Note: cash, creditCard, check, etc. are dynamically filled. If any storeId has no such payment types, these fields may not be there.
Try this one:
db.collection.aggregate([
  {
    $group: {
      _id: {
        storeId: "$storeId",
        paymentType: "$paymentType"
      },
      total: {
        $sum: "$total"
      }
    }
  },
  {
    $group: {
      _id: "$_id.storeId",
      paymentType: {
        $push: {
          "k": "$_id.paymentType",
          "v": "$total"
        }
      },
      "total": {
        $sum: "$total"
      }
    }
  },
  {
    "$replaceWith": {
      "$arrayToObject": {
        "$concatArrays": [
          "$paymentType",
          [
            {
              "k": "storeId",
              "v": "$_id"
            },
            {
              "k": "Total Amount",
              "v": "$total"
            }
          ]
        ]
      }
    }
  }
])

MongoPlayground
Java - complex aggregation pipeline
private static AggregationOperation replaceWith() {
    return ctx -> Document.parse("{" +
        "'$replaceWith': {" +
            "'$arrayToObject': {" +
                "..." +
            "}" +
        "}"+
    "}")
}

Comment: thanks, the mongo query works as expected but I didnt understand what to do with this replaceWith() java function. Should I just paste the entire replace block from mongo query inside this? Or is there any better way to use if we are using spring-data-mongo ?
Comment: @jarvo69 Yes. Instead of translating each agregation pipeline to Spring data syntax (which is horrible for the complex queries), just parse them as JSON with `Document.parse()` method.
Comment: What about this one?

`{
    $group: {
      _id: "$_id.storeId",
      paymentType: {
        $push: {
          "k": "$_id.paymentType",
          "v": "$total"
        }
      },
      "total": {
        $sum: "$total"
      }
    }
  },`

how do i add this one in java? Can you please provide java equivalent for the same?
Comment: @jarvo69 Sure. `private static AggregationOperation group1() {return ctx -> Document.parse(put here 1st pipeline)}`, `private static AggregationOperation group2() {return ctx -> Document.parse(put here 2nd pipeline)}`, etc.
Answer: If you want to group and add up some data from your MongoDB collection. Here's how you can do it using Java with Spring Data MongoDB:
If You want to group the data by the "storeId" and sum the amounts for different payment types ("cash" and "creditCard"). Here's how you can do that:
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.query.Criteria;

// ...

GroupOperation groupingLogic() {
    return Aggregation.group("storeId")
        .sum(
            ConditionalOperators.when(Criteria.where("paymentType").is("cash")).then("$total.$numberDecimal").otherwise(0)
        ).as("cashPayment")
        .sum(
            ConditionalOperators.when(Criteria.where("paymentType").is("creditCard")).then("$total.$numberDecimal").otherwise(0)
        ).as("cardPayment")
        .sum("$total.$numberDecimal").as("totalAmountCashCard");
}

To show in your format. Here's how you can do that:
import org.springframework.data.mongodb.core.aggregation.ProjectionOperation;

ProjectionOperation projectionLogic() {
    return Aggregation.project()
        .and("storeId").as("StoreId")
        .and("cashPayment").as("Cash Payment")
        .and("cardPayment").as("Card Payment")
        .and("totalAmountCashCard").as("Total Amount Cash + Card");
}

Putting It All Together:
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class YourService {

    private final MongoTemplate mongoTemplate;

    public YourService(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    public List<YourOutputType> getGroupedData() {
        Aggregation aggregation = Aggregation.newAggregation(
            groupingLogic(),
            projectionLogic()
        );

        return mongoTemplate.aggregate(aggregation, "yourCollectionName", YourOutputType.class).getMappedResults();
    }
}

Remember to replace yourCollectionName with the actual name of your MongoDB collection and YourOutputType with the appropriate class that matches the expected output.
Comment: but hardcoding `.is("cash")` and `.is("creditCard")` is not desirable. tomorrow there could possibly be more types of payment options then we will again need to add more conditions right?
Comment: getting error "field name cannot start with $"


Trying to scrape the entire content of a div

Question: I have this project i'm working on and id like to add a really small list of nearby places using facebooks places in an iframe featured from touch.facebook.com I can easily just use touch.facebook.com/#/places_friends.php but then that loads the headers the and the other navigation bars for like messges, events ect bars and i just want the content.
I'm pretty sure from looking at the touch.facebook.com/#/places_friends.php source, all i need to load is the div "content" Anyway, i'm extremely new to php and im pretty sure what i think i'm trying to do is called web scraping.
For the sake of figuring things out on stackoverflow and not needing to worry about authentication or anything yet i want to load the login page to see if i can at least get the scraper to work. Once I have a working scraping code i'm pretty sure i can handle the rest. It has load everything inside the div. I've seen this done before so i know it is possible. and it will look exactly like what you see when you try to login at touch.facebook.com but without the blue facebook logo up top and thats what im trying to accomplish right here.
So here's the login page, im trying to load the div which contains the text boxes to login the actual login button. If it's done correctly we should just see those with no blur Facebook header bar above it.
I've tried
<?php
$page = file_get_contents('http://touch.facebook.com/login.php');
$doc = new DOMDocument();
$doc->loadHTML($page);
$divs = $doc->getElementsByTagName('div');
foreach($divs as $div) {
      if ($div->getAttribute('id') === 'login_form') {
         echo $div->nodeValue;
    }
}
?>

all that does is load a blank page.
I've also tried using http://simplehtmldom.sourceforge.net/
and i modified the example basic selector to
<?php
include('../simple_html_dom.php');

$html = file_get_html('http://touch.facebook.com/login.php');

foreach($html->find('div#login_form') as $e)
    echo $e->nodeValue;

?>

I've also tried
<?php
$stream = "http://touch.facebook.com/login.php";
$cnt = simplexml_load_file($stream);

$result = $cnt->xpath("/html/body/div[@id=login_form]");

for($i = 0; $i < $i < count($result); $i++){
    echo $result[$i];
}
?>

that did not work either
Comment: I could imagine this data to be available in JSON over FB's Graph API which would save you the scraping. Have you checked the API docs yet?
Comment: I thought about it, but I'm really hellbent on figuring this idea out. I've seen it done before and i really liked the result.
Answer: $stream = "http://touch.facebook.com";
$cnt = simplexml_load_file($stream);

$result = $nct->xpath("/html/body/div[@id=content]");

for ($i = 0; $i < count($result); $i++){
    echo $result[$i];
}

there was a syntax error in this line i removed it now just copy and paste and run this code
Answer: Scraping isn't always the best idea for capturing data else where.  I would suggest using Facebook's API to retrieve the values your needing.  Scraping will break any time Facebook decides to change their markup.
http://developers.facebook.com/docs/api
http://github.com/facebook/php-sdk/
Answer: Im assuming that you can't use the facebook API, if you can, then I strongly suggest you use it, because you will save yourself from the whole scraping deal.
To scrape text the best tech is using xpath, if the html returned by touch.facebook.com is xhtml transitional, which it sould, the you should use xpath, a sample should look like this:
$stream = "http://touch.facebook.com";
$cnt = simplexml_load_file($stream);

$result = $nct->xpath("/html/body/div[@id=content]");

for ($i = 0; $i < $i < count($result); $i++){
    echo $result[$i];
}

Comment: what you're saying makes sense. I changed a few typos and spaces,but i get this error Parse error: syntax error, unexpected '<' on line 7. I'm not exactly sure what's going on in that part to really make any adjustments.
Answer: You need to learn about your comparison operators
=== is for comparing strictly, you should be using ==
if ($div->getAttribute('id') == 'login_form')
{

}


Can an amplifier with only one output be wired in parallel?

Question: I have a Peavey ValveKing 20MH amp which has a single output jack for connecting it to a cabinet.  I'm exploring my options for cabinets and am trying to understand if I can consider running cabinets in parallel or if I'm limited to running them in series.
Can I split a single output to run two cabinets in parallel, or will I need to run them in series?
Comment: It doesn't matter. These are cone diameters, not voice coil impedances, which is what's important.
Comment: fyi - my plan is to run a 1x12 and a 1x10 cabinet, just in case you're wondering
Answer: It depends on the load requirements of the amplifier and the impedances of the speakers, neither of which you have specified.
If the amplifier has a 4 ohm output transformer tap, or it is solid state and well-specified into a 4 ohm load, you can put 2 x 8ohms or 4 x 16ohms in parallel.
Similarly if you have 2 x 16ohm speakers you can put them in parallel off the 8 ohm tap.
If you don't know any of these numbers, put the speakers in series.
If you have 4 speakers you should put them in series-parallel (two pairs of 2 parallel speakers with the pairs in series) so they present the same impedance as one speaker would.
Comment: It should be noted that two speakers in series will actually be _quieter_ than each of them alone. Also, whereas increasing the speaker impedance is always safe for solid-state amps, I don't think this is true for tube power stages; at any rate these are reported to suffer damage when operated _without_ load; too high impedance, even if it doesn't cause harm, can quite possibly mess up transmission properties of the power stage. So... it's rather not a good idea to put two or even more speakers in series, if you don't know the specs. Bottom line: you should _always_ know the specs...
Comment: Absolutely. I should have made it clearer that you should only operate a valve amplifier into an impedance corresponding to the selected output transformer tapping.
Answer: A Peavey ValveKing 20MH amp has a speaker output impedance switch which allows selection of either 16Ω or 8Ω speaker/cabinet impedances with 8Ω max on the 20MH.
If you are considering wiring more than two speakers to the amplifier, you need to concern yourself with your amplifier's ability to handle low impedance loads. If you ignore the way you wire them together you can damage the amplifier
Adding speakers in series increases the overall resistance of the circuit.
Zt =Za+Zb
8Ω speakers
Zt = 8Ω + 8Ω
Zt = 16Ω

Use 16Ω setting
Adding Speakers in parallel decreases the overall resistance of the circuit.
Zt =1(1/Za+1/Zb)
16Ω speakers
Zt =1(1/16Ω+1/16Ω)
     = 1(1/8Ω)
Zt = 8Ω

Use 8Ω setting
As long as you're careful with output impedance you can run an 20 watt amp though any drivers greater than 20 watt. This will alows you to extend your clean headroom a bit, but any overdrive will be strictly from the natural tube amp breakup, your attack or your pedals.
Answer: Do not wire different speakers in series.  The sound output of a speaker is specified with respect to its driving voltage, and speakers' impendance tends to vary wildly over its frequency range.  The only thing you know is that it will not undercut its nominal impedance by more than 20%.
The amplifier is called "Valve King".  Why?  Valve power amplifiers don't actually have zero output impedance (which is the equivalent circuitry for a solid state amp: this does not mean that solid states can drive even 2Ohm speakers reliably but merely that as long as they do not break down, their output voltage will be unimpressed by the load).
Now I am totally guessing here, but the name suggests that the amplifier is from a time where tubes were special.  That could mean that it only uses a preamp tube but has a solid state power amp.  In that case, you would connect cabinets in parallel, making sure that the combined impedance is not lower than what the amplifier can work with.  Putting 3 cabinets with 8 Ohm in parallel leaves you with 8/3 Ohm impedance, so it's 2.7Ohm.  You need a 2 Ohm setting for accommodating that safely.
If your power amp stage is indeed tube, many bets are off.  You then really want to connect a cabinet intended to match that particular amplifier.
Comment: You don't have to guess. ValveKings are still made by Peavey and they are 100% tube, so they do not have solid state power amps, they have tube power amps. Also, tubes are **still special**, which is why 100% tube designs are still be developed and manufactured by most amp manufacturers.
Comment: The sound output of a speaker is specified with respect to its driving *power*. Never seen one that wasn't, in 50 years. You don't know any such thing as the 20% margin you mention. Some speakers dip far more than that.


Proving $\forall s\in\mathbb{N},(\exists x \in\mathbb{N},s^2=3x)∨(\exists y\in\mathbb{N},s^2=3y-2)$

Question: I'd like to prove the following statement:

$\forall s\in\mathbb{N},(\exists x \in\mathbb{N},s^2=3x) \lor (\exists y\in\mathbb{N},s^2=3y-2)$

One approach which is most likely wrong that I have attempted was to split $s$ into odd and even numbers; $s=2k$ or $s=2k+1$
Any help would be appreciated.
Comment: This seems wrong: what about $s=2$?
Comment: Oh, my mistake, I'll fix that right away!
Comment: So what you want to prove now is that if you square any natural number the result is either $0$ or $1$ modulo $3$. Are you familiar with modular arithmetic?
Comment: Unfortunately no. Is it necessary for this proof?
Comment: No, it just makes it real easy. The key to doing this is, for any $s\in\Bbb N$, you can write $s=3k$ or $s=3k+1$ or $s=3k+2$ by the division algorithm. If this makes sense to you, then you're basically done: just square each case and see if you can write them in the form $3x$ or $3y-2$.
Comment: What is the division algorithm and would that be something I need to prove as well? Sorry, I'm still relatively new to proofs as a whole.
Comment: @Dave $2^2= 3\cdot 2-2$  [edit: oh, the statement has been modified since your comment; disreguard[
Comment: @GrahamKemp My original statement had it as $s$ instead of $s^2$, sorry about that.
Comment: The division algorithm is pretty basic, and I think it would be assumed known for this proof. Essentially, you're taking any integer $s$ and dividing it by $3$ to get a quotient $k$ and remainder $r$, i.e. you're writing $s=3k+r$ with $0\leq r<3$. So we must have $r=0,1,$ or $2$. I assume you know about remainders with integer division?
Comment: Haha, yes. And thanks for all the help! I think I'll be able to handle the rest.
Comment: Happy to help. When you complete your solution you're allowed to post it as an answer to your own question, and then you can accept the answer if you want (and if there's no other answer you want to accept) just to close off the question.
Answer: We want to show
$\forall s\in\mathbb{N},(\exists x \in\mathbb{N},s^2=3x) \lor (\exists y\in\mathbb{N},s^2=3y-2)$
Note that every natural number $s$ is either $s= 3k$ or  $s=3k\pm 1$
In the first case let $$s^2=9k^2 = 3(3k^2)=3x$$ and in the second case $$s^2=9k^2\pm 6k+1$$ thus $$ s^2+2=9k^2\pm 6k+3=3(3k^2 \pm 2k+1)=3y$$
that is $s^2 =3y-2$
Answer: You can't prove the statement, since it's false.  You have tried to split the natural numbers into those divisible by 3 and those congruent to 1 (same as -2) mod 3, but you've left out those congruent to 2 mod 3.  Thus, s = 2, 5, 8, etc., are all counter-examples to your statement.
Comment: Yea, sorry about that, I made an edit just now.
Answer: The statement  $$   \forall s\in\mathbb{N},(\exists x \in\mathbb{N},s=3x) \lor (\exists y\in\mathbb{N},s=3y-2) $$                   is not true.
For example for  $s=5$ you can not find an $x\in \mathbb{N} $ such that $5=3x$ nore you can find a  $y\in \mathbb{N} $ such that $5=3y-2$
Comment: This proof works for your unedited version.