问:
400 Bad Request - Ajax with Jquery and Wordpress
Iḿ trying to use ajax in my JQuery script to read a JQuery var into functions.php of Wordpress.

```<code>$.ajax({

    url: js_admin_url.ajax_url,
                  type: 'POST',
                  beforeSend: function(xhr) {
                    xhr.setRequestHeader("Authorization", "CloudSight [key]");
                  },
                  data: JSON.stringify({
                      'action': 'send_ranking_data', // Ação do Ajax
                      '_ajax_nonce': js_admin_url.nonce,
                      's': settings.ranking // O que vamos postar para $_POST
                  }),
                  dataType: "json",
                  contentType: "application/json",
                  success: function(response) { console.log(response); },
                  error: function(e) { console.log(e); }
              });

</code>```

Status Code: 400 Bad Request

答:
I see at least that you shouldn't be using JSON.stringify with your ajax data, just do:

```<code>data: {
    'action': 'send_ranking_data',
    '_ajax_nonce': js_admin_url.nonce,
    's': settings.ranking
}
</code>```

And that will automatically send the data as JSON

Body:
Iḿ trying to use ajax in my JQuery script to read a JQuery var into functions.php of Wordpress.

$.ajax({

    url: js_admin_url.ajax_url,
                  type: 'POST',
                  beforeSend: function(xhr) {
                    xhr.setRequestHeader("Authorization", "CloudSight [key]");
                  },
                  data: JSON.stringify({
                      'action': 'send_ranking_data', // Ação do Ajax
                      '_ajax_nonce': js_admin_url.nonce,
                      's': settings.ranking // O que vamos postar para $_POST
                  }),
                  dataType: "json",
                  contentType: "application/json",
                  success: function(response) { console.log(response); },
                  error: function(e) { console.log(e); }
              });

Status Code: 400 Bad Request

Body:
I see at least that you shouldn't be using JSON.stringify with your ajax data, just do:

data: {
    'action': 'send_ranking_data',
    '_ajax_nonce': js_admin_url.nonce,
    's': settings.ranking
}

And that will automatically send the data as JSON


来源: stackexchange

问:
Controller sends null value in a set command in Symfony2
I have a controller that inserts new records, but sends NULL value to idUsuario which is the ID of the user who is creating the new record.

I have already checked the entity file, the estructure of the table, even setting a manual value like 1. I have tried the sql command directly in mysql command window and the problem in that idUsuario is comming NULL.

Controller:

```<code>  function createAction ....
    $user = $this->getUser();
    $idUser = $user->getId();

    $entity = new InProveedor();
    $entity->setIdUsuario($idUser);
    $em = $this->getDoctrine()->getManager();
    $em->persist($entity);
    $em->flush();
</code>```

Entity:

```<code>/**
 * @ORM\ManyToOne(targetEntity="Nival\AccesoBundle\Entity\AdUsuario",
   inversedBy="proveedorUsuario")
 * @ORM\JoinColumn(name="id_usuario", referencedColumnName="id_usuario")
 */
protected $proveedorUsuario;

/**
 * @var integer
 *
 * @ORM\Column(name="id_usuario", type="integer", nullable=false)
 */
private $idUsuario;

/**
 * Set idUsuario
 *
 * @param integer $idUsuario
 * @return InProveedor
 */
public function setIdUsuario($idUsuario)
{
    $this->idUsuario = $idUsuario;

    return $this;
}

/**
 * Get idUsuario
 *
 * @return integer
 */
public function getIdUsuario()
{
    return $this->idUsuario;
}
</code>```

An exception occurred while executing 'INSERT INTO in_proveedor (razon_social, nombre_comercial, direccion, telefono, email, nrc, nit, contacto, fecha_ingreso, id_forma_pago, dias_entrega, id_aut1_asig, id_notificado, fecha_notificado, id_aut1, fecha_aut1, id_categoria, id_usuario, fecha_creado, activo, id_empresaa) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["GM Consulting SA de CV", "GM Consulting SA de CV", "9 Calle poniente 81 Ave norte col Escal\u00f3n 7-29, San Salvador", "22875000", "gmccapacitaciones2019@gmail.com", "22222", "222", "Astrid Cuadra", "2019-05-28", 1, null, 1, null, null, null, null, 1, null, "2019-05-28 20:50:41", 0, "2"]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id_usuario' cannot be null

So, it seems that even if I set a value for field idUsuario, it always return as NULL. Please help me out.

答: Well, what I did it was so weird, I had to remove the relationship beteewen tables, and save a record with the ID, then I put back the relationship in the entity files (both: AdUsuario and InProveedor) and it worked properly.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a controller that inserts new records, but sends NULL value to idUsuario which is the ID of the user who is creating the new record.

I have already checked the entity file, the estructure of the table, even setting a manual value like 1. I have tried the sql command directly in mysql command window and the problem in that idUsuario is comming NULL.

Controller:

  function createAction ....
    $user = $this->getUser();
    $idUser = $user->getId();

    $entity = new InProveedor();
    $entity->setIdUsuario($idUser);
    $em = $this->getDoctrine()->getManager();
    $em->persist($entity);
    $em->flush();

Entity:

/**
 * @ORM\ManyToOne(targetEntity="Nival\AccesoBundle\Entity\AdUsuario",
   inversedBy="proveedorUsuario")
 * @ORM\JoinColumn(name="id_usuario", referencedColumnName="id_usuario")
 */
protected $proveedorUsuario;

/**
 * @var integer
 *
 * @ORM\Column(name="id_usuario", type="integer", nullable=false)
 */
private $idUsuario;

/**
 * Set idUsuario
 *
 * @param integer $idUsuario
 * @return InProveedor
 */
public function setIdUsuario($idUsuario)
{
    $this->idUsuario = $idUsuario;

    return $this;
}

/**
 * Get idUsuario
 *
 * @return integer
 */
public function getIdUsuario()
{
    return $this->idUsuario;
}

An exception occurred while executing 'INSERT INTO in_proveedor (razon_social, nombre_comercial, direccion, telefono, email, nrc, nit, contacto, fecha_ingreso, id_forma_pago, dias_entrega, id_aut1_asig, id_notificado, fecha_notificado, id_aut1, fecha_aut1, id_categoria, id_usuario, fecha_creado, activo, id_empresaa) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["GM Consulting SA de CV", "GM Consulting SA de CV", "9 Calle poniente 81 Ave norte col Escal\u00f3n 7-29, San Salvador", "22875000", "gmccapacitaciones2019@gmail.com", "22222", "222", "Astrid Cuadra", "2019-05-28", 1, null, 1, null, null, null, null, 1, null, "2019-05-28 20:50:41", 0, "2"]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id_usuario' cannot be null

So, it seems that even if I set a value for field idUsuario, it always return as NULL. Please help me out.


问:
Change your "From Email" in Gmail
I receive forwarded emails from an email like info@companyname.com to my Gmail account; when I respond to these emails, I want they look as if they came from info@companyname.com instead of my Gmail account.

Is this possible?

答:
Yes, this is entirely possible.

Here's a link to google's knowledgebase describing exactly what to do: http://mail.google.com/support/bin/answer.py?answer=22370

ContentLicense: CC BY-SA 3.0

Title: Change your "From Email" in Gmail


问:
Unique identifier for Racket objects?
Is there a way to get a unique identifier for an object in Racket? For instance, when we use Racket's eq? operator to check whether two variables refer to the same object, what identifier is it using to achieve this comparison?

I'm looking for something like python's id function or Ruby's object_id method, in other words, some function id such that (= (id obj) (id obj2)) means that (eq? obj obj2) is true.

Some relevant docs:

Object Identity and Comparisons

Variables and Locations

答:
You most likely won't find an identity, but the object itself is only eq? with itself and nothing else. eq? basically compares the address location of the values. So if you want an id you can just store the whole object at that place and it will be unique.

A location is a binding. Think of it as an address you cannot get and an address which has an address to a object. Eg. a binding ((lambda (a) a) 10) would store the address location of the object 10 in the first stack address and the code in the body just returns that same address. A location can change by set! but you'll never get the memory location of it.

It's common for lisp systems to store values in pointers. That means that some types and values doesn't really have an object at the address, but the address has a value and type encoded in it that the system knows. Typically small integers, chars, symbols and booleans can be pointer equal even though they are constructed at different times. eg. '(1 2 3) would only use 3 pairs and not any space for the values 1-3 and ().

Title: Unique identifier for Racket objects?


问:
Why would I get an error that an input VMID does not resolve to a single virtual machine?
I'm using PowerShell to connect to a Hyper-V virtual machine.  But for some reason when I try to start a PSSession, I get the error "The input VMID  does not resolve to a single virtual machine."

The code looks like this:

```<code>$HyperVServerName = "TheServerName"
$VMName = "AValidVMName"
$SnapshotName = "ASnapshotName"
$creds = Get-Credential

Restore-VMSnapshot -ComputerName $HyperVServerName -VMName $VMName -Name $SnapshotName -Confirm:$false

Start-VM -ComputerName $HyperVServerName -Name $VMName

#Do some checks to make sure the VM is running...

$VMID = (Get-VM -ComputerName $HyperVServerName -Name $VMName).ID

If(-Not ($VMID -eq $null))
{
    $psSession = New-PSSession -VMId $VMID -Credential $creds
    If(-Not ($psSession -eq $null))
    {
        Enter-PSSession -Session $psSession
        #Do some stuff here...
    }
}
</code>```

I'm getting the error on the line $psSession = New-PSSession -VMId $VMID -Credential $creds.

More Information about the error:

CategoryInfo: InvalidArgument (:) [New-PSSession], ArgumentException

FullyQualifiedErrorId : InvalidVMIdNotSingle,Microsoft.PowerShell.Commands.NewPSSessionCommand

Any ideas on what's causing this error, and how I can correct it?

I was able to run commands on the VM before, but I tried to modify the code so that I didn't have to supply the host name of the VM when using Invoke-Command.

答:
Just a few thoughts here, and not real sure why you are targeting the VMId, but it's a choice.

I am just calling stuff dynamically here to avoid, well, you know...

