Create a rectangle based on user's character input

Question: I have to write a program in C (which I'm new in) so that the user enters the number of lines and columns and the character they want to display as the rectangle, for example, a 6 lines and 6 columns asterisk rectangle.
Here is the assignment in detail.

The first thing your program will do is print a menu of choices for
the user. You may choose your own version of the wording or order of
choices presented, but each choice given in the menu must match the
following:A function that prompts the user to enter a single
character. The return value of the function be a char and will return
the character value entered by the user.This return value will be
stored in a local variable, C, in main(). The initial default value of
this character will be ' ' (blank or space character).
A function that prompts the user to enter a numerical value between 1
and 15 (inclusive). If the user enters a value outside this range, the
user is prompted to re-enter a value until a proper value is entered.
The return value of the function be an int and will return the value
entered by the user. This return value will be stored in a local
variable, N, in main(). The initial default value of this character
will be 0.
Two "Print Rectangle" functions. Each function will take the current
integer value N and character value C as input parameters. The return
values of these functions will be void. The functions will print
rectangles of N lines and columns using the input character C. The
Border Only function will print the rectangle with the just the
border. The Filled In function will print the rectangle as a solid
rectangle. For example, if the integer value N = 6, and the character
value C = '*' and the Filled In type is called, the following
rectangle will be printed:

Here is my code so far. What I am doing wrong and am I coding the program correctly?
       #include <stdio.h>
       #include <stdlib.h>

       char enterSingleChar();
       int enterNumValue();
       void printRectanlgeOne(int N, char C);
       void printRectangleTwo(int N, char C);

     int main()
    `enter code here`{
        char userChoice;
        int N = 0;
        char C = ' ';

        fprintf(stdout, "Please choose one of the following choices below \n");
        fprintf(stdout, "Enter/Change Character (C/c)\n");
        fprintf(stdout, "Enter/Change Number (N/n) \n");
        fprintf(stdout, "Print Rectangle Type 1 (Border Only), enter 1 \n");
        fprintf(stdout, "Print Rectangle Type 2 (Filled in), etner 2 \n");
        fprintf(stdout, "Quit Program (Q/q) \n");

        scanf("%c", &userChoice);

        switch(userChoice)
        {
                case 'C':
                case 'c':
                        enterSingleChar();
                        break;
                case 'N':
                case 'n':
                        enterNumValue();
                        break;
                case '1':
                        printRectangleOne(N,C);
                        break;
                case '2':
                        printRectangleTwo(N,C);
                        break;
        break;
                case 'Q':
                case 'q':
                        fprintf(stdout, "The program will now quit\n");
                        exit(1);
                default:
                        break;
        }
}

char enterSingleChar()
{
        char singleChar = ' ';
        fprintf(stdout, "Please enter a single character \n");
        scanf("%c", &singleCharC);
        return singleChar;
}

int enterNumValue()
{
        int numValue;
        fprintf(stdout, "Please enter a numerical value between 1 and 15 inclusively \n");

scanf("%d", &numValue);

        while(numValue <= 1 || numValue >= 15)
        {
                fprintf(stdout, "You have entered an invalid num \n");
                fprintf(stdout, "Please try again \n");
                fprintf(stdout, "Please enter a numerical value between 1 and 15 inclusively \n");
                scanf("%d", &numValue);
        }
        return numValue;
}

void printRectangleOne(int N, char C)
{
        int i;
        int j;
        for(i = 0; i <= N; i++)
        {
                fprintf(stdout, &C);

                for(j = 0; i <= N; i++)
                {
fprintf(stdout, &C);
                }
        }
        printf();
}

void printRectangleTwo(int N, char C)
{

}

Comment: So, what is your specific problem?
Comment: In printRectangleOne function, look at the second loop: for(j = 0; i <= N; i++)
 There is a mix of j and i
Comment: How do the variables `C` and `N` ever change?
Comment: `fprintf(stdout, &C)`? Didn't your compiler warn you about that?
Answer: Use your compiler
If you try and compile that code with all warnings enabled, it starts spewing out errors which you should correct before going on:

test.c:10:5: error: stray '`' in program
     `enter code here`{
     ^
test.c: In function 'main':
test.c:10:6: error: unknown type name 'enter'
     `enter code here`{
      ^

And:

test.c: In function 'main':
test.c:34:25: warning: implicit declaration of function 'printRectangleOne' [-Wimplicit-function-declaration]
                         printRectangleOne(N,C);
                         ^
test.c: In function 'enterSingleChar':
test.c:53:22: error: 'singleCharC' undeclared (first use in this function)
         scanf("%c", &singleCharC);

Check your input
One problem that I can see is that when using scanf to read from standard input, also the Enter key will be put in the queue.
So you are asked,
Enter one character:
Enter another character:

and you type:
A Enter B Enter
and you expect the two characters to be A and B. What is really in the input queue could be, depending on platforms (I'm not sure):
A\r\nB\r\n  (*six* characters!)
A\nB\n      four characters
A\rB\r      four characters

Also, if you use one of those spurious characters (e.g. "\n", which is newline) to draw a 3x3 rectangle around the character "C", you will actually send to the output three empty lines (the top row), one empty line (the left border of the central line), a "C", and another four empty lines.
Which can be quite puzzling.
You do not state in your question what your problem actually is, but check your input routines, should any of the above symptoms make itself known.
Other problems
void printRectangleOne(int N, char C)
{
        int i;
        int j;
        for (i = 0; i <= N; i++)
        {
                // Why do you output this C here?
                fprintf(stdout, &C);
                // You are checking and incrementing i here, not j.
                for(j = 0; i <= N; i++)
                {
                     // fprintf does not work this way. Use
                     // putchar(C);
                     // instead.
                     fprintf(stdout, &C);
                }
        }
        // I don't think this is going to work. Use either
        // putchar('\n') or printf("\n") to get a newline.
        printf();
}

Answer: I suggest an iterative approach. If you run and write code together without compiling then debugging would be difficult. Hence start with a simple complete program.
I think the problem description is clear with different tasks. You could first start with the menu and then ensure it works fine before adding another feature to your code. This also provides you better learning and new features.
Comment: I'm leaving my answer as it contains some pointers I think are useful, but I'm upvoting yours because you suggested the correct **approach**,  which will be much more useful to the OP than fixing this one program.


Permissão para shutdown!

Question: Como faço para dar permissão a executar o comando shutdown ao user ?
Estou usando o OS Linux Mint 13.
Comment: Creio que está pergunta seja off-topic para o SOpt, talvez um lugar para perguntar seja o http://unix.stackexchange.com ou http://askubuntu.com (Mint é uma "fork" do Ubuntu)
Comment: `sudo` não resolve o seu problema?
Comment: não, ele pede a senha do root!
Comment: Por que você não adiciona seu usuário no sudoers?
Comment: Já adicionei, mas  não funciona, manda um ex por favor!
Answer: Uma das alternativas é editar o arquivo /etc/sudoers e incluir nesse arquivo a seguinte linha:
user host = (root) NOPASSWD: /sbin/shutdown

Onde:
user = usuário que você deseja dar a permissão ao shutdown sem solicitar a senha
host = nome do host (execute o comando hostname para saber)
Para editar o arquivo /etc/sudoers utilize a ferramenta visudo, veja abaixo:
sudo visudo -f /etc/sudoers

Um exemplo real (meu computador de backup):
luiz storage = (root) NOPASSWD: /sbin/shutdown

Executando o comando:
sudo /sbin/shutdown -r now

O comando acima dará um shutdown imediato e fará uma reinicialização do computador. Nenhuma senha será solicitada.

Permissão para shutdown!


Toolbar not showing in the layout editor of Android Studio 3.6.1

Question: After updating android studio to 3.6.1 Toolbar not showing in the layout editor.
It's showing like this..

But it should be like this.

Number 3 Option not showing in my case.
Comment: Hi check updated answer it may help you. go to view--> Tool Windows--> preview
Answer: Ok as far as I think there's no option to show or hide the specific toolbar you are mentioning in your question. Android Studio seems to be doing it by default.
The issue in your case is that android studio will show the toolbar if you open the any layout.xml inside the layout folder in your res folder. Try opening an xml inside layout it should be showing this by default.
As visible from your screenshot you have opened an xml from menu folder. The layout editor in this case only shows the contents in your main_menu.xml like a dropdown list etc. and not how it appears in the actual layout if I am not wrong.
If this menu is include in some layout's xml file in the layout folder try opening that to see the contents and the toolbar you mentioned.
See if this works for you


jsii error when attempting to create a EC2 using Parameter via AWS CDK in python

Question: Here is the code, this is pieced together from referencing the official documentation:
    image_id = core.CfnParameter(
        self,
        id='ImageName',
        type='String',
        default='MyTestImage',
        constraint_description="Must be the AMI name not the ID",
        )

    vpc_id = "vpc-XXXXXX"
    # lookup existing VPC
    vpc = ec2.Vpc.from_lookup(
        self,
        "vpc",
        vpc_id=vpc_id,
    )

    # create a new security group
    sec_group = ec2.SecurityGroup(
        self,
        "MyAppSG",
        vpc=vpc,
        allow_all_outbound=True,
    )

    ami_id = ec2.LookupMachineImage(
        name=image_id.value_as_string
    )

    ec2_instance = ec2.Instance(
        self,
        "ec2-instance",
        instance_name='Web',
        instance_type=ec2.InstanceType('t2.micro'),
        machine_image=ami_id,
        vpc=vpc,
        key_name='Mykey',
        security_group=sec_group,
    )

Then run the CDK command:
cdk diff --parameters ImageName=MySecondTestImage
Error:
Searching for AMI in XXXXXXXX:us-east-1
jsii.errors.JavaScriptError:
  Error: Invalid context key: context keys can't include tokens
      at ConstructNode.setContext (/private/var/folders/w3/b69qmypx72nd9kk9s0vx73hdhdcs6y/T/jsii-kernel-kDU1vU/node_modules/@aws-cdk/core/lib/construct-compat.js:356:19)
      at App.loadContext (/private/var/folders/w3/b69qmypx72nd9kk9s0vx73hdhdcs6y/T/jsii-kernel-kDU1vU/node_modules/@aws-cdk/core/lib/app.js:75:23)
      at new App (/private/var/folders/w3/b69qmypx72nd9kk9s0vx73hdhdcs6y/T/jsii-kernel-kDU1vU/node_modules/@aws-cdk/core/lib/app.js:46:14)
      at /data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_embedded/jsii/jsii-runtime.js:3621:49
      at Kernel._wrapSandboxCode (/data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_embedded/jsii/jsii-runtime.js:4105:16)
      at Kernel._create (/data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_embedded/jsii/jsii-runtime.js:3621:26)
      at Kernel.create (/data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_embedded/jsii/jsii-runtime.js:3356:21)
      at KernelHost.processRequest (/data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_embedded/jsii/jsii-runtime.js:13162:28)
      at KernelHost.run (/data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_embedded/jsii/jsii-runtime.js:13100:14)
      at Immediate._onImmediate (/data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_embedded/jsii/jsii-runtime.js:13103:37)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/data/CDK/POC/test/app.py", line 9, in <module>
    app = core.App()
  File "/data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_runtime.py", line 83, in __call__
    inst = super().__call__(*args, **kwargs)
  File "/data/CDK/POC/test/.venv/lib/python3.9/site-packages/aws_cdk/core/__init__.py", line 14940, in __init__
    jsii.create(App, self, [props])
  File "/data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_kernel/__init__.py", line 265, in create
    response = self.provider.create(
  File "/data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_kernel/providers/process.py", line 353, in create
    return self._process.send(request, CreateResponse)
  File "/data/CDK/POC/test/.venv/lib/python3.9/site-packages/jsii/_kernel/providers/process.py", line 335, in send
    raise JSIIError(resp.error) from JavaScriptError(resp.stack)
jsii.errors.JSIIError: Invalid context key: context keys can't include tokens
Subprocess exited with error 1

why the CDK Error is being produced?
Answer: From https://docs.aws.amazon.com/cdk/latest/guide/parameters.html

A CfnParameter instance exposes its value to your AWS CDK app via a
token. Like all tokens, the parameter's token is resolved at synthesis
time, but it resolves to a reference to the parameter defined in the
AWS CloudFormation template, which will be resolved at deploy time,
rather than to a concrete value.

You are trying to use the value before synthesis time when it hasn't been resolved. For what you want to achieve the Runtime Context https://docs.aws.amazon.com/cdk/latest/guide/context.html is more suitable. Here is an example:
from aws_cdk import core
import aws_cdk.aws_ec2 as ec2

class MyCdkStack(core.Stack):

    def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        image_name = self.node.try_get_context("image_name")
        vpc_id = self.node.try_get_context("vpc_id")

        # lookup existing VPC
        vpc = ec2.Vpc.from_lookup(
            self,
            "vpc",
            vpc_id=vpc_id,
        )

        # create a new security group
        sec_group = ec2.SecurityGroup(
            self,
            "MyAppSG",
            vpc=vpc,
            allow_all_outbound=True,
        )

        ami_id = ec2.LookupMachineImage(
            name=image_name
        )

        ec2_instance = ec2.Instance(
            self,
            "ec2-instance",
            instance_name='Web',
            instance_type=ec2.InstanceType('t2.micro'),
            machine_image=ami_id,
            vpc=vpc,
            key_name='Mykey',
            security_group=sec_group,
        )

You can run it by supplying the context e.g.:
cdk synth --context image_name=xxxxx --context vpc_id=xxxxx


Propriedade '_$visited' em objeto JavaScript no retorno da função map() do Obervable

Question: Tenho um WebService implementado com JAX-RS e estou o consumindo com um serviço(utilizando Angular 2)
Segue o serviço:
@Injectable()
export class ModeloService {

  constructor(private http: Http) {
  }

  getAll(): Observable<Modelo[]> {
    return this.http.get(myEnvironment.MODELO_SERVICE_PATH)
      .map(res => <Modelo[]> res.json());
  }

}

Modelo é essa minha classe:
export class Modelo{
  id: number;
  type: string;
  size: number;

  constructor() {

  }

}

Acontece que o retorno da função map(), monta o seguinte objeto JavaScript, ou seja, ela insere essa propriedade _$visited : true:
{
  "id": 28,
  "type": "type",
  "size": null,
  "_$visited": true
}

Essa propriedade "_$visited" não faz parte do meu modelo lá do lado do WebService, nem do lado do front-end, se eu consumo esse WebService por um client Rest(utilizo o Restlet Client), o json retornado é o esperado ou se eu logar o retorno da própria função res.json():
{
  "id": 28,
  "type": "type",
  "size": null
}

Queria saber, primeiro de onde vem essa propriedade "_$visited" e qual a melhor forma de sumir com ela, pois quando vou enviar esse objeto pro meu web service de novo, ele vai com essa propriedade.
Comment: Em uma pesquisa rápida pela Internet, vi que o lugar que usa essa propriedade "_$visited" é o Primefaces, mais especificamente o PrimeNG. Você está usando essa biblioteca?
Comment: Sim, estou usando essa biblioteca? pode me passar a referência?
Comment: Cheguei nisso através dessa issue no GitHub https://github.com/primefaces/primeng/issues/1937 provavelmente você não precisa se preocupar com essa propriedade, é apenas um controle do PrimeNG.
Comment: acontece que ela é setada e quando vou enviar um post com esse mesmo objeto pro web service, dá erro lá do outro lado.
Comment: Acredito que qualquer implementação que você esteja utilizando tem alguma maneira de dizer para os objetos ignorarem as propriedades que não são mapeadas no seu Backend. Por exemplo o Jackson tem @JsonIgnoreProperties(ignoreUnknown = true), dê uma olhada.
Comment: Não conhecia essa annotation, vlw brother. deu certo.
Comment: Redigi uma resposta para ajudar quem mais tiver esse problema. Se puder aceitá-la. Abraço.
Answer: Essa propriedade é adicionada pelo PrimeNG para realizar alguns controles da biblioteca. Teoricamente ela não deve influenciar no envio de requisições para o seu backend.
Porém se o backend estiver lançando exceções dizendo que não conhece a propriedade, você pode usar uma anotação da sua biblioteca JSON para ignorar essas propriedades desconhecidas.
Um exemplo de anotação do Jackson na classe de comunicação:
@JsonIgnoreProperties(ignoreUnknown = true)

Dessa maneira a biblioteca não tentará realizar o parse dessa propriedade.


Is Chef/Puppet too complicated?

Question: I know both of them are amazing tools, and have great feature sets. But maybe, just maybe, they are like Word/Excel, which I probably only use < 10% feature in my lifetime. To me, a bash-based script language would be much better than a DSL.
Is it just me?
Comment: You've asked this exact question on Reddit, Linkedin, and now here with pretty much the same response. Perhaps it's time to actually try a config management system rather than imagine you can easily create your own with Bash?
Comment: How can any of us possibly answer this? Obviously many people find these tools invaluable. This depends on your configuration, your experience, and your knowledge. This isn't a discussion site, take a look at the [faq]
Comment: What is the question here?
Comment: Sounds like it's too complicated **for you**. That's nice and all, but others have different use cases.
Comment: Puppet borders on being simple if you stick to the basic, File/Package/Service resources, which will give you ton of useful functionality.  Like every other tool there are lots of advanced features that you probably don't need, but they are there because somebody needs them.  If you want to learn puppet, then pick up a copy of Pro Puppet.  http://www.amazon.com/dp/1430230576/  It is a really good technical book.
Answer: Yes, Puppet and Chef are complicated and have a steep learning curve. What are you looking to accomplish? There are lighter-weight configuration management tools out there.
Comment: I don't know about you, but I find puppet manifests tend to be less complicated and far clearer, then many scripts I have seen.
Comment: Yes, whenever I tried to write the recipe in chef/puppet for our riak deployment, I started to miss the command line. And https://github.com/cmer/shoestrap looks quite interesting. Want to find out whether others feel the same.

Is Chef/Puppet too complicated?


How to Import a CSV file into an entity automatically?

Question: Is there a way to import a CSV file into a CRM record automatically, say when the CSV file is created?
The plan is that this CSV file would have some cost center hours inside and job number which corresponds to a certain record already created in CRM.
And uploading this CSV would then update this record.
Please help me to solve this problem
Comment: Use File system watcher, Task scheduler, Console app, SSIS, etc by mix & match to achieve the automagic data load :)
Comment: you may want to review [Ask], and research Microsoft Power Automate.
Comment: Thanks, I'm not sure Power Automate would work, this is all on premise so limits me on the use of cloud services.
Answer: You can import data both using UI and code in D365.
Also there are plenty of tools solving exactly same problem: KingswaySoft SSIS, Scribe, etc.
But it looks like buying 3rd party software might be overkill in your scenario. You can use Windows task scheduler and write a few PowerShell scripts to implement it.
Where to start:

https://learn.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/import-data
https://learn.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/sample-import-data-complex-data-map
https://github.com/seanmcne/Microsoft.Xrm.Data.PowerShell
https://learn.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/define-alternate-keys-entity


Question about least element in an interval.

Question: For the open interval (-1, 1), intuitively I know that there is no least element in the interval, since there is always a negative value that's very close to -1 but never reaches -1, and it's less than some "supposed" least element.
For example, I know how to show that the interval (0, 1) has no least element:
By contradiction, suppose that there is a least element $p \in (0,1)$, but $ \frac{p}{2} \in (0,1)$ and $\frac{p}{2} < p$, which shows that $p$ is not the least element, which contradicts what was supposed. Thus there is no least element in (0,1).
However, for the interval (-1,1), I can't use the above method, since we're looking at the negative values for the least element, and negative value divided by a positive value will be greater than that negative value. So in this case, does it make sense to use absolute value for some element in (-1,1) and show that there is no least element?
Thanks
Comment: Why can't you use a similar approach? Given least element $p\in(-1,1)$, WLOG $p\in(-1,0)$, so consider $\frac{p-1}2$. $-1<\frac{p-1}2<p$, so contradiction.
Answer: Suppose $p\in (-1,1)$ is a least element.
Then $-1 \lt p \lt 1 \implies-2 \lt p-1 \lt 0\implies- 1\lt \frac{p-1}{2} \lt 0\implies \frac{p-1}{2} \in (-1,1)$.
But $\frac{p-1}{2} \lt p $ is a contradition


Efficent way to store "180-bit" (more than 64-bit) integer

Question: I am using bits to represent events which occur on a day. For instance if I store 4 days of information I could use 1011 (staring from right to left) would indicate on days 1,2, and 4 events occurred (bit 1,2, and 4 are set).
I am using the type of Long to store the bits (which would in this example store the number 11). Now with Long I could store 63 days of events (long max size is 2^64 -1).
FYI: I later take one on my sets of events and then compare it with another set to see  how many events occurred on the same day (I use Long's bitcount method to do this). For example, 1011 AND 1000 = 1 event occurred on the same day in these two sets.
he problem I am facing is: I now need to store more than 63 days of data. I need about 180 days now. I am facing performance issues with my two solutions and was wondering if there is a more efficient way to essentially store a "180-bit" Integer.
My first solution was to use BigInteger, but this is very slow when running. My other solution is to breakup the 180 bits into 3 Longs and later compare accordingly, but obviously this creates 3 times the work.
Comment: How about java.util.BitSet
Comment: First of all I dont understand your method of storing, and secondly  break it to three Long dont make it three time slower.
Comment: In terms of primitives your choices are between the various integer data types.  One way or another you need to "splice" values together to get 180 bits.  (Note:  It might be wise to avoid using `boolean[]` as the Oracle versions I've seen implement boolean arays as byte arrays with one bit per byte.)  Otherwise use java.util.BitSet or another Set implementation.  (You are talking about manipulating sets, after all.)
Comment: What if something happened on the 3rd or 5th day etc? That would be misinterpreted as something happening on the 1st and 2nd, or 4th and 1st day respectively. I suggest using a boolean array for this instead.
Comment: @YvesDaoust -- I only recall 36-bit LOGICALs (I think), on the 7094.  But, come to think of it, I think the CDC 6600 (which I also used) had 60-bit LOGICALs.  The thing about Java is even the `boolean` *arrays* are one bit per byte, in the Sun/Oracle implementation (as it existed a few years back, at least).  Very inefficient for storing bit sets.
Comment: @YvesDaoust - But anyone with any sense knew not to use LOGICAL arrays (if the compiler even supported them).  Would not be the case for someone using Java today, since the sense of what's going on with the hardware has been lost.
Comment: @YvesDaoust - Ah, but everyone knew the work-arounds.  (Of course, don't ask me what they are, since I haven't coded FORTRAN since 1974.)
Answer: java.util.BitSet
BitSet is part of the standard library and is suitable for your Use-case. But maybe you should look also at the second option below which is a compressed alternative. Which is supposed to be much more memory and performance efficient.
Using the standard library you could define something like
BitSet bits1 = new BitSet(180);

Even if you store more than 180 bits you can resize it at any point of time.
If you want to compare it with a other set you can do something like this:
BitSet bits1 = new BitSet(180);
BitSet bits2 = new BitSet(180);
// do something here to set events

// find events which happened on the same day in bits1 and bits2
bits1.and(bits2);

and then you can traverse the set using something like nextSetBit. An example from Oracle documentation to traverse over all events which occur in bits1 and bits2 would be then:
for (int i = bits1.nextSetBit(0); i >= 0; i = bits1.nextSetBit(i+1)) {
     // operate on index i here
}

Compressed Bitset JavaEWAH
see: Github repository for javaewah
Alternative to Java BitSet used in some Big-Data projects like Apache Hive and Apache Spark.
Example with JavaEWAH:
EWAHCompressedBitmap eventsBitmap1 = EWAHCompressedBitmap.bitmapOf(
    0,1,22,64,1<<30);
EWAHCompressedBitmap eventsBitmap2 = EWAHCompressedBitmap.bitmapOf(
    1,3,64,1<<30);
System.out.println("Events 1: "+eventsBitmap1);
System.out.println("Events 2: "+eventsBitmap2);

Find events which happened on the same day
EWAHCompressedBitmap bothEventsBitmap = eventsBitmap1.and(eventsBitmap2);
System.out.println("Days where both events took place: "+bothEventsBitmap);

Further implementations

Roaring Bitmap, also a compressed bitmap implementation.
Comment: Thanks for the reply! I have never heard of JavaEWAH but will have a look and try to implement it!
Comment: Doing a little bit of research I noticed another alternative, RoaringBitmap. I will try to do a little benchmarking, but if anyone knew generally which one is faster already that would be great to know!
Comment: @user2924127 I add the RoaringBitmap to the answer.
Comment: roaring bitmap only support 2^32-1 for one object
Answer: It sounds like you need arbitrary precision and you can use BigInteger which provides immutable arbitrary-precision integers for that,
BigInteger val = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE);
System.out.println(val);

Output is
9223372036854775808

Answer: If your sets of bits are sparse, explicit enumeration of the 'ones' can be advantageous (in your example case, you store the integers 1, 2 and 4 as three bytes, preceded by a count or followed by a terminator byte -> n ones (=3) require n+1 bytes (=4) instead of 23.
As long as the average number of ones is smaller than 23, this representation is more compact. Depending on the operations you perform, it can be slower or faster.
Anyway, handling a variable length representation can be difficult, especially if it is dynamic.
The explicit bit set representation is often preferred, but if your distribution of events calls for it, a mixed representation is also possible (enumeration for, say, 10 ones or less, bits set otherwise).
In the terrible cases where you need a more compact representation, Huffman entropy coding can help you compress by a further factor 2 or 3.


I want to know the memory location for a list and normal variable in python

Question: I am storing a value in a variable and same value in another variable then it is giving the same id for both variables. but if i am assining a list to a variable and same list to another variable that ID is differing why?
my example program is:
>>> x=10
>>> y=10
>>> id(x)
21122368
>>> id(y)
21122368

>>> x=[1,2,3]
>>> y=[1,2,3]
>>> id(x)
35525896
>>> id(y)
35527736

Comment: Because it is a different list, where you've put the same content.
Comment: Integers are *immutable* and hence it doesn't make a difference whether one is reused or not. Lists however are mutable and must be separate instances to provide the expected behaviour.
Comment: It;s a possible duplicate of tens (literally) of similar questions.
Comment: I forgot to mention, while a Python programmer may need to know the memory location of an **object** (note that I haven't written _variable_), hence the inclusion of `id()` in the language, they usually doesn't.
Comment: your saying immutable and nutable behaves different if that is the case string is also immutable but for string i am getting the same memory location allocated
Comment: example:>>> x="s" >>> y="s" >>> id(x) 21122368 >>> id(y) 21122368
Answer: This happens due to an optimization in the most popular Python implementation.  Basically, small integers are not created as full objects, rather you receive a reference to an  existing small integer, and it's the same one every time.
Answer: Some immutable objects are cached in python, being some numbers and strings an example. That means, when you write 1 you get a reference to an object that already existed on the heap.
Lists are not cached (makes little sense, starting from the fact that they are mutable), and therefore they have different identity, although they can be equal in contents.
Maybe a little comparison helps. Each person that takes a look at the moon, is seeing the very same moon (that would be getting a reference to 1)... therefore you can say that
id(my_moon) == id(your_moon)

or just
my_moon is your_moon

Since the moon is the moon, and 1 is 1, some implementations of python decide to cache this object for performance reasons.
On the other hand, mutable objects are a horrible candidate for caching. For instance, each person that takes a bag of chips, is taking a different instance of a bag of chips, therefore it can be that at some point
my_chips == your_chips

because they have the same amount of chips, but in no case whatsoever it would be
id(my_chips) == id(your_chips)
because that would mean that the object is shared, and when somebody else eats a chip (mutates the chips bag object), a chip would dissapear from your bag... and that would be a terrible world to live in :)
Comment: your saying immutable and nutable behaves different if that is the case string is also immutable but for string i am getting the same memory location allocated
Comment: example:>>> x="s"
>>> y="s"
>>> id(x)
21122368
>>> id(y)
21122368
Comment: I don't understand your comment. Some immutable objects are cached by the Python VM for performance reasons (this is implementation dependent). Strings and Integers happen to be cached sometimes, and that is your case. That is why `1 is 1` and `'s' is 's'`.


JAVA - Desenhar Poligonos (triangulos, pentagonos)

Question: Boas queria saber se alguém me pode ajudar,
Eu estou a fazer um projecto em que tenho de desenhar varias figuras, entre elas triângulos e pentágonos, eu ja consegui meter os rectângulos a funcionar, rectângulos:
import java.awt.Color;
import java.awt.Graphics;

public class Retangulo extends Figura {
int largura, altura;

public Retangulo() {
    super();
    largura = altura = 0;
}

public Retangulo(int x, int y, int l, int a, Color cor) {
    super(x, y, cor);
    largura = l;
    altura = a;
}

@Override
public void desenha(Graphics g) {
    g.setColor(cor);
    g.drawRect(p.x, p.y, largura, altura);
}

@Override
public void setCoordenadas(int x1, int y1, int x2, int y2) {
    p.x = Math.min(x1, x2);
    p.y = Math.min(y1, y2);
    largura = Math.abs(x1-x2);
    altura = Math.abs(y1-y2);
}
}

Eu neste exemplo usei o drawRect() que está na API do JAVA, ao tentar fazer o mesmo com os poligonos com o drawPolygon(), tive alguns problemas com isso, o código dos polignos que fiz(mal) foi:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Poligonos extends Figura{
    public void Poligonos (int[] xPoints, int[] yPoints, int nPoints){
        //private int[] xPoints = {(x1/2), x1, (x1+(x1/2))}  // {(getX()/2), getX(), (getX()+(getX()/2))};
        //private int[] yPoints = {( y1 + y1 ), y1 ,( y1 + y1 )};

    }
    @Override
    public void desenha(Graphics g) {
        g.setColor(cor);
        g.drawPolygon(  xPoints, yPoints, 3);
    }
    @Override
    public void setCoordenadas(int x1, int y1, int x2, int y2) {
        p.x = Math.min(x1, x2);
        p.y = Math.min(y1, y2);

        int xPoints[] = {(p.x /2), p.x , ( p.x +( p.x /2))};  // {(getX()/2), getX(), (getX()+(getX()/2))};
        int yPoints[] = {( p.y + p.y ), p.y ,( p.y + p.y )};
    }
}

O drawPolygon() estou a usa-lo de uma forma errada, visto que o xPoints e o yPoins não estão a entrar no drawPolygon.
Isto é para ser desenhado com o rato, atravez de:
   @Override
     public void mousePressed(MouseEvent e) {
            x1 = e.getX();
            y1 = e.getY();
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            x2 = e.getX();
            y2 = e.getY();
            r.setCoordenadas(x1, y1, x2, y2);
            pEdicao.repaint();
        }

Alguém me sabe dar uma dica ou alguma ajuda ? Obrigado.
Answer: E se ao invés de você utilizar coordenadas, considerar o vértice do mesmo, assim cria um vetor que aumenta com a quantidade, mas daí deve considerar os ângulos, lados a partir de um ponto. Utilizando o point.
Aqui está um exemplo de polígono:http://www.cin.ufpe.br/~ccc2/PG/Poligono.java.
Comment: Exato, foi exatamente isso que eu gostaria de fazer, mas infelizmente eu não sei como o fazer, não sei como passar isso para codigo, não sei como criar esse vector a partir das coordenadas do getx() e do gety(), é exatamente isso que gostaria de aprender a fazer, sabe como me ajudar ?
Answer: Foi assim que consegui resolver o meu problema e poder desenhar um pentágono, neste caso é um pentágono vazio, ou seja apenas tem as linhas do seu perímetro:
public class Pentagono extends Figura {
    int[] xPoints;
    int[] yPoints;
    Ponto p2;

    public Pentagono () {
        super();
        p2 = new Ponto();
        xPoints = new int [5];
        yPoints = new int [5];

    }
    public Pentagono (int x, int y, int x2, int y2, Color cor){
        super(x, y, cor);
        p2 = new Ponto(x2, y2);
        xPoints = new int [5];
        yPoints = new int [5];
        setCoordenadas(x, y, x2, y2);
    }

    @Override
    public void setCoordenadas(int x1, int y1, int x2, int y2) {
        p.x = x1;
        p.y = y1;
        p2.x = x2;
        p2.y = y2;

        double raio = Point2D.distance(x1, y1, x2, y2);
        double ang = Math.atan2(y2-y1, x2-x1);
        double inc = 72 * Math.PI / 180;
        for(int i=0; i<xPoints.length; i++) {
            xPoints[i] = (int) (raio * Math.cos(ang) + x1);
            yPoints[i] = (int) (raio * Math.sin(ang) + y1);
            ang += inc;
        }
    }
    public void desenha(Graphics g) {
        g.setColor(cor);
        g.drawPolygon(xPoints, yPoints, 5);
    }
    public double Area() {
        Ponto p2 = new Ponto(xPoints[1], yPoints[1]);
        Ponto p3 = new Ponto(xPoints[2], yPoints[2]);
        double d = distancia(p2, p3);
        return( ((5*(d*d)) * Math.tan(54))/4);
    }
    public double Perimetro() {
        Ponto p2 = new Ponto(xPoints[1], yPoints[1]);
        Ponto p3 = new Ponto(xPoints[2], yPoints[2]);
        return ( 5 * (distancia(p2, p3)));
    }
    private double distancia(Ponto r, Ponto s) {
        return Math.sqrt(
                Math.pow(r.x-s.x, 2) +
                Math.pow(r.y-s.y, 2)
                );
    }
    public String mostrarInfo() {
        Ponto p = new Ponto(xPoints[0], yPoints[0]);
        return (" Area = " +Area() +" Perimetro = " +Perimetro()+
                " Ponto Inicial = " +p.x +"," + p.y);
    }
    public boolean contains(int x, int y) {
        Polygon p = new Polygon(xPoints, yPoints, 5);
        if (p.contains(x, y)) {
            return true;
        }
        return false;
    }
    public void mover (int dx, int dy) {
        for(int i = 0; i < xPoints.length; i++) {
            xPoints[i] += dx;
            yPoints[i] += dy;
        }
    }
}

Se alguém quiser fazer um pentágono mas cheio em toda a sua área, apenas terá de acrescentar a seguinte class:
public class PentagonoCheio extends Pentagono {
    public void desenha(Graphics g) {
        g.setColor(cor);
        g.fillPolygon(xPoints, yPoints, 5);
    }
}

Se quiserem ver o meu projecto todo podem encontra-lo em: soeiromass GitHub


Negative predictions for binomial predictions from gbm in R

Question: I've just fit a binomial model (training y = 0 or 1) using R's gbm package. When I calculated predicted values using my validation data, some of the predicted values were less than 0.
Is this normal behavior? If so, how do I handle the negative values, floor them at 0?
Answer: I emailed the author of the package, Greg Ridgeway, and got this response:
"Predictions are on the canonical scale, which for binomial us the log-odds scale. You can use the type="response" when predicting to put it on the probability scale."


Detect OS and Java on Windows and Linux

Question: I have a JavaFX project based on Maven. I want to build the Maven project on Windows and on Linux. In order to automate the process when I deploy the bundle I want to automatically detect the operating system.
In windows I have this configuration:
<code>              <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <bootclasspath>${sun.boot.class.path}${path.separator}${java.home}/lib/jfxrt.jar</bootclasspath>
                    </compilerArguments>
                </configuration>
            </plugin>
</code>
But on Linux I have this configuration:
<code>          <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <bootclasspath>/opt/java/lib/jfxrt.jar</bootclasspath>
                    </compilerArguments>
                </configuration>
            </plugin>
</code>
Can I somehow set the Java usage based on the operating system on which the bundle is deployed?
Answer: You can use profiles for such purposes like this:
<code><profiles>
  <profile>
    <activation>
      <os>
        <name>Windows XP</name>
        <family>Windows</family>
        <arch>x86</arch>
        <version>5.1.2600</version>
      </os>
    </activation>
    ...
  </profile>
</profiles>
</code>
Comment: Do I need to set them manually or the OS will choose the appropriate one when the application is started.
Comment: The OS detection is done automatically. You can see that if you `mvn --version` in the last of the output you see the values you have on your os.

Detect OS and Java on Windows and Linux


Deeper Understanding Mean Value Theorem. Show that $(1+x)^r>1+rx$

Question: Let $r>1$.
If
$$x>0 \text{ or } -1 \leq x<0,$$
show that $(x+1)^r>rx+1$,
This is what ive done:
$$f(x)=(x+1)^r-r x-1$$
$$\frac{d }{dx}-r+r (x+1)^{r-1}$$
From this I can see that if $-1\leq x<0$ then $f'(x)<0$, and if $x>0$ then $f'(x)>0$.
We already know that:$$\frac{f(x)-f(0)}{x-0}=f'(x),$$ this means that $f(x)-f(0)=(x-0) f'(x)$,
I can easily see that by plugging in zero into the function it spits out zero. But I might be confused because it is stated that given this information I should be able to see that $f(x)>f(0)=0$,
Now this is how I'm reasoning but I hope that someone could point it out if I am wrong:
I know if $f'(x) \cdot x$, where $x <0$, gives a positive value (negative times negative).
And for $x>0$ we get positive (positive times positive)
And in both these cases
$f(x)>f(0)=0$,  if $x>0$ or $-1 \leq x<0$
If my reasoning is correct so far then this is my next step,
Since I have proved that
$f(x)=(x+1)^r-r x-1>0$, I can rearrange and get $(x+1)^r>rx+1$.
This is what I am interested to know, is my reasoning correct. And could someone explain the underlying theory with regards to this example.
I see that there is at least one point on the interval where the tangent line to that point is parallel to the chord line, but if it was not for the fact that I knew that I had to use the theorem I would not be able to solve this question.
The book uses this explanation for the MVT.
But I do not see the logic regarding: show that $(x+1)^r>\text{rx}+1$.
Stupid but important to understand is: So what if the slope at one point is equal to the slope of the chord line?
But I just dont get it!
Comment: I fixed the title to reflect what's being asked in the question (the title used $1-x$ where the question clearly uses $1+x$, and the form used in the text with the $1$ on the right is much more familiar)
Comment: You may be interested to know that the inequality is called Bernoulli's inequality.
Comment: @GerryMyerson Would you be able to verify that what is written in the answer provided is correct cause I just do not get it.
Comment: I assume you're enrolled in a class somewhere. Your teacher will be happy to let you know whether the answer provided is correct.
Comment: @GerryMyerson Unfortunately not Im studying it on my own.
Answer: Let $$f(x) \colon= (1+x)^r$$ for all $x \geq 1$, where $r > 1$ is arbitrary but fixed.
Then $f(0) = 1$, and $$f^\prime(x) = r (1+x)^{r-1}$$ for all $x \geq 1$.
Now since $r > 1 $, we see that $f^\prime(x) > 0$ for all $x > -1$.
Moreover, by the Mean Value Theorem, we have, for any $x \geq -1$, the relation  $$ f(x) - f(0) = x \cdot f^\prime(x_0)$$ for some $x_0$ strictly between $0$ and $x$.
That is, for any $x \geq -1$, we have $$ (1+x)^r - 1 = x \cdot r (1+x_0)^{r-1}.$$
Now I hope you would be able to arrive at the answer to your question. Good luck!
Comment: For the function f(x), we have that x>=1,but then you define f(0) wish is less than the range specified,  and then we have for the mean value theory where there is a x>=-1, I just do not understand.
Comment: Would you be able to explain a bit more, I get really confused with the intervals used. I tried to make sense by plotting the graph but I was still unable to see what was going on.


A system of three linear equations

Question: Problem
If the linear system
$$
\begin{align*}
ax+by&=k\\
cx+dy&=l\\
ex+fy&=m
\end{align*}
$$
is consistent, why at least one equation can be discarded from the system without altering the solution set? (Anton Elementary Linear Algebra 9th edition, Exercise Set 1.1, problem 13)
My Attempt
If the linear system is consistent, then it has at least one solution (exactly one solution or infinitely many solutions). If each of the linear equations in the system correspond to lines $l_1$, $l_2$, and $l_3$, then:

If we have infinitely many solutions, then the three lines are coincident. Two of the lines are coincident so the third line can be discarded without altering the solution set.
If we have exactly one solution, then the three lines intersect in exactly one point. Two of the lines intersect in one point so the third line can be discarded without altering the solution set.
Comment: Yes, your attempt seems correct.
Answer: Your attempt is correct. (Just be careful about the geometric interpretation of equations as lines; as long as you have clearly defined how you are converting an algebra problem into a geometry problem and back, nobody can question you.)
Another [algebraic] approach is to show that two of the equations are sufficient to solve for $x$ and $y$ in terms of the coefficients (you can use matrices, the standard substitution method, or whatever else to do this). As you have assumed nothing about the actual coefficients, you can choose any two of the given equations and you will always be able to find the solution. This method requires some special handling of the infinite solutions or no solutions cases, but does not require geometry.

A system of three linear equations


Assessing stability or instability of a system of equations with complex eigenvalues

Question: Having this system
, we get clearly two complex eigenvalues. If one has to assess the stability of the system at these eigenvalues, we have for the matrix A:
\begin{pmatrix}
 a & b\\
c & d
\end{pmatrix}
that $T^2-4\Delta \geq  or \leq or = 0$, where  $T=a+c$, while  $\Delta=ad-bc=DetA$. But with complex eigenvalues  $\pm2i$, $T$ which must be real, becomes complex and $\Delta$ is always $0$, when it would vary from greater than or lesser than zero for real eigenvalues. How do we solve this with complex eigenvalues?
Thanks
Answer: If the eigenvalues are pure imaginary, then the system has only a center.
If the eigenvalues are complex, the non-zero real part  (call it $\alpha)$ of the term $T^2-4\Delta$ defines whether it is a stable or unstable spiral - for $\alpha > 0$, then it is a unstable spiral point, and inversely, $\alpha<0$ then it is a stable spiral.


How to remove the least-recently-used image layers from Docker cache?

Question: I would like to (1) avoid running out of disk space due to Docker filling up its cache and (2) easily recover from such situation without discarding the cached objects that have been used recently. For this, it would be great if some command could remove all cached objects that haven't been used in a couple weeks or so. I'm aware of the following:
<code>docker image prune -a --force --filter "until=240h"
</code>
But unless I'm mistaken, the above will delete any base image or layer that's older than 10 days (240 hours) even if we're still using it actively. Instead, we'd like to delete extra layers that were created during the development process and are no longer in use. Of course, we also want to delete downloaded base images that are no longer in use. We could then run such command every night and live happily ever after.
In short, how can we turn Docker's cache into an LRU cache?
Answer: Docuum will do LRU eviction of docker images. Docker itself doesn't store the date of last use, so Docuum monitors image usage and stores the necessary state itself.


Dropdown SubMenus Based on Roles Stopped Working

Question: My site has a menu/top nav of course and I have various dropdown/sub menus.  Yesterday it was all working fine.  If you are an anonymous user, you see a particular menu item, that has a particular dropdown.  If an authenticated user, you see another menu.
Today, I looked at the page, first as an anonymous users, the top level menus are there, but when I hover the dropdown menus items do not appear.  I then logged in and same thing, the top level is there, but the hover does not display the submenus at all.
I then logged in as the admin and can see the top level menu and on hover, all the submenus appear.  So natural thought, something happened with the permissions settings, but I checked everything "seems" fine.  The only changes between today and yesterday afternoon where several updates to a stylesheet and I did add/install several modules [webform, token, date, calendar geolocation], I have not done anything to turn off the menu.  The top level is checked to show as expanded and of course, they show and function correctly when I am logged in as the ADMIN.
To explain my setup: where needed, I created two top menus for "speakers" for example:
speakers ->one ->two (permissions set to display for anonymous users)
speakers ->five ->twelve  (permissions set to display for anonymous users)
In the above example, anonymous user goes to page, hovers over speakers menu item, and should see in the dropdown [submenu items one and two] and this has been working for weeks now.  Same would apply for the authenticated user hovering over the second "speakers" and seeing [five and twelve in the submenu].
How do I debug this scenario to find out what is wrong?  I've been doing this long enough to know it is probably something I have done, but after checking permissions, checking menu visibility - oh I am also using the "Menu Per role" module that has been in place for weeks, I would like some insight on how to attack this problem.
Any suggestions would be greatly appreciated.
Answer: just posting my solution for those who may come after.
As I stated above, I did suspect that it was something I had or had not done to cause this issue.  Knowing for certain that the only changes made were related to stylesheet updates, which I knew could not cause this problem, and loading of new modules,  I decided I would have to uninstall them one-by-one, but before doing that, I went over the modules I installed yesterday [just a note: the reason I didn't see this issue yesterday was because the correct display had been cached] and thought about the problem and which module would most relate to that problem, so I started with jquery_update. [jquery/javascript typically used for these types of effects, hover onClick, etc.]
I installed jquery_update yesterday.  I did change the admin display option to version 1.7, but I left the working option at 1.10.  I disabled the module, refreshed my page and the submenus did appear on hover.
I was going to uninstall the module completely, then decided to set the working version back to 1.8 and the dropdown on hover continued to work.
I have not had time to really look, but the original developer set up the site with an older theme and I bet there is a conflict in the version used in the theme he/she chose and the most recent version of jquery.
Hopefully this will save someone a few hours of their life.
I do still love Drupal.


A property of $l_p$ space

Question: I'd like to show the following. Let $(u_n)_{n\geq 1}$ be a sequence of elements in $l_p(\mathbb{N})$. Suppose $u_n$ is p-norm-bounded by some $m>0$ and that for every $k\geq 1$, $\lim\limits_{n\to\infty}u_n(k)=0$, then $u_n$ has limit $0$ in weak topology.
I tried consider $f\in l_p^*$ and make $f(u_n)$ go to $0$ like this:
$|f(u_n)|\leq \lVert f\rVert.\lVert u_n\rVert_p$ , but I'm stuck. Hope somebody could help!
Answer: In this problem, $p$ must be greater than $1$. Here is a sketch of the proof. Let $\pi_{\leq N}$ be the coordinate projection on the subspace of $\ell_p$ spanned by $e_1, \dots, e_N$; let $\pi_{{}> N}$ be the coordinate projection on the closed subspace spanned by $e_{N+1}, e_{N+2}, \dots$.
Consider $f\in \ell_p^*$. Note that $f = f\pi_{{}> N} + f\pi_{{} \leq N}$. We have that $\|f\pi_{{}> N} \| \to 0$ as $N\to \infty$ since
$$\|f\pi_{{}> N}\| = \left(\sum_{i=N+1}^\infty |f_i|^q\right)^{1/q}$$
(where $1/ p + 1/q = 1$).
Choose $N$ such that $\|f\pi_{{}> N} \|\leq \varepsilon$. Then,
$$\limsup_{n\to \infty} |f(u_n)| \leq \limsup_{n\to \infty} |f\pi_{{}\leq N}(u_n)| + \limsup_{n\to \infty} |f\pi_{{}> N}(u_n)| \leq 0 + \|f\pi_{{}> N}\|\cdot m \leq \varepsilon m.$$
We get that for every $\varepsilon > 0$, $\limsup_{n\to \infty} |f(u_n)| \leq \varepsilon m$. Thus $\limsup_{n\to \infty} |f(u_n)| = 0$.
Here is a counterexample for $p=1$. Let $u_i = e_i$ and $f(u) = \sum_{i=1}^\infty u(i)$. The conditions of the problem hold but $f(u_i) = 1\not\to 0$.
Answer: This isn't true for $p=1$.
For $1<p<\infty$, here is a hint:
Write $$|<f,u_n>| = \biggl|\sum_{i=1}^k f(i)u_n(i)\,\biggr| +\biggl| \sum_{i=k+1}^\infty f(i)u_n(i)\,\biggr|, $$
where $f(i)$ is the $i^{\rm th}$ coordinate of $f$ (and similarly for $u_n(i)$).
Apply Hölder's  inequality to obtain
$$
|<f,u_n>|\le
\biggl(\sum_{i=1}^k |f(i) |^q\biggr)^{1/q} \underbrace{\biggl(\sum_{i=1}^k |u_n(i) |^p\biggr)^{1/p}}_A  +\underbrace{
\biggl(\sum_{i=k+1}^\infty |f(i) |^q\biggr)^{1/q}}_B \
\underbrace{\biggl(\sum_{i=k+1}^\infty |u_n(i) |^p\biggr)^{1/p}  }_C
$$
Note:

You may  choose $k$ so large that term $B$ is as small as desired.
Using the pointwise convergence of $(u_n)$, for a fixed $k$, you may choose $N$, so
that $n>N$ forces term $A$ to be as small as desired.
The term $C$ is bounded since the $u_n$ are norm bounded.
Comment: I can see what $u_n(i)$ means, I think, but $f(i)$ is not so clear when $f\in l_p^*$, could you be more precise? Also in your notation it looks like a scalar product...Thanks!
Comment: @Rodriguez $f$ is in $\ell_q=\ell_p^*$, where $(1/q)+(1/p)=1$; so $f(i)$ is its $i^{\rm th}$ coordinate. I'm using the notation $$ to denote the action of the functional $f$ on the point $u$.
Comment: I think I got the idea, but I'm still missing a bit. You are saying that $f(u_n)=\sum_{i=1}^\infty f(i)u_n(i)$ ? If you could explain that a little more, the rest is clear.
Comment: @Rodriguez Think of how a linear functional on $\ell_p$ works. If $y=(y_1, y_2,\ldots)$ is in $\ell_q$ (sorry for changing notation here) then its value at $x=(x_1,x_2,\ldots)\in\ell_p$ is $\sum y_ix_i$. I had to use the, perhaps cumbersome, notation above since subscript notation was already taken for the $u_n$. I'm using parentheses for coordinates. So I need some new notation for functional evaluation. But yes, "$f$ evaluated at $u_n$" is $\sum_{i=1}^\infty f(i)u_n(i)$, where the parentheses here denote coordinates.
Comment: Thanks, I'll give it some thoughts!

A property of $l_p$ space


Prove that the limit of two consecutive fibonacci numbers EXISTS.

Question: Using the definition of Fibonacci numbers, $F_n=F_{n-1}+F_{n-2}$, I can prove that the limit of $\frac{F_{n+1}}{F_n}$ as $n\to\infty$ is $\phi$ if we assume that the limit exists.
How can we prove that the limit does in fact exist?
Is there more than one method?

I do not think this is a duplicate. Please can someone explicitly show how to split the odd and even terms of this ratio sequence into two sequences- one monotonic increasing and one monotonic decreasing- and given that all ratios are between 1 and 2, show that the limit exists and we do not oscillate forever.

Most of the question has been answered.
I have shown that there are two subsequences- one increasing and bounded above by 2 and one decreasing, bounded below by 1. Using the fact that the limit exists, I can show it has value $\phi$. But how can I show the limit is the same for both subsequences?!
Comment: I would start with the fact that the limit is obviously bounded above by $2$ (can you see this?), and show it is monotonic.
Comment: A simple way is to use the "Binet" formula for $F_n$.
Comment: Daniel Littlewood- thank you. The only problem is that the sequence of ratios oscillates to the limit, right? If I could say it was monotonic increasing and bounded above then I would know what to do, or monotonic decreasing and bounded below, but that isn't the case.

Andre Nicolas- Thanks for that answer. The Binet formula is quite incredible! I've seen that proof and would like to use that as a second solution. I would also really like to be able to show the limit exists using only real analysis if possible.
Comment: @preferred_anon only monotonic considering even or odd terms.
Answer: By Cassini's Identity:
$$\left|\frac{F_{n+1}}{F_{n}}-\frac{F_{n}}{F_{n-1}}\right|=\left|\frac{F_{n+1}F_{n-1}-F_{n}^{2}}{F_{n}F_{n-1}}\right|=\left|\frac{(-1)^{n}}{F_{n}F_{n-1}}\right| \to 0$$
Proof of Cassini's Identity: $$F_{n+1}F_{n-1}-F_{n}^{2}\\ =(F_{n}+F_{n-1})F_{n-1}-F_{n}^{2}\\ =F_{n-1}F_{n}-F_{n}^{2}+F_{n-1}^{2}\\ =-(F_{n}(F_{n}-F_{n-1})-F_{n-1}^{2})\\ =-(F_{n}F_{n-2}-F_{n-1}^{2})$$
You can fill in the rest by induction.
Comment: I like this a lot. I haven't heard of Cassini's Identity before. Could you please link to a proof or derivation of it?
Comment: I've sketched a proof in the answer - is this clear enough?
Comment: Yes this is good, thank you!

What I really want to do is split the sequence of ratios into two sequences- a monotonic increasing one and a monotonic decreasing one and go from there. But I don't know how to do it...
Comment: Simply replace $n$ by $2n$. Clearly when $n$ is even the difference is positive and when $n$ is odd the difference is negative!
Comment: Yes, I did that. 2n and 2n+1 for even and odd respectively. But then what?
Comment: If the difference is positive it is increasing, if negative it is decreasing.
Comment: Substitute into the Cassini's? Or into the general definition? Where do you substitute in?
Comment: Explicitly: $\frac{F_{2n+1}}{F_{2n}}-\frac{F_{2n}}{F_{2n-1}}=\frac{1}{F_{2n}F_{2n-1}}>0$
Comment: OK so you have really just shown that the sequence is oscillating, right?
Comment: Consider the two subsequences: If $a_{n}=F_{n+1}/F_{n}$, we have seen that $a_{2n}$ is increasing and bounded above (e.g. by 2), and $a_{2n+1}$ is decreasing and bounded below (e.g. by 1). Thus both have limits (and this limit is $\varphi$ in both cases).
Comment: Sorry if I'm being stupid, but I do not understand where you have shown that $a_{2n}$ is increasing and $a_{2n+1}$ is decreasing
Comment: By the above argument, $a_{2n}-a_{2(n-1)}>0$ so $a_{2n}$ is increasing. Similarly for $a_{2n-1}$.
Comment: GOT IT. Thanks- perfect answer
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13225/discussion-between-guest-and-daniel-littlewood)
Answer: Hint: Consider $\frac{F_n}{F_{n-1}}=1+\frac{F_{n-2}}{F_{n-1}}$. Let $f_n=\frac{F_n}{F_{n-1}}$. We have
$$f_n=1+\frac{1}{f_{n-1}}.$$
Let $f(x)=1+\frac{1}{x}$ for $1<x<2$. Show if $x<\phi$, then $x<f(x)<\phi$ (We also have $\phi<f(x)<x$ for $x>\phi$, but it is irrelevant to our concern.).
Comment: Thank you for this answer. This is how I was able to show that the limit was $\phi$ if it exists, but how do you know $f_n$ exists and is a real number as $n \to \infty$?
Comment: Thanks for the edit. Would you be able to do the next step? Sorry- I am still unclear on how this would prove the existence of the limit given its oscillation?
Comment: @Guest If you showed my claim, then $f_1<f_2<f_3\cdots \le \phi$.


Performance evaluation measures for binary random forest classifier

Question: I am using Random forest (Matlab) to classify the binary data. Broadly, the input to the random forest is number of features and class label. And random forest, after training, return the labels for "unseen" data (30% of the overall data). I have two (very basic) questions related to performance evaluation:

I don't have any threshold, I am using simple random forest implementation in Matlab. Is there any way to compute ROC curve? Will the threshold be "number of tress"? (I am very new to ROC curves, just read about these)
I already calculated TPR, FPR, F-scores and confusion matrix, are there any other performance evaluation measures for binary classification? Pointers or just names will be good help.

Suggestions/Comments?
Answer:
When you say that you don't have any threshold, do you mean that you only get predicted class labels, but not classification scores? Without scores, you cannot compute a ROC curve. If you do get scores, take a look at the perfcurve function in the Statistics and Machine Learning Toolbox.
The doc for the perfcurve function shows other evaluation measures.


How to Set TwoCellAnchor for Images in EPPlus to Enable "Move and Size with Cells"?

Question: I am using EPPlus to programmatically add images to an Excel worksheet in a .NET application. I need the images to "Move and Size with Cells", which requires setting the EditAs property of the ExcelPicture object to eEditAs.TwoCell. However, when I attempt to set this property, I encounter a System.InvalidOperationException with the message: "EditAs can only be set when CellAnchor is set to TwoCellAnchor".
Here's the relevant portion of my code:
using (MemoryStream imageStream = new MemoryStream(imageData)) {
var excelPicture = workSheet.Drawings.AddPicture($"Image_{recordIndex}", imageStream);
excelPicture.SetPosition(recordIndex - 1, 2, 0, 2);
excelPicture.SetSize(200, 200);
excelPicture.EditAs = eEditAs.TwoCell; // This line throws the exception
workSheet.Row(recordIndex).Height = 153;}

I understand that the EditAs property can only be set when the picture's anchor is explicitly set to TwoCellAnchor, but I'm not sure how to do this with the EPPlus API. The documentation and examples I've found do not clearly demonstrate how to set the anchor type for an image when adding it to the worksheet.
Questions:
How can I explicitly set an image's anchor to TwoCellAnchor using EPPlus when adding it to a worksheet?
Is there an alternative approach to ensuring that images added to an Excel worksheet with EPPlus will "Move and Size with Cells"?
Any guidance, code snippets, or references to relevant EPPlus documentation would be greatly appreciated.
Answer: excelPicture.ChangeCellAnchor(eEditAs.TwoCell);


Como fazer para dois apps utilizarem a mesma base de dados no firebase?

Question: boa tarde!
Estou iniciando no mundo de desenvolvimento para mobile. Gostaria de desenvolver dois apps. Em que o app A grava e lê certos dados e esses dados são visualizados (apenas leitura) pelo app B. Estou utilizando o serviço do Firebase. Por onde começo??
Comment: Só criar os aplicativos no mesmo projeto do firebase
Comment: Muito obrigado!!!
Answer: Sim, é possível. Como o @Matheus disse no comentário acima, um projeto Firebase pode ter "n" aplicativos vinculados a ele, e o banco de dados está vinculado ao projeto, não ao aplicativo.
Mas mesmo que os aplicativos não estejam no mesmo projeto, é possível acessar o banco de dados do outro. Mas neste caso você não usará o arquivo json que você baixa do console, e vai ter que inicializar tudo manualmente no app.
Comment: Muito obrigado!!!


Proving relation between related angles of two triangles given two constraints

Question: I stumbled upon a theorem from My Instructor's geometry notes, it goes like
Consider two triangles ABC and PQR such that $\angle$ B=$\angle$ Q And Ratios $(BC/QR)=(CA/RP)$
Then
$\angle$ P=$\angle$ A or  $\angle$ p=180°-$\angle$ A
To prove I used similarity earlier, but failed
Edit: I was able to prove It using Sine law, I will Answer this question myself, any other ideas to prove the theorem will be great
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Answer: In My second Attempt I found That sine rule Helps in proving the above theoeam as follows
$BC=2R_1\sin(A)$ Where $R_1$ is circumradius of triangle (ABC)
$QR=2R_2\sin(P)$ Where $R_2$ is circumradius of triangle (PQR)
$AC=2R_1\sin(B)$ Where $R_1$ is circumradius of triangle (ABC)
$PR=2R_2\sin(Q)$ Where $R_1$ is circumradius of triangle (PQR)
now as $(BC/QR)=(AC/PR)$
It follows that
$R_1\sin(A)/R_2\sin(P)=R_1\sin(B)/R_2\sin(Q)$
Rearranging terms
and substituting $\sin(B)=\sin(Q)$ because  $\angle B=\angle Q$
we get sin(A)=sin(P)
as $\angle A$ and $\angle P$ are both less than 180 degrees,
It follows that
$\angle A$ = $\angle P $
or
$\angle A $=180°-$\angle P$
hence proved


Adding a sub layer in FramerJS

Question: I'm trying to add a sub layer to the main set of layers in a framer prototype:
myLayers = Framer.Importer.load("imported/some-psd")

layer = new Layer();
myLayers.addSubLayer(layer);

But I get the following error:
Uncaught TypeError: undefined is not a function app.js:4
(anonymous function)

Answer: Try adding the superLayer property to the layer var, rather than adding layer to myLayers as a subLayer
In other words:
myLayers = Framer.Importer.load("import/some-psd")
layer = new Layer()
    superLayer: myLayers

Or
layer.superLayer = myLayers

Adding a sub layer in FramerJS


Is there a specific reason to declare GUI components as fields? Also should ActionListener be anonymous?

Question: There are several examples on how to make a simple GUI. The question I have is what is considered the proper way of doing this, and what is the rationale of doing it either way?
I have been using Window Builder Pro under Eclipse, and examining the code that is being generated. Apparently Window Builder prefers to declare components (buttons etc.) as local variables within the main method of the visual class. However there is a button in Window Builder that allows conversion to field. Most examples that I have come across seem to prefer field declaration.
Also many examples show that it is better to create a separate class that extends JFrame. Window Builder just declares JFrame as a field in the class.
Also should I have a single handler for many events or multiple handlers. Window Builder declares anonymous handlers for each event.
I just want to be clear on what the preferred approach is.
Answer:
Is there a specific reason to declare GUI components as fields?

I'd say that you only need to do this if you are going to need to refer to that component somewhere in your program. For example this is usually not the case for most garden-variety JLabels, and so these are probably best declared and used at site of use. Many JButtons and JTextComponents however will need to be used elsewhere and these will likely be best declared as private class fields.

Also should ActionListener be anonymous?

Only if it makes sense to do so. To clarfiy, many/most quick one-off ActionListeners should be anonymous, but larger ones should be private inner classes, and complex larger ones should be separate stand-alone classes. I know of no simple test to distinguish between these other than feel and experience.

I have been using Window Builder Pro under Eclipse, and examining the code that is being generated...

If you're an apprentice Swing coder, you'll probably want to put this tool to the side a bit until you are very familiar with creating Swing GUI's, as GUI builders can be tricky to use if you're not quite familiar with the underlying library. Otherwise if you're a journeyman and certainly if you're an expert Swing programmer, than sure, go ahead and continue to use it.

Also many examples show that it is better to create a separate class that extends JFrame. Window Builder just declares JFrame as a field in the class.

Most experts in the Swing field that I know suggest that it's usually best to not extend JFrame at all, but rather to create and use a JFrame object when needed. There are several reasons for this, but number one is to avoid unintended side effects such as overriding a critical method without realizing. This has happened to me when I've overridden a JComponent and gave it int getX() and int getY() methods. The component would never stay where it was supposed to be located!

Also should I have a single handler for many events or multiple handlers. Window Builder declares anonymous handlers for each event.

Most folks I know use a single handler to handle a single type of action. For instance, if you're creating a calculator, it makes sense to create a single handler to be shared by all the number buttons, and perhaps several for the different types of operations: one handler for the basic math operations such as +, -, *, /, and one for the memory operations, and one each for more complex operations.
Comment: +1 great comments, I would also suggest [Actions](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html) as part of the general action handler discussion, these are most appropriate for re-usable actions (such as "File Open" in the menu and for re-use on the toolbar). IMHO
Answer: @HovercraftFullOfEels already gave very good answers to your questions. I would just like to add a little bit to this one:

Also should I have a single handler for many events or multiple handlers. Window Builder declares anonymous handlers for each event.

I assume you are asking if you should have one handler for many buttons, in the case of ActionEvents. My general rule of thumb is to avoid switch if-else statements which detect which button was clicked. If each button does something drastically different, then I usually create separate anonymous inner classes for each button.


Comparing Fractions that contain epsilon

Question: Given $\epsilon$ a constant s.t. $0<\epsilon<1$, and $n,p$ positive integers, $n >= 2p$, is the following true:
$\frac{(1+\epsilon)n}{(2+\epsilon)p} \geq \lceil\frac{n}{2p}\rceil$
Answer: No, the ceiling can make it fail. Take $n=3,p=1$ the right side is $2$, the left about $3/2$


Binary matrix decomposition

Question: Let $m\in\mathbb{N}$. I have a matrix $A$ which is $m^2\times m^2$, which I need to enter into a computer. I am looking for a decomposition of this matrix as a function of simple matrices. I will provide the actual matrix and an example.

The matrix $A$ is such that
$$
A((i-1)m + \ell,(j-1)m+k) = \delta_{ik}\delta_{jl},
$$
where $i,j,\ell,k\in\{1,\ldots,m\}$. Take $m=3$, then the matrix $A$ is given by
$$
\left[
\begin{array}{ccc|ccc|ccc}
1&0&0&0&0&0&0&0&0 \\
0&0&0&1&0&0&0&0&0 \\
0&0&0&0&0&0&1&0&0 \\
\hline
0&1&0&0&0&0&0&0&0 \\
0&0&0&0&1&0&0&0&0 \\
0&0&0&0&0&0&0&1&0 \\
\hline
0&0&1&0&0&0&0&0&0 \\
0&0&0&0&0&1&0&0&0 \\
0&0&0&0&0&0&0&0&1 \\
\end{array}
\right]
$$

Example of the kind of answer I am looking for. Define $\text{vec}(\cdot)$ as the function which maps a matrix to a column vector, where the columns of the matrix are stacked underneath eachother (going from left to right). Define $B$ as
$$
B((i-1)m + \ell,(j-1)m+k) = \delta_{i\ell}\delta_{jk},
$$
then $B = \text{vec}(I_m)\otimes(\text{vec}(I_m))'$, where $I_m$ is the $m\times m$ identity matrix, $\otimes$ is the Kronecker product and $'$ denotes a transpose.
Thank you in advance!
Answer: If $e_1,e_2,e_3$ are the unit vectors, then the $i,j-$Block of $A$ is given by the $3 \times 3$ matrix. $$B_{ij}= e_j (e_i)^T,$$
which has a $1$ in the $j$th row and $i$th column and $0$ everywhere else.
Then $A$ is given by
$$A=\sum_{i,j=1}^3 (e_i (e_j)^T) \otimes (B_{ij}) = \sum_{i,j=1}^3B_{ij}^T \otimes (B_{ij}) = \sum_{i,j=1}^3B_{ji} \otimes B_{ij}.$$
Comment: Thank you very much. That is exactly the kind of answer I was looking for.

Binary matrix decomposition


Changing system time causes application to hang LINUX (LUBUNTU) TCL/TK

Question: I have a tcl/tk with c desktop application, and one of the requirements is to change the system time, in the background there are threads running from the c code, and "after" commands from the tcl code. Whenever I change the time to an earlier time the system hangs
i.e: 05:50:12 -> 05:45:12 also i get weird behavior when going forward in time. I'm running lubuntu. I'm not sure what to do in this situation, I made some test and it seems the after keeps on waiting after i change back in time.
to change the time i use : exec date --set="STRING" from the tcl code
Comment: Read [time(7)](http://man7.org/linux/man-pages/man7/time.7.html) and learn about [adjtime(3)](http://man7.org/linux/man-pages/man3/adjtime.3.html), [NTP](https://en.wikipedia.org/wiki/Network_Time_Protocol), [chrony](http://linux.about.com/cs/linux101/g/chrony.htm)...
Comment: If you really, really know what you are doing, you can build a custom Tcl with overriden time functions (see http://www.tcl.tk/cgi-bin/tct/tip/233.html) and get total control. Just moving the system time back and forth is a pretty heavy handed tool. So yes, of course you get weird behaviour when you let your system pretend to be time travelling.
Answer: Tcl depends on the system time (converted to seconds from the start of the Unix epoch) increasing fairly close to monotonically for the correct behaviour of a number of things, but most particularly anything in the after command. Internally, after computes the absolute time that an event should happen and only triggers things once that time is reached, so that things being triggered early (which can happen because of various OS events) don't cause problems. If you set the system time back a long way, Tcl will wait until the absolute time is reached anyway, which will look a lot like a hang.
Just synch your clock with NTP (i.e., switch on ntpd) and stop fiddling with the system clock by hand.
Comment: the problem with ntp that it has to be connected to the internet this application won't be connected to the internet.
Comment: Can you give a reason for fiddling with the system time? Why is this needed at all?


Representing displacement vectors in cylindrical coordinates and finding the distance in cylindrical coordinates?

Question:
In cartesian coordinates, we can derive the vector $\vec v_3$ by vector subtraction $\vec v_2-\vec v_1$. We then get the distance between $P$ och $Q$ by taking the absolute value of $\vec v_3$ which then is:
$$\lvert \vec v_3\rvert = \lvert \vec v_2-\vec v_1 \rvert= \lvert (x_2,y_2,z_2)-(x_1,y_1,z_1) \rvert = \sqrt{(x_2-x_1)^2 + (y_2-y_1)^2 + (z_2-z_1)^2}$$
But how can we do this completely in cylindrical coordinates without converting to cartesian coordinates? We only have, and can only use, $\rho_1$ and $\theta_1$ for $\vec v_1$ as well as $\rho_2$ and $\theta_2$ for $\vec v_2$  in cylindrical coordinates $(\rho,\theta,z)$, where $z=0$ in this example.
Answer: Your problem for $z=0$ reduces to the polar coordinate problem already answered here.
$$|\vec v_3|^2=(\vec v_2-\vec v_1)\cdot(\vec v_2-\vec v_1)=|\vec v_1|^2+|\vec v_2|^2-2\vec v_2\cdot \vec v_1$$
Now using cylindrical coordinates, $|\vec v_i|^2=r_i^2+z_i^2$ and $\vec v_2\cdot \vec v_1=r_1r_2\cos(\theta_2-\theta_1)+z_1z_2$.
Then the final answer will be
$$|\vec v_3|^2=r_1^2+r_2^2-2r_1r_2\cos(\theta_2-\theta_1)+(z_2-z_1)^2$$
Comment: Yes, I've seen this solution, but isn't it based in terms of cartesian coordinates/base vectors, $\hat e_x$, $\hat e_y$ and $\hat e_z$ after all? This since, I guess, you must express a distance in constant base vectors? I'm a bit confused about how to interpret the problem I have to admit. How would it look if I want to express the solution completely in cylindrical coordinates with $\vec v_1=\rho_1 \hat e_\rho (\theta_1)$ and base vectors $\hat e_\rho$, $\hat e_\theta$, and $\hat e_z$ etc? Would that be possible?
Comment: I did not use Cartesian coordinates. The $z$ coordinate is there in cylindrical system. The only other reference to the Cartesian system is the angle $\theta$. The issue that you have is that the basis of the cylindrical coordinate system changes with the vector, therefore equations will be more complicated.
Comment: Okay, I see. is it possible to express the solutions with the base vectors of the cylindrical coordinates? Do you have to choose one of the vectors as the reference then or how does that work since they have different vector basis due to different angles? Thanks!
Comment: If you choose one of the vectors as the reference, the cylindrical coordinate system is just a Cartesian system rotated with respect to the original. $\hat e_\rho$ is the new $\hat e_x$, and  $\hat e_\theta$ is the new $\hat e_y$.
Comment: Yes, that seems reasonable. So the only real applicable solution is the one you have described in your first answer above? Or are there any other solutions where "equations will be more complicated"? Thank you.
Comment: In this case, calculating $\theta$ is relatively easy, the $z$ component is trivial ($z_2-z_1$). If you want more complicated, try to repeat the angle calculations for spherical coordinate system.


how can i extract arrays from one array & convert them in object and put them in a new array?

Question: Imagine you have this :

[[{id: 1}], [{id: 2}]]

Is posible to convert the previous array in something like this? :
[{id:1}, {id:2}]
Answer: You can simply use Array.prototype.flat for that:

console.log([
  [{
    id: 1
  }],
  [{
    id: 2
  }]
].flat());
Answer: One way is:

console.log([[{id: 1}], [{id: 2}]].map(arr => arr[0]))

Another way is Array.prototype.flat():

const arr1 = [[{id: 1}], [{id: 2}]]

console.log(arr1.flat())


How to change text color of the last two menus

Question: I'm wondering how to change the color of the last two menus, what I want is instead of using black for the last two menus I want to use white.
URL: https://hrcstaging.wpengine.com/

the last two menus is designed like a button and I want to change the text color to white.
Comment: Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor.
Comment: [Something in my web site or project doesn't work. Can I just paste a link to it?](https://meta.stackoverflow.com/questions/254428/something-in-my-web-site-or-project-doesnt-work-can-i-just-paste-a-link-to-it)
Answer: You could add an ID to those elements and add a CSS property to them.
HTML:
Verify Insurance
Number

CSS:
a#white-link {
    color: white;
}

Demo
Answer: li#menu-item-4779 a, li#menu-item-4780 a  {
    color: white;
    font-weight: bold;
}

thanks guys I got the code and it works good now
Answer: with css you can use
button{
  color: #fff;
}

Or the buttons class, in this case it would be
.btnClass{
  color: #fff;
}

Answer: add this css to your css file.
.main-navigation .main-nav ul li:nth-last-child(2) a,.main-navigation .main-nav ul li:last-child a{
    color:#fff;
}

Comment: Oops, If I add this code the sub menus will became white also
Answer: If you want a more dynamic approach than using IDs, and your menu will retain the same number of list items, you can use pseudo classes. :nth-child should work. :nth-of-type might also work, but I'd use :nth-child.
#menu-primary-menu li:nth-child(7) a, #menu-primary-menu li:nth-child(8) a { color: white }

or
#menu-primary-menu li:nth-of-type(7) a, #menu-primary-menu li:nth-of-type(8) a { color: white }

In your case, if the IDs won't ever change, that's the easiest way, but it's good to know about pseudo classes in general.
Answer: Kindly add two classes with the same name to your buttons. Do

.white{
  color: #fff;
}
<button class='white'>Verify Insurance</button>
<button class='white'>(704)-970-4106</button>

Mention that the button tag can be whatever html element with custom properties. It can be an a tag for example.
You can also replace the #fff code by the name of the color as #fff is the white hex code.
Comment: I tried to put a class but its not working
Answer: ok, for te last item menu:
.your_custom_menu ul li:last-child a{ /** your code here  */ }

for the item before the last:
.your_custom_menu ul li:last-child(2) a{ /** your code here  */ }


Border image on top of table

Question: I have been looking at Z-index to position my  border image on top of my table and its contents. I have managed to get the text to go backwards, but I cannot seem to get all the table backwards or the image forwards. I have added tr within the class.
   position: absolute; //static ,relative ,fixed, absolute
   z-index: -1;

http://jsfiddle.net/wayneker/5v1abef2/5/
td + td {
  border-left:1px solid #eee;
}
td, th {
  border-bottom:1px solid #eee;
  background: #ddd;
  color: #000;
  padding: 2px 10px;
}

.tableBorder {
    -webkit-border-image: url("http://www.ahoymearty.co.uk/basebubble/images/border.png") 30 stretch;
       -moz-border-image: url("http://www.ahoymearty.co.uk/basebubble/images/border.png") 30 stretch;
         -o-border-image: url("http://www.ahoymearty.co.uk/basebubble/images/border.png") 30 stretch;
            border-image: url("http://www.ahoymearty.co.uk/basebubble/images/border.png") 30 stretch;

    //  border-top-width: 50px;
    //  border-right-width: 20px;
    //  border-bottom-width: 10px;
    //  border-left-width: 20px;
      border-width: 50px 20px 10px 20px;
}

Answer: You might need to split the image into 4 borders to get the achieved effect. You also need to make modifications to your background image.

I don't have access to Photoshop or something similar, so I have forked your jsfiddle and added 4 empty pink boxes where you should add your splitted image (top right, top left, bottom left, bottom).
http://jsfiddle.net/w0vbvggv/1/

I've done the CSS inline on each box.

top left image

top right image

bottom image left

bottom image right

You can also use the same background image on the elements like this jsfiddle. I've used the image above to set them aside.

top left image

top right image

bottom image left

bottom image right

Comment: the top left and right are the same image but flipped, so too are the bottom ones
Comment: will absolute work ok when the table expands horizontally and vertically ?
Comment: That shouldn't be an issue!

I've added an image to the original post, where you need to uncover the background-image.
Comment: will try this when i return home also, need to photoshop myself and that is on home pc. will upvote when i check :) but thanks in advance
Comment: Also added a better solution where you use the same background image. :)
Answer: Using the CSS border-image attribute with your table in essence locks the z-index of the table to the image. This may work if you are content to resize your table so that it fits inside the border defined by the image.
Otherwise, to use the z-index on the border image you will need to separate the border image tag as its own element from that of the table. Refer to this SO Q&A for this approach.

Border image on top of table


Find critical points using bordered hessian

Question: Find the critical points of $ x + y^2 $ with the restriction $ 2x^2 + y^2 = 1 $ Use the bordered hessian matrix to classify the critical points.
So, using that $ F(x,y,\lambda) = f(x,y) - \lambda(g(x,y)) $ we have that
$ F(x,y, \lambda) = x + y^2 - 2\lambda x^2 - \lambda y^2 + \lambda $
And the bordered Hessian Matrix would be
$$
        \begin{pmatrix}
        0 & 4x & 2y \\
        4x & -4\lambda & 0 \\
        2y & 0 & 2 - 2\lambda \\
        \end{pmatrix}
$$
Next, the determinant would be
$ 4y^2(-4\lambda) - 16x^2(2-2\lambda) $
If the first derivatives equal to 0, we have that
$ 1 - 4\lambda x = 0  $
$ 2y - 2\lambda y = 0  \Rightarrow  2y (1 - \lambda ) = 0 \Rightarrow  y = 0 $ or $ \lambda = 1$
If $\lambda = 1$, then $ x = {1 \over 4} $
From this, I get a critical point, I think, which is $ ({1 \over 4}, 0) $ . Evaluating the determinant in this point gives
$ 4y^2(-4\lambda) - 16x^2(2-2\lambda) = 2\lambda - 2$
Next I think that I have to analyse $\lambda$ (if it is minor than cero or equal than cero, to see if I obtain a minimum an maximun value?
It is also not clear to me when I get a chair point or a point that I cannot decide what it is.
Answer: Your derivatives w.r.t x and y are o.k. Also your Bordered Hessian Matrix. But you haven´t found all critical points.
You have also to calculate the partial derivative w.r.t. $\lambda$.
$\frac{\partial F}{\partial \lambda}=1-2x^2-y^2=0 \quad (1)$
The two other derivatives:
$\frac{\partial F}{\partial x}= 1 - 4\lambda x = 0  \quad (2)$
$\frac{\partial F}{\partial y}= 2y - 2\lambda y = 0  \quad (3)$
Case 1: $y=0$
Now we can insert $y=0$ in $(1)$: $1=2x^2 \Rightarrow x_{1/2}=\pm \frac{1}{\sqrt{2}}$ Thus the first two crititcal points are $P_1(\frac{1}{\sqrt{2}},0)$ and $P_2(-\frac{1}{\sqrt{2}},0)$
Case 2: $y\neq 0$
From (3) we get $\lambda=1$, because we can divide (3) by $2y$ and get $1-\lambda=0$. If $\lambda=1$, then we get from (2) that $x=\frac1 4$
If you insert the value for x in (1) you will get $y_{3/4}=\pm \sqrt{\frac7 8}$
Thus the next two crititcal points are $P_3(\frac1 4,\sqrt{\frac7 8})$ and $P_4(\frac1 4,-\sqrt{\frac7 8})$
The decision rule for a critical point, $x_0$, by using the Bordered Hessian Matrix, $\tilde{H}$, is:

local maximum, if $\text{det} \ \tilde{H}(x_0)>0$
local minimum, if $\text{det} \ \tilde{H}(x_0)<0$
no decision possible, if $\text{det} \ \tilde{H}(x_0)=0$


Trouble with showing a factored expression

Question: I had a go at expanding and simplifying to prove the first part of this, but couldn't get anywhere, any ideas ?
Thanks.
Show that for every integer n≥0,
$$u^n-v^n=(u-v)(u^{n-1}+u^{n-2}v+...+uv^{n-2}+v^{n-1})=(u-v) \sum_{k=0}^{n-1}u^{n-1-k}v^k$$
Comment: You want to remove the last "$=$" sign
Comment: You are unable to prove the above equality, is that right?
Comment: Yes that's right
Comment: @caleb   Do you know the equtation $x^n -1 = (x-1) (x^{n-1} + x^{n-2} + \cdots + x + 1) $?
Comment: No I haven't seen that equation before
Comment: Thank you @bing, the next part is to differentiate $f(x)=x^{3/7}$ for all x≠0 using this formula, and the definition of a derivative
Answer: It's straight-forward if you expand the right hand side, you'll get:
$$(u-v)\sum_{k=0}^{n-1}u^{n-1-k}v^k=\sum_{k=0}^{n-1}u^{n-k}v^k-\sum_{k=0}^{n-1}u^{n-k-1}v^{k+1}$$
$$=u^n + \sum_{k=1}^{n-1}n^{n-k}v^k - \sum_{k=0}^{n-2}u^{n-k-1}v^{k+1} - v^n$$
$$=u^n + \sum_{k=1}^{n-1}n^{n-k}v^k - \sum_{k=1}^{n-1}n^{n-k}v^k - v^n=u^n - v^n$$


In OpenERP, Import and Export menu not shown

Question: I'm learning OpenERP. I created a new Database but I want to import csv file but not seeing it's menu. Can Any one help me where from I get?
Thanks in Advance,
Cheers
Answer: Following step try it.

Setting Menu => Configuration => General Settings
You See the Import / Export menu. Now mark it True and than go your place where you want to import or Export file.

Hope you will see the what you desire. ;-)


Por que a variável numero retorna uma string vazia quando declaro ela fora de uma função

Question: Quando a função printNumero é chamada, a variável local numero faz o que eu queria, retorna o valor que foi inserido no input. Mas a variável numero global retorna uma string vazia, mesmo eu tendo colocado um valor no input dela.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>bingo.html</title>

<input type="text" id="numero">
<input type="submit" id="verificar" value="Adicione e verifique no Bingo!">

EDIT
Por que a variável numero local(a da função) consegue retornar o valor do input e a variável numero global retorna uma string vazia? Lembrando, sem o auxílio da função, é a variável global mesmo.
Answer: É que do jeito que está, você declara uma nova variável com o mesmo nome dentro do escopo da função printNumero() e a retorna, ou seja, o valor dela é tratado de forma separada do escopo global.
E com em nenhum momento você chama a função printNumero() atribuindo seu retorno a variável numero, a variável inicial permanece intacta.
Uma possível correção seria:
verificar.addEventListener("click", function() {
    numero = printNumero();
    console.log(numero);
});

Ou você pode apenas usar a variável em escopo global, dentro da função, sem redeclará-la. Assim:
function printNumero() {
    numero = document.getElementById("numero").value;
    return numero;
};

Daí, bastaria chamá-la antes de printar, não seria necessária a atribuição.
verificar.addEventListener("click", function() {
    printNumero();
    console.log(numero);
});

EDIT:
Caso não queira usar a função basta atualizar o valor dentro do callback do evento click:
verificar.addEventListener("click", function() {
    numero = document.getElementById("numero").value;
    console.log(numero);
});

Comment: Obrigado, mas, e se a função não existisse e eu usasse só a variável global que eu declarei, o que seria necessário fazer para que o valor não retornasse uma string vazia, ou, não tem como?
Comment: @ThomasDota, editei a resposta ;)
Comment: Muito obrigado pela ajuda :)
Answer: Na hora que você faz isto:
var numero = document.getElementById("numero").value;

Você está copiando o valor do campo para a variável. Como ao carregar a página esse campo está vazio, a variável fica com o valor vazio. Mudanças posteriores no valor do campo não afetam a variável, porque o valor foi copiado.
A maneira mais simples de adaptar o seu código é guardar na variável o próprio campo, em vez do valor dele. Como o campo é um objeto, e não um valor primitivo (string, número, etc), a variável vai guardar uma referência ao campo, e não uma cópia. E você pode usar essa referência para pegar o valor atual a qualquer momento:
var campoNumero = document.getElementById("numero");
var verificar = document.getElementById("verificar");
verificar.addEventListener("click", function() {
    console.log(campoNumero.value); // valor no momento do clique
});

Comment: Muito obrigado, me ajudou bastante :)


Initializing double linked list

Question: I have been writing this code for double linked list but according to the debugging tool there's some segmentation faults. Compiles fine but explodes at run.
header file
#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED

struct Node
{
     int data;
     Node* next; //next node
     Node* prev; //prev node
};

typedef struct
{
     Node* first; //aims to first node
     Node* last;  //aims to last node
} List;

void initList(List &l);

Linked list cpp
#include <cstddef>
#include "List.h"

void initList(List &l)
{
    l.first->data = -1;
    l.first = NULL;
    l.first->prev = NULL;

    l.last->data = -2;
    l.last->next = NULL;
    l.last->prev = NULL;
}

main
   #include <iostream>
   #include <stdio.h>
   #include "List.h"

    using namespace std;

    int main()
    {
        List nlist;

        initList(nlist);

        return 0;
    }

Comment: You are missing the following key concepts that you need to fully understand before you can implement your linked list: 1. Class construction and initialization; 2. Automatic and dynamic scope. You apparently didn't recognize that your list members must be instantiated. You need to go back and reread the relevant chapters in your C++ book. There are too many problems with the shown code.
Comment: *Compiles fine but explodes at run* -- "Compiling fine" doesn't really mean anything.  All it means is that your C++ syntax is legal -- it has no bearing on whether you have logical or other runtime errors.  Also `typedef struct` is from `C`.  What book(s) is (are) teaching you old C-style coding?
Comment: It's also a clear case of a linked list that isn't linked. OP NULLing the pointers doesn't mean they are initialized to anything sensible in the context of a linked list. The recommendation that OP reads up on the topic still holds. It's obvious that they don't yet get it.
Answer: Thanks for the replies, i was expecting more light on the matter but i managed to figure it out. Also i forgot to add that the code posted above wasn't the full code (Since it was above 100+ lines i focused on what i thought was the problem)
The segmentaion fault was from an if statement which was involved in many other functions.
the constructor you were talking about.
Node* initNode(int data)
{
    Node* nNode = new Node;
    nNode->data = data;
    nNode->next = NULL;
    nNode->prev = NULL;

    return nNode;
}

and the function where the segmentaion fault actually was.
bool isEmpty(List l)
{
   if((l.first->next == NULL) && (l.last->prev == NULL))
   {
        return true;
   }
    else
        return false;
}

Sorry for the misleading post and thanks for the help.

Initializing double linked list


Programmatically load the page variant being used on path or node object

Question: I'm attempting to be able to load a page variant given a specific path. My ultimate goal is to loop through all the links in a menu, find out what page_manager variant is being used and load the context data from that variant. I'm able to grab the data just fine if I manually supply a page id. Below is me obtaining the data from the about page I've created in page manager.
<code>$page_storage = \Drupal::entityTypeManager()->getStorage('page');
$variant_storage = \Drupal::entityTypeManager()->getStorage('page_variant');
$about = $page_storage->load('about');
$about_variant = $about->getVariants();
$about_variant = reset($about_variant);
foreach($about_variant->getContexts() as $context){
    $label = $context->getContextDefinition()->getLabel();
    if($label == 'Icon'){
        var_dump($context->getContextValue());
    }
}
</code>
This works just fine. But what if I want to load the context data of each link in a menu? These are links that I can't anticipate. Also some of these links will be regular pages and some will be actual nodes that also have their own variant.
I can load the nodes from the route like so
<code>$params = \Drupal\Core\Url::fromUserInput($path)->getRouteParameters();
if (isset($params['node'])) {
    $node = \Drupal\node\Entity\Node::load($params['node']);
    //We have a node which I don't know how to get the variant of
} else {
    //We have a regular page that I don't know obtain the id of
}
</code>
But even though I have the node I have no idea of a way to interface with it in a way that allows me to obtain the page variant I'm using. If it's a regular page, then as long as I have the page id of it I can load the page variant like I have done before, but I don't know how to obtain that.
So ultimately I suppose I need to be able to programmatically obtain two things

How to obtain the page id from a page given its path
How to see the page variant being used on a node

UPDATE: I did manage to obtain the page with this line
<code>$page = \Drupal::entityTypeManager()->getStorage('page')->loadByProperties(['path' => $link]);
</code>
Still not sure how to grab the variant the node is using yet though.
Answer: In order to get the variant being used by the node I was able to retrieve the info inside the array returned by
<code>$node->panelizer->getValue()
</code>
And to get the page I used
<code>$page = \Drupal::entityTypeManager()->getStorage('page')->loadByProperties(['path' => $link]);
</code>