How to change key size in OpenSSH?

Question: How to change key size in OpenSSH? I would like to change it from 1024 key size length to 512.
Answer: I am pretty sure this is what you are after. You need to use ssh-keygen.
<code>ssh-keygen -t rsa -b 512
</code>
this should create a 512 rsa crypto key
Comment: This doesn't work. OpenSSH back at least to 5.3 ~ 2009 requires minimum 768 bits for RSA, and the page you linked dated 2007 says the same. As an update, since 7.6 in 2017 the minimum is 1024. And of course RSA-512 was _broken_ and insecure since about 1990, although this Q did not ask about security. OpenSSL has always been, and even 1.1.1 in 2018 still is, willing to generate RSA-512 with `openssl genrsa 512`. c
Answer: There's also a ServerKeyBits option in sshd_config, can set that to a minimum of 512.
Comment: That's only used for legacy SSH-1 connections, and is not used with SSH-2.

How to change key size in OpenSSH?


iframe problem using javascript

Question: Does anyone know how to get the HTML out of an IFRAME? I have tried several different ways:
document.getElementById('iframe01').contentDocument.body.innerHTML, document.frames['iframe01'].document.body.innerHTML, document.getElementById('iframe01').contentWindow.document.body.innerHTML, etc
but none of them worked.
I believe the reason they're not working is that the content of my iframe doesn't have a body tag (I'm loading XML). Any other way to get all the contents of the iframe? I am open to jQuery too.
This:
document.getElementById('iframe01').contentWindow.document.body.innerHTML
works fine in the IE, but this:
document.getElementById('iframe01').contentDocument.body.innerHTML
does not work for FF.
Comment: Do you need all the html? Or do you just need a sub-section? I guess what I'm trying to ask is, what are you doing with the innerHTML value?
Comment: i want the inner html content (which is an xml with xsl) and then display it in an ckeditor.
Comment: heres the sample of my innerhtml thru FF firebug :

TitleRest content
Another Content
Answer: Since you tagged this jQuery, I assume you'd appreciate an answer in jQuery to get past the cross-browser issues.
$("#iframe01").contents()

will get you into the jQuery object for the contents of the iframe. You can work from there. Security issues may prevent you from getting the actual HTML content (you'll get an error like "permission denied to get property htmldocument").
Full sample code:
<!DOCTYPE html>

Hello World, there's an iframe below this. Click me!

Note that you will have to load the iframe from the same domain and be sure the iframe has loaded before doing anything.
Comment: iframe_content.html contains your example
     TitleRest content Another Content
Answer: I had a similar issue a while ago. Try using:
document.frames["iframe0"].contentWindow.document.body.innerHTML

That should work for both IE and FF
Comment: it works if only i have body tag within the iframe. but in mycase the body tag is not there because i am opening an xml with xsl in the iframe. it shows no body tag it shows one  tag which also i cant access

iframe problem using javascript


How do I inner join two array in numpy?

Question: I have two array looks like this:
A:
20131010 123 12321 12312312
20131011 123 12321 12312312
20131012 123 12321 12312312
20131013 123 12321 12312312

B:
20131010 bbbb sad sadsad
20131011 asd asdd asdad
20231012 123 12321 12312312
20141013 123 12321 12312312
20141023 123 12321 12312312

Now I need to inner join these two array by the first column(date), the result should looks like this:
20131010 123 12321 12312312 bbbb sad sadsad
20131011 123 12321 12312312 asd asdd asdad

How do I make it ? Note that each have lots of columns so I can't name every column, but the compare column is indeed only one.
Comment: I think Pandas does this really nicely for you... Will both arrays have the same indices present, once and only once? You could then sort both arrays by the first column and then `hstack` them. If it's mor complicated, you'll have to give us more details.
Answer: This is horribly under documented, but check out numpy.lib.recfunctions.join_by. It will do several kinds of SQL like joins, including inner join. I don't see this module on the numpy page, but at least the doc strings give you some info (copied from 1.9.1 below).
Note that this looks like it requires a structured array to work, so you may have to cast into a recarray, rather than just say "join on column 0"
Join arrays `r1` and `r2` on key `key`.

The key should be either a string or a sequence of string corresponding
to the fields used to join the array.  An exception is raised if the
`key` field cannot be found in the two input arrays.  Neither `r1` nor
`r2` should have any duplicates along `key`: the presence of duplicates
will make the output quite unreliable. Note that duplicates are not
looked for by the algorithm.

Parameters
----------
key : {string, sequence}
    A string or a sequence of strings corresponding to the fields used
    for comparison.
r1, r2 : arrays
    Structured arrays.
jointype : {'inner', 'outer', 'leftouter'}, optional
    If 'inner', returns the elements common to both r1 and r2.
    If 'outer', returns the common elements as well as the elements of
    r1 not in r2 and the elements of not in r2.
    If 'leftouter', returns the common elements and the elements of r1
    not in r2.
r1postfix : string, optional
    String appended to the names of the fields of r1 that are present
    in r2 but absent of the key.
r2postfix : string, optional
    String appended to the names of the fields of r2 that are present
    in r1 but absent of the key.
defaults : {dictionary}, optional
    Dictionary mapping field names to the corresponding default values.
usemask : {True, False}, optional
    Whether to return a MaskedArray (or MaskedRecords is
    `asrecarray==True`) or a ndarray.
asrecarray : {False, True}, optional
    Whether to return a recarray (or MaskedRecords if `usemask==True`)
    or just a flexible-type ndarray.

Notes
-----
* The output is sorted along the key.
* A temporary array is formed by dropping the fields not in the key for
  the two arrays and concatenating the result. This array is then
  sorted, and the common entries selected. The output is constructed by
  filling the fields with the selected entries. Matching is not
  preserved if there are some duplicates...

Comment: Now, there is some documentation https://numpy.org/devdocs/user/basics.rec.html#record-arrays
Answer: Try converting the numpy arrays to pandas DataFrames. Then use pandas.merge().
Like
df = pd.merge(df1,df2,on='Unnamed: 2',how='inner')

How do I inner join two array in numpy?


How to create view?

Question: I have this data.

ID        UserID        Grade
1           1             A
2           1             A
3           1             a
4           1             a
5           1             b
6           1             C
7           1             c
8           1             b
9           2             b
10          2             C
11          1             b
12          2             A

I want to create view for this result.

RunningNumber UserID         Result         Count
1                1             a              4
2                1             b              1
3                1             c              2
4                1             b              2
5                2             b              1
6                2             c              1
7                2             a              1

The result will count column Grade (case insensitive) and must be group by UserID.
I try to use below.

      SELECT ROW_NUMBER()
        OVER (ORDER BY Grade) AS RunningNumber ,
       UserID, Grade, COUNT(ID) AS Count
        FROM Table1
      GROUP BY UserID,Grade;

But It's not my results. I want count by select Grade [order by id]. If Grade of next record is the same with current record, Count will be +1. But if not, it will be new record.
Ex. from my data.
   userID=1 Grade=A ==> record 1 : userID=1 result=a count=1
   userID=1 Grade=A ==> record 1 : userID=1 result=a count=2
   userID=1 Grade=a ==> record 1 : userID=1 result=a count=3
   userID=1 Grade=a ==> record 1 : userID=1 result=a count=4
   userID=1 Grade=b ==> record 2 : userID=1 result=b count=1
   userID=1 Grade=C ==> record 3 : userID=1 result=c count=1
   userID=1 Grade=c ==> record 3 : userID=1 result=c count=2
   userID=1 Grade=b ==> record 4 : userID=1 result=b count=1
   userID=2 Grade=b ==> record 5 : userID=2 result=b count=1
   userID=2 Grade=C ==> record 6 : userID=2 result=c count=1
   userID=1 Grade=b ==> record 4 : userID=1 result=b count=2
   userID=2 Grade=A ==> record 7 : userID=2 result=a count=1

Comment: Which are the results you want?  The table in the middle ("this result") or the example at the end?
Answer: From what I can tell, you just want to include userid in the row_number() to get your desired output:
  SELECT ROW_NUMBER() OVER (ORDER BY UserId, Grade) AS RunningNumber,
         UserID, Grade, COUNT(ID) AS Count
  FROM Table1
  GROUP BY UserID, Grade
  ORDER BY UserID, Grade;

How to create view?


Integração Windows form com página html

Question: Eu tenho uma aplicação que é um Windows Forms que eu preciso integrar em uma página HTML da minha aplicação web
No caso fazer com que o Windows Form fique ali fixo como se os dois fossem uma coisa só.
Isto é possível?
Answer: Usando apenas Html não é possível.
Você pode incluir na sua página Html aplicativos desenvolvidos com Flash e Silverlight, por exemplo.
Houve tempo em que era muito comum incluir também componentes ActiveX (que podem ser desenvolvidos em qualquer linguagem) ou Java applets; mas este tipo de recurso é um risco em potencial para o usuário então há uma tendência de não serem mais suportados ou terem o seu uso dificultado pelos navegadores.
Há opções que fazem parecer que o aplicativo está rodando dentro do Browser, como o Citrix, mas o aplicativo não estará embutido em uma página Html.
Comment: @Lorena O que eu conheço por *Websockets* é comunicação por rede. Não parece estar relacionado.
Comment: @Lorena Não dá não. A página web teria que mandar o browser consumir este aplicativo externo, o qual o browser não tem como saber se é seguro ou não. O browser precisa limitar o máximo possível o acesso de uma página web à máquina do usuário; a idéia é tornar segura a navegação web mesmo que o usuário não conheça previamente a idoneidade do link que ele vai clicar.
Comment: Com Websockets teria alguma solução?
Comment: é exatamente isto que preciso, não precisa estar embutido mas parecer que está, não vai ter troca de dados entre a página html e o software externo, só preciso fazer com que o usuário veja os dois juntos como se fossem apenas um.
Answer: Você poderia botar um WebBrowser na sua form, em seguda botar no código:
<code> [nome do webbrowser].DocumentText = "Código HTML em string";
ou [nome do webbrowser].Navegate("url da página HTML ou caminho no computador");
</code>
Você poderia usar o DocumentText do webbrowser para interagir, modificar o código HTML ou ler o código, e asim interagir

Integração Windows form com página html


Alterar atributos de classe a partir de método genérico

Question: Tenho uma classe com muitos atributos e gostaria de poder alterar esses atributos a partir de um método genérico onde deve-se passar o nome do atributo a ser alterado e o novo valor.
class Classe_com_muitos_atributos:
   def __init__(self, atr1, atr2, atr4 ...):
      self.atr1 = 5
      self.atr2 = 5
      self.atr3 = 5
      self.atr4 = 5
      #muitos atributos...

   def altera_atributo(self, var_com_o_nome_do_atributo, valor):
      self.var_com_nome_do_atributo = valor

A idéia é que o método seja executado da seguinte forma:
instancia.altera_atributo('atr2', 10)

Minha dificuldade é que o python procura na classe, um atributo com o nome "var_com_o_nome_do_atributo" e não sei como fazer para que, ao invés disso, ele procure na classe pelo atributo que está contido na variável, neste exemplo, atr2.
Imagino que deve ser algo simples, mas estou começando agora e não estou encontrando a solução.
Comment: Digo para usar dicionário no lugar da classe, se quer algo de acesso dinâmico você não quer uma classe. É até possível fazer o que deseja, mas pra que? Use a ferramenta certa para a tarefa.
Comment: Então pra que fazer uma classe? Não seria melhor fazer um dicionário?
Comment: muitos dos "atributos" da classe são dicionários... o método é justamente pra facilitar o acesso
Answer: Utilize o setattr.
Sua função altera_atributo vai ficar assim:
def altera_atributo(self, var_com_o_nome_do_atributo, valor):
  setattr(self, var_com_o_nome_do_atributo, valor)

Answer: O comentário do Maniero me ajudou na resolução. A classe continua sendo uma classe mas os atributos semelhantes foram transformados em um único dicionário (como atributo da classe). Não sei se é uma boa prática mas resolveu.
Comment: Inicialmente usar um dicionario como uma classe resolveu, mas como parecia muito um POG, fui estudar POO (em c# que tô mais acostumado), me pareceu uma solução mais elegante utilizar uma subclasse como atributo uma vez que só os valores mudam, os índices são imutáveis e utilizados em muitos lugares.


getting error when using ansible Kerberos

Question: I create 2 servers, windows and Linux. Linux is for ansible runner machine, windows as host machine.
Through the Linux ansible machine, login to host windows machine and install tools. In Linux ansible machine installed all tools, windows host machine is domain joined, but not for Linux. we don't have domain join for Linux. Now I'm trying to authenticate with Kerberos. I'm getting some errors.
Kerberos ref link I used: (user authentication process)
https://docs.ansible.com/ansible-tower/3.3.1/html/administration/kerberos_auth.html

see above screenshot, I added Kerberos config file, and run kinit command.
How to config Kerberos in ansible, Kerberos need VM domain join or not?
No active directory accounts to authenticate, only VM username and VM password. what is the process to config VM username and VM Password in Kerberos config file, and login to host machine.
Please help me on this.
Comment: Please edit your question and add the **code, logs, output, error messages... in the question body as code blocks**. Using images for this has [numerous disadvantages](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557) and is specifically listed as a bad practice in [ask]. Thanks
Answer: For me your KDC is wrong.
You need to go on your windows host. Open a command line and enter the following command :
nslookup -type=srv _kerberos._tcp.WSUS.COM

Expected result :
priority       = 0
          weight         = 100
          port           = 88
          svr hostname   = REALKDC

Change your KDC in krb5.conf by REALKDC.
And now your kinit command will work normally.
Don't forget to use a username which exist in your AD :
kinit myuser


Django ReverseSingleRelatedObjectDescriptor.__set__ ValueError

Question: I am creating a custom data migration to automatically create GenericRelation entries in the database, based on existing entries across two different models.
Example models.py:
<code>...
class Place
   content_type = models.ForeignKey(ContentType)
   object_id = models.PositiveIntegerField()
   content_object = generic.GenericForeignKey('content_type', 'object_id')

class Restaurant
   name = models.CharField(max_length=60)
   location = models.CharField(max_length=60)

class House
   location = models.CharField(max_length=60)
</code>
Example 0011_place_data.py:
<code># -*- coding: utf-8 -*-
from django.contrib.contenttypes.models import ContentType
from django.db import models, migrations

def forwards_func(apps, schema_editor):
    Restaurant = apps.get_model("simpleapp", "Restaurant")
    House = apps.get_model("simpleapp", "House")
    Place = apps.get_model("simpleapp", "Place")

    db_alias = schema_editor.connection.alias

    content_type = ContentType.objects.using(db_alias).get(
        app_label="simpleapp",
        model="restaurant"
    )

    for restaurant in Restaurant.objects.using(db_alias).all():
        Place.objects.using(db_alias).create(
            content_type=content_type,
            object_id=restaurant.id)

    content_type = ContentType.objects.using(db_alias).get(
        app_label="simpleapp",
        model="house"
    )
    for house in House.objects.using(db_alias).all():
        Place.objects.using(db_alias).create(
            content_type=content_type,
            object_id=house.id)

class Migration(migrations.Migration):

    dependencies = [
        ('simpleapp', '0010_place')
    ]

    operations = [
        migrations.RunPython(
            forwards_func,
        ),
    ]
</code>
When I run this (Django 1.7.4) I get
<code>Operations to perform:
  Apply all migrations: simpleapp, admin, sessions, auth, contenttypes
Synchronizing apps without migrations:
  Creating tables...
  Installing custom SQL...
  Installing indexes...
Running migrations:
  Applying projects.0011_place_data...passing
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File ".../lib/python3.4/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
  File ".../lib/python3.4/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
  File ".../lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
  File ".../lib/python3.4/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
  File ".../lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 161, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
  File ".../lib/python3.4/site-packages/django/db/migrations/executor.py", line 68, in migrate
self.apply_migration(migration, fake=fake)
  File ".../lib/python3.4/site-packages/django/db/migrations/executor.py", line 102, in apply_migration
migration.apply(project_state, schema_editor)
  File ".../lib/python3.4/site-packages/django/db/migrations/migration.py", line 108, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File ".../lib/python3.4/site-packages/django/db/migrations/operations/special.py", line 117, in database_forwards
self.code(from_state.render(), schema_editor)
  File ".../simpleapp/migrations/0011_place_data.py", line 19, in forwards_func
object_id=restaurant.id)
  File ".../lib/python3.4/site-packages/django/db/models/query.py", line 370, in create
obj = self.model(**kwargs)
  File ".../lib/python3.4/site-packages/django/db/models/base.py", line 440, in __init__
setattr(self, field.name, rel_obj)
  File ".../lib/python3.4/site-packages/django/db/models/fields/related.py", line 598, in __set__
self.field.rel.to._meta.object_name,
ValueError: Cannot assign "<ContentType: restaurant>": "Place.content_type" must be a "ContentType" instance.
</code>
If I comment out the stanza raising the value error in the Django module (django.db.models.fields.related.ReverseSingleRelatedObjectDescriptor.set) it works as expected:
<code>...

    elif value is not None and not isinstance(value, self.field.rel.to):
        print('skipping')
        #raise ValueError(
        #    'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
        #        value,
        #        instance._meta.object_name,
        #        self.field.name,
        #        self.field.rel.to._meta.object_name,
        #    )
        #)

...
</code>
Should this exception be raised in the first place? Is this a bug in Django or am I doing it wrong?
Comment: i don't understand what you are commenting out. And please can you show the *full* traceback?
Answer: Edit:
The solution below does not actually work; it just ends up not running the forwards_func so there are no errors. New solutions welcome:

I was able to resolve this using Django's post_migrate signal.
This also fixes some other issues that arrive from these types of migrations (data migrations which reference the ContentType table).
My understanding is that essentially, the issue is the ContentType table doesn't get created until the very end of a migration for performance reasons. This means I'm not actually retrieving the same type ContentType object that the relation module is checking for.
The solution is to run this type of data migration as a callback:
<code># -*- coding: utf-8 -*-
from django.db.models.signals import post_migrate
from django.contrib.contenttypes.models import ContentType
from django.db import models, migrations

def forwards_func(apps, schema_editor):
    Restaurant = apps.get_model("simpleapp", "Restaurant")
    House = apps.get_model("simpleapp", "House")
    Place = apps.get_model("simpleapp", "Place")

    db_alias = schema_editor.connection.alias

    def add_stuffs(*args, **kwargs)
        content_type = ContentType.objects.using(db_alias).get(
            app_label="simpleapp",
            model="restaurant"
        )

        for restaurant in Restaurant.objects.using(db_alias).all():
            Place.objects.using(db_alias).create(
                content_type=content_type,
                object_id=restaurant.id)

        content_type = ContentType.objects.using(db_alias).get(
            app_label="simpleapp",
            model="house"
        )
        for house in House.objects.using(db_alias).all():
            Place.objects.using(db_alias).create(
               content_type=content_type,
               object_id=house.id)

    post_migrate.connect(add_stuffs)

class Migration(migrations.Migration):

    dependencies = [
        ('simpleapp', '0010_place')
    ]

    operations = [
        migrations.RunPython(
            forwards_func,
        ),
    ]
</code>
Answer: Looks like it's somewhat related to this Django bug/wontfix
I had similar error when tried to re-assign permissions to user groups in my migration. To fix it I had to manually emit post_migrate signal as described here
Here is my migration code example:
<code># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations
from django.core.management.sql import emit_post_migrate_signal

def trigger_post_migrate(db_alias):
    try:
        # Django 1.9
        emit_post_migrate_signal(2, False, db_alias)
    except TypeError:
        # Django < 1.9
        try:
            # Django 1.8
            emit_post_migrate_signal(2, False, 'default', db_alias)
        except TypeError:
            # Django < 1.8
            emit_post_migrate_signal([], 2, False, 'default', db_alias)

def up(apps, schema_editor):
    # trigger post migrate to make sure all permissions and contenttypes are in place
    trigger_post_migrate(schema_editor.connection.alias)

    # migration code here...

class Migration(migrations.Migration):
    dependencies = [
        ('accounts', '0008_auto_20160712_0608'),
    ]

    operations = [
        migrations.RunPython(up),
    ]
</code>


Asyncpg and AWS Lambda

Question: I'm trying to use asyncpg with AWS Lambda and got next error when trying to import asyncpg
Unable to import module 'handler': No module named asyncpg.protocol.protocol'

I import python dependencies like at this answer with and without virtual environment.
upd. Found this repo with custom compiled psycopg2 what works good with AWS Lambda but for asyncpg don't found such alternative or instruction on compiling Lambda-friendly asyncpg package.
Answer: This library has c-bindings and lambda does not play nicely with those.
The main way to handle it is to upload the specific library with its bindings precompiled for Linux environments.
The main way to is to follow the instructions here and make sure that the library it already compiled in your linux ( or mac I guess ). This would easily happen by just creating a venv and including it as the above guidelines suggest.
You can find a similar problem here.
In general,  this is a common and frameworks like chalice try to find some workarounds.
Answer: write your code under the def lambdahandler() and also import all libraries and function  below this function.

Asyncpg and AWS Lambda


Como carregar apenas o dado em si do banco de dados no ComboBox?

Question: Meu Combobox está apresentando os dados armazenados no banco de forma errada, quando eu clico nele,  ao invés de aparecer unicamente o nome dos supostos clientes cadastrados, o Combobox apresenta o nome do pacote, da classe e uma gama de letras e números.
Trecho de código responsável por carregar o Combobox:
public void carregarComboBoxCliente() {
    ObservableList<Cliente> observableListaCliente = FXCollections.observableArrayList(
            this.clienteListaController.retornaListagemCliente());

    this.cbxClientes.setItems(observableListaCliente);
}

Trecho de código do retornaListagemCliente:
public List<Cliente> retornaListagemCliente(){

    if(this.getClienteDAO()==null) {
        this.setClienteDAO(new ClienteDAO());
    }

    return this.getClienteDAO().getAll();
}

Código da classe(entidade) Cliente:
public class Cliente {

//atributos
private Long id;
private String nome;
private String email;
private Date dataCadastro;
private String cpf;

//getters e setters
public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}
}

Obs: A classe cliente possui apenas métodos "getters e setters" de seus respectivos atributos.
]1
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: @Danizavtz já editei a pergunta conforme pedido.
Comment: Eu coloquei uma resposta, poderia verificar se resolve o seu problema? Escrevi de uma maneira que a solução fica genérica assim você pode implementar sozinho. :-)
Answer: Utilizei o método toString() na classe Cliente e consegui solucionar esse problema.
Código da classe Cliente, onde apenas foi acrescentado o método toString():
public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