```<code>$HyperVServerName = $env:COMPUTERNAME
$VMName = (Get-VM)[3].Name
$creds = Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME"

# I am using variable squeezing to assign and output info. In prod you'd remove those parens.
($VMID = (Get-VM -ComputerName $HyperVServerName -Name $VMName).ID)

<#
When it comes to PSRemotig, it's one or the other
- Implicit = New-PSSession - remote command stuff - Invoke-Command, etc...
- Explicit = Enter-PSSssion - user ineractive stuff
they cannot be use on the same target at the same time, it's redundant.

Also, the $VMID would never be not null, becasue you are directly populating it above.
#>

If(-Not ($VMID -eq $null))
{
    <#
    There is going to be an Implicit PSRemoting session when you do this
    You can see this, if you output the info as you call it. Well, in testing.
    I am using variable squeezing to assign and output info. In prod you'd remove those parens.
    #>
    ($psSession = New-PSSession -VMId $VMID -Credential $creds)

    <#
    So this is moot. The session wll never be -Not null, becasue of the previous command,
    Unless the session connection failed, then you should be catching that error anyway.
    so, don't do this Explicit command, if you are directly setting an Implicit one.
    Even in your code below, it's still moot, as you are trying to use that $pssession
    which does not exist, via the ENter-PSSession.

    So, if $pssession is null, the Enter-PSSEssion is also moot.
    #>

    <#
    If(-Not ($psSession -eq $null))
    {

        Enter-PSSession -Session $psSession
        #Do some stuff here...
    }
    #>

}

# So, you code could be something like.

$HyperVServerName = "TheServerName"
$VMName = "AValidVMName"
$SnapshotName = "ASnapshotName"
$creds = Get-Credential

Restore-VMSnapshot -ComputerName $HyperVServerName -VMName $VMName -Name $SnapshotName -Confirm:$false

Start-VM -ComputerName $HyperVServerName -Name $VMName

#Do some checks to make sure the VM is running...
($VMHost = Get-VM -ComputerName $HyperVServerName -Name $VMName)

Try
{
    ($psSession = New-PSSession -VMId $VMHost.Name -Credential $creds)
    # Do some stuff here
}
Catch
{
    Write-Warning -Message "Error calling the implicit remote session for $($VMHost.Name). Starting explicit session for $($VMHost.Name)."
    $Error | Format-List -Force | Out-String | clip | notepad
    Start-Sleep -Seconds 1
    [void][reflection.assembly]::loadwithpartialname("system.windows.forms")
    [system.windows.forms.sendkeys]::SendWait('^v')

    Enter-PSSession -ComputerName $($VMHost.Name) -Credential $creds
    #Do some stuff here...
}
</code>```

Body:
I'm using PowerShell to connect to a Hyper-V virtual machine.  But for some reason when I try to start a PSSession, I get the error "The input VMID  does not resolve to a single virtual machine."

The code looks like this:

$HyperVServerName = "TheServerName"
$VMName = "AValidVMName"
$SnapshotName = "ASnapshotName"
$creds = Get-Credential

Restore-VMSnapshot -ComputerName $HyperVServerName -VMName $VMName -Name $SnapshotName -Confirm:$false

Start-VM -ComputerName $HyperVServerName -Name $VMName

#Do some checks to make sure the VM is running...

$VMID = (Get-VM -ComputerName $HyperVServerName -Name $VMName).ID

If(-Not ($VMID -eq $null))
{
    $psSession = New-PSSession -VMId $VMID -Credential $creds
    If(-Not ($psSession -eq $null))
    {
        Enter-PSSession -Session $psSession
        #Do some stuff here...
    }
}

I'm getting the error on the line $psSession = New-PSSession -VMId $VMID -Credential $creds.

More Information about the error:

CategoryInfo: InvalidArgument (:) [New-PSSession], ArgumentException

FullyQualifiedErrorId : InvalidVMIdNotSingle,Microsoft.PowerShell.Commands.NewPSSessionCommand

Any ideas on what's causing this error, and how I can correct it?

I was able to run commands on the VM before, but I tried to modify the code so that I didn't have to supply the host name of the VM when using Invoke-Command.

Body:
Just a few thoughts here, and not real sure why you are targeting the VMId, but it's a choice.

I am just calling stuff dynamically here to avoid, well, you know...

$HyperVServerName = $env:COMPUTERNAME
$VMName = (Get-VM)[3].Name
$creds = Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME"

# I am using variable squeezing to assign and output info. In prod you'd remove those parens.
($VMID = (Get-VM -ComputerName $HyperVServerName -Name $VMName).ID)

<#
When it comes to PSRemotig, it's one or the other
- Implicit = New-PSSession - remote command stuff - Invoke-Command, etc...
- Explicit = Enter-PSSssion - user ineractive stuff
they cannot be use on the same target at the same time, it's redundant.

Also, the $VMID would never be not null, becasue you are directly populating it above.
#>

If(-Not ($VMID -eq $null))
{
    <#
    There is going to be an Implicit PSRemoting session when you do this
    You can see this, if you output the info as you call it. Well, in testing.
    I am using variable squeezing to assign and output info. In prod you'd remove those parens.
    #>
    ($psSession = New-PSSession -VMId $VMID -Credential $creds)

    <#
    So this is moot. The session wll never be -Not null, becasue of the previous command,
    Unless the session connection failed, then you should be catching that error anyway.
    so, don't do this Explicit command, if you are directly setting an Implicit one.
    Even in your code below, it's still moot, as you are trying to use that $pssession
    which does not exist, via the ENter-PSSession.

    So, if $pssession is null, the Enter-PSSEssion is also moot.
    #>

    <#
    If(-Not ($psSession -eq $null))
    {

        Enter-PSSession -Session $psSession
        #Do some stuff here...
    }
    #>

}

# So, you code could be something like.

$HyperVServerName = "TheServerName"
$VMName = "AValidVMName"
$SnapshotName = "ASnapshotName"
$creds = Get-Credential

Restore-VMSnapshot -ComputerName $HyperVServerName -VMName $VMName -Name $SnapshotName -Confirm:$false

Start-VM -ComputerName $HyperVServerName -Name $VMName

#Do some checks to make sure the VM is running...
($VMHost = Get-VM -ComputerName $HyperVServerName -Name $VMName)

Try
{
    ($psSession = New-PSSession -VMId $VMHost.Name -Credential $creds)
    # Do some stuff here
}
Catch
{
    Write-Warning -Message "Error calling the implicit remote session for $($VMHost.Name). Starting explicit session for $($VMHost.Name)."
    $Error | Format-List -Force | Out-String | clip | notepad
    Start-Sleep -Seconds 1
    [void][reflection.assembly]::loadwithpartialname("system.windows.forms")
    [system.windows.forms.sendkeys]::SendWait('^v')

    Enter-PSSession -ComputerName $($VMHost.Name) -Credential $creds
    #Do some stuff here...
}


问:
Oracle How to Map Data Types to CODE/IDs - Dump and dbms_sql.define_column produce data type codes
When using DUMP() or when using dbms_sql.define_column both return the CODE of the Oracle Data type.

Is there a MAP that ties the Oracle Data Types to their Oracle CODEs that are returned by the DUMP() function or the dbms_sql.define_column feature?

I'm looking for this to aid in testing as well as to locate custom data types such as a NESTED TABLE.  A nested table exists in one of my tables and produces a Data Type Code of 109.  How do I lookup the type that is associated with Type Code of 109?  Examples below of dump and dbms_sql.define_column.

I must assume this is available within the database to query due to the fact that when I write a query I define the columns using the 'TEXT' name of the column type and NOT the Code.  So where is the text aka name of my data types  stored whether they are 'built-in' or 'custom'?  It's got to be somewhere.

DUMP

```<code>SELECT
    DUMP(to_date('15-JAN-18'),10,1,1) AS date_type
  , DUMP(123,10,1,1)   AS num_type
  , DUMP('abc',10,1,1) AS var_type
FROM dual
;
</code>```

Dump Output

```<code>/* OUTPUT:
 |
 | "DATE_TYPE"          "NUM_TYPE"          "VAR_TYPE"
 |--------------------|-------------------|------------------
 | "Typ=13 Len=8: 226"  "Typ=2 Len=3: 194"  "Typ=96 Len=3: 97"
*/
</code>```

DBMS_SQL.DEFINE_COLUMN

```<code>... some code above ...

-- Define columns:
FOR i IN 1..n_colcnt
LOOP
    dbms_output.put_line(v_desctab(i).col_name ||': ' || v_desctab(i).col_type);

    IF v_desctab(i).col_type = 2
    THEN dbms_sql.DEFINE_COLUMN(n_curid, i, v_num_var);
    ELSIF v_desctab(i).col_type = 12 THEN
        dbms_sql.define_column(n_curid, i, v_date_var);
    ELSE
        dbms_sql.define_column(n_curid, i, v_name_var, 50);
    END IF;
END LOOP;

... some code below ...
</code>```

DBMS_SQL.DEFINE_COLUMN Output - Outputs column names and their data type CODEs.  I want Text instead.

```<code>QUERY_ID: 2
OTHER_ID: 2
ACTIVE: 1
QUERY_NAME: 1
QUERY_DESC: 1
QUERY_DEF: 112
QUERY_TYPE: 2
CREATED: 12
UPDATED: 12
CREATED_BY: 2
UPDATED_BY: 2
</code>```

One thing I have regarding a mapping of Oracle Data Types to their corresponding IDs is an excel file I continue to reference.  I am hoping there is something I can query within Oracle to give me what I'm looking for rather than referencing an external document.

There is THIS link however this doesn't assist me when I'm looking for Custom Types and it missing documentation for CODE 13.

Here is another very nice Data Type Map somebody put together: Oracle Type Code Mappings

答:
The 'in-built' list can be seen from the view text for DBA_TAB_COLS_V$ (which underlies views like DBA_TAB_COLUMNS). 12.2 should be something like this:</p>

