Invalid Encoding Symbol with Classifier gem

Question: Everything seemed to be working fine as I added items to my Postgres database. Without changing anything, my Rails app started failing whenever it started Madeleine anywhere in my app:
EncodingError in EventsController#update
  invalid encoding symbol
  app/controllers/events_controller.rb:137:in `update'

137 is the problem line:
135 def update
136   @event = Event.find(params[:id])
137   m = SnapshotMadeleine.new("bayes_data")
      ....
    end

I'm able to classify things in the console, though, which is part of what's causing me confusion. In the console, this works fine:
m = SnapshotMadeleine.new("bayes_data") {}
   => #<Madeleine::DefaultSnapshotMadeleine:0x000...
m.system
   => #<Classifier::Bayes:0x000...
m.system.classify "test"

I'm using the latest Classifier gem with Madeleine.
I figured that something was corrupted in my snapshot that it attempted to load, so I removed it, but that didn't solve the problem. Here's my second-to-last snapshot (now the most recent one):
a = File.read('bayes_data/000000000000000000041.snapshot')
a.encoding
   => #<Encoding:UTF-8>
a.valid_encoding?
   => true

Not sure what's going on here. I saw some people with Ruby 1.9.3-p125 had similar problems, so I upgraded to the latest stable release, 1.9.3-p194, but that didn't help, either.
Here's a link to the documentation for Classifier, which mentions how to use Madeleine as well: http://classifier.rubyforge.org/
I'd really appreciate any insight into what's going on here. Thanks!
Comment: Did you ever solve this? I am finding the same issue!
Comment: Never did. I wound up abandoning the feature for the sake of time. I'd recommend finding another, more stable gem.
Comment: you should clean your string before feeding it to the classifier, for example, transliterate the accented characters
Answer: i had an issue with the rails_admin gem with mysql adapter which was not encoding aware, maybe you can check if your postgres adaptar is and if not try another one
Answer: I don't know why the standard Marshal class doesn't work, but I had good results using
m = SnapshotMadeleine.new("bayes_data", YAML) do
  b = Classifier::Bayes.new "Positive", "Negative
end

and then
m = SnapshotMadeleine.new("bayes_data", YAML)

something broken with Marshal? Not really sure.
Answer: You have to make sure the strings that you use to train the data are UTF-8 encoded. If you are training the data set, an ugly hack is to have
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8

in your script.


Problemas copm o pacote "dns" em Python

Question: Estou com um problema em um script onde preciso utilizar o pacote dns em Python.
import dns.resolver

E para executar uma simples verificação de DNS:
my_resolver = dns.resolver.Resolver()
my_resolver.nameservers = ['184.108.40.206']
records = my_resolver.query(domain, 'MX')

Já instalei o pacote, e continuo com o seguinte erro:
    records = my_resolver.query(domain, 'MX')
  File "build/bdist.linux-x86_64/egg/dns/resolver.py", line 1036, in query
  File "build/bdist.linux-x86_64/egg/dns/resolver.py", line 233, in __init__
dns.resolver.NoAnswer: The DNS response does not contain an answer to the question: uol.com.br. IN MX

Alguma dica?
Answer: import dns.resolver

def lista_mx(hosts):
    return ['\n'.join(map(str,[resul for resul in [dns.resolver.query(host, 'MX') for host in hosts][i]])) for i in range(hosts.__len__())]
if __name__ == "__main__":
    hosts = ['google.com','uol.com.br','hawksec.com.br']
    for i in lista_mx(hosts):
        print(i)

40 alt3.aspmx.l.google.com.
20 alt1.aspmx.l.google.com.
30 alt2.aspmx.l.google.com.
10 aspmx.l.google.com.
50 alt4.aspmx.l.google.com.
10 mx.uol.com.br.
10 webserver01.floripa.com.br.

http://www.dnspython.org/examples.html

Problemas copm o pacote "dns" em Python


Postfix rewrite header issue

Question: I currently relay all my cPanel (exim) outbound emails through my Postfix server. However, postfix seems to remove some important part in the header that exim added before sending to relay. As example, exim add in the headers the path of the PHP script that send the email, or the unix user ID of the sender.
Anyone know how to stop postfix relay from removing those important header part ?
Here is an example of headers part that is removed by the postfix relay :
<code>X-PHP-Script: www.website.com/user/email/index.php for 18.104.22.168
X-AntiAbuse: This header was added to track abuse, please include
  it with any abuse report
X-AntiAbuse: Primary Hostname - server.website.com
X-AntiAbuse: Original Domain - website.com
X-AntiAbuse: Originator/Caller UID/GID - [99 32003] / [47 12]
X-AntiAbuse: Sender Address Domain - www.website.com
X-Source:
X-Source-Args: /usr/local/apache/bin/httpd -k start -DSSL
X-Source-Dir: website.com:/public_html/website/email
</code>
Thanks,
Karl
Comment: Can you show us an example of what the headers look like before they get to postfix and after postfix has modified them?
Comment: @larsks I added them in the original post, thanks.
Comment: After doing a tcpdump on the source server, it seems that exim/cpanel doesn't add all those X-AntiAbuse when sending at the relay. So the issue come from exim and not the postfix relay.
Answer: I've finaly find the problem. If anyone have the same problem with cPanel, simply add headers_add = "${perl{mailtrapheaders}}" in the routers configuration of exim.conf

Postfix rewrite header issue


How to convert code to Swift 4 because of undeclared types?

Question: I found some code that won't work in Swift 4. The thing is that SequenceType and GeneratorOf are undeclared and I'm not sure how to convert this code with new protocols in Swift 4.
I tried changing SequenceType to Sequence and GeneratorOf to Iterator, but not sure how it actually works.

public struct WeakSet<T> where T: AnyObject, T: Hashable {
    typealias Element = T

    /// Maps Element hashValues to arrays of Entry objects.
    /// Invalid Entry instances are culled as a side effect of add() and remove()
    /// when they touch an object with the same hashValue.
    private var contents: [Int: [Entry<Element>]] = [:]

    public init(_ objects: T...) {
        self.init(objects)
    }

    public init(_ objects: [T]) {
        for object in objects {
            insert(newElement: object)
        }
    }

    /// Add an element to the set.
     mutating func insert(newElement: Element) {
        var entriesAtHash = validEntriesAtHash(hashValue: newElement.hashValue)
        var found = false
        for entry in entriesAtHash {
            if let existingElement = entry.element {
                if existingElement == newElement {
                    found = true
                    break
                }
            }
        }
        if found {
            return
        }
        let entry = Entry(element: newElement)
        entriesAtHash.append(entry)
        contents[newElement.hashValue] = entriesAtHash
    }

    /// Remove an element from the set.
     mutating func remove(removeElement: Element) {
        let entriesAtHash = validEntriesAtHash(hashValue: removeElement.hashValue)
        let entriesMinusElement = entriesAtHash.filter { $0.element != removeElement }
        if entriesMinusElement.isEmpty {
            contents[removeElement.hashValue] = nil
        }
        else {
            contents[removeElement.hashValue] = entriesMinusElement
        }
    }

    // Does the set contain this element?
     func contains(element: Element) -> Bool {
        let entriesAtHash = validEntriesAtHash(hashValue: element.hashValue)
        for entry in entriesAtHash {
            if entry.element == element {
                return true
            }
        }
        return false
    }

    private func validEntriesAtHash(hashValue: Int) -> [Entry<Element>] {
        if let entries = contents[hashValue] {
            return entries.filter {
                $0.element != nil
            }
        }
        else {
            return []
        }
    }
}

private struct Entry<T> where T: AnyObject, T: Hashable {
    typealias Element = T
    weak var element: Element?
}

// MARK: SequenceType
extension WeakSet: SequenceType {
    typealias Generator = GeneratorOf<T>

    /// Creates a generator for the items of the set.
    public func generate() -> Generator {
        // This is not straightforward because we need to iterate over the arrays and then their contents.
        var contentsGenerator = contents.values.enumerated()         // generates arrays of entities
        var entryGenerator = contentsGenerator.next()?.generate()  // generates entries
        return Swift.GeneratorOf {
            // Note: If entryGenerator is nil, the party is over. No more.
            if let element = entryGenerator?.next()?.element {
                return element
            }
            else { // Ran out of entities in this array. Get the next one, if there is one.
                entryGenerator = contentsGenerator.next()?.generate()
                return entryGenerator?.next()?.element
            }
        }
    }
}

So, I'm getting undeclared type error for SequenceType and GeneratorOf, and I kind of don't understand this generate() method at the bottom.
Comment: [This question](https://stackoverflow.com/questions/30565875/what-is-the-difference-between-sequencetype-and-collectiontype-in-swift) might be a good place to start
Comment: Yeah, I looked at it already. That gave me some understanding but not enough to figure this out myself. Thanks for the answer.
Answer: The thing here is that I wanted Weak Reference Set. But I found another solution. If anyone needs it here it is:
class WeakObject<T: AnyObject>: Equatable, Hashable {
    weak var object: T?
    init(object: T) {
        self.object = object
    }

    var hashValue: Int {
        if var object = object { return UnsafeMutablePointer<T>(&object).hashValue }
        return 0
    }

    static func == (lhs: WeakObject<T>, rhs: WeakObject<T>) -> Bool {
        return lhs.object === rhs.object
    }
}

class WeakObjectSet<T: AnyObject> {
    var objects: Set<WeakObject<T>>

    init() {
        self.objects = Set<WeakObject<T>>([])
    }

    init(objects: [T]) {
        self.objects = Set<WeakObject<T>>(objects.map { WeakObject(object: $0) })
    }

    var allObjects: [T] {
        return objects.compactMap { $0.object }
    }

    func contains(_ object: T) -> Bool {
        return self.objects.contains(WeakObject(object: object))
    }

    func addObject(_ object: T) {
        self.objects.formUnion([WeakObject(object: object)])
    }

    func addObjects(_ objects: [T]) {
        self.objects.formUnion(objects.map { WeakObject(object: $0) })
    }
}


list_filter in admin

Question: DECOM_CHOICES = (
    ('N', 'No'),
    ('Y', 'Yes'),
)

class Host(models.Model):
    hostname = models.CharField(max_length=36, unique=True)
    decommissioned = models.CharField(max_length=1, choices=DECOM_CHOICES, default='N')
    ip_address = models.IPAddressField()
    def __unicode__(self):
        return self.hostname

class HostAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Host Info', {'fields': ['hostname','decommissioned','ip_address']}),
    list_display = ('hostname', 'ip_address', 'decommissioned')
    list_filter = ('decommissioned')

Now is there any way so that i can set decommissioned filter to 'N' by default instead of 'All'?
Comment: http://code.djangoproject.com/ticket/8851
Answer: Looks like you're using code almost exactly from a Django ticket, which has a workaround in the comment for setting the default filter value. At present there's not a particularly elegant way to do this.
As an aside - wouldn't you be better of using a boolean field, since you're storing yes or no?
Answer: I do this by modifying the GET data in the request object before passing it to changelist_view(). Not elegant, but it works.
class MyModelAdmin(admin.ModelAdmin):
    def changelist_view(self, request, extra_context=None):
        if not request.GET.has_key('decommissioned__exact'):
            q = request.GET.copy()
            q['decommissioned__exact'] = 'N'
            request.GET = q
            request.META['QUERY_STRING'] = request.GET.urlencode()
        return super(MyModelAdmin,self).changelist_view(request, extra_context=extra_context)

Note: I haven't tried this exact code here, but you should get the idea.
Comment: Is there any way to make the 'All' link working with your solution ?
Answer: if ('HTTP_REFERER' in request.META) and (request.META['HTTP_REFERER'].find('?') == -1) and (not request.GET.has_key('status__exact')):
Use this save condition instead of the given in the above sulution given by 'gerdemb' so that all can also be selected

list_filter in admin


Como fazer is_unique de dois campos?

Question: Estou com uma necessidade que não sei como realizar.
Bom, o meu problema:
Tenho um campo is_unique que se refere a dois campos do meu BD, o IDENTIFICADOR e a PLANTA.
Gostaria de saber como realizar essa validação?
para um único campo eu utilizo assim:
<code>$imeiRules = "required|min_length[3]|max_length[45]|xss_clean|strip_tags";
        if($this->input->post('txtImei') != $this->input->post('imeiOld')){
            $imeiRules .= " |is_unique[equipamento.equipamento_imei]";
        }
</code>
só não sei fazer com doi campos unicos.
Comment: Obrigado, agora consegui entender como realizar a validação.
Comment: Já tentou fazer `"|is_unique[campo1]|is_unique[campo2]"` ?
Comment: Pior que já... e nada.
Comment: Veja essa resposta http://stackoverflow.com/questions/14575165/validation-unique-field-in-codeigniter-with-2-index
Answer: Deixarei traduzido o link que o @Wallace Masters informou acima para quem não sabe inglês.
"Eu não acho que o CI tenha uma solução interna para caso com mais de uma Chave Primaria. Eu usaria um callback_ como este:
Mas perceba que você precisa enviar a segunda chave primária como uma uma informação extra e a regra precisa ser aplicada na primeira chave primária.
Pesquise na documentação por callbacks para saber mais."
<code>$this->form_validation->set_rules('form_field', 'form_label', 'callback_combpk[$pk2]');
    public function combpk($pk1, $pk2)
        {
               $this->db->where('field1', $pk1);
               $this->db->where('field2', $pk2);
               $result = $this->db->get('table');
               if($result->num_rows() > 0)
               {
                  $this->form_validation->set_message('combpk','something'); // set your message
                  return false;
               }
               else{ return true;}

        }
</code>

Adição minha:
Callbacks - Usando sua própria validação ( CI 3.0 )

Como fazer is_unique de dois campos?


How to fix the type or namespace 'App_Code' does not exist in the namespace 'WebApplication1'

Question: I want to create a shopping cart, but i get this error. As you may see, i have the ShoppingCart class in the  WebApplication1.App_Code namespace but when i try using WebApplication1.App_Code in the Default.aspx.cs, it does not work.
namespace WebApplication1.App_Code
{
    public class ShoppingCart
    {
        public List<CartItem> Items { get; private set; }

        public static readonly ShoppingCart Instance;

        static ShoppingCart()
        {
            if (HttpContext.Current.Session["ShoppingCart"] == null)
            {
                Instance = new ShoppingCart();
                Instance.Items = new List<CartItem>();
                HttpContext.Current.Session["ShoppingCart"] = Instance;
            }
            else
            {
                Instance = (ShoppingCart)HttpContext.Current.Session["ShoppingCart"];
            }
        }

using System;
using System.Data;
using System.Linq;
using WebApplication1.App_Code;
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnAddShoes_Click(object sender, EventArgs e)
        {
            ShoppingCart.Instance.AddItem(1);

            Response.Redirect("ViewCart.aspx");
        }

Answer: You have to make sure the ShoppingCart.cs file is set to compile. To do this Right click on the file and in the properties set the BuildAction to Compile.


Is there any way to get back the committed changes before a git revert?

Question: I accidently performed a git revert so that I could change a spelling mistake in the immediate previous commit message
$ git commit -m "fix: pagination for tag, auhtor pages"
[dev 389531c] fix: pagination for tag, auhtor pages
10 files changed, 398 insertions(+), 64 deletions(-)
...

$ git revert 389531c

I have lost all my changes and want to get them back. I have tried git reset 389531c and git cherry-pick 389531c but I am not getting my committed changes back and digging myself more into reset. Is there any way to get them back? I am not familiar with "advanced" git commands.
What I want is to get the changes I committed in HEAD@{4}.Here is my git reflog> Thank you.
$ git reflog
389531c (HEAD -> dev) HEAD@{0}: reset: moving to 389531c
389531c (HEAD -> dev) HEAD@{1}: reset: moving to 389531c
389531c (HEAD -> dev) HEAD@{2}: reset: moving to HEAD@{1}
e7d8df9 HEAD@{3}: revert: Revert "fix: pagination for tag, auhtor pages"
389531c (HEAD -> dev) HEAD@{4}: commit: fix: pagination for tag, auhtor pages
f4c0fb3 (origin/main, origin/HEAD, main) HEAD@{5}: checkout: moving from main to dev

Comment: Well, I'm also curious to know if it is possible. But for your future reference, you should have used `git commit --amend` to fix the commit message
Comment: @LeonardoAlvesMachado Turns out it was possible as @TTT answered. Yes I will keep in mind about `--amend` flag in the future. Thank you.
Answer: Solution: Add --hard to your reset command.
Reason: The command git reset 389531c defaults to --mixed which means your reverted changes will be pending and still present in your local directory. When you do --hard it will also delete those reverted changes.  Another thing you can do is undo your pending changes after a mixed reset.
Side Note: As Leonardo Alves Machado pointed out in a comment, a simple way to fix the spelling error (which you can still do after the hard reset) is to make your minor tweak and amend your existing commit (git commit --amend).
Comment: Thank you. This worked. I have learnt something of value.
Comment: @dEBAM Happy to help. Learning something of value is why we're all here!


Simple timed based cache accessed by multiple threads

Question: I have data that i want to cache for set period of time, this data is accessed by multiple threads.
I have created simple cache mechanism for it:
public class ExpirationCache<T> {
    private final Supplier<T> computable;
    private final long validTime;
    private final Lock lock = new ReentrantLock();
    private LocalDate lastAccess;
    private Future<T> data;

    public ExpirationCache(Supplier<T> computable, long validTime) {
        this.computable = computable;
        this.validTime = validTime;
    }

public boolean hasExpired() {
    if( lastAccess == null ){
        return true;
    }
    return LocalDateTime.now().isAfter(lastAccess.plus(validTime, ChronoUnit.MILLIS));
}

    public T getData() throws InterruptedException {
        while (true) {
            if (hasExpired()) {
                FutureTask<T> ft = new FutureTask<T>(computable::get);
                try {
                    lock.lock();
                    if (hasExpired()) {
                        data.cancel(true);
                        data = ft;
                    }
                } finally {
                    lastAccess = LocalDate.now();
                    lock.unlock();
                }
            }
            try {
                return data.get();
            } catch (CancellationException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

My question is about 'data' and 'lastAccess' variables, since i am making compound execution and not locking them on every access.
Could there be scenario

when first call to hasExpired results into false, but millisecond after, another thread calls the getData method hasExpired results into true, goes into sync block and change the data varaible refference and thus the first thread  results into undefinned behavior?

does locking prevents instruction reorganization? Or could i set new value for data and lastAccess in one thread since hasExpired was true, but the second thread invoked right would see new value for lastAccess but old value for data?

If some of the points are correct, what is the correct way to fix it? Do i need  make lastAccess or data AtomicRefferences? Every scenario which could lead to unwanted behavior includes haxExpired call, however locking it with lock would basicly made this class synchronous.
On top of that, given the scenario when calculation of data takes longer than validTime, before setting refference of data to new Future i cancel the operation, does this mean my computable variable has to listen fo interrupted flag to proper exit the computation ?
Thanks for help!
Comment: @Johnyb No, not `LocalDateTime`. Never call `LocalDateTime.now`. That class lacks the context of a time zone or offset-from-UTC. So that class cannot represent a moment, a specific point on the timeline. For a moment, use `Instant` or `ZonedDateTime` (or `OffsetDateTime`, mainly for SQL in JDBC).
Comment: Note: `LocalDate` contains only date (day, month, year), but not time (hour, minute, second, millisecond), so `hasExpired` may not work like you would expect it to.
Comment: @ŠimonKocúrek ah yes should be LocalDateTime my bad.
Comment: Also, I may be wrong on this one, but the `FutureTask` does not seem like it would execute on the background, if you don't submit it to an executor.
Answer: I would suggest using the well-established pattern used for thread safe singletons:
public class Singleton {

    private static volatile Singleton instance = null;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

So in your case it would be:
public class ExpirationCache<T> {

    ... volatile variables

    public T getData() throws InterruptedException {
        if (data == null || isExpired()) {
            synchronized(lock) {
                if (data == null || isExpired()) {
                    data = computable.get();
                    lastAccess = Instant.now();
                }
            }
        }
        return data;
    }
}

change the data varaible refference and thus the first thread results into undefinned behavior?

It would either return data that was still valid at the time of the request, or the refreshed data. That should not be a problem with cacheable data.

does locking prevents instruction reorganization?

I would suggest adding volatile keyword to all variables you don't want to get reorganized.
Comment: I thought an enum was the the well-established pattern used for thread safe singletons.
Comment: This is not what an enum does under the hood.  This is not a well known pattern.  It isn't even a particularly good pattern.  OP: correct pattern: https://stackoverflow.com/questions/15019306/regarding-static-holder-singleton-pattern
Comment: An enum is doing the same thing under the hood. (And also does not support inheritance)
Comment: @markspace https://en.wikipedia.org/wiki/Singleton_pattern#Lazy_initialization . Any reason, why it shouldn't be good? Do you know other simple, thread safe implementation for lazily initialized singleton? And if yes, why is it better than this one?
Comment: I don't care.  That's double checked locking, which is different from the well known Java pattern I linked to.


How to find time period of a discrete time signal?

Question: [] = cos (/8− )
Getting the value of cos(0)=1. For that we get n=8 and for again getting cos(x)=1, we can put n=24. So the value is repeating itself in the interval of 16. How do i state it mathematically? Or there is some another answer?
Can anyone please demonstrate by solving the above problem?
Comment: What is the sampling rate?
Comment: (-)infinity to +infinity
Comment: that is not a sampling rate
Answer: Note that the normal cosine function has a period of $2\pi$. To find the period of this function, we want to find the smallest positive $n$ such that $\frac{n}{8} - \pi$ is a multiple of $2\pi$ off of $\frac{0}{8} - \pi$. Note that setting $\frac{n}{8} - \pi - (0 - \pi) = 2 \pi k$ for arbitrary integer $k$ gives us $\frac{n}{8} = 2\pi k$ so $n = 16\pi k$. Then the minimum positive value at $k=1$ gives us a period of $16 \pi$.
In general, for sinusoids of the form:
$$f(x) = a\cos (bx - h) + k$$

$a$ represents amplitude
$b$ represents frequency (so the period is given by $\frac{2\pi}{b}$)
$h$ represents horizontal shift (to the right)
$k$ represents vertical shift (upwards)
Comment: Thanks. Amazing explanation. Just for what was looking for. (y)


Tipos iguais mas com objetos diferentes. Qual a melhor forma de usá-lo?

Question: Tive que criar um novo objeto mas totalmente igual ao existente no sistema C#. Já que os objetos são iguais tentei fazer:
ObjetoOriginal.Propriedades = ObjetoClone.Propriedades;

Infelizmente não funciona não é?
Tentei então:
ObjetoOriginal.Propriedades = (ObjetoOriginal)ObjetoClone.Propriedades;

E nada.
Então tive que fazer algo assim:
ObjetoOriginal.Propriedades.A = ObjetoClone.Propriedades.A;

ObjetoOriginal.Propriedades.B = ObjetoClone.Propriedades.B;

Qual seria a melhor forma para pegar todas as propriedades de uma vez?
Comment: Você tem controle sobre essa classe? Pode mexer nela?
Answer: Primeiro ponto: você deve pensar 10 vezes antes de clonar um objeto. Costuma ser problemático fazer isto e quase sempre não é necessário.
Se o objeto foi pensado para ser clonado ele implementará a interface IClonable. Eu já respondi sobre isso. E é recomendado fazer isso apenas onde é necessário e com muita consciência. É fácil fazer errado.
Me parece que está querendo clonar qualquer objeto. Se o objeto não foi pensado para ser clonado é quase certo que estará cometendo um erro, mas pode usar reflexão para fazer isso sem ter que ficar copiando cada membro manualmente. Idealmente crie um método para fazer isso de forma genérica:
static class ObjectUtil<T> {
    public static T Clone(T obj) {
        Type type = obj.GetType();
        var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        var cloned = Activator.CreateInstance(type);
        for (int i = 0; i < fields.Length; i++) {
            fields[i].SetValue(cloned, fields[i].GetValue(obj));
        }
        return (T)cloned;
    }
}

Veja funcionando no ideone. E no repl.it.  Também coloquei no GitHub para referência futura.
Comment: Olá, Tivemos que clonar o objeto por causa de melhorias.
Estamos levando tudo o que há em certo projeto para outro.
Então durante execução eu preciso "recriar" o mesmo objeto com o novo tipo.
É algo assim meu cenário.
Enfim, da forma que eu fiz resolve este problema. Problema este que penso que não voltará a acontecer.

Mas irei testar o que mandou.
Abs
Comment: Esse é um caso que pode ser útil, mas faça com cuidado. Teste bem.
Answer: Implemente a classe ICloneable na sua classe que vai te proporcionar clonar uma cópia da classe com os mesmo valores, mas, sendo objetos distintos. Dentro do método criado pela implementação ICloneable chame MemberwiseClone() que retorna uma cópia em um novo objeto.
Código:
public class Propriedades: ICloneable
{
    public Propriedades()
    {

    }
    public int Id { get; set; } = 1;
    public string Name { get; set; } = "Name 1";

    public object Clone()
    {
        return MemberwiseClone();
    }
}

Usar:
Propriedades p = new Propriedades();
Propriedades c = (Propriedades)p.Clone(); //Clone "ICloneable"

Uma outra forma é utilizando reflexão (reflection):
Propriedades propr1 = new Propriedades();
propr1.Id = 2;
propr1.Name = "Nome 2";
Type propType1 = propr1.GetType();

Propriedades propr2 = new Propriedades();
Type propType2 = propr1.GetType();

foreach(PropertyInfo info in propType1.GetProperties())
{
    propType2.GetProperty(info.Name)
        .SetValue(propr2, info.GetValue(propr1));
}

o código acima pode ser simplificado com métodos de extensão com um código assim:
public static class Utils
{
    public static T Clone<T>(this T _t)
        where T: class
    {
        T _r = Activator.CreateInstance<T>();
        Type _t1 = _t.GetType();
        Type _r1 = _r.GetType();
        foreach (System.Reflection.PropertyInfo info in _t1.GetProperties())
        {
            _r1.GetProperty(info.Name)
                .SetValue(_r, info.GetValue(_t));
        }
        return _r;
    }
}

e sua utilização é bem parecido com a primeira alternativa:
Propriedades propr1 = new Propriedades();
propr1.Id = 2;
propr1.Name = "Nome 2";

Propriedades propr2 = propr1.Clone(); // método de extensão

Tem também um pacote do nuget o AutoMapper, exemplo:
Propriedades propr1 = new Propriedades();
propr1.Id = 2;
propr1.Name = "Nome 2";

Mapper.Initialize(cfg => { });
Mapper.Configuration.CompileMappings();

Propriedades propr2 = Mapper.Map<Propriedades>(propr1);

Observações: eu passaria os valores para as nova instâncias para não ter problema com referencias e valores inesperado. Só usaria se isso não comprometesse o código e suas instâncias, ainda o modo atribuição simples é o melhor jeito de implementar.
Referencias:

Interface ICloneable
Object.MemberwiseClone Method ()
How to Clone Objects
O que é Reflection, por que é útil? Como usar?
Para que usar métodos de extensão do C#?
Answer: Venho aqui adicionar uma alternativa, que pode vir a ser útil caso a classe tenha uma referencia circular e você tenha domínio sobre a mesma.
Você pode decorar ela com o atributo [DataContract] e [DataMember] e seriaizar o binário da mesma usando o DataContractSerializer
segue o exemplo.:
var serialize = new DataContractSerializer(typeof(MyClass));
var myClone = default(MyClass);
using (var stream = new MemoryStream())
{
    serialize.WriteObject(stream, myObject);
    stream.Position = 0;
    stream.Flush();
    myClone = (MyClass)serialize.ReadObject(stream);
}

Para que a serialização com referencias cíclicas dê certo, é necessario usar a propriade IsReference do DataContrac com valor igual à true;
Segue um exemplo completo.:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;

namespace ConsoleApplication2
{
    [DataContract(IsReference = true)]
    public class Pessoa
    {
        [DataMember]
        public string Nome { get; set; }

        [DataMember]
        public Pessoa Companheiro { get; set; }

        [DataMember]
        public Pessoa Pai { get; set; }

        [DataMember]
        public Pessoa Mae { get; set; }

        [DataMember]
        public List<Pessoa> Filhos { get; set; }

        [DataMember]
        public List<Pessoa> Irmaos { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var pessoa1 = new Pessoa() { Nome = "Pai" };
            var pessoa2 = new Pessoa() { Nome = "Mãe" };
            var pessoa3 = new Pessoa() { Nome = "Filho 1" };
            var pessoa4 = new Pessoa() { Nome = "Filho 2" };
            var pessoa5 = new Pessoa() { Nome = "Filho 3" };

            pessoa1.Companheiro = pessoa2;
            pessoa2.Companheiro = pessoa1;
            pessoa1.Filhos = pessoa2.Filhos = new List<Pessoa> { pessoa3, pessoa4, pessoa5 };

            pessoa3.Pai = pessoa4.Pai = pessoa5.Pai = pessoa1;
            pessoa3.Mae = pessoa4.Mae = pessoa5.Mae = pessoa2;
            pessoa3.Irmaos = new List<Pessoa> { pessoa4, pessoa5 };
            pessoa4.Irmaos = new List<Pessoa> { pessoa3, pessoa5 };
            pessoa5.Irmaos = new List<Pessoa> { pessoa3, pessoa4 };

            var serialize = new DataContractSerializer(typeof(Pessoa));
            var clone = default(Pessoa);
            using (var stream = new MemoryStream())
            {
                serialize.WriteObject(stream, pessoa1);
                stream.Position = 0;
                stream.Flush();
                clone = (Pessoa)serialize.ReadObject(stream);
            }

            clone.Companheiro.Filhos[1].Nome = "Clone do Filho 2";
            Console.WriteLine($"{clone.Companheiro.Filhos[1].Nome}, {pessoa1.Companheiro.Filhos[1].Nome}, {pessoa4.Nome}");
        }
    }
}

Comment: +1 gostei ......


How to compute binomial random variables

Question: I the book we have following problem:
Let X be a Binomial random variable with n = 10 and p = 0.4. Compute the following:
(a) $E[(3 + 5X)]$;
(b) $E[(2 + X)^2]$;
(c) $Var(4 + 3X)$;
I am not sure how to approach this problem having some expression for random variable.
I know that Binomial Random Var. expectation is computed using following formula:
$$E[x] = np$$
and $$Var(x) = np(1-p)$$
Though, I am not sure what does it mean to compute
$E[(3 + 5X)]$ and book does not clarify it. It simply gives all those formulas...
Need your help! Thanks
Comment: **Hint:** $E[\cdot ]$ is a linear operator.
Comment: @IvoTerek does it mean that I can rewrite :
E[(3+5X)] = E[3] + 5E[x]?
And E[3] = 3
then E[x] = 4
So E[(3 + 5x)] = 3 + 5 * 4 = 23 ?
Comment: That's right.${}{}$
Answer: Note that $Var(Y) = E[Y^{2}] - (E[Y])^{2}$.
So to calculate $Var(4 + 3X)$, consider first $E[16 + 24X + 9X^{2}]$. You can break this up using the linearity of the expected value. Similarly, consider $E[4 + 3X]$ and square the result.
Comment: Or, more simply, remember that $\operatorname{var}(a+bX)=b^2\operatorname{var}(X)$ is a very useful identity to memorize.


Is a batsman out if the bails are removed but fall back onto the stumps?

Question: Let me know what happens to the batsman in this situation.

The spin bowler made an magic delivery so that it hit the stumps and a bail is pushed out of its position (the grooves), but didn't fall to the ground, rather it balanced on top of one of the stumps.

I know it's an extremely weird and rare scenario, but I'm too curious to know the decision of the umpire.
Answer: Not out. Quoting from Law 30.1(a):

The striker is out Bowled if his wicket is put down by a ball delivered by the bowler

and Law 28.1:

(a) The wicket is put down if a bail is completely removed from the top of the stumps
[...]
(b) The disturbance of a bail, whether temporary or not, shall not constitute its complete removal from the top of the stumps


Get information about a menu item

Question: In Drupal 8, you can use system blocks to show menus starting from different levels. For example:
Menu item 1 (level1)
--- Menu Item 2 (level2)
--- Menu Item 3 (level2)

Menu item 4 (level1)
--- Menu Item 5 (level2)
--- Menu Item 6 (level2)

When user is on a page linked by menu item 2 I want to have a block showing the following:
Menu item 1
    --- Menu Item 2
    --- Menu Item 3

What the main system block offers is the following result:
    --- Menu Item 2
    --- Menu Item 3

You see? I need the parent menu item of these menu items as well.
What I did so far is to define a custom block in my module:
class MainMenuBlockSecondLevel extends BlockBase {

  public function build() {
    $menu_name = 'main';
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $parameters->setMinDepth(2);

    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);

    $parents = $parameters->expandedParents;  // menu_link_content:dd7b39a6-c4c8-48dd-a1cf-92a755087c29

    $build['parent']['#markup'] = '
Parent
';
    $build['menu'] = $menu_tree->build($tree);
    return $build;
  }
}

With the $parents variable I get an array like that:
Array
(
    [0] =>
    [1] => menu_link_content:dd7b39a6-c4c8-48dd-a1cf-92a755087c29
)

Here it stops for me now. What is menu_link_content:dd7b39a6-c4c8-48dd-a1cf-92a755087c29 and how can I get the needed information like menu item title and path out of it?
Answer: MenuTreeParameters::$expandedParents are a list of menu tree ids (a composite key of the menu bundle and the menu content UUID). You can see its data in the menu_tree, menu_link_content, menu_link_content_data, database tables.
If you need to programmatically invoke the menu item for reference, you can load it via Drupal's entity manager:
// Load each menu content item per UUID
foreach ($parents as $menu_uuid) {
  $menu_content = current(\Drupal::entityManager()->getStorage('menu_link_content')->loadByProperties(array('uuid' => $menu_uuid)));
  // @TODO: Reference menu content properties for data
  // (e.g. $menu_content->get('title')->value / $menu_content->get('link')
}

Comment: Thank you very much for this information - I will go deeper into all this stuff with this information. My first question: as the value of each key in my $parents array as a composite of bundle and UUID is there a helper function to get just the UUID of such a construction? I used '$uuid = substr($parents[2], 18)' to get just the UUID part. Additionally $parents array has many items - how can I get just the direct parent of the current menu item?
Comment: Newer versions of Drupal use entityTypeManager() instead of entityManager().

Get information about a menu item


OpenIndiana ZFS with shareiscsi property missing

Question: I'm trying to present a ZFS file system as an iSCSI target. This is ultimately for using it with OS X Time Machine, but that should be irrelevant in this question.
# zfs get all | grep scsi

From several blog posts, it appears it should have a "shareiscsi" property. But just to be thorough, I installed the iscsi target package, hoping it would show up:
# pkg install pkg:/network/iscsi/target
# svcadm enable -rs network/iscsi/target
# svcs | grep scsi
online         Mar_30   svc:/network/iscsi/initiator:default
online          6:02:56 svc:/network/iscsi/target:default

Still no shareiscsi in the properties. I did see a blog post about having to install "SUNWiscsitgt" but according to pkg, it is obsolete:
# pkg info -r SUNWiscsitgt
Name: SUNWiscsitgt
State: Not installed (Obsolete)

What am I missing?
Answer: It appears OpenIndiana does not use the shareiscsi property. Also (perhaps relatedly) COMSTAR is not included as part of the base installation. So I fired up a fresh OpenIndiana VM and ran the following commands and was able to create, share and mount a sparse LUN without any drama:
sudo -s
pkg install network/iscsi/target
svcadm enable -s stmf
svcadm enable -s iscsi/target
zfs create -o mountpoint=none rpool/iscsi
zfs create -V 8G -s rpool/iscsi/yourmom
sbdadm create-lu /dev/zvol/rdsk/rpool/iscsi/yourmom
sbdadm list-lu

Use that GUID from the sbdadm output (my GUID below):
stmfadm add-view 600144f096c28d0000004dbeb9df0001
itadm create-target
itadm list-target

Take your target name (example: iqn.1986-03.com.sun:02:9f57392e-9859-61fe-ec5c-da681f9214dd) and put it in to your iSCSI initiator (I use the free globalSAN iSCSI on my mac) along with the IP address (or hostname) of your OpenIndiana box. Tada.
Source: Setting up COMSTAR and iSCSI target on the Nexenta Wiki.
Comment: Oracle Solaris 11 doesn't seem to support shareiscsi either. These directions did work for me though.

Too bad it's not as straightforward as the previous zfs goodness.
Comment: I wish I could double plus one for "yourmom".


Why is this code not correct for PySchools Topic 2 Q uestion 7?

Question: That's my second post in 2 days about pyschools , i hope it's OK.
The exercise asks me to do the following: Write a function that uses a default value.
It also gives me an example code which i have to improve in order to print out the correct output (like if the input is introduce('Lim', 20) , the output should be 'My name is Lim. I am 20 years old.'
The code given by pyschool which i have to improve:
def introduce(name, age = 0):
    msg = "My name is %s. " % name
    if age == 0:
       msg += ""
    else:
       msg += ""
    return msg

My code:
def introduce(name, age=0):
    msg = "My name is %s. " % name
    if age == 0:
        msg += " My age is secret."
    else:
        msg += " I am %d years old." % age
    return msg

It returns the same answers as pyschools' code checker, but due to unclear reasons, the website says my answers are wrong. What might be the problem ?
I'm sorry if i didn't make myself clear enough and you don't understand what i'm trying to say. I have a hard time expressing myself as English is not my native language.
Thank you very much!
Comment: Please rewrite your title to describe your problem or ask a clear question.
Comment: The problem could be that you have a blank space both at the end of the `name` format string, and also at the beginning of the other strings. Probably you just need one or the other?
Answer: Your code is fine. The only thing I can think of is that the output has two spaces in the middle. Try fixing that: msg = "My name is %s." % name
Comment: I just tried it on the site (after posting my comment). That's the problem.
Answer: Try this one:
def introduce(name, age=0):
    msg = "My name is %s. " % name

    if age == 0:
       msg += "My age is secret."
    else:
       msg += "I am %s years old." % age
    return msg


Vertically align sans-serif font precisely at changing font-size

Question: My problem is an extension to the problem I stated already in an earlier problem, see here Vertically align sans-serif font precisely using jquery/css.
In a nutshell: I want to align two divs with text, one above the other, in order to always align the beginning of the A (basically the lower left point of the A) with the H (the left vertical line of the H)? An idea of what i'm trying to achieve:

The top div has a varying font-size and I want to align the lower div according to the font. The reason is that I scale my font size according to the window size.
A demo on jfiddle .
HTML

HEADER

HEADER

A

B

C

CSS
div.Header {
    font-family:sans-serif;
    text-align:justify;
    white-space: nowrap;
}
div.menubar {
    text-align: justify;
    -ms-text-justify: distribute-all-lines;
    text-justify: distribute-all-lines;
    margin-bottom: 0px;
    position: relative;
}
div.menubutton_left, div.menubutton_middle, div.menubutton_right {
    vertical-align: top;
    display: inline-block;
    *display: inline;
    zoom: 1;
    width:60px;
}
div.menubutton_left {
    margin-left:12px;
}
div.menubutton_middle {
    text-align: center;
}
div.menubutton_right {
    text-align: right;
}
.stretch {
    border: 2px dashed #444;
    width: 100%;
    display: inline-block;
    font-size: 0;
    line-height: 0
}

JSCRIPT
resizeHead("#Hideheader", "#header");

$(window).resize(function() {
  resizeHead("#Hideheader", "#header");
});

function resizeHead(p1, p2) {
    var fontsize = parseFloat($(p1).css("font-size"));
    var spacing = parseFloat($(p1).css("letter-spacing"));
    var initWidth = $(p1).width();
    initWidth = initWidth - spacing;
    var outWidth = $(p2).width();

    var s = outWidth / initWidth;
    s = fontsize * s;
    $(p2).css({
        "font-size": s
    });
}

Try resizing your browser window. I becomes especially apparent for smaller end of font sizes
Answer: I don't know if I really understand your question.. But, due to your fiddle, I think I see what you want. I would recomend:
1: Don't use JS to set increase font-size. You can use variable size units like vw, vh or vmin. They change it's size according to parent container, like: font-size: 20vw.
It is a LOT lighter than having javascript to trigger on every window resize.
2: You have set a fixed width to your divs, so whenever it becomes smaller than 60px your layout will break. Remove it. You can set a dynamically calculated width, like: width: calc(100% / 3), so all your three divs will be placed accordingly.
3: You have set a margin-left on your first div that also breaks your layout. Instead, add the margin to the  tag inside the div:
div.menubutton_left a {
    margin-left:12px;
}

Here's an updated fiddle, with all the changes (and no js \o/): http://jsfiddle.net/ksuTQ/7/
Comment: Wow, that's some great advice, thanks! Would you also happen to know a solution in order to always align the beginning of the A (basically the lower left point of the A) with the H (the left vertical line of the H)? I hope I'm not too confusing with my question. And I don' have enough reputation to upvote your answer :|
Comment: No problem at all... Well, first, I've set your header to `text-align: center`, so change it back to `text-align: left`. Now, to align the way you want, maybe you can set your  `margin-left` to something percentual. See if it helps someway: http://jsfiddle.net/ksuTQ/8/
Answer: Well, I've solved this issue with my own applications before, but by sloppy means. You might not want to do things this way, but I'll share it anyway. I do really like the post by @LcSalazar, but I've found in the past that I sometimes have trouble configuring the rest of my page once I've added elements with relative positioning, but it appears that your doing that anyway. Try the answer by @LcSalazar first, then if you really want to, try this. I also suggest trying to use elements such as span instead of div, but that might change your entire project.
The biggest issue is that, in HTML, there really is no good means of collecting TextMetrics, as that is what you are asking for. Canvas elements have TextMetrics, but they only provide width.
var myCanvas = document.createElement('canvas');
var myContext = myCanvas.getContext('2d');

var myText = "I'm getting measured by canvas calls!";

var textMetrics = myContext.measureText(myText);

var textWidth = textMetrics.width;

Unfortunately, what your looking for is height.
This is what I've done in the past.
var hiddenDiv =  document.createElement('div');
hiddenDiv.style.visibility = 'hidden';
hiddenDiv.style.position = 'absolute';
hiddenDiv.style.top = '0px';
hiddenDiv.style.left = '0px';
document.body.appendChild(hiddenDiv);

var myText = "I'm getting measured by a sloppy div";

function getTextHeight(text, font)
{
   hiddenDiv.style.font = font;
   hiddenDiv.innerHTML = text;

   return hiddenDiv.clientHeight;
}

var myFont = 'normal 13px Verdana';

var textHeight = getTextHeight(myText, myFont);

You can then use the text height to do any sort of resizing or relative positioning that you wanted to do. Sorry I didn't try to incorporate it into your project myself, I just wanted to show you a means of collecting text height without writing a massive block of code. Make sure that you set the font of the div before you measure it! Hope this helps!
Comment: Actually, I'm not looking not for height, but the offset to the beginning of the division, an idea of what i'm trying to achieve: http://i.imgur.com/xyn5UDZ.png
Comment: Ooh, now I understand what you saying. Sounds kinda tricky, but I think that this could be accomplished using CSS. Try setting margin and padding to 0. I'm not exactly sure if this will do what you want it too, I've never actually tried to do that before.


(Gamer Question) Really Hard Word Problem About Balancing

Question: Warriors have a fortress in which they need to defend against beasts. They gain points for defending. Warriors do 200dmg/sec to beasts who have health points of 200hp each. If a beast dies, they revive. The fortress that they need to defend is 1000hp (so basically, it's going to be used as warrior's hp). The number of beasts are 20. A beast does 30dmg/sec each hit to the fortress. Warriors get 3 points per 100dmg. Beasts don't need points meaning they just get 0 points or it just doesn't count. The question is, in a time period of 60 seconds, would warriors get more points from a beast with 10000hp than a beast with 200hp (its normal hp)? Or is it balanced?
EDIT*:
WarriorDmg=200dmg/sec                                                                                Warrior(Fortress)Hp=1000hp                                                                                PointsForWarrior=3points/100dmg                                                                                PointsForBeast=0points                                                                                BeastDmg=30dmg/sec                                                                                BeastHp=200hp                                                                                NumberOfBeasts=20
After a beast dies, they start attacking again.
It takes an interval of 0.5 seconds before a dead beast starts attacking again.
If humans attack a beast with 200dmg/sec, and a beast's hp is 200. That means they die instantly. The beast is able to do at least 30 damage before they die. After 0.5, a beast revives again and it comes to a loop until the fortress is destroyed. (-1000hp from 30x)
QUESTION: In 60 seconds, would warriors get more POINTS defending beasts of 200hp, or get more points with beasts of 10000hp?
Assume that the group of warriors is the fortress itself. So once the fortress of 1000hp goes down, that's when warriors lose. Warrior damage applies to beast (200hp in normal circumstances). Beast damage applies to warriors (fortress of 1000hp)
Comment: Here are some questions that you haven't provided the answers to, which are (probably) essential to the question. You claim that warriors revive: under what mechanism can they die? Are there multiple beasts in the 200 scenario? The 10000 scenario? What are the beast(s) doing damage to? When beasts and warriors engage, which strikes first?
Comment: What else am I missing? I've retouched some variables.
Comment: Hm, I think that's enough. Let me think a bit.
Comment: One more thing, are there multiple warriors? Or is the 200/sec ouput their collective damage (i.e. the fortress' damage)?
Comment: Just think of warriors = fortress (one collective, one warrior). So warrior hp is 1000hp in which they do 200dmg/sec as their collective damage. Yes.
Answer: First sanity check: the fortress survives in both scenarios. If it doesn't, then then the one that survives longer wins. This is because the effective hit point pool of beasts is infinite; the nominal hp doesn't matter because of the revival mechanism. Given that, for warriors accruing a constant number of points for a constant amount of damage, you have a direct relationship between survival time and points.
I will use dps for damage per second. Because beasts always do damage before death, we can model them as doing all of their damage at zero seconds and at the instant they revive, and model the warriors as attacking at the $.9$ second mark.
200hp scenario: Warriors kill one beast every second. Beasts revive every half second. Therefore, it does not matter how beasts are killed; all of them will deal $30$ damage, precisely once, at some time in each one-second interval. This deals $30*60=1800$ damage, which kills the warriors. So they do not survive.
10000hp scenario: No beast dies, $1800$ damage is still dealt.
Therefore, everything comes down to the warriors' final moments. There are certain scenarios in which it is possible for the 10000hp to be slightly more favorable to the warriors, but this difference is only relevant during this last second, so it cannot be more than 1 second worth of points. They die between second $33$ and $34$, so we are talking about a $3$% difference.
However, if it matters for multiplayer balancing reasons, it is probably relevant that it is not possible to adjust the parameters so the 200hp scenario has more favorable outcomes. This is because the difference between the two deals with the dying of the beasts, and so for example if the warriors attack at the .4 second mark instead of the .9 second mark, then killed beasts will ressurect before a full second has passed, and therefore receive two full attacks in a second.
Comment: For the 10,000hp scenario, do beasts do exactly 1800 damage as the 200hp scenario? Or do they do more?
Comment: Exactly the same. The fact that they have more hp does not change the fact that their damage output is still 30/sec; given 60 seconds to hit something, and the capacity to survive, $30\text{ dmg}/\text{sec}*60\text{ sec} = 1800$ dmg.


Canonical Transformation and Symplectic Conditions

Question: I have one question regarding Canonical transformation and symplectic matrix.
I have read some notions from the following note:
http://www.chim.unifi.it/orac/MAN/node6.html
For me it is not clear how it is obtained the following  relation:
$$\dot y = MJM^t \frac{\partial H}{\partial y}.$$
Can you explain me, please.
Update1
What I have tried.
I'll consider the  case when $n=2$.
We try to make a transformation $y \to y(x)$.
relation 1(a):
$$\dot y = \frac{\partial y}{\partial  x} \dot x $$
relation 2(a):
$$\dot x = J \frac{\partial H}{\partial x}$$
BUT
relation 3(a):
$$\frac{\partial H}{\partial x}=\frac{\partial H}{\partial y}\frac{\partial y}{\partial x}$$
So, we have:
$$\dot y= \frac{\partial y}{\partial x} \dot x = \frac{\partial y}{\partial  x} J \frac{\partial H}{\partial x}=\frac{\partial y}{\partial  x} J\frac{\partial H}{\partial y}\frac{\partial y}{\partial x}.$$
From here I get stuck.
Looks similar but I don't know how to continue to obtain same form.
I don't know why there appear the transpose of that matrix.
Can you help me to write in coordinates $\displaystyle \frac{\partial y}{\partial x}$.
UPDATE2
from relation 1(a):
$$\dot y = \frac{\partial y }{\partial x} \dot x $$
In matrix notation, for $n=2$, I'll have:
relation (1b)
$$\begin{pmatrix}
\dot y_{1}\\ \dot y_{2}
\end{pmatrix}=\begin{pmatrix}
\frac{\partial y_{1}}{\partial x_{1}}& \frac{\partial y_{1}}{\partial x_{2}}\\
\frac{\partial y_{2}}{\partial x_{1}}&\frac{\partial y_{2}}{\partial x_{2}}
\end{pmatrix} \begin{pmatrix}
\dot x_1\\\dot x_2
\end{pmatrix}.$$
Now, From relation 3(a) I want to obtain in a matrix form relation 3(b):
$$\begin{pmatrix}
\frac{\partial H}{\partial x_1}\\
\frac{\partial H}{\partial x_2}
\end{pmatrix}=\begin{pmatrix}
\frac{\partial H}{\partial y_1}\\
\frac{\partial H}{\partial y_2}
\end{pmatrix} \begin{pmatrix}
\frac{\partial y_1}{\partial x_1} & \frac{\partial y_1}{\partial x_2}\\
\frac{\partial y_2}{\partial x_1} & \frac{\partial y_2}{\partial x_2}
\end{pmatrix}.$$
So,the relation from UPDATE1
$$\dot y=\frac{\partial y}{\partial  x} J\frac{\partial H}{\partial y}\frac{\partial y}{\partial x}.$$
will become:
$$\begin{pmatrix}
\dot y_{1}\\ \dot y_{2}
\end{pmatrix}=\begin{pmatrix}
\frac{\partial y_{1}}{\partial x_{1}}& \frac{\partial y_{1}}{\partial x_{2}}\\
\frac{\partial y_{2}}{\partial x_{1}}&\frac{\partial y_{2}}{\partial x_{2}}
\end{pmatrix} \begin{pmatrix}
0 & 1\\
-1 & 0
\end{pmatrix}\begin{pmatrix}
\frac{\partial H}{\partial y_1}\\
\frac{\partial H}{\partial y_2}
\end{pmatrix} \begin{pmatrix}
\frac{\partial y_1}{\partial x_1} & \frac{\partial y_1}{\partial x_2}\\
\frac{\partial y_2}{\partial x_1} & \frac{\partial y_2}{\partial x_2}
\end{pmatrix} $$
And from here, again, it seems impossible for me... more and more, the matrix multiplication is not possible...
Thanks!
Comment: Hint to the question (v4):  In matrix notation, be careful with what are rows and what are columns.
Comment: ok. I will try and I stop I will ask you. thanks!
Comment: You actually did for any dimension, write it down using $y=\left(\begin{array}{c}y_1 \\ y_2\end{array}\right)$. Then you will understand Qmechanic's comment about tracking columns and rows.
Comment: OK. I will try again. I hope I'll obtain the good results. Thanks!
Comment: Your difficulty lies is the relation 3(b). Try to multiply the matrices in that relation and you will see that you are doing something wrong... then try to write it in a way that it makes sense.
Comment: What have you tried? Start with the case where the dimension is 2, and write down the system of equations. Then apply to that system an arbitrary (not necessarily canonical) change of coordinates to see what happens.
Comment: I have tried something. I hope it is ok what I have did.
Comment: @CvZ
It is ok what I did. Can you help me to solve this problem? Thanks!
Comment: @Qmechanic It is ok what I did. Can you help me to solve this problem? Thanks!
Answer: Don't know if you're still interested in this, but here goes.
Take the coordinate transformation $\vec{x}\to\vec{y}(\vec{x})$, i.e. we consider $\vec{y}$ to be a function of $\vec{x}$.
Let the Hamiltonian function in terms of the new coordinates be denoted $\tilde{H}$, that is, $\tilde{H}(\vec{y}(\vec{x}))=H(\vec{x})$.
Rather than doing the calculation in terms of matrices, it is easier to do it in terms of components (tensor notation). Then you don't have to worry about tracking rows/columns, and also the notation is a lot more compact. Let $y_i$ denote the $i$'th component of $\vec{y}$, etc. Also, $M_{ij}$ denotes the $ij$ component of the $M$ matrix, which is $\frac{\partial y_i}{\partial x_j}$ (there is a typo in the definition of $M$ in your link).
Our goal is to show
$$\dot{y}_i=\left(M J M^T \frac{\partial H}{\partial \vec{y}}\right)_i.$$
Consider the LHS above, $\frac{d}{dt}\left(y_i (\vec{x}(t))\right)$. By the chain rule, this is equal to
$$\frac{\partial y_i}{\partial x_j}\frac{dx_j}{dt}$$
with implicit summation over $j$. But $\frac{\partial y_i}{\partial x_j}=M_{ij}$, so
$$\dot{y}_i=\frac{\partial y_i}{\partial x_j}\frac{dx_j}{dt}=M_{ij}\dot{x}_j=(M\dot{\vec{x}})_i$$
$$\implies \dot{\vec{y}}=M\dot{\vec{x}}=MJ\frac{\partial H}{\partial \vec{x}}.$$
Now recalling $H(\vec{x})=\tilde{H}(\vec{y}(\vec{x}))$, apply the chain rule to get
$$\frac{\partial H}{\partial x_i}=\frac{\partial \tilde{H}(\vec{y})}{\partial y_j}\frac{\partial y_j}{\partial x_i}=M_{ji}\frac{\partial \tilde{H}}{\partial y_j}=(M^T)_{ij}\frac{\partial \tilde{H}}{\partial y_j}=\left(M^T \frac{\partial \tilde{H}}{\partial \vec{y}}\right)_i$$
$$\frac{\partial H}{\partial \vec{x}}=M^T \frac{\partial \tilde{H}}{\partial \vec{y}}.$$
Substitute this into the above gives
$$\dot{\vec{y}}=MJM^T\frac{\partial \tilde{H}}{\partial\vec{y}}$$
as required.


Relationship between Winning Margin and Point Spread in NBA Betting

Question: For an NBA game, I see a market for Spread and one for Winning Margin. The Spread market lists "Team A -5.5: 10/11". The Winning Margin markets lists "Team A, 6 points or more: 3/4". Shouldn't the odds for these two best be equal?
Comment: Please site an example.
Comment: Are they the same book?
Answer: There's no fundamental reason they should be equal, because a bookies' job isn't to accurately reflect the chance of a team winning: it's to make as much money as possible for the bookie. If a bookie has taken too much money on one side of a line, they'll move the odds and/or the line to encourage punters to bet the other side of the line; bookies really don't like a situation where they're at risk of taking a significant loss if one result or another happens - their desired situation is if they have equal exposure on either result, and then they're guaranteed a nice profit thanks to their cut.
Comment: My question was more in line with: should these be equal under perfect betting? By your answer I infer that yes.
Answer: In theory the two markets for the same situation, and so the odds should be the same. However, there are many reasons why they might not be.
One, is the rules and regulations, if both markets are for regular time only or if they include OT.
And the other one is the margin or juice applied. As a general rule, bookmakers apply 3 pp per each selection, so if the winning margin has 9 selections it will apply 127% book. Usually handicpas apply 6%.
Also, for the winning margin, as the odds become smaller, we tend to apply less margin (dynamic margin).
So, you can try using those differences in your favor, trying to get as much value as possible.
Answer: They should be equal if odds were fair and if both markets apply to the same principle with respect to overtime rules. Usually handicap markets include overtime while margin of victory not (you may find a selection of draw there).
Additionally bookmakers apply margin to odds, so there might be a case where handicap is offered in x margin and winning margin in y.


Evaluation of $\lim_{x\to 0} \frac{(1+x)^{1/x}-e+\frac{ex}{2}}{x^2}$

Question: Evaluate the following limit:
$$L=\lim_{x\to 0} \frac{(1+x)^{1/x}-e+\frac{ex}{2}}{x^2}$$
Using $\ln(1+x)=x-x^2/2+x^3/3-\cdots$
I got $(1+x)^{1/x}=e^{1-x/2+x^2/3-\cdots}$
Could some tell me how to proceed further?
Comment: Are you sure , your question is correct ?
Comment: That series expansion for $\ln(1+x)$ is centered around $x=0$. Are you sure it's not $x \to 0$? (see my answer)
Comment: @MichaelTong Yes. My bad. Thank You for pointing that out.
Comment: He probably has it right, because the last two terms in the numerator exactly cancel the two leading parts  of the first term, leaving a finite answer.
Answer: Indeed, the expansion of $(1+x)^{1/x}$ about $x=0$ is $e - \frac{ex}{2} + \frac{11e}{24} x^2 + O(x^3)$, so the limit is then $\dfrac{11e}{24}$.
--
To get this expansion, start with
$$(1+x)^{1/x} = \exp \left({1 - x/2 + x^2 / 3 - \dots}\right)$$
which you already found and put this into the power series of $\exp$ to get
$$\sum_{n=0}^{\infty} \frac{(1 - x/2 + x^2/3 - \dots)^n}{n!}$$
The coefficient of $x^0$ is
$$\sum_{n=0}^{\infty} \frac{1}{n!} = e$$
The coefficient of $x^1$ in $\dfrac{(1-x/2+x^2/3 - \dots)^n}{n!}$ is $-\frac{n/2}{n!}$, hence the coefficient in total is
$$\sum_{n=1}^{\infty}  -\frac{1}{2 (n-1)!} = -\frac{e}{2}$$
I'll leave the coefficient of $x^2$ to you. (It's the hardest, but not too bad).
Comment: It would be better and much simpler to evaluate the coefficients if you write $$\exp\left(1 - \frac{x}{2} + \frac{x^{2}}{3} - \cdots\right) = e\cdot\exp\left(- \frac{x}{2} + \frac{x^{2}}{3} - \cdots\right)$$ and then you don't need to sum an infinite series to calculate coefficients. Thus coefficient of $x^{2}$ is $$e\left(\frac{1}{3} + \frac{1}{2}\cdot\left(\frac{1}{2}\right)^{2}\right) = \frac{11e}{24}$$
Comment: @ParamanandSingh Why is that expression the coefficient? I don't see where it follows from - I see that you took the coefficient of $x^2$ and added $1/2$ times the square of the coefficient of $x$, but I don't see why that is immediate when you manipulate the series like that
Comment: we have $$\exp(-x/2 + x^{2}/3 + \cdots) = 1 + (-x/2 + x^{2}/3 - \cdots) + \frac{(-x/2 + x^{2}/3 - \cdots)^{2}}{2} + \cdots$$ and note that further terms involve $x^{3}$ and higher powers. So the coefficient of $x^{2}$ is $1/3 + (-1/2)^{2}\cdot (1/2) = 11/24$. Thus you don't need to sum infinite numbers of terms to obtain coefficients. You can similarly get coefficients of $x^{3}, x^{4}$ with far too less effort.
Comment: @ParamanandSingh Oh, I see. Yeah, I suppose it's a bit simpler.
Comment: Let $s = 1 - x/2 + x^{2}/3 - \cdots, t = -x/2 + x^{2}/3 - \cdots$. Now the term $x^{k}$ is present in each term of expansion $\exp(s) = 1 + s + s^{2}/2! + \cdots$ but $x^{k}$ is present in expansion $\exp(t) = 1 + t + t^{2}/2! + \cdots$ only till $t^{k}/k!$.
Answer: You can proceed in the following manner
\begin{align}
L &= \lim_{x \to 0}\dfrac{(1 + x)^{1/x} - e + \dfrac{ex}{2}}{x^{2}}\notag\\
&= e\lim_{x \to 0}\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1\right) - 1 + \dfrac{x}{2}}{x^{2}}\notag\\
&= e\lim_{x \to 0}\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1\right) - \exp\left(\log\left(1 - \dfrac{x}{2}\right)\right)}{x^{2}}\notag\\
&= e\lim_{x \to 0}\exp\left(\log\left(1 - \dfrac{x}{2}\right)\right)\cdot\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)\right) - 1}{x^{2}}\notag\\
&= e\lim_{x \to 0}\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)\right) - 1}{\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)}\cdot\dfrac{\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)}{x^{2}}\notag\\
&= e\lim_{x \to 0}\dfrac{\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)}{x^{2}}\notag\\
&= e\lim_{x \to 0}\dfrac{\left(1 - \dfrac{x}{2} + \dfrac{x^{2}}{3} + o(x^{2})\right) - 1 + \left(\dfrac{x}{2} + \dfrac{x^{2}}{8} + o(x^{2})\right)}{x^{2}}\text{ (using Taylor series)}\notag\\
&= e\left(\frac{1}{3} + \frac{1}{8}\right)\notag\\
&= \frac{11e}{24}\notag
\end{align}
The above approach uses the standard limit $$\lim_{t \to 0}\frac{\exp(t) - 1}{t} = 1$$ Taylor series is used only when necessary and this approach avoids any multiplication/division of infinite series.
Answer: It's a well-known fact that $$\log(1+x)=x-\dfrac{x^2}2+\dfrac{x^3}3+\underset{x\to 0}{o}(x^3)$$
Hence we get $$\dfrac 1x\log(1+x)=1+u(x)$$ where $$u(x)=-\dfrac x2+\dfrac{x^2}3+\underset{x\to 0}{o}(x^2)$$
Notice that $$\lim_{x\to 0} u(x)=0$$
We can write $$(1+x)^{1/x}=ee^{u(x)}$$
But we know that $$e^u=1+u+\dfrac{u^2}2+\underset{u\to 0}o(u^2)$$
Now using the identity $$(a+b+c)^2=a^2+b^2+c^2+2ab+2bc+2ac$$
we quickly find, since we only need the terms whose degrees are less than three (the other terms are all some $\underset{x\to 0}o(x^2)$), that
$$(u(x))^2=\left(-\dfrac x2+\dfrac{x^2}3+\underset{x\to 0}{o}(x^2)\right)^2=\dfrac{x^2}4+\underset{x\to 0}o(x^2)$$
Hence, since $\displaystyle\lim_{x\to 0}u(x)=0$, we see than an $\underset{u\to 0}o(u^2)$ function is an $o(x^2)$ when $x$ tends to $0$.
This leads to
$$\begin{align*}(1+x)^{1/x} & = e\left(1+\left(-\dfrac x2+\dfrac{x^2}3+\underset{x\to 0}{o}(x^2)\right)+\dfrac 12\left(\dfrac{x^2}4+\underset{x\to 0}o(x^2)\right)+\underset{x\to 0}{o}(x^2)\right)\\ & = e-\dfrac{ex}2+\dfrac{11e}{24}x^2+\underset{x\to 0}o(x^2)\end{align*}$$
And so :
$$\dfrac{(1+x)^{1/x}-e+\dfrac{ex}2}{x^2}=\dfrac{11e}{24}+\underset{x\to 0}o(1)$$
which means exactly that $$\lim_{x\to 0}\dfrac{(1+x)^{1/x}-e+\dfrac{ex}2}{x^2}=\dfrac{11e}{24}$$
Comment: You can simply write $o(x^{2})$ etc instead of $\underset{x \to 0}o(x^{2})$. The fact that $x \to 0$ is clear from context.


Google Earth: is a dynamic parametrized KML possible?

Question: I made a large KML file ca. 23 MBytes long. Google Earth renders it very long period of time, lags and occupies 1GB RAM and more. On slower computers it may also not to render some areas.
So the idea is to use a parametrized GET request to the server returning kml data only for a region with specified boundaries.
Can GoogleEarth initiate and use such requests?
Answer: What you're asking can be done with a NetworkLink. If you dynamically generate the KML from a servlet, web-service, script, etc. then you can instruct Google Earth to send the bounding box for its view from which you can generate the KML to return. This approach requires hosting a custom "service" on an application server/web server that can generate KML in response to requests sent by Google Earth.
In your root-level NetworkLink you need to define refreshMode=onChange to refesh when view is changed along with the URL to the servlet. Recommended to set viewRefreshMode=onStop with a viewRefreshTime element so the data is only fetched 1 second after the user stops zooming/moving around otherwise the data is continually refreshed. Also the viewFormat is needed to instruct Google Earth to return the bounding box of the view. In this example, the BBOX parameter is added to the HTTP parameters sent to the servlet in an HTTP GET request.
<code><Link>
      <href>servlet-url</href>
      <refreshMode>onChange</refreshMode>
      <viewRefreshMode>onStop</viewRefreshMode>
      <viewRefreshTime>1</viewRefreshTime>
      <viewFormat>BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]</viewFormat>
</Link>
</code>
If your data spans a large area then you could break up the data into separate KML files then specify Region-based NetworkLinks in parent KML file. This approach would allow you to generate the data once as static KML files and only serve up what data is "active" based on the user's view.
Related Tutorial:
https://developers.google.com/kml/documentation/regions#regionbasednl
Reference:
https://developers.google.com/kml/documentation/kmlreference#networklink
https://developers.google.com/kml/documentation/kmlreference#region
https://developers.google.com/kml/documentation/kmlreference#viewformat
Answer: Yes, this isn't a problem at all. You add the source URL of you KML in Google Earth as a URL with parameters and then load it as several separate sources. With that approach though you are only 'dynamically' providing the criteria at the time you add the KML to GE, and from then on it looks like any other static KML file you would have loaded.
EDIT I see now (logging into GE) that it actually calls these network links as described by @JasonM1 (under Add->NetworkLink)


Set a cookie whenever front page is viewed

Question: I run a Drupal 7 site (currently 7.15) since longer time and have the problem with cookies:
I need 2 cookies for non-Drupal PHP-scripts at my web site.
I set them in the hook_init of my custom module:
/**
 * Implements hook_user_login().
 */
function pref_user_login(&$edit, $account) {
    if ($account->uid <= 0) {
      return;
    }

    #drupal_set_message('
Hello, '.$account->name.'
');
    $auth  = md5(join('_', array($account->uid, MY_SECRET)));
    $year  = time() + 60 * 60 * 24 * 30 * 12;
    setcookie('pref_id', $account->uid, $year, '/', '.preferans.de');
    setcookie('pref_auth', $auth, $year, '/', '.preferans.de');
}

The problem is, that I need to set the both cookies each time a logged in user visits the front page and not just when the user logs in.
Does anybody please have an idea how to do it, maybe by JavaScript if I can't do it regular way?
Answer: You could do this in hook_preprocess_page() and instead of setting a variable, you could do something like this:
function pref_preprocess_page(&$vars) {
  global $user;

  // whatever other preprocess stuff you want to do here

  if ($user->uid && drupal_is_front_page()) {
    $auth  = md5(join('_', array($user->uid, MY_SECRET)));
    $year  = time() + 60 * 60 * 24 * 30 * 12;
    setcookie('pref_id', $account->uid, $year, '/', '.preferans.de');
    setcookie('pref_auth', $auth, $year, '/', '.preferans.de');
  }

}

Comment: You might have to clear the Drupal cache before you see new preprocess_page hooks working...


How can I prove this inequality:$(x+y)^4\le8(x^4+y^4)$?

Question: I have to proce that $(x+y)^4\le8(x^4+y^4)$
I have seen that the equality is when $x=y$...
I have tried to develop $(x+y)^4$ but it leads me nowhere... I think that I have to pass by the intermediate of the averages, but I don't see witchone... Could someone please help?
Comment: By the way, the MathJax code \le ("less equal") will yield $\le$.
Comment: ... or `\leq` (**l**ess than or **eq**ual to), if you prefer.
Answer: Hint: If $y=0$ it's obviously true. If $y\ne 0$ then divide both sides by $y^4$ and let $t=\frac{x}{y}$. Then move everything to the RHS and study the function of $t$ which you got.
Answer: You can divide both sides by 16, and then use that $f(x)=x^4$ is a convex function (since $f''(x)\ge 0$).
Answer: your inequality is equivalent to $$8(x^4+y^4)-(x+y)^4=(x-y)^2 \left(7 x^2+10 x y+7 y^2\right)\geq 0 $$
Answer: $$(x+y)^4= x^4+4x^3y+6x^2y^2+4xy^3+y^4$$
Now, by AM-GM you have
$$
x^3y \leq \frac{x^4+x^4+x^4+y^4}{4} \\
x^2y^2 \leq \frac{x^4+y^4}{2} \\
xy^3\leq \frac{x^4+y^4+y^4+y^4}{4}$$
Thus
$$(x+y)^4 \leq x^4+4 \cdot \frac{x^4+x^4+x^4+y^4}{4} +6 \frac{x^4+y^4}{2} +4 \frac{x^4+y^4+y^4+y^4}{4} +y^4$$
Comment: How do you prove the things by AM-GM please? I have been trying but I can't see
Answer: My idea: we have equality when $x = y$, so your inequality is true if moving $x$ and $y$ away from equality increases the RHS more than the LHS.
Let $m$ be the midpoint of $x$ and $y$, and $c$ the distance from $m$ to each of them, say $x = m + c$, $y = m - c$, so $c$ is a measure of how different $x$ and $y$ are. We have \[(m + m)^4 = 8(m^4 + m^4),\] as you pointed out, and moreover $(m + c) + (m - c) = m + m$, so the LHS is also $(x + y)^4$, your LHS. So adding $c$ to one term and subtracting it from the other doesn't change the size of the LHS. It only remains to prove that doing the same to the RHS makes it bigger, that is, \[8(m^4 + m^4) \le 8((m + c)^4 + (m - c)^4).\] Expand some brackets and cancel some terms and this should be easy to verify.


Can I set cookies in JavaScript POST-request to the external site?

Question: Subj. More detailed:
If I have JS-code on the page, loaded from my site, can that code make POST-request to the third site and set up cookies for that request?
Or more commonly - can I set up arbitrary headers (including cookies) in the JavaScript POST-request to the third-party site?
Answer: For security reasons that's not possible
You can have a hidden iframe tag into your html, but you can't access the cookies that the site saves into the browser
<code><?php

$var=$_COOKIE['somevar'];
?>
<iframe src="http://www.someurl.com/somefile?variable=<?php echo $var?>" style="display:none" />
</code>


Even function I don't think is even

Question: My professor provided the following function:

which he says is even with a period of $2\pi$.
I get what he means, it's supposed to be a sawtooth-like function. But is this really even? In a function like that, every single line portion would be a different line, right? This function is just going to keep going further and further away, naturally, as we move from $(0,0)$.
Am I misunderstanding something here?
Comment: The function is defined on (0,pi) and has period 2pi. To impose that it is even is a way of defining it completely.
Comment: Oh, of course. What confused me was that the professor made it look like you needed to prove it was even. Thanks.
Answer: The function is even about the line $x=\frac{\pi}{2}$; i.e. about the line $x=\frac{\pi}{2}$, if the left hand part of the function is the reflection of the right hand part of the function, then the function is even.
Or, in other words, shift the origin of the co-ordinate system to $(\frac{\pi}{2},0)$ and suitably change the functions according to the shifting of the axes. Then you will find that the function is even i.e. $f(-x)=f(x)$.
Answer: Let $X$ be a set of real numbers, and say that $X$ is symmetric if $X$ is invariant under reflection in the origin, i.e., if $-x \in X$ if and only if $x \in X$.
Let $X$ be symmetric. A real-valued function defined on $X$ is even if $f(-x) = f(x)$ for all $X$ in $X$, and is odd if $f(-x) = -f(x)$ for all $X$ in $X$.
As Did notes, your function is defined on $[0, \pi]$, an interval that is not symmetric, and does not have length $2\pi$.
Since your professor mentions an even function with period $2\pi$, it's fairly clear from context that you're meant to consider the even extension of $f$, defined on $[-\pi, \pi]$ by requiring $f(-x) = f(x)$ for $-\pi \leq x < 0$. (There is also an odd extension, defined by requiring $f(-x) = -f(x)$ for $-\pi \leq x < 0$.)
On the guess that you're studying Fourier series, note carefully that a piecewise-$C^{1}$ function $f$ on $[0, \pi]$ has:

A cosine series, the Fourier series of the even extension.
A sine series, the Fourier series of the odd extension.

The function $f$ itself does not have a Fourier series with respect to the standard trigonometric basis because $f$ (as initially defined, on an interval of length $\pi$) is not $2\pi$-periodic.

Even function I don't think is even


Image Styles and Progressive Images

Question: I am specifically asking for a D7 site, however I wouldn't mind know for D8 as well.
Scenario

Save an image in Photoshop as a progressive image.
Upload this to an Drupal image field that utilizes image styles.

Question
When doing this image styles creates a new image, is the new image still progressive or is there something I would need to configure to make sure that image styles does this automatically?
Answer: Basically Drupal does not change that kind of attribute on an image.
But I thinkg you can check this way :
1- Make a very large image with Photoshop ;
2- Save it without making it progressive ;
3- Upoad it on the website and try displaying it.
NB : Very large image because for this test you want to make sure the image will display slowly.
4- save your image again with Photoshop, making it progressive this time. And then :
5- Upload the new one ;
6- Try to display it in a new tab and compare.
Certainly you will see if there is a difference.
That's what I would do....
Comment: Is it even going to matter for image styles that crop down to 500x500 or smaller?
Comment: You may try the same method and crop the second image and see the difference

Image Styles and Progressive Images


AJAX event and disable select form element

Question: I have a little problem:
/**
 * Form callback
 */
function ajax_disable_test_form($form, &$form_state) {
  $form['select'] = array(
    '#type' => 'select',
    '#required' => FALSE,
    '#title' => t('Change me!'),
    '#empty_option' => t('- Select -'),
    '#options' => drupal_map_assoc(range(1, 3)),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['change'] = array(
    '#type' => 'submit',
    '#value' => t('Change!'),
    '#ajax' => array(
      'callback' => 'ajax_disable_test_form_submit_ajax',
      'wrapper' => 'select_box_wrapper',
    ),
  );
  return $form;
}

/**
 * Ajax callback
 */
function ajax_disable_test_form_submit_ajax($form, $form_state) {
  $form['select']['#title'] = t('Changed!'); // It's work!
  $form['select']['#disabled'] = TRUE; // It's not work!
  return $form['select'];
}

Link: https://gist.github.com/nevergone/23f0a50bee01acc34ed2
If clicked the button, select box title changed, but select box not disabled. Why?
Version: Drupal 7.41
Comment: http://drupal.stackexchange.com/questions/20321/returning-disabled-in-ajax-callback
Answer: try:
$form['select']['#attributes']['disabled'] = 'disabled';

Ok, a detailed explanation can be found on this article https://www.drupal.org/node/357328
But pretty much resumes to:

we cannot simple set the $element['#disabled'] attribute of the
  element. The reason is this attribute is transformed into
  $element['#attributes']['disabled'] by
  _form_builder_handle_input_element executes()...
Comment: Please try explaining why the code works. A code-only answer doesn't explain why it works or what the asker did wrong in the first place.
Comment: ok, some background was added to my answer.
Answer: You will need to rebuild your form. Have a look at the Ajax Framework docs for further information.
<?php

/**
 * Form callback
 *
 * Implements hook_form().
 */
function ajax_disable_test_form($form, &$form_state) {
  $form['select'] = array(
    '#type' => 'select',
    '#required' => FALSE,
    '#title' => t('Change me!'),
    '#empty_option' => t('- Select -'),
    '#options' => drupal_map_assoc(range(1, 3)),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (!empty($form_state['values']['change'])) {
    $form['select']['#disabled'] = TRUE;
    $form['select']['#title'] = t('Changed');
  }

  $form['change'] = array(
    '#type' => 'submit',
    '#value' => t('Change!'),
    '#submit' => array('ajax_disable_test_change_submit'),
    '#ajax' => array(
      'callback' => 'ajax_disable_test_ajax_callback',
      'wrapper' => 'select_box_wrapper',
    ),
  );
  return $form;
}

/**
 * Submit handler to disable the select input, and then rebuild the form.
 * If the button was click with JS enabled, then ajax_form_callback() calls
 * ajax_disable_test_submit_ajax() to return just the changed part of the form.
 */
function ajax_disable_test_change_submit($form, &$form_state) {
  if ($form_state['values']['change']) {
    $form_state['select_is_disabled'] = true;
  }
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback
 *
 * @see ajax_disable_test_change_submit().
 */
function ajax_disable_test_ajax_callback($form, $form_state) {
  return $form['select'];
}


Add language menu to the main menu

Question: I have menu structure like this:
Home | About | Products
if a user is currently on English page then I need like this:
Home | About | Products | Swedish
and if a user is currently on Swedish language then it will show like:
Home | About | Products | English
1: So how can I add a menu switcher link to the main menu which shows only one language link at a time?
2: What will be the pate for each of the language in the path field while adding a menu link.
Answer: You have two ways of doing this, one is to use HTML/CSS to position the language switcher block in the menu, probably a little harder to do with a variable length menu unless you right align it.
Two would be to add the language switcher to the menu, you can use something like http://www.liquidcms.ca/how-to-language-switcher-menu-item to do that.
Comment: I am actually using dropdown menus on my site. I guess the first option is not possible to append the language switcher to the main-menu. 2nd I am new to drupal and coding as well.
Comment: That's probably your theme or modules doing something, by default it's just two text links.
Comment: You're going to want to read up on https://drupal.org/node/361112 it will let you know how to properly do this. Basically you'll want a new custom module with that PHP (in the url above) in there. If you need more help just ask.
Comment: While adding a menu item for language what should I write in the path field ? like mysite/en or mysite/sv
Comment: That is another option if you don't mind not keeping the current path.
Comment: It depends how you set it up in the language settings.
Comment: @Steven - The above link is dead.
Answer: Menu per language module will have the option

This module enables you to have an clear overview per language what
  the menu entries are. In Drupal all of these links are on the same
  page and thus it is not clear in which language it is and the menus
  will grow very big in time aswell.
Comment: I have made two menu blocks one for each language. Now all I need al-least is to change the url from "mysite/?q=en" to "mysite/?q=sv" when a user click the menu item "Swedish". How can I do that?
Answer: I have solved my problem with the help of a friend. I have created a list of two menus lists using menu-block module. One set of English menus and one set of Swedish menus in the following order.
Home | About | Products | Svenska

and for Swedish
Hem | OM | Produkter | English
After creating the menus , I was unable to provide URL or link to a node (/node/3) OR language (/?language=en) in the path field while creating the link item.
In my case if I change the language such as (http//mysite.com/?q=en) to (http//mysite.com/?q=sv) the above created Swedish menu-block appears. As Swedish menu-block was enabled on Swedish language and English on English menu-block. After that I change one of the hook available in the main theme to my requirement.
I used yourtheme_menu_link() hook in template.php file. Under the set of if statements I added this block.
    if ($element['#original_link']['mlid'] == 2662) {
    global $language;
     $lang = $language;
     $lang->prefix = "en";
    $special_link = '<a href="' . url('<front>', array('language' => $lang)) . '">English';
} else if ($element['#original_link']['mlid'] == 2675) {
    global $language;
     $lang = $language;
     $lang->prefix = "sv";
    $special_link = '<a href="' . url('<front>', array('language' => $lang)) . '">Svenska';
}

if (at_get_setting('extra_menu_classes', $theme_name) == 1 && !empty($element['#original_link'])) {
  if (!empty($element['#original_link']['depth'])) {
    $element['#attributes']['class'][] = 'menu-depth-' . $element['#original_link']['depth'];
  }
  if (!empty($element['#original_link']['mlid'])) {
    $element['#attributes']['class'][] = 'menu-item-' . $element['#original_link']['mlid'];
  }
}

Here 2662 and 2675 is the menu item id. This may help if someone need. It solved my problem.

Add language menu to the main menu


Android Room what does @field mean

Question: Im recently learning Room to manage my database and using "GithubBrowerSample" as the template.
Generally, it looks good to me except for the @field keyword. I have been googling quite a bit but fail to find any explanation about it. Thee android doc examples seem to work fine without it. What is it really doing here in Room?
Answer: This isn't something unique to Room - instead this is Kotlin Annotation targets:

When you're annotating a property or a primary constructor parameter, there are multiple Java elements which are generated from the corresponding Kotlin element, and therefore multiple possible locations for the annotation in the generated Java bytecode.

So @field:SerializedName("owner") means that the SerializedName("owner") annotation should be added to the underlying field itself (rather than say, when using @get: where it would attached to the generated getOwner() method or the @property: default which, as per that same page, isn't available to Java, which is what Room is parsing).
Comment: I still don't quite fully understand. Are you saying when kotlin code converts to java byte code, e.g. val name: String, it actually converts to three code snippet: 1. String name, 2. getName(), 3. setName().  And "@field" means to add annotation SerializedName("owner") only to the part "String name"? Am I getting the right idea?
Comment: Yep, that's correct. Android Studio has a built in tool for [showing the generated code](https://link.medium.com/WVe6LItIb6) which you might find useful.

Android Room what does @field mean


Comparing two gaussian distributions

Question: Apologies if this is a really simple question; I'm sure if only I knew what to google I'd be able to find the answer myself, but it's been driving me mad.
I have two datasets with approximately gaussian distributions. Both are measurements of the same background distribution, taken for reproducibility of some optical instrumentation I've developed. I need to prove this using the two measurements.
My understanding is that to achieve this, I integrate common area that's underneath both measured distributions. However...
In my case, gaussian 1 has a mean of 41.3 and a standard deviation of 1.0. Gaussian 2 has a mean of 41.7 and a standard deviation of 1.6. This means that the two gaussians intersect twice.
When I integrate the common area, I get 0.76, which I interpret to mean there's a 0.76 probability that the two measurements are of the same background distribution. This sounds way too low to me.
I had a look at KL divergence, but this is asymmetric and assumes that one of the measured distributions is the 'true' distribution - this is not the case for my measurements.
I have some more similar comparisons with more than two measured distributions to worry about, but I'd like to walk before trying to run...
Comment: One can never actually measure an entire distribution--that's physically impossible.  How, then, do you obtain these means and SDs?  This is fundamentally important, for otherwise there is no disciplined correct way to answer your question.
Comment: I'm measuring size distributions of particles. A computer algorithm interrogates the scattered light from single particles and uses this to infer a size of that particle. Each of my distributions is composed of a large number (thousands) of such measurements. The two distributions are measuring the same particles; as such I am confident of the same background distribution.
Comment: Following @whuber's comments, it seems you use `distribution` in an un-statistical sense, which makes your question confusing.
Comment: @ Xi'an I've made an edit which hopefully clarifies the question.
Comment: It's unclear what you are asking.  Your question seems to be "I need to prove this," but what exactly does "this" refer to?  That the optical measurements are reproducible?  That the background particle size distributions are indeed the same?  That they are indeed approximately Gaussian? (That, by the way, would be unusual for a particle size distribution: typically it's the cube roots of the sizes that tend to have Gaussian distributions.)  And precisely what data--and how much of them--do you have to make your "proof"?
Comment: "I had a look at KL divergence, but this is asymmetric and assumes that one of the measured distributions is the 'true' distribution". It is a very common thing to use the mean of the two KL divergences: $D = 0.5 \times D_{KL}(p||q) + 0.5 \times D_{KL}(q||p)$
Comment: @whuber I need to demonstrate that the measurements are reproducible. Each 'measurement' is composed of a large number of measurements of individual particles (several thousand particles). I'm happy that the background distribution is closely approximated by a gaussian for these particular particles, and to a very good approximation the measurements of this distribution are also gaussian.
Comment: Okay, that helps us understand better what you're doing.  In general it is difficult, if not impossible, to assess reproducibility of measurements by means of just two of them: typically one collects a larger set of measurements in order to assess how much they typically vary.  Do you seek a way of *quantifying the difference* between two observed distributions?  And if so, which aspects of their difference are of greatest importance in your application?
Comment: @whuber I'm specifically seeking a way of calculating the probability that the two measurements of my background distribution are indeed both measurements of the (unknown) background distribution. Failing that, I'd like to quantify the similarity between them or find the probability that they are the same. I'm more interested in the difference (or similarity) of the means than I am in the differences between the standard deviations.
Comment: That probability does not exist unless you (a) make probability assumptions about what the background might be and (b) also adopt a probability model of how the measurements arise from a distribution.  In fact, it's hard to make sense of your question: your measurements  clearly *are* measurements of your background distribution. Moreover, they are so detailed that it's extremely unlikely they ever would be the same. If you're interested in the difference of means, then you are in the classical textbook setting of testing the difference of means of two Normal distributions.
Comment: That's actually incredibly helpful - I was beginning so suspect that exactly the measure I was looking for was impossible to calculate, but I didn't have the expertise to confirm this myself. Thanks for taking the time to decipher my imprecise waffle.
Comment: Look at my answer here:  https://stats.stackexchange.com/questions/271582/is-the-intersection-area-between-2-pdfs-a-probability/271590#271590
Answer: What you are looking for is a two-sample test for equality of distribution.  There are a number of known tests of this kind, including the Wald-Wolfowitz two-sample runs test, the Friedman-Rafsky two-sample runs test, the Kolmogorov-Smirnov two-sample test, the Henze nearest neighbour test, and the Zeck-Aslan minimum energy test.  There are probably many others, but these will get you started.  The Kolmogorov-Smirnov two-sample test is a particularly common test which is easy to implement and which has an explicit formula to estimate the p-value.
Answer: Concerning your comments on KL divergence:

I had a look at KL divergence, but this is asymmetric and assumes that one of the measured distributions is the 'true' distribution - this is not the case for my measurements.

I would suggest you use the symmetrized KL divergence:
$$ KL_{sym}(P, Q) = (KL(P||Q) + KL(Q||P)) / 2 $$

Comparing two gaussian distributions


Can Cloudstack be used to manage Rackspace Cloud servers

Question: Specifically, I'm looking at the latest version of Cloudstack, the 184.108.40.206RC..  I can't find in the documentation anything specifically saying whether cloudstack supports or does not support Rackspace Cloud at this time.
Is there a comprehensive list somewhere of all the available VM / Cloud environment managers that Cloudstack supports?
Answer: rackspace cloud is built upon the openstack.
cloudstack is a tool to enable you to manage virtual servers but it requires you to have physical servers to do the virtual server hosting.
rackspace cloud in its raw form available to the end user is NOT compatible with cloudstack, besides virtualising servers in a virtual environment is 99% not worth it and I believe you can only virtualise openvz within a xen environment (with some work and not recommended)
Comment: Thanks.  I wasn't thinking to virtualize the rackspace cloud servers themselves, but to manage the rackspace cloud servers alongside any other VMs I were to create.
Comment: yeah cloudstack doesnt work like that with 3rd party providers... you need your own hardware
Answer: CloudStack is NOT based on OpenStack.
CloudStack started in 2008, written in Java.
OpenStack started in 2010 and is written in Python.
And no, you can't manage RackSpace Cloud. CloudStack is for running your own cloud, be it a public cloud offering cloud services like Godaddy, KT, or Tata; or a private cloud internal to your company like Zynga, Edmunds.com, etc.


Expect and --More--

Question: Im trying to use expect to auto accept an EULA that is prompted in --more--.
#!/usr/bin/expect
spawn "./greenplum-perfmon-web-18.104.22.168-build-2-RHEL5-x86_64.bin"
expect "--More--"
send "q"
expect "*****"
send "yes"
expect "*****"
send ""
expect "*****"
send "yes"

This does not work and Im not sure why. The script always halts at the --More-- prompt and the second I click ANYTHING it instantly processess the rest of the script.
I have tried with
expect -exact "--More--"

and
expect "the Customer"
(what is written above the --More--)

Comment: set `exp_internal 1` to get a better debug output
Comment: change `send "yes"` to `send "yes\r"` if the program expects the user to hit enter. `expect "****"` will probably match anything, since the default matching mode is `-glob` and `*` is a glob-special character: use `expect -exact ****`
Answer: Try setting $MORE to something like -99999999 so that the more prompt never shows up.
Comment: The environment variable. You know, the one that `more` reads to get its options? You know this because you read the man page, right?
Answer: A solution avoiding expect altogether:
You could avoid the problem altogether by setting the PAGER environment variable to a different program and using the yes program. The following turns off yes and sends as many yes\n strings into the installer as it will take:
PAGER=cat  yes yes | ./greenplum-perfmon-web-22.214.171.124-build-2-RHEL5-x86_64.bin

If that looks weird to you, it is almost equivalent to the following:
export PAGER=cat
yes yes | ./greenplum-perfmon-web-18.104.22.168-build-2-RHEL5-x86_64.bin

The difference is that with the one-liner, PAGER is only set for that one command, not for anything that comes afterwards.

Expect and --More--