@Override
public String toString() {
    return this.nome;
}

Resultado na tela:
Comment: Parabéns, muito bom.
Answer: Uma maneira de resolver o problema é implementando o método toString() da classe que deseja exibir no elemento da interface combobox.
Para entender o que está acontecendo considere o seguinte exemplo:
Pessoa.java
public class Pessoa {
    private String nome;

    //construtor
    public Pessoa(String nome){
        this.nome = nome;
    }

    //setter
    public void setNome(String nome) {
        this.nome = nome;
    }
    //getter
    public String getNome() {
        return nome;
    }
}

Ao usar esta classe e tentar imprimir o conteúdo dessa classe no console, então temos o seguinte resultado:
main.java
 public static void main(String[] args) {
        Pessoa p = new Pessoa("eu");
        System.out.println(p);
        //com.example.stckovrflw.Pessoa@254989ff
        //que também é equivalente à
        System.out.println(p.toString());
        //com.example.stckovrflw.Pessoa@254989ff
    }

Repare que é uma saída bem parecido com o que está obtendo em seu programa. Outro ponto é que em nenhum momento na declaração da classe Pessoa foi implementado o método toString, mas mesmo assim foi possível executar este método em meu objeto.
Isso acontece porque em Java toda classe é direta ou indiretamente uma subclasse de Object. Ref. Assim todas as classes herdam esta implementação que foi feita na classe Object. O método toString() possui uma implementação "padrão" em que o classpath é concatenado com o endereço de memória que aponta para o conteúdo deste objeto. Como podemos ver a implementação do método toString() da classe Object.
Implementação concreta do método toString() da classe Object.
public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Agora que sabemos o motivo de imprimir desta forma, o que você pode fazer para resolver este problema é implementar o método toString() da classe Cliente.
Para o exemplo da classe Pessoa, uma implementação possível seria:
public String toString() {
    return this.nome;
}