```<code>decode(c.type#, 1, decode(c.charsetform, 2, 'NVARCHAR2', 'VARCHAR2'),
                   2, decode(c.scale, null,
                             decode(c.precision#, null, 'NUMBER', 'FLOAT'),
                             'NUMBER'),
                   8, 'LONG',
                   9, decode(c.charsetform, 2, 'NCHAR VARYING', 'VARCHAR'),
                   12, 'DATE',
                   23, 'RAW', 24, 'LONG RAW',
                   58, nvl2(ac.synobj#, (select o.name from obj$ o
                            where o.obj#=ac.synobj#), ot.name),
                   69, 'ROWID',
                   96, decode(c.charsetform, 2, 'NCHAR', 'CHAR'),
                   100, 'BINARY_FLOAT',
                   101, 'BINARY_DOUBLE',
                   105, 'MLSLABEL',
                   106, 'MLSLABEL',
                   111, nvl2(ac.synobj#, (select o.name from obj$ o
                             where o.obj#=ac.synobj#), ot.name),
                   112, decode(c.charsetform, 2, 'NCLOB', 'CLOB'),
                   113, 'BLOB', 114, 'BFILE', 115, 'CFILE',
                   121, nvl2(ac.synobj#, (select o.name from obj$ o
                             where o.obj#=ac.synobj#), ot.name),
                   122, nvl2(ac.synobj#, (select o.name from obj$ o
                             where o.obj#=ac.synobj#), ot.name),
                   123, nvl2(ac.synobj#, (select o.name from obj$ o
                             where o.obj#=ac.synobj#), ot.name),
                   178, 'TIME(' ||c.scale|| ')',
                   179, 'TIME(' ||c.scale|| ')' || ' WITH TIME ZONE',
                   180, 'TIMESTAMP(' ||c.scale|| ')',
                   181, 'TIMESTAMP(' ||c.scale|| ')' || ' WITH TIME ZONE',
                   231, 'TIMESTAMP(' ||c.scale|| ')' || ' WITH LOCAL TIME ZONE',
                   182, 'INTERVAL YEAR(' ||c.precision#||') TO MONTH',
                   183, 'INTERVAL DAY(' ||c.precision#||') TO SECOND(' ||
                         c.scale || ')',
                   208, 'UROWID',
                   'UNDEFINED')
</code>```

Body:
When using DUMP() or when using dbms_sql.define_column both return the CODE of the Oracle Data type.

Is there a MAP that ties the Oracle Data Types to their Oracle CODEs that are returned by the DUMP() function or the dbms_sql.define_column feature?

I'm looking for this to aid in testing as well as to locate custom data types such as a NESTED TABLE.  A nested table exists in one of my tables and produces a Data Type Code of 109.  How do I lookup the type that is associated with Type Code of 109?  Examples below of dump and dbms_sql.define_column.

I must assume this is available within the database to query due to the fact that when I write a query I define the columns using the 'TEXT' name of the column type and NOT the Code.  So where is the text aka name of my data types  stored whether they are 'built-in' or 'custom'?  It's got to be somewhere.

DUMP

SELECT
    DUMP(to_date('15-JAN-18'),10,1,1) AS date_type
  , DUMP(123,10,1,1)   AS num_type
  , DUMP('abc',10,1,1) AS var_type
FROM dual
;

Dump Output

/* OUTPUT:
 |
 | "DATE_TYPE"          "NUM_TYPE"          "VAR_TYPE"
 |--------------------|-------------------|------------------
 | "Typ=13 Len=8: 226"  "Typ=2 Len=3: 194"  "Typ=96 Len=3: 97"
*/

DBMS_SQL.DEFINE_COLUMN

... some code above ...

-- Define columns:
FOR i IN 1..n_colcnt
LOOP
    dbms_output.put_line(v_desctab(i).col_name ||': ' || v_desctab(i).col_type);

    IF v_desctab(i).col_type = 2
    THEN dbms_sql.DEFINE_COLUMN(n_curid, i, v_num_var);
    ELSIF v_desctab(i).col_type = 12 THEN
        dbms_sql.define_column(n_curid, i, v_date_var);
    ELSE
        dbms_sql.define_column(n_curid, i, v_name_var, 50);
    END IF;
END LOOP;

... some code below ...

DBMS_SQL.DEFINE_COLUMN Output - Outputs column names and their data type CODEs.  I want Text instead.

QUERY_ID: 2
OTHER_ID: 2
ACTIVE: 1
QUERY_NAME: 1
QUERY_DESC: 1
QUERY_DEF: 112
QUERY_TYPE: 2
CREATED: 12
UPDATED: 12
CREATED_BY: 2
UPDATED_BY: 2

One thing I have regarding a mapping of Oracle Data Types to their corresponding IDs is an excel file I continue to reference.  I am hoping there is something I can query within Oracle to give me what I'm looking for rather than referencing an external document.

There is THIS link however this doesn't assist me when I'm looking for Custom Types and it missing documentation for CODE 13.

Here is another very nice Data Type Map somebody put together: Oracle Type Code Mappings

Body:
The 'in-built' list can be seen from the view text for DBA_TAB_COLS_V$ (which underlies views like DBA_TAB_COLUMNS). 12.2 should be something like this:

