Como criar um vetor que exibe a frequência de cada elemento em uma matriz?

Question: "Escreva um método contaFrequencia que recebe dados de uma matriz A que possui inteiros entre 0 e x; gera um vetor com as ocorrências de cada inteiro entre 0 e x. Escreva um método maior que recebe um vetor de inteiros e devolve o maior elemento do vetor. Escreva o módulo main, que preenche uma matriz somente com valores entre 0 e x e exibe qual valor foi o mais frequente (chame obrigatoriamente os métodos contaFrequencia, maior e leMatriz). "
Eu já montei a matriz sorteando os números, agora estou tentando criar o método contaFrequencia. Tenho duas dúvidas:
1) Como faço pra que o algoritmo "pule" a contagem de números que já foram contados? Por exemplo, se a matriz for: (0   0   1); (2   3   0); (1   2   3), o programa vai contar 0 três vezes, aí quando passar pro próximo, vai contar 0 três vezes outra vez.
2) Como declarar o vetor que vai armazenar as frequências contadas sem saber seu tamanho? Pensei em criar uma string e depois convertê-la para vetor de inteiros, mas a repetição na contagem da frequência ainda seria um problema. Também pensei em deixar os elementos da matriz em ordem crescente para encontrar o maior valor. Com isso eu saberia o tamanho do vetor que armazena as frequências. Mas não estou conseguindo ordenar utilizando Arrays.sort()...
public class Freq_Maior {
    static Scanner ent = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.print("Digite o número de linhas e colunas da matriz: ");
        int m = ent.nextInt();
        int n = ent.nextInt();
        System.out.print("Digite o valor máximo do intervalo usado para preencher a matriz: ");
        int x = ent.nextInt();
        int [][] A = new int[m][n];
        leMatrizR(A, x);

    }
    // método para ler a matriz
    public static void leMatrizR(int matriz[][], int a) {
        Random rnd = new Random();
        for (int i=0; i<matriz.length; i++) {
            for (int j=0; j<matriz[0].length; j++) {
                matriz[i][j] = rnd.nextInt(a+1);
            }
        }
    }
    public static void Freq(int matriz[][]) {
        ????
    }
}

Answer: O seu vetor com as frequências você na verdade sabe o tamanho: x + 1, sendo x o valor máximo do intervalo usado para preencher a matriz. Então o vetor freqs pode ser declarado como:
int [] freqs = new int[x + 1];

Feito isso, você pode passá-lo para o método Freq e realizar a computação das frequências, e para "pular" os elementos ja contados, basta compará-los com o elemento que estamos querendo contar no momento:
public static void contaFrequencia(int matriz[][], int freqs[]) {
    // para cada elemento possível (0..x)...
    for ( int e = 0; e < freqs.length; e++ ) {
        freqs[e] = 0; // initializa o valor da frequência com 0.
        for ( int i = 0; i < matriz.length; i++ ) {
            for ( int j = 0; j < matriz[i].length; j++ ) {
                // se encontramos o elemento...
                if ( matriz[i][j] == e ) {
                    // incrementamos a frequência do elemento.
                    freqs[e]++;
                }
            }
        }
    }
}

Comment: Obrigada pela ajuda! Acabei encontrando um outro jeito de fazer baseada na sua sugestão.
Comment: Mas como faço essa comparação dos elementos já contados com o que estou contando no momento?
O programa também está imprimindo os valores do vetor, mas eu não mandei imprimir... estranho.
Comment: O primeiro `for` varia a variável `e` para todos os valores possíveis de elemento, garantindo que a gente verifique todos eles. Depois, no `if ( matriz[i][j] == e )`, verificamos se o elemento atual da matriz é o que estamos contando. Apenas no caso de ele ser o elemento sendo contato, incrementamos a posição respectiva desse elemento no vetor de frequência. Gostaria de notar que o algorítmo que implementei é ineficiente, e é possível reimplementá-lo realizando apenas uma passagem na matriz inteira.


Indice indefinido em passagem de valor com AJAX

Question: Estou tentando enviar dados binários do Blob por Ajax para fazer o upload via PHP.
Porém, nao estou conseguindo acessar o $_GET. Retorna um erro dizendo índice indefinido:

responseText : "Nenhuma imgagem encontrada"

quando comento a linha do die() do upload.php:

responseText : " ↵Notice: Undefined index: obBlob in
  C:\xampp\htdocs\WEBCAM\upload.php on line 4

Retorno do AJAX 'error':

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ,
  setRequestHeader: ƒ, overrideMimeType: ƒ, …} abort : ƒ (e) always : ƒ
  () catch : ƒ (e) done : ƒ () fail : ƒ () getAllResponseHeaders : ƒ ()
  arguments : (...) caller : (...) length : 0 name :
  "getAllResponseHeaders" prototype : {constructor: ƒ}
  proto : ƒ () [[FunctionLocation]] : jquery-3.3.1.min.js:2 [[Scopes]] : Scopes[3] getResponseHeader : ƒ (e) overrideMimeType : ƒ
  (e) pipe : ƒ () progress : ƒ () promise : ƒ (e) readyState : 4
  responseText : "Nenhuma imgagem encontrada" setRequestHeader : ƒ (e,t)
  state : ƒ () status : 200 statusCode : ƒ (e) statusText : "OK" then :
  ƒ (t,r,i)
  proto : Object

segue o codigo:
index.html (completo):
<!doctype html>

        <meta http-equiv="content-type" content="text/html; charset=utf-8">

        <title>Webcam TRIX</title>

        <video src="" id="video" muted autoplay></video>
        <canvas id="pic"></canvas>

        <input type="text" id="blobOut" value="">
        Foto
        <input type="button" id="btnStart" value="Tirar Foto">
        <input type="button" id="btnSave" value="Salvar Foto">

upload.php (completo):
<?php
header("Content-Type: application/json", true);
if(empty($_GET["obBlob"])) die("Nenhuma imgagem encontrada");
$obBlob = $_GET["obBlob"];
$servername = "localhost";
$username = "root";
$password = "";
$database = "fotos";
$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO fotos (foto) VALUES ($obBlob)";
if(mysqli_query($conn, $sql)){
    mysqli_close($conn);
    echo $conn->error;
}else{
    mysqli_close($conn);
    die("Error:".$conn->error);
}
?>

EDIT:
tentei da seguinte forma, utilizando a API FormData com o AJAX, sem sucesso:
document.getElementById("btnSave").addEventListener("click", event => {
                            canvas.toBlob(function(blob){
                                var formData = new FormData();
                                formData.append("obBlob", blob);
                                $.ajax({
                                    url : "//localhost/webcam/upload.php",
                                    type: "POST",
                                    data: {obBlob: formData},
                                    contentType: false,
                                    processData: false,
                                    success: function(resultado) {
                                      console.log(resultado);
                                    },
                                    error: function(resultado) {
                                        console.log(resultado);
                                    }
                                });
                            });
                        });

e tentei assim também, fazendo o envio manual... tentei enviar o blob direto, ou convertendo em JSON (que no caso se mostra vazio quando jogo no console!):
document.getElementById("btnSave").addEventListener("click", event => {
                    canvas.toBlob(function(blob){
                        json = JSON.parse(JSON.stringify(blob));
                        console.log(json);
                        var xhr = new XMLHttpRequest();
                        xhr.open("POST", 'upload.php', true);
                        xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
                        xhr.send(json);
                    });
                });

como faço pra pegar o erro neste ultimo caso caso?
alguma idéia do que poderia ser?
EDIT 2:
desisti de usar blob e tentei com canvas.toDataURL, mas o array chega vazio!!!
document.getElementById("btnSave").addEventListener("click", event => {
                var dataURL = canvas.toDataURL();
                $.ajax({
                    url : "//localhost/webcam/upload.php",
                    type: "POST",
                    data: {"imgBase64":dataURL},
                    contentType: false,
                    processData: false,
                    dataType:"json",
                    success: function(resultado) {
                      console.log(resultado);
                    },
                    error: function(resultado) {
                        console.log(resultado);
                    }
                });
            });

quando verifico o payload na aba network das ferramentas de desenvolvedor do Chrome o objeto está la!
já tentei de tudo e não sai disse... verifiquei o $_SERVER['REQUEST_METHOD'] e está retornando POST, tentei passar usando XMLHttpRequest... Não tenho idéia do que possa ser... estou na base da tentativa e erro!
Comment: Você está realizando `POST` mas está recuperando a variável via `$_GET`
Comment: O AJAX do jQuery não permite o tipo `blob`, tem que fazer uma requisição na mão ou usar mais alguma biblioteca
Answer: Consegui resolver o problema utilizando um objeto FormData acrescentando um índice ao objeto que eu gostaria de passar do JS para o PHP com o método "append()". e depois passando o objeto FormData utilizando o método send do XMLHttpRequest...
document.getElementById("btnSave").addEventListener("click", event => {
   var fd = new FormData();
   var dataURL = canvas.toDataURL('image/jpeg', 1.0);
   fd.append("data", dataURL);
   var oReq = new XMLHttpRequest();
   oReq.open("POST","upload.php");
   oReq.send(fd);
});

Para acessar utiliza-se o $_POST normalmente, acessando o índice criado no objeto FormData. ex do código acima:

$_POST['data']

Obrigado a todos pela ajuda!!!


C++ constructor syntax explaination

Question: I was going through a tutorial for building an AST with the help of Clang/LLVM.
I see this syntax there:
struct PPContext {
  // Takes ownership of client.
  PPContext(clang::DiagnosticClient* client = 0,
            const std::string& triple = LLVM_HOSTTRIPLE)
    : diagClient(client == 0?new clang::TextDiagnosticPrinter:client),
      diags(diagClient),
      target(clang::TargetInfo::CreateTargetInfo(triple)),
      headers(fm),
      pp(diags, opts, *target, sm, headers)
  {
    // Configure warnings to be similar to what command-line `clang` outputs
    // (see tut03).
    // XXX: move warning initialization to libDriver
    using namespace clang;
    diags.setDiagnosticMapping(diag::kind,diag::MAP_IGNORE);
//diag::warn_pp_undef_identifier was the initial value instead of diag::kind. But I changed since it gave error.
  }

