Proving a family of probability distributions is not complete

Question: Consider the family of normal distributions $$\{N(
\mu,\sigma^2):  \mu \in \mathbb{R}, \sigma >0\}$$  on $\mathbb{R}^n$.  Its claimed in the book Statistical Inference by Silvey that if we restrict to the subfamily where $\mu = \sigma^2$, we have a nonzero function $\mathbb{R}^n\rightarrow \mathbb{R}$, namely $$f(x):= \overline{x}- \frac{1}{n-1}\sum_i(x_i-\overline{x})^2$$
with zero expectation w.r.t. every distribution in the subfamily.  ($\overline{x}$ is supposed to be the average of the coordinates.) This is hard for me to see. Just in the two dimensional case I get a messy integral
$$\int_{\mathbb{R}^2}
\bigg( \frac{x+y}{2} - \big[(x-\frac{x+y}{2})^2 - (y-\frac{x+y}{2})^2\big]\bigg)
\cdot exp \big[\frac{-(x-\mu)^2-(y-\mu)^2}{2\mu}\big]dxdy$$
which even wolfram alpha doesn't want to do. Am I really supposed to hack through this integral? Or is this supposed to be more clear?  I can see that in some sense $f$ is the difference of an average and a variance (although the $n-1$ rather than $n$ in the denominator puzzles me), but I don't know how to make sense of that.
Comment: Just show $E[\overline{x}]=\mu$ and $E \left [ \frac{1}{n-1} \sum_i (x_i-\overline{x})^2 \right ]=\sigma^2$ and use linearity and the assumption. The second calculation is not *quite* so simple, you may want to look up "derivation of the Bessel correction". But it has absolutely nothing to do with the normality assumption.
Comment: @Ian ah, so the Bessel correction was exactly the source of my confusion. That clears it up. thanks.
Answer: In general if $X_i$ are an iid sample from a fixed distribution with finite variance, $\overline{X}=\frac{1}{n} \sum_i X_i,S^2=\frac{1}{n-1} \sum_i (X_i-\overline{X})^2$, then $E[\overline{X}]=\mu$ and $E[S^2]=\sigma^2$. In statistical language we say the sample mean and sample variance are unbiased estimators for the population mean and population variance respectively.
The unbiasedness of the sample mean is just a simple application of linearity.
The presence of the $n-1$ in the sample variance (instead of $n$ as you might expect) is called the Bessel correction. To derive it, first note that $S^2$ is translation invariant, so it suffices to consider the case $\mu=0$. Once you have done that, expand out the square. You have $E[X_i^2]-2E[X_i \overline{X}]+E[\overline{X}^2]$. The first term is just $\sigma^2$ (since we have assumed $\mu=0$). The third term is $\frac{\sigma^2}{n}$ by the independence. The interesting thing is that the second term is $-2\frac{\sigma^2}{n}$: each member of the sample has some positive correlation with the sample mean, which is not exactly cancelled by the $E[\overline{X}^2]$ term.
This is the first instance of the statistical concept of "degrees of freedom".


Marker not shown in google-maps-react

Question: I want to show a simple map with a marker in it.
This is my code:
import React, { Component } from 'react';
import {Map, Marker, GoogleApiWrapper} from 'google-maps-react';
import demoFancyMapStyles from "./MapStyle.json";

export class MapContainer extends Component {
  propTypes: {
      currentPosLat: React.PropTypes.string.isRequired,
      currentPosLon: React.PropTypes.string.isrequired
  }

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Map google={this.props.google}
                zoom={14}
                options={{ styles: demoFancyMapStyles }}
                center={{ lat: this.props.currentPosLat, lng: this.props.currentPosLon }}>

        <Marker position={{lat: this.props.currentPosLat, lon: this.props.currentPosLon}} />

      </Map>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: ("[myApiKey]")
}) (MapContainer)

The map renders fine and even sets the center to my current position.
However, the marker is not shown on the map. I tried setting a custom icon for the marker but this changed nothing.
And whenever I try to use this approach in step 1 like this:
import {GoogleMap, Marker, GoogleApiWrapper} from 'google-maps-react';
[...]
<GoogleMap
        defaultZoom={14}
        defaultOptions={{ styles: demoFancyMapStyles }}
        defaultCenter={{ lat: this.props.currentPosLat, lng: this.props.currentPosLon }}>

  <Marker position={{lat: this.props.currentPosLat, lon: this.props.currentPosLon}} />

</GoogleMap>
[...]

I get this error:
Error: Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
undefined. You likely forgot to export your component from the file
it's defined in, or you might have mixed up default and named imports.

Check the render method of `MapContainer`.

Which approach is the better one, and where am I doing wrong?
Answer: I think you confused 2 packages. The google-maps-react which you are referring to, does not have GoogleMap component, but you are trying to import it:
import {GoogleMap, Marker, GoogleApiWrapper} from 'google-maps-react';

Also, the link to example you provided refers to react-google-maps package. So, I feel you definitely must ave confused the two.

Marker not shown in google-maps-react


In badminton, how do invasion and obstruct interact chronologically?

Question: This question is somewhat theoretical in nature since I've never seen it actually happen, but I just saw an instance that came very, very close, and I wondered what would have been done if it had actually happened.
Section 13 of the Laws of Badminton deals with faults and among other things specifies that:

13.4 [It shall be a 'fault'] if, in play, a player:
13.4.2 invades an opponent's court over the net with racquet or person except that the striker may follow the shuttle over the net with the racquet in the course of a stroke after the initial point of contact with the shuttle is on the striker's side of the net;
13.4.4 obstructs an opponent, i.e. prevents an opponent from making a legal stroke where the shuttle is followed over the net;

Now these two can easily interact with each other since they occur in the same situation: when a player is making a stroke where the racquet goes over the net and ends up on the opponent's court, while the opponent has his racquet up in defence to try to catch the shuttle.
Consider now the following scenario:

Player A has an opportunity to take the shuttle very close to the net and smash/tap it down on the opponent's court
Player B sees this and puts his racquet up in defence to hopefully intercept the smash/tap and get it back over the net
Player A smashes/taps the shuttle, but the shuttle ends up not crossing the net, so Player A strikes the shuttle on his opponent's court
Player B's racquet is positioned in such a way that it completely unambiguously obstructs Player A's racquet in the completion of the stroke

In this situation, Player B put up his racquet in position at the net before Player A had started the stroke, and thus also before Player A commits the fault of striking the shuttle on his opponent's court.
But the actual obstruction that prevents the completion of "following the shuttle over the net with the racquet" does not occur until after Player A has committed a fault – a fault which, incidentally, puts 13.4.2 out of play (since the stroke is no longer "after the initial point of contact with the shuttle is on the striker's side of the net").
So it all boils down to which exact moment in time a fault is taken to occur according to §13.4.4:

as soon as Player B raises his racquet to the net, knowing that Player A will almost certainly try to smash/tap = Player B commits a fault before Player A, so Player A will get the point despite hitting the shuttle on Player B's court
when Player A's movement is actively impeded by Player B's racquet = Player A commits a fault before Player B, so Player B will get the point despite obstructing Player A's stroke.

Which scenario would be followed if it happened in an actual match?
Or would the umpire likely just consider it too close to call (the difference is milliseconds) and play a let?
Answer: All of the referenced faults happen in play; §15.3 means that the first fault ends the rally. The only provision for concurrent faults causing a let is during the service. While in theory §14.2.7 could be used to call a let if the umpire doesn't know what happened first, this is a shaky argument; in practice umpires are strongly encouraged to decide which fault happened first.
In your example, this should be obvious: The umpire must decide whether B obstructed A's shot before A crossed the net. If it did, then it's B's fault and A gets awarded a point. Otherwise, crossing above the net without having hit the shuttle is a fault, and ends play immediately. One of these events almost certainly precedes the other.
The BWF Umpire Manual Level 2 elaborates on the laws:

In order to call a fault for obstruction (...) the
umpire must be convinced that Player B's racket impeded Player A's shot or
altered how it would otherwise have been played.
The umpire should mentally replay the net exchange and make a judgement
as to whether Player A was able to play the shot as naturally intended, or if it
was adjusted in order to avoid making contact with Player B's raised racket.
If the umpire is convinced that Player A had to adjust the shot, then "Fault" should be called. If the umpire is unsure, then "Fault" should not be called.

So it depends on the specifics.
But most likely – both per the rules and umpiring in practice – per ITTO §6.7 the umpire will not fault for obstruction.
On the other hand, crossing the net is very clearly defined, and will be called a fault. Therefore, very likely A will be faulted, and the point will be given to B.
Comment: I guess "It depends" is probably the best possible answer, then. Assume in my scenario that there was no doubt that Player B obstructed Player A. In the example I just saw, Player A's racket actually hit Player B's, and a fault was called on Player B – the only difference was that the shuttle did cross the net (just!) so there was no fault by Player A.
Comment: In the example you saw the ruling is very clear: Touching of the rackets is definitely obstruction, and A didn't commit a fault in the first place.
Comment: Yeah, in that example there was no doubt at all. It was just what made me think, because the slow recap showed that the shuttle was very close to the net, and I wondered what would have been done if it had been just half an inch shorter so Player A had committed a fault.


Result of function, as value in object

Question: Is possible to obtain in sum result of a function ? Not function itself, just result.
let a = 1;
let b = 2;

let object = {
    dummy: 'dummy text',
    sum: function () {
        a + b
    },
}

console.log(object) // { dummy: 'dummy text', sum: [Function: sum] }

