text:
Q: Passing data from model to print into tcpdf in codeigniter I'm trying to create a pdf file with some data in that I get from a query, the pdf creator is in the controller (TCPDF).
My storyboard :
I am using codeigniter to develop my php application. In my view, there is a table that every row have a button to create a pdf from information its row. I can preview it in modal bootstrap.
Now , I am confused how to passed that information to pdf (TCPDF).
Should i using GET or somrthing like that in my Controller ?
Or in modal ?
This is my view

  <?php
    $no = 1;
    foreach($data_request as $data) {
  ?>

        <?php echo $no++.". ";?>
        <?php echo $data['id_request'];?>
        <?php echo "$name"; ?>
        <?php echo date ("d-m-Y, H:i ",strtotime($data['time_start']));?>
        <?php echo $data['keluhan'];?>
        <?php echo $data['status_request'];?>
        <?php echo date ("d-m-Y, H:i ",strtotime($data['close_request']));?>

                     Close

                <a class="btn btn-success" href="#" id="print" req_id="<?php echo $data['id_request']; ?>">
                     Print

   <?php } ?>

//This is my modal bootstrap preview :

            <button type="button" class="close" data-dismiss="modal">×</button>

Print Preview

             <?php $id= $data['id_request'];?>
             <a href="<?php echo base_url().'control_closing/generate_pdf/id'; ?>" class="btn btn-primary">Jadikan PDF
            Close