decode(c.type#, 1, decode(c.charsetform, 2, 'NVARCHAR2', 'VARCHAR2'),
                   2, decode(c.scale, null,
                             decode(c.precision#, null, 'NUMBER', 'FLOAT'),
                             'NUMBER'),
                   8, 'LONG',
                   9, decode(c.charsetform, 2, 'NCHAR VARYING', 'VARCHAR'),
                   12, 'DATE',
                   23, 'RAW', 24, 'LONG RAW',
                   58, nvl2(ac.synobj#, (select o.name from obj$ o
                            where o.obj#=ac.synobj#), ot.name),
                   69, 'ROWID',
                   96, decode(c.charsetform, 2, 'NCHAR', 'CHAR'),
                   100, 'BINARY_FLOAT',
                   101, 'BINARY_DOUBLE',
                   105, 'MLSLABEL',
                   106, 'MLSLABEL',
                   111, nvl2(ac.synobj#, (select o.name from obj$ o
                             where o.obj#=ac.synobj#), ot.name),
                   112, decode(c.charsetform, 2, 'NCLOB', 'CLOB'),
                   113, 'BLOB', 114, 'BFILE', 115, 'CFILE',
                   121, nvl2(ac.synobj#, (select o.name from obj$ o
                             where o.obj#=ac.synobj#), ot.name),
                   122, nvl2(ac.synobj#, (select o.name from obj$ o
                             where o.obj#=ac.synobj#), ot.name),
                   123, nvl2(ac.synobj#, (select o.name from obj$ o
                             where o.obj#=ac.synobj#), ot.name),
                   178, 'TIME(' ||c.scale|| ')',
                   179, 'TIME(' ||c.scale|| ')' || ' WITH TIME ZONE',
                   180, 'TIMESTAMP(' ||c.scale|| ')',
                   181, 'TIMESTAMP(' ||c.scale|| ')' || ' WITH TIME ZONE',
                   231, 'TIMESTAMP(' ||c.scale|| ')' || ' WITH LOCAL TIME ZONE',
                   182, 'INTERVAL YEAR(' ||c.precision#||') TO MONTH',
                   183, 'INTERVAL DAY(' ||c.precision#||') TO SECOND(' ||
                         c.scale || ')',
                   208, 'UROWID',
                   'UNDEFINED')


问:
Add value to one column in query results
I have a query in a spreadsheet:

```<code>=IFERROR(QUERY(swgohEventsCal!$A$2:$D,"SELECT A,B,C where A contains 'TB' and C >= date '"&TEXT(TODAY(),"yyyy-MM-dd")&"' order by B limit 4", 0),"Nothing Scheduled!")
</code>```

Column B displays a date and time, but the time defaults to 12 AM.  What I would like to do is add 24 hours, or one day, to that time.

So when the result is 5/26/2019 0:00:00, I would like for it to display 5/27/2019 0:00:00.

here's my spreadsheet for reference

答:
```<code>=ARRAYFORMULA(IFERROR(QUERY(
 {swgohEventsCal!$A$2:$A,swgohEventsCal!$B$2:$B+1,swgohEventsCal!$C$2:$D},
 "select Col1,Col2,Col3
  where Col1 contains 'TB'
    and Col3 >= date '"&TEXT(TODAY(), "yyyy-MM-dd")&"'
  order by Col2
  limit 4", 0), "Nothing Scheduled!"))
</code>```

Body:
I have a query in a spreadsheet:

=IFERROR(QUERY(swgohEventsCal!$A$2:$D,"SELECT A,B,C where A contains 'TB' and C >= date '"&TEXT(TODAY(),"yyyy-MM-dd")&"' order by B limit 4", 0),"Nothing Scheduled!")

Column B displays a date and time, but the time defaults to 12 AM.  What I would like to do is add 24 hours, or one day, to that time.

So when the result is 5/26/2019 0:00:00, I would like for it to display 5/27/2019 0:00:00.

here's my spreadsheet for reference


问:
How to obtain constant memory usage when migrating a Rails application from mongoid (MongoDB) to ActiveRecord (Postgres)?
I have recently started consulting and helping with the development of a Rails application that was using MongoDB (with Mongoid as its DB client) to store all its model instances.

This was fine while the application was in an early startup stage, but as the application got more and more clients and while starting to need more and more complicated queries to show proper statistics and other information in the interface, we decided that the only viable solution forward was to normalize the data, and move to a structured database instead.

So, we are now in the process of migrating both the tables and the data from MongoDB (with Mongoid as object-mapper) to Postgres (with ActiveRecord as object-mapper). Because we have to make sure that there is no improper non-normalized data in the Mongo database, we have to run these data migrations inside Rails-land, to make sure that validations, callbacks and sanity checks are being run.

All went 'fine' on development, but now we are running the migration on a staging server, with the real production database. It turns out that for some migrations, the memory usage of the server increases linearly with the number of model instances, causing the migration to be killed once we've filled 16 GB of RAM (and another 16GB of swap...).

Since we migrate the model instances one by one, we hope to be able to find a way to make sure that the memory usage can remain (near) constant.

The things that currently come to mind that might cause this are (a) ActiveRecord or Mongoid keeping references to object instances we have already imported, and (b) the migration is run in a single DB transaction, so Postgres is taking more and more memory until it is completed maybe?

So my question:

What is the probable cause of this linear memory usage?

How can we reduce it?

Are there ways to make Mongoid and/or ActiveRecord relinquish old references?

Should we attempt to call the Ruby GC manually?

Are there ways to split a data migration into multiple DB transactions, and would that help?

These data migrations have about the following format:

```<code>class MigrateSomeThing < ActiveRecord::Migration[5.2]
  def up
    Mongodb::ModelName.all.each do |old_thing| # Mongoid's #.all.each works with batches, see https://stackoverflow.com/questions/7041224/finding-mongodb-records-in-batches-using-mongoid-ruby-adapter
      create_thing(old_thing, Postgres::ModelName.new)
    end
    raise "Not all rows could be imported" if MongoDB::ModelName.count != Postgres::ModelName.count
  end

  def down
    Postgres::ModelName.delete_all
  end

  def create_thing(old_thing, new_thing)
    attrs = old_thing.attributes
    # ... maybe alter the attributes slightly to fit Postgres depending on the thing.
    new_thing.attributes = attrs
    new_thing.save!
  end

end
</code>```

答:
I suggest narrowing down the memory consumption to the reading or the writing side (or, put differently, Mongoid vs AR) by performing all of the reads but none of the model creation/writes and seeing if memory usage is still growing.

Mongoid performs finds in batches by default unlike AR where this has to be requested through find_in_batches.

Since ActiveRecord migrations are wrapped in transactions by default, and AR performs attribute value tracking to restore model instances' attributes to their previous values if transaction commit fails, it is likely that all of the AR models being created are remaining in memory and cannot be garbage collected until the migration finishes. Possible solutions to this are:

Disable implicit transaction for the migration in question (https://apidock.com/rails/ActiveRecord/Migration):

disable_ddl_transaction!

Create data via direct inserts, bypassing model instantiation entirely (this will also speed up the process). The most basic way is via SQL (Rails ActiveRecord: Getting the id of a raw insert), there are also libraries for this (Bulk Insert records into Active Record table).

Body:
I have recently started consulting and helping with the development of a Rails application that was using MongoDB (with Mongoid as its DB client) to store all its model instances.

This was fine while the application was in an early startup stage, but as the application got more and more clients and while starting to need more and more complicated queries to show proper statistics and other information in the interface, we decided that the only viable solution forward was to normalize the data, and move to a structured database instead.

So, we are now in the process of migrating both the tables and the data from MongoDB (with Mongoid as object-mapper) to Postgres (with ActiveRecord as object-mapper). Because we have to make sure that there is no improper non-normalized data in the Mongo database, we have to run these data migrations inside Rails-land, to make sure that validations, callbacks and sanity checks are being run.

All went 'fine' on development, but now we are running the migration on a staging server, with the real production database. It turns out that for some migrations, the memory usage of the server increases linearly with the number of model instances, causing the migration to be killed once we've filled 16 GB of RAM (and another 16GB of swap...).

Since we migrate the model instances one by one, we hope to be able to find a way to make sure that the memory usage can remain (near) constant.

The things that currently come to mind that might cause this are (a) ActiveRecord or Mongoid keeping references to object instances we have already imported, and (b) the migration is run in a single DB transaction, so Postgres is taking more and more memory until it is completed maybe?

So my question:

What is the probable cause of this linear memory usage?

How can we reduce it?

Are there ways to make Mongoid and/or ActiveRecord relinquish old references?

Should we attempt to call the Ruby GC manually?

Are there ways to split a data migration into multiple DB transactions, and would that help?

These data migrations have about the following format:

class MigrateSomeThing < ActiveRecord::Migration[5.2]
  def up
    Mongodb::ModelName.all.each do |old_thing| # Mongoid's #.all.each works with batches, see https://stackoverflow.com/questions/7041224/finding-mongodb-records-in-batches-using-mongoid-ruby-adapter
      create_thing(old_thing, Postgres::ModelName.new)
    end
    raise "Not all rows could be imported" if MongoDB::ModelName.count != Postgres::ModelName.count
  end

  def down
    Postgres::ModelName.delete_all
  end

  def create_thing(old_thing, new_thing)
    attrs = old_thing.attributes
    # ... maybe alter the attributes slightly to fit Postgres depending on the thing.
    new_thing.attributes = attrs
    new_thing.save!
  end

end


问:
How to tokenize on regex pattern and sort the resulting list?
I have a file that looks something like this:

```<code>select a,b,c FROM Xtable
select a,b,c FROM Vtable
select a,b,c FROM Atable
select a,b,c FROM Atable
select d,e,f FROM Atable
</code>```

I want to get a sortedMap:

```<code>{
"Atable":["select a,b,c FROM Atable", "select d,e,f FROM Atable"],
"Vtable":["select a,b,c FROM Vtable"],
"Xtable":["select a,b,c FROM Xtable"]
}
</code>```

The keys of sortedMap will be tableName and values being the textline in list.

I started off with this, but stuck in tokenizing the line for regex matching:

```<code>import re

f = open('mytext.txt', 'r')
x = f.readlines()
print x
f.close()
for i in x:
    p = re.search(".* FROM ", i)
 //now how to tokenize and get the value that follows FROM
</code>```

答:
We most likely might not want to do this task with regular expressions, yet if we do, we
can start with a simple expression, maybe similar to:

```<code>\"(.+?([a-z]+))\"
</code>```

We would replace it with "\2":["\1"],, then we would add a {}.

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"\"(.+?([a-z]+))\""

test_str = ("\"select a,b,c FROM Xtable\"\n"
    "\"select a,b,c FROM Vtable\"\n"
    "\"select a,b,c FROM Atable\"\n"
    "\"select a,b,c FROM Atable\"\n"
    "\"select d,e,f FROM Atable\"")

subst = "\"\\2\":[\"\\1\"],"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE | re.IGNORECASE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I have a file that looks something like this:

select a,b,c FROM Xtable
select a,b,c FROM Vtable
select a,b,c FROM Atable
select a,b,c FROM Atable
select d,e,f FROM Atable

I want to get a sortedMap:

{
"Atable":["select a,b,c FROM Atable", "select d,e,f FROM Atable"],
"Vtable":["select a,b,c FROM Vtable"],
"Xtable":["select a,b,c FROM Xtable"]
}

The keys of sortedMap will be tableName and values being the textline in list.

I started off with this, but stuck in tokenizing the line for regex matching:

import re

f = open('mytext.txt', 'r')
x = f.readlines()
print x
f.close()
for i in x:
    p = re.search(".* FROM ", i)
 //now how to tokenize and get the value that follows FROM

Body:
We most likely might not want to do this task with regular expressions, yet if we do, we
can start with a simple expression, maybe similar to:

\"(.+?([a-z]+))\"

We would replace it with "\2":["\1"],, then we would add a {}.

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"\"(.+?([a-z]+))\""

test_str = ("\"select a,b,c FROM Xtable\"\n"
    "\"select a,b,c FROM Vtable\"\n"
    "\"select a,b,c FROM Atable\"\n"
    "\"select a,b,c FROM Atable\"\n"
    "\"select d,e,f FROM Atable\"")

subst = "\"\\2\":[\"\\1\"],"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE | re.IGNORECASE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
How many trees were used in my caret "rf" model?
When not specifying the ntree count in a caret "rf" model, I am having a difficult time finding how many trees were used in the model.

Here is the code I am using to train my model:

```<code>fitControl <- trainControl(
    method = "cv",
    number = 3,
    savePredictions = "final",
    classProbs = T,
    summaryFunction = twoClassSummary,
    sampling = "down")

set.seed(3219)
  rf_model_down <- train(Class ~ .,
                         data = train_data,
                         method ='rf',
                         tuneLength = 2,
                         trControl = fitControl,
                         metric = "ROC")
</code>```

using the print(rf_model_down) function, I am able to see what the mtry was, but it doesn't tell us the ntree count used.

```<code>print(rf_model_down)

# Random Forest
#
# 10000 samples
#    94 predictor
#     2 classes: 'Fraud', 'notFraud'
#
# No pre-processing
# Resampling: Cross-Validated (3 fold)
# Summary of sample sizes: 6667, 6666, 6667
# Addtional sampling using down-sampling
#
# Resampling results across tuning parameters:
#
#   mtry  ROC        Sens       Spec
#    2    0.7401603  0.7691257  0.5717070
#   94    0.7449104  0.6814208  0.6641911
#
# ROC was used to select the optimal model using the largest value.
# The final value used for the model was mtry = 94.
</code>```

Thanks, in advance, for what is most likely an easy answer that I'm having a difficult time finding...

答:
Inspecting str(rf_model_down) shows that we can use

```<code>rf_model_down$finalModel$ntree
</code>```

Body:
When not specifying the ntree count in a caret "rf" model, I am having a difficult time finding how many trees were used in the model.

Here is the code I am using to train my model:

fitControl <- trainControl(
    method = "cv",
    number = 3,
    savePredictions = "final",
    classProbs = T,
    summaryFunction = twoClassSummary,
    sampling = "down")

set.seed(3219)
  rf_model_down <- train(Class ~ .,
                         data = train_data,
                         method ='rf',
                         tuneLength = 2,
                         trControl = fitControl,
                         metric = "ROC")

using the print(rf_model_down) function, I am able to see what the mtry was, but it doesn't tell us the ntree count used.

print(rf_model_down)

# Random Forest
#
# 10000 samples
#    94 predictor
#     2 classes: 'Fraud', 'notFraud'
#
# No pre-processing
# Resampling: Cross-Validated (3 fold)
# Summary of sample sizes: 6667, 6666, 6667
# Addtional sampling using down-sampling
#
# Resampling results across tuning parameters:
#
#   mtry  ROC        Sens       Spec
#    2    0.7401603  0.7691257  0.5717070
#   94    0.7449104  0.6814208  0.6641911
#
# ROC was used to select the optimal model using the largest value.
# The final value used for the model was mtry = 94.

Thanks, in advance, for what is most likely an easy answer that I'm having a difficult time finding...

Body:
Inspecting str(rf_model_down) shows that we can use

rf_model_down$finalModel$ntree


问:
UITableView not remembering selection when collapsing
I have a tableview with 3 collapsible sections. users can only select rows in section 3 and when they select it goes green. However, when this section is collapsed all the selections are forgotten and when I re-open the section, usually the first row is always green (though it shouldn't be). Sometimes, other sections end up being green too when they shouldn't - not sure what I've got wrong?</p>

```<code>// Number of table sections
func numberOfSections(in tableView: UITableView) -> Int {
    return 3
}

// Set the number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if (self.expandedSectionHeaderNumber == section) {

        // If markscheme, create the markscheme format
        if (section == 2)
        {
            return self.markschemeRows.count
        }
        else
        {
            let arrayOfItems = self.sectionItems[section] as! NSArray
            return arrayOfItems.count
        }

    } else {
        return 0;
    }
}

// Set titles for sections
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if (self.sectionNames.count != 0) {
        return self.sectionNames[section] as? String
    }
    return ""
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44.0;
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
    return 0;
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    //recast your view as a UITableViewHeaderFooterView
    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    header.contentView.backgroundColor = UIColor.darkGray
    header.textLabel?.textColor = UIColor.white

    if let viewWithTag = self.view.viewWithTag(kHeaderSectionTag + section) {
        viewWithTag.removeFromSuperview()
    }
    let headerFrame = self.view.frame.size
    let theImageView = UIImageView(frame: CGRect(x: headerFrame.width - 32, y: 13, width: 18, height: 18));
    theImageView.image = UIImage(named: "Chevron-Dn-Wht")
    theImageView.tag = kHeaderSectionTag + section
    header.addSubview(theImageView)

    // make headers touchable
    header.tag = section
    let headerTapGesture = UITapGestureRecognizer()
    headerTapGesture.addTarget(self, action: #selector(CaseViewController.sectionHeaderWasTouched(_:)))
    header.addGestureRecognizer(headerTapGesture)
}

// Load the table data
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
    let section = self.sectionItems[indexPath.section] as! NSArray

    cell.textLabel?.textColor = UIColor.black
    cell.selectionStyle = .none
    //cell.backgroundColor = .white

    // Get the data from different arrays depending on the section
    if indexPath.section == 2 {
        cell.textData?.text = markschemeRows[indexPath.row]

    } else {
        cell.textData?.text = section[indexPath.row] as! String

    }

    return cell
}

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {

    if indexPath.section == 0{

        if indexPath.row == 0{
            return nil
        }

    }
    else if indexPath.section == 1{

        if indexPath.row == 0{
            return nil
        }

    }
    return indexPath

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
    let cell = tableView.cellForRow(at: indexPath)

    cell?.backgroundColor = .green
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let cell = tableView.cellForRow(at: indexPath)

    if (cell?.backgroundColor == .green)
    {
        cell?.backgroundColor = .white
    }
}

// MARK: - Expand / Collapse Methods

@objc func sectionHeaderWasTouched(_ sender: UITapGestureRecognizer) {
    let headerView = sender.view as! UITableViewHeaderFooterView
    let section    = headerView.tag
    let eImageView = headerView.viewWithTag(kHeaderSectionTag + section) as? UIImageView

    if (self.expandedSectionHeaderNumber == -1) {
        self.expandedSectionHeaderNumber = section
        tableViewExpandSection(section, imageView: eImageView!)
    } else {
        if (self.expandedSectionHeaderNumber == section) {
            tableViewCollapeSection(section, imageView: eImageView!)
        } else {
            let cImageView = self.view.viewWithTag(kHeaderSectionTag + self.expandedSectionHeaderNumber) as? UIImageView
            tableViewCollapeSection(self.expandedSectionHeaderNumber, imageView: cImageView!)
            tableViewExpandSection(section, imageView: eImageView!)
        }
    }
}

func tableViewCollapeSection(_ section: Int, imageView: UIImageView) {
    let sectionData = self.sectionItems[section] as! NSArray

    self.expandedSectionHeaderNumber = -1;
    if (sectionData.count == 0) {
        return;
    } else {
        UIView.animate(withDuration: 0.4, animations: {
            imageView.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(Double.pi)) / 180.0)
        })
        var indexesPath = [IndexPath]()

        // If markscheme, different number needed
        if (section == 2)
        {
            for i in 0 ..< markschemeRows.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }
        else
        {
            for i in 0 ..< sectionData.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }

        self.tableView!.beginUpdates()
        self.tableView!.deleteRows(at: indexesPath, with: UITableView.RowAnimation.fade)
        self.tableView!.endUpdates()
    }
}

func tableViewExpandSection(_ section: Int, imageView: UIImageView) {
    let sectionData = self.sectionItems[section] as! NSArray

    if (sectionData.count == 0) {
        self.expandedSectionHeaderNumber = -1;
        return;
    } else {
        UIView.animate(withDuration: 0.4, animations: {
            imageView.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(Double.pi)) / 180.0)
        })
        var indexesPath = [IndexPath]()

        // If markscheme, create the markscheme format
        if (section == 2)
        {
            for i in 0 ..< markschemeRows.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }
        else
        {
            for i in 0 ..< sectionData.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }
        self.expandedSectionHeaderNumber = section
        self.tableView!.beginUpdates()
        self.tableView!.insertRows(at: indexesPath, with: UITableView.RowAnimation.fade)
        self.tableView!.endUpdates()
    }
}
</code>```

答:
The key thing to understand here is that the Cells are Reused when you say

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
</code>```

dequeueReusableCell basically reuses a previously loaded UITableViewCell and in your case you changed the background color of the cell to green

To get a better understanding of the concept consider reading some articles like this one on Reusing Cells

Changes in Code

What you should do considering the above in mind

```<code>var backgroundColors = [UIColor](repeating: UIColor.white, count: 10)
</code>```

you have to save the state of the colors in a model (ideally you should make a custom struct)

now in cellForRowAt add this

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
    .
    .
    cell.backgroundColor = backgroundColors[indexPath.row]

    // **EDIT**
    let cellShouldBeSelected = backgroundColors[indexPath.row] == .green

    if cellShouldBeSelected {
         tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }
    .
    .
    return cell
}

</code>```

And your didSelectRowAt and didDeselectRowAt should update the model

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.backgroundColors[indexPath.row] = .green

    tableView.reloadRows(at: [indexPath], with: .none)
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    if (self.backgroundColors[indexPath.row] == .green) {
        self.backgroundColors[indexPath.row] = .white
        tableView.reloadRows(at: [indexPath], with: .none)
    }
}
</code>```

On second thought

Solution 2 (Recommended)

From you comments, i see you only need one selected cell at one time, assuming that keeping an array of backgroundColors is just a bad idea.

declare a int for the selected index

```<code>// -1 representing nothing is selected in the beginning
var selectedRow = -1
</code>```

now your cellForRowAt will look like

```<code> let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell

    .
    .
    if indexPath.section == 2, indexPath.row == self.selectedRow  {
       cell.backgroundColor = .green
    } else {
       cell.backgroundColor = .white
    }
    .
    .

    return cell
}
</code>```

And your didSelectRowAt

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     if indexPath.section == 2 {
        self.selectedRow = indexPath.row

        tableView.reloadSections([2], with: .automatic)
     }
}
</code>```

And now you can remove didDeselectRowAt completely

Body:
I have a tableview with 3 collapsible sections. users can only select rows in section 3 and when they select it goes green. However, when this section is collapsed all the selections are forgotten and when I re-open the section, usually the first row is always green (though it shouldn't be). Sometimes, other sections end up being green too when they shouldn't - not sure what I've got wrong?

// Number of table sections
func numberOfSections(in tableView: UITableView) -> Int {
    return 3
}

// Set the number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if (self.expandedSectionHeaderNumber == section) {

        // If markscheme, create the markscheme format
        if (section == 2)
        {
            return self.markschemeRows.count
        }
        else
        {
            let arrayOfItems = self.sectionItems[section] as! NSArray
            return arrayOfItems.count
        }

    } else {
        return 0;
    }
}

// Set titles for sections
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if (self.sectionNames.count != 0) {
        return self.sectionNames[section] as? String
    }
    return ""
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44.0;
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
    return 0;
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    //recast your view as a UITableViewHeaderFooterView
    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    header.contentView.backgroundColor = UIColor.darkGray
    header.textLabel?.textColor = UIColor.white

    if let viewWithTag = self.view.viewWithTag(kHeaderSectionTag + section) {
        viewWithTag.removeFromSuperview()
    }
    let headerFrame = self.view.frame.size
    let theImageView = UIImageView(frame: CGRect(x: headerFrame.width - 32, y: 13, width: 18, height: 18));
    theImageView.image = UIImage(named: "Chevron-Dn-Wht")
    theImageView.tag = kHeaderSectionTag + section
    header.addSubview(theImageView)

    // make headers touchable
    header.tag = section
    let headerTapGesture = UITapGestureRecognizer()
    headerTapGesture.addTarget(self, action: #selector(CaseViewController.sectionHeaderWasTouched(_:)))
    header.addGestureRecognizer(headerTapGesture)
}

// Load the table data
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
    let section = self.sectionItems[indexPath.section] as! NSArray

    cell.textLabel?.textColor = UIColor.black
    cell.selectionStyle = .none
    //cell.backgroundColor = .white

    // Get the data from different arrays depending on the section
    if indexPath.section == 2 {
        cell.textData?.text = markschemeRows[indexPath.row]

    } else {
        cell.textData?.text = section[indexPath.row] as! String

    }

    return cell
}

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {

    if indexPath.section == 0{

        if indexPath.row == 0{
            return nil
        }

    }
    else if indexPath.section == 1{

        if indexPath.row == 0{
            return nil
        }

    }
    return indexPath

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
    let cell = tableView.cellForRow(at: indexPath)

    cell?.backgroundColor = .green
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let cell = tableView.cellForRow(at: indexPath)

    if (cell?.backgroundColor == .green)
    {
        cell?.backgroundColor = .white
    }
}

// MARK: - Expand / Collapse Methods

@objc func sectionHeaderWasTouched(_ sender: UITapGestureRecognizer) {
    let headerView = sender.view as! UITableViewHeaderFooterView
    let section    = headerView.tag
    let eImageView = headerView.viewWithTag(kHeaderSectionTag + section) as? UIImageView

    if (self.expandedSectionHeaderNumber == -1) {
        self.expandedSectionHeaderNumber = section
        tableViewExpandSection(section, imageView: eImageView!)
    } else {
        if (self.expandedSectionHeaderNumber == section) {
            tableViewCollapeSection(section, imageView: eImageView!)
        } else {
            let cImageView = self.view.viewWithTag(kHeaderSectionTag + self.expandedSectionHeaderNumber) as? UIImageView
            tableViewCollapeSection(self.expandedSectionHeaderNumber, imageView: cImageView!)
            tableViewExpandSection(section, imageView: eImageView!)
        }
    }
}

func tableViewCollapeSection(_ section: Int, imageView: UIImageView) {
    let sectionData = self.sectionItems[section] as! NSArray

    self.expandedSectionHeaderNumber = -1;
    if (sectionData.count == 0) {
        return;
    } else {
        UIView.animate(withDuration: 0.4, animations: {
            imageView.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(Double.pi)) / 180.0)
        })
        var indexesPath = [IndexPath]()

        // If markscheme, different number needed
        if (section == 2)
        {
            for i in 0 ..< markschemeRows.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }
        else
        {
            for i in 0 ..< sectionData.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }

        self.tableView!.beginUpdates()
        self.tableView!.deleteRows(at: indexesPath, with: UITableView.RowAnimation.fade)
        self.tableView!.endUpdates()
    }
}

func tableViewExpandSection(_ section: Int, imageView: UIImageView) {
    let sectionData = self.sectionItems[section] as! NSArray

    if (sectionData.count == 0) {
        self.expandedSectionHeaderNumber = -1;
        return;
    } else {
        UIView.animate(withDuration: 0.4, animations: {
            imageView.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(Double.pi)) / 180.0)
        })
        var indexesPath = [IndexPath]()

        // If markscheme, create the markscheme format
        if (section == 2)
        {
            for i in 0 ..< markschemeRows.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }
        else
        {
            for i in 0 ..< sectionData.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }
        self.expandedSectionHeaderNumber = section
        self.tableView!.beginUpdates()
        self.tableView!.insertRows(at: indexesPath, with: UITableView.RowAnimation.fade)
        self.tableView!.endUpdates()
    }
}