I want to obtain : { dummy: 'dummy text', sum: 3 }
I don't want to use an external function
Comment: why not: sum: a + b
Comment: You would need to execute the function.  For example: `console.log({ dummy: object.dummy, sum: object.sum() });`  For a more generic approach, you'd likely need to write some function (potentially recursive if you need to support larger and more complex objects) which iterates the properties of an object, checks if the property is a function, and executes that function.  Which will get very complex once your functions accept arguments.  Overall I guess it's not entirely clear what the goal/need is here.
Answer: If you want a simple static value, you could simply assign a + b as the value for sum. Otherwise you'd need to invoke sum method call.

let a = 1;
let b = 2;

let object = {
    dummy: 'dummy text',
    sum: a + b,
}

console.log(object) // { dummy: 'dummy text', sum: 3 }
Comment: Thanks for quick answer, but I need to keep the function. In fact, in function will be multiple lines of code, but I need to keep all code stick to sum.  Object itself is huge, and I would like the result of the function to be next to sum, for a better visibility in the code. I have no idea if what I want is possible, but I said to ask anyway
Comment: Understood. You could consider separating the function outside the object and then invoke the call inside the object—as mentioned in another answer. A more detailed context might be helpful to get a better answer in this case. What the function does, how they're handled, etc.
Answer: You just need to execute the function instead of initializing it.
This can be done by instantiating the function before and then call it when creating the object.

let a = 1;
let b = 2;

const sum = (a, b) => a + b

let object = {
    dummy: 'dummy text',
    sum: sum(a, b)
}

console.log(object)
Answer: Use an IIFE if you want to assign the result of a function invocation to sum

let a = 1;
let b = 2;

let object = {
  dummy: 'dummy text',
  sum: (function () {
    return a + b;
  })(),
};

console.log(object);

Result of function, as value in object


DynamoDB: How do I do a putItem but just if key doesn't exists in Python?

Question: I use Amazon AWS DynamoDB just new now. In Future I want to put Items in my table but just if a Item with the same key doesn't exist so that I do not override an existing value. You know how I do that? My code:
from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb', region_name='eu-central-1')

table = dynamodb.Table('Movies')

title = "The Big New Movie"
year = 2015

response = table.put_item(
    Item={
        'year': year,
        'title': title,
        'info': {
             'plot':"Nothing happens at all.",
             'rating': decimal.Decimal(0)
        }
    },
 )

I heard of ConditionExpression. But I don't know how to add this on. It don't work like this:
response = table.put_item(
    Item={
        'year': year,
        'title': title,
        'info': {
             'plot':"Nothing happens at all.",
             'rating': decimal.Decimal(0)
        }
    },
     ConditionExpression = "attribute_not_exists",
 )

Because then I get the following error:
Traceback (most recent call last):
  File "/Users/iTom/ownCloud/Documents/Workspace/PyCharm/DynamoDBTest/MoviesItemOps1.py", line 32, in <module>