Após fazer esta implementação toda vez que eu for fazer um "print" deste objeto, o resultado será:
public static void main(String[] args) {
    Pessoa p = new Pessoa("eu");
    System.out.println(p);
    //eu
    System.out.println(p.toString());
    //eu
}

Repare que eu só começo a obter este resultado após implementar o método toString() na classe Pessoa pois desta forma eu estou sobre-escrevendo (override) a implementação padrão (herdada da classe Object).
Answer: Você está imprimindo apenas a referência da memória... Isso acontece quando voce chama o objeto na página mas ele não tem um toString.
Voce tem duas opções
1- Criar um toString na classe Cliente
2- Chamar apenas o getCliente.getNome() na página, aconselho a usar essa segunda opção, a não ser que você necessite de todas as informações do cliente na tela.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Linear Programming: Three variable graphical solution

Question:
A small bank offers three type of loans: housing loans at $8.50$%
  interest, education loans at $13.75$% interest rates, and loans to
  senior citizens at $12.25$% interest. Further, it needs to adhere to
  certain policy restrictions. The restrictions require the bank to
  ensure that Condition 1: housing loans make up between $25$% and $60$% of
  the total loan amount disbursed;and Condition 2: the amount of loans
  disbursed to senior citizens should be least one third of  the total
  amount disbursed as loans. In a particular year, its lending capacity
  is $25,000,000\$$. The bank would like to disburse loans so as to
  maximize its earnings from the interest paid. Solve the problem
  graphically by taking two at a time.

From the problem, I derive the following LP model:
Decision variables:
$X_1:$ Amount disbursed as housing loan.
$X_2:$ Amount disbursed as education loan.
$X_3:$ Amount disbursed as loans to senior citizens.
Maximize $$0.085X_1 + 0.1375X_2 + 0.1225X_3$$
Subject to constraints:
$$X_1 \ge 625 \times 10^4$$
$$X_1 \le 150 \times 10^5$$
$$X_3 \ge \frac{25}{3} \times 10^6$$
where $X_1,X_2,X_3 \ge 0$
My question is: Is this formulation correct? and how to solve this three variable equations using graphical method. Precisely I don't understand "Solve the problem
 graphically by taking two at a time"
Answer: It looks sensible, except I think your constraints should be
$$
\begin{aligned}
X_1&\geq0.25(X_1+X_2+X_3) \\
X_1&\leq0.6(X_1+X_2+X_3) \\
X_3&\geq\frac{1}{3}(X_1+X_2+X_3) \\
X_1+X_2+X_3&\leq25000000 \\
X_1,X_2,X_3&\geq0
\end{aligned}
$$
Of course, at the optimal solution, the bank will lend all it can, but that is for the optimisation to take care of.
Comment: @Quixotic: Yes of course, I'll edit!
Comment: Hm, then we need  another constraint: $X_1 + X_2 + X_3 <= 25,000,000\$$


SQL Server 2008 R2 installation hangs

Question: On a freshly installed Windows Server 2008 R2 Standard SP1 I am installing SQL Server 2008 R2.
After configuring setup, install starts, but then it will hang on:
Install_sqlSupport_KatmaiRTM_Cpu64_Action: InstallFiles. Copying new files.
What happens here? Why does the installation hang?
Answer: As documented, SQL 2008 R2 requires at least .Net Framework 3.5 SP1 - the Windows Server-provided .Net 4.0 client profile is not sufficient.
Make sure you have installed the full framework, 3.5 SP1 or higher.
Comment: It is at times like these that you are reminded that SQL Server is entirely its own product, and acts differently than most other Microsoft swag.
Comment: Dang. And I read the message "needs .net and install thingies" at the start as "am going to install them if you click ok now".
Comment: Strange. .Net 3.5.1 already was installed as feature.
Comment: Can you include the relevant bits from the install summary file ?
Comment: Am working on it.
Comment: Long after canceling the setup it reported an timeout error while waiting for "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe" /noconfig /fullpaths @"C:\Users\sys-admin\AppData\Local\Temp\1\3i5ioqvl.cmdline". Is that due to me canceling setup?
Comment: Nyaaarrgrg, it seems my dvd has read errors :( #Damn
Answer: Same issue.  I had to verify .Net 3.5.1 was installed then Uninstall all Sql(Express) related programs and reboot.  Afterward, Re-install succeeded.  [it repeatedly failed until i uninstall Sql(Express)].

SQL Server 2008 R2 installation hangs


Difference between exponential fit and log-linear fit

Question: I have data with a clear exponential dependency. I tried to fit a curve through it with two different, very simple models.
The first one is a straight forward exponential fit. For the second one, I log transformed the y values and then used a linear regression.
To eventually plot the line, I raised my result to the power of e.
However, when plot both resulting regression lines, they look quite different. Also there r^2 value is quite different.
Can somebody explain to me why the fit is so different? I honestly thought the same curve should result from both models.

Below is the code that I used to generate the curves.
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
import math
from sklearn.metrics import r2_score

def exp(x, k):
    return np.exp(k * x)

def lin(x, m):
    return m * x

x = np.array([0.03553744809541667, 0.07393361944488888, 0.11713398354352941, 0.1574279442442857, 0.20574484316400002,
              0.24638269718399997, 0.28022173237600007, 0.33088392763600005, 0.37608523866, 0.4235348808,
              0.4698941935266667,
              0.5049780023645001, 0.53193232248, 0.59661874698, 0.64686695376, 0.6765964062965002, 0.7195010072795001,
              0.7624056082625001, 0.8053102092455002, 0.8696671107200001])

y = np.array([1.0, 0.9180040755624065, 0.7580780029008654, 0.662359339541471, 0.556415757973503, 0.4575163368602455,
              0.3982995279500034, 0.3309496816813175, 0.25142343840921577, 0.21526738042912116, 0.19490849614884595,
              0.12714651046365663, 0.12714651046365663, 0.1015770731180174, 0.0728982261567812, 0.04180399979351543,
              0.04180399979351543, 0.04180399979351543, 0.04180399979351543, 0.04180399979351543])

k_exp = curve_fit(exp, x, y)[0]
m_lin = curve_fit(lin, x, np.log(y))[0]
x_ticks = np.linspace(x.min(), x.max(), 100)

print("Exponential fit", r2_score(y, [exp(i, k_exp) for i in x])) #0.964
print("Log linear fit", r2_score(y, [np.exp(i * m_lin) for i in x])) #0.939

plt.scatter(x, y, c="k", s=5)
plt.plot(x_ticks, exp(x_ticks, k_exp), "r--", label="Exponential fit")
plt.plot(x_ticks, [np.exp(x * m_lin) for x in x_ticks], label="Log-linear fit")
plt.legend()

plt.show()

Answer: One is:
exp(k * x) + err = y

other is:
m * x + err = log(y)

or:
exp(m*x + err) = y

so as you can see, the distribution of errors is different, therefore fit will be different.
Comment: Thanks, this makes a lot of sense.
Is the equation how I calculate the goodness of fit (R^2) still right? Or do I have to adjust the way I calculate the expected y values
Comment: not sure about r^2 but for loglinear you have to correct expected values, but I don't remember how this correction was called
Answer: The minimizing problems of an exponential fit and a log-linear fit are a bit different. If you are fitting different things, you should also be prepared to obtain a different result.
In exponential fit, the differences
exp(k_exp, x) - y

array([-0.11232018, -0.13754469, -0.08285192, -0.07245726, -0.05473322,
       -0.01973325, -0.00746918, -0.00117105,  0.03198186,  0.02645663,
        0.01201946,  0.05681884,  0.04092329,  0.03372492,  0.04142677,
        0.06167547,  0.04781162,  0.03580521,  0.02540738,  0.01236329])

are minimized in least square sense
sum((exp(k_exp, x) - y)**2)

0.06488526426576267

In log-linear fit, the differences
m_lin * x - np.log(y)

array([-0.14034862, -0.20643379, -0.18563015, -0.20978567, -0.22631195,
       -0.19110049, -0.18613326, -0.20097633, -0.10466277, -0.13679878,
       -0.22053568,  0.06809742, -0.03835371, -0.06929866,  0.06400883,
        0.5026701 ,  0.33322626,  0.16378243, -0.00566141, -0.25982716])

are minimized in least square sense
sum((m_lin * x - np.log(y))**2)

0.8549505409763158

When looking the log-linear fit as though it would be exponential fit, the differences were
exp(m_lin, x) - y

array([-0.13094479, -0.17122601, -0.12843302, -0.12534621, -0.11269128,
       -0.07958516, -0.06764601, -0.06025541, -0.0249844 , -0.02752286,
       -0.03857453,  0.00895996, -0.00478421, -0.00680079,  0.0048187 ,
        0.02730342,  0.01653194,  0.00743936, -0.000236  , -0.00956539])

There are two differences

The log-linear fit shows higher sum of squares sum((exp(m_lin,x) - y)**2) = 0.11011945823779898 in a non-log-linear scale than the exponential fit (0.06488526426576267), and,
the errors exp(m_lin,x) - y of log-linear fit in non-log-linear scale are more far from zero with small values of x.

The values y
array([1.        , 0.91800408, 0.758078  , 0.66235934, 0.55641576,
       0.45751634, 0.39829953, 0.33094968, 0.25142344, 0.21526738,
       0.1949085 , 0.12714651, 0.12714651, 0.10157707, 0.07289823,
       0.041804  , 0.041804  , 0.041804  , 0.041804  , 0.041804  ])

are small in the whole range of x values, whereas values np.log(y)
array([ 0.        , -0.08555345, -0.27696899, -0.41194706, -0.5862395 ,
       -0.78194269, -0.92055097, -1.10578893, -1.38061676, -1.53587439,
       -1.63522508, -2.06241523, -2.06241523, -2.28693743, -2.61869097,
       -3.17476326, -3.17476326, -3.17476326, -3.17476326, -3.17476326])

are much higher in absolute sense for higher values of x
array([0.03553745, 0.07393362, 0.11713398, 0.15742794, 0.20574484,
       0.2463827 , 0.28022173, 0.33088393, 0.37608524, 0.42353488,
       0.46989419, 0.504978  , 0.53193232, 0.59661875, 0.64686695,
       0.67659641, 0.71950101, 0.76240561, 0.80531021, 0.86966711])

closer to value 1.
In this case, in exponential scale you are fitting on average remarkably smaller absolute values than in log-linear scale.


Finding the layers and layer sizes for each Docker image

Question: For research purposes I'm trying to crawl the public Docker registry ( https://registry.hub.docker.com/ ) and find out 1) how many layers an average image has and 2) the sizes of these layers to get an idea of the distribution.
However I studied the API and public libraries as well as the details on the github but I cant find any method to:

retrieve all the public repositories/images (even if those are thousands I still need a starting list to iterate through)
find all the layers of an image
find the size for a layer (so not an image but for the individual layer).

Can anyone help me find a way to retrieve this information?
EDIT: is anyone able to verify that searching for '*' in Docker registry is returning all the repositories and not just anything that mentions '*' anywhere? https://registry.hub.docker.com/search?q=\*
Comment: >>>find all the layers of an image , if you do not use the API, you can do a `docker history myimage` and you will see the size of each layer. More generally, on an image, you can do `docker history myimage | awk 'NR>1 {print $1}' | xargs docker inspect --format '{{ ((index .ContainerConfig.Cmd ) 0) }}'` to see what commands were issued to create the image
Comment: This is already a great help for step 2 although that requires me to download every image  through Docker to my local machine. I guess that is an option but only if I find a way to retrieve a list of 'myimages' to start with (e.g. every image in public registry in step 1). I'll definitely explore this option, thank you!
Comment: `https://registry.hub.docker.com/search?q=*` shows for me 87031 repositories,
Answer: Check out dive written in golang.

Awesome tool!
Comment: dive breaks on my 14Gb image
Answer: You can first find the image ID using:
$ docker images -a

Then find the image's layers and their sizes:
$ docker history --no-trunc <Image ID>

Note: I'm using Docker version 1.13.1
$ docker -v
Docker version 1.13.1, build 092cba3

Comment: +1 I had to remove the --no-trunc as the output was unusable on my terminal, but this still gives great info.
Comment: @SherwinF Alternatively, pipe it to `less -S`, or save it to a file and open it in a text editor, or any of various other things one can do to work with output that's too wide for the terminal (assuming that's what you mean by "unusable")
Answer: You can find the layers of the images in the folder /var/lib/docker/aufs/layers; provide if you configured for storage-driver as aufs (default option)
Example:
 docker ps -a
 CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
 0ca502fa6aae        ubuntu              "/bin/bash"         44 minutes ago      Exited (0) 44 seconds ago                       DockerTest