Body:
The key thing to understand here is that the Cells are Reused when you say

let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell

dequeueReusableCell basically reuses a previously loaded UITableViewCell and in your case you changed the background color of the cell to green

To get a better understanding of the concept consider reading some articles like this one on Reusing Cells

Changes in Code

What you should do considering the above in mind

var backgroundColors = [UIColor](repeating: UIColor.white, count: 10)

you have to save the state of the colors in a model (ideally you should make a custom struct)

now in cellForRowAt add this

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
    .
    .
    cell.backgroundColor = backgroundColors[indexPath.row]

    // **EDIT**
    let cellShouldBeSelected = backgroundColors[indexPath.row] == .green

    if cellShouldBeSelected {
         tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }
    .
    .
    return cell
}

And your didSelectRowAt and didDeselectRowAt should update the model

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.backgroundColors[indexPath.row] = .green

    tableView.reloadRows(at: [indexPath], with: .none)
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    if (self.backgroundColors[indexPath.row] == .green) {
        self.backgroundColors[indexPath.row] = .white
        tableView.reloadRows(at: [indexPath], with: .none)
    }
}

On second thought

Solution 2 (Recommended)

From you comments, i see you only need one selected cell at one time, assuming that keeping an array of backgroundColors is just a bad idea.

declare a int for the selected index