  ~PPContext()
  {
    delete diagClient;
    delete target;
  }

  clang::DiagnosticClient* diagClient;
  clang::Diagnostic diags;
  clang::LangOptions opts;
  clang::TargetInfo* target;
  clang::SourceManager sm;
  clang::FileManager fm;
  clang::HeaderSearch headers;
  clang::Preprocessor pp;
};

And:
//What is the constructor doing here ? The construct looks very different and difficult to comprehend !!!
// Could someone break it up for me ?
PPContext(clang::DiagnosticClient* client = 0,
            const std::string& triple = LLVM_HOSTTRIPLE)
    : diagClient(client == 0?new clang::TextDiagnosticPrinter:client),
      diags(diagClient),
      target(clang::TargetInfo::CreateTargetInfo(triple)),
      headers(fm),
      pp(diags, opts, *target, sm, headers)
  {
    // Configure warnings to be similar to what command-line `clang` outputs
    // (see tut03).
    // XXX: move warning initialization to libDriver
    using namespace clang;
    diags.setDiagnosticMapping(diag::kind,diag::MAP_IGNORE);
//diag::warn_pp_undef_identifier was the initial value instead of diag::kind. But I changed since it gave error.
  }

Please let me know if there is any other material which would be of good help and learning experience. Thanks
Comment: what things confuse you specifically? default parameters? or A ? B : C expression? or something else?
Comment: The expression is PPContext(,) : ("5 times"). I am fine with the default parameters.  I am confused about what"() : () {//body of the constructor }". What does "():()" mean ?
Comment: Don't forget to mark a correct answer, if there isn't one, perhaps leave comments as to why you feel they aren't correct.
Answer: These are constructor initializers.  They initialized class members with the value given to them.  For instance:
class TestClass
{
private:
    int someField;

public:
    TestClass() : someField(5) { }
};

Will initialize the member someField to have a value of 5 during the call to the TestClass() constructor.  You can separate multiple initializers with a , to initialize multiple members.  You can also pass parameters from the constructor to these initializers such as:
class TestClass
{
private:
    int someField;

public:
    TestClass(int _someField) : someField(_someField) { }
};

When this constructor is called, the value passed to _someField will be used to initialize someField.
Also consider inheritance.  Using the second TestClass as our base we get the following derived type:
class TestClassDerived : public TestClass
{
public:
    TestClassDerived(int _someField) : TestClass(_someField) { }
};

That's how you can construct a base class from a derived type and pass parameters to a non-default constructor.  Without this you wouldn't be able to construct the base with the appropriate parameters using a non-default constructor.
Comment: Before voting me down, please explain why you're doing so.  I would appreciate it, so I can fix whatever it was that I got voted down for.
Answer: It's called a constructor initialization list, which is used for inheritance and initializating member variables.
Click this link for a good explanation of this topic.
One scenario this is required is dealing with inheritance. Consider the following:
class Base
{
public:
    Base(int n)
    {
    }
};

class Derived : Base
{
public:
    // Error! How do we construct Base? We never pass n
    // to the constructor of Base.
    Derived(int n)
    {
    }
};

How can we change the above to compile? With a constructor initialization list:
class Base
{
public:
    Base(int n)
    {
    }
};

class Derived : Base
{
public:
    // Now your compiler is happy.
    Derived(int n) : Base(n)
    {
    }
};

Answer: This constructur is in the format
PPContext(arg1, arg2)
    : initConstructor1,
      ...,
      initConstructor5

where you can exchange initConstructor to the initialization constructors of
the PPContext members

C++ constructor syntax explaination


cURL POST to REST Service

Question: I am trying to post to a REST service using PHP cURL but I'm after running into a bit of difficulty (this being that I've never used cURL before!!).
I've put together this code:
  <?php