Now to view the layers of the containers that were created with the image "Ubuntu"; go to /var/lib/docker/aufs/layers directory and cat the file starts with the container ID (here it is 0ca502fa6aae*)
 root@viswesn-vm2:/var/lib/docker/aufs/layers# cat    0ca502fa6aaefc89f690736609b54b2f0fdebfe8452902ca383020e3b0d266f9-init
 d2a0ecffe6fa4ef3de9646a75cc629bbd9da7eead7f767cb810f9808d6b3ecb6
 29460ac934423a55802fcad24856827050697b4a9f33550bd93c82762fb6db8f
 b670fb0c7ecd3d2c401fbfd1fa4d7a872fbada0a4b8c2516d0be18911c6b25d6
 83e4dde6b9cfddf46b75a07ec8d65ad87a748b98cf27de7d5b3298c1f3455ae4

This will show the result of same by running
root@viswesn-vm2:/var/lib/docker/aufs/layers# docker history ubuntu
IMAGE               CREATED             CREATED BY                                         SIZE                COMMENT
d2a0ecffe6fa        13 days ago         /bin/sh -c #(nop) CMD ["/bin/bash"]             0 B
29460ac93442        13 days ago         /bin/sh -c sed -i 's/^#\s*\   (deb.*universe\)$/   1.895 kB
b670fb0c7ecd        13 days ago         /bin/sh -c echo '#!/bin/sh' > /usr/sbin/polic   194.5 kB
83e4dde6b9cf        13 days ago         /bin/sh -c #(nop) ADD file:c8f078961a543cdefa   188.2 MB

To view the full layer ID; run with --no-trunc option as part of history command.
docker history --no-trunc ubuntu

Comment: Since Docker version 1.10, with introduction of the content addressable storage, images and layers are now separated. `docker history` command no longer tells the actual layer disk storage information on the docker host. Check this [blog](http://windsock.io/explaining-docker-image-ids/)
Comment: This is no longer the case with docker version 1.10 onwards. `docker history` command won't give the image layers as shown in the /var/lib/docker/aufs/layers folder. Read the update [here](https://docs.docker.com/engine/userguide/storagedriver/imagesandcontainers/#copying-makes-containers-efficient).
Answer: In my opinion, docker history <image> is sufficient. This returns the size of each layer:
$ docker history jenkinsci-jnlp-slave:2019-1-9c
IMAGE        CREATED    CREATED BY                                    SIZE  COMMENT
93f48953d298 42 min ago /bin/sh -c #(nop)  USER jenkins               0B
6305b07d4650 42 min ago /bin/sh -c chown jenkins:jenkins -R /home/je… 1.45GB

Answer: This will inspect the docker image and print the layers:
$ docker image inspect nginx -f '{{.RootFS.Layers}}'
[sha256:d626a8ad97a1f9c1f2c4db3814751ada64f60aed927764a3f994fcd88363b659 sha256:82b81d779f8352b20e52295afc6d0eab7e61c0ec7af96d85b8cda7800285d97d sha256:7ab428981537aa7d0c79bc1acbf208c71e57d9678f7deca4267cc03fba26b9c8]

Answer: They have a very good answer here:
https://stackoverflow.com/a/32455275/165865
Just run below images:
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock nate/dockviz images -t

Comment: Hi @bummi , sorry I think this question initially is looking for solution in docker registry, and i found that solution we provided above direct to the layers of docker image. so I try to supplement another solution (which i think easier)
Answer:
https://hub.docker.com/search?q=* shows all the images in the entire Docker hub, it's not possible to get this via the search command as it doesnt accept wildcards.
As of v1.10 you can find all the layers in an image by pulling it and using these commands:
docker pull ubuntu
ID=$(sudo docker inspect -f {{.Id}} ubuntu)
jq .rootfs.diff_ids /var/lib/docker/image/aufs/imagedb/content/$(echo $ID|tr ':' '/')

3) The size can be found in /var/lib/docker/image/aufs/layerdb/sha256/{LAYERID}/size although LAYERID != the diff_ids found with the previous command. For this you need to look at /var/lib/docker/image/aufs/layerdb/sha256/{LAYERID}/diff and compare with the previous command output to properly match the correct diff_id and size.
Comment: docker inspect imagename | jq .[].RootFS.Layers" is much simpler way to do 2)
Comment: RE1) Did not work for me seems to redirect to hub.docker.com.
Answer: It's indeed doable to query the manifest or blob info from docker registry server without pulling the image to local disk.
You can refer to the Registry v2 API to fetch the manifest of image.
GET /v2/<name>/manifests/<reference>

Note, you have to handle different manifest version. For v2 you can directly get the size of layer and digest of blob. For v1 manifest, you can HEAD the blob download url to get the actual layer size.
There is a simple script for handling above cases that will be continuously maintained.
Answer: To find all the layers of an image and to find the size for a layer, you can display the manifest from the docker hub registry via the "manifest" experimental feature:
docker manifest inspect ubuntu