// -1 representing nothing is selected in the beginning
var selectedRow = -1

now your cellForRowAt will look like

 let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell

    .
    .
    if indexPath.section == 2, indexPath.row == self.selectedRow  {
       cell.backgroundColor = .green
    } else {
       cell.backgroundColor = .white
    }
    .
    .

    return cell
}

And your didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     if indexPath.section == 2 {
        self.selectedRow = indexPath.row

        tableView.reloadSections([2], with: .automatic)
     }
}

And now you can remove didDeselectRowAt completely


问:
How to train my model to draw bounding box around text present in image?
I am trying to draw bounding_box around the image. I have a different model to predict the class of text detected. Everywhere yolo implementation is based on bounding box+ class prediction. So the loss function they have defined is a loss for class prediction, confidence, and the probability of given class. I just want my loss function to be defined only in terms of the bounding box. Please suggest me how to do it, or suggest me some articles to read.</p>

答:
So the loss function they have defined is a loss for class prediction,
  confidence, and the probability of given class.

Actually the loss function of YOLO consists of

the classification loss

the localization loss (errors between the predicted boundary box and the ground truth)

the confidence loss (the objectness of the box).

https://medium.com/@jonathan_hui/real-time-object-detection-with-yolo-yolov2-28b1b93e2088

If you are looking for accuracy only for bounding box, then what you want is called mAP (mean Average Precision). To be able to understand how mAP is calculated will take some time for newcomer in object detection, so I will just put some good link for later study https://medium.com/@jonathan_hui/map-mean-average-precision-for-object-detection-45c121a31173.

If you want to visualize the mAP for your YOLO model during training, you can use this popular github repository created by AlexeyAB https://github.com/AlexeyAB/darknet.

For example you can train your model by inputting -map flag like this :

```<code>./darknet detector train data/obj.data yolo-obj.cfg darknet53.conv.74 -map
</code>```

The chart below will be generated and the red line indicates the mAP and the blue line indicates the average loss of your trained model.

Finally after training, you can check which weights is the best for you (checking the mAP value)

```<code>./darknet detector map data/obj.data yolo-obj.cfg backup\yolo-obj_7000.weights
</code>```

The author of this repo writes everything on his github repo so please take a time to read all the steps that you need.

Additional Information

I also do the same thing as you do for my current project. I use YOLO only to detect object and draw bounding box. But for the classification I use another CNN model.

Body:
So the loss function they have defined is a loss for class prediction,
  confidence, and the probability of given class.

Actually the loss function of YOLO consists of

the classification loss

the localization loss (errors between the predicted boundary box and the ground truth)

the confidence loss (the objectness of the box).

https://medium.com/@jonathan_hui/real-time-object-detection-with-yolo-yolov2-28b1b93e2088

If you are looking for accuracy only for bounding box, then what you want is called mAP (mean Average Precision). To be able to understand how mAP is calculated will take some time for newcomer in object detection, so I will just put some good link for later study https://medium.com/@jonathan_hui/map-mean-average-precision-for-object-detection-45c121a31173.

If you want to visualize the mAP for your YOLO model during training, you can use this popular github repository created by AlexeyAB https://github.com/AlexeyAB/darknet.

For example you can train your model by inputting -map flag like this :

./darknet detector train data/obj.data yolo-obj.cfg darknet53.conv.74 -map

The chart below will be generated and the red line indicates the mAP and the blue line indicates the average loss of your trained model.

Finally after training, you can check which weights is the best for you (checking the mAP value)

./darknet detector map data/obj.data yolo-obj.cfg backup\yolo-obj_7000.weights

The author of this repo writes everything on his github repo so please take a time to read all the steps that you need.

Additional Information

I also do the same thing as you do for my current project. I use YOLO only to detect object and draw bounding box. But for the classification I use another CNN model.


问:
Responsive INLINE SVG - content of svg must fill parent width
GOAL:

I am trying to get an INLINE SVG element to fill the full available width of the parent element. I can achieve the same effect easily using an img and object tag to reference the svg file, but I want to use inline svg because I am animating the svg inner elements with javascript.

PROBLEM:

I can achieve this in Firefox and with some tweaks also in Chrome, but safari and IE9 & IE10 won't play ball.

The inner content of svg doesn't always fill the svg element in all screen widths

webkit adds a mysterious padding/height (in this example the padding is within svg element) The height of SVG element should be auto and wrap the inner svg content.

MAIN QUESTION:

Is there a cross browser solution for responsive INLINE SVG: View the example in IE9 & 10 and -webkit-Safari and notice the unrequired extra height within SVG element (cyan color).

http://jsfiddle.net/David_Knowles/9tUAd/

```<code><div class="block">stuff</div>
<div class="wrap">
    <svg version="1.1" baseProfile="basic" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 550 350" xml:space="preserve" preserveAspectRatio="xMinYMin meet">

        <rect x="0" y="0" width="550" height="350"/>
        <polyline points="0,0 0,350 550,350"/>
        <text x="0" y="50%" fill="#ffffff" stroke="none" width="100%">The text</text>
    </svg>
</div>
<div class="block">stuff</div>
</code>```

答:
After much fiddling, the modern browser and IE11 compatible solution I used has two parts:

Specify both viewBox and preserveAspectRatio="xMinYMin meet" in the svg root tag.

Use css media queries to give your svg element a height in vw units for each layout.

good luck!

Body:
GOAL:

I am trying to get an INLINE SVG element to fill the full available width of the parent element. I can achieve the same effect easily using an img and object tag to reference the svg file, but I want to use inline svg because I am animating the svg inner elements with javascript.

PROBLEM:

I can achieve this in Firefox and with some tweaks also in Chrome, but safari and IE9 & IE10 won't play ball.

The inner content of svg doesn't always fill the svg element in all screen widths

webkit adds a mysterious padding/height (in this example the padding is within svg element) The height of SVG element should be auto and wrap the inner svg content.

MAIN QUESTION:

Is there a cross browser solution for responsive INLINE SVG: View the example in IE9 & 10 and -webkit-Safari and notice the unrequired extra height within SVG element (cyan color).

http://jsfiddle.net/David_Knowles/9tUAd/

stuff

    <svg version="1.1" baseProfile="basic" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 550 350" xml:space="preserve" preserveAspectRatio="xMinYMin meet">

        <rect x="0" y="0" width="550" height="350"/>
        <polyline points="0,0 0,350 550,350"/>
        <text x="0" y="50%" fill="#ffffff" stroke="none" width="100%">The text</text>
    </svg>

stuff


问:
How do you center content in a flexbox
I have images and text, and they are currently are located on the left side of the flexbox.

The issue I'm having is that anything above 1000px in browser size leaves a big open space on the right side. So what I want to do is if the browser width is 1000px or larger center the content so I can get rid of the white space.

I'm having trouble centering these items in my media break. I need help centering for these conditions.

section {
    display: flex;
    flex-flow: wrap;
    align-items: flex-start;

    width: 80%;
    margin: 1em auto;

    border: solid .125em #00aaff;
    background-color: white;
    opacity: 0.9;
}

section > figure {
    flex: 1 1 25%;
    text-align: center;
    align-self: center;
    padding: 1em 0em;

}

section > article {
    flex: 1 1 75%;
    align-self: center;
    line-height: 1.6;
    padding: 1em 0em;
}

figure img {
    width: 75%;
}

@media screen and (min-width:1000px) {
     /*Center the content in the middle of the flexbox*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
        <figure id="image1">
            <img src="images/512x512.png" alt="Dynamo">
        </figure>

        <article>
                <p>Houston Dynamo</p>
                <p>Sport Science/Sport Performance Intern</p>
                <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
        </article>

        <figure>
            <img src="images/UW-Logo.png" alt="Wisconsion">
        </figure>

         <article>
                <p>University of Madison Wisconsin-Madison</p>
                <p>Strength and Conditioning Coach, Graduate Assistant</p>
                <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
        </article></code>```

答:
Wouldn't you just continue with flexbox and use justify-content:center;?

section {
  display: flex;
  flex-direction: row;
  width: 100%;
  border: solid .125em #00aaff;
}

@media screen and (min-width: 1000px) {
  section {
    justify-content:center;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <figure id="image1">
    <img src="//placehold.it/100x100" alt="Dynamo">
  </figure>

  <article>
    <p>Houston Dynamo</p>
    <p>Sport Science/Sport Performance Intern</p>
    <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
  </article>

</section>
<section>
  <figure>
    <img src="//placehold.it/100x100" alt="Wisconsion">
  </figure>

  <article>
    <p>University of Madison Wisconsin-Madison</p>
    <p>Strength and Conditioning Coach, Graduate Assistant</p>
    <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
  </article>
</section></code>```

Title: How do you center content in a flexbox

Body:
I have images and text, and they are currently are located on the left side of the flexbox.

The issue I'm having is that anything above 1000px in browser size leaves a big open space on the right side. So what I want to do is if the browser width is 1000px or larger center the content so I can get rid of the white space.

I'm having trouble centering these items in my media break. I need help centering for these conditions.

section {
    display: flex;
    flex-flow: wrap;
    align-items: flex-start;

    width: 80%;
    margin: 1em auto;

    border: solid .125em #00aaff;
    background-color: white;
    opacity: 0.9;
}

section > figure {
    flex: 1 1 25%;
    text-align: center;
    align-self: center;
    padding: 1em 0em;

}

section > article {
    flex: 1 1 75%;
    align-self: center;
    line-height: 1.6;
    padding: 1em 0em;
}

figure img {
    width: 75%;
}

@media screen and (min-width:1000px) {
     /*Center the content in the middle of the flexbox*/
}