error_reporting(E_ALL);
if ($result == "00")
{

$url = 'http://127.0.0.1/xxxxxx/AccountCreator.ashx'; /*I've tried it a combination of ways just to see which might work */

$curl_post_data = array(
    'companyName' =>urlencode($companyName),
    'mainContact' =>urlencode($mainContact),
    'telephone1' =>urlencode($telephone1),
    'email' => urlencode($email),
    'contact2' => urlencode($contact2),
    'telephone2' => urlencode($telephone2)
    'email2' => urlencode($email2);
    'package' => urlencode($package)
    );

foreach($curl_post_data as $key=>$value) {$fields_string .=$key. '=' .$value.'&';
}
rtrim($fields_string, '&');
die("Test: ".$fields_string);

$ch = curl_init();

curl_setopt ($ch, CURLOPT, $url);
curl_setopt ($ch, CURLOPT_POST, count($curl_post_data));
curl_setopt ($ch, CURLOPT_POSTFIELDS, $fields_string);

$result = curl_exec($ch);

curl_close($ch);

Following this, my code sends an email and performs an IF statement. I know this works okay, I only started running into trouble when I tried to insert this cURL request.
I've tried this however it doesn't run. As I am integrating with payment partners, it just says:
Your transaction has been successful but there was a problem connecting back to the merchant's web site. Please contact the merchant and advise them that you received this error message. Thank you.

The exact error that was received was a HTTP 500 error.
Thanks.
Comment: 'email' => urlencode($email),
    'contact2' => urlencode($contact2),
    'telephone2' => urlencode($telephone2)
    'email2' => urlencode($email2);
    'package' => urlencode($package) you should really fix this array! it's missing commas, there's a semicolon.. it's all messed up
Comment: @sathia, thanks, I fixed that. Embarrassed I missed that! The die("Test: ".$fields_string); is now outputting:: Test: companyName=xxx&mainContact=xxx+xxx&telephone1=xxxx with all the correct values.  however that is all it outputs - It doesn't update my database and it doesn't proceed with the following mail() function or IF statement.
Comment: of course, now you need to comment that die() because die does what die says: Kill the execution of the program. just comment it //die("Test.. and it will go on
Comment: That would make sense!! I did that, It runs through my script fine, even sends me a confirmation email. Still doesn't update my database though :-S I'm assuming this is more of a problem with the URL of the web service rather than my code at this stage now. What do you think?
Answer: foreach($curl_post_data as $key=>value) {$fields_string .=$key. '=' .value.'&';

value here is missing a dollar i guess
foreach($curl_post_data as $key => $value) {$fields_string .=$key. '=' .$value.'&';

have you tried die($fields_string); to see what are you actually sending to the merchant?
Comment: I tried inserting the dollar symbol where it was missing and still no joy. Thanks anyway.
Comment: have you added both dollars sign? what die($fields_string); prints?
Comment: @sathia, yup, both dollars sign. I didn't try die($fields_string); prints, where should I insert this?
Comment: foreach($curl_post_data as $key=>$value) {$fields_string .=$key. '=' .value.'&';
}
rtrim($fields_string, '&'); die($fields_string);
Comment: Hi sathia, I inserted that line however nothing comes up. I think whoever set up the server however turned off error reporting. Is there a way of turning this on for just this file?
Comment: put this as the first line of your code then: error_reporting(E_ALL); and this as your die output: die("Test: ".$fields_string);
Comment: @sathia...there was still no output from this.
Comment: I've just posted a larger snippet of my code so you can have a look sathia. I did not post beyond the curl method because it's basically just a large email I send to users, and an IF statement. I have tested prior to inserting curl and it worked okay so I'm confident it is curl that is throwing it off.
Answer: First of all: are you testing locally? Because that IP you're using is not a valid server address.
The constant to set the URL is called CURLOPT_URL:
curl_setopt ($ch, CURLOPT_URL, $url);

Also CURLOPT_POST must be true or false ( http://php.net/curl_setopt ), not a number (except for 1 maybe):
curl_setopt ($ch, CURLOPT_POST, true);

Here's some POST sample code: PHP + curl, HTTP POST sample code?
Comment: @DanMan, thanks for the reply. No I am testing on the server. The web service I am connecting to is on a different port for now, which represents the :00 at the end of the IP address. This was one of the things I was unsure about - if I could use the port number?
Comment: I suppose it shoud work, but you can try setting CURLOPT_PORT instead, too.
Comment: If you're testing directly ON the server, then the IP should be 127.0.0.1
Comment: Hmm, still no luck with that one. Will keep trying anyway
Comment: In your last edit, you're still using CURLOPT instead of CURLOPT_URL.
Answer: It would be best if you can provide your PHP version.
As of PHP 5, some handy functions are bundled in the core instead of separate PECL libraries.
// If you are working with normal HTTP requests, simply do this.
$curl_post_data = http_build_query($curl_post_data);

curl_setopt($ch, CURLOPT, $url);

// This is a boolean option, although passing non-zero integer
// will be type-casted to TRUE, count() is not the proper way.
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_post_data);

// If you really want the next statement be meaningful, do this.
// Otherwise your HTTP response will be passed directly into
// the output buffer.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$result = curl_exec($ch);

Keep in mind that CURLOPT_POSTFIELDS in PHP supports file uploads, by adding a '@' character followed by a full file path as the value.
You don't want to call http_build_query() on such situations.
Sample code for file upload
$curl_post_data = array('file1' => '@/home/user/files_to_be_uploaded');

While you can optionally specify MIME type, see the documentation for more information.
As said, check your PHP version first. This feature only works in PHP 5, AFAIK there are companies still hosting PHP 4.x in their servers.
Answer: Have a look at http_build_query

cURL POST to REST Service


Possible to add a worker on-the-fly?

Question: When starting a TensorFlow server (tf.distribute.Server), you must pass a ClusterSpec which specifies all tasks/workers in the cluster.
Is it possible, after you started the server, to add further workers to it? How?
If not, why not?
(This is related to the question, why does the server need to know at all about all the workers in advance?
Although it is not quite the same question.)
(This is also related to the question, what operators are there for remote communication? Currently I only know about this (official) distributed TensorFlow functionality, via a TF server with ClusterSpec.
Other inofficial solutions are e.g. Tensorpack TF ZMQ ops, where you can communicate in whatever way you want (via ZeroMQ), and you also do not need to know the whole cluster beforehand / in advance.)
Answer: Out of the box, I don't think it is possible to add further workers/tasks to a running server.
The tf.distribute.Server class uses the server class of TensorFlow's low-level C API. This class provides an UpdateServerDef method, which probably could be used to modify the configuration of a running server, and consequently to change the workers/tasks.
However, this update method is not exposed via the TensorFlow python binding, so unless you are willing to modify and compile your own TensorFlow C core I don't think it is possible.

Possible to add a worker on-the-fly?


Creating a tag list in a view of multlingual nodes

Question: I am creating a multilingual site in English and Swedish on Drupal 7.
I have a content type called 'News' which has a taxonomy term field that categorises the news posts. I have the content type set up with 'Multilingual support' set to 'Enabled, with field translation'.
The views at /en/news and /sv/nyheter are working to the extent that they only show news in the users language. However, I can't work out how to create a tag list in a block that shows the taxonomy terms for the users language.  i.e. when I am at /en/news I get a block which shows only English tags, (e.g. Fundraising (4), Events (2), Membership (2)) and and when I am at /sv/nyheter I only see Swedish tags (e.g. Insamling(4), Evenemanger(2), Medlemskap(2)).
What Translation mode should I use for the taxonomy?
What settings (fields, filters, relationships, etc.) should I use in the view?
Is it possible to create a view with two paths, one of the Swedish /sv/nyheter and one for the English /en/news?
I can provide more details on how I currently have it set up if necessary, and am also up for changing how it is set up to get it working. If you can point me to examples of this working with a views export and details of how you have the taxonomy set up that would also be really handy.
Thanks!
Comment: As taxonomy are translatable, so you just need to create the same views as you created for news and use same filters.
Answer: You should use " Translate. Different terms will be allowed for each language and they can be translated." in the vocabulary's settings.
In the view's settings, make sure that "news category" content field's "formatter" option is selected as "Link (localized)" or "plaintext (localized)".


Imprimir vários números com um separador entre eles, mas não colocar o separador após o último

Question:
Faça um programa que leia dois números inteiros, representando os valores inicio e fim de um intervalo e imprima os múltiplos de 5 entre eles.

Meu código:
valores = input().split()
numero1 = int(valores[0])
numero2 = int(valores[1])
for n in range(numero1, numero2+1):

    if n % 5 == 0:

        print(n, end='|')

Notem que os números são separados por |, mas não pode ter esse caractere depois do último número.
Comment: Uma possibilidade é do segundo em diante imprimir um| antes do número.
Answer: Uma alternativa é usar join:
print('|'.join(str(n) for n in range(numero1, numero2 + 1) if n % 5 == 0))

Apesar de parecer a mesma coisa da outra resposta, tem uma diferença. Lá foi criada uma lista contendo os números, depois esta lista foi passada para join. Aqui eu passei diretamente a generator expression, que não cria a lista. Assim, o join itera pelos números e já vai construindo a string final (não que vá ter aquela diferença de performance - ainda mais para ranges com poucos valores - mas é importante saber que você pode construir o que precisa sem criar listas - ou quaisquer outras estruturas - sem necessidade).

Mas na verdade existe outra forma de otimizar o código. Se a ideia é imprimir apenas os múltiplos de 5, não tem porque o range ser de 1 em 1 e ir testando se cada número é divisível por 5 (já que entre 2 múltiplos, outros 4 números serão testados sem necessidade). Em vez disso, você pode simplesmente começar em um múltiplo de 5 e fazer o range ir de 5 em 5:
numero1 = # ler o número
numero2 = # ler o número

# se não for múltiplo de 5, ajustar para o próximo múltiplo
resto = numero1 % 5
if resto != 0:
    numero1 += 5 - resto

# range pula de 5 em 5
print('|'.join(map(str, range(numero1, numero2 + 1, 5))))

Dessa forma, eu só preciso testar se o primeiro número é divisível por 5. Se for, não precisa fazer nada. Se não for, eu ajusto para o próximo múltiplo (por exemplo, se for 7, ajusto para 10). Como agora eu sei que estou começando com um múltiplo de 5, o range pode iterar de 5 em 5, e assim eu não preciso testar dentro do loop se os números são divisíveis por 5 (na verdade nem precisa mais do for: eu posso passar o range diretamente, pois agora ele só terá múltiplos de 5).
Uma alternativa ao join é imprimir o range diretamente:
numero1 = # ler o número
numero2 = # ler o número

# se não for múltiplo de 5, ajustar para o próximo múltiplo
resto = numero1 % 5
if resto != 0:
    numero1 += 5 - resto

print(*range(numero1, numero2 + 1, 5), sep='|')

Note o asterisco antes do range: ele serve para fazer o unpacking dos valores do range (é como se eu passasse cada um deles separadamente para print), e o parâmetro sep indica o caractere que será impresso entre os elementos (é mais ou menos o que a outra resposta sugeriu, mas sem precisar criar a lista).

Outra alternativa é usar enumerate, que itera pelos números e seus respectivos índices. Assim, você não imprime o caractere | somente para o primeiro elemento:
numero1 = # ler o número
numero2 = # ler o número

# se não for múltiplo de 5, ajustar para o próximo múltiplo
resto = numero1 % 5
if resto != 0:
    numero1 += 5 - resto

for i, n in enumerate(range(numero1, numero2 + 1, 5)):
    if i > 0: # não é o primeiro número, coloca o separador
        print('|', end='')
    print(n, end='')

Ou não use o índice, simplesmente verifique se o número é igual ao primeiro:
numero1 = # ler o número
numero2 = # ler o número

# se não for múltiplo de 5, ajustar para o próximo múltiplo
resto = numero1 % 5
if resto != 0:
    numero1 += 5 - resto

for n in range(numero1, numero2 + 1, 5):
    if n != numero1: # não é o primeiro número, coloca o separador
        print('|', end='')
    print(n, end='')

Comment: @Evilmaax Deixei o código completo em todos os exemplos para evitar mais confusões :-)
Comment: Seus 2 últimos exemplos (enumerate e sem índice) estão printando números não múltiplos de cinco: 1, 6, 11, 16...
Comment: Boooa, valeu @hkotsubo
Comment: Muito obrigado, não conhecia esse join e nem esse map, agora entendo seus usos e obrigado também por demonstrar várias formas de fazer .
Answer: Sem considerar que você não está tratando o input, uma maneira fácil de juntar os números seria colocando todos eles em uma lista de strings e usar o método join() para imprimir o resultado.
Esse método é esperto o suficiente para fazer exatamente o que você quer, ou seja, só colocar o separador entre os elementos.
O código do laço for e da condição if fica todo em uma compreensão de lista. Cada elemento é convertido para o tipo str, para que o join() funcione.
Ficaria assim:
valores = input().split()
numero1 = int(valores[0])
numero2 = int(valores[1])

lista = [str(n) for n in range(numero1, numero2+1) if n % 5 == 0]

print('|'.join(lista))


Should train and test dataset label distribution match reality?

Question: Assume I'm building a binary classification model to detect a disease that according to research is present in 3% of the population. I'm given a balanced dataset to train the model where half of the people have the disease and the other half do not. I set aside 20% of the dataset for testing and 80% for training with cross validation.
Before making predictions on the test set, should I randomly under-sample the test set's positive class so it matches the 97-3 distribution that exists in real life? I'm worried that using the balanced dataset in train and test could make performance look better than it is if I'm using precision and recall to evaluate the model. At the same time this would make it harder to detect over- or under-fitting if the distribution is different in the test set. I also don't want to under-sample the entire dataset because there's valuable information in all of those positive observations.
Should the train and test set label distribution match what I expect to see when the model is making predictions in a live environment?
Answer: Undersampling ( or over-...) is rarely a good idea! as you have realized. You should better treat your problem as one of probability estimation, for example with logistic regression.  There is many similar questions, and for good links to more information see Rare Events Logistic Regression  (or search this site for Frank Harrell).
Also have a look at proper score functions: Why is accuracy not the best measure for assessing classification models?


On the cartesian closed T-spaces

Question: Good morning to everybody. I have a question concerning exercise 27I (pag. 450) of Adamek's "The Joy of Cats" (that you can find here: http://katmat.math.uni-bremen.de/acc/acc.pdf)
Such an exercise characterize the $T$-spaces (where $T$ is a set-functor) which are cartesian closed. More in detail, I do not well understand the meaning of the sentence "T weakly preserves pullbacks, i.e., for each 2-sink $(f,g)$, the factorizing morphism of the $T$-image of the pullback of (f,g) through the pullback of $(Tf, Tg)$ is a retraction.
If I have well understood, I must consider the $2$-sink $(f,g)$ and next to compute their pullback. Call it $(P,h_1,h_2)$. Secondly, I must consider the image of the previous pullback square, namely the square with arrows $T(h_1),T(h_2),Tf,Tg$ and with vertices $T(P),T(Dom(f)),T(Cod(f)),T(Dom(g))$. In general this is not a pullback square. Therefore, if I consider the pullback $(X,k_1,k_2)$ of $(T(f),T(g))$, then there exists a unique morphism $s: T(P) \to X$ (the factorizing morphism of the $T$-image of the pullback of $(f,g)$ through the pullback of $(Tf,Tg)$) such that $s \circ k_1=T(h_1)$ and $s \circ k_2=T(h_2)$. I must only show that $s$ is a retraction. Is it my interpretation correct?
I have also a second question: in the paper "J. Adamek, V. Koubek, Cartesian closed functor-structured categories, Commentationes Mathematicae Universitatis Carolinae, Vol. 21 (1980), No. 3, 573-590." the authors characterize cartesian closed T-spaces by requiring that $T$ covers each non-empty pullback. A pullback is said to be covered by a functor if this functor maps it on a square, through which all commuting squares factorize but not necessarily uniquely.
Well, my question is: it seems that T covers non-empty pullbacks is equivalent to that of weakly preserve pullbacks. But why (without using their equivalence with cartesian closedness)?
Using the definition of retraction, it is easy to check that weakly preserves pullbacks implies covers non-empty pullbacks!
Answer: Regarding the first question, your interpretation is correct. Regarding the second, one can interpret "covering" as sending a pullback to what is known as a weak pullback. One can then show weak pullbacks are exactly retractions onto pullbacks (hence "cover" being interpreted as retraction onto).
In detail, given a diagram $J\colon D\to C$, a cone $h_j\colon d\to Jj$ is called a weak limit of $J\colon D\to C$ if every cone $g_j\colon d'\to Jj$ factors as $h_j\circ g'\colon d'\to d\to Jj$ for some (not necessarily unique) morphism $g'\colon d'\to d$.
If there is a limiting cone $\pi_j\colon \lim J\to Jj$, then the cone $h_j\colon d\to Jj$ factors as $\pi_j\circ h\colon d\to\lim J\to Jj$ for a unique morphism $h\colon d\to\lim J$. Since any other cone $g_j\colon d'\to Jj$ factors uniquely as $\pi_j\circ g\colon d'\to\lim J\to Jj$, we see that $h\colon d\to\lim J$ is a weak limit if and only if every morphism $g\colon d'\to\lim J$ factors as $h\circ g'\colon d'\to d\to\lim J$ for some morphism $g'\colon d'\to d$. In particular, it is necessary that $\mathrm{id}_{\lim J}\colon\lim J\to\lim J$ factor as $h\circ s\colon\lim J\to d\to\lim J$ for some morphism $s\colon\lim J\to d$, i.e. that $h\colon d\to\lim J$ be a retraction. Conversely, given such a factorization, any $g\colon d'\to\lim J$ factors as $(h\circ s)\circ g=h\circ(s\circ g)\colon d'\to d\to\lim J$.

On the cartesian closed T-spaces


Substring(string.IndexOf()) está retornando partes indesejadas

Question: Estou capturando um site de músicas. Gostaria de retornar somente 2 informações artista e a música. Ela está neste trecho de código:

                edoardo bennato

            le ragazze fanno grandi sogni

Artista = edoardo bennato
música = le ragazze fanno grandi sogni
Estou tentando recuperar assim:
string musica = resposta.Substring(resposta.IndexOf(""), resposta.IndexOf(""));
string artista = resposta.Substring(resposta.IndexOf("autore"), resposta.IndexOf("
"));

No caso artista ok, sei que tem itens a mais, mas na música pra mim estaria 100% correto, porém ele retorna na música o seguinte conteúdo:
"le ragazze fanno grandi sogni\n            \n
\n     \t\n        \n        \n                \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n
\n        \n                \n           \n           \n           \n        \n        \n        \n\t\t       \n        \t\n       \n           \t\t
\n\t\t\n\t\t\n       \n        \n        \n        \n     \n
    \n       \n    \tFoto: 53\n   \n        \n    \tVideo: 35\n\t\n    \t\n
\n
\n    \t\n    \t    Tutte le news\n        \n\t
\n        \n        \n        \n        \n        \n
\n
Artisti consigliati
\n
\n

\n
<img src=\"http://sta"

O que está errado?
Answer: Você realmente está pegando as posições erradas.
O início não está considerando os caracteres do que está buscando. Então se está buscando  você tem que começar 6 caracteres à frente para não pegar a própria string de busca.
O segundo parâmetro espera quantos caracteres você quer pegar e não a posição. Então você deve achar a string que faz o casamento do final e deve subtrair o que já foi desconsiderado antes, no caso o valor do primeiro parâmetro. Desta forma você tem a quantidade de caracteres e não a posição.
Assim:
using static System.Console;

public class Program {
    public static void Main() {
        var resposta = @"

                edoardo bennato

            le ragazze fanno grandi sogni

";
        var inicio = resposta.IndexOf("") + 6;
        var musica = resposta.Substring(inicio, resposta.IndexOf("") - inicio);
        inicio = resposta.IndexOf("autore") + 6;
        var artista = resposta.Substring(inicio, resposta.IndexOf("
") - inicio);
        WriteLine(musica);
        WriteLine(artista);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Note que o resultado do artista está errado como você reconhece. Adapte ao que precisa agora. Você já sabe onde estava errando.
Um detalhe: ficar parseando páginas de terceiros é pedir para ter problemas, a não ser que o criador da página afirme que nunca fará alterações nela. Só faça em desespero.
Comment: Concordo, qualquer mudança no código gerará um erro pra mim, mas como é algo pessoal então se mudar eu mudo tb, tranquilo.


Whether to stratify or do a simple random sampling from a set of papers to be compared?

Question: I have a population/set of papers (~350) that have been categorized into non-mutually exclusive types of in vivo biological target each with different numbers of paper. Another way of categorizing these papers is the method by which some drug against the target is administered. Categories by this categorization are mutually exclusive.
I want to compare the merits of the biological target categories. Should I stratify the papers by biological target, or by method of drug administration, or should I just take a simple random sample?
Similarly, if I were to do the converse - compare the merits of the methods of administration - how should I sample?
Finally, bearing in mind that the method of assessing each category is laborious, what sample size should I be using?
Comment: Clarifications: (1) are the categorizations of the targets and delivery methods already available? Options: (a) yes, I already have them; (b) no, but I can quickly get them for all 350 papers by scanning the abstract; (c) no, I have to read paper in depth to get them. (2) what are the variables of interest? That is, for the papers that you are going to select for in-depth analysis, what will you get out of such an analysis? E.g., effect size, cost of the study, number of citations, etc.
Comment: (1) (a); (2) The variables or attributes of interest are specific measures, such as ratio of adverse events to patients.
Answer: (1) If you can stratify on the delivery method, do so.
(2) If you can stratify on the targets, do so; come up with a meaningful stratification strategy that would give you mutually exclusive categories. (You would have to tell more about how the categories overlap for us to provide meaningful advice.)
(3) If you can stratify on both of these variables, stratify on the pair-wise cells.
Whatever strata you produce, consider proportional allocations between strata (unless you have reasons to expect that some of the variables of interest have certain behaviors associated with stratification). That is, the sampling rates within strata should be the same: if you decide you want to have a sample size of 50, then you might want to have the sampling rate of 1/7 in each strata. This would also mean that each strata should have at least 14 units in the population, so that you could sample at least 2 papers, in other to be able to produce variance estimates (you can't do that with just 1 observation in a stratum). Thus you may have to combine the strata that are too small.
The sample size issue is entirely up to you. This is a trade-off between accuracy and cost, and both of these are probably in your head only. If you had just one target variable of interest, and had an idea about the effect size you are trying to capture, there would have been a way to conduct some power analysis and try to figure out the sample size. If you have several response variables and no clue about how they behave in your population of papers, then basically you would want to sample until you get tired of reading these papers.


PHP Multiple Dropdown Box Form Submit To MySQL (Part 2)

Question: This is a continuation of the discussion at
PHP Multiple Dropdown Box Form Submit To MySQL
which ended with the words: "Once you have the variables, it is trivial to create new rows."  No doubt that's generally true, but apparently not for this learner...  :-D
Given the following form:
    <form action="form.php" method="POST">
    <select name="colors[]" multiple="yes" size="2">
    <option>Red</option>
    <option>Blue</option>
    </select>
    <input type="submit" value="Go!">
    </form>

how do I create new rows?  The following script
foreach($_POST['colors[]'] as $color)
    {
        $id = mysqli_real_escape_string($link, $color);
        $sql = "INSERT INTO colors SET id = '$id'";
    }

raises the error
 Warning: Invalid argument supplied for foreach() in form.php on line ...

whereas the following
    $colors = $_POST['colors[]'];
    for ($i = 0; $i < count($colors); $i++)
        {
            $color = $colors[$i];
            $sql = "INSERT INTO colors SET id = '$color'";
        }

raises no errors but does no row creation.
What triviality am I missing here?
Answer: Use:
foreach($_POST['colors'] as $color)

No need to specify [] here, php knows that it is an array.
Comment: Yes, however I'm still not getting the database to create rows.  I created a table like so: CREATE TABLE colors (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
color TEXT
); --- I can't see what the problem is...
Comment: @Peterc: I could not understand your comment completely but why don't you use a sql client software such as sqlyog to create your table?
Comment: @Sarfraz - good suggestion.  I think I found the problem.  Thanks again for your help!
Comment: What was the problem? It helps for others who encounter the problem to know where you found the problem and an alternative solution for it.
Comment: @Anthony - it was precisely what you said in your answer below - I had left out the mysql_query statement. Doh! :-D
Answer: Inside of your foreach loop I did not see that you are executing the query. You need to execute mysql_query with your INSERT statement.
foreach($_POST['colors'] as $color) {
 $id = mysqli_real_escape_string($link, $color);
 $sql = "INSERT INTO colors SET id = '$id'";
  if (!mysql_query($sql)) {  // if the query encountered a problem.
     die('Invalid query: ' . mysql_error());
  }
}

Comment: @Anthony - That's correct - as I just discovered (to my chagrin)!  Thanks for the help.


Analytic solutions to a Stochastic Differential Equation

Question: I want to solve an SDE as follows:
$$
dX_t = \alpha(\beta - X_t)dt + dB_t,\quad X_0 = x_0
$$
where $\alpha$, $\beta$ are positive constants and B_t is a Browian motion independent to $X_t$.Is there a way to solve it? Thank in advance for any help or some references to this kind of equation.
Comment: The condition that $(B_t)$ is independent from $(X_t)$ is absurd.
Answer: Let assume this
$$
Y_t = X_t\mathrm{e}^{\alpha t}
$$
then using Ito we find
$$
dY_t = \alpha  X_t\mathrm{e}^{\alpha t} dt + \mathrm{e}^{\alpha t}dX_t
$$
with some rearrangement we can find
$$
\mathrm{e}^{-\alpha t} dY_t = dX_t + \alpha X_t dt
$$
which looks awfully like what you have as the original SDE above except we have
$$
dX_t = \alpha\beta dt -\alpha X_t dt  + dB_t
$$
thus we can easily see
$$
\mathrm{e}^{-\alpha t} dY_t = \alpha\beta dt + dB_t
$$
thus
$$
dY_t = \alpha\beta \mathrm{e}^{\alpha t} dt + \mathrm{e}^{\alpha t}dB_t
$$
integrating we get
$$
Y_t = Y_0 + \beta\left(\mathrm{e}^{\alpha t} - 1\right) + \int_0^t\mathrm{e}^{\alpha s}dB_s
$$
or
$$
X_t = x_0 + \beta\left(1-\mathrm{e}^{-\alpha t}\right) + \int_0^t\mathrm{e}^{\alpha (s-t)}dB_s
$$
Comment: Thank you very much Chinny84. Does $X_t$ is a Ornstein-Uhlenbeck process? I have just found this on wiki: http://en.wikipedia.org/wiki/Ornstein%E2%80%93Uhlenbeck_process
Comment: Yes you are correct, but with volatility set to 1.


grep start and end time from log file- AIX

Question: Log file looks something like below
Process Beginning -  2016-04-02-00.36.13
Putting Files To daADadD for
File will move to /sadafJJHFASJFFASJ/
Extract Files :-/ASFDSHAF_ABC_2016-04-02.csv
/ASFDSHAF_ABC.2016-04-02.csv /
ASFDSHAF_ABC.2016-04-02.csv /ASFDSHAF_ABC.2016-04-02.csv /
Process Ending -  2016-04-02-00.36.36
Process Beginning -  2016-04-02-10.01.20
Putting Files To daADadD for
File will move to /sadafJJHFASJFFASJ/
Extract Files :-/sdshsdhsh_cvb.2016-04-02.csv
/sdshsdhsh_cvb.2016-04-02.csv /sdshsdhsh_cvb.2016-04-02.csv
Process Ending -  2016-04-02-10.01.21
There is multiple entries of pattern / Process Beginning -  2016-04-02/ /Process Ending -  2016-04-02/
how do I find entry or block which has pattern /ABC_2016-04-02.csv/ in between
Comment: Edit your question to show the expected output given that input. If you need to search for some pattern in a block, make sure to include both blocks that do AND blocks that don't match that pattern in your sample input/output.
Comment: Again (and for the last time) - **Edit your question to show the expected output given that input**. Also use the `{}` editor button to make your blocks of data or code appear as-is and get rid of any formatting you've tried to add (e.g. making parts bold with `**`s). Make your input and output appear in your question the same as they do in your real files so we can test a potential solution against it.
Answer: You can do it with sed (at least with GNU sed 4, sorry no AIX sed to test with):
# read complete block into hold space
/Process Beginning/,/Process Ending/ {
    H
}

# "test" for csvfile in the block
/Process Ending/ {
    # get hold space (i.e. complete block)
    x
    # if s did a "substition" (i.e. csvfile occured in the block): print
    s/ASFDSHAF_ABC.2016-04-02.csv/&/p
    # clear hold space for next block
    s/.*//
    h
}

Say your log file is grplog.log and the script is grplog.sed then run the script like this: sed -n -f grplog.sed grplog.log.
Explanation:

The script reads all lines in your processing block into the hold space in the first part.
The second part triggered on the Process Ending line uses the p flag of the s command: if a substitution was made, print the new pattern space. Due to the use of & old and new pattern space are the same.
Comment: will it work when we multiple occurrence for process Beginning and ending??
Comment: @Sushma Please provide example lines from your log file for testing.
Comment: @Sushma What do you mean by *multiple occurrence for process Beginning and ending*? Several blocks? I tested the script with several blocks. If it does not work for you, please edit the question and provide more lines in the example.
Comment: Could you please give me full scipt
Comment: @SushmaBhandary the script `grplog.sed` is what is in the gray area in my answer. I use sed version 4.2.2 on Linux and for me the script seems to work.  After your edit, I replaced csvfile in line 11 with your new filename.


How to populate list as class object?

Question: How do you populate a list as a class object? For example, this does not work:
[DataContract]
public class JsonReviewFormFields
{
    [DataMember]
    public PersonalDevelopmentPlan personalDevelopmentPlan { get; set; }
}

public class PersonalDevelopmentPlan
{
    public List<ShortTerm> shortTerm { get; set; }
    public List<LongTerm> longTerm { get; set; }
}

public class ShortTerm
{
    public string workRelated { get; set; }
    public string structured { get; set; }
    public string informal   { get; set; }
    public string reviewDate { get; set; }
}

public class LongTerm
{
    public string workRelated { get; set; }
    public string structured { get; set; }
    public string informal { get; set; }
    public string reviewDate { get; set; }
}

This is controller action:
public JsonReviewFormFields GetReviewForm()
{
    PersonalDevelopmentPlan personalDevelopmentPlan = new PersonalDevelopmentPlan();

     List<ShortTerm> _itemsShort = new List<ShortTerm>();
    _itemsShort.Add(new ShortTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
    jsonReviewFormFields.personalDevelopmentPlan.shortTerm =  _itemsShort;

    List<LongTerm> _itemsLong = new List<LongTerm>();
    _itemsLong.Add(new LongTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
    jsonReviewFormFields.personalDevelopmentPlan.longTerm =  _itemsLong;

    return jsonReviewFormFields;
}

The code crashes at
jsonReviewFormFields.personalDevelopmentPlan.shortTerm =  _itemsShort;

It's probably a basic object orientated error. How do you populate the list?
Comment: can you add the crash log or error message?
Comment: Where is `jsonReviewFormFields` defined?
Answer: You are not instantiating it, you have to instantiated the type first:
jsonReviewFormFields.personalDevelopmentPlan = new PersonalDevelopmentPlan();

and then set property of it:
jsonReviewFormFields.personalDevelopmentPlan.shortTerm =  _itemsShort

before that you also have to instantiate main class which i don't see in your controller action anywhere :
JsonReviewFormFields jsonReviewFormFields = new JsonReviewFormFields();

Comment: JsonReviewFormFields jsonReviewFormFields = new JsonReviewFormFields();
Comment: Ehsan, forgot to include in the code above. All is now good, ta

How to populate list as class object?


Search pdf content in google storage

Question: could you help me with the following? How can I search pdf words hosted on google cloud storage?
example: pdf1, pdf2, pdf3 hosted on storage.
Look for the "father" word in all documents.
Thanks
Answer: Google Cloud Storage doesn't allow to check what's inside a document, it's just a Storage service. If you want to search for words in your hosted documents you have to download them to your local machine, Google Compute Instance, Cloud Function, etc. and do the pdf processing there with your tool or language of choice.

Search pdf content in google storage


Laravel - Função no Controller

Question: Estou com uma dúvida em relação ao Laravel e um projeto meu sendo essa a função que recebe as informações de um formulário na qual o administrador escolhe o evento e os usuarios (multiple select) para gerar o certificado (armazenado na tabela certificados - colunas id / id_usuario / id_evento)
public function gerar(Request $request)
{
    $id_evento = $request->id_evento;
    $id_participantes = $request->input('participantes');

    foreach ($id_participantes as $id)
    {
        if($this->existeCertificado($id, $id_evento))
        {
            $certificado = new Certificado();

            $certificado->id_evento = $request->id_evento;
            $certificado->qualidade = $request->qualidade;
            $certificado->id_usuario = $id;
            $certificado->save();
            $pusher = App::make('pusher');

            //default pusher notification.
            //by default channel=test-channel,event=test-event
            //Here is a pusher notification example when you create
            //a new resource in storage.
            //you can modify anything you want or use it wherever.
            $pusher->trigger('test-channel',
                             'test-event',
                            ['message' => 'Certificado $evento->titulo_evento !!']);

            return redirect('certificado')->with('status', 'Certificados gerados!');
        }
        else
        {
            return redirect('certificado')
                       ->with('status', 'Erro ao gerar alguns certificados!');
        }
     }
}

Essa é a função que busca no meu banco de dados se o usuário (id_usuario) já possui algum certificado no evento (id_evento):
public function existeCertificado($id, $id_evento)
{
    $existeCert = DB::table('certificados')
             ->where([['id_usuario', $id], ['id_evento', $id_evento]])
             ->get();
    if($existeCert == NULL)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

Caso o usuário já tenha um certificado no mesmo evento, não é gerado outro se não tiver, é então gerado.
O problema é que de qualquer forma (se já houver registro do usuario no evento ou se não houver) o sistema cai no else (erro ao gerar).
Comment: A principio o codigo parece estar correto, ja tentou dar um dd() (var_dump do laravel) nas variaveis recebidas na função antes de fazer a consulta para verificar se estão com valores corretos ou vem vazios ou em forma de array?
Comment: Todas as vezes que dois ou mais partipantes forem escolhidos o seu código vai bugar ... !!! porque ele faz um foreach e executa um redirect ele não executa todo o for ... Você observou esse detalhe?
Answer: O teu código está retornando sempre TRUE pelo fato de que o método get() do Eloquent retorna uma coleção e não um valor booleano. Ou seja, mesmo que não existam registros que satisfaçam a tua consulta o retorno vai ser sempre TRUE. Tu deves verificar se esta coleção está vazia ou não para que tua lógica faça sentido.
Comment: Nesses casos é melhor usar o `count()` no lugar do `get()`.
Comment: Concordo que o ideal seja usar o `count()`, mas minha resposta foi a explicação do PORQUE não está funcionando a lógica dele.
Comment: Com certeza, eu coloquei pra ajudar na resposta para o Gabriel e você pode até editar a sua resposta para colocar um exemplo usando o `count()`. ;)
Answer: Creio que apenas com a inserção da função firstOrNew resolve o problema.
        $certificado = certificado::firstOrNew(['id_evento' => $request->id_evento]);
        $certificado->id_evento = $request->id_evento;
        $certificado->qualidade = $request->qualidade;
        $certificado->id_usuario = $id;
        $certificado->save();
        $pusher = App::make('pusher');

Comment: Alterei a resposta e retirei o link.
Answer: public function existeCertificado($id, $id_evento)
{
    $existeCert = DB::table('certificados')
             ->where([['id_usuario', $id], ['id_evento', $id_evento]])
             ->first();

    if(is_null($existeCert))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

Se você substituir o get() por first() o laravel vai te retornar o valor encontrado, ou um null, caso não tenha.. só de uma olhadinha na doc, acho que pode ser mais interessante usar o Eloquent, do que o query builder assim nestes casaso, como está fazendo.
Também seria legal fazer a comparação usando a função is_null() php, que serve exatamente para informar se um valor é nulo ou não:
is_null() php: http://php.net/manual/pt_BR/function.is-null.php
first() - Laravel: https://laravel.com/docs/5.6/queries
Answer: Refatorei o seu código e consegui enxugar os 2 métodos em apenas 1, espero que te ajude.
public function gerar(Request $request)
{
    $fields = $request->all();

    foreach ($fields['participantes'] as $value) {
        $hasEvent = Certificado::where('id_usuario', $value)->where('id_evento', $fields['id_evento'])->first();
        if ($hasEvent) {
            return redirect('certificado')->with('status', 'Erro ao gerar alguns certificados!');
        }

        $certificado = Certificado::create($fields);
        $pusher = App::make('pusher');

        // Obs.: não sei de onde você tirou essa variavel $evento pq no seu código não tem ela instanciada
        $pusher->trigger('test-channel',
                             'test-event',
                            ['message' => "Certificado {$evento->titulo_evento} !!"]);

        return redirect('certificado')->with('status', 'Certificados gerados!');
    }
}

Laravel - Função no Controller


How to set Linux capabilities on docker swarm mode service invocations

Question: I'm looking into the notion of vault running under swarm (1.12.x).
A single container would be started with:
docker run -d --cap-add IPC_LOCK -p 8200:8200 -p 8215:8125 --name vault --volume /vagrant/vault:/vagrant/vault vault server -config=/path/to/vault.hcl
but when I want to run this in swarm as a service, there appears to be no way to specify the IPC_LOCK capability, in order to lock down encrypted swapping for the vault service in this case.
How can I set --cap-add flags when starting a swarm mode service with the docker service create command?
Answer: As of 20.10, this is available from docker service create with --cap-add:
$ docker service create --help
...
      --cap-add list                       Add Linux capabilities
      --cap-drop list                      Drop Linux capabilities

Or in a compose file used with docker stack deploy with the same syntax from the version 2 file:
version: "3.9"
services:
  app:
    image: your-image:tag
    cap_add:
    - CAP_NAME1
    - CAP_NAME2
    cap_drop:
    - CAP_NAME3
    - CAP_NAME4

[ Original answer from before 20.10 ]
It's currently not supported, but Docker is working on a solution. The logic behind not including the --cap-add option blindly is in a large cluster, there could be security concerns of a manager submitting containers with added privileges to a worker. The worker may trust running secure containers that can't access the host, but not want to allow remote root access to the host via a privileged container.
Discussion on this is over on github at:
https://github.com/docker/docker/pull/26849#issuecomment-252704844
https://github.com/docker/swarmkit/issues/1030
https://github.com/docker/swarmkit/pull/1722
https://github.com/moby/moby/issues/25885#issuecomment-557790402 and https://github.com/docker/cli/pull/2199
Answer: All of the other answers here are old. Docker 20.10.0 and newer now supports specifying capabilities for Swarm services via the docker service command line and the Docker Stack YAML file format.
On the command line, you just specify --cap-add [capability] or --cap-drop [capability].
And here is an example for adding a capability in a Docker Stack YAML file:
version: "3.9"
services:
  your-service:
    cap_add:
      - CAP_SYS_ADMIN

Comment: The main pull request confirms this information https://github.com/docker/cli/pull/2687 but unfortunately, the official docker-compose file reference doesn't document this improvement yet and still indicates that cap_add and cap_drop are not supported in swarm mode.
Comment: This is good to know, but also keep in mind that 19.03.x is still widely used and will be for many years due to its use in various long-term supported distros.
Comment: I'm interested to know if I should - at some point - change the 'correct answer' when the same q is answered with a more recent version of the software in mind (that 'most' people use)
Answer: I found a solution to solve the problem and I can use cap_net_admin in swarm mode.
You can modify the runtime source code to add the capabilities that you need (it will be a local default setting).
For example I added the CAP_NET_ADMIN to my runtime (used nvidia-container-runtime)
wanyvic/nvidia-container-runtime.
After that I rebuilt it, started a container (use swarm mode), input: capsh --print and  CAP_NET_ADMIN  can be found:
root@25303a54ebb3:/# capsh --print
Current:=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_admin,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap+eip
Bounding set =cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_admin,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap
Securebits: 00/0x0/1'b0
 secure-noroot: no (unlocked)
 secure-no-suid-fixup: no (unlocked)
 secure-keep-caps: no (unlocked)
uid=0(root)
gid=0(root)
groups=

But this method is not good.
I also can't set cap_add or cap_drop in docker-compose.yml, but I can't find a way to solve it.
Answer: See https://hub.docker.com/r/ixdotai/swarm-launcher
That repo is based on this comment/idea: https://github.com/moby/moby/issues/25885#issuecomment-573355530

Depending on the use case, a workaround is to bind-mount /var/run/docker.sock from the swarm host(s) to the service, then run docker run --privileged ... or docker run --cap-add ... from the service for executing your actual privileged commands. (You'll have to install docker cli in the image for the service.) The innermost container that you docker run in this way will have the privileges/capabilities of the swarm host rather than of the service, and the service just becomes a thin container layer.


Problema ao utilizar jQuery UI no ASP.NET MVC

Question: Estou tentando adicionar a "ComboBox Autocomplete" do jQuery UI no meu projeto ASP.NET MVC, mas ele diz que a função widget não é uma função.

jquery-3.1.1.min.js: 2 jQuery.Deferred exception: $.widget is not a function TypeError: $.widget is not a function

Estou seguindo os passos do exemplo do site do jQuery (Tutorial do jQuery UI), a diferença é que extraí o scripts para arquivo externo e o css também.
Eu já vinculei os scripts necessários para utilizar essa função, que está na seguinte ordem:
<code><link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/jquery-ui.css")">
<link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/app/cliente/meu-css.css")">

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-3.1.1.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-ui.min.js")"></script>

<script type="text/javascript" src="@Url.Content("~/Scripts/app/cliente/meu-script.js")"></script>
</code>
Eu refiz esse exemplo no bloco de notas e deu certo, mas no projeto MVC não deu.
Comment: Você tem algum problema ao carregar o JS que tem a função widget, confere os JS carregados na pagina para saber qual não foi carregado
Comment: Ricardo, todos foram carregados, inclusive o jquery-ui.js que contém a função. Isso que não entendo. :(
Answer: Consegui achar o problema!
Mesmo o jQuery sendo carregado primeiramente, o meu script não encontrava a função, pois eu não estava passando o '$' no parâmetro
da função do meu script:
<code>(function($){
    $(document).ready(function(){
        $.widget("custom.combobox", {
        ...
    });
})();
</code>
Ainda não entendi o porque, nesse caso, o meu script não conseguir enxergar o jQuery sem ter que passar o '$' no parâmetro , sendo que quando fiz esse mesmo exemplo no bloco de notas não precisou fazer isso.


How to assign a user a title based on the number of created nodes?

Question: I want to set up a system where a user is given a title based on how much content they have created/published. So, for instance, if the user has published:
0 nodes  - Noobie
1+ nodes - Poster
10+ nodes - Frequent poster
20+ nodes - Super Poster
50+ nodes - God`

I'm wondering if there is a way to implement this in a Drupal site. I can think of a way to do it using database queries and a computed field, but I'm wondering if there might be a more efficient way to go about doing it.
Answer: I doubt there is a module for this, but hey. Do not let that bring you down, it's actually a great idea for a custom module! If you have a bit of patience, Drupal is very easy to learn once you get past the initial learning curve.
If you need a start, the module developper section and the create a module page on Drupal are great place to start.
There are many, many ways you could do this, but to start I would probably create a small module. Imagine it's called super_usernames, for the purpose of this post. I would just create a folder in sites/all/modules called `super_usernames. That folder would need to  contain only 2 files:
super_usernames.info and super_usernames.module. The info file is very easy:
name = Super Usernames
description = Gives special credits to usernames depending on number of posts.
core = 7.x
files[] = super_usernames.module

The module file would need at the minimum just one hook to be defined.  Hooks are just plain old php functions that use a simple naming convention in order to be executed by Drupal automatically.
The hook you need here is hook_node_view. Basically you want to add :
/*
 * Implements hook_node_load
 */
function super_usernames_node_view($node, $view_mode){
  $supported_node_types = array('page', 'article', 'blog'); // Supports default content types
  if (in_array($node->type, $supported_node_types) {
    // query to get number of nodes this user has published
    $result = db_query("SELECT count(nid) as nodecount from {node} WHERE uid = %d", $node->uid);
     $row = db_fetch_object($result);
     $node_count = $row->nodecount; // Easier to read
     switch ($node_count){
       case $node_count >= 50:
           $node->super_username = "God";
         break;
       case $node_count >= 20:
          $node->super_username = "Super Poster";
         break;
       case $node_count >= 10:
          $node->super_username = " Frequent Poster";
         break;
       case  $node_count >= 1:  // same as > 0, but who cares...
           $node->super_username = "Poster";
         break;
       default:
           $node->super_username = "Noobie";
     }
  }
}

Now. After doing this, all your nodes should contain the dynamic value of the number of nodes posted by that node's author.  This would be added on the fly on every page load from content-types articles, and pages.
You still need to have it displayed somewhere, though! This is where you would ideally create a sub-theme (so as not to hack a base theme). But for the purpose of this post, we will simply modify one file: node.tpl.php.
Check the theme you are using, by default it is bartik but the procedure is mostly the same whatever theme you are using.
Go into your themes/bartik/templates directory, open the node.tpl.php file.  Locate where you want to add the super username in the html, and add this code snippet:
<?php if ($node->super_username): ?>

    <?php print $node->super_username; ?>

<?php endif; ?>

Now. One last step, you may need to clear the cache for changes to take effect. Devel module makes it easy, Drush makes it even easier. After this, you should have your super usernames dynamically shown on all the content-types defined in the supported_node_types array.
Hope this doesn't sound too complicated, it's actually quite trivial when you go through the process a few times.  Feel free to message me or repost here if you need any help.
Happy coding, cheers!

PS: This code has been slapped up from memory, nothing is tested but should be pretty close to a fully working example. Your mileage may vary, there may be typos in there.
Comment: I haven't gotten a chance to try and implement this yet, so I'll get back to you when I do. Seems like a great option though! Thanks for writing it our. However, I'm wondering if there is a way to make this information fieldable -- so that I can make it appear within Views and possibly modify its positioning within a node using Display Suite -- or is this created as a value that can only be displayed by modifying the node.tpl.php?
Comment: Also, do you know if there is anything that needs to be changed to limit the count to only nodes of a certain type, or to allow this to appear in a user's profile page?
Comment: If you look at the code, the first line in the function sets an array `$supported_types` that holds the content types you want a count on.  As for having this data fieldable, of course it is possible but then the data would be "static", that is instead of being calculated on every node load would be calculated once, at node creation.  If one takes this approach,  the field would need to belong to the user, not the node.  Consider this: User creates a node that has  field populated to newbie status. User creates 50 nodes. The original node still contains the original .
Comment: A view uses templates that can be over-ridden just like the node.tpl.php.  Even if you use a field, attached to the user, every time user creates a node you would need code to update the user profile on every node save.  However you look at it, you need custom code somewhere and this simple module I posted is truly the most elegant and simple way I could think of. Simplicity and elegance is what I aim for, so that anyone looking at this can see at a glance what is happening. Of course, there can be improvements like returning a render array, but I kept it simple.  Good-luck friend, cheers!
Comment: @stefgosselin : I know, nearly years later now, but do you still "doubt" (as in your 1st paragraph)? Refer to my answer I just added to understand why I ask ... Nevertheless: interesting answer (to consider for integrating in the **Goals** module also ... some day)
Comment: This is the most straightforward way to do it.
Answer: A general-purpose module for use cases like this is User Points, which integrates with Rules.  You could use rules to automatically add points when a user's content is published.  You could even make some content types more valuable than others.
As for the titles, there is the User Badges module for D6, although there has been no official release for D7.  In the meantime, depending on how complex your setup is, you could add a text select field to the user profile and use Field Permissions to forbid users from editing it.  Then, you could use Rules to automatically set the data value at each threshold (1, 10, 20, etc.)
Comment: Your first paragraph could be part of the original specs of the **Goals** module (refer to my answer I just added for details). Maybe you should edit your 2nd parg about D7-status these days (there is an official release now)? Quick extra question (curiosity) about the data value at each threshold: how would you "keep track" of its progress, or would you just recalculate the value any time a node would get published?
Answer: Another option to the already good suggestion of using the User Points + Rules modules, would be the Achievements module.
This is more geared towards mimicking the idea of gamification found on sites such as this, but will definitely give you full control if you're up for calling a few API functions.
Comment: For this task, I think I might go with the custom module suggested by stefgosselin. However, I'm definitely going to take a look at the Achievements module for other aspects of the site. Seems like a more all-encompassing way to take care of the task of user points/badges from one place. I'm new to writing modules, though, so I'm not at all familiar with making API calls. I see that there are a couple pages suggested on the module's page, but are there any other resources that you might suggest for getting started on learning the process?
Answer: The Goals module is yet another solution to answer this question.
Goals and Tasks are implemented using fieldable entities. So you can customize Goals via "Manage Fields" and/or "Manage display". E.g. to add your own fields, such as:

descriptions.
images.
links to external resources.
etc.

Head over to the Goals video which includes:

a general introduction to the module.
a demonstration to install, configure and use it.
samples of how it uses the Rules modules to do its magic (i.e. to track the progress of a user to achieve the various roles.

Using the Goals Extras sub-module it integrates with the User Points module also.
Measuring the number of nodes published by a user (as in your question here), would really be like a getting started with this module: each of the 5 examples would become "a" Goal, whereas the actual "Tasks" would consists of just "publishing a node".
Even though your question (requirements) doesn't seem to include that, you could take it a bit further. E.g. by only taking into account 1 published node per day (so a user publishing 3 nodes on the same day would only count for 1).
All this can be done with site building features only (no custom code involved), though hooks are available to integrate it in custom coding also).
For more details, refer to its Community Documentation. For some details about how it differs from the Achievements module, refer to What is the difference with the Achievements module, which states:

The Goals module is built around using the admin interface configuration. Plus, goals and tasks within the Goals module are fieldable entities, so you have the flexibility to add additional fields and incorporate these entities into views.
I can't speak definitively for the Achievements module, but my best understanding is that it relies heavily on custom coding to handle many of the functions.

Disclosure: I'm the maintainer of this module.
Comment: @herci: don't worry, nobody knows all of the +17K modules available today, right? I only know about 500 to 1000 of them (most of them only by name) ... Also, if you're interested in another "[interesting module](https://www.drupal.org/project/answers)", then use the "Try out a demonstration" link on that project page (and be aware I became the new maintainer of it recently also).
Comment: Why I didn't know these kind of modules before? :( Thanks for sharing it and of course maintaining it :)


Filter values out of a 3D matrix

Question: I am almost sure there has to be a MATLAB way for this, but I don't have much experience:
width=length(hsvSecond(:,1,1));
height=length(hsvSecond(1,:,1));
for i=1:width
    for j=1:height
        if(hsvSecond(i,j,2)>0.35)
            hsvSecond(i,j,1)=0;
            hsvSecond(i,j,2)=0;
            hsvSecond(i,j,3)=0;
        end
    end
end

So, basically, if the hsvSecond(i,j,2) value is bigger than a number, I want to put hsvSecond(i,j,:) to zero.
Answer: Here is a simple one-liner:
hsvSecond(repmat(hsvSecond(:,:,2) > 0.35, [1,1,3])) = 0;

or this possibly more efficient alternative (although some rudimentary test suggest otherwise which does surprise me):
hsvSecond = bsxfun(@times, hsvSecond(:,:,2) <= 0.35, hsvSecond)

Some comments on your code though:
width=length(hsvSecond(:,1,1));
height=length(hsvSecond(1,:,1));

Should be
width = size(hsvSecond,1)
height = size(hsvSecond,2)

and
hsvSecond(i,j,1)=0;
hsvSecond(i,j,2)=0;
hsvSecond(i,j,3)=0;

could have been
hsvSecond(i,j,:)=0;

Filter values out of a 3D matrix


Can I use DEFAULT constraint with multiple values in MySQL? Can I add more default values in the example below?

Question: <code>CREATE TABLE Employee (

    Code int NOT NULL,
    Last_Name varchar(25) NOT NULL,
    First_Name varchar(25),
    Age int(2),
    City varchar(30) DEFAULT 'KAJI'

);
</code>
Comment: What do you mean? DEFAULT with multiple values? Please add some details to your question as it is very much unclear.
Comment: What do you mean? Do you want to have multiple default value option for a single column? If so no only one default value per column is possible
Comment: DEFAULT is not a constraint..
Answer: If I am following you correctly then you are talking about the following line:
<code>...
City varchar(30) DEFAULT 'KAJI'
...
</code>
It is not allowed to provide multiple default values for a single column.
If multiple default values are allowed then which value will be used as the default(How DB will decide it)? That's why it is very obvious that there should be only one default value. I Hope, I am clear.


Adicionar um valor em um objeto JSON

Question: Como eu poderia adicionar uma cadeia de valores em um objeto JSON?
Por exemplo:
var a = 12;
var b = 3;

var obj = {
 c: 11,
 d:22
}
console.log(obj);

Como eu poderia aplicar a e b, dentro da minha variável obj para que se tornem parte deste objeto JSON?
Answer: vcoê pode adicionar uma propriedade ao objeto obj com os valores de a e b, mas note que ao faze-lo, você estará atribuindo uma copia do valor, então modificações à na variavel não serão refletidas no obj e vice-versa.

var a = 12;
var b = 3;

var obj = {
 c: 11,
 d:22
}

obj.a = a;
obj.b = b

console.log(obj);

a = 17;

//obj.a continua com o valor 12
console.log(obj);

se precisar que alterações nas propriedades no objeto sejam refletidas nas variaveis e vice-versa, você deve definir um get e set para a propriedade do obj

var a = 12;
var b = 3;

var obj = {
 c: 11,
 d:22
}

Object.defineProperty(obj, "a", {
  get: function () { return a; },
  set: function (value) { a = value; },
  enumerable: true
});

Object.defineProperty(obj, "b", {
  get: function () { return b; },
  set: function (value) { b = value; },
  enumerable: true
});

console.log(JSON.stringify(obj));

a = 17;

console.log(JSON.stringify(obj));

obj.a = 12;

console.log(a);

agora se você tiver dois objetos, pode usar o método Object.assign para meclar os dois ou mais objetos.

var base = { a: 12, b: 7 };
var objA = { c: 16, d: 4 };
var objB = { e: 13, f: 9 };

Object.assign(base, objA, objB);

console.log(base, objA, objB);

objA.c = 17;

//base.c continua com o valor 16
console.log(base, objA, objB);
Comment: sim, você terá que fazer isto para cada variavel. porém existe uma forma de meclar objetos usando o `Object.assign`, adicionei um exemplo na resposta.
Comment: então caso eu tenha n valores, eu teria que realizar um laço de repetição para setar cada valor?
Comment: vc é foda cara, muito obrigado pela ajuda
Answer: var a = 12;
var b = 3;

var obj = {
 c: 11,
 d:22
}

obj["a"] = a;

Segue exemplo: https://jsfiddle.net/oo6fodmd/

Adicionar um valor em um objeto JSON


Prove if $C$ and $D$ are non empty disjoint closed subsets of $M$ such that $C$ or $D$ is compact, then $d(C,D)$ > 0

Question: Prove if $C$ and $D$ are non empty disjoint closed subsets of $M$ such that $C$ or $D$ is compact, then $d(C,D)$ > 0
In $R$, two closed subsets are compact and their distance is definitely greater than 0 as long as they're disjoint, how can I generalize this any Metric Space?
Answer: Assume $C$ is compact. Take a covering of $C$ by balls $B_\rho(x)$ such that
$x$ is in the complement of $D$ and also the ball $B_\rho(x)$ is in the complement of $D$. This is possible as the complement of $D$ is open.
Now you can select a finite number of such balls covering $C$. These balls do not touch $D$. Thus the distance between $C$ and $D$ is larger than the smallest radius of this finite number of balls, which is positive.
Answer: Suppose that $d(C,D)=0$ and that $C$ is compact. So there exists a sequence of elements $c_n\in C$ such that $d(c_n,D)\to 0$.
Because $C$ is compact, $\{c_n\}$ admits a convergent subsequence, say $\{c_{n_k}\}$, that converges to $c\in C$. But then
$$
d(c,D)=\lim d(c_n,D)=0.
$$
That is, there exists a sequence $\{d_n\}$ in $D$ with $d_n\to c$. As $D$ is closed, $c\in D$. So $c\in C\cap D$, contradicting the fact that $C$ and $D$ are disjoint.
In conclusion, $d(C,D)>0$.
Comment: Perhaps edit out the statement "Because $C$ and $D$ are compact..." and start off with "Because either $C$ or $D$ is compact ..."
Comment: Oh, I missed that. I have to change the argument, then. Thanks for noticing.


Generate "table" with

Question: I'd like generate the representation below by
. The constraints :

the full size = 100%
the first + second column = 50%, the 3rd + 4th column = 50%
the first column is smaller than the second, the second take "the rest of the place", same for column 3 and 4 :)
the 3rd lines, combines 2 cells
the last line combine 4 cells
don't worry about the color :)

PS : no debate table vs div ;-)
Comment: If what you're actually going to display in these "table cells" is statistics, lists or other typical tabular data, you should indeed use a `table` and not a bunch of `div`-elements. Of course, using `div` could be perfectly legitimate as well.
Comment: Would divs with `display: table-cell` be considered cheating?
Comment: What kind of data are you trying to represent with this structure?
Comment: How about posting your HTML and CSS and telling us where you get stuck?
Comment: It's possible, yes. But you want to 'generate the representation below by `div`'? Where's the `div` coming from? As @Alec says, your html (and css) would be a great help in answering the question.
Comment: I posted a Table Answer (but got a -5) because it wasn't what the user wanted (though I'm adding it as a comment to my answer)
Answer: Here is my proposed markup:

(1)

(2)

(1)

(2)

(3)

(3)

  (4)

And styles:
/* structure */
.row { clear: both; overflow: hidden; }
.col { float: left; }
.half { width: 50%; }
.narrow { width: 30%; }
.remainder { float: none !important; overflow: hidden; }

/* skin: just for demo */
.row { text-align: center; border-bottom: 1px solid #999; }
.half { background: #fcc; }
.narrow { background: #ccf; }
.remainder { background: #cfc; }

The first two rows are split into half. In each half are two cells: the first is called narrow and is floated. I put 30% on the width for this one just for the demo (note: that's 30% of the half of the row). The other column is called remainder and is not floated. It uses overflow to set its own rendering context, which means it fills the block to the right of the floated column.
You can have more floated columns (left or right), but only one remainder.
I put it up on jsfiddle: play with it.
Comment: I definitely like your CSS styling better than mine :)
Answer: Sorry for the misread, my previous Answer was using TABLE when you wanted to use DIV.
Also, note that if you want to use Borders, you have to offset the width percentage. (The other answer on this page may not display properly)

1

2

3

4

1 (50% width)

2 (50% width)

1 (100% width)

Comment: This is how I did it using a TABLE in my first downvoted answer
1234
1234
something something
something
 (This is simply for reference since I deleted my other answer as it was getting downvoted)
Comment: And using TABLES makes it easier to add borders without having to adjust width percentages or other style attributes like you have to do with DIV's
Answer: Here, try this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

The style is in the header, but it really should be in its own CSS file.
Comment: just a heads up but the borders throw off the alignment of your cells on my browser.
Comment: As a side note: tables are not always bad. They get a bad rep due to people using them inappropriately for layout, but if you are displaying tabular data, you really should be using tables. They're easier for older screen readers to work with (508 compliance huzzah!)
Comment: @KennyCason: Borders can be a problem, cross-browser. If I were to really, really do this, it would be quite a bit longer, with lots of border-lefts and firsts.
Comment: right. I was just pointing it out for the sake of the question asker, that way he would at least know why it may not work for him. :P
Comment: Of course it's just for the demo: borders don't work well with percentages and `width:49.9%` is just praying that it will fill the width without overflowing... in reality I'd put another div inside each column for the borders instead.

Generate "table" with


Add image to actionsheet

Question: How to add screenshot of tableview to first "action" in UIAlertController?
I tried to do it like that
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let action = UIAlertAction(title: NSLocalizedString("Share routine", comment: ""), style: .default, handler: { _ in
})
action.setValue(image, forKey: "image")
actionSheet.addAction(action)
actionSheet.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil))
UIApplication.topViewController()?.present(actionSheet, animated: true, completion: nil)

Comment: Don't. That's hacking. Instead use a custom view/viewcontroller that will mimic a UIAlertController in ActionSheet. `UIAlertController` shouldn't be subclassed/hacked.
Comment: I don't see any problems in your code. Are you sure, you take screenshot correctly?
Comment: Please share screenshot...
Comment: @LoraKucher - just because you _can_ do it that way, doesn't mean you _should_. Apple could change `UIAlertController` and break your code at any time, Rather than just copying some code you found on SO, take time to do it correctly.
Answer: I tried your code, and found some mistakes
First of all, instead of image use
image.withRenderingMode(.alwaysOrigin)

And if you want to place your image to certain position use imageView
Answer: action.setValue(myImage.withRenderingMode(.alwaysOriginal), forKey: "image")

I need add .withRenderingMode(.alwaysOriginal) <- this for correct image. Thanks all for help

Add image to actionsheet


How to add only the postal code field to the user registration page?

Question: I have a custom template file successfully rendering the user account creation page. I am using the Location Module, which adds a field (which appears to be a field group) to the user. I want to add only the postal code field (zip Code) to the user registration page.
template.php code:
    function responsive_bartik_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'responsive_bartik_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'responsive_bartik_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'responsive_bartik_preprocess_user_pass'
    ),
  );
  return $items;
}

user-register-form.tpl.php code:

<?php
     print render($form['account']['name']);
     print render($form['account']['mail']);
     print render($form['account']['pass']);
     print render($form['captcha']);
     print drupal_render($form['actions']);
     print render($form["form_build_id"]);
     print drupal_render($form['form_token']);
     print drupal_render($form['form_id']);
?>

   Forgot Password

Already have an account? Log in

Answer: Use this module Postal Code they can allow to only add postal code in user page

A very minimal D7 Postal Code (ZIP Code) field with validation for one
  country or a combination of countries
Comment: but postal code doesnt tie into other stuff, like location module or drupal commerce, or search api in the same way. Also, other fields like a detailed address will be needed later on, once user creates their account.
Comment: then you can use address field module for this purpose
Comment: I tried installing that module, but there is no configuration for it. Do i need to other modules to get it to work?
Comment: what you mean there is no configuration do you used devel module
Comment: Ok so with the Address Field Module, What code do i Type to only get the postal code on the account creation page?
Comment: add a in user registration page and get field value using devel module after that render it on your tpl file
Comment: Here is my devel line of the page. Please, in detail tell me what i would add to my custom template. field_address (Array, 17 elements)

    #type (String, 9 characters ) container
    $...['content']['system_main']['field_address']['#type']