This is my controller
public function generate_pdf($idRequest){
    $this->model_request->selectOneRequest($idRequest);
    $this->load->library("TC_PDF");
    $pdf = new TC_Pdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    // set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Dzil');
    $pdf->SetTitle('Form Perbaikan / Permintaan');
    $pdf->SetSubject('TMS/DEPT/IT/06');
    $pdf->SetKeywords('TCPDF, PDF, form, perbaikan, Permintaan');

    // set default header data
    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);

    // set header and footer fonts
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    // set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    // set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    // set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    // set some language-dependent strings (optional)
    if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
        require_once(dirname(__FILE__).'/lang/eng.php');
        $pdf->setLanguageArray($l);
    }

    // ---------------------------------------------------------

    // set font
    $pdf->SetFont('helvetica', '', 12);

    // add a page
    $pdf->AddPage();
    $pdf->Ln(8);

    $pdf->Cell(30, 5, 'Nama', 0, 0, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell( 2, 5, ': ', 0, 0, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell( 0, 5, '$data_pdf[nama]', "B", 1, 'L', 0, '', 0, false, 'T', 'C');

    $pdf->Cell(30, 5, 'Departement', 0, 0, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell( 2, 5, ': ', 0, 0, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell( 0, 5, '', "B", 1, 'L', 0, '', 0, false, 'T', 'C');

    $pdf->Cell(30, 5, 'NIK', 0, 0, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell( 2, 5, ': ', 0, 0, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell( 0, 5, '', "B", 1, 'L', 0, '', 0, false, 'T', 'C');

    $pdf->Ln(4);

    $pdf->Cell(30, 5, 'Permintaan / ', 0, 1, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell(30, 5, 'Perbaikan  ', 0, 0, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell( 2, 5, ': ', 0, 0, 'L', 0, '', 0, false, 'T', 'C');

    $html = <<<EOD

    <form action="">
        <input type="checkbox" name="request[]" id="Login" value="Login" >   Login
        <input type="checkbox" name="request[]" id="Login" value="Login" >   Printer
        <input type="checkbox" name="request[]" id="Login" value="Login" >   Monitor
        <input type="checkbox" name="request[]" id="Login" value="Login" >   Computer
        <input type="checkbox" name="request[]" id="Login" value="Login" >   Network
        <input type="checkbox" name="request[]" id="Login" value="Login" > Lain-lain
    </form>
 EOD;

    $pdf->writeHTML($html, true, 1, false, 1);

    $pdf->Ln(4);
    $pdf->Cell(30, 10, 'Keluhan', 0, 0, 'L', 0, '', 0, false, 'T', 'T');
    $pdf->Cell( 2, 5, ': ', 0, 0, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell( 0, 90,' ', 0, 1, 'L', 0, '', 0, false, 'T', 'T');

    $pdf->Cell(30, 10, 'Keterangan', 0, 0, 'L', 0, '', 0, false, 'T', 'T');
    $pdf->Cell( 2, 5, ': ', 0, 0, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell( 0, 60,' ', 0, 1, 'L', 0, '', 0, false, 'T', 'T');

    $pdf->Cell(30, 10, 'Catatan', 0, 0, 'L', 0, '', 0, false, 'T', 'T');
    $pdf->Cell( 2, 5, ': ', 0, 0, 'L', 0, '', 0, false, 'T', 'C');
    $pdf->Cell( 0, 10,' ', 0, 1, 'L', 0, '', 0, false, 'T', 'T');
    $pdf->Ln(4);

    $pdf->SetFont('helvetica', '', 8);
    $pdf->Cell(30, 5, 'Tgl Permintaan / Paraf', 1, 0, 'C', 0, '', 0, false, 'T', 'C'); //width, height,
    $pdf->Cell(30, 5, 'Persetujuan Manajer', 1, 0, 'C', 0, '', 0, false, 'T', 'C');
    $pdf->Cell(25, 5, 'Tgl Persetujuan', 1, 0, 'C', 0, '', 0, false, 'T', 'C');
    $pdf->Cell(25, 5, 'Diterima Oleh', 1, 0, 'C', 0, '', 0, false, 'T', 'C');
    $pdf->Cell(25, 5, 'Tgl Terima', 1, 0, 'C', 0, '', 0, false, 'T', 'C');
    $pdf->Cell(25, 5, 'Perkiraan Selesai', 1, 0, 'C', 0, '', 0, false, 'T', 'C');
    $pdf->Cell(25, 5, 'Tgl Selesai', 1, 1, 'C', 0, '', 0, false, 'T', 'C');
    $pdf->Cell(30, 25, '', 1, 0, 'L', 0, '', 0, false, 'T', 'T'); //width, height,
    $pdf->Cell(30, 25, '', 1, 0, 'L', 0, '', 0, false, 'T', 'T');
    $pdf->Cell(25, 25, '', 1, 0, 'L', 0, '', 0, false, 'T', 'T');
    $pdf->Cell(25, 25, '', 1, 0, 'L', 0, '', 0, false, 'T', 'T');
    $pdf->Cell(25, 25, '', 1, 0, 'L', 0, '', 0, false, 'T', 'T');
    $pdf->Cell(25, 25, '', 1, 0, 'L', 0, '', 0, false, 'T', 'T');
    $pdf->Cell(25, 25, '', 1, 1, 'L', 0, '', 0, false, 'T', 'T');
    $pdf->Ln(2);
    $pdf->SetFont('helvetica', '', 8);
    $pdf->Cell(0, 0, 'TMS-IT-06 (10.2001)', 0, 0, 'L', 0, '', 0, false, 'T', 'T');

    // reset pointer to the last page
    $pdf->lastPage();

    // ---------------------------------------------------------

    //Close and output PDF document
    $pdf->Output('example_057.pdf', 'I');

}

This is my model
public function selectOneRequest($id_request){
   $query = $this->db->get_where('tbl_request', array('id_request'=>$id_request));
    return $query->result_array();
}

A: Just construct the href of the link to point to the generate_pdf function.. assuming your controller name is Tcpdf
<a href="/tcpdf/generate_pdf/<?php echo $data['id_request']; ?>">Print


text:
Q: Running a Python program from Go I have written some code in Python that uses some libraries that are not in Go. I have a web server that I have written in Go and I would like to be able to call a Python program from my Go program and then use the output of the Python program as input in my Go program. Is there anyway to do this?

A: It's actually relatively easy. All you need to do is use the os/exec library. Here is an example below.
Go Code:
package main

import (
   "fmt"
   "os/exec"
)

func main() {
    cmd := exec.Command("python",  "python.py", "foo", "bar")
    fmt.Println(cmd.Args)
    out, err := cmd.CombinedOutput()
    if err != nil { fmt.Println(err); }
    fmt.Println(string(out))
}

Python Code:
import sys

for i in range(len(sys.argv)):
   print str(i) + ": " + sys.argv[i]

Output From Go Code:
[python python.py foo bar]
0: python.py
1: foo
2: bar

redpajama_set_name: RedPajamaStackExchange


text:
Q: Comparing the means of two groups when a large number of data points have the same value I have data on the profitability of wagers made according to two different strategies.
One strategy was to bet $1 on the underdogs in each of a sequence of sporting matches. They have data like this:
Lost \$1
Lost \$1
Won \$4.50
Lost \$1
Won \$3
Lost \$1
...and so on.
Of the 1400 data points from wagers on underdogs, 1000 of them result in a loss of the \$1 stake while the profitable wins come in varying amounts but are all at least a profit of at least $1.10 or so.
The other strategy was to bet on favorites. There the data looks like this:
Won \$0.20
Won \$0.50
Won \$0.10
Lost \$1
Won \$0.80
Won \$0.20
...and so on.
Here only 400 of the bets result in a loss of \$1, and the vast majority of bets result in a profit of some small amount (always less than $1). The actual data is viewable here.
Ultimately I'm interested in comparing strategies, and so I want to compare the means of the "bet on favorites" strategy with the "bet on underdogs" strategy. Theory tends to suggest both should lose money, but that betting on underdogs should lose more.
What I'm wondering is what sort of test I should do to compare means, given the nature of the data. I wasn't sure what the implications would be of the fact that in one of my groups most of the data points are fixed to a particular value (-1). If nothing else it creates a massive skew in my dataset. I thought that maybe doing a Mann–Whitney U test might work well here, but I was unsure on this point, especially as my data is paired in the sense that each game generates one favorite to bet on and one underdog to bet on. Also, Wikipedia states that "the Mann–Whitney U test should not be used when the distributions of the two samples are very different". My distributions are really different since a huge number of the underdogs resulted in a loss of $1, whereas that is not true of the favorites.


text:
Q: Modo interrupción espero me puedan ayudar.
Tengo en mi base de datos de mysql una tabla que contiene aproximadamente 18000 registros, cada registro contiene un documento pdf.
Lo que debo hacer es exportar esos pdf a una ruta de la PC, pero cuando intento hacerlo, despues de un rato me lanza el siguiente mensaje.
el codigo que utilizo es el siguiente
for (int j = 0; j <= cantidad;) {
    using (GestorDocumento elDocumento = new GestorDocumento()) {
        DataTable miDataTable = new DataTable();
        //se guardan los 10 resultados en un datatable para despues guardarlos en la ruta establesida
        miDataTable = elDocumento.CargarDocumentoTodo(j);

        int filas = miDataTable.Rows.Count;
        if (filas >= 1) {
            byte[] documento = null;
            for (int i = 1; i <= filas; i++) {
                documento = (byte[])miDataTable.Rows[i - 1][1];
                File.WriteAllBytes(lblRuta.Text + miDataTable.Rows[i - 1][0].ToString() + ".pdf", documento);
            }
        }
    }
    j = j + 100;
}

A: Esa excepción la lanza el depurador del Visual Studio en depuraciones con procesos con tiempos de espera altos. No tiene nada que ver con tu código, puedes comprobarlo intentando poner try/catch y verás que no la captura. Porque la excepción no está en tú codigo.
Simplemente dale a continuar con la depuración y verás que sigue depurando y tu código termina correctamente.


text:
Q: Parsing vcxproj with python and lxml I'm trying to parse a vcxproj with Python and lxml. When I attempt to do that nothing is chown during print unless I delete what's in <Project >.
Here is my .vcxproj (I reduced it to test) :
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Debug|x64">
      <Configuration>Debug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="ReleaseDebug|Win32">
      <Configuration>ReleaseDebug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="ReleaseDebug|x64">
      <Configuration>ReleaseDebug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|x64">
      <Configuration>Release</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
  </ItemGroup>
</Project>

And my python code :
#!/usr/bin/python3
# -*- coding: utf-8 -*-

from lxml import etree

tree = etree.parse("core.xml")

for conf in tree.xpath("/Project/ItemGroup/ProjectConfiguration/Configuration"):
    print(conf.text)

If I run like this, script works but show nothing. If I delete DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" in node Project script works...
I'm new to xml, maybe I'm doing something wrong. can you help me please to  solve this ?
Thanks for help.

A: Found solution here : lxml etree xmlparser remove unwanted namespace
It seems, I have to precise namespace before (if there is one) like that :
from lxml import etree

tree = etree.parse("core.xml")

namespaces = {'ns':'http://schemas.microsoft.com/developer/msbuild/2003'}
for conf in tree.xpath('//ns:Configuration', namespaces=namespaces):
    print (conf.text)


text:
Q: Why does the number of holes in an N-type semiconductor increase with temperature? I was watching this video.

I understand that the dopant atoms introduce huge numbers of free electrons that essentially overshadow any additional electrons that break free due to higher temperatures.
What I don't understand is why the hole concentration increases. Surely, since we have so many free electrons, any additional holes that are created due to higher temperatures should get instantly filled by the large number of electrons. Hence, shouldn't P remain constant?

A: point is: nothing is ever instant. Nothing: So, while the number of free charge carriers of poth polarities increases, and so do the recombinations, the number of available ones at every point in time increases just as well.

A: The energy required to break electron free out of atom decreases with temperature. Thus at higher temperatures it's harder for an atom to bound to a free electron.

A: First, we should understand how the carrier concentration varies with temperature in an intrinsic (pure) semiconductor.
Intrinsic semiconductor
At zero Kelvin (absolute zero), there are no free carriers in the semiconductor. In the 'bond model', this means that all the electrons are bound to the atom, as there is no energy available to break the bond. In the band-diagram, this is equivalent to the condition where all the electrons are residing in the valence band, no free electrons are in the conduction band.
As the temperature increases, the thermal energy increases, a few electrons attain enough energy to jump from the conduction band to the valence band (or to break free from the atom). As the temperature further increases, the thermal energy increases and the free carriers also increase (both electrons and holes, equally). This increase in intrinsic carrier concentration (\$n_i\$) is exponential in nature. (see image below). This increase in electron and hole concentrations happen even in doped semiconductors. (This is what is shown in the question).

Doped semiconductor
Now consider the case when the semiconductor is doped with donor atoms. The dopant atoms contribute additional electrons to the semiconductor to make it n-type. Note that the doping concentration (\$N_D\$) will be so much higher than the intrinsic carrier concentration of the semiconductor, so that the intrinsic concentration is negligible (almost zero when plotted together) at room temperature. The electron concentration will thus be equal to the dopant concentration. \$n=N_D+n_i\approx N_D\$.
The dopant concentration is fixed. But the electron and hole concentration increases with temperature. Above some high temperature value, the value of hole concentration becomes significant and the increase will be visible as shown in the question. Note that both electron and hole concentrations are increasing and at very high temperatures, when the intrinsic carrier concentration becomes very much higher than that of the doping concentration, the semiconductor becomes intrinsic (it's no longer n-type). \$n=N_D+n_i\approx n_i\$, and \$p=n_i\$.
NB: This is one of the reasons why semiconductors have an upper limit on operating temperature.

A: When temperature increases, the energy gap between conduction band and valence band decreases. Effectively, it will be easier for electron-hole pairs (both to break).  There are more free electrons and they might combine with the holes. But in parallel, there will be electron-hole pairs breaking and forming free electrons and holes.
This is dynamic; pairs are being formed and get broken. But to understand, we take the net effect, i.e., 'the number of pairs generated - pairs broken'. So, when more pairs are broken than generated, we say free electrons and holes are produced.


text:
Q: c# Отправка файла по ftp асинхронно. Этот вариант не слишком избыточен в смысле асинхронности? Сразу скажу что это рабочий вариант:
public async static void SendFileToFtp(string ftpAddress, string ftpUser, string ftpPassword, FileInfo file)
{
    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}{1}", ftpAddress,file.Name));
    request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
    request.KeepAlive = false;
    request.UseBinary = true;
    request.Method = WebRequestMethods.Ftp.UploadFile;

    FileStream fs = File.OpenRead(file.FullName);
    byte[] sBuffer = new byte[fs.Length];
    await fs.ReadAsync(sBuffer, 0, sBuffer.Length);
    fs.Close();

    Stream stream = await request.GetRequestStreamAsync();
    await stream.WriteAsync(sBuffer, 0, sBuffer.Length);
    stream.Close();
}

Суть вопроса в слудующем, не слишком ли много await в этом случае. await request конечно должен быть, но вот имеет смысл считывать и записывать файл с await? (await fs.ReadAsync,  await stream.WriteAsync).
Как выяснилось это не избыточно, а нормально и разве что можно обернуть потоки в using. Так же рабочий вариант будет такой но проблема с безопасностью выполнения FtpWebRequest останется.
public async static void SendFileToFtp(string ftpAddress, string ftpUser, string ftpPassword, FileInfo file)
{
    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}{1}", ftpAddress, file.Name));
    request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
    request.KeepAlive = false;
    request.UseBinary = true;
    request.Method = WebRequestMethods.Ftp.UploadFile;

    using (FileStream fs = new FileStream(file.FullName, FileMode.Open))
    {
        byte[] sBuffer = new byte[fs.Length];
        await fs.ReadAsync(sBuffer, 0, sBuffer.Length);
        fs.Close();
        using (Stream stream = await request.GetRequestStreamAsync())
        {
            await stream.WriteAsync(sBuffer, 0, sBuffer.Length);
            stream.Close();
        }
    }
}

Решается это непростым путём, вот ссылка с MSDN https://msdn.microsoft.com/ru-ru/library/system.net.ftpwebrequest(v=vs.110).aspx

A: Нет, избыточности нет. Следует только обернуть потоки в конструкцию using.
В общем пусть будет так. Безопасность FtpWebRequest оставим за кадром.
public async static void SendFileToFtp(string ftpAddress, string ftpUser, string ftpPassword, FileInfo file)
{
    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}{1}", ftpAddress, file.Name));
    request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
    request.KeepAlive = false;
    request.UseBinary = true;
    request.Method = WebRequestMethods.Ftp.UploadFile;

    using (FileStream fs = new FileStream(file.FullName, FileMode.Open))
    {
        byte[] sBuffer = new byte[fs.Length];
        await fs.ReadAsync(sBuffer, 0, sBuffer.Length);
        using (Stream stream = await request.GetRequestStreamAsync())
        {
            await stream.WriteAsync(sBuffer, 0, sBuffer.Length);
        }
    }
}

Можно упросить до такого вот решения что бы писать в другой поток(сразу на сервер) без предварительной буферизации.
public async static void SendFileToFtp(string ftpAddress, string ftpUser, string ftpPassword, FileInfo file)
{
    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}{1}", ftpAddress, file.Name));
    request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
    request.KeepAlive = false;
    request.UseBinary = true;
    request.Method = WebRequestMethods.Ftp.UploadFile;

    using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, 4096, true)) {
        using (Stream stream = await request.GetRequestStreamAsync())
        {
            await fs.CopyToAsync(stream);
        }
    }
}


text:
Q: Importing Timestamp Values from a .txt file into an equivalent column (UTC timestamp) in a Teradata Table I have Timestamp values in a column 'Ride_Time' in a .txt file. An example of a value in the 'Ride_Time' column is 6/13/2016 9:39. I am trying to create a table in Teradata using Teradata SQLA by importing the values in the 'Ride_Time' column in the .txt file (using the 'Import Data' option and inserting the values from the 'Ride_Time' column to an equivalent column in my new Teradata table. Below is my create table query,
CREATE TABLE Ride_Info
(
Ride_ID VARCHAR(50),
ride_time TIMESTAMP FORMAT 'YYYY-MM-DDbHH:MI:SS',

);
I keep getting the 'Invalid Timestamp' error. Can someone help me with this?

A: Your input data doesn't match the FORMAT of the target column (solution: apply/change the correct format) and Teradata is fussy regarding single digits (solution: RegEx to add missing leading zeroes). This should work
Cast(RegExp_Replace(?,'\b([0-9])\b', '0\1') AS TIMESTAMP(0) FORMAT 'mm/dd/yyyyBhh:mi')


text:
Q: How to Access an onBindViewHolder item Value from MainActivity in Android I have an OnbindViewHolder method in my CarDetailsListAdapter.java file like below
 @Override
public void onBindViewHolder(final CarDetailsListAdapter.ViewHolder viewHolder, final int i) {
    final CarDetailModel currentItem = getItem(i);

    Log.e("check", String.valueOf(modelItems));
    Log.e("check position", i+" "+currentItem.getCarIsSelected());

    // check car min is no cabs or not
    if(!currentItem.getCarMin().equals("No cabs")) {

        if (selectcar) {

            viewHolder.itemView.setSelected(true);
            //selectedItem =viewHolder.getLayoutPosition();
            selectcar = false;
        } else {

            viewHolder.itemView.setSelected(false);
        }
    }

    // set default select car
    viewHolder.itemView.setSelected(selectedItem == i);

    if(first&&currentItem.getCarIsSelected())
    {
        viewHolder.itemView.setSelected(true);
        first=false;
    }
    viewHolder.car_min.setText(currentItem.getCarMin());
    viewHolder.car_amount.setText(currentItem.getCarAmount());

Now I need to access above viewHolder.car_amount value from my MainActivity, i have no idea how to access this value

A: You want to access car_amount but you have multiple cell in your recyclerview. I will suppose that you want to access it after an "onClick" on your cell.
You can give to your adapter a listener to call when a click is done on a specific cell.
public CarDetailsListAdapter(CarDetailsListListener listener){
    mListener = listener;
}

@Override
public void onBindViewHolder(final CarDetailsListAdapter.ViewHolder viewHolder, final int i) {
   viewHolder.itemView.setOnClickListener(v->{
      mListener.onClick(currentItem.getCarAmount());
   }
}

Your activity :
public CarDetailsListActivity extends Activity implements CarDetailsListListener {
   ...

   mAdapter = new CarDetailsListAdapter(this);

   @Override
   public void onClick(int carAmount){
      ...
   }
}


text:
Q: How draw Bezier path with tikZ? How draw Bezier path like this with tikz?

This patch is x(1-x-y)
I saw similar : https://tikz.net/torus/
How to use \addplot3 ?

A: Functions x (1 − x − y) and y (1 − x − y) are not too attractive for static image. Better are, for example, (x + y) (1 − x − y) and especially x y (1 − x − y).
Simple exmaple using \addplot3:
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\begin{document}
\begin{tikzpicture}
    \begin{axis}[colormap/blackwhite]
     \addplot3[surf,color=blue,opacity=0.5,domain=-1:1,z buffer=sort] {x*y*(1-x-y)};
  \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: JSON-LD created by javascript is not displayed in view-source There are 'duplicates' to my question but nobody answer my question :(
I am trying to generate JSON-LD structured data with javascript. Everything was fine until I checked from the tool, the JSON-LD code generated by javascript doesn't show up on the test table. When I proceed to view source on chrome it do not display the JSON-LD code.
You can see it live here
The code is below
<script id='myJSONID' type='application/ld+json'></script>
<script type='text/javascript'>
//<![CDATA[
$('#myJSONID').text(function() {
    return JSON.stringify({
        "@context":"https://schema.org",
        "@type":"Review",
        "author": {
            "@type":"Person",
            "name":"Nhà đất Sơn Nghĩa",
            "sameAs":"https://www.nhadatsonnghia.com/"
        },
        "inLanguage":"vi",
        "itemReviewed": {
            "@type":"Product",
            "name": "" + document.title,
            "description":"" + document.getElementsByName("description")[0].content,
            "aggregateRating": {
                "@type": "AggregateRating",
                "ratingValue": "5",
                "bestRating": "5",
                "ratingCount": "20"
             }
        }
    });
});
//]]>
</script>

Does the above code have any problem? If not then how the JSON-LD code generated by javascript can be displayed when view-source (Ctrl + U)
Any suggestions are appreciated!
Thanks so much!

A: Because it shows only raw data and not exute Javascript in view-source, Try to use server side language to achieve this.


text:
Q: how to print ASCII value against input in emu8086 am using EMU8086 i wan to print ascii value of string like "ABC" output is: "65" "66" "67".
 please guide me how to print ascii value of string when user input the value.
am also print character with the help of ascii table but i don't know how to print ascii value of character

A: This is the Solution for your Problem
org 100h
.data
mystr DB 'A','B','C'
RES  DB 10 DUP ('$')
.code
; Print the ASSCII for A
lea si,mystr[0]
mov AX,[si]
mov ah,0
    LEA SI,RES
    CALL HEX2DEC
    LEA DX,RES
    MOV AH,9
    INT 21H
; Print the coma
mov dl,','
mov ah,2
int 21h
; Print the ASSCII for B
lea si,mystr[1]
mov AX,[si]
mov ah,0
    LEA SI,RES
    CALL HEX2DEC
    LEA DX,RES
    MOV AH,9
    INT 21H
; Print the coma
mov dl,','
mov ah,2
int 21h
; Print the ASSCII for C
lea si,mystr[2]
mov AX,[si]
mov ah,0
    LEA SI,RES
    CALL HEX2DEC
    LEA DX,RES
    MOV AH,9
    INT 21H
    MOV AH,4CH
    INT 21H
HEX2DEC PROC NEAR
    MOV CX,0
    MOV BX,10
LOOP1: MOV DX,0
       DIV BX
       ADD DL,30H
       PUSH DX
       INC CX
       CMP AX,9
       JG LOOP1
       ADD AL,30H
       MOV [SI],AL
LOOP2: POP AX
       INC SI
       MOV [SI],AL
       LOOP LOOP2
       RET
HEX2DEC ENDP
END START

ret

END


text:
Q: what should i do when" "Array.forEach ()" this is shown in console while i am using the following code in javascript     [inpTitle, inpBody].forEach(inputField => {
        inputField.addEventListener("blur", () => {
            const updatedTitle = inpTitle.value.trim();
            const updatedBody = inpBody.value.trim();

            this.onNoteEdit(updatedTitle, updatedBody);
        });
    });

this error is being shown in the console too
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

A: You can add an if statement to check if the inputField exists, but there should be other ways to make sure that you don't have an empty input.
[inpTitle, inpBody].forEach(inputField => {
  if(inputField){
    inputField.addEventListener("blur", () => {
        const updatedTitle = inpTitle.value.trim();
        const updatedBody = inpBody.value.trim();

        this.onNoteEdit(updatedTitle, updatedBody);
    });
   }
});


text:
Q: Ошибка php Warning: mysqli_query() [function.mysqli-query]: Empty query in C:\Users\mahmu\Desktop\OpenServer\domains\Venitore.rp\rcabin.php on line 40 Моя задача из БД получить логин и вывести его на экран, но ничего не получается выходит лишь только ошибка Warning: mysqli_query() [function.mysqli-query]: Empty query in C:\Users\mahmu\Desktop\OpenServer\domains\Venitore.rp\rcabin.php on line 40
Вот строка на которую ругается php

Ник: <?php $query = "SELECT * FROM `users` WHERE `login`"; $result = mysqli_query($connect, $result); $login = $_POST['login']; echo($login);?>


text:
Q: Does Windows have an equivalent to Linux/FreeBSD's `RESOLVE_BENEATH` and `O_RESOLVE_BENEATH`? I want to open a file, while ensuring that no component of the path goes outside a certain directory.
On Linux, I can accomplish this using openat2 and RESOLVE_BENEATH, and on FreeBSD there is the O_RESOLVE_BENEATH flag with openat.
Is there any way to achieve the same effect on Windows? Note that this needs to be on a per-call basis — globally restricting my process to a given directory is not useful.


text:
Q: How can I use google api in chrome extension content script? I am trying to list labels using Gmail api. I want to use Gmail api in content script. Following is my manifest.json file and content script file:
{
  "name": "Append Test Text",
  "description": "Add test123 to body",
  "version": "1.0",
  "permissions": ["activeTab"],
  "content_scripts": [
    {
      "matches": ["https://mail.google.com/*"],
      "js": ["jquery-3.4.1.min.js", "gmail.js", "content-script.js"],
      "all_frames": true
    }
  ],
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "browser_action": {
    "default_title": "Append Test Text"
  },
  "manifest_version": 2
}

content-script.js:
// Client ID and API key from the Developer Console
var CLIENT_ID = "<CLIENT_ID>";
var API_KEY = "<API_KEY>";

// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = [
  "https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"
];

// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/gmail.readonly";

/**
 *  On load, called to load the auth2 library and API client library.
 */
function handleClientLoad() {
  console.log("hello");
  gapi.load("client:auth2", initClient);
}

/**
 *  Initializes the API client library and sets up sign-in state
 *  listeners.
 */
function initClient() {
  gapi.client
    .init({
      apiKey: API_KEY,
      clientId: CLIENT_ID,
      discoveryDocs: DISCOVERY_DOCS,
      scope: SCOPES
    })
    .then(
      function() {
        // Listen for sign-in state changes.
        gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

        // Handle the initial sign-in state.
        updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      },
      function(error) {
        console.log(JSON.stringify(error, null, 2));
      }
    );
}

/**
 *  Called when the signed in status changes, to update the UI
 *  appropriately. After a sign-in, the API is called.
 */
function updateSigninStatus(isSignedIn) {
  if (isSignedIn) {
    listLabels();
  } else {
    gapi.auth2.getAuthInstance().signIn();
  }
}

/**
 * Print all Labels in the authorized user's inbox. If no labels
 * are found an appropriate message is printed.
 */
function listLabels() {
  gapi.client.gmail.users.labels
    .list({
      userId: "me"
    })
    .then(function(response) {
      var labels = response.result.labels;
      console.log("Labels:");

      if (labels && labels.length > 0) {
        for (i = 0; i < labels.length; i++) {
          var label = labels[i];
          console.log(label.name);
        }
      } else {
        console.log("No Labels found.");
      }
    });
}
var script = $(
  '<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === "complete") this.onload()"></script>'
);
$("body").append(script);

after running this there should at least be a "hello" in the console proving that the handleClientLoad() function is working. But nothing shows in the console.

A: Technically, Chrome won't allow you to do that. If you use content script to inject into a website then you can just send request only on that site, if you're trying to send a request into another site, Chrome will stop you due to CORS policy.
So to achieve it, you have to setup a background script which receive passed messages from your content script and then send request into Google API endpoint and then you can return the result into your content script via defined message channel. Here is how you can setup message passing in Chrome Extension.


text:
Q: Excel 2010 VBA With Setting Cell Colors I am trying to automate a highlighting process to show that certain rows are complete.  This process works well, however at the beginning of my sheet I am trying to make the code create a "Key" for the sheet to show the different meanings of the colors.  In the key, the colors White, Green, and Red are used as labels for being Not yet completed (White), completed (green) and Error/Incomplete (Red).  Grey is also used for private pipes.  I am trying to color the corresponding labels with their color, green as green, red as red, etc.  I have made code for this that works for the first line, but on green it does not color the "Green" cell as green (it leaves it white) and on "Red" it colors the cell as green.  Here is the code I am using (I apologize it is bad as I am new to coding):
Sub SmartHighlight()
Dim Counter As Integer
Dim i As Integer
Dim j As Integer
Dim k As Range
Dim Chkr As Integer
Chkr = 0
xTitleId = "Smart Highlighter"
MsgBox "This macro analyzes the given pipe data to highlight completed sections."
For Each k In ActiveSheet.UsedRange.Rows
    Counter = 0
    i = 8
    For j = 0 To 3
        If ActiveSheet.Cells(k.Row, i).Value = 0 Then
            Counter = Counter + 1
        End If
        i = i + 1
    Next j
    If ActiveSheet.Cells(k.Row, 1) = "PIPE_ID" Then
        ActiveSheet.Cells(k.Row, 15).Value = "KEY:"
        ActiveSheet.Cells(k.Row, 16).Value = "White"
        ActiveSheet.Cells(k.Row, 17).Value = "Not yet completed."
        ActiveSheet.Cells(k.Row, 18).Value = "Grey"
        k.Cells(k.Row, 18).Interior.ColorIndex = 15
        ActiveSheet.Cells(k.Row, 19).Value = "Private."
    ElseIf ActiveSheet.Cells(k.Row, 1) = "" And Chkr = 0 Then
        ActiveSheet.Cells(k.Row, 16).Value = "Green"
        k.Cells(k.Row, 16).Interior.ColorIndex = 4
        ActiveSheet.Cells(k.Row, 17).Value = "Completed."
        Chkr = Chkr + 1
    ElseIf ActiveSheet.Cells(k.Row, 1) = "" And Chkr = 1 Then
        ActiveSheet.Cells(k.Row, 16).Value = "Red"
        k.Cells(k.Row, 16).Interior.ColorIndex = 3
        ActiveSheet.Cells(k.Row, 17).Value = "Error/Incomplete."
    ElseIf ActiveSheet.Cells(k.Row, 4) = "PRIVATE PIPE" Then
        k.EntireRow.Interior.ColorIndex = 15
    ElseIf Counter <> 4 Then
        k.EntireRow.Interior.ColorIndex = 4
    ElseIf Counter = 4 And ActiveSheet.Cells(k.Row, 14) = "" Then
        k.EntireRow.Interior.ColorIndex = 3
    End If
Next k

End Sub

And here is the output in excel:
Click for Image
If anyone can help me correct the coloring error that would be most appreciated.  Thanks!

A: It's unclear why you're switching between ActiveSheet.Cells and k.Cells ?
    ActiveSheet.Cells(k.Row, 18).Value = "Grey"
    k.Cells(k.Row, 18).Interior.ColorIndex = 15

In your code the Range k represent a single row in your sheet's data.  You can get a reference to a single cell in that range using Cells(), but you need to be careful to use the correct index(es), otherwise you'll end up with a cell which is not even part of k.
For example, if k is set to row 4 on your sheet:
k.Cells(4).Address()

is D4, but
k.Cells(k.Row,4).Address() 'same as k.Cells(4, 4).Address()

is D7, not D4
k.Cells(1, 4).Address()

would be D4.

A: I would propose you to make a sub procedure that will update the headers/keys etc. more static information when you run the macro.
This is what I ended up doing in one Excel macro gadget, a piece of the sub that draws the header rows:
Sub PrepareHeaders(szSheetName)
Sheets(szSheetName).Cells(iRow + 1, iCel) = "Add/Update"
Select Case szSheetName
    Case "Value Lists"
        Sheets(szSheetName).Cells(iRow + 1, iCel + 1) = "Object Type Name Singular"
        Sheets(szSheetName).Cells(iRow + 1, iCel + 2) = "Object Type Name Plural"
        Sheets(szSheetName).Cells(iRow + 1, iCel + 3) = "ID"
        Sheets(szSheetName).Cells(iRow + 1, iCel + 4) = "Real Object"
        Sheets(szSheetName).Cells(iRow + 1, iCel + 5) = "Owner Type ID"
        Sheets(szSheetName).Cells(iRow + 1, iCel + 6) = "Aliases"
    End Select
    Sheets(szSheetName).Rows(iRow + 1).Font.Bold = True
    Sheets(szSheetName).Columns("A:Z").EntireColumn.AutoFit
    Sheets(szSheetName).Cells(1, iCel).Select
End Sub

Additionally, you can use styles in your Excel sheet. Those styles can be called from VBA, and in case you need to change the color scheme or so, you can alter your style to apply formatting to whole spreadsheet.
Sheets(szSheetName).Cells(iRow + 1, iCel + 5).Style = "Input"

Another good thing to do is to fit your input, and finally select some specific cell.
Sheets(szSheetName).Columns("A:Z").EntireColumn.AutoFit
Sheets(szSheetName).Cells(1, iCel).Select

And one more thing, you may want to look for conditional formatting. That might provide one additional feature to use.


text:
Q: Nancy.ViewEngines.ViewNotFoundException: Unable to locate view 'Index' I know this question was asked month before but was never answered.
My program starts normally but after returning View["Index", blogPost] it could not find the Index.cshtml and raises an exception.
Get["/"] = parameters =>
{
   var blogPost = new BlogPost
   {
       Id = 1,
       Title = "Test",
       Content = "Lorem ipsum...",
       Tags = { "c#", "aspnetmvc", "nancy" }
   };

   return View["Index", blogPost];
};

Exception:

Nancy.RequestExecutionException: Oh noes! ---> Nancy.ViewEngines.ViewNotFoundException: Unable to locate view 'Index'
  Currently available view engine extensions: sshtml,html,htm,cshtml,vbhtml
  Locations inspected: views/Home/Index-de-DE,views/Home/Index,Home/Index-de-DE,Home/Index,views/Index-de-DE,views/Index,Index-de-DE,Index`

A: If the answer giving my Christian doesn't help you like it didn't help me there is a alternative issue/solution. The alternative is to make sure that the file you created is being copied to the output directory at compile time. You can check it under the properties tab like shown bellow

A: The exception message tells you where Nancy tried to look for the view:
Locations inspected: views/Home/Index-de-DE,views/Home/Index,Home/Index-de-DE,Home/Index,views/Index-de-DE,views/Index,Index-de-DE,Index

The exception also tells you which file extensions Nancy tried to look for:
Currently available view engine extensions: sshtml,html,htm,cshtml,vbhtml

That is Nancy looks for a file in one of the listed locations with one of the listed extensions.
So the question is if your index.cshtml is in one the listed folders. If not you can either move it there or set up a view location convention.

A: We ran into this error and noticed the .cshtml file it was complaining about was not getting copied to the server. The solution was in Visual Studio, in the file's properties, we changed the Build Action to Content. This forces it to get included in the build artifacts that are deployed to the server. Similarly you could change the Copy to Output Directory to Always as others have mentioned; either works, but I find setting the file as Content a bit more informative.

In your case, I'm guessing you have an Index.cshtml file which you need to set this property on.


text:
Q: Unable to return searched value in javascript via forEach I'm trying to return searched element via forEach, but unfortunately, its not returning proper value but via for loop,can able to return proper value after searching.

function search(arr, searchValue) {
  arr.forEach((_eachItem,i)=> {
    if(_eachItem===searchValue) {
      return i
    }
  })

  return -1

//   for(let i=0;i<arr.length;i++) {
//     if(arr[i]===searchValue) {
//       return i
//     }
//   }
//   return -1
}

console.log(search([11,1,2,3,4,9],9))

A: forEach returns undefined, what you should be using is includes.

function search(arr, searchValue) {
  return arr.includes(searchValue);
}

console.log(search([11,1,2,3,4,9],9))

A: Returning from the forEach callback does not return from the outer function. You can use Array#indexOf.

function search(arr, searchValue) {
  return arr.indexOf(searchValue);
}

console.log(search([11,1,2,3,4,9],9))


text:
Q: I'm looking for a way to put a lot of work on a single backround thread, in silverlight I've got an interesting issue with an app for Windows Phone 7.
Right now, I'm sending out some two dozen or so requests for small (a few KB) xml files to keep rapidly changing information (bus locations to be exact). I have a Timer ticking off every 10 sec to send out the requests asyncronously.
The data retreived is handled with an asynchronous callback to verify the request came back with a file, and stores the file into IsolatedStorage. When the data is needed (by the View-Model of the UI), the file is read from IsolatedStorage, parsed into internal objects (basically a GeoCoordinate and some strings) and used.
1) I'm running into the limitations of the phone's CPU here, just a bit. If I parse all the bus data to determine which bus routes are active on the UI thread, the thread noticably slows down. I moved the work into a bakground worker like this:
public class RunningWorkerHelper
{
    public BusRouteIdModel Route { get; set; }
    public Visibility Visible { get; set; }
}

public class RunningWorker
{
    BackgroundWorker bw;
    Queue<BusRouteIdModel> workQueue;

    public RunningWorker()
    {

        bw = new BackgroundWorker();
        workQueue = new Queue<BusRouteIdModel>();

        bw.DoWork += CheckIfRunning;
        bw.RunWorkerCompleted += CheckRunningCompleted;
    }

    public void QueueWorkItem(BusRouteIdModel route)
    {
        workQueue.Enqueue(route);
        StartWorkItem();
    }

    void StartWorkItem()
    {
        if (!bw.IsBusy && workQueue.Count > 0)
            bw.RunWorkerAsync(workQueue.Dequeue());
    }

    void CheckIfRunning(object sender, DoWorkEventArgs args)
    {
        BusRouteDataService server= BusRouteDataService.Current;
        var route = (BusRouteIdModel)args.Argument;
        if (route == null) return;

        var vehicleFile = server.GetBusVehiclesFile(route);
        var vehiclesOnRoute = RouteDataParser.ExtractBusVehicles(vehicleFile);
        var helper = new RunningWorkerHelper { Route = route };
        if (vehiclesOnRoute.Count > 0)
        {
            helper.Visible = Visibility.Visible;
        }
        else
        {
            helper.Visible = Visibility.Collapsed;
        }
        args.Result = helper;
    }

    void CheckRunningCompleted(object sender, RunWorkerCompletedEventArgs args)
    {
        var helper = (RunningWorkerHelper)args.Result;
        if (helper != null)
            helper.Route.IsRunning = helper.Visible;
        StartWorkItem();
    }

}

here's the BusRouteIdModel (for reference)
public class BusRouteIdModel : BusRouteId, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    Visibility _isRunning;
    /// <summary>
    /// True when there is a bus active on this route
    /// </summary>
    public Visibility IsRunning
    {
        get { return _isRunning; }
        set
        {
            if (value == _isRunning) return;
            _isRunning = value;
            OnPropertyChanged(new PropertyChangedEventArgs("IsRunnning"));
       }
    }

    /// <summary>
    /// True while path data for the route isn't available yet
    /// </summary>
    Visibility _isLoading;
    public Visibility IsLoading
    {
        get { return _isLoading; }
        set
        {
            if (value == _isLoading) return;
            _isLoading = value;
            OnPropertyChanged(new PropertyChangedEventArgs("IsLoading"));
        }
    }

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, args);
    }
}

public class BusRouteId
{
    public String Uid { get; set; }
    public String Name { get; set; }
}

This is data bound to a listbox element on the page (I'm using the MVVM Light Toolkit):
    public const string RouteIdsPropertyName = "RouteIds";
    private ObservableCollection<BusRouteIdModel> _routeIds = null;
    public ObservableCollection<BusRouteIdModel> RouteIds
    {
        get { return _routeIds; }
        private set
        {
            if (_routeIds == value) return;
            var oldValue = _routeIds;
            _routeIds = value;
             RaisePropertyChanged(RouteIdsPropertyName);
        }
    }

And I call my worker like this (the args.Uid id's the bus route that got new data):
foreach (var route in RouteIds)
    if (route.Uid == args.Uid)
        runningWorker.QueueWorkItem(route);

2) Mysteriously, the IsRunning change isn't reflected in the UI. What did I miss?
3) How can I generalize this Queue + BackgroundWorker to handle other tasks? (I would use the Task Pool Library, but Silverlight does not have it.) I want to have a single worker so that the UI thread doesn't get starved on the map page.

A: 1) Not a question?
2) IsRunning in the UI isn't updating because of a typo:
OnPropertyChanged(new PropertyChangedEventArgs("IsRunnning"))

Too many n's
3) For threading like this, try ThreadPool - see http://wildermuth.com/2011/01/11/Architecting_WP7_-_Part_9_of_10_Threading


text:
Q: Calculate Conway's Constant I found a code golf challenge that requires you to calculate Conway's Constant to the first 1000 digits. The problem is I couldn't find any place that tells how to calculate this, just websites showing polynomials with a variable x that I do not know what is.
I calculated the first 30 numbers in the Look-and-say sequence with this code:

const nums = ["1"],

  trailingSequences = seq => {
    const num = seq[0];
    let counter = 1;
    let idx = 0;
    for (let i = 1; i < seq; i++) {
      if (num == seq[i]) {
        counter++
        idx = i;
      } else {
        break
      };
    }
    return [`${counter}${num}`, idx + 1];
  },

  getNext = previous => {
    let next = "";
    while (true) {
      if (previous == "") {
        break
      };
      const part = trailingSequences(previous);
      next += part[0];
      previous = previous.slice(part[1]);
    }
    return next;
  }

for (let i = 0; i < 30; i++)
  nums.push(getNext(nums[nums.length - 1]))

console.log(nums.join("\n\n\n"));

But I still do not know how to extract Conway's constant regardless.
So, how to calculate Conway's Constant to a modifiable precision in JavaScript?

A: The Conway Constant is the ratio between the length of digits of n and n-1 as n approaches inf.

const nums = ["1"],

  trailingSequences = seq => {
    const num = seq[0];
    let counter = 1;
    let idx = 0;
    for (let i = 1; i < seq; i++) {
      if (num == seq[i]) {
        counter++
        idx = i;
      } else {
        break
      };
    }
    return [`${counter}${num}`, idx + 1];
  },

  getNext = previous => {
    let next = "";
    while (true) {
      if (previous == "") {
        break
      };
      const part = trailingSequences(previous);
      next += part[0];
      previous = previous.slice(part[1]);
    }
    return next;
  }

for (let i = 0; i < 30; i++){
  let prev = (nums[nums.length - 1] + '').length;
  let current = (getNext(nums[nums.length - 1]) + '').length;
  nums.push(getNext(nums[nums.length - 1]))
  // ratio of n / n-1, this is the approx of Conway's Constant
  console.log(current / prev);
}
//console.log(nums.join("\n\n\n"));

A: Conway's Constant is the unique real positive root of an order-71 polynomial. As you might expect it is irrational1, and cannot be expressed as a finite continued fraction.
One of the easiest, and generally speaking most efficient methods to compute polynomial roots is with Newton's method:

where xn is the current guess and f(xn) is a function that evaluates the target polynomial at xn.
In the case that arbitrary precision reals/rationals are not available, the result can instead be scaled by a large power of 10 to compute the desired precision. The implementation below uses V8's BigInts to compute Conway's Constant to 1000 places.
/**
 * Evaluates a polynomial given by coeffs at x,
 * or the derivative thereof, scaled by a factor.
 */
function evalpoly(x, coeffs, scale, deriv) {
  let ret = 0n;
  const d = deriv ? 1 : 0;
  for(let i = coeffs.length - 1; i >= d; i--) {
    ret = x*ret / scale + BigInt(coeffs[i] * [1, i][d]) * scale;
  }
  return ret;
}

const poly = [
  -6, 3, -6, 12, -4, 7, -7, 1, 0, 5, -2, -4, -12, 2, 7, 12, -7, -10,
  -4, 3, 9, -7, 0, -8, 14, -3, 9, 2, -3, -10, -2, -6, 1, 10, -3, 1,
  7, -7, 7, -12, -5, 8, 6, 10, -8, -8, -7, -3, 9, 1, 6, 6, -2, -3,
  -10, -2, 3, 5, 2, -1, -1, -1, -1, -1, 1, 2, 2, -1, -2, -1, 0, 1]

const scale = 10n**1000n

// initial guess 1.333333...
let x = scale * 4n / 3n

for(let i = 0; i < 14; i++) {
  x -= evalpoly(x, poly, scale, 0) * scale / evalpoly(x, poly, scale, 1)
}

x

1 Finch, Steven R., Mathematical Constants, pp. 642, Cambridge University Press, 2003.


text:
Q: i want to add linear layout and webview and the screen must be fully scrollable     <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:layout_width=""
                android:layout_height=""/>
            <WebView
                android:layout_width=""
                android:layout_height=""/>
        </LinearLayout>

    </ScrollView>

This like layout I want to achieve where full screen need to be scrollable
Any one suggest better ideas

A: <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="500dp"
                android:background="#dedede"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal"
                    android:layout_marginTop="30dp"
                    android:text="LinearLayout" />

            </LinearLayout>

            <WebView
                android:id="@+id/webView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            </WebView>
        </LinearLayout>

    </ScrollView>

</LinearLayout>


text:
Q: How can I replicate select (HTML) in android string.xml file I have to replicate
<select>
  <option value="36">Volvo</option>
  <option value="45">Saab</option>
  <option value="56">Mercedes</option>
  <option value="71">Audi</option>
</select>

in string.xml so that when I select any Item in Spinner it gives me value of the item instead of name of the item.
I mean I have to use this value. I tried using StringArray but it does not give me option to give value to an item. A the values are static I was wondering if this can be done in string.xml rather than using other workarounds.
Please tell me how can I proceed.

A: You can define two string-arrays, one for the names, another for the values :
<Spinner
    android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawSelectorOnTop="true"
    android:entries="@array/array_names"
    android:entryValues="@array/array_name_values"
/>

EDIT :
Forgot strings.xml
strings.xml:
<string-array name="array_names">
    <item>Volvo</item>
    <item>Saab</item>
    <item>Mercedes</item>
    <item>Audi</item>
</string-array>

<string-array name="array_name_values">
    <item>36</item>
    <item>45</item>
    <item>56</item>
    <item>71</item>
</string-array>

A: Spinners and other similar list-based elements in android are populated via adapters, which translate data (in this case, either an array of data, or a cursor from a database query) into a form that can be displayed by the View.
Here, you want to be looking at an ArrayAdapter; this class is the interface between your data and your spinner. The ArrayAdapter can be populated from a number of sources: An array created programmatically in your java code, or one that is hard-coded as an array in your xml resources string file, like so:
<resources>
    <string-array name="cars_array">
        <item>Volvo</item>
        <item>Saab</item>
        <item>Mercedes</item>
        <item>Audi</item>
    </string-array>
</resources>

If you want to use static data in this way, the 'item' tag does not have any attributes like the options tag in your example does. Your options would be one of the following:
1 - Use this array along with an existing adapter class and put the values in programmatically somewhere in your java code.
2 - Put the values in a separate array resource and create your own adapter class if necessary to use both of them as you wish
For more information and further links on the use of spinners, look here.
Hope this helps!


text:
Q: Error sending a string to SQL Server I'm working on a project with C# and SQL Server. I have a table called Area and it has a column called flag, it is a char(1).
I create the object with the following code:
Area objArea = new Area()
{
    CodArea = txtCod.Text.ToString().ToUpper().Trim(),
    NameArea= txtNombre.Text.ToString().ToUpper().Trim(),
    UserCreate= Session.CurrentSession.User.User1,
    DateCreate= DateTime.Now,
    Flag= "A"
};

It worked okay until yesterday but now the program shows this message:

the field flag should be an string or array with length 1.

Does anybody know what is wrong?
I'm using Entity Framework, I catch the exception with the following code:
public void Insert(Area data)
{
        dataBase.Area.Add(data);

        try
        {
            dataBase.SaveChanges();
        }
        catch(DbEntityValidationException ex)
        {
            foreach(var errors in ex.EntityValidationErrors)
            {
                foreach(var error in errors.ValidationErrors)
                {
                    Trace.TraceInformation("Property: {0}, Error: {1}",
                                             error.PropertyName,
                                             error.ErrorMessage);
                }
            }
        }
}

Interesting fact: I have another class called Product and I send the value "A" for flag and it doesnt have any error.
This is the class, is auto-generated
public partial class Area
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Area()
    {
        this.Articuloes = new HashSet<Articulo>();
    }

    public int Id_Area { get; set; }
    public string CodArea { get; set; }
    public string NombreArea { get; set; }
    public string UsuarioCreacion { get; set; }
    public System.DateTime FechaCreacion { get; set; }
    public string UsuarioModificacion { get; set; }
    public Nullable<System.DateTime> FechaModificacion { get; set; }
    public string Estado { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Articulo> Articuloes { get; set; }
}


text:
Q: Expression Tree: Get property value of dynamic object I have list of dynamic objects where I want to query by custom property. In other words, it would look like this if I wasn't going for reflection:
IEnumerable<User> FilterUsers(IEnumerable<User> users, string selectedValue)
{
    users.Where(user => user.Name == selectedValue);
}

So far I've come up with the following implementation that works if users is typed:
IEnumerable<User> FilterUsers(IEnumerable<User> users, string selectedField, string selectedValue)
{
    LabelTarget returnTarget = Expression.Label(typeof(bool));
    ParameterExpression userParameter = Expression.Parameter(typeof(User));
    MemberExpression userSelectedField = Expression.Property(userParameter, selectedField);
    Expression test = Expression.Equal(userSelectedField, Expression.Constant(selectedValue));
    Expression iftrue = Expression.Return(returnTarget, Expression.Constant(true));
    Expression iffalse = Expression.Return(returnTarget, Expression.Constant(false));

    var ex = Expression.Block(
        Expression.IfThenElse(test, iftrue, iffalse),
        Expression.Label(returnTarget, Expression.Constant(false)));

    var whereClause = Expression.Lambda<Func<User, bool>>(
        ex,
        new ParameterExpression[] { userParameter }
    ).Compile();

    return users.Where(user => whereClause(user));
}

What I am really trying to do is to make users dynamic object:
IEnumerable<dynamic> FilterUsers(IEnumerable<dynamic> users, string selectedField, string selectedValue) {
    // ...
    ParameterExpression userParameter = Expression.Parameter(typeof(object)); // ???
    MemberExpression userSelectedField = Expression.Property(userParameter, selectedField); // throws
    // ...
}

This throws the following exception: Instance property 'Name' is not defined for type 'System.Object' (Parameter 'propertyName'). What am I missing?
Alternatively, how can I use Dictionary<string, object>?

A: Using dynamic here doesn't get you much: you'd be better off using generics if you can:
IEnumerable<T> FilterUsers<T>(IEnumerable<T> users, string selectedField, string selectedValue)
{
    var userParameter = Expression.Parameter(typeof(T));
    var userSelectedField = Expression.Property(userParameter, selectedField);
    // etc...
}

If you do need to use dynamic, then you'll need to get the runtime type of each user, using .GetType(). However bear in mind that there's nothing stopping someone from passing in an IEnumerable containing lots of different types of object, and they don't all have to have a property called selectedField!
Or, they might pass in lots of different types of object, each of one has a property called selectedField, but they're distinct properties (e.g. class A { public string Foo { get; set; } } and class B { public string Foo { get; set; } } -- those two Foo properties are distinct).
So you'll have to call .GetType() on each one of them, which means you won't be able to get the performance benefits of using compiled expressions.
If you can guarantee that all elements have the same type, you can do something like:
private static IEnumerable<dynamic> FilterCollection(IEnumerable<dynamic> collection, string property, string value)
{
    if (!collection.Any()) return collection;
    var collectionItemType = collection.First().GetType();
    var userParameter = Expression.Parameter(typeof(object));
    var convertedUser = Expression.Convert(userParameter, collectionItemType);
    var userSelectedField = Expression.Property(convertedUser, selectedField);
    ...
}

Beware however that you're enumerating users twice, which is probably a bad thing. You might do better to get the IEnumerator yourself and work with it explicitly.

A: As @canton7 said you should be using a generic method. I also see in your question you specified you're looking for properties, why not use regular old reflection?
public static IEnumerable<T> FilterItems<T>(IEnumerable<T> items, string property, string value)
{
  var prop = typeof(T).GetProperties().First(p => p.Name == property);
  return items.Where(i => prop.GetValue(i).ToString().Contains(value));
}

Of course that code should be enhanced to handle different errors....


text:
Q: How to access graph which is present in views.py file into html templates in django I have a views.py file as follows
def showimage(request):
    # Construct the graph
    t = arange(0.0, 2.0, 0.01)
    s = sin(2*pi*t)
    plot(t, s, linewidth=1.0)

    xlabel('time (s)')
    ylabel('voltage (mV)')
    title('About as simple as it gets, folks')
    grid(True)

    buffer = StringIO.StringIO()
    canvas = pylab.get_current_fig_manager().canvas
    canvas.draw()
    pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb())
    pilImage.save(buffer, "PNG")
    pylab.close()

Could you please help me to pass that graph into the html page?

A: It looks like you copied your code directly from https://www.eriksmistad.no/making-charts-and-outputing-them-as-images-to-the-browser-in-django/ but without the imports and definition.
You also left off the ending:
# Send buffer in a http response the the browser with the mime type image/png set
return HttpResponse(buffer.getvalue(), content_type="image/png")

But I wouldn't put this directly in my views.


text:
Q: Export from Excel to text file without line breaks I have a regular Excel spreadsheet with only 1 column. I want to export it to a text file with a separator. I am not interested in separating columns, since I only have one. My  concern is to export with separators instead of line breaks so that my final result is a simple list like this "item1","item2","item3"... and so on. item1, item2 and item3 were in the same column, in different rows in my Excel file. Is it possible to do this straight from Excel? I can only get the final file with line breaks. Thanks!

A: You will need to use "VBA" to loop over the cells in that column and print their content to a file.

A: If you want to be quick and inelegant, just use the cells to the right to concatenate with separation (semi-colon, say). Assuming your data starts in A2, put this in B2:
=A1

And put this in B3 and fill down:
=B2&";"&A3

The text you want is in the bottom cell of the B column.

A: If you don't want a vba solution and use max. 256 rows you can copy your used cells and paste them transposed to a different sheet in A1.
Now all the values are in a row and you can export/save the sheet as a *.csv. The cell values will be seperated by a semicolon but will not be quoted! Your texteditor should be able to replace ; with " ;".
The VBA loop is the better solution.

A: You may wish to use ADO and GetString.
Dim cn As Object
Dim rs As Object

strFile = Workbooks(1).FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

strSQL = "SELECT F1 FROM [Sheet1$]"

rs.Open strSQL, cn

str = rs.GetString(2,,"|")

Further information: http://www.w3schools.com/ADO/met_rs_getstring.asp


text:
Q: How to cut ellipse? I am drawing jigsaw using CAShapeLayer.Drawing a line that is easy part and also i did it.But now i want to draw ellipse with cutting some portion of that ellipse.Now my question is how can i cut ellipse using CGPathAddEllipseInRect?Here is my code :
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:self.bounds];
    [shapeLayer setPosition:self.center];
    [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
    [shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
    [shapeLayer setLineWidth:3.0f];

    // Setup the path
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 10, 10);
    CGPathAddLineToPoint(path, NULL, 75,10);
    CGPathAddEllipseInRect(path, NULL, CGRectMake(75, 10, 50, 20));
    [shapeLayer setPath:path];
    CGPathRelease(path);

    [[self layer] addSublayer:shapeLayer];

Hint will be appreciated.

A: Don't use CGPathAddEllipseInRect, instead you need to calculate the start and end positions and use CGPathAddArcToPoint or, more likely, CGPathAddQuadCurveToPoint.


text:
Q: What is the theoretical difference between method with type parameter and generics method type parameter declaration Hi all i am learning Generics in Java. in which i have created this hierarchy.
Now i have created a LivingThing class
public class LivingThing<T extends LivingThingTypes> implements Iterable<LivingThingTypes>{
public ArrayList<T> create(Class<T> type) {
        ArrayList arrayList = new ArrayList<>();
        for (T item : list) {
            if (item.getClass().equals(type)) {
                arrayList.add(item);
            }
        }
        return arrayList;
    }
}

So when i try to access create() method like this code of section it doesn't works.
livingList.create(Human.class).size();
livingList.create(Cat.class).size();
livingList.create(Hen.class).size();

But if i change method into this it works perfectly
public class LivingThing<T extends LivingThingTypes> implements Iterable<LivingThingTypes>{
        public <V extends LivingThingTypes>ArrayList<V> create(Class<V> type) {
            ArrayList arrayList = new ArrayList<>();
            for (T item : list) {
                if (item.getClass().equals(type)) {
                    arrayList.add(item);
                }
            }
            return arrayList;
        }
    }

A: The important thing about generics is that they are invariant. This means in your case that even though Human class extends LivingThingTypes but List<Human> doesn't extend List<LivingThingTypes>. So basically you can't do the following assignment:
List<Human> list1;

List<LivingThingTypes> list2 = list1; //compile error

That's how Generics are designed. The reason is imaging you have a Animal parent class and Dog and Cat as child classes. Now you created a List<Dog> and assigned it to List<Animal>. Now Since Animal is parent class of Cat also you can add cats to List<Animal>. Wile iterating it may give ClassCastException. Now the basic pros of using Generics is they provide Type safety but getting ClassCastException means that is not the case and thus the Generics are invariant.
But when you use extends along with Type parameter then it allows the assignment but then you have to remember PECS(Producer Extends and Consumer Super).
In your first case you have Type Parameter  declared at class level.  Now when you create instance of LivingThing class you have to mention the type parameter like LivingThing<LivingThingTypes> livingList = new LivingThing();. And that becomes the value of T. Now the compiler will expect you to send the same Type inside create method also because of the reason I mentioned in the earlier para.
In your second case you are creating a new Type parameter which is bound to the method only and here you are telling it that V extends LivingThingType and thus now Class<V> type argument of create method can accept Human.class/Hen.class/Cat.class. You can use the same Type parameter T also in place of V but to avoid confusion you should name them differently as you have done.

A: That was not working because of this concept defined in Java-Oracle-Docs.

(As Java Doc Says)
Given two concrete types A and B (for example, Number and Integer), MyClass has no relationship to MyClass, regardless of whether or not A and B are related. The common parent of MyClass and MyClass is Object.


text: Q: Supremum and infimum of a stochastic process Suppose $\{X_t\}_{t\geq 0}$ is a real-valued stochastic process satisfying $E[X^2_t]\rightarrow\infty$ as $t\rightarrow\infty$. Does it hold that $\sup |X_t|\rightarrow \infty$? Intuitively I think since the second moment of $X_t$ explodes, $X_t$ must diverge either from above or from below, or both. However, I simply don't know where to start to prove it.


text:
Q: Execute a script with GUI Access before login I need to execute a command-line tool to force maximum display brightness before user logs in (so login screen is shown with maximum brightness)
My problem is, if I run it from LaunchDaemons, it doesn't work. I think it is because from LaunchDaemons you can't run anything that interacts with the Window Server.
If I run it from LaunchAgents, it works. But it runs after login, so it is not an option.
Is there any alternative to LaunchDaemons to run scripts or programs that allow WindowServer access?

A: PreLoginAgents
macOS supports the ability to run graphical applications pre-login:

Running Agents Before Login
Most software that displays a user interface does not run prior to the user logging in. However, in some rare cases, it may be necessary to create a graphical agent that does.
By default, OS X does not allow any application to draw content prior to login. If you need to do so, your agent must call the setCanBecomeVisibleWithoutLogin: method on its windows. For more information, see the documentation for that method and the PreLoginAgents sample code.

The trick is to add the following lines to your /Library/LaunchAgents  launchd plist:
<key>LimitLoadToSessionType</key>
<string>LoginWindow</string>

The executable must be stored in /Library/PrivilegedHelperTools.
We used this ability to show a notification window pre-login for Power Manager pending events.
This functionality may not be supported in the latest macOS; we have not relied on it for a long while.


text:
Q: Comparison of Amazon S3, Amazon Athena, and Amazon Athena with partitioning I wanted to know the performance improvement when we use Amazon Athena without partitioning and with partitioning. I know for sure that Athena with partitioning is much better than Athena. But does Athena without partitioning give any improvement over Amazon S3?

A: Partitioning separates data files into separate directories. If the column used for partitioning is part of a query's WHERE clause, it allows Athena to skip-over directories that do not contain relevant data. This is highly effective at improve query performance (and lowering cost) because it reduces the need for disk access and memory.
There are several ways to improve the performance of Amazon Athena:

*

*Store data in a columnar format, such as Parquet. This allows Athena to go directly to specific columns without having to read all columns in a wide table. (This is similar to Amazon Redshift.)

*Compress data (eg using Snappy compression) to reduce the amount of data that needs to be read from disk. This also reduces the cost of queries since they are charged based on the amount of data read from disk. (Instant savings!)

*Partition data to completely skip-over input files when the partition key is used in a query's WHERE clause

For some examples of these benefits, see: Analyzing Data in S3 using Amazon Athena | AWS Big Data Blog


text:
Q: How can I add a floating label to a input? I want that when a user comes and tries to type text in "input" the label goes up, and if they leave that area blank it comes back to the original position. If user typed something over there it will stay up there.
I tried this code with input box with required it is working fine, but when I try to do this with input and add some content in input the label coming back down it need to be stay up there.

div{
  margin-top:40px;
}
.btn-add input[type="text"]{
    width: 90%;
    padding: 10px 20px 0 20px;
    border: none;
    border-bottom:1px solid #999;
    font-size: 140%;
    color: #000;
}
.btn-add input:focus ~ .floating-label{
    top: -20px;
    bottom: 10px;
    left: 10px;
    font-size: 20px;
    opacity: 1;
    color: rgb(100, 6, 6);
}
.floating-label {
    position: absolute;
    pointer-events: none;
    left: 20px;
    top:10px;
    transition: 0.2s ease all;
    color: #999999;
    font-size: 120%;
}
.form-float{
    position: relative;
}

     <input type="text" class="inputText" placeholder="" >
     Button text

I remove input:not(:focus):valid~.floating-label so it can work with not required field

A: Try this code since because of placeholder happening.

.form-group {
  position: relative;
  margin-bottom: 1.5rem;
}

input + .form-control-placeholder {
  position: absolute;
  transition: all 200ms;
  top: -20px;
    bottom: 10px;
    font-size: 20px;
    opacity: 1;
    color: rgb(100, 6, 6);
}

input:placeholder-shown + .form-control-placeholder {
      position: absolute;
    pointer-events: none;
    left: 20px;
    top:10px;
    transition: 0.2s ease all;
    color: #999999;
    font-size: 120%;
}

.form-control:focus + .form-control-placeholder {
  position: absolute;
  transition: all 200ms;
    top: -20px;
    bottom: 10px;
    font-size: 20px;
    opacity: 1;
    color: rgb(100, 6, 6);
}
input[type="text"]{
    width: 90%;
    padding: 10px 20px 0 20px;
    border: none;
    border-bottom:1px solid #999;
    font-size: 140%;
    color: #000;
}
label{
    position: absolute;
    pointer-events: none;
    left: 20px;
    top:10px;
    transition: 0.2s ease all;
    color: #999999;
    font-size: 120%;
}

  <input type="text" class="form-control" placeholder=" " >
  Button text

A: Add Space to you placeholder by default and after that use input:not(:placeholder-shown) property to check if input is empty or not. Here working example of your code

div{
  margin-top:40px;
}
.btn-add input[type="text"]{
    width: 90%;
    padding: 10px 20px 0 20px;
    border: none;
    border-bottom:1px solid #999;
    font-size: 140%;
    color: #000;
}
.btn-add input:focus ~ .floating-label{
    top: -20px;
    bottom: 10px;
    left: 10px;
    font-size: 20px;
    opacity: 1;
    color: rgb(100, 6, 6);
}
.btn-add input:not(:placeholder-shown) ~ .floating-label{
  top: -20px;
    bottom: 10px;
    left: 10px;
    font-size: 20px;
    opacity: 1;
    color: rgb(100, 6, 6);
}

.floating-label {
    position: absolute;
    pointer-events: none;
    left: 20px;
    top:10px;
    transition: 0.2s ease all;
    color: #999999;
    font-size: 120%;
}
.form-float{
    position: relative;
}

     <input type="text" class="inputText" placeholder=" " >
     Button text

A: Since :placeholder-shown only works with placeholder text shown (no empty string) you could use visibility.

div {
    margin-top:40px;
}
.btn-add input[type="text"] {
    width: 90%;
    padding: 10px 20px 0 20px;
    border: none;
    border-bottom:1px solid #999;
    font-size: 140%;
    color: #000;
}
.floating-label {
    position: absolute;
    pointer-events: none;
    left: 20px;
    top: -20px;
    transition: 0.2s ease all;
    color: #999999;
    font-size: 120%;
}
.form-float input:placeholder-shown ~ label {
    top: 0;
    visibility: hidden;
}

.form-float {
    position: relative;
}

    <input type="text" placeholder="Button Label" >
    Button Label

A: These are two solutions. I think they need some adjustment because probably they are not correct.
Solution #1: Floating label on focus

    .custom-form-input {
            display: block;
            width: 100%;
            height:32px;
            padding: 1rem .55rem .065rem .55rem;
            font-weight: 400;
            border: 1px solid #cad3d6;
            transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;
            background-color: #fafafa;
            font-size: 0.79em;
            color:#000000;
            border-radius: 2px;
            font-family: Arial, Helvetica, sans-serif;
        }

        .custom-form-input:focus,
        .custom-form-input:active {
            color: #212529;
            background-color: #fff;
            border-color: #585d61;
            outline: 0;
        }

        .custom-form-floating {
            position:relative;
        }

        .custom-form-floating-label {
            position:absolute;
            color: #9aa0a9;
            font-size: 0.85em;
            height:100%;
            width:100%;
            top: 0px;
            display:flex;
            align-items: center;
            padding: 0 .55rem 0 .55rem;
            transition: 0.2s ease all;
            -moz-transition: 0.2s ease all;
            -webkit-transition: 0.2s ease all;
            user-select: none;
            pointer-events: none

        }

        .custom-form-input:focus ~ label,
        .custom-form-input:valid ~ label {
          font-size: 0.65rem;
          height:55%;
        }

.wrapper {
  width:150px;
}

         <input id="test" class="custom-form-input" aria-label="usuario o correo electrónico" required=true aria-required="true"/>
         Example 1

         <input id="test" class="custom-form-input" aria-label="usuario o correo electrónico" required=true aria-required="true"/>
         Example 2

Solution #2: Floating label when type a letter

.custom-form-input {
    display: block;
    width: 100%;
    height: 5px;
    font-weight: 400;
    border: 1px solid #cad3d6;
    transition: border-color .15s ease-in-out;
    background-color: #fafafa;
    font-size: 1.2em;
    color: #000000;
    padding: 1rem .50rem 1rem .50rem;
    border-radius: 2px;
    font-family: Arial, Helvetica, sans-serif;
}

.custom-form-input:focus,
.custom-form-input:active {
    color: #212529;
    background-color: #fff;
    border-color: #585d61;
    outline: 0;
}

.custom-form-floating {
    position: relative;
}

.custom-form-floating-label {
    position: absolute;
    color: #9aa0a9;
    font-size: 0.85em;
    height: 100%;
    width: 100%;
    top: 0px;
    display: flex;
    align-items: center;
    padding: 0 .55rem 0 .55rem;
    transition: 0.2s ease all;
    -moz-transition: 0.2s ease all;
    -webkit-transition: 0.2s ease all;
    user-select: none;
    pointer-events: none
}

.custom-form-input:valid {
    padding: 1.50rem .50rem .50rem .50rem;
    font-size: 0.79em;
}

.custom-form-input:valid~label {
    font-size: 0.65rem;
    height: 55%;
}

.wrapper {
  width:250px;
}

                            <input id="test" class="custom-form-input"
                                aria-label="usuario o correo electrónico" required=true aria-required="true"/>
                            Correo electrónico o
                                usuario


text:
Q: Footer div is not being pushed down I have a div for the header, two divs in the middle and one div as the footer. The middle divs are set for float:left and float:right. When the middle divs grow vertically, I want the footer div to push down on the page. It currently only works in IE. On all other browsers, the footer div remains in the same spot and the other divs just overlap the footer. What am I doing incorrectly?
Also, all of these divs are wrapped in a parent div.
Thanks

A: Have you cleared float before the footer div?
If not, put a div before the footer div with the style
clear: both;


text:
Q: After performing KPA on Hill Cipher the matrix is formed wrong. Whenever I'm solving the hill cipher's key the final matrix is not in the original form. When I do the one from Wikipedia and also the one that I made myself neither comes back in the original form for the encryption or decryption key.
First Wikipedia example.
C=Cipher-text Matrix.
P=Plain-text Matrix.
C=
$\begin{bmatrix}
7&8& \\
0&19 \\
\end{bmatrix}$
P=$\begin{bmatrix}
7&4\\
11&15 \\
\end{bmatrix}$
To calculate the decryption key I have to setup the formula like so.
$D = [C]^{-1} ~\cdot P$
Then I calculate the modular multiplicative inverse of C as follows.
$[C]^{-1} = \det[C]^{-1} \cdot adj([C])$
$det[C]= (ad - bc) \mod 26$
$7*19 - 8*0 \mod 26 = 133 \mod 26 = 3 $
mod inverse of 3 mod 26 is 9.
$adj([C]) = \begin{bmatrix}19&-8\\0&7 \end{bmatrix}$
$[C]^{-1} =9 \cdot \begin{bmatrix}19&-8\\0&7 \end{bmatrix} \mod 26 \Rightarrow \begin{bmatrix}15&6\\0&11\end{bmatrix} $
$D=\begin{bmatrix}15&6 \\ 0&11 \end{bmatrix} \cdot \begin{bmatrix}7&4\\11&15\end{bmatrix} \mod 26 \Rightarrow \begin{bmatrix}129&255\\44&165\end{bmatrix} \mod 26 \Rightarrow D = \begin{bmatrix} 15&20\\17&9\end{bmatrix}$
Wikipedia's decryption matrix though is $\begin{bmatrix}15&17\\20&9\end{bmatrix}$
It seems to hold true for all matricies that I calculate that the end result matrix is $\begin{bmatrix}a&c\\b&d\end{bmatrix}$ every single time. I don't know if this is normal or not but I don't get it.
My own matricies.
$K=\begin{bmatrix}7&11\\8&11\end{bmatrix}$
$P=\begin{bmatrix}7&11\\4&11\end{bmatrix}$
$C=\begin{bmatrix}15&16\\22&1\end{bmatrix}$
$D=\begin{bmatrix}25&1\\22&23\end{bmatrix}$
If I convert my $C^{-1}$ and rotate it to instead be $\begin{bmatrix}a&c\\b&d\end{bmatrix}$ then I get back the encryption key correctly. I don't know what's going on with it though as the vectors are setup like wikipedia.
P.S.
I'm writing a lab to show the rest of the students how I solved a hill cipher CTF challenge utilizing the KPA against it but it seems like I've forgotten how in the world I solved it. My goal is to make it so that everyone at my community college who's interested in doing such events has the knowledge as to how to do such events. Somehow, somewhere I'm rotating things and I don't know how/why/where. I had it working Tuesday Morning at 01:30 when I woke up with the answer and did it on my phone's calculator but I didn't write it down and now I'm back into the same boat again.

A: Call the encryption matrix $E$. Then $E \cdot P = C$, so $E = C \cdot P^{-1}$ (so $P$ has to be invertible, which it is), or, if you really want the decryption matrix $D$ only, start from $D \cdot C = P$ and get $D = P \cdot C^{-1}$, which is in another order as you have.
$$C=
\begin{bmatrix}
7&0 \\
8&19 \\
\end{bmatrix}$$
(Using the Wikipedia preferred way of having the plain/cipher text in column vectors and we multiply $E$ on the right by what we're encrypting. $P$ is also transposed because of that)
And indeed $\det(C)=7 \cdot 19 = 3 \pmod{26}$ and its inverse is $9$.
So $$C^{-1} =9 \cdot \begin{bmatrix}19& 0 \\ -8 & 7 \end{bmatrix} \pmod {26} = \begin{bmatrix}15&0 \\6 &11\end{bmatrix} $$
which checks out.
So the decryption matrix becomes $$D = P \cdot C^{-1}= \begin{bmatrix} 7&11 \\ 4&15 \\
\end{bmatrix} \cdot \begin{bmatrix}15&0\\6 &11\end{bmatrix} = \begin{bmatrix} 15 &17\\ 20 & 9 \end{bmatrix}$$


text:
Q: Loosing the generic type parameter when calling getActualTypeArguments public class RemoveCategoryCommandHandler extends BaseCommandHandler<Categenter code hereory>
    implements CommandHandler<RemoveCategory> {

        public RemoveCategoryCommandHandler(RepositoryFactory repositoryfactory) {
        super(repositoryfactory);
        }

        public abstract class BaseCommandHandler<T extends AggregateRoot> {

            protected final Repository<T> repository;

            protected BaseCommandHandler(RepositoryFactory repositoryfactory) {
                this.repository = repositoryfactory.<T>create();
            }

        }

        public class RepositoryFactory {
            private final EventStore eventstore;
            private final EventPublisher eventPublisher;

            public RepositoryFactory(EventStore eventstore, EventPublisher eventPublisher) {
                this.eventstore = eventstore;
                this.eventPublisher = eventPublisher;
            }
            public <T extends AggregateRoot> Repository<T> create() {

                return new AggregateRepository<T>(eventstore, eventPublisher) {
                    @Override
                    public void save(T aggregate, int version) {
                        super.save(aggregate, version);
                    }
                };
            }
        }
    }

Given the above scenario where in RemoveCategoryCommandHandler I am
  passing a RepositoryFactory which return me an AgreegateRepository of
  Type T.
When I am calling the below code , clazz = getclass() on repository.

 ParameterizedType pt = (ParameterizedType) clazz.getGenericSuperclass();
            @SuppressWarnings("unchecked")
              Class<? extends AggregateRoot> parameterizedClazz = (Class<? extends AggregateRoot>) pt.getActualTypeArguments()[0];

repository = new AggregateRepository<Category>(store, new SimpleEventPublisher(resolver)) {
    @Override
    public void save(Category aggregate, int version) {
        super.save(aggregate, version);
    }
};

I am getting the below error
      java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast
  to java.lang.Class

But if I directly use the code in the handler it works.
Why am I losing the parameter type?

A: You are not loosing the parameter type. You get it returned by pt.getActualTypeArguments()[0].
But, instead of (what you for some reason expect) Class the returned type argument is a TypeVariable. Which is correct.
To get your Class check getBounds().


text:
Q: What is the backbone @$el exactly? in many tutorials I see that people do this:
view = new Raffler.Views.EntriesIndex(collection: @collection)
$('body').html(view.render().el)

And then in the view of EntriesIndex he does:
render: ->
  @$el.html(@template())

I thought that with @$el it was say: hey render this template in the parent element(in this case it's body)...but it doesn't work and not show anything...If I use $('body').html(@template()) instead all works fine.
Now...why people use @$el in tutorials(I've seen this in 2-3 tutorials) ?

A: In Backbone, views usually store a reference to their element, wrapped in jQuery. This is usually named this.$el.
The $ sign indicates that this is not simply a DOM Element, but a full flegded jQuery instance. This means you can call methods like $el.find() and $el.children().
In CoffeeScript, @ is a shortcut for this. So @$el means precisely this.$el.


text:
Q: How can you add warning flags using cmake cross platform? I see a number of articles that suggest you check for compiler and add flags as appropriate, eg.
if (CMAKE_COMPILER_IS_GNUCC)
  ...
endif()
if (MSVC)
  ...
endif()
This is a deeply undesirable situation though.
It relies on you having, for every project, to add specific support for each compiler that you support, one at a time.
Other things, like C++11 features and debug flags are automatically generated by cmake for each of the compilers it supports.
Is there no equivalent solution for adding the equivalent of -Wall / /W3 to the compile simply via a cmake setting?

A:
It relies on you having, for every project, to add specific support for each >compiler that you support, one at a time.

At now you can only have something like compiler.cmake, where you configure suitable flags for each compiler, and share compiler.cmake among projects.

Is there no equivalent solution for adding the equivalent of -Wall / /W3 to the >compile simply via a cmake setting?

No, now there is only disscussion about similar feature and it's possible implementation, see
https://cmake.org/pipermail/cmake-developers/2016-March/028107.html

A: For anyone else who finds this...
There is a reasonably robust implementation of this which can be found here, as a 3rd party addition:
https://github.com/ruslo/sugar/wiki/Cross-platform-warning-suppression
You use it like this:
## Project
cmake_minimum_required(VERSION 3.1)
project(npp)

# Dependencies
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/npp)
... whatever ...

# Clone entire sugar repo to source folder and import
include(${CMAKE_CURRENT_SOURCE_DIR}/sugar/cmake/Sugar)
include(sugar_generate_warning_flags)

# Generate flags, included excluded flags, etc.
# see: https://github.com/ruslo/leathers/wiki/List
sugar_generate_warning_flags(
  flags
  properties
  ENABLE ALL
  DISABLE c++98-compat padded
  TREAT_AS_ERROR ALL
  CLEAR_GLOBAL)

# Library / executable if any
file(GLOB_RECURSE SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/npp/*.cpp)
add_library(npp STATIC ${SOURCES})

# Set flags
set_target_properties(npp PROPERTIES ${properties} COMPILE_OPTIONS "${flags}")

# Local tests
enable_testing()
add_executable(tests "${CMAKE_CURRENT_SOURCE_DIR}/tests/tests.cpp")

# Set flags
set_target_properties(tests PROPERTIES ${properties} COMPILE_OPTIONS "${flags}")
target_link_libraries(tests npp)
add_test(tests tests)

Obviously this is far from ideal, as it's quite irritating to have to clone a set of modules, but it's practical for the moment.


text:
Q: Halo CE Windows 10 dx fatal error
This is the error I get when I try to open Halo CE. So far I've tried installing directx web installer but I already have the latest dx so it was useless. Not sure what else to do. Can I get some help solving this?

A: You should be able to play on Windows 10 with a patch that Bungie provided several years ago.
Halo PC/CE 1.0.10 now available


text:
Q: Eclipse Oxygen Java giving empty error I have some Java that, in theory, draws a line from the top left corner to the bottom right corner of the 500x500 window. The code:
import javax.swing.JComponent;
import javax.swing.JFrame;

import java.awt.*;
import java.awt.geom.*;

@SuppressWarnings("serial")

public class graphix extends JFrame{

    public static void main(String[] args){

        new graphix();
    }

    public graphix(){

        this.setSize(500, 500);

        this.setTitle("Title Here");

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.add(new Draw(), BorderLayout.CENTER);

        this.setVisible(true);

    }

    private class Draw extends JComponent{

        public void paint(Graphics g){

            Graphics2D graph2 = (Graphics2D)g;

            graph2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            Shape drawLine = new Line2D.Float(10, 10, 490, 490);

            graph2.setPaint(Color.BLACK);

            graph2.draw(drawLine);

        }

    }

}

When i run this code, eclipse gives me the error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:

at graphix.graphix.main(graphix.java:11)

normally in eclipse, the error message will be displayed in the empty space between those two lines, but it says the error is triggered at line 11, which is
public static void main(String[] args){

My project name is graphix, and the class file name is graphix.java
EDIT:
There is also a non-fatal error:
The declared package "" does not match the expected package "graphix"

triggered by:
import javax.swing.JComponent;

A: The package declaration is missing on the top of the file, it must match the file structure inside your project:
package xxx.yyy.zzz;