Houston Dynamo

Sport Science/Sport Performance Intern

<time datetime="2018-01-01"></time>January 2019 - Present

University of Madison Wisconsin-Madison

Strength and Conditioning Coach, Graduate Assistant

<time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time>

Body:
Wouldn't you just continue with flexbox and use justify-content:center;?

section {
  display: flex;
  flex-direction: row;
  width: 100%;
  border: solid .125em #00aaff;
}

@media screen and (min-width: 1000px) {
  section {
    justify-content:center;
  }
}

<section>
  <figure id="image1">
    <img src="//placehold.it/100x100" alt="Dynamo">
  </figure>

  <article>
    <p>Houston Dynamo</p>
    <p>Sport Science/Sport Performance Intern</p>
    <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
  </article>

</section>
<section>
  <figure>
    <img src="//placehold.it/100x100" alt="Wisconsion">
  </figure>

  <article>
    <p>University of Madison Wisconsin-Madison</p>
    <p>Strength and Conditioning Coach, Graduate Assistant</p>
    <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
  </article>
</section>


问:
How to create QR not using zxing in android?
I need to create a QR Code following configuration below:

```<code> - Model 2
 - Version 10
 - Size 57 x 57
 - Level H (30%)
 - Max 174 alphanumeric characters or 119 binary
 - Modules size 0.03 inch
</code>```

Actually, I'm using zxing to create the QR but I can't figure out how to set these 3 configurations

```<code>- Model 2
- Max 174 alphanumeric characters or 119 binary
- Modules size 0.03 inch
</code>```

And this the code I'm using (Kotlin)

```<code>
        imgQrCode.run{setImageBitmap(BarcodeEncoder().createBitmap(
             MultiFormatWriter().encode(content,
                                        BarcodeFormat.QR_CODE,
                                        57, 57,
                                        mapOf<EncodeHintType, Any>(
                                           Pair(EncodeHintType.QR_VERSION, 10),
                                           Pair(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H)

    ))))}

</code>```

Any idea how can I set those configurations with zxing or is there any alternative option to archive all the factors above?

答:
Model 2

ZXing appears to be supporting Model 2 QR Code as the code:
https://github.com/zxing/zxing/blob/master/core/src/main/java/com/google/zxing/qrcode/encoder/Encoder.java#L280

seems to handle versions 1 through 40. Model 1 only goes up to version 14.

Max 174 alphanumeric characters or 119 binary

Count? Or use the rough metric from QR Code Storage section which lists 5.5 bits for Alphanumeric and 8 bits for binary. Do realize that changing error correction will change the number of bits/modules used in the image.

Modules size 0.03 inch

This is a display density question, calculate via Getting the screen density programmatically in android?.

Body:
I need to create a QR Code following configuration below:

 - Model 2
 - Version 10
 - Size 57 x 57
 - Level H (30%)
 - Max 174 alphanumeric characters or 119 binary
 - Modules size 0.03 inch

Actually, I'm using zxing to create the QR but I can't figure out how to set these 3 configurations

- Model 2
- Max 174 alphanumeric characters or 119 binary
- Modules size 0.03 inch

And this the code I'm using (Kotlin)

        imgQrCode.run{setImageBitmap(BarcodeEncoder().createBitmap(
             MultiFormatWriter().encode(content,
                                        BarcodeFormat.QR_CODE,
                                        57, 57,
                                        mapOf<EncodeHintType, Any>(
                                           Pair(EncodeHintType.QR_VERSION, 10),
                                           Pair(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H)

    ))))}

Any idea how can I set those configurations with zxing or is there any alternative option to archive all the factors above?


问:
How to make a perfect circle
I don't know what other technique i can use to make a perfect circle. The problem tells me that the circle must have 200px of diameter on CSS. Yet, someone made it differently using other variables. I want to do it the right way but don't know how.

I'd created a div which specifies the image to have 200px but still it didn't work

```<code><img class="rounded" src="https://assets.breatheco.de/apis/img/funny/einstein.png" />
</code>```

答:
Use border-radius to achieve the circle.
Read more about border radius

.circle {
width: 200px;
height: 200px;
background: #d8d8d8;
border-radius: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle"></div></code>```

Title: How to make a perfect circle

Body:
Use border-radius to achieve the circle.
Read more about border radius

.circle {
width: 200px;
height: 200px;
background: #d8d8d8;
border-radius: 100%;
}

<div class="circle"></div>


问:
A simple merkle-tree implementation in java
I am attempting to write a very simple merkle-tree implementation in Java.

I am using the values of the txids in block 170 on the bitcoin blockchain for reference, so I can see what the correct result should be.

The txids corresponding with that block are as follows:

```<code>b1fea52486ce0c62bb442b530a3f0132b826c74e473d1f2c220bfa78111c5082
</code>```

```<code>f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16
</code>```

It is my understanding that bitcoin's merkle-tree implementation works the following way:

split the transactions in the block up into pairs

byte-swap the txids

concatenate the txids

double hash the concatenated pairs

With a caveat being:

```<code>If there's no additional pairs of txids, concatenate the result of the first pair after double hashing with itself and repeat
</code>```

My code is within a switch statement which looks like this:

```<code>case "test merkle root": {
    // txid A
    String A = "b1fea52486ce0c62bb442b530a3f0132b826c74e473d1f2c220bfa78111c5082";

    // txid A byte-swapped
    String A_little = MainChain.swapEndianness(A);

    // txid B
    String B = "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16";

    // txid B byte-swapped
    String B_little = MainChain.swapEndianness(B);

    // txid A + B concatenated
    String AB_little = A_little + B_little;

    // double hash of byte-swapped concatenated A+B
    String ABdoubleHash =  SHA256.generateSHA256Hash(SHA256.generateSHA256Hash(AB_little));

    // double hash concatenated with itself
    String ABAB_little = ABdoubleHash + ABdoubleHash;

    // double hash of self-concatenated double-hashed txid
    String merkleRootLittleEndian = SHA256.generateSHA256Hash(SHA256.generateSHA256Hash(ABAB_little));

    // print result byte-swapped back to big-endian
    System.out.println("Merkle root: " + MainChain.swapEndianness(merkleRootLittleEndian));
}
</code>```

The swapEndianness method I wrote is not a true 'byte level' swap, and instead just changes the order of the String, it looks like this:

```<code>public static String swapEndianness(String hash) {
        char[] hashAsCharArray = hash.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = hash.length() - 1; i > 0; i-=2) {
            sb.append(hashAsCharArray[i - 1]);
            sb.append(hashAsCharArray[i]);
        }
        return sb.toString();
    }
</code>```

The expected result for the merkle root of these two txid's is:

```<code>7dac2c5666815c17a3b36427de37bb9d2e2c5ccec3f8633eb91a4205cb4c10ff
</code>```

However, the result I end up with is:

```<code>3b40cab1157838cc41b08e27641f65d245957ab07b3504d94bc2d355abaed06c
</code>```

Am I not getting the result I am expecting because I am cheating when I do the byte-swap, because I am missing a step, or because I have an error in my code (or some combination of these)? Any help would be appreciated!

答:
You're not understanding what a byte[] is in Java. The strings in your example are "hex" representations of a byte[]. See How do I initialize a byte array in Java?

```<code>public class MerkleTree {
    static MessageDigest digest;
    public static void main(String[] args) throws NoSuchAlgorithmException {
        digest = MessageDigest.getInstance("SHA-256");
        new MerkleTree().run();
    }
    private void run() {
        // txid A
        byte[] A = hexStringToByteArray("b1fea52486ce0c62bb442b530a3f0132b826c74e473d1f2c220bfa78111c5082");
        System.out.println(Arrays.toString(A));
        // txid A byte-swapped
        byte[] A_little = swapEndianness(A);
        System.out.println(Arrays.toString(A_little));

        // txid B
        byte[] B = hexStringToByteArray("f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16");
        System.out.println(Arrays.toString(B));

        // txid B byte-swapped
        byte[] B_little = swapEndianness(B);
        System.out.println(Arrays.toString(B_little));

        // txid A + B concatenated
        byte[] AB_little = Arrays.copyOf(A_little, A_little.length + B_little.length);
        System.arraycopy(B_little, 0, AB_little, A_little.length, B_little.length);
        System.out.println(Arrays.toString(AB_little));

        // double hash of byte-swapped concatenated A+B
        byte[] ABdoubleHash = SHA256(SHA256(AB_little));
        System.out.println(Arrays.toString(ABdoubleHash));

        // print result byte-swapped back to big-endian
        byte[] result = swapEndianness(ABdoubleHash);
        System.out.println(Arrays.toString(result));
        System.out.println(getHex(result));
    }
    byte[] swapEndianness(byte[] hash) {
        byte[] result = new byte[hash.length];
        for (int i = 0; i < hash.length; i++) {
            result[i] = hash[hash.length-i-1];
        }
        return result;
    }
    byte[] SHA256(byte[] obytes) {
        return digest.digest(obytes);
    }
    byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
    private static final String    HEXES    = "0123456789abcdef";
    String getHex(byte[] raw) {
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }
}
</code>```

Finally, refer to Java code To convert byte to Hexadecimal

EDIT: This would be a little better on the resources since you often want to do this sort of thing a lot.

```<code>    // txid A byte-swapped
    byte[] A = swapEndianness(
            hexStringToByteArray("b1fea52486ce0c62bb442b530a3f0132b826c74e473d1f2c220bfa78111c5082")
        );
    // txid B byte-swapped
    byte[] B = swapEndianness(
            hexStringToByteArray("f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16")
        );
    // txid A + B concatenated
    byte[] AB = Arrays.copyOf(A, A.length + B.length);
    System.arraycopy(B, 0, AB, A.length, B.length);

    // print result byte-swapped back to big-endian
    String result = getHex(swapEndianness(SHA256(SHA256(AB))));
    System.out.println(result);
    }
    byte[] swapEndianness(byte[] hash) {
        for (int i = 0; i < hash.length/2; i++) {
            byte t = hash[hash.length-i-1];
            hash[hash.length-i-1] = hash[i];
            hash[i] = t;
        }
        return hash;
    }
</code>```

Body:
I am attempting to write a very simple merkle-tree implementation in Java.

I am using the values of the txids in block 170 on the bitcoin blockchain for reference, so I can see what the correct result should be.

The txids corresponding with that block are as follows:

b1fea52486ce0c62bb442b530a3f0132b826c74e473d1f2c220bfa78111c5082

f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16

It is my understanding that bitcoin's merkle-tree implementation works the following way:

split the transactions in the block up into pairs

byte-swap the txids

concatenate the txids

double hash the concatenated pairs

With a caveat being:

If there's no additional pairs of txids, concatenate the result of the first pair after double hashing with itself and repeat

My code is within a switch statement which looks like this:

case "test merkle root": {
    // txid A
    String A = "b1fea52486ce0c62bb442b530a3f0132b826c74e473d1f2c220bfa78111c5082";

    // txid A byte-swapped
    String A_little = MainChain.swapEndianness(A);

    // txid B
    String B = "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16";

    // txid B byte-swapped
    String B_little = MainChain.swapEndianness(B);

    // txid A + B concatenated
    String AB_little = A_little + B_little;

    // double hash of byte-swapped concatenated A+B
    String ABdoubleHash =  SHA256.generateSHA256Hash(SHA256.generateSHA256Hash(AB_little));

    // double hash concatenated with itself
    String ABAB_little = ABdoubleHash + ABdoubleHash;

    // double hash of self-concatenated double-hashed txid
    String merkleRootLittleEndian = SHA256.generateSHA256Hash(SHA256.generateSHA256Hash(ABAB_little));

    // print result byte-swapped back to big-endian
    System.out.println("Merkle root: " + MainChain.swapEndianness(merkleRootLittleEndian));
}

The swapEndianness method I wrote is not a true 'byte level' swap, and instead just changes the order of the String, it looks like this:

public static String swapEndianness(String hash) {
        char[] hashAsCharArray = hash.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = hash.length() - 1; i > 0; i-=2) {
            sb.append(hashAsCharArray[i - 1]);
            sb.append(hashAsCharArray[i]);
        }
        return sb.toString();
    }