ConditionExpression = "attribute_not_exists",
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/boto3/resources/factory.py", line 518, in do_action
response = action(self, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/boto3/resources/action.py", line 83, in __call__
response = getattr(parent.meta.client, operation_name)(**params)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/botocore/client.py", line 252, in _api_call
return self._make_api_call(operation_name, kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/botocore/client.py", line 542, in _make_api_call
raise ClientError(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the PutItem operation: Invalid ConditionExpression: Syntax error; token: "<EOF>", near: "attribute_not_exists"

Answer: You have to specify an attribute in your conditional expression, like this:
ConditionExpression = "attribute_not_exists(title)"

Comment: This answer did not work for me. My hash-key has white space on it, I don't know if that could be the problem.


Converting input of State to the abbreviation

Question: I am working on a personal C++ project and one of the features is to save contact information. When it comes to the address I want the state to save in its  abbreviation format.
I am working on a method that will accept a string input of the full name of the state and return a string value of the 2 character state abbreviation. That being said I have been brainstorming with some friends as to the best way to do this. As of right now I have finished the states that begin with 'A'; but before I go through the other 47 states I wanted to broaden my brainstorming by asking this question. If there a "better" or more efficient way to accomplish this? Please look at my function so far.
    std::string Address::formatStateInput(std::string stateInput){
        char firstLetter = toupper(stateInput.at(0)); //makes first character capital for easy checking
        if(firstLetter == 'A'){
        char letterToCheck = toupper(stateInput.at(3)); //makes fourth character capital for easy checking
            //Alabama
            if (letterToCheck == 'B'){
                return "AL";
            }
            //Alaska
            else if (letterToCheck == 'S'){
                return "AK";
            }
            //Arizona
            else if (letterToCheck == 'Z'){
                return "AZ";
            }
            else{
                return "NULL";
            }
        }
        else{return "NULL";}
    }

Comment: Give us an example of the string you pass to the method.
Comment: The string that would pass through the method would be the name of one of the 50 United States (haven't got far enough to accept all countries) such as "Alabama".
Answer: I would use an std::map (or std::unordered_map).
std::map<std::string, std::string> abbrs;

abbrs["Alabama"] = "AL";
abbrs["Alaska"] = "AK";
abbrs["Arizona"] = "AZ";
// ...

Then to look up a state's abbreviation, you'd do something like:
auto pos = abbrs.find(user_input_state_name);
if (pos == abbrs.end())
    error_invalid_state_name(user_input_state_name);
else
    abbreviation = *pos;

Note that in a typical case, you probably don't want to really hard-code all the state names and abbreviations into your source code. You probably want to have the names and abbreviations in an external configuration file.
Comment: With this solution the input would have to be formatted perfectly with the first letter capital and the remaining characters lowercase though.
Comment: @Juken: Yes -- you normally want to take care of that separately (though it may be easier to opt for all lower-case, for example)
Comment: True. I guess that would also come in handy if I need the full state name later also.
Comment: A problem with this is it doesn't handle mispellings and typos. The op's approach could be coded in such a way to minimize this


Implementing a dynamic typed language with LLVM IR

Question: I'm trying to build a JIT compiler for a dynamic language using LLVM C API but I'm stuck at implementing dynamic types, for example in function definition, LLVM needs types for each argument but the type is unknown until runtime based on what the user passes, i googled this for a while but no any good resources about it anywhere, I also tried looking at Julia's source code to see how they did it, unfortunetely the code is big and complex and i have to eye jump everywhere to find such a small detail, from what i seen so far in it is they represent their types as an empty LLVM struct pointers and a func sig type that holds some extra data, but I'm very unsure of how that works or even if I'm explaining it right, any resources can be helpful, an example code is most appreciated, the example doesn't have to be in C API, C++ is also fine I'll convert it myself one way or the other.
Thanks in advance.
Comment: You probably want to implement the value of your language as some tagged union (or as some pointer), and your LLVM IR would return that type.
Comment: do you have a specific question? asking for examples or any off-site resources is offtopic
Comment: That's 1 long sentence and no question in sight!
Comment: The question is the "how" to do that.
Comment: The dynamic type is a property of the value you pass. The value itself has a static type nevertheless. For example, you can be passing `std::variant`: it's a dynamically typed value with static type. Its dynamic type is like a color: just because cars come in many colors (the dynamic aspect), they are still cars. Just because values come in many dynamic types, they are still values: this hints that you need a concrete `Value` type that represents a dynamically-typed value. If you'll make that concrete type fit in a `void*`, then you'll be passing around a suitably sized integer.
Answer: LLVM IR has nothing to do with this. It's already a language. Statically typed one (of course). It has no impact on what can be compiled down to it.
Where are many ways to go about this, but ultimately, it's no different than implementing JIT-compiler for any dynamically-typed language.
Think about how you want it to work. How would it function. How other dynamically-typed langues handle this.
Hint: they are all typed, even if they only have 3 types: Object, String and Number, if not less. They just use some way to figure out the referenced type at run time.
Do you have an existing language in mind or are you in the process of designing it? If it's the former, than study existing implementations/specifications, if it's the former - than you can do anything you want really, you have all the power.
Comment: Thanks, i was thinking of something similar to ruby in my mind, i think I'll look into how MacRuby is done https://github.com/MacRuby/MacRuby its an implementation of ruby with LLVM, although its discontinued the code still might help.
Comment: @FreeTNT so you are creating your own language. In that case, you don't really need to think about LLVM (and especially IR). Think about how it'll work underneath. LLVM IR is more or less just higher-level asm. Implementation detail. You come up with how dynamic types would be implemented in your language. Then you just implement it via LLVM. Or it can be compiled C/C++. Or anything. That's just a back-end at this point. In your own language, you can convert `foo + 42` to anything you want it to be.


Update Active Admin Record from Slack or Form

Question: I'm mildly technical and have never worked with rails, so forgive my ignorance. Our team has a manual process where we update a company record in Active Admin with info from another team. I was wondering if there's a way I can pass information in to Active Admin from Slack, Formstack, or something similar, then update the record. From a cursory google there doesn't seem to be an API to work with. Does anyone have any guidance here?
Comment: Sorry, but this question is way to broad for Stack Overflow. For general discussion and guidance I would suggest to place your question on [reddit](https://www.reddit.com/r/Slack/). Voting to close.
Comment: ActiveAdmin is just a UI layer sitting on top of a database.  You can expose the database via an API that can be called from an other system.
Answer: The question is very broad, but just want to highlight you what is possibility, you can consume API of Slack to do your requirement but it is not being done use ActiveAdmin individual field. Following you can perform
Setup a chat bot of Slack to use, and when someone submit data on that specific bot communication, it will hit another API on your rails project, which will update record accordingly. That mean any spoken to that user/bot of slack will come to rails api(which you have to develop) and will update database.
But if you are thinking just one single field of active admin is collected from team and rest your fill, than have to do very big changes, on record basis, so empty record is created from slack and you just go and reedit records already filled by chatbot of slack and amend it.


CRUD com AngularJS

Question: Tenho uma single-page e preciso salvar o valor de uma variavél no banco de dados.
Como fazer isso usando o angular js?
Essa variavél ela recebe o titulo da minha single-page.
Esse titulo ele será personalizado pelo cliente.
Alguém teria uma dica de como poderia fazer isso apenas usando tecnologias client-side?
Answer: Estou estudando exatamente sobre isso estes dias, para isto, dê uma estudada sobre ngResource (https://docs.angularjs.org/api/ngResource/service/$resource). Você vai precisar de um serviço (como PHP) e um banco de dados (como MySQL) para poder manusear os dados.
Answer: Infelizmente acredito que isto não é possível usando apenas tecnologias client-side (usando file:// como repositório) - AngularJS necessitará de URLs válidas.
Estabeleça um serviço HTTP local (NodeJS, IIS e Apache são alguns candidatos) e sirva seus arquivos a partir deles.
Quanto a bancos de dados client-side, uma sugestão é o IndexedDB.

CRUD com AngularJS


Strict aliasing rule with incompatible but same structs

Question: Does this code violate strict aliasing rule? Why or why not?
#include <stdlib.h>

#define STRUCT struct {int x; char y;}
typedef STRUCT my_struct_t;

void get(my_struct_t *data, int *x, char *y)
{
    *x = data->x;
    *y = data->y;
}

int main(void)
{
    STRUCT *data = malloc(sizeof(*data));
    data->x=100;
    data->y=55;

    int x;
    char y;
    get((my_struct_t*)data, &x, &y);

    return 0;
}

Since structs are not compatible because they don't share a tag my guess would be that this code violates the strict aliasing rule.
Comment: data is already a my_struct_t pointer so there's no need to re-cast it. I don't see where there are any aliasing violations. There could be alignment issues however. It would be better to declare data as STRUCT data; You allocate it dynamically but don't free it. It will free itself when the program terminates, but it's good practice to put in the free anyway as the code may be changed later and someone might forget to free it. Not that it's a big deal in this example.
Comment: @SimonGoater `I do not see` is not a very good assurance. C standard is the only source of information, not someones opinion
Comment: @0___________ Ask C standard then.
Comment: Code compiles with gcc tags -Wall -fstrict-aliasing -Wstrict-aliasing=2 without issuing any warnings.
Answer: The structure pointer data is pointing to a different type from my_struct_t because you have struct { … } *data = …; in main() (after macro expansion), and each time you have struct { … }, you are defining a new type distinct from any other type, even if those structure types have the same members.
C11 §18.104.22.168 Structure and union specifiers ¶8 says:

The presence of a struct-declaration-list in a struct-or-union-specifier declares a new type, within a translation unit.

The italicized terms are part of the syntax of the structure (and union) grammar.
Consequently, you are casting between types with the call
get((my_struct_t*)data, &x, &y);

In theory, that means undefined behaviour.  In practice, it will work with almost any compiler.
I tried using both GCC 11.2.0 and Apple Clang 14.0.0 with extensive options on your code, which I changed to specify static before the definition of get() to avoid errors for "no previous prototype for 'get'":
$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes \
      -fno-common -pedantic -pedantic-errors -fstrict-aliasing -Wstrict-aliasing=2 \
      -c sa43.c
$ clang -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes \
        -fno-common -pedantic -Weverything -Wno-nullability-extension \
        -Wno-nullability-completeness -pedantic-errors -fstrict-aliasing \
        -Wstrict-aliasing=2 -c sa43.c
$

The -Weverything flag for Clang triggers complaints about padding (-Wpadded, could be suppressed by -Wno-padded).  That then exposes a complaint about using /usr/local/include because of -Wpoison-system-directories.  The Clang -Weverything option is not all that helpful because it activates too many warnings, but adding -Wno-poison-system-directories (as well as -Wno-padded) allows the code to compile cleanly.
The -Wno-nullability-extension and -Wno-nullability-completeness are an extremely irritating necessity because otherwise the system headers fail horribly on my MacBook Pro running macOS Monterey 12.6.3.
So, de facto, your code is OK — but de jure, you are casting between different types.
Comment: Re "In practice, it will work with almost any compiler": This particular code may, but we should not conclude any code with aliasing violation like this will "work." E.g., consider a function in another translation unit taking pointers to two differently tagged but otherwise identical structures. The compiler might conclude the two pointers it receives point to different objects.
Answer: Constructs such as yours are allowed in conforming C programs, but not strictly conforming C programs.  In discussing the distinction, the authors of the Standard noted:

A strictly conforming program is another term for a maximally portable program. The goal is to give the programmer a fighting chance to make powerful C programs that are also highly portable, without seeming to demean perfectly useful C programs that happen not to be portable, thus the adverb strictly.

The Standard deliberately gives implementations which are intended to serve narrowly specialized purposes broad latitude to behave in whatever ways would best serve those purposes, even at the expense of being unsuitable for everything else.  Because there are some programs that don't need such such constructs, and the performance of those programs could be improved if compilers didn't have to accommodate them, the C99 Standard waives jurisdiction over the question of which implementations should be expected to support such constructs.
The clang and gcc optimizers will process constructs which pass pointers to structure types which are defined at the point of use meaningfully if invoked with the -fno-strict-aliasing flag, but should not be expected to do so reliably if invoked without that flag.  If defining structure types at the point of use will make it practical to do something that would otherwise more difficult, one should use a compiler configuration that supports such a construct, rather than jumping through hoops to be compatible even with implementations specialized exclusively for tasks where such constructs would not be useful.  Not only would jumping through hoops often make code harder to read, but it can also cause unexpected compiler behaviors which would not have occurred in code written for the -fno-strict-aliasing dialect.  For example, trying to make a function accept pointers to multiple structure types interchangeably by casting the passed address a union of involved structure types may fail if different structures have different alignment requirements, even the passed pointer satisfies the alignment requirements of all the structure types that are actually be used.


Why this site is called expatriates instead of migrants?

Question: Many of us that live abroad don't identify ourselves as "expatriates", but rather as "migrants".
Although it might appear simmilar, "expat" can be considered vocabulary invented to differentiate White or Western people, from other races or origins, living abroad. It can be considered therefore implicitly racist. See for instance this.
Comment: You mean classist, not racist.  See the footnote in [my answer](http://meta.expatriates.stackexchange.com/a/311/6).
Answer: Yes, the word expat(riate) has classist¹ origins.
Why is this site called expats, you ask?
History
Stack Exchange originates in Stack Overflow, a website for programmers.  Many SE sites exhibit a strong bias toward the programming profession, and Expats is no exception.  One site where this is particularly obvious is The Workplace.  Browse the questions there and you will see overwhelmingly disproportionately many more questions concerning software developers than janitors, cleaners, fast food workers (there are some of those, often students), fishermen, farmers in rural Kenya, cooks, drivers, mailmen, barbers, or indeed middle class non-programming professions such as nurses, teachers, doctors, lawyers.  Hence, it is no surprise that the initiative for our Q&A came from white-collar mind workers, quite possibly dominated by software developers.  Within such communities, people often refer to themselves as expatriates rather than migrant workers.
That does not mean that anyone who uses the word expatriate is classist.  More likely than not, most have not thought about it too much.
Our community
On Stack Exchange, we should thrive to be an inclusive community.  Clearly, we welcome questions from migrant workers (and non-workers) in all categories I have listed above and many more.  The key questions to think about are:

Is usage of the name "Expatriates" off-putting to people whose questions and expertise would be a welcome addition to the site, but who do not identify as such?  In other words; are we losing potential users due to our name?
If the answer to question (1) is demonstrably positive, would a name change, such as "Migrants", resolve this problem?
Are there any downsides to a name change?  Might any current users feel less welcome, users who identify as expatriates but not as migrants?  Would we risk losing users?

My view
Personally, I don't like the word expatriate at all.  I've lived outside my home country for nearly ten years.  I've worked as a scientist in Sweden, Canada, and the United Kingdom.  When people talk about migrant workers, they typically think of blue-collar manual workers in restaurants, hotels, agriculture, construction, etc.  I consciously refer to myself as a migrant worker, perhaps just to remind people that migration transcends class boundaries.
I would support a broad and inclusive debate about the pros and cons of a name change.  A name change is a quite radical measure, and should not be taken lightly.  However, if we can show solid evidence that a name change would be beneficial to the site and its users, then I believe it is the right path to take.

¹I think the word is classist, but I don't think it's racist.  A middle class man from Bangalore who moves to Silicon Valley is typically described as an expat.  A construction worker from Bulgaria who seeks a job in Germany is typically referred to as a migrant worker.  Skin colour is not the determinant, although it does correlate with class on a global scale, of course.  The article you link claims that Top African professionals going to work in Europe are not considered expats. They are immigrants., but I am not convinced.  If an African analyst works for a bank in the City of London and earns £200k/year, I believe he or she will be called an expat.
Comment: For example, BBC News uses the word expats for Turks in western Europe: http://www.bbc.co.uk/news/world-europe-39264536
Comment: Yes, I agree with the most part of your comment. I've always been an immigrant indeed, but at some point people started treating me as an expat (when my status changed) so the word results quite annoying to me and my class consciousness. Anyway, my goal was indeed to open some discussion around the issue, so thanks for the clarity. I guess that it would be too ambitious to change the name of the site, although i would not be against.
Comment: As for the racism / clasism debate, also mostly agree with you. I would add indeed that racism is often in fact a manifestation of clasism, as Kareem abdul Jabbar brilliantly exposes here http://time.com/3132635/ferguson-coming-race-war-class-warfare/
Comment: When people talk about migrant workers, they do mean brown people too, I don't think isolated counter-examples or the implied poverty make the word any less racist.
Comment: @Gala Maybe you're right.  Sounds ilke a topic for sociologists to study.
Comment: I am an immigrant (I moved to this country 48 years ago) but not an expat. My mother is an expat, with strong ties and frequent visits to our country of origin. I am most assuredly not a migrant worker, because to me that implies a person who regular goes back and forth between countries according to the work available, or who is **temporarily** in another country for work reasons. I like the name expats because it refers to the state during which people need the site. You're new in town and don't consider yourself a local yet. You are out of your own country and not yet fully in this one.
Answer: Er? Half my office is from India and Bangladesh and they all call themselves expats as well. I think it's stretching it to call it racist.
Names generally come from the area51 site, in this case: http://area51.stackexchange.com/proposals/38732/expatriates
Íf voted on, committed to and accepted, they become these beta sites.
The idea of an expat, to me at least, is also someone who still has ties to their original country, and runs into problems being an expat - eg sending money home, or dealing with international taxation issues.
Technically immigrants have this too, but anyway.  As seen by this thread on quora, there has been language drift on this over time anyway, and the two have kinda merged for many segments of the population.
Comment: Clearly immigrants and usually their children and often even grandchildren have (often strong) ties to their home country.  Just consider the current controversy with Turkish-origin citizens of Germany, Netherlands, and elsewhere in Europe.  I don't think any attempt for an objective non-classist distinction between migrants / migrant workers and expatriates really holds, at least the ones I've seen do not.
Comment: Well, you're right, maybe I could have said classist better. I don't know if you're counting the janitors and cleaning personnel, which is usually latino here where I work, and certainly consider themselves as immigrants (as the society considers them too). And yes, people from their same countries and color, that work in highly educated jobs, consider themselves as expats (maybe because that way they can separate themselves from the former!).
Comment: And anyway, that a majority is voting for a name, does not mean a lot  when it comes to this kind of questions. And certainly I dont think is a valid argument against my complains.
Comment: FWIW, I've lived, studied, and worked outside my home country for almost 10 years and I refuse to call myself an expat, I make a point of calling myself a migrant worker (NB: I work a a scientist at a university).  Still happy to participate in this site, though.


Como colocar um dropdown menu em uma barra de navegação usando bootstrap?

Question: Entendo muito pouco de css e estou tendo dificuldades para colocar um dropdown menu na barra de navegação de uma página.
Eu tenho vários links nessa barra de navegacao e precisava abrir um menu com uma lista de outras opções ao clicar em um item.
HTML:

            Inicio

                  Home

CSS:
.color-links a{
color: #000;
text-decoration: none;
}
.color-links a:hover{
color: #fff;
}
.itens-lista{

width: 24%;
margin-right: 11px;

}

.nav-tabs{
border-bottom: none;
}
.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover{
border: none;
background-color: #ee7e4b;
}

    .nav>li>a:focus, .nav>li>a:hover{
background-color: #ee7e4b;
border: none;
}

.topo-fone{
text-align:right;
font-size:18px;
margin-top: 5px;

}

    @media (max-width: 767px) {

.topo-fone{
text-align: center;
}

.itens-lista{

width: 50%;
margin-right: 0px;

}

}

Answer: Se você esta usando bootstrap basta seguir a documentação oficial.
Ficaria mais ou menos assim:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Brand

Link (current)

Link

          Dropdown

Action

Another action

Something else here

Separated link

One more separated link

http://getbootstrap.com/components/#navbar


iTextSharp - Adicionar imagem TIFF num PDF

Question: Estou a usar as bibliotecas Magick.NET-Q16-AnyCPU versão 7.12.0 e o iTextSharp.
Primeiro abro a imagem com o Magick e guardo essa página do TIFF numa pasta. Depois uso essa imagem para adicioná-la no PDF.
Estive a fazer alterações no código e deixou de funcionar. E já tentei usar um código que eu sabia que estava correto e mesmo assim dá-me este erro:

System.ArgumentException: Extra samples are not supported.
at iTextSharp.text.pdf.codec.TiffImage.GetTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s)
    at iTextSharp.text.pdf.codec.TiffImage.GetTiffImage(RandomAccessFileOrArray s, Int32 page, Boolean direct)
   at iTextSharp.text.Image.GetInstance(Uri url)
    at iTextSharp.text.Image.GetInstance(String filename)
    at ProjetoFCT.Form1.ConvPdfError3(String dest, String[] e) in C:\Users\user\Documents\Projeto\ProjetoA\Form1.cs:line 5253

Código
<code>        public void ConvTiffToPdf(string dest, string[] e)
        {
            for (int i = 0; i < e.Length; i++)
            {
                int pages = 0;
                string output = dest + "\\" + Path.GetFileNameWithoutExtension(e[i]) + ".pdf";
                iTextSharp.text.Document document = new iTextSharp.text.Document();
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(output, FileMode.Create));
                writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
                writer.PdfVersion = PdfWriter.VERSION_1_7;

                string folder = AppDomain.CurrentDomain.BaseDirectory + "temporario\\" + Path.GetFileNameWithoutExtension(e[i]);
                if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

                bool @continue = true;
                while (@continue == true)
                {
                    MagickReadSettings settings = new MagickReadSettings
                    {
                        Compression = ImageMagick.CompressionMethod.LZW,
                        Format = MagickFormat.Tiff,
                        FrameIndex = pages
                    };
                    try
                    {
                        using (MagickImage image = new MagickImage(e[i], settings))
                        {
                            string file = folder + "\\" + Path.GetFileNameWithoutExtension(e[i]) + "- Página " + (pages + 1) + ".tif";
                            image.Quality = 75;
                            image.Format = MagickFormat.Tiff;
                            image.Write(file, MagickFormat.Tiff);

                            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(file); //o erro é aqui
                            iTextSharp.text.Rectangle size = new iTextSharp.text.Rectangle(img.ScaledWidth, img.ScaledHeight);
                            document.SetPageSize(size);
                            document.SetMargins(0, 0, 0, 0);
                            document.Open();
                            iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
                            img.SetAbsolutePosition(0, 0);
                            img.SetDpi(300, 300);
                            cb.AddImage(img);
                            document.NewPage();
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is MagickException)
                        {
                            document.Close();
                            Invoke(new Action(() => { succed = 1; pbar.PerformStep(); caseSwitch = 6; }));
                            @continue = false;
                        }
                        else if(ex is System.ObjectDisposedException)
                        {
                            document.Close();
                            Invoke(new Action(() => { succed = 1; pbar.PerformStep(); caseSwitch = 6; }));
                            @continue = false;
                        }
                        else if(ex is System.ArgumentException)
                        {
                            MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK);
                        }
                        else
                            MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK);
                    }
                    pages++;
                }
            }
        }
</code>
Alguém me podia ajudar a descobrir o que está errado no meu código?
Obrigada desde já.
Comment: O suporte de tiff no iText vai ter sempre problemas porque o formato tiff é essencialmente um saco para uma coleção de formatos de imagem. Se está a usar o Magick para conversões a melhor hipótese e guardar a imagem como PNG e não como tiff. Assim vai sempre funcionar.
Comment: qual versão do itext você está usando?
Comment: @LucasMiranda Eu tenho PDF com versões 1.3 e o iText versão 5 não estava a ler essas versões, então fui procurar a versão 4.1.6
Comment: @PauloSoares bem visto, mas a biblioteca PdfSharp faz o que preciso sem dar erro alguem, de qualquer maneira vou experimentar a guardar como PNG.
Comment: @PauloSoares se guardar como PNG funcionou sem algum problema. Obrigada.
Comment: Recomendaria você abandonar o tiff, por que você precisa trabalhar com essa extensão?
Comment: @LeandeoAngelo eu preciso de trabalhar com ela pois estou a fazer um estágio numa empresa que digitaliza documentos então o formato TIFF tem uma qualidade excelente e sendo que é Tagged é perfeito para organizar documentos.
Answer: Eu tentei usar o PdfSharp e o ItextSharp.
Para coisas simples você precisa escrever muito código sendo que deveria isto estar encapsulado facilitando a sua vida.
Eu sugiro usar a biblioteca IronPDF que tem uma boa documentação e muito mais fácil de usar
Comment: Muito obrigada, já não estou a trabalhar nesse assunto mas pelo que vi, essa biblioteca parece ser uma opção muito interessante.


On nets convergence

Question: I am trying to prove the following statement
If $(x_{\alpha})_{\alpha \in \Lambda}$ verifies that every sub-net has a sub-sub-net which converges to $x$, then $(x_{\alpha})_{\alpha \in \Gamma}$ converges to $x$.
I think it would be useful to let you know the definition of sub-net I am using:
$\{y_e\}_{e \in E}$ is a subnet of $\{x_d\}_{d \in D}$ (where $D$ and $E$ are directed (filtered) sets) if and only if there is a function $f: E \to D$ that verifies the following two properties:

$\forall d \in D$ there is $e' \in E$ such that for all $e\geq e'$, $f(e) \geq d$.

2.$\forall e \in E$, $y_e=x_{f(e)}$
Now, I've tried to show the statement straightforward but I couldn't. So maybe it is easier to show it by the absurd:
Suppose $(x_{\alpha})_{\alpha \in \Lambda}$ doesn't converge to $x$. Then, there is some $U$ open with $x \in U$ such that for all $\alpha$, there is $\alpha'$ with $\alpha'\geq \alpha$ such that $x_{\alpha'} \not \in U$.
I don't know how to get a contradiction from these affirmations. I would appreciate suggestions.
Answer: You have already suggested yourself to start by assuming that $(x_\alpha)_{\alpha\in\Lambda}$ does not converge to $x$.
You wrote:

Suppose $(x_{\alpha})_{\alpha \in \Lambda}$ doesn't converge to $x$. Then, there is some $U$ open with $x \in U$ such that for all $\alpha$, there is $\alpha'$ with $\alpha'\geq \alpha$ such that $x_{\alpha'} \not \in U$.

Let us fix one such neighborhood $U$ and rewrite this slightly: For every $\alpha\in\Lambda$ let us choose $\beta(\alpha)\in\Lambda$ with the property that $\beta(\alpha)\ge\alpha$ and $x_{\beta(\alpha)}\notin U$. (This is basically the same thing you wrote, but I wanted to stress that this element depends on $\alpha$ and also to choose exactly one such element for each $\alpha$.)
Let us denote $D=\{\beta(\alpha); \alpha\in\Lambda\}$. It should be relatively easy to show that $D\subseteq\Lambda$ is a directed set and $(x_\alpha)_{\alpha\in D}$ is a subnet of $(x_\alpha)_{\alpha\in\Lambda}$. Since all elements of $(x_\alpha)_{\alpha\in D}$ are outside the open set $U$, no subnet of this net can converge to $x$.

EDIT: Here follows my original answer, which is unnecessary complicated; but I decided to keep it, some of the facts mentioned there might be useful for someone reading this.
This only works for Tychonoff spaces, since I am using compactification of $X$. I hope this is not too restrictive for you. (But I suppose someone will post proof without this assumption.)

Let us consider the same net $(x_\alpha)_{\alpha\in\Lambda}$ in some compactification $cX$ of $X$.
This make things easier: Working in a compact Hausdorff space, we know that every net has a cluster point. We also know that a net converges if and only if it has unique cluster point. Another useful fact is that $y$ is a cluster point of some net if and only if there is a subnet converging to $y$.
Now if $(x_\alpha)_{\alpha\in\Lambda}$ does not converge to $x$, then there is a cluster point $y$ of $(x_\alpha)_{\alpha\in\Lambda}$ such that $y\ne x$. (Otherwise $x$ would be unique cluster point, hence it would be the limit.)
So there is a subnet $(x_\alpha)_{\alpha\in\Lambda'}$ which converges to $y$ in $cX$. Then every subnet of $(x_\alpha)_{\alpha\in\Lambda'}$ also converges to $y$ in $cX$. Clearly, such subnet does not converge to $x$ in $X$ (or in $cX$, which is the same thing).
Comment: Thanks for the answer, though I haven't seen Tychonoff spaces, I am supposed to prove it for a general topological space. If you can think of an answer or a hint that helps me to show it for $X$ arbitrary topological space, then you can add it to your previous answer
Comment: I have edited my post.

On nets convergence


Dividir o body em 4 partes de cores diferentes

Question: Teria como chegar ao resultado da imagem abaixo utilizando apenas Css no body?

Obs: Sem usar divs

Máximo que consegui:

body{
  background: linear-gradient( to right, red 25%, green 25%, green 70%, yellow 70%, yellow 80%, blue 80%, blue );
}
Comment: Podeira usar ``! Seria mais fácil e acredito eu, possível. Já com o `body` não sei se dá para fazer.
Comment: Por que só com o `body`?
Comment: Quero este plano de fundo na tela inteira.
Comment: Vc quer só as 4 cores ou vc quer 4 containers?
Comment: @JoãoPedroSchmitz Não posso usar `div` amigão para isto.
Comment: @hugocsl isso, só as 4 cores.
Answer: Opção 1
4 backgrounds com 1/4 do tamanho da tela e alinhados cada um em um cando com background-position

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
body {
    background-image:
                    linear-gradient(#f00 0, #f00 100%),
                    linear-gradient(#ff0 0, #ff0 100%),
                    linear-gradient(#0f0 0, #0f0 100%),
                    linear-gradient(#00f 0, #00f 100%);
    background-size: 50% 50%;
    background-position: top left, top right, bottom right, bottom left;
    background-repeat: no-repeat;
}

Opção 2
Exatamente com essas cores eu não consegui por causa do blend-mode das cores... mas deu para chegar em um resultado bem próximo...

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
body {
    background:
    linear-gradient(to bottom, #f00 0, #f00 50%, transparent 50%, transparent 100%),
    linear-gradient(to right, #00f 0, #00f 50%, #ff0 50%, #ff0 100%);
    background-size: 100% 100%, 100% 100%;
        background-blend-mode: difference;
}
Comment: @LeAndrade tranquilo jovem, na verdade eu tb usaria a primeira rss, só que eu fiquei tão frito com o `background-size` que não me dei conta que o `background-position` que era o caminho na verdade... Ei deixei as duas resposta... Boa sorte ai! tmj
Comment: Show Hugo, valeu cara. Vou utilizar a primeira opção. Obrigado pelas duas respostas


É possível fazer streaming de um sinal de vídeo localmente para um browser?

Question: É possível exibir o sinal de TV aberta utilizando uma placa de captura e exibir dentro de um navegador web utilizando HTML5 ou JavaScript?
Considerando que uso Ubuntu.
Comment: No caso de smart TV é possivel usando essa chamada, sabem dizer?
Answer: Depende do driver da placa de vídeo, dá. Muitos drivers podem funcionar de maneira idêntica a uma webcam, então tanto o Flash quanto o HTML5 têm acesso.
Exemplo de vídeo em HTML5:
<video autoplay id="vid" style="display:none;"></video>
<canvas id="canvas" width="640" height="480" style="border:1px solid #d3d3d3;"></canvas>

<button onclick="snapshot()">Salvar um quadro</button>

Verifique se a opção "media.navigator.enabled" está ligada no "about:config", no chrome.

Fonte do exemplo: http://www.scottpreston.com/articles/1442.php
Comment: Conheçe alguma placa de captura que o driver faça o mesmo que o driver da webcam ?
Comment: Estou usando uma AverTV .. instalei aqui no pc só que apenas funciona com o softwares desta placa.
Answer: Outra opção é utilizar softwares para isso como:

Windows Media Encoder
Media Server (versões de servidores do windows)
Flash Media Live Encoder (na minha opinião o melhor)
softwares de terceiros..

O Windows Media Encoder, pega o vídeo da sua placa e transformar em streaming.
Assim você poderá chamar qualquer player tanto em html5 quanto html antigo o vídeo.
Porém consome muita banda, eu com a NET 20MB consigo umas 4~6 pessoas assistindo a 640x420 com qualidade razoável, acho que era uns 480kbps


Different baseline data for sites

Question: I have the data with 2 treatments and 1 site (see the image). I am trying to run a mixed model with the code below.
model <- lmer(Yield ~ Treatment + Variety + (1 | site),
              data = yieldn, REML = FALSE)

However, I have one confusion. If you look at the data the "Treatment" (amount of nitrogen added/present) has three levels but the first level at each site is different. So when the first level of treatment at sites is different but followed by similar second and third level. How do you consider for this variation in the model?
There are three levels of treatments of Nitrogen fertilizer, to check the effects of fertilizer on yield. Treatment level 2 and 3 is to apply exactly same amount of nitrogen to all plots. However treatment level 1 is the amount of nitrogen already present in the soil. but since these sites are different from each other, amount of N present is different. Aim is to check if Nitrogen applied to these sites can gradually increase yield.
Comment: What's the aim of the analysis?
Comment: There are three treatments of Nitrogen fertilizer, to check the effects of fertilizer on yield. Treatment 2 and 3 is to apply exactly same amount of nitrogen to all plots. However treatment level 1 is the amount of nitrogen already present in the soil. but since these sites are different from each other, amount of N present is different. Aim is to check if Nitrogen applied to these sites can gradually increase yield.
Answer: This model,
model <- lmer(Yield ~ Treatment + Variety + (1 | site),
              data = yieldn, REML = FALSE)

Incorporates a random intercept for each site, which accounts for the inherent variability between sites.
This model,
model <- lmer(Yield ~ Treatment + Variety + (1 + Treatment | site),
              data = yieldn, REML = FALSE)

in addition to a random intercept for each site, also contains a random slope for the treatment within each site. This implies that the impact of the treatment on yield varies from site to site.

Different baseline data for sites


How to implement Iterable

Question: I am trying to port the Java code below to Dart and am puzzled about to do this.
In Java the Iterable interface is where clean with one method and to implement this is a snap.
How is this code best transformed to Dart?
/**
 * Chess squares represented as a bitmap.
 */
public class ChessSquares implements Iterable<ChessSquare> {

private static class ChessSquaresIterator implements Iterator<ChessSquare> {
    long bits;
    int nextBit;

    public ChessSquaresIterator(long bits) {
        this.bits = bits;
        nextBit = Long.numberOfTrailingZeros(bits);
    }

    @Override
    public boolean hasNext() {
        return (nextBit < 64);
    }

    @Override
    public ChessSquare next() {
        ChessSquare sq = ChessSquare.values()[nextBit];
        bits = bits & ~sq.bit;
        nextBit = Long.numberOfTrailingZeros(bits);
        return sq;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

@Override
public Iterator<ChessSquare> iterator() {
    return new ChessSquaresIterator(bits);
}

...

Answer: By using IterableMixin you only need to implement the iterator-function.
class ChessSquares with IterableMixin<ChessSquare> {
    @override
    Iterator<ChessSquare> get iterator => new ChessSquaresIterator(bits);
    ...
}

Visit http://blog.sethladd.com/2013/03/first-look-at-dart-mixins.html for a short introduction on mixins.
The Iterator-interface is straight forward. You only have to implement the function moveNext and the getter current.
Comment: Fails for me:
```
class ChessSquare{}

class ChessSquares extends Object with IterableMixin {
  Iterator iterator() => null;
}
```
Gets:
error: Class 'ChessSquares' can't define method 'iterator' and have field 'Iterable.iterator' with the same name. (conflicting_method_and_field at [flutterui] lib/state/sample.dart:330)
Comment: Needs  `Iterator get iterator()` to resolve.
This is a better answer than the accepted solution (when fixed and compiles).
Comment: Fixed the code to work with the current version of Dart. Also removed `extends Object` as that's not required anymore either.
Answer: Soo I tried this which is kind of not what I want since I do not want to extend a base class.
/**
 * Chess squares represented as a bitmap.
 */
class ChessSquares extends IterableBase<ChessSquare> {

  Iterator<ChessSquare> get iterator {
    return new ChessSquaresIterator(this);
  }

  ...

}

class ChessSquaresIterator implements Iterator<ChessSquare> {
  int _nextBit;
  int64 _bits;
  ChessSquare _current;

  ChessSquaresIterator(ChessSquares squares) {
    _bits = new int64.fromInt(squares._bits);
  }

  bool moveNext() {
    _nextBit = _bits.numberOfTrailingZeros();
    if (_nextBit < 64) {
      _current = ChessSquare.values()[_nextBit];
      _bits = _bits & ~_current.bit();
    } else {
      _current = null;
    }
    return _nextBit < 64;
  }

  E get current => _current;
}

Comment: If you don't want to extend a base class, mix in the Mixin class.
Comment: Can you provide an example of the mixin class? IterableMixin is defined as `abstract class IterableMixin implements Iterable `, and so it would seem it also a base class, not a mixin/interface.

How to implement Iterable


Help with note naming in a diminished chord with extensions

Question: I've always considered a diminished chord to be a stack of minor thirds.
But when I think about this, it causes me problems when I try to name the notes.
For instance in a C# diminished chord, we have C#, E natural, G natural and Bb
The intervals between each pair of notes is a proper minor third. So far so good.
But—a minor third up from the top note, Bb, is Db, which although it is enharmonically the same pitch as C#, isn't a C#
Is my initial premise about the structure of diminished chords correct? And is there a way of naming the notes that doesn't involve enharmonic equivalent note names, or lots of double flats?
Answer: The intervals are minor thirds.  But the naming convention comes from a formula using the degrees of the major scale.
(1, b3, b5, bb7)
So, the letter names must match this convention to provide the expected spelling of the chord.  In your example, E#, G#, and B# are the 3rd, 5th, and 7th degree of C# maj.  Hence their appearance in the spelling.  You are now using Bb as the starting point to jump a minor 3rd (which is okay) but then using its 3rd in the spelling (which breaks the standard spelling convention).  As a side note this might be different in Just tuning rather than 12TET.
Answer: Let's consider this

Every interval of a "third" is a step over one note name, for example from C something to E something. The somethings can be e.g. natural, flat or sharp
In a diminished chord you have three notes and TWO such steps
In a fully diminished seventh chord you have four notes and THREE such steps

C fully diminished seventh should be

C something
E something
G something
B something

If all the steps are minor thirds, then I get the following solution for the somethings:

C natural
E flat
G flat
B double-flat

If you want to voice the chord with doubled notes in the next octave you're left with the interval from B double-flat to the next octave's C. Because it's from B something to C something, it must be some kind of a second. So is that an augmented second then?
Following this same logic, let's see what kind of a solution we get for C# fully diminished. Remember, because they're thirds, it has to be C something, E something, G something, B something.

C sharp
E natural
G natural
B flat

At the end of the day, I see the whole thing as a theoretical kludge, trying to shoehorn music to fit into theory. Fully diminished chords fit the diminished eight-note scales nicely (unless you think about the note names), but the note naming scheme is based on having seven note names. In tunings we have commas, and in note naming we have this. Sometimes you'll find bits of theory that seem to describe music in a meaningful way, sometimes not.
Comment: @BrianTHOMAS Yes, the seven-note way of thinking and eight-note way of thinking are a bit like different languages. If your thinking is fixed to the seven-note idea - and our note naming system is based on that assumption! - then having more notes per octave and these weird diminished seventh chords feel like the rules of nature are being bent. It's like in Japanese, you have past tense forms of _adjectives_, so there are separate words for "currently yellow" and "yellow in the past". You need to use a different structure to translate that, because a single word won't work.
Comment: Those are significant points about the conflict between eight-note and seven-note scales, and about how the intervals within the diminished chord must be thee minor thirds and some sort of second, rather than four minor thirds.
Answer: I think part of the problem is how you called the chord generically a "diminished" chord instead of specifically "diminished seventh" or "diminished ninth" chord. As you stack up the thirds you need to keep those extensions in mind.

But—a minor third up from the top note, Bb, is Db

This introduces the same problem. You are now talking about some kind of ninth chord. If you disregard the sharps and flats and just look at letters C E G B D you can see it's some kind of ninth chord.
C# E G B♭ makes the first part specifically a diminished seventh chord.
Now just add on the ninth, lets use octave numbers to make the ninth clear, C#4 D♭5. You want to call that an octave, because the notes are enharmonically equivalent to an octave, but your spelling is a diminished ninth.
C# E G B♭ D♭ is a diminished ninth chord.
Of course it is enharmonically equal to a plain diminished seventh chord, but if you want to spell it with a diminished ninth, then name it with a diminished ninth.

And is there a way of naming the notes that doesn't involve enharmonic equivalent note names, or lots of double flats?

Let's do it again but with a root of C natural.
Start with letters C E G B D
Apply flats to make a diminished ninth chord C E♭ G♭ B♭♭ D♭♭
The way to avoid it is either:

don't bother with the diminished ninth, spell it a just a diminished seventh chord C E♭ G♭ B♭♭ C
use a different root to avoid double flats C E♭ G♭ A C, now it is an A diminished seventh chord.

You probably should not switch around the root to avoid double flats at the expense of clear harmonic function. C diminished seventh should resolve to a tonic of D♭ an A diminished seventh chord should resolve to B♭. Use the spelling that make the function clear.
Answer: The seventh of any chord is a second away from the octave.
The issue at hand is not unique to diminished (seventh) chords. The basic interpretation of all seventh chords are stacks of major and/or minor thirds. A C# dominant seventh, for example, is (from bottom to top) is C#-E#-G#-B (M3-m3-m3). The seventh, B, is a (major) second away from the octave, C#, not a third.
In the diminished seventh case, the seventh is an augmented second from the octave.
As Michael Curtis points out, the third above the seventh is the ninth, rather than the octave. It's just that in a diminished seventh chord, the octave and the (diminished) ninth happen to be enharmonically equivalent.
Answer: Within tuning differences, I'd say your idea of a diminished chord as a stack of minor 3rds is correct.
There are differences between diminished chords and the diminished 7th chords you mention in all but name - regular diminished chords have no 7th and consist of only 3 pitch classes (e.g. C♯-E-G).
There are ways to name some diminished 7th chords that don't involve enharmonic equivalent note names or lots of double flats - just start with sharps instead. (If you're lucky, you can get away with starting with naturals.) Your initial C♯-E-G-B♭ is on the right track. So are D♯-F♯-A-C and B-D-F-A♭. Just don't try looping them back onto themselves.
Answer: Whilst a diminished chord appears to be stacked m3s, it actually isn't - quite. It's better to look at it from the more usual 1,3,5,7 aspect.
Thus, C diminished seventh will have letter names C E G and B. The root stays as such. The third is a minor 3, the 5th is a diminished 5, and the 7 is a diminished 7. So, the 3 is called E♭. The 5 is called G♭. The 7 is called B♭♭.
All that if the root is C. What if, with the same chord, the root is E♭? m3 is G♭. 5 is B♭♭. 7 is D♭♭. Slight change, and getting a little technical. No wonder a lot would write the B♭♭ as A! Having said that, I, along with I suspect many others, don't necessarily play the root as the lowest note. The whole chord goes round and round, and I often feel that the quoted 'root' is there either to fulfil some technicallity, or because that's what the writer decided it was going to be at that moment. Each to his own.


when GC remove class, which only handle event

Question: I create windows form application using MVP design pattern. Example:
IViewInterface view = new FormSome();
IPresenter presenter = new Presenter(view);

In presenter constructor I do something like this:
public Presenter( IViewInterface view ) {
    this.view = view;

    this.view.someEvens += myMethod;
}

Now my question:
What happens when I do something like this:
IViewInterface view;
{
    view = new FormSome();
    IPresenter presenter = new Presenter(view);
}
// if my presenter exists here?

I don't want to call any method from presenter explicitly. I only want to my presenter handle view's event. Does GC remove my presenter from memory, or GC knows that my presenter handle view events, so as long as view exists, my presenter also will exist?
edit
I tested it and it works. But I'm not sure if it works because GC don't destroy my presenter yet, or GC is more intelligent then I thought.
Comment: `this.view.someEvens += myMethod();` Is that a typo? Shouldn't it be `this.view.someEvens += myMethod;`? Otherwise, what does myMethod return?
Comment: This is not a matter of intelligence. By definition, the GC collects all objects that aren't referenced anymore. And your presenter is still referenced as long as the event `someEvens` is attached.
Comment: @KooKiz - I fixed this error. Should be `this.view.someEvens += myMethod;`
Answer: The presenter will still remain "alive" as it is referenced through the event set here
this.view.someEvens += myMethod;

If the view is collected by the GC, the presenter is also destroyed.
But please note that you do not have a reference to the presenter at the moment! You can not access it anymore after the code snipped you've posted.
EDIT
This, by the way, happened to be a problem for me when I thought I had destroyed all instances of a class, but they were still active because I had accidentially used them as event targets. I had TCP commands being handled even though they shouldn't have been handled.
That's why I can tell that what you're asking is actually the case :-)


How to open create form on click of N:N relationship subgrid + button? currently, it shows lookup search behavior

Question: I have N:N relationship between account and custom address entity and on account form, I have subgrid for custom address. On click of subgrid + button, it shows lookup search. But I need to change that to show create form popup. I know in this scenario, I should have used 1:N relationship between account and custom address but at this point, I cannot change that. I tried hiding "add existing associated" button on ribbon but that was hiding + button itself. I want to subgrid + button but want to open create form on its click event. Any help or pointers would be very helpful.
Answer: Make the Account lookup field as "Business required" in N:N entity form, then it will work as expected.
Then, If you have a quick create form & "Allow quick create" is enabled for that N:N entity, (+) will open the QC form. If not "Information" Main Form will popup.
When Account lookup is optional, in-line lookup search experience is default.
Read more
Comment: @GregOwens exactly. Native N:N don't have create form, OP wanted the create form popup, so it's not native. :)
Comment: I can't see how this would work...? The only way to edit attributes on an N:N entity is if it is a "custom" N:N entity (i.e. manually creating a link entity that is simple lookups to two other entities). The link you posted would work fine for 1:N relationships but OP referred to (presumably native) N:N
Comment: @GregOwens Lookup search experience is the only available option for Native N:N subgrid. We cannot achieve entity form experience in Native N:N relationship. Manual N:N is simply 1:N relationships between a new intersect entity and other 2 entities & this can be achieved: https://community.dynamics.com/crm/b/gonzaloruiz/archive/2013/04/29/availability-of-add-new-and-add-existing-buttons-in-sub-grids
Comment: I think this is exactly my point Arun - I don't see how the solution you originally posted is actually possible ("Make the Account lookup field 'business required' in N:N entity form")  This isn't possible - or did I miss something?
Comment: @GregOwens where do you see this is is about native N:N ? Am I missing anything?
Comment: I guess we are approaching this on different assumptions. Whenever I read "N:N relationships" in the context of Dynamics 365 / CRM, I *always* assume it is a "native" relationship (versus manual intersect entity). The OP didn't say that they had created a manual intersect entity so I naturally assume they have a native N:N relationship. In that case, your solution cannot work :)
Comment: Ahh *that's* where we've differed then;I'd interpreted that the OP wanted to show the create form of the "custom address entity". Your solution makes sense to me now.


Who determines the teams shirt colors, and based on what?

Question: From the games I've seen (anywhere, not only in my own country), looks like each team gets one of two colors,  but couldn't find a clear pattern or how it's being determined.
Are there any global regulations about basketball shirt colors assigned to teams?
Related question about shirt colors, however for different sport so likely not really relevant for me.
Answer: Every league has its own regulations.   Most basketball leagues work like this.

Create uniform demo for a "white" and "dark" jersey.
Ask league for permission.
Print jerseys.
Wear "white" version for home games and "dark" for away games (note hockey and American football do the opposite).

Some leagues allow alternative jerseys to the standard two.   Then it is up to the home team to notify league and away team and follow league protocol (or get permission) to wear the non-standard jersey.   So if the Celtics want to wear a throwback green jersey at home they need to make sure the away team is ready with white uniforms (which they might not normally travel with).
This is pretty standard globally as I have played/watched basketball in Europe.
The only stipulations on this - also governed by each league - that I have seen is the number of colors allowed.   The NBA for instance usually tries to limit teams to three colors (there are exceptions but not many) and I have seen overseas the jerseys much more colorful.   The teams themselves choose the colors to go with mascot or just for marketing.
I can't remember the NBA ever rejecting a color scheme based on being too close to another team's because the teams can use the same colors but really the teams are trying to differentiate between each other from a marketing/sales standpoint.
Comment: Thanks, any references for that or is it from personal observations?
Answer: The FIBA rule on uniforms is covered in Article 4
4.3.3 Teams must have a minimum of 2 sets of shirts and:

The first team named in the schedule (home team) shall wear light-coloured
shirts (preferably white).
The second team named in the schedule (visiting team) shall wear dark-coloured
shirts.
However, if the 2 teams agree, they may interchange the colours of the shirts.


How do I access options passed to an acts_as plugin (ActiveRecord decorator) from instance methods?

Question: At the moment I store each option in its own class attribute but this leads to hard to read code when I need to access the passed options from instance methods.
For example if I pass a column name as an option I have to use self.send(self.class.path_finder_column) to get the column value from an instance method.
Notice I have prefixed the class attribute with the name of my plugin to prevent name clashes.
Here is a simple code example of a plugin which is passed an option, column, which is then accessed from the instance method set_path. Can the getters/setters be simplified to be more readable?
# usage: path_find :column => 'path'

module PathFinder
  def path_finder(options = {})
    send :include, InstanceMethods

    # Create class attributes for options
    self.cattr_accessor :path_finder_column
    self.path_finder_column = options[:column]

    module InstanceMethods
      def set_path
        # setter
        self.send(self.class.path_finder_column + '=', 'some value')
        # getter
        self.send(self.class.path_finder_column)
      end
    end
  end
end

ActiveRecord::Base.send :extend, PathFinder

Answer: You can generate all those methods at runtime.
module PathFinder
  def path_finder(options = {})

    # Create class attributes for options
    self.cattr_accessor :path_finder_options
    self.path_finder_options = options

    class_eval <<-RUBY
      def path_finder(value)
        self.#{options[:column]} = value
      end

      def path_finder
        self.#{options[:column]}
      end
    RUBY
  end
end

ActiveRecord::Base.send :extend, PathFinder

Unless you need to store the options, you can also delete the lines
self.cattr_accessor :path_finder_options
self.path_finder_options = options

Note that my solution doesn't need a setter and a getter as long as you always use path_finder and path_finder=.
So, the shortest solution is (assuming only the :column option and no other requirements)
module PathFinder
  def path_finder(options = {})

    # here more logic
    # ...

    class_eval <<-RUBY
      def path_finder(value)
        self.#{options[:column]} = value
      end

      def path_finder
        self.#{options[:column]}
      end
    RUBY
  end
end

ActiveRecord::Base.send :extend, PathFinder

This approach is similar to the one adopted by acts_as_list and acts_as_tree.
Answer: To start with cattr_accessor creates a class variable for each symbol it's given. In ruby, class variables have their names prefixed with @@.
So you can use @@path_finder_column in place of self.class.path_finder_column.
However that's a moot point considering what I'm going to suggest next.
In the specific case presented by the code in the question. The combination getter and setter you've defined doesn't fit ruby conventions. Seeing as how you're essentially rebranding the accessors generated for the path_finder_column with a generic name, you can reduce it all to just a pair of aliases.
Assuming there's an error in the combo accessor (how is the code supposed to know whether to get or set), The finalized module will look like this:
module PathFinder
  def path_finder(options = {})
    send :include, InstanceMethods

    # Create class attributes for options
    self.cattr_accessor :path_finder_column
    self.path_finder_column = options[:column]
    alias :set_path, path_finder_column
    alias :set_path=, "#{path_finder_column}="
  end

  module InstanceMethods
    # other instance methods here.
  end
end

Answer: You can use cattr_accessor to store the configuration value at a class level and use in all your instance methods. You can see an example at http://github.com/smsohan/acts_as_permalinkable/blob/master/lib/active_record/acts/permalinkable.rb
The code to look at is this:
def acts_as_permalinkable(options = {})
          send :cattr_accessor, :permalink_options
          self.permalink_options = { :permalink_method => :name, :permalink_field_name => :permalink, :length => 200 }
          self.permalink_options.update(options) if options.is_a?(Hash)

          send :include, InstanceMethods
          send :after_create, :generate_permalink
        end

Hope it helps!
Comment: -1: Code posted in the question already makes use of cattr_accessor.


Define priority of database access into SQL Server 2008

Question: We're using a SQL Server 2008 database. This database provides data for two main applications:

A website to display a Viewer.
A routing application that needs to be highly responsive !

Is it possible to give different priorities to those two applications and what would be all the possibilities available to us ? I'm afraid that our Viewer website, through a bug or anything else would slow down our routing application.
I want to protect the routing application in order to keep it highly responsive, what are the solutions I could use?
Comment: No, as queries are identical to SQL Server before that. Priotitzation is not a concept and proirities / limits are exactly what the governor is for.
Comment: What server? Did you check the Resource Governor? it is only available in special editions, though.
Comment: I've seen Resource Governor, is there any other ways of doing this ?
Answer: Andy M, to achieve this level of tunning in SQL, you must use the Resource Governor. It can be a problem, since it's available only in the (expensives) Datacenter & Enterprise editions.
If you can't afford this editions, there's a few things you can consider:
GENERAL

Split your database in 2: one for the routing app, another for the viewer app. This way, you can tune them separately, to obtain the best performance;
Consider acquiring HDs to your server (SSD, if you can afford), and split the data/index files between them, to increase I/O (thus the responsiveness);

ROUTING APP

If you need a high performance just in querying data, you can pre-process this data, leaving it in its final modeling. This approach can boost your query performance in orders of magnitude;
If you have to process information for this requests, but not all of this processing is relevant for the output, try to buffer the processing: analyze what data processing can be post-poned, and just write the data to some dummy tables (maybe in another DB), and process them in a different time.


$\sum|B_n|$ converges then $\sum \left(3|B_n|+2\cdot B_n+\frac{\sin(n)\cdot B_n}{n}\right)$ converges

Question: I'm studying to my finals and I was asked to prove the following, a bit strange, theorem:

Let $B_n$ be so $\sum |B_n|$ converges. Then $$\sum\left(3|B_n|+2\cdot B_n+\frac{\sin(n)\cdot B_n}{n}\right)$$ is converges.

I don't understand how to prove it. I don't how anything about $B_n$. I only know about $|B_n|$. How should I prove it?
Comment: Actually, saying that $\sum|B_n|$ converges is the same as saying the series $\sum B_n$ is *absolutely convergent*, so you do know something about $B_n$.
Comment: Shouldn't that sum on $i$ be a sum on $n$? And isn't $\sin n\cdot B_n/n$ undefined when $n=0$?
Comment: @GerryMyerson Actually It said in the exam $\sum |B_n|$ and so I though it was talking about $n=0$.
Comment: I would assume you were meant to think of it as $\sum_{n=1}^{\infty}$.
Answer: Since $$\left|3|B_n|+2\cdot B_n+\frac{\sin(n)\cdot B_n}{n}\right|\leqslant
3|B_n|+2|B_n|+\frac{|\sin(n)|}{n}\,|B_n|$$
$$\leqslant3|B_n|+2|B_n|+|B_n|=6|B_n|$$
(I used that $|\sin x|\leqslant |x|$ for all $x$, so $\frac{|sin n|}{n}<1$ for all $n$) and $\displaystyle \sum_{n=1}^{\infty} |B_n|$ converges, series: $$\sum_{n=1}^{\infty}\left(3|B_n|+2\cdot B_n+\frac{\sin(n)\cdot B_n}{n}\right)$$
is absolutely convergent and therefore convergent.
Comment: $|\sin x|\le1$ is good enough for this question.
Comment: That's true, since $\frac{|\sin n|}{n}\leqslant \frac{1}{n}\leqslant 1$.


Evaluate the line integral given the pathway C= C1+ C2

Question: Evaluate the line integral where
$$
\int_C ydx + x^2dy
$$

C1 is the path of the straight line segment from the origin, (0,0) to the point (2,18)
C2 is the path of the parabola $y=−x^2+8x+6$ from the point (2,18) to the point (5,21)

First I looked at just c1. I found that y=9x. Then I took the integral of
$$
\int_0^2 (9x+9x^2)dx =42
$$
Then I looked at c2 where I took the integral
$$
\int_2^5[(-x^2+8x+6) + x^2(-2x+8)]dx
$$
$$
\int_2^5(-2x^3+7x^2+8x+6)dx = 58.5
$$
I added what I got from C1 and C2 to get 100.5 but this is not correct. Can someone look at my work and see where I am going wrong?
Comment: I think the second integral is wrong. I get $70.5$ evaluating it. If the correct answer in the end is $112.5$ this might be it.
Comment: @mickep That is correct. What did I mess up in my second integral?
Comment: No idea, since the left-hand side is correct, and the right-hand side is not, and you do not provide any further details.
Answer: I've solved the two integral by two distinct methods,
$$\int_{C_1}=\int_{0}^2(9x)dx+\int_0^2x^2d(9x)=\int_0^29x+x^2\cdot9dx=42.$$
$$\int_{C_2}=\int_{2}^5(-x^2+8x+6)dx+\int_2^5x^2(-2x+8)dx$$
$$=\int_2^{5}7x^2+8x+6-2x^3dx=383-\frac{625}{2}.$$
Putting $\int_C Fdr=\int_{C_{1}}Fdr+\int_{C_{2}}Fdr$ for $F(x,y)=(y,x^2)$, then $F(x(t),y(t))=(y(t),(x(t))^2)$.
Thus on $C_1$ we have: $F(t)=F(x(t),y(t))=(9t,(t)^2)$ since $r(t)=(x(t),y(t))=(t,9t)$.
And on $C_2$ we have: $F(t)=F(x(t),y(t))=(-t^2+8t+6,(t)^2)$ since  $r(t)=(x(t),y(t))=(t,-t^2+8t+6)$.
And limits in integrals are the same because $x(t)$ is equals to $t$ in both cases. In your book you can find the following method and compute as follows since the functions and paths satisfy the requiered hypothesis:
$$\int_{C_{1}}Fdr=\int_{0}^2 F(x(t),y(t))\cdot r'(t)dt=\int_0^2(9t,t^2)\cdot (1,9)dt=\int_0^2 9t+9t^2dt=42.$$
$$\int_{C_{2}}Fdr=\int_{2}^5 F(x(t),y(t))\cdot r'(t)dt=\int_2^5(-t^2+8t+6,t^2)\cdot (1,-2t+8)dt=$$
$$=\int_2^5 -2t^3+7t^2+8t+6dt=\left[-\frac{2t^4}{4}+\frac{7t^3}{3}+\frac{8t^2}{2}+6t\right]_{t=2}^{t=5}=$$
$$=-\frac{625}{2}+\frac{875}{3}+100+30+8-\frac{56}{3}-16-12=-\frac{625}{2}+383.$$
Comment: Very thanks much


How to learn pieces by heart when time is limited?

Question: Instruction to learn a piece by heart (3 pages) in a brief space of time (2 days)?
Comment: If it's a piece you don't know very well, it could help to listen to recordings (or just one recording) when you're doing something else. A possible adverse effect is that you interpret everything the same way other people do (especially if you only listen to only one recording). But of course the real answer is: practise a lot. (Maybe someone else has some more specific suggestions, though.)
Comment: See also https://music.stackexchange.com/questions/49251/what-exactly-do-pianists-musicians-memorize and https://music.stackexchange.com/questions/3009/how-do-you-remember-your-music-and-how-do-i-improve-in-this-regard
Answer: Meaningful repetition.
Set aside a certain groups of time, interspersed throughout the next two days, where you can dedicate your total focus on running thru this piece, steadily, and over and over.
Mix it up with other task accomplishment.
Do a load of laundry.
Clean  up the kitchen.
Make some tuna salad and put it in the fridge.
And then get back to it.
Keep your sheet music handy to reference as you go along, but wean yourself off of it each time you run thru the piece.
Meaningful repetition means repeating it until it becomes a comfortable muscle memory. But two hints;
Don't over do it,
and
don't save it all for the last morning of the actual performance.
That's too much pressure, and it'll only make you more nervous.
Make sure you have it wired-tight the afternoon before, and then get a good night's sleep.
Answer: This is what I do:

Break it in chunks
Do 25 minutes of learning sessions followed by 5 minutes of anything else
Give yourself a 15 minute break between four sessions of 25 minutes
Interleave the learning sessions with unrelated tasks sessions

Sometimes I also write down the music when learning without the sheet music.


Alto Saxophone: tremolo using alternate fingerings

Question: On Alto Saxophone, which notes can easily produce a "tremolo" effect, using alternate fingerings?
It's a kind of "warble" effect I'm looking for, but without changing pitch (or without changing pitch much). I've seen and heard sax players produce this effect plenty of times, but what is the best notation? And, which notes in the Alto Saxophone range can produce this effect?
Or can most notes achieve this effect, even if you're not using a "proper" alternate fingering, but instead just using one of the side-keys?
I've just been reading up on saxophone false fingerings here. It's great info, but I wanted some specific advice about which notes have two different fingerings which can be switched between quickly enough to be played as a tremolo (with just one side-key, for instance).
I've seen this effect notated in a couple of ways. Firstly, I found this in a book of Cannonball Adderley transcriptions (using a tremolo):

(Yes, I know these notes are in a pretty extreme register...!)
And, I'm pretty sure this kind of notation would work too (with or without the tremolo mark):
Comment: A trill is by definition to a different note. If you want dual-fingerings for the same pitch, your best bet by far is to talk to a saxophone teacher. (tho' the page you referenced certainly has a solid list of techniques. Have you tried them?)
Comment: I don't play the saxophone! I'm arranging something for sax. I guess "tremolo" might be a better word than "trill"...
Comment: Ah, yes, then, 'tremolo' would be a good way to go.  I actually discussed this w/ my conductor a zillion years ago (in Summer Band Camp :-) ). We were playing a transcription of the Pines of Rome& us clarinets were supposed to mimic the violins' tremolo. Some kids played a trill and I said that was the wrong sound, etc.
Answer: This type of technique is known as a timbral trill where normal fingerings are toggled with false or alternate fingerings in order to produce subtle timbral shifts without actually changing pitch.  Technically speaking, it is actually a repeat tremolo as the pitch is being changed at the microtonal level due to tuning and intonation of the instrument and therefore negligible in most circumstances.
Searching for "contemporary saxophone techniques" yields many examples of charts that show fingerings and their alternates for such use. I would recommend using these charts as a starting point and going from there.
For notation, there are a couple different options:

If the fingering is ad lib., the instruction alternate fingering should be added at the first occurrence, and the abbreviation alt. fing. thereafter.
Above the intended trilled note, place "tr" along with a wavy line to indicate duration. Next to trilled note, place a small black note head in parenthesis to indicate the desired "trill to" pitch.
If a specific rhythm is wanted, write the intended rhythm with each note tied to the next throughout along with the above notation suggestion.
The clearest notation, however, is one with the alternate fingerings written in the music and is my personal recommendation.

N.B. The last should be used in addition to either the wavy line notation above or the tied note values option.
I would use the charts I suggested above to find fingerings to suite your purpose and then put them in the score to fit the corresponding note.
That all said, there is nothing that substitutes actually working with a saxophonist to find out what works.  Figure out some fingerings, write a bunch down, take it to a saxophonist (or the one you're arranging for) and ask them to try each of the fingerings out - which ones sound the best / easiest to use.  Once you know which ones work, use them in the score.
Comment: Absolutely fantastic answer, thank you! I reckon I'll use the less specific "ad lib." notation you suggest above for the arrangements I'm currently doing, but would go for the fully worked out fingerings if composing. In either case though, I will check out the kind of charts you mention, just to check that any note I want to produce this effect on actually has an alternate fingering. Thanks again, I looked quite a bit online, but sometimes you have to know what you're looking for...
Comment: No problem - glad to help!
Comment: This technique is available on trumpet and other valved brass instruments as well.