The result is a JSON file (only the first lines are shown here):
{
   "schemaVersion": 2,
   "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
   "manifests": [
      {
         "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
         "size": 529,
         "digest": "sha256:10cbddb6cf8568f56584ccb6c866203e68ab8e621bb87038e254f6f27f955bbe",
         "platform": {
            "architecture": "amd64",
            "os": "linux"
         }
      },
      {
         "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
         "size": 529,
         "digest": "sha256:dd375524d7eda25a69f9f9790cd3e28855be7908e04162360dd462794035ebf7",
         "platform": {
            "architecture": "arm",
            "os": "linux",
            "variant": "v7"

Answer: one more tool : https://github.com/CenturyLinkLabs/dockerfile-from-image
GUI using ImageLayers.io
Comment: This currently gives a stack trace.
Answer: Not exactly the original question but to find the sum total of all the images without double-counting shared layers, the following is useful (ubuntu 18):
sudo du -h -d1  /var/lib/docker/overlay2 | sort -h

Answer: I've solved this problem by using the search function on Docker's website where '*' is a valid search that returns 200k repositories and then I crawled each invididual page. HTML parsing allows me to extract all the image names on each page.


Redirect loop in full site to mobile site using session

Question: I have a full site that has been in OS-commerce and mobile site is in core PHP (codeignitor), and full version and  a mobile version on sub-domain.
e.g  full site: www.example.com  and mobile site domain is  m.example.com. when user open full site domain in mobile, then website redirect proper mobile domain, But if mobile user want to view full site then user can view fullsite in mobile.
I have used this to complete the redirect http://code.google.com/p/php-mobile-detect/,  But it is not redirecting to the full site or to the mobile site using session. I know that I have to use PHP SESSIONS and REQUEST in order to get this to work but I am not sure how to use them in this instance, so could you please suggest how to solve this redirecting issue using session?
Here my code is:
session_start();

  include('includes/Mobile_Detect.php');
  $detect = new Mobile_Detect;

 if(isset($_REQUEST['fullsite']) && $_REQUEST['fullsite'] == 'yes')
 {//check if fullsite view request from mobile or website?

    $_SESSION['fullsite']="yes";

    if($detect->isMobile()) {
               $_SESSION['website']="mobile";
    }
    else{
       $_SESSION['website']="computer";
    }

    $deviceType = header('Location: https://www.example.com/');
  }
  else
  {
    if($_SESSION['website'] =="mobile"  && $_SESSION['fullsite'] !="yes")
    {
        if($detect->isTablet())
        {
            $deviceType = 'tablet';
        }
        else
        {
            $deviceType = 'phone';
        }

        $deviceType = header('Location: https://m.example.com/');
    }
    elseif($_SESSION['website'] =="computer" && $_SESSION['fullsite'] =="yes")
    {
        $deviceType = 'computer';
        $deviceType = header('Location: https://www.example.com/');
    }
    else{
        $deviceType = 'computer';
     }

    $scriptVersion = $detect->getScriptVersion();
    session_destroy();
  }

Answer: From what I could get from github page you should be able to make it work like this:
index.php
session_start();

if ($_GET['fullscreen'] == 'yes') {
    $_SESSION['fullscreen'] = 1;
} else if ($_GET['fullscreen'] == 'no') {
    $_SESSION['fullscreen'] = 0;
}

if (false == isset($_SESSION['fullscreen']) && ($_SESSION['fullscreen'] == 0)) {
    // If session['fullscreen'] has not been set (maybe first visit
    // or the user does not what in fullscree
    // check the device and do redirect
    require_once 'Mobile_Detect.php';
    $detect = new Mobile_Detect();

    // Any mobile device (phones or tablets).
    if ( $detect->isMobile() ) {

    }
    ...
}

// Other code here

When visiting from mobile, if the user wants the full version, provide an anchor to url with GET parameter fullscreen=yes (http://example.com?fullscreen=yes)
If on full site and detect mobile (not included in code above), you could provide a link to mobile version with fullscreen=no


Install only dblink module from postgresql-contrib package in centOS

Question: I would like to install only the dblink module from postgresql-contrib package. I use the command as below
zypper install postgres-contrib
But it installs everything. Is there a way to install a specific module.
Answer: There is no reasonable way to install just a part of an RPM package. Is there any specific reason to do so? The contrib package isn't that large and the modules aren't used unless you want to use them.


Armazenar valor de uma função em um scaffold

Question: Eu possuo um código em Rails com um input que carrega arquivos e um botão que coleta o nome do arquivo selecionado através do input:

<%= file_field_tag 'file' %>

<button onclick="myFunction()">Salvar nome do arquivo</button>

Sim eu misturei Html com código Ruby, mas eu não sei como é um label em código Ruby.
Esse é meu código JS, mas só a parte da coleta do nome, que é a que importa no momento:
function myFunction() {
  var x = document.getElementById('file').files[0].name;
  alert(x);
}

Como eu poderia pegar o valor dessa função e armazena-la em meu scaffold?
Meu scaffold (que eu gostaria de armazena-lo):

<%= notice %>

Histórico

      Arquivos validados:

    <% @historicos.each do |historico| %>

        ##ss<%= link_to 'Show', historico %>

    <% end %>

<%= link_to 'Voltar', root_path %>

Sim, eu removi a box para digitar os textos até por que os nomes seriam obtidos através da minha função então eu não via motivo de possui-los eu tbm removi os links para as outras views(show, delete e edit).
Agradeço desde já!!!
Answer: Quando você diz que quer salvar no seu scaffold, você quer dizer no banco de dados? Ou apenas exibir na página onde o arquivo é selecionado?
Se for para exibição, você pode usar Javascript para atribuir o resultado de document.getElementById('file').files[0].name; em algum elemento do DOM. Dá para fazer isso dentro dessa função que você criou:
function myFunction() {
  var fileName = document.getElementById('file').files[0].name;
  document.getElementById('#file-name').value = fileName;
}

Se for para salvar no banco de dados, supondo que o file_field_tag esteja dentro de um form, você tem acesso aos dados do arquivo no controller. Nesse caso, sua página feita via scaffold teria acesso ao dado direto da instância historico.
Os dois códigos estão em páginas diferentes?


Namesake of Cantor's diagonal argument

Question: There are two results famously associated with Cantor's celebrated diagonal argument. The first is the proof that the reals are uncountable.

This clearly illustrates the namesake of the diagonal argument in this case. However, I am told that the proof of Cantor's theorem also involves a diagonal argument. Given a set $S$, suppose there exists a bijection $f:S\longrightarrow\ P(S)$ from $S$ to its powerset. The construction of the set
$$B=\{b\in S\mid b\notin f(b)\}$$
is said to be a diagonal argument due to the dual occurrence of $b$ in $b\notin f(b)$. Now I am not exactly sure why this is called a diagonal argument. Is there a geometric representation of this argument like the picture above? Or is it simply an analogy to the first proof using the idea of constructing a witness to show $f$ is not surjective?
Comment: Generally **namesake** denotes the name of a person that something is named after.  Since we are not talking about a Mr. Diagonal here, that is not the right word.
Comment: Well, if $S=\mathbb N$ and if you associate to each subset the corresponding sequences of 0's and 1's - see e.g. [here](http://math.stackexchange.com/questions/84180/finding-a-correspondence-between-two-sets) - you will get pretty much the same picture as above.
Answer: Diagonalization is a common method in mathematics. Essentially it means "write it in an infinite matrix and then walk along a coordinate line which approaches infinity on both axes".
The "Cantor diagonal argument" says write the numbers in a matrix, and take the $n$-th number's $n$-th digit, and change it.
The Cantor theorem is a form of diagonalization because what you actually do is write the function in matrix form:
$$\begin{array}{|c|c|c|c|c}
&x_1 & x_2 & x_3 & \ldots\\ \hline
f(x_1)\\ \hline
f(x_2)\\ \hline
f(x_3)\\ \hline
\vdots
\end{array}$$
Now we write $1$ into the blank cells if $x_i\in f(x_j)$, and $0$ otherwise. The proof takes the set of all $x\in X$ such that $x\notin f(x)$, That is walk along the diagonal and take the coordinates which give $0$. This defines a subset of $X$ which is not in the range of $f$, much like the diagonal argument gives a number which is not in the enumeration.

Similar, but different arguments are given when showing the real numbers can be defined as Cauchy sequences of rationals up to some equivalence, and that this is a complete space. We take a Cauchy sequence of Cauchy sequences and we take the $k$-th element of the $k$-th sequence.
Of course this is not exactly what we do, but it is close enough. We need to toy with $\epsilon-\delta$ and define the diagonal we are going to walk on (for the $k$-th element we want to take some $x^k_j$ for $j$ large enough so and so...)
Answer: HINT $\ $ To see the analogy, represent subsets by bit-vectors, so the i'th element of the vector is $1$ if the i'th element is in the subset, and 0 if not. Then the rows of the matrix are the bit-vectors of the subsets, and said powerset diagonalization corresponds simply to complementing the diagonal bits in the bit-matrix.
Ignoring ordering, it boils down to the very simple fact that when we have at least as many "components" (indexes) as "objects" (vectors) then we can always construct a different object simply by making sure that it differs from each object in at least one component. Introducing an ordering simply provides a vivid way to visualize this construction, by placing the changed components along the diagonal.
Answer: If the first 'diagonalization' you exhibited is over the alphabet $\{0,1\}$ and $S=\mathbb{N}$ in the second 'diagonalization', then the arguments are the same. To see this, note that every real number in $[0,1]$ corresponds to a set of natural numbers when viewed as a characteristic function of that set. The (characteristic function of the) set $B$ is then exactly the new real number generated in the first diagonal argument. You should work the details out yourself.
Answer: The proof of the first result you give mentions
the 1st digit of the 1st number, and
the 2nd digit of the 2nd number, and
the 3rd digit of the 3rd number, and
the 4th ditit of the 4th number, and
........ etc.  You see the "dual occurrence" of something here.  You also see that the first digit of the first number is not the same as the first digit of the number you're constructing, and the second digit of the second number is not the same as the second digit of the number you're constructing and so on.  The same thing happens with the second proof.

Namesake of Cantor's diagonal argument


TFS API for team capacity work details

Question: I'd like to retrieve the team capacity work details (the right area of the team capacity web page) using the TFS REST API.
Can this be achieved?
I tried to use the "Get a team's capacity" API but it returns only the days off and the capacity per day for the team members.
Answer: If you are meaning the work details such as below picture

There is no REST API or Client API will directly return such things. If you have got remaining work days. According to the returned team members days off and capacity per day. You should be able to  calculate the values.

TFS API for team capacity work details


How do I programmatically add a product reference to a commerce product node?

Question: I am trying add a commerce product to a node when a person fills out a content node. I am generating the product, but can't add it back to the node.
When I try to add the data to the node, there is no product reference field data when Do not show a widget is selected in the content type > Manage fields.
Do not show a widget seems to remove the field from the node completely.
If I try to load in hook_node_presave():
<code>$product = commerce_product_load_by_sku($sku);

$field_studio_pass_product = array(
  LANGUAGE_NONE => array(
    0 => array(
      'product_id' => $product->product_id,
    )
  )
);

$node->field_studio_pass_product = $field_studio_pass_product;
</code>
It won't work since there is no current field. I don't want to show the field to editor as they can't change it.
Further. This above code does work if the product field has a widget, or the ideal code:
<code>$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_studio_pass_product->set($product->product_id);
</code>
Again, if you set the field type to Do not show a widget there is no property on the node object, and as a result no ability to add a value.
Answer: Your issue isn't that there wasn't a field available in the data model to edit but that you used the wrong array structure for the product reference. Instead of the "value" key you should've been using "product_id".
I highly recommend against directly inserting field data like your answer proposes. The Entity / Field APIs should be allowed to perform their full jobs on this data when it's entered. For example, in your case you didn't put the necessary data into the field data revision table at the same time.
Comment: Agreed with concept, answer doesn't work though. There is no field_studio_pass_product property of the node array. This means that I can't add it. See http://drupal.stackexchange.com/questions/12290/how-to-update-a-field-value-for-a-node for updating a node field - it is normally 'value'. If a stdClass does not have a property the only way I know to add properties is to cast to array and back - another hack. I tried a few other  such as altering the field to make it hidden.
Comment: Yes. If you use entity_metadata_wrapper you get an array that has field_studio_pass_product['und'][0]['product_id'] = 56. Doesn't make it work under the 'no widget' scenario.
Comment: Could be the order of base entity vs. field hook invocation then. If you're just going to make direct queries on node insert you may as well actually update / save the entity itself.
Answer: The following 'nice answer' works
<code>$node_wrapped = entity_metadata_wrapper('node', $node);
$node_wrapped->field_studio_pass_product = $product->product_id;
field_attach_update('node', $node);
</code>


Is self-calling functions in Javascript harmful?

Question: I have a Javascript function that is calling itself for purpose of refreshing notification bar. My function is like:
function refreshLoop() {
      refresh();
      setTimeout("refreshLoop();", 10000);
}

My question is that if I use that function like this, will be there any harm -programming error-. I am asking this question because you see refreshLoop() function never ends.
Should I use it like this or do you have any other ideas?
Thanks
Comment: That's not recursive.
Comment: For this specific case, you can use `setInterval()`.
Comment: Also, this indeed isn't recursion. `setTimeout()` means the function should be called on the browser page's *event loop* in 10 seconds. For that to happen, the current event that sets the timeout must necessarily finish executing.
Comment: No, this is not harmful. This is perfectly fine.
Comment: If the OP switches to setInterval() the calling pattern will need to change as well so that it calls refresh not refreshLoop.
Answer: This construct is frequent and fine (especially if a conditional call of setTimeout makes it hard to use setInterval), but it's not written as you did. Don't eval code when you can directly pass the function. Use this :
function refreshLoop() {
      refresh();
      setTimeout(refreshLoop, 10000);
}

Answer: You can end the timeout loop by removing the timeout like that:
var timeout;

function refreshLoop() {
  refresh();
  timeout = setTimeout(refreshLoop, 1000);
}

refreshLoop()

// later on
clearTimeout(timeout)

Answer: I don't see anything wrong with it, but you could lose the eval "refreshLoop();"
function refreshLoop() {
  refresh();
  setTimeout(refreshLoop, 10000);
}

Comment: Why write a second identical answer ?
Comment: Cuz. **R.E.P.** @dystroy
Comment: There was no answer when I started writing my answer.  I'll be sure to check new answer alert next time.


Simple understanding of Convolutional Neutral Network

Question: I want to ask a basic understanding of CNN.
Let say I have 1 dataset (100 pictures) with

Class A (Picture of Cat: 40 pictures)
Class B (Picture of Dog: 60 pictures)

And then, I input 100 pictures into CNN and run it.
My question is:

What is the output should I look at?
Is that mean if I input a picture (either Cat and Dog), I can know the picture (is cat or is a dog) by looking at the output?

Thank you.
Comment: What do you understand now? Do you understand logistic regression? (If not, do you understand linear regression?)
Comment: @Dave, logistic regression is not similar. This is CNN
Comment: Logistic regression is extremely similar. In fact, a logistic regression is a neural network with no hidden layers. Now do you understand logistic regression?
Comment: @Dave, yes, I did learn logistic regression. So both work similar, just CNN with hidden layer.
Comment: Let's look at how it would work for logistic regression. Transform your pictures into vectors you input into the logistic regression model, perhaps just by flattening the image. (How you so this doesn't matter for the example.) What is your answer to #1? What is your answer to #2?
Answer: The classifier would not necessarily be a logistic regression(it would be an SVM or some other classifiers), but it would be simpler to illustrate the issue using just logistic regression.

What is the output should I look at?

I thought you mean logistic regression. The output would just be a float between 0 to 1 or two floats complementing each other(we use this type here, but they are equivalent) and adding up to 1. You can refer to this answer. You can see from the picture below that the blue and red nodes form a binomial logistic regression model.

Is that mean if I input a picture (either Cat and Dog), I can know the picture (is cat or is a dog) by looking at the output?

Yes. The CNN or any other encoders is just for extracting features. The last layer of a CNN is just like the input of the logistic regression.
The fully connected layer depicted below is what I mean the last layer of the CNN, and the output as depicted is what you want. In your case, there would be just 2 floats(each red node is a float number). Each red node stands for a class and they add up to 1 and you choose the one with the biggest number. In your case, if 0 indexed node represents cats and 1 indexed node represents dogs(you train it to do that with such labels) and node 1 is bigger than node 0(in the inference mode) we can say that the input of the model would be a dog.

A simple and typical CNN binary classifier.
Hope this removes your doubts.
Answer: The basic intuition of a CNN is that it is a modified neural network which uses a trick of parameter sharing to capture more abstract patterns in the images which are then used to classify different classes like dog and cat in your case. So, the purpose of a CNN architecture is feature extraction in an efficient way. Each layer in CNN captures different abstract patterns which add to the overall differentiability among the classes. These extract features can be then fed to a fully connected layer which acts as a classifier and finally classified using a sigmoid(binary classification) or softmax function(multi-class) which produces in terms of probabilities.

You should look at which class has maximum probability in the output layer. Ex. if your output layer has .2 for cat and .8 for dog, then final output of your model is a dog.
If you feed an image of a cat in input layer and your output layer produces .95 probability for cat label in output layer then you can know your output is a cat.
Comment: Does the output of `sigmoid` and `softmax` the same?
Comment: thanks. Does `sigmoid(binary classification)` only for `classify 2 classes, e.g. Cat and Dog` and `softmax function(multi-class) for `classify more than 2 classes, e.g. Cat, Dog, Bird`?
Comment: Yes, that's right.
Comment: @Viviek, thanks. do you have any resource for such implementation using Matlab?
Comment: @aan, You can checkout this gitgub repo : https://github.com/xuzhenqi/cnn for matlab implementation.
Comment: it is difficult to run/unable to run the code after I download the code from github. Not sure what is the problem, but couldn't see any clue there
Comment: I have not used MATLAB before so can't really help you with that. You can explore mathworks for matlab implementations.
Comment: thanks for your reply. How about Python?
Comment: There are tons of implementations online for CNN in python. Take a look at this and try to implement yourself: https://towardsdatascience.com/building-a-convolutional-neural-network-cnn-in-keras-329fbbadc5f5


How many ways can comments be added in a C program?

Question: When I was solving a problem from the famous KR book to remove comments from a c program I have searched over the internet to know all the possible cases where comments can be inserted in a C program and didn't find any complete answer of this question. So here I am adding the answer to this question. feedback is welcomed.
Comment: Here are at least 3 `//`, `/* */`, `#if 0  #endif`
Comment: When that old book was written, `//` didn't exist...
Answer: How many ways are there to insert comments in a C program?

When a single line comment symbol is inserted anywhere in a line everything that appears before a newline is part of the comment.
Any type of comment symbol can appear inside a double-quoted string — so single-line and multi-line comment symbols appearing inside double quotes are not a comment; they are normal text.
Multi-line comments can be placed anywhere in the source code where you can put a blank.
In C, comments cannot be nested. Inserting a multi-line comment start symbol inside another multiple line comment will truncate the parts of comments that come after the first comment terminating symbol. Check the example of #4 to understand clearly.

<code>#include <stdio.h>
#define TABSIZE /*false comment*/ 8

// this is a demo program. /* comment here */           XD example of #1

int main()
{
    printf("#1  :- /* multiple */ and // single \n"); // example of #2

    char str[40] = "/* multiple */ and // single"; // example of #2
    printf("#2  :- %s\n", str);

    char one /* example of #3 */ = 'x'; // example of #3
    char two /* example of #3 */ = 'y'; // example of #3
    printf("#3  :- %c and %c\n", one, two);

    return /*example of #3 */ 0; // example of #3

    /*(start1) this is a comment /*(start2) trying to-      -- example of #4
     insert an nested comment here */
    //  (e2) this part is not considered as comment */(e1).
    //  so to successfully run the program this part of the
    //  comment  is handled by single line comment symbol '//'.
    //  remove all the '//' to see what happens.
}
</code>
Comment: Note that `int c1 = '/*'; int c2 = '*/'; int c3 = '//';` also contains no comments.  Multi-character integer constants are allowed, but have implementation-defined values (See C11 [§126.96.36.199 Character constants](http://port70.net/~nsz/c/c11/n1570.html#22.214.171.124), especially ¶10.)
Comment: Note that line-splicing occurs before comment elimination (see C11 [§18.104.22.168 Phases of translation](http://port70.net/~nsz/c/c11/n1570.html#220.127.116.11) — phase 2 is line splicing; phase 3 is comment elimination).  That means that a `//` comment can be continued onto the next line by ending the line with a backslash. and this can be repeated for multiple lines.  Also, comment symbols can be split over newlines by using one or more backslash-newline character pairs to separate the first character from the second.  However, that's more recondite than you're likely to have to deal with.
Comment: I don't understand your `//` comments after the attempt at nesting comments (number 4).  The `/* … */` comment ends at the first `*/`, regardless of the appearance of `/*` within the comment.  The material in the `//` comments won't compile unless you define an astonishing number of object-like macros, and the `*/` still prevents it compiling (because `*/` isn't a valid character sequence in C code except after the start of an unclosed `/*` comment).
Comment: Also, the `/* false comment */` in the `#define` directive looks like a true (valid) comment to me.


How report Standar error of measurement (SEM)?

Question: How report standard error of measurement (SEM)? Always with "±" due is a range?
Answer: The standard error of the mean, SEM, should be reported in a manner that makes it clear to the reader. Given that the ± thing can be applied to SEM, SD, interval bounds, and maybe other things, it is not sufficient to just report ±SEM. You do not need to always use the ± symbol. Different disciplines and different journals have different preferred styles, so you could check the style guide of a relevant journal. If in doubt, you should specify explicitly what the variability number represents.
SEM is not the "standard error of measurement". The 'mean' in its name is important because the SEM is an estimation from the data of the standard deviation of (theoretical) means from the sample size used repeatedly drawn from the same population as the original sample.
Comment: https://www.statisticshowto.com/standard-error-of-measurement/
Comment: https://us.humankinetics.com/blogs/excerpt/standard-error-of-measurement
Comment: https://www.researchgate.net/publication/327273189_Standard_Error_of_Measurement
Comment: In response to your links (only one that I clicked: if you can't b e botherred writing words then I don't see why a reader would be bothered reading them!) I will say that even if 'standard error of measurement' is a thing, the advice on how to present it is the same.
Comment: Of course that standar error of the measurement it´s a thing...there is lot of papers about it. Links are information about.


How to distribute private office add-ins?

Question: We have a small excel app to complement our SaaS product. Standalone it's useless and because of that I have big problems getting it into the office app store. And actually it doesn't make any sense there, it's just for our users. But how else can users install this app easily?
It's written using HTML and JS with the Office.js library, so the app itself is basically just an xml manifest file pointing to a static url. There is documentation how to sideload an add in for testing:

https://dev.office.com/docs/add-ins/testing/create-a-network-shared-folder-catalog-for-task-pane-and-content-add-ins
https://dev.office.com/docs/add-ins/testing/sideload-office-add-ins-for-testing
https://dev.office.com/docs/add-ins/testing/sideload-an-office-add-in-on-ipad-and-mac

Most of our users have a windows pc with excel installed locally. And creating a shared folder, .... is way beyond their capabilities. I hoped that I could somehow configure nginx as webdav or similar to add it to excel as a trusted catalog url, however I didn't find any documentation stating what this catalog url can be, except a network share.
Regarding mac and iPad, I'm even more puzzled. I could provide them with a simple script / app they'd need to execute in order to get the manifest copied to the right location.
But I guess what I'm really wondering, isn't there any "official" way to distribute an office add on which is only interesting for a few people - who are NOT in your organisation - keep in mind, there is no common share point server. And if there isn't what is the friendliest way for the user you'd suggest?
Update:
To make it maybe easier to grasp - the application is called WebBSC and basically makes it easier to perform some tasks, which usually used to be done in Excel before. But since all of our customers have the original data in excel, we created an add in for importing these data (this might not be just one time, but can also be periodically on a monthly basis) - This is why the add-in doesn't really make sense in the store, on the other hand we don't share any Office365 or Sharepoint / exchange account with our customers, it's just a simple SaaS app.
Comment: Hi Peter, I have exact same problem. Can you let me know how did you manage to resolve this issue? I cannot ask users to create shared folder, as it requires admin access . I also tried to place manifest.xml file on one of our web servers and tried to paste that path under catalog url with trusted center settings, but addin doesn't show up.
Answer: Eric is partially correct:  just 6 months ago, side-loading and private SharePoint catalogs would have been the only way.
However, there is a new "Office 365 Admin Center" that makes it much easier to deploy internal add-ins, and does not require SharePoint.  Please see
https://support.office.com/en-us/article/Deploy-Office-Add-ins-in-the-Office-365-Admin-Center-737e8c86-be63-44d7-bf02-492fa7cd9c3f
Comment: Peter, thanks for the clarification. This is somewhat of a known gap in the platform to date – we have good public distribution through the Store, and good internal distribution through this new Office 365 Admin Center.  But to be admittedly don't have a great solution to something that's in the middle ground. Folks are aware of it for the longer term, but for your purposes, I think your best bet is still the Store. The store is OK with having add-ins that are meant only for specific audience. Just make sure to give the store a test account when you submit, so they can see the add-in in action
Comment: @FedericoTomassetti, I have since moved on to a different team within Microsoft.  I recommend re-asking the question as a separate StackOverflow thread, so that the request bubbles up to folks on the product team.
Comment: Thx for the link, unfortunately I don't think it helps us, since we want to distribute the add-in to our customers with whom we don't share any other common accounts including office 365 - maybe I missed something, but I didn't find in the documentation how people outside of your organisation would be able to install it. - I've updated the question with more specific info - thx
Comment: Michael, we also would love the ability to publish to a specific audience (multiple companies) where internal distribution is not possible.  How can we publish to Office Store, but limit access (not appear in public store listing)?
Comment: @MichaelZlatkovsky-Microsoft Does the "Office 365 Admin Center" work when a company uses a BYOD model?
Comment: @MichaelZlatkovsky-Microsoft years later there is still no solution to this problem? We build tools for companies and we would like to offer some of them as office add-in, but it seems that you do not support that in a reasonable way
Comment: @MichaelZlatkovsky-Microsoft I can hardly find any information on this. Also facing the same problem of offering a self hosted Office web add-in. If I understand the documentation correctly, the add-in runtime ,api limitations and SSL should provide some sense of security for global admins to consent? I am speaking from a customer standpoint where they are only familiar with codesigned native add-ins and marking as trusted.
Answer: Unfortunately side-loading or using a private catalog are the only methods available for loading an add-in that's not published in the Office Store.
Add-in's can also be sideloaded in Mac and iPad, see https://dev.office.com/docs/add-ins/testing/sideload-an-office-add-in-on-ipad-and-mac.


Why does Hadamard claim that Pascal could have discovered non-Euclidean geometry

Question: In The psychology of invention in the mathematical field, p. 53, Hadamard makes the following claim:

Is his point that there must, in any axiomatic theory, be undefined terms, and if you write the parallel postulate entirely expanded, i.e., with definiens substituted for definiendum , then you will see that its not a truth of logic? But that seems completely off. You may still "see" that its a truth for perceptual space (let us grant, for the sake of the argument), and moreover, you may still fail to see that it isn't implied by the other axioms+logic. Thus, while you may arguably conceive of the possiblity of non-Euclidean axiom systems, you might still not yet perceive that of non-Euclidean geometries (qua sciences of space); and in fact, without a proof of relative consistency of these systems, e.g. by an inner model in Euclidean geometry, or by a model in R, you aren't technically allowed to even assume so much as the possibility of these systems, since (lacking such proof), the PP might -- for all you know -- after all be a consequence of the other axioms.
Am I completely misunderstanding Hadamard's point here?
Comment: This question should be asked on [History of Science and Mathematics](https://hsm.stackexchange.com/)
Comment: My guess is that he meant that Pascal could have discovered Hilbert's notion of formal axiomatic systems, whose truth is independent of their correspondence with our physical world. But this is a guess only.
Comment: A formal statement involving primitive notions would be it true meaning.
Comment: I do not think he claims that Pascal could have discovered non-Euclidean geometry.
Comment: But what do you think his claim is, then?
Comment: This is also my guess (I literally this second added it as an edit to this version https://hsm.stackexchange.com/questions/13044/why-does-hadamard-claim-that-pascal-could-have-discovered-non-euclidean-geometry), but then what's the business with "the true meaning" of Euclid's postulate?
Comment: Hm. That's an interesting point. So it would be regarded as expressing a structural feature of all its possible interpretations, rather than (exclusively) one of perceptual or physical space? Or what is the meaning of the primitives? If they are still interpreted uniquely as refering to perceptual/physical space, then that meaning is precisely the same that Euclid had in mind. So Pascal ought to have anticipated a modern type of semantic theory, is that it?
Comment: @10012511: I would not go as far as saying "ought" but "could." However, this is just my reading of a single Hadamard's sentence and it would not surprise me if there were other options.
Comment: I think yours is an interesting interpretation, but I agree that this passage offers more than one. It is the only thing he says about this subject in this book, btw, before and after the paragraph I quoted he discusses other points.
Answer:
Why, according to Hadamard, Pascal could have discovered non-Euclidean geometry?

Let start from Euclid's definition:

Definition 23 Parallel straight lines are straight lines which, being in the same plane and being produced indefinitely in both directions, do not meet one another in either direction.

The issue is not about substitution of definiens in place of definiendum in the statement of the postulate.
The original text of Euclid's Postulate 5 does not use the definiendum "parallel lines" but refers to the "meeting condition" of the definies:

Postulate 5. That, if a straight line falling on two straight lines makes the interior angles on the same side less than two right angles, the two straight lines, if produced indefinitely, meet on that side on which are the angles less than the two right angles.

The issue is to note that in Post.5 Euclid uses a property of lines: to meet that is not mentioned in any other postulates.
Thus, we cannot derive anything about "lines meeting" from them.
Obviously, it is not easy at all to note this fact: the modern concept of model (the intuitive one) dates from late XIX Century and was very far away from Ancient and Early Modern mathematics.
Hilbert's proof is a mathematical proof, and not an intuition (made with hindsight).
The question posed by Hadamard can be rewritten as: can Pascal have had that intuition without a development of mathematics comparable to that of Hilbert?
Comment: That is a really great point, thank you! But is it really that easy to see that the PP is not derivable from the other axioms (or axioms equivalent to them) in this way? Why then did Hilbert go to such lengths in Grundlagen to prove its independence? Certainly, there are axioms missing in Euclid's presentation (or rather, implicitly presupposed), e.g., ensuring that a line cutting a circle must intersect it, which, when supplemented, would undermine your interpretation? What Pascal could have seen from his principles is that the axioms are incomplete, not that PP is independent, right?
Comment: Also, thanks for correcting my sloppy latin :)


Is it possible to use rules to set user profile pictures?

Question: I would like to use the rules module's Set a data value action to set a user's profile picture whenever that user uploads an image of an "image" content type that I have created.
However, the user profile picture does not appear as an option in the data selector for site:current user.  Is there another way to set the user profile picture using rules or am I out of luck?
Answer: Create a componnent in rule with this ! On the componnent you have 2 parameters. One for the user and another one for the file you want to use ! I use Drupal 7.
<code>$uid = $user->uid;
$account = user_load($uid);
$thefile = file_load($file->fid);

$edit['picture'] = $thefile;
user_save($account, $edit);
</code>
Call the componnent from the rules you want. On my side i'm using a flag to trig the rules. The user mark an image to use it has a profile picture and it work.
I use this link has a starter to create the rule. http://taggartjensen.com/code-snip/drupal-7-set-user-picture-programmatically
Good luck !
Comment: The link is rotten. May you update it?
Answer: Another solution is to use the User Picture Field module. This module allows you add an image field to user, and show it on user register form, after user register an account, this module will use the fid that upload by image field as user picture's fid.
The benefit of this approach is that you can manipulate the new field like other fields (you can't do that with the default "picture" field.)
This new field, which replaces the default field, then appears in most data selector lists that involve nodes.
Easy to use, requires no programming.
Answer: You will need to do some programming, enabling the php filter for a php action, get the uploaded file path, load the user, then create a new file, update the user picture file column , assign the picture on file_usage to the user


Show that if $P : V \to V$ is a linear map such that $P^2 = P$, then $V = \ker P + \text{im } P$

Question: Please note that this is not a duplicate and is related to the finite-dimensional case (right now I've just started learning the subject from Serge Lang's Linear Algebra). I just have a question specific to my approach, which is as follows:
Let $v_1 \in V$ be a non-zero vector such that $P(v_1) = v_2 \neq 0$. Assume that $P(v_2) = 0$. Then $P(v_1) = v_2 \implies P^2(v_1) = P(v_2) = 0$. But since $P^2 = P$, $P^2(v_1) = P(v_1) = v_2 \neq 0$, contradicting the assumption that a vector in the image of $P$ can also lie in $\ker P$.
So the kernel and image of $P$ are both disjoint subspaces of $V$. Suppose their bases are respectively $\{u_1, \ldots, u_m\}$ and $\{w_1, \ldots, w_n\}$. Then $\dim V = \dim \ker P + \dim \text{im } P = m+n$. All elements in the two bases are mutually independent, for otherwise one could express one of the two bases' elements in terms of the other basis, which would contradict the fact that the two subspaces are disjoint.
$\{u_1, \ldots, u_m, w_1, \ldots, w_n\}$ forms maximal independent subset, and hence a basis, of $V$. If $v \in V$, it can be written as
$v = x_1u_1 + \ldots + x_mu_m+ y_1w_1 + \ldots + y_nw_n = u + w,$
for some $u \in \ker P$ and $w \in \text{im } P$.
Is there a problem with the above reasoning? I'm asking this because the representation of $v$ in this way seems like a unique one (as a sum of vectors in kernel and image). So $V$ should be a direct sum of $\ker P$ and $\text{im } P$, which is a stronger result than the one required to be proved (which of course makes me skeptical of my approach or concept).
Comment: What if $V$ is not finite dimensional? The result is still correct but your proof won't work.
Comment: @humanStampedist: Ah I should've specified: as of now I'm just studying finite-dimensional linear algebra from Linear Algebra by Serge Lang. So I'm only familiar with finite-dimensional concepts. I'll edit my question.
Answer: For each $v \in V$ we have
$$ \quad v=Pv+(I-P)v \in \text{im} P+ \ker P,$$
since $(I-P)v \in \ker P$.
Comment: Thanks! But I'm aware of that answer; my question pertains to whether the representation of $V$ as the **direct sum** of the kernel and image, as it seems from what I described, is correct or not.


How to reset cache on a specific page by a given URL?

Question: In Drupal 7, I found a way to reset cache on a specific page with:
<code>$url = url('<front>',  array('absolute' => TRUE));
cache_clear_all($url, 'cache_page');
</code>
What is the equivalent way in Drupal 9?
Comment: Using cache tags and contexts. Here's the docs https://www.drupal.org/docs/8/api/cache-api/cache-api and this is how to invalidate caches with a certain tag https://www.drupal.org/docs/drupal-apis/cache-api/cache-tags#s-invalidating
Comment: Yes, there isn't a directly equivalent way in D9, as the way of handing caching was much improved between D7 and D8+.
Comment: why do you want to do this?
Comment: I was adding a library to a specific page and it could be updated only through a configuration settings form, which would then reset the cache, so the library is properly updated.
Answer: Solved it like this:
<code>$url = Url::fromUserInput($custom_url);
  if ($url instanceof UrlInterface) {
    if ($url->isRouted()) {
      $nid = $url->getRouteParameters()['node'];
      /** @var \Drupal\node\Entity\Node $node */
      $node = Node::load($nid);
      if ($node instanceof NodeInterface) {
        $tags = $node->getCacheTags();
        \Drupal::service('cache_tags.invalidator')->invalidateTags($tags);
      }
    }
  }
</code>


Have two bottom seeds ever faced off before in a "World Series?"

Question: In October 2014, the San Francisco Giants and the Kansas City Royals "faced off" in the baseball World Series. They were both wild cards in their respective leagues, meaning that this will be a match between two bottom seeds (after the wild card round).
A few years ago, I pointed out this almost (but didn't) happen in football, but would have happened if the New York Jets had beaten the Pittsburgh Steelers for the AFC crown, and gone on to face the Green Bay Packers.
Is this the first time that this has happened in the World Series during the wildcard era? Has this happened before in any other sport such as football that also has wildcards?
Comment: Well back when the world series was the pennant winner of NL vs pennant winner of AL...  You had the "bottom seeds" (only seeds) facing each other every year.
Comment: @Coach-D: Changed question to discuss wildcard era.
Comment: The Royals weren't the bottom seed in the AL - Oakland was.
Comment: Good question, but you may want to limit "any other sport", to a couple ... otherwise we may end up with [another question with no single answer](http://sports.stackexchange.com/questions/6905/father-and-son-who-were-active-players-at-the-same-time-in-nfl-nba-nhl-mlb).
Comment: @pacoverflow is right - the Wild card game was in Kansas City.
Comment: @pacoverflow: Changed Kansas City to "wildcard."
Comment: Might also add "American" sport if you intend to limit it to those sports, or include an example of a non-American sport in the list.
Answer: In 2002, when the Angels defeated the Giants in the World Series, both teams were wildcards (and as there was only one wildcard, the bottom seed by default, though they were not the lowest win totals as Minnesota had 5 fewer wins than Anaheim, as Central Division champions).  That is the only example in Baseball, though there really have only been two decades of history where it would be meaningful to say the two lowest seeds faced each other; prior to the wildcard, you only had one team from each division (so 4 total teams) in the playoffs, and with divisional play it's hard to say who would be seeded what in a larger playoff.
The NHL and NBA have longer histories of large seeded playoffs.  In the NHL, never have two 8 seeds faced each other, but in 2012 the Kings (8) beat the Devils (6) for the first 8 seed win in NHL history and the largest sum of seeds in the Finals history.
In the NBA, 8 seeds nearly never beat 1 seeds; the 1998-1999 New York Knicks remain the only 8 seeds to reach the finals, losing to the Spurs (Duncan and Robinson's first championship).   The lowest seed to win a championship was the Rockets in 1994-95 (6 seed), but they beat the top seeded Magic that year.  No other team higher than 4th has ever won a NBA Finals.
In the NFL, there have never been a particularly low combination.  Although 6 seeds have been successful, for example in 2005 PIT (6 seed) defeated SEA (1 seed), they've never had to face similarly low seeded teams; the lowest I see is 6 seed vs 2 seed (Packers/Steelers), which isn't exactly a low seeded combo either.
Comment: @GreenMatt Good point, though The Admiral was definitely declining then, he was a significant contributor even - can't believe I missed that!  Updated.
Comment: Perhaps nitpicking, but 98-99 wasn't the only championship for Robinson and Duncan. David Robinson's last season was  '02-'03, when the Spurs (including Tim Duncan) won their 2nd championship.


Cron Process Hangs Indefinitely In Logrotate

Question: I currently have a server that isn't rotating it's logs daily has intended. The logrotate itself is most likely the one making my cron process hang.
I have to kill the process manually every time after the cron runs, so it can run again the next day.
[root@localhost ~]# ps aux | grep cron
root     15364  0.0  0.0 116884  1304 ?        Ss   Sep12   0:03 crond
root     17898  0.0  0.0  19060   972 ?        Ss   Sep13   0:00 /usr/sbin/anacron -s
root     17911  0.0  0.0 106112  1272 ?        SN   Sep13   0:00 /bin/bash /usr/bin/run-parts /etc/cron.daily
root     17915  0.0  0.0 106112  1140 ?        SN   Sep13   0:00 /bin/sh /etc/cron.daily/logrotate
root     17916  0.0  0.0 105968   900 ?        SN   Sep13   0:00 awk -v progname=/etc/cron.daily/logrotate progname {?????   print progname ":\n"?????   progname="";????       }????       { print; }
root     22439  0.0  0.0 103320   856 pts/0    S+   09:53   0:00 grep cron

As can bee seen in the logs, the job is locked by another anacron.
[root@localhost ~]# tail /var/log/cron
Sep 16 09:01:01 localhost run-parts(/etc/cron.hourly)[22374]: starting 0anacron
Sep 16 09:01:01 localhost anacron[22386]: Anacron started on 2016-09-16
Sep 16 09:01:01 localhost anacron[22386]: Job `cron.daily' locked by another anacron - skipping
Sep 16 09:01:01 localhost anacron[22386]: Normal exit (0 jobs run)
Sep 16 09:01:01 localhost run-parts(/etc/cron.hourly)[22388]: finished 0anacron
Sep 16 09:10:01 localhost CROND[22393]: (root) CMD (/usr/lib64/sa/sa1 1 1)
Sep 16 09:20:01 localhost CROND[22400]: (root) CMD (/usr/lib64/sa/sa1 1 1)
Sep 16 09:30:01 localhost CROND[22409]: (root) CMD (/usr/lib64/sa/sa1 1 1)
Sep 16 09:40:01 localhost CROND[22421]: (root) CMD (/usr/lib64/sa/sa1 1 1)
Sep 16 09:50:01 localhost CROND[22432]: (root) CMD (/usr/lib64/sa/sa1 1 1)

Have been checking the configurations files in logrotate.d and everything seems normal, what can possibly leaving my cron hanging ?
Comment: All your redirection does is capture any regular output and errors from logrotate and throws them away.  That's the exact opposite of what you want when you're trying to troubleshoot a program.  Have you tried running the script as it was originally from the command line?
Comment: What happens if you run the program manually - does it still hang?
Answer: Debug your logrotate configuation by running the logrotate command manually from the command line with the --debug or --verbose option to see where and why it hangs.
Comment: I think it is. There are lots of reasons why `logrotate` might hang, and running it interactively with `--verbose` is *the* way to find out the one that applies in your case. In my experience, it prints much more than what you cited, and you also get a chance to look at `ps` and `lsof`output in parallel while it is apparently hanging.
Answer: Apparently someone left a squid configuration file in logrotate with the following configuration:
/dir/user/logs/squid/* {
    weekly
    rotate 5
    compress
    notifempty
    missingok
    sharedscripts
    postrotate
      # Asks squid to reopen its logs. (log_rotate 0 is set in squid.conf)
      # errors redirected to make it silent if squid is not running
      /usr/sbin/squid -k rotate 2>/dev/null
      # Wait a little to allow Squid to catch up before the logs is compressed
      sleep 1
    endscript
}

The problem in that configuration is that it is rotating every single file, including the already compressed files, leavinf me with million of multiple times compressed files and their offspring. The configuration should be to include the *.log* and not all *:
/dir/user/logs/squid/*.log


Drupal 7: fetchField(0) giving me half of the records!

Question: I am trying to get all the records from one table. I get from the count 18 record, but the actual given lines are 9.
$name = 'admin';
$result = db_query("SELECT name FROM {users} WHERE name <> :name", array(':name' => $name));
$rownum = $result->rowCount();
print "This is the total number: ";
print $rownum;
print "
";
foreach ($result as $record) {
  $value = $result->fetchField(0);
  print $value;
print '
';
}

Results:

This is the total number: 18
  user1
  user2
  user3
  user4
  user5
  user6
  user7
  user8
  user9

Do you think is my loop?
Answer: Yes, the loop iterates through result, but additionally you do that kind of again in your line $value = $result->fetchField(0);.
This should be changed to $value = $record->name;.


GLEW with OpenGL 1.1

Question: I am trying to run a solution on VS2012 from school, but I am getting
<code>ERROR: Opengl 2.0 not supported
</code>
I've concluded that it's because they've started using GLEW for this assignment. Is there a way to get GLEW to work with my OpenGL 1.1?
Comment: Are you doing something unusual like running in a VM or over Remote Desktop?
Comment: It isn't a problem with GLEW. User code expects some GL 2.0 functions and, judging by GL version, determined that they are missing. GLEW just extracts function addresses - if function doesn't exist, it have no address, only re-implementing user code for older versions could help here (which is unreasonable - 1.1 is dead, even software implementations do much better now).
Answer: Make sure you have the latest nVidia/AMD graphics driver
Also try:
<code>  glewExperimental = true;
</code>

GLEW with OpenGL 1.1