The expected result for the merkle root of these two txid's is:

7dac2c5666815c17a3b36427de37bb9d2e2c5ccec3f8633eb91a4205cb4c10ff

However, the result I end up with is:

3b40cab1157838cc41b08e27641f65d245957ab07b3504d94bc2d355abaed06c

Am I not getting the result I am expecting because I am cheating when I do the byte-swap, because I am missing a step, or because I have an error in my code (or some combination of these)? Any help would be appreciated!

Body:
You're not understanding what a byte[] is in Java. The strings in your example are "hex" representations of a byte[]. See How do I initialize a byte array in Java?

public class MerkleTree {
    static MessageDigest digest;
    public static void main(String[] args) throws NoSuchAlgorithmException {
        digest = MessageDigest.getInstance("SHA-256");
        new MerkleTree().run();
    }
    private void run() {
        // txid A
        byte[] A = hexStringToByteArray("b1fea52486ce0c62bb442b530a3f0132b826c74e473d1f2c220bfa78111c5082");
        System.out.println(Arrays.toString(A));
        // txid A byte-swapped
        byte[] A_little = swapEndianness(A);
        System.out.println(Arrays.toString(A_little));

        // txid B
        byte[] B = hexStringToByteArray("f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16");
        System.out.println(Arrays.toString(B));

        // txid B byte-swapped
        byte[] B_little = swapEndianness(B);
        System.out.println(Arrays.toString(B_little));

        // txid A + B concatenated
        byte[] AB_little = Arrays.copyOf(A_little, A_little.length + B_little.length);
        System.arraycopy(B_little, 0, AB_little, A_little.length, B_little.length);
        System.out.println(Arrays.toString(AB_little));

        // double hash of byte-swapped concatenated A+B
        byte[] ABdoubleHash = SHA256(SHA256(AB_little));
        System.out.println(Arrays.toString(ABdoubleHash));

        // print result byte-swapped back to big-endian
        byte[] result = swapEndianness(ABdoubleHash);
        System.out.println(Arrays.toString(result));
        System.out.println(getHex(result));
    }
    byte[] swapEndianness(byte[] hash) {
        byte[] result = new byte[hash.length];
        for (int i = 0; i < hash.length; i++) {
            result[i] = hash[hash.length-i-1];
        }
        return result;
    }
    byte[] SHA256(byte[] obytes) {
        return digest.digest(obytes);
    }
    byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
    private static final String    HEXES    = "0123456789abcdef";
    String getHex(byte[] raw) {
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }
}

Finally, refer to Java code To convert byte to Hexadecimal

EDIT: This would be a little better on the resources since you often want to do this sort of thing a lot.

    // txid A byte-swapped
    byte[] A = swapEndianness(
            hexStringToByteArray("b1fea52486ce0c62bb442b530a3f0132b826c74e473d1f2c220bfa78111c5082")
        );
    // txid B byte-swapped
    byte[] B = swapEndianness(
            hexStringToByteArray("f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16")
        );
    // txid A + B concatenated
    byte[] AB = Arrays.copyOf(A, A.length + B.length);
    System.arraycopy(B, 0, AB, A.length, B.length);

    // print result byte-swapped back to big-endian
    String result = getHex(swapEndianness(SHA256(SHA256(AB))));
    System.out.println(result);
    }
    byte[] swapEndianness(byte[] hash) {
        for (int i = 0; i < hash.length/2; i++) {
            byte t = hash[hash.length-i-1];
            hash[hash.length-i-1] = hash[i];
            hash[i] = t;
        }
        return hash;
    }


问:
How to make table view animations smooth when resizing a cell
I have a UITable view with custom cells. Some cells have a button to expand/collapse. Sometimes the cell being resized appears to jump in the UI.

I'm using Autolayout and dynamic height calculation via heightForRowAtIndexPath:. I have looked through several tutorials, including this one on self-sizing table view cells, which I'm using to investigate the issue.

To reproduce the issue, scroll midway through the table and expand several cells. Tap on a cell that's partially showing. The cell will appear to jump instead of staying in place.

Example:

Video 1

The problem is more obvious when I comment out the line that scrolls to the top of the cell after selecting a cell.

Video 2

I tried @DonMag's suggestion. With small cells, the problem does not occur. When I increased cell heights to take up >60% of the screen height, the jump animation occurred (video).

I changed

Question Label.top = topMargin + 8

to

Question Label.top = topMargin + 800

When I dive into the code, the problem seems to occur when calling

```<code>[tableView beginUpdates];
[tableView endUpdates];
</code>```

But this snippet is necessary for the table view to recalculate cell heights.

I want the cell to stay in-place while resizing, without the jumping animation.

答:
After further investigation, the issue is caused when the table has cells with varying heights (e.g. 100 vs 800). I can't use the same estimated height for every cell, or else the content appears to jump when expanding/collapsing cells.

The solution has 2 parts, both of which are needed.

Using Real Cell Sizes

In heightForRowAtIndexPath:, each row uses a precise calculation instead of an estimate.

Multiple Reuse Pools

I assigned a unique ID to every type of cell. Each type of cell has similar heights. For example, type A has height=120, type B has height=400.

Then I registered a different "pool" of cells for each type. Even though CustomCell is the the same class for different cell types, each cell type has different constraints and sizes. This allows a cell with the correct estimated size to be dequeued from the reuse pool.

```<code>tableView.rowHeight = UITableViewAutomaticDimension;
[tableView registerClass:[CustomCell class] forCellReuseIdentifier:typeA];
[tableView registerClass:[CustomCell class] forCellReuseIdentifier:typeB];
...
NSString *cellID = // Could be typeA, typeB, etc.
cell = [tableView dequeueReusableCellWithIdentifier:cellID];
</code>```

Body:
I have a UITable view with custom cells. Some cells have a button to expand/collapse. Sometimes the cell being resized appears to jump in the UI.

I'm using Autolayout and dynamic height calculation via heightForRowAtIndexPath:. I have looked through several tutorials, including this one on self-sizing table view cells, which I'm using to investigate the issue.

To reproduce the issue, scroll midway through the table and expand several cells. Tap on a cell that's partially showing. The cell will appear to jump instead of staying in place.

Example:

Video 1

The problem is more obvious when I comment out the line that scrolls to the top of the cell after selecting a cell.

Video 2

I tried @DonMag's suggestion. With small cells, the problem does not occur. When I increased cell heights to take up >60% of the screen height, the jump animation occurred (video).

I changed

Question Label.top = topMargin + 8

to

Question Label.top = topMargin + 800

When I dive into the code, the problem seems to occur when calling

[tableView beginUpdates];
[tableView endUpdates];

But this snippet is necessary for the table view to recalculate cell heights.

I want the cell to stay in-place while resizing, without the jumping animation.

Body:
After further investigation, the issue is caused when the table has cells with varying heights (e.g. 100 vs 800). I can't use the same estimated height for every cell, or else the content appears to jump when expanding/collapsing cells.

The solution has 2 parts, both of which are needed.

Using Real Cell Sizes

In heightForRowAtIndexPath:, each row uses a precise calculation instead of an estimate.

Multiple Reuse Pools

I assigned a unique ID to every type of cell. Each type of cell has similar heights. For example, type A has height=120, type B has height=400.

Then I registered a different "pool" of cells for each type. Even though CustomCell is the the same class for different cell types, each cell type has different constraints and sizes. This allows a cell with the correct estimated size to be dequeued from the reuse pool.

tableView.rowHeight = UITableViewAutomaticDimension;
[tableView registerClass:[CustomCell class] forCellReuseIdentifier:typeA];
[tableView registerClass:[CustomCell class] forCellReuseIdentifier:typeB];
...
NSString *cellID = // Could be typeA, typeB, etc.
cell = [tableView dequeueReusableCellWithIdentifier:cellID];


问:
vim + janus / indent a perl block
using vim + janus (https://github.com/carlhuda/janus)
is enabled by default  in .vim/vimrc

filetype plugin indent on

i'm writing perl, every newline is indented by default.

how i can select a block (or the full document) and
reindent automatically?

答:
Since you're asking about perl I'm assuming "blocks" are identified by { and }.  If that's the case, I'd suggest indenting the block by using one of the following from somewhere inside the block:

>i{ to forcibly indent all lines by one shiftwidth

=i{ to reindent the block per the indent rules for perl

I personally prefer the latter, but if you have some non-standard indentation you don't want to screw up inside the block then you'd want to use the prior.

This takes advantage of vim's "Block"  text objects to operate on only the desired text.

Title: vim + janus / indent a perl block