问:
how to format mysql float into sytem local values or decimal comma for a reportlab billing system
I have a Reportlab form for a billing system and it works good. But what I want to get are the values in sytem local values, with decimal comma, or separator; something as next instead as shown in the picture:

```<code>1,350,000.00
</code>```

I'd like something like FORMAT in MySQL, but the problem with this one is that it does'nt let me to sum the values to get the total because it returns the values as string.

SELECT FORMAT (columna, 'es_CO') FROM tabla;

How my form looks like

And my Python code:

Just retefuente, ivajuridico, rteiva and i_vlrenta are float in mysql

```<code>#!/usr/bin/python
#-*- coding:utf-8 -*-
from Tkinter import*
from tkMessageBox import*
import MySQLdb
from controller import *
import analisis_arrendatarios
import os
import datetime
import time
import locale
locale.setlocale(locale.LC_ALL, "")
#LIBRERÍA PLATYPUS DE REPORTLAB PARA CREAR TABLAS
from reportlab.platypus import (SimpleDocTemplate, PageBreak, Image, Spacer,
Paragraph, Table, TableStyle)
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
styleSheet = getSampleStyleSheet()
style = styleSheet['BodyText']

class Proceso_Fact_Auto_Arre(Frame):
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)

        global opt

        #VARIABLES
        opt = IntVar()

        #WIDGETS
        header = Label(self, text="TENANTS AUTO BILLING PROCESS", font="bold")
        header.pack(pady=20, side=TOP)

        wrapper = Frame (self)
        wrapper.pack()

        r1 = Radiobutton(wrapper, text="Generate Analysis", variable=opt, value=0).pack(pady=5, anchor=W)
        r2 = Radiobutton(wrapper, text="Generate Billings", variable=opt, value=1).pack(pady=5, anchor=W)
        Button(wrapper, text="Iniciar Proceso", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=operacion).pack(pady=5, anchor=W)

def operacion():
    if opt.get()==0:
        showinfo('Operation', "Generate Analysis")
        try:
            connect.commit()
            #Consulta de códigos y valores de la tabla 'configuracion'
            cursor.execute("SELECT cod_canon, cod_subtotalarrend, cod_ivaarrend,
                      retefuente, ivajuridico, rteiva, resolucion
                    FROM configuracion;")
            dato1 = cursor.fetchall()
            #Consulta de datos generales del propietario y el arrendatario para la factura
            cursor.execute("SELECT p_cc, dueño, r_carpeta, relacionip.i_cod, i_dir, i_vlrenta, i_tel, contratos.a_cc, inquilino, a_tpersona, a_contribuyente
                  FROM contratos
                  INNER JOIN relacionip ON contratos.r_id = relacionip.r_id
                  INNER JOIN inmuebles ON relacionip.i_cod = inmuebles.i_cod
                  INNER JOIN arrendatarios ON contratos.a_cc = arrendatarios.a_cc;")
            #cursor.execute("SELECT p_cc, dueño, r_carpeta, relacionip.i_cod, i_dir, FORMAT(SUM(i_vlrenta), 2,'es'), i_tel, contratos.a_cc, inquilino, a_tpersona, a_contribuyente
                  #FROM contratos
                  #INNER JOIN relacionip ON contratos.r_id = relacionip.r_id
                  #INNER JOIN inmuebles ON relacionip.i_cod = inmuebles.i_cod
                  #INNER JOIN arrendatarios ON contratos.a_cc = arrendatarios.a_cc;")
            dato2 = cursor.fetchall()
        except:
            pass
        for c in dato1:
            canon = c[0]
            subtotal = c[1]
            iva = c[2]
            retef = c[3]
            ivajuridi = c[4]
            retei = c[5]
            resolucion = c[6]

        doc = SimpleDocTemplate("facturas/factura_auto_inquilino.pdf", pagesize = (595.27,400.00), rightMargin=5, leftMargin=5, topMargin=10, bottomMargin=0)
        story=[]

        for i in dato2:
            nit = i[0]
            prop = i[1]
            folder = i[2]
            inm = i[3]
            loc = i[4]
            renta = i[5]
            tel = i[6]
            cc = i[7]
            arrend = i[8]
            tipo = i[9]
            contri = i[10]
            #SI ARREND ES NATURAL(1)
            if tipo == 1:
                tipo = 0
            #SI ARREND ES JURÍDICO(2)
            if tipo == 2:
                tipo = renta*ivajuridi/100

            total = renta+tipo

            tiempo = datetime.date.today()
            anio = time.strftime("%Y")
            mes = time.strftime("%B")

        #-------------------------------------------- CABECERA DEL DOCUMENTO

            #VARIABLES
            logo = Image("img/logo.gif", width=150, height=45) #LOGO
            logo.hAlign ='LEFT' #Posicion de la img en la hoja

            info = Paragraph('''<para align=center leading=8><font size=6>CALLE 11A N°42-68 LOC,195 ED. EL DORADO<br/>TELEFONO: 3110513 FAX:2664154<br/>AFILIADO A FENALCO<br/>M.A.V.U N°000078</font></para>''', styleSheet["BodyText"])

            tipoDoc = Paragraph ('''<para align=right><b>FACTURA DE VENTA<br/>N°</b></para>''', styleSheet["BodyText"])

            #TABLA 1
            tabla1 = Table([[logo, info, tipoDoc]], colWidths=[200,150,140], rowHeights=None)
            tabla1.setStyle([
                ('VALIGN', (1,0), (2,0), 'TOP'),
                ('ALIGN', (2,0), (2,0), 'RIGHT')#ALINEAR A LA DER
                ])

            story.append(tabla1) #Construye la tabla 't' definida anteriormente
            story.append(Spacer(0,-10)) #Espacio del salto de línea con el siguiente Ejemplo

        #-------------------------------------------- DATOS GENERALES DEL DOCUMENTO

            #VARIABLES
            inquilino = Paragraph ('''<font size=6><b>Nombre Arrendatario:</b><br/></font>%s'''%arrend, styleSheet["BodyText"])
            docID = Paragraph ('''<font size=6><b>CC/Nit: </b></font>   %s''' %nit, styleSheet["BodyText"])
            locImn = Paragraph ('''<font size=6><b>Dirección Inmueble:</b><br/></font>%s'''%loc, styleSheet["BodyText"])
            telefono = Paragraph ('''<font size=6><b>Teléfono:</b><br/></font>%s'''%tel, styleSheet["BodyText"])
            IDpropietario = Paragraph ('''<font size=6><b>CC/Nit:</b><br/></font>%s'''%cc, styleSheet["BodyText"])
            propietario = Paragraph ('''<font size=6><b>Propietario: </b></font>%s'''%prop, styleSheet["BodyText"])
            fechaFormato = Paragraph ('''<para align=center fontSize=6>Día Mes Año</para>''', styleSheet["BodyText"])
            hoy = time.strftime("%d/%m/%Y")
            fecha = Paragraph ('''<para align=center spaceBefore=0>%s</para>''' %hoy, styleSheet["BodyText"])
            codigoImn = Paragraph ('''<font size=6><b>Código Inmueble:</b><br/></font>%s'''%inm, styleSheet["BodyText"])

            #TABLA 2
            datos = [[inquilino,'','','','',[fechaFormato,fecha]],
                    [docID,'','',propietario,'',''],
                    [locImn,'',telefono,IDpropietario,'',codigoImn]]

            tabla2 = Table(datos,
                           style=[('BOX',(0,0),(2,2),0.5,colors.black),
                                  ('VALIGN', (0,0),(2,0),'TOP'),
                                  ('SPAN',(0,0),(2,0)),#Combinar 3 filas (col0,row0) hasta (col2,row0) Arrendatario #0
                                  ('SPAN',(0,1),(2,1)),#Combinar 3 filas CC/Nit #1
                                  ('SPAN',(0,2),(1,2)),#Combinar 2 filas Dirección #2
                                  ('SPAN',(3,1),(5,1)),#Combinar 3 filas Nombre Propietario #
                                  ('SPAN',(3,2),(4,2)),#Combinar 2 filas CC/Nit Propietario #
                                  ('GRID',(3,1),(4,2),0.5,colors.black),
                                  ('GRID',(5,0),(5,2),0.5,colors.black)
                                 ],colWidths=[100,90,90,90,80,70], rowHeights=None)

            #Constructor y espaciado
            story.append(Spacer(0,15)) #Espacio del salto de línea con el siguiente Ejemplo
            story.append(tabla2) #Construye la tabla 't' definida anteriormente

        #-------------------------------------------- DETALLES DEL DOCUMENTO

            #VARIABLES
            desc = Paragraph('''<para align=center><b>DESCRIPCION</b></para>''', styleSheet["BodyText"])
            vlr = Paragraph('''<para align=center><b>VALOR</b></para>''', styleSheet["BodyText"])
            concepto = Paragraph('''Valor Arrendamiento Mes: %s/%s''' % (mes,anio), styleSheet["BodyText"])

            resol = "Resolucion Dian N°110000658514 de Diciembre de 2015 Consectivo Facturacion 33001 al 36000. P"

            #TABLA 3
            data=[[desc, '', vlr],      #0
                  [concepto, '', renta], #1
                  ['', '', ''],         #2
                  ['', '', ''],         #3
                  ['', '', ''],         #4
                  ['', '', ''],         #5
                  ['', '', ''],         #6
                  ['Observaciones', 'SUBTOTAL', renta], #7
                  ['', 'IVA', tipo], #8
                  [resolucion, 'TOTAL', total]] #9

            #Formato de la tabla
            tabla3 = Table(data,
                        style=[('GRID',(0,0),(2,0),0.5,colors.black),#Color regilla de DESCRIPCION & VALOR
                               ('BOX',(2,1),(2,9),0.5,colors.black), #Color & grosor de la tabla/marco externo de los VALORES
                               #('BACKGROUND',(0,0),(2,0), colors.pink), #Color de fondo de DESCRIPCION & VALOR #0
                               ('SPAN',(0,0),(1,0)), #Combinar filas DESCRIPCION #0
                               ('BOX',(0,1),(2,6),0.5,colors.black), #Color & grosor de la tabla o marco externo de los DETALLES
                               ('ALIGN', (2,1), (2,1), 'RIGHT'),#Centrar renta #1
                               ('ALIGN', (2,7), (2,7), 'RIGHT'),#Centrar renta #7
                               ('ALIGN', (2,8), (2,8), 'RIGHT'),#Centrar tipo #8
                               ('ALIGN', (2,9), (2,9), 'RIGHT'),#Centrar total #9
                               #('ALIGN', (2,9), (2,9), 'CENTER'),#Centrar total #9
                               ('SPAN',(0,1),(1,1)), #Combinar filas de Detalle #1
                               ('SPAN',(0,2),(1,2)), #Combinar filas de Detalle #2
                               ('SPAN',(0,3),(1,3)), #Combinar filas de Detalle #3
                               ('SPAN',(0,4),(1,4)), #Combinar filas de Detalle #4
                               ('SPAN',(0,5),(1,5)), #Combinar filas de Detalle #5
                               ('SPAN',(0,6),(1,6)), #Combinar filas de Detalle #6
                               ('GRID',(1,7),(2,9),0.5,colors.black),#Color regilla de SUBTOTAL, IVA, TOTAL
                               ('BOX',(0,7),(0,9),0.5,colors.black), #Color & grosor de la tabla o marco externo de los OBSERVACIONES Y RESOLUCION
                               ('FONTSIZE', (0,9),(0,9),7), #Tamaño de la Resolucion
                               #('BACKGROUND',(1,9),(1,9),colors.black),#Color de fondo de TOTAL
                               ('TEXTCOLOR',(1,9),(1,9),colors.black), #Color de letra de TOTAL
                               #('BACKGROUND',(2,9),(2,9),colors.grey)#Color de fondo de VALOR TOTAL
                              ],colWidths=[340,80,100], rowHeights=None)

            story.append(Spacer(0,15)) #Espacio del salto de línea con el siguiente Ejemplo
            story.append(tabla3) #Construye la tabla 't' definida anteriormente

        #-------------------------------------------- FIN PDF

        doc.build(story) #Constructor del documento

        if sys.platform == 'linux2':
            os.system("xdg-open ~/Project/facturas/factura_auto_inquilino.pdf")#DEBIAN
        elif sys.platform == 'linux2':
            os.system("/usr/bin/gnome-open facturas/factura_auto_inquilino.pdf")#UBUNTU
        else:
            os.startfile("Project/facturas/factura_auto_inquilino.pdf")#WINDOWS

    else:
        #Code to insert data into a billinf table)
</code>```

答:
```<code>SELECT FORMAT(SUM(columna), 2, 'es_CO') FROM tabla;
</code>```

For example:

```<code>mysql> SELECT FORMAT(SUM(population), 3, 'es_CO') FROM canada;
+-------------------------------------+
| FORMAT(SUM(population), 3, 'es_CO') |
+-------------------------------------+
| 23584718,000                        |
+-------------------------------------+
1 row in set (0.01 sec)
</code>```

I suspect you wanted something like

```<code>| 23.584.718,000                      |
</code>```

Then I suggest you file a bug with bugs.mysql.com .  It seems that the 'grouping separator' is incorrect?

Meanwhile, will 'es' (instead if 'es_CO') work correctly enough?

Body:
I have a Reportlab form for a billing system and it works good. But what I want to get are the values in sytem local values, with decimal comma, or separator; something as next instead as shown in the picture:

1,350,000.00

I'd like something like FORMAT in MySQL, but the problem with this one is that it does'nt let me to sum the values to get the total because it returns the values as string.

SELECT FORMAT (columna, 'es_CO') FROM tabla;

How my form looks like

And my Python code:

Just retefuente, ivajuridico, rteiva and i_vlrenta are float in mysql

#!/usr/bin/python
#-*- coding:utf-8 -*-
from Tkinter import*
from tkMessageBox import*
import MySQLdb
from controller import *
import analisis_arrendatarios
import os
import datetime
import time
import locale
locale.setlocale(locale.LC_ALL, "")
#LIBRERÍA PLATYPUS DE REPORTLAB PARA CREAR TABLAS
from reportlab.platypus import (SimpleDocTemplate, PageBreak, Image, Spacer,
Paragraph, Table, TableStyle)
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
styleSheet = getSampleStyleSheet()
style = styleSheet['BodyText']

class Proceso_Fact_Auto_Arre(Frame):
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)

        global opt

        #VARIABLES
        opt = IntVar()

        #WIDGETS
        header = Label(self, text="TENANTS AUTO BILLING PROCESS", font="bold")
        header.pack(pady=20, side=TOP)

        wrapper = Frame (self)
        wrapper.pack()

        r1 = Radiobutton(wrapper, text="Generate Analysis", variable=opt, value=0).pack(pady=5, anchor=W)
        r2 = Radiobutton(wrapper, text="Generate Billings", variable=opt, value=1).pack(pady=5, anchor=W)
        Button(wrapper, text="Iniciar Proceso", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=operacion).pack(pady=5, anchor=W)

def operacion():
    if opt.get()==0:
        showinfo('Operation', "Generate Analysis")
        try:
            connect.commit()
            #Consulta de códigos y valores de la tabla 'configuracion'
            cursor.execute("SELECT cod_canon, cod_subtotalarrend, cod_ivaarrend,
                      retefuente, ivajuridico, rteiva, resolucion
                    FROM configuracion;")
            dato1 = cursor.fetchall()
            #Consulta de datos generales del propietario y el arrendatario para la factura
            cursor.execute("SELECT p_cc, dueño, r_carpeta, relacionip.i_cod, i_dir, i_vlrenta, i_tel, contratos.a_cc, inquilino, a_tpersona, a_contribuyente
                  FROM contratos
                  INNER JOIN relacionip ON contratos.r_id = relacionip.r_id
                  INNER JOIN inmuebles ON relacionip.i_cod = inmuebles.i_cod
                  INNER JOIN arrendatarios ON contratos.a_cc = arrendatarios.a_cc;")
            #cursor.execute("SELECT p_cc, dueño, r_carpeta, relacionip.i_cod, i_dir, FORMAT(SUM(i_vlrenta), 2,'es'), i_tel, contratos.a_cc, inquilino, a_tpersona, a_contribuyente
                  #FROM contratos
                  #INNER JOIN relacionip ON contratos.r_id = relacionip.r_id
                  #INNER JOIN inmuebles ON relacionip.i_cod = inmuebles.i_cod
                  #INNER JOIN arrendatarios ON contratos.a_cc = arrendatarios.a_cc;")
            dato2 = cursor.fetchall()
        except:
            pass
        for c in dato1:
            canon = c[0]
            subtotal = c[1]
            iva = c[2]
            retef = c[3]
            ivajuridi = c[4]
            retei = c[5]
            resolucion = c[6]

        doc = SimpleDocTemplate("facturas/factura_auto_inquilino.pdf", pagesize = (595.27,400.00), rightMargin=5, leftMargin=5, topMargin=10, bottomMargin=0)
        story=[]

        for i in dato2:
            nit = i[0]
            prop = i[1]
            folder = i[2]
            inm = i[3]
            loc = i[4]
            renta = i[5]
            tel = i[6]
            cc = i[7]
            arrend = i[8]
            tipo = i[9]
            contri = i[10]
            #SI ARREND ES NATURAL(1)
            if tipo == 1:
                tipo = 0
            #SI ARREND ES JURÍDICO(2)
            if tipo == 2:
                tipo = renta*ivajuridi/100

            total = renta+tipo

            tiempo = datetime.date.today()
            anio = time.strftime("%Y")
            mes = time.strftime("%B")

        #-------------------------------------------- CABECERA DEL DOCUMENTO

            #VARIABLES
            logo = Image("img/logo.gif", width=150, height=45) #LOGO
            logo.hAlign ='LEFT' #Posicion de la img en la hoja

            info = Paragraph('''<para align=center leading=8>CALLE 11A N°42-68 LOC,195 ED. EL DORADO
TELEFONO: 3110513 FAX:2664154
AFILIADO A FENALCO
M.A.V.U N°000078</para>''', styleSheet["BodyText"])

            tipoDoc = Paragraph ('''<para align=right>FACTURA DE VENTA
N°</para>''', styleSheet["BodyText"])

            #TABLA 1
            tabla1 = Table([[logo, info, tipoDoc]], colWidths=[200,150,140], rowHeights=None)
            tabla1.setStyle([
                ('VALIGN', (1,0), (2,0), 'TOP'),
                ('ALIGN', (2,0), (2,0), 'RIGHT')#ALINEAR A LA DER
                ])

            story.append(tabla1) #Construye la tabla 't' definida anteriormente
            story.append(Spacer(0,-10)) #Espacio del salto de línea con el siguiente Ejemplo

        #-------------------------------------------- DATOS GENERALES DEL DOCUMENTO

            #VARIABLES
            inquilino = Paragraph ('''Nombre Arrendatario:
%s'''%arrend, styleSheet["BodyText"])
            docID = Paragraph ('''CC/Nit:    %s''' %nit, styleSheet["BodyText"])
            locImn = Paragraph ('''Dirección Inmueble:
%s'''%loc, styleSheet["BodyText"])
            telefono = Paragraph ('''Teléfono:
%s'''%tel, styleSheet["BodyText"])
            IDpropietario = Paragraph ('''CC/Nit:
%s'''%cc, styleSheet["BodyText"])
            propietario = Paragraph ('''Propietario: %s'''%prop, styleSheet["BodyText"])
            fechaFormato = Paragraph ('''<para align=center fontSize=6>Día Mes Año</para>''', styleSheet["BodyText"])
            hoy = time.strftime("%d/%m/%Y")
            fecha = Paragraph ('''<para align=center spaceBefore=0>%s</para>''' %hoy, styleSheet["BodyText"])
            codigoImn = Paragraph ('''Código Inmueble:
%s'''%inm, styleSheet["BodyText"])

            #TABLA 2
            datos = [[inquilino,'','','','',[fechaFormato,fecha]],
                    [docID,'','',propietario,'',''],
                    [locImn,'',telefono,IDpropietario,'',codigoImn]]

            tabla2 = Table(datos,
                           style=[('BOX',(0,0),(2,2),0.5,colors.black),
                                  ('VALIGN', (0,0),(2,0),'TOP'),
                                  ('SPAN',(0,0),(2,0)),#Combinar 3 filas (col0,row0) hasta (col2,row0) Arrendatario #0
                                  ('SPAN',(0,1),(2,1)),#Combinar 3 filas CC/Nit #1
                                  ('SPAN',(0,2),(1,2)),#Combinar 2 filas Dirección #2
                                  ('SPAN',(3,1),(5,1)),#Combinar 3 filas Nombre Propietario #
                                  ('SPAN',(3,2),(4,2)),#Combinar 2 filas CC/Nit Propietario #
                                  ('GRID',(3,1),(4,2),0.5,colors.black),
                                  ('GRID',(5,0),(5,2),0.5,colors.black)
                                 ],colWidths=[100,90,90,90,80,70], rowHeights=None)

            #Constructor y espaciado
            story.append(Spacer(0,15)) #Espacio del salto de línea con el siguiente Ejemplo
            story.append(tabla2) #Construye la tabla 't' definida anteriormente

        #-------------------------------------------- DETALLES DEL DOCUMENTO

            #VARIABLES
            desc = Paragraph('''<para align=center>DESCRIPCION</para>''', styleSheet["BodyText"])
            vlr = Paragraph('''<para align=center>VALOR</para>''', styleSheet["BodyText"])
            concepto = Paragraph('''Valor Arrendamiento Mes: %s/%s''' % (mes,anio), styleSheet["BodyText"])

            resol = "Resolucion Dian N°110000658514 de Diciembre de 2015 Consectivo Facturacion 33001 al 36000. P"

            #TABLA 3
            data=[[desc, '', vlr],      #0
                  [concepto, '', renta], #1
                  ['', '', ''],         #2
                  ['', '', ''],         #3
                  ['', '', ''],         #4
                  ['', '', ''],         #5
                  ['', '', ''],         #6
                  ['Observaciones', 'SUBTOTAL', renta], #7
                  ['', 'IVA', tipo], #8
                  [resolucion, 'TOTAL', total]] #9

            #Formato de la tabla
            tabla3 = Table(data,
                        style=[('GRID',(0,0),(2,0),0.5,colors.black),#Color regilla de DESCRIPCION & VALOR
                               ('BOX',(2,1),(2,9),0.5,colors.black), #Color & grosor de la tabla/marco externo de los VALORES
                               #('BACKGROUND',(0,0),(2,0), colors.pink), #Color de fondo de DESCRIPCION & VALOR #0
                               ('SPAN',(0,0),(1,0)), #Combinar filas DESCRIPCION #0
                               ('BOX',(0,1),(2,6),0.5,colors.black), #Color & grosor de la tabla o marco externo de los DETALLES
                               ('ALIGN', (2,1), (2,1), 'RIGHT'),#Centrar renta #1
                               ('ALIGN', (2,7), (2,7), 'RIGHT'),#Centrar renta #7
                               ('ALIGN', (2,8), (2,8), 'RIGHT'),#Centrar tipo #8
                               ('ALIGN', (2,9), (2,9), 'RIGHT'),#Centrar total #9
                               #('ALIGN', (2,9), (2,9), 'CENTER'),#Centrar total #9
                               ('SPAN',(0,1),(1,1)), #Combinar filas de Detalle #1
                               ('SPAN',(0,2),(1,2)), #Combinar filas de Detalle #2
                               ('SPAN',(0,3),(1,3)), #Combinar filas de Detalle #3
                               ('SPAN',(0,4),(1,4)), #Combinar filas de Detalle #4
                               ('SPAN',(0,5),(1,5)), #Combinar filas de Detalle #5
                               ('SPAN',(0,6),(1,6)), #Combinar filas de Detalle #6
                               ('GRID',(1,7),(2,9),0.5,colors.black),#Color regilla de SUBTOTAL, IVA, TOTAL
                               ('BOX',(0,7),(0,9),0.5,colors.black), #Color & grosor de la tabla o marco externo de los OBSERVACIONES Y RESOLUCION
                               ('FONTSIZE', (0,9),(0,9),7), #Tamaño de la Resolucion
                               #('BACKGROUND',(1,9),(1,9),colors.black),#Color de fondo de TOTAL
                               ('TEXTCOLOR',(1,9),(1,9),colors.black), #Color de letra de TOTAL
                               #('BACKGROUND',(2,9),(2,9),colors.grey)#Color de fondo de VALOR TOTAL
                              ],colWidths=[340,80,100], rowHeights=None)

            story.append(Spacer(0,15)) #Espacio del salto de línea con el siguiente Ejemplo
            story.append(tabla3) #Construye la tabla 't' definida anteriormente

        #-------------------------------------------- FIN PDF

        doc.build(story) #Constructor del documento

        if sys.platform == 'linux2':
            os.system("xdg-open ~/Project/facturas/factura_auto_inquilino.pdf")#DEBIAN
        elif sys.platform == 'linux2':
            os.system("/usr/bin/gnome-open facturas/factura_auto_inquilino.pdf")#UBUNTU
        else:
            os.startfile("Project/facturas/factura_auto_inquilino.pdf")#WINDOWS

    else:
        #Code to insert data into a billinf table)

Body:
SELECT FORMAT(SUM(columna), 2, 'es_CO') FROM tabla;

For example:

mysql> SELECT FORMAT(SUM(population), 3, 'es_CO') FROM canada;
+-------------------------------------+
| FORMAT(SUM(population), 3, 'es_CO') |
+-------------------------------------+
| 23584718,000                        |
+-------------------------------------+
1 row in set (0.01 sec)

I suspect you wanted something like

| 23.584.718,000                      |

Then I suggest you file a bug with bugs.mysql.com .  It seems that the 'grouping separator' is incorrect?

Meanwhile, will 'es' (instead if 'es_CO') work correctly enough?


来源: stackexchange

问:
Is there any way to assign an index of my choice to array collection in flex?
I want to give an array index to array collection let say 205 when it is started is it possible to do so in flex or any alternate of this.

actually I need to index the objects with a specific no, in 2D array collection

say

```<code>205 a c d g f d
268 s g h g f f
805 d g h h f f d
</code>```

where integers are indexes and alphabets are object referenced by these integers

答:
I am having some trouble completely understanding your question, but if I do understand you correctly, you want to override the indexing method of an object?

The easiest way to do this is to have your class extend Proxy.  You need to override nextNameIndex(index:int):int and nextValue(index:int):*.  If that is a bit confusing, just put breakpoints in your overrides when you try to do something like myObject[205].

Good luck :)

ContentLicense: CC BY-SA 2.5

Body:
I want to give an array index to array collection let say 205 when it is started is it possible to do so in flex or any alternate of this.

actually I need to index the objects with a specific no, in 2D array collection

say

205 a c d g f d
268 s g h g f f
805 d g h h f f d

where integers are indexes and alphabets are object referenced by these integers


问:
Stuck on Some Javascript - Displaying Image on Mouseover of text
I'm trying to replicate the functionality of this page http://www.annedeckerarchitects.com/recognition/publications/ in a simpler way. The functionality I'm referring to is mousing over on something on the right and changing the image on the left.

What I have; https://jsfiddle.net/7j2zkndx/3/

html:

```<code><img class="global-image" />
<div class="scrolling-list">
<ul>
    <li data-link="http://i.imgur.com/ne3L7hy.jpg">Link Test <a href="#">click for more</a></li>
    <li data-link="http://i.imgur.com/mwa1Wwl.jpg">Link Test 2 <a href="#">click for more</a></li>
</ul>
</div>
</code>```

javascript;

```<code>var globalImage = $(".global-image").first();
$(".scrolling-list>li").each(function() {
    var list = this;
    var img = document.CreateElement("img");
    img.src = $(list).getAttribute("data-link");
    img.addEventListener("load", function() {
        list.addEventListener("mouseOver", function() {
            globalImage.src = $(list).getAttribute("data-link");
        });
    });
}();
</code>```

css;

```<code>.scrolling-list {
    width: 600px;
    height: 600px;
    overflow: scroll;
}
.global-image. .scrolling-list {
    display: inline-block;
}
</code>```

I'm honestly at a loss why it isn't working. It would be best to assume I'm a novice in JS.

Thanks.

答:
globalImage is a jQuery collection. globalImage.src won't change the src attribute of the element. Use jQuery's attr function to set it. Also, you need to be more careful with your capitalization. mouseOver should be mouseover, CreateElement should be createElement.

$(".scrolling-list>li") only works if your
 is
.

Lastly, you can have issues if you assign img.src before adding the onload event handler. If the image is cached, it might finish loading before there is a handler, which means that your code won't execute at all.

Fiddle

```<code>var globalImage = $(".global-image").first();
$(".scrolling-list>li").each(function() {
    var list = this;
    var img = document.createElement("img");

    img.addEventListener("load", function() {
        list.addEventListener("mouseover", function() {
            globalImage.attr("src", $(list).attr("data-link"));
        });
    });
    img.src = $(list).attr("data-link");
    console.log(img.src);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to replicate the functionality of this page http://www.annedeckerarchitects.com/recognition/publications/ in a simpler way. The functionality I'm referring to is mousing over on something on the right and changing the image on the left.

What I have; https://jsfiddle.net/7j2zkndx/3/

html:

Link Test click for more

Link Test 2 click for more

javascript;

var globalImage = $(".global-image").first();
$(".scrolling-list>li").each(function() {
    var list = this;
    var img = document.CreateElement("img");
    img.src = $(list).getAttribute("data-link");
    img.addEventListener("load", function() {
        list.addEventListener("mouseOver", function() {
            globalImage.src = $(list).getAttribute("data-link");
        });
    });
}();

css;

.scrolling-list {
    width: 600px;
    height: 600px;
    overflow: scroll;
}
.global-image. .scrolling-list {
    display: inline-block;
}

I'm honestly at a loss why it isn't working. It would be best to assume I'm a novice in JS.

Thanks.

Body:
globalImage is a jQuery collection. globalImage.src won't change the src attribute of the element. Use jQuery's attr function to set it. Also, you need to be more careful with your capitalization. mouseOver should be mouseover, CreateElement should be createElement.

$(".scrolling-list>li") only works if your <ul> is <ul class="scrolling-list">.

Lastly, you can have issues if you assign img.src before adding the onload event handler. If the image is cached, it might finish loading before there is a handler, which means that your code won't execute at all.

Fiddle

var globalImage = $(".global-image").first();
$(".scrolling-list>li").each(function() {
    var list = this;
    var img = document.createElement("img");

    img.addEventListener("load", function() {
        list.addEventListener("mouseover", function() {
            globalImage.attr("src", $(list).attr("data-link"));
        });
    });
    img.src = $(list).attr("data-link");
    console.log(img.src);
});


问:
Selectable Recipient with Pipes Contact Form 7
I have integrating contact form 7 plugin for mail functionality. On different services, mail should be delivered to different emailIDs. For that i have used dropdown with selectable pipe. I want to call this Select Recipient in "To field" in mail section from backend so that mail functionality work differently for each service.</p>

答:
First fill out the shortcode in the "Form" Tab of the Contact Form 7 Dashboard, such as [select* email-recipient “Sales|sales@yourdomain.com” “Tech Support|support@yourdomain.com” “Inquiry|info@yourdomain.com”], which it sounds like you have already done.

Then navigate to the "mail" tab and enter the corresponding tag for your select fields. In the example above, I would use [email-recipient] in order to dynamically select the appropriate email address.


问:
importerror: no module named flask.ext.script
In fact I cannot use any pakage now!

importerror: no module named flask.ext.script

importerror: no module named Pymongo

答:
If you are using the IDE such as pycharm, then maybe need to set the interpreter of python for the right version. Otherwise the packages that you have installed can not be used for the current project. I have also encountered such kind of questions until I set my IDE's interpreter to  the Python 2.7.
Then you can freely import the flask_script</p>


问:
How can I dynamically generate parameters for a create method?
I have a model "Item", and I want to generate a bunch of Items with data taken from a CSV file. But I want to allow the user to select which data columns are used.

So my model "User" has a json attribute called Columns, telling which columns should be used from that user's CSV file. For example, if user.columns == {"title"=>"true","category"=>"false"}, then the Title column should be used but the Category column shouldn't.
(Alternatively, I could only list the columns I want to include, like this: {"title"=>"included"}, and later do something like user.columns.each {|c| c[0]} to get an array of all the included columns.)

I have a method for generating Items based on the CSV data:

```<code>def create
  #...
  SmarterCSV.process(file).each do |row| #this line returns an array of all the rows in the CSV file
    Item.create(title: row[:title], category: row[:category])
  end
end
</code>```

but how can I modify the method's parameters based on the contents of user.columns? For the {"title"=>"true","category"=>"false"} example, the method would just be Item.create(name: row[:title]). Is it possible to dynamically generate a method like that?

I'm planning to have quite a lot of possible columns, so doing an if conditional for every possibility is unfeasible.

答:
I would add a method to your User model to return the column names as symbols:

```<code>class User
  def selected_columns
    columns.select{|_,v| v == "true"}.keys.map(&:to_sym)
  end
end
</code>```

and then modify your item creation like so:

```<code>Item.create(row.slice(*user.selected_columns))
</code>```

Body:
I have a model "Item", and I want to generate a bunch of Items with data taken from a CSV file. But I want to allow the user to select which data columns are used.

So my model "User" has a json attribute called Columns, telling which columns should be used from that user's CSV file. For example, if user.columns == {"title"=>"true","category"=>"false"}, then the Title column should be used but the Category column shouldn't.
(Alternatively, I could only list the columns I want to include, like this: {"title"=>"included"}, and later do something like user.columns.each {|c| c[0]} to get an array of all the included columns.)

I have a method for generating Items based on the CSV data:

def create
  #...
  SmarterCSV.process(file).each do |row| #this line returns an array of all the rows in the CSV file
    Item.create(title: row[:title], category: row[:category])
  end
end

but how can I modify the method's parameters based on the contents of user.columns? For the {"title"=>"true","category"=>"false"} example, the method would just be Item.create(name: row[:title]). Is it possible to dynamically generate a method like that?

I'm planning to have quite a lot of possible columns, so doing an if conditional for every possibility is unfeasible.

Body:
I would add a method to your User model to return the column names as symbols:

class User
  def selected_columns
    columns.select{|_,v| v == "true"}.keys.map(&:to_sym)
  end
end

and then modify your item creation like so:

Item.create(row.slice(*user.selected_columns))


问:
Customising CSS within RMarkdown Slidy Presentations
So, there are a few questions on SO but none that seem to have solved this particular issue.

I am looking to customise my RMarkdown/Slidy presentation, created from RStudio, with a custom CSS template.

RStudio already allows minimal customisation using the built-in Bootswatch themes, accessible thus output: slidy presentation / theme: readable

There are other Bootswatch themes that are not built-in; specifically I might want to use Cyborg or Slate, which have a nice dark background (instead of white)

The following is an intuitive solution for overriding the Slidy CSS with a custom file:

```<code>```{css}

<link href="bootstrap-slate.css" rel="stylesheet">

```
</code>```

However, it fails with:

```<code>pandoc.exe: Could not fetch .\../fonts/glyphicons-halflings-regular.eot
.\../fonts/glyphicons-halflings-regular.eot: openBinaryFile: does not exist (No such file or directory)
Error: pandoc document conversion failed with error 67
In addition: Warning message:
running command '"C:/Program Files/RStudio/bin/pandoc/pandoc" +RTS -K512m -RTS segmentations.utf8.md --to slidy --from
markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --
output segmentations.html --smart --email-obfuscation none --self-contained --template "C:\Users\ME\Documents\R\R-3.3.3\library\rmarkdown\rmd\slidy\default.html" --include-in-header
"C:\Users\ME\AppData\Local\Temp\RtmpGYLCFf\rmarkdown-str378022cf50b0.html" --mathjax --variable "mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" --highlight-style pygments' had status 67
Execution halted
</code>```

Any suggestions would be welcome. Note that the solution in the documentation   rMarkdown documentation does not work. Solution there copied here for reference:

```<code>---
output:
  slidy_presentation:
    css: styles.css         ##
---

Error in yaml::yaml.load(string, ...) :
  Scanner error: mapping values are not allowed in this context at line 5, column 21
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load_utf8 -> <Anonymous> -> .Call
Execution halted
</code>```

答:
I've managed to answer my own question by developing my understanding of Bootstrap

I needed to use the entire Bootstrap directory, not just the Bootswatch theme css file in my WD. Then, to use "Slate" or whichever, involves replacing the default Bootstrap.css with the new theme.

This Post (how to include glyphicons in bootstrap 3)   has a top answer that describes it perfectly:

Body:
So, there are a few questions on SO but none that seem to have solved this particular issue.

I am looking to customise my RMarkdown/Slidy presentation, created from RStudio, with a custom CSS template.

RStudio already allows minimal customisation using the built-in Bootswatch themes, accessible thus output: slidy presentation / theme: readable

There are other Bootswatch themes that are not built-in; specifically I might want to use Cyborg or Slate, which have a nice dark background (instead of white)

The following is an intuitive solution for overriding the Slidy CSS with a custom file:

```{css}

<link href="bootstrap-slate.css" rel="stylesheet">

```

However, it fails with:

pandoc.exe: Could not fetch .\../fonts/glyphicons-halflings-regular.eot
.\../fonts/glyphicons-halflings-regular.eot: openBinaryFile: does not exist (No such file or directory)
Error: pandoc document conversion failed with error 67
In addition: Warning message:
running command '"C:/Program Files/RStudio/bin/pandoc/pandoc" +RTS -K512m -RTS segmentations.utf8.md --to slidy --from
markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --
output segmentations.html --smart --email-obfuscation none --self-contained --template "C:\Users\ME\Documents\R\R-3.3.3\library\rmarkdown\rmd\slidy\default.html" --include-in-header
"C:\Users\ME\AppData\Local\Temp\RtmpGYLCFf\rmarkdown-str378022cf50b0.html" --mathjax --variable "mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" --highlight-style pygments' had status 67
Execution halted

Any suggestions would be welcome. Note that the solution in the documentation   rMarkdown documentation does not work. Solution there copied here for reference:

---
output:
  slidy_presentation:
    css: styles.css         ##
---

Error in yaml::yaml.load(string, ...) :
  Scanner error: mapping values are not allowed in this context at line 5, column 21
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load_utf8 -> <Anonymous> -> .Call
Execution halted


问:
Cannot access a disposed object - How to fix?
In a VB.NET WinForms project, I get an exception

Cannot access a disposed of object

when closing a form. It occurs very rarely and I cannot recreate it on demand. The stack trace looks like this:

```<code>Cannot access a disposed object. Object name: 'dbiSchedule'.
  at System.Windows.Forms.Control.CreateHandle()
  at System.Windows.Forms.Control.get_Handle()
  at System.Windows.Forms.Control.PointToScreen(Point p)
  at Dbi.WinControl.Schedule.dbiSchedule.a(Boolean A_0)
  at Dbi.WinControl.Schedule.dbiSchedule.a(Object A_0, EventArgs A_1)
  at System.Windows.Forms.Timer.OnTick(EventArgs e)
  at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
  at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code>```

The dbiSchedule is a schedule control from Dbi-tech. There is a timer on the form that updates the schedule on the screen every few minutes.

Any ideas what is causing the exception and how I might go about fixing it? or even just being able to recreate it on demand?

Hej! Thanks for all the answers. We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.

It's a really annoying problem because if someone did come up with a solution that worked - I wouldn't be able to confirm the solution because I cannot recreate the problem manually.

答:
If this happens sporadically then my guess is that it has something to do with the timer.

I'm guessing (and this is only a guess since I have no access to your code) that the timer is firing while the form is being closed.  The dbiSchedule object has been disposed but the timer somehow still manages to try to call it.  This shouldn't happen, because if the timer has a reference to the schedule object then the garbage collector should see this and not dispose of it.

This leads me to ask: are you calling Dispose() on the schedule object manually?  If so, are you doing that before disposing of the timer?  Be sure that you release all references to the schedule object before Disposing it (i.e. dispose of the timer beforehand).

Now I realize that a few months have passed between the time you posted this and when I am answering, so hopefully, you have resolved this issue.  I'm writing this for the benefit of others who may come along later with a similar issue.

Hope this helps.

OwnerDisplayName: beta tester ben

ContentLicense: CC BY-SA 4.0

Body:
In a VB.NET WinForms project, I get an exception

Cannot access a disposed of object

when closing a form. It occurs very rarely and I cannot recreate it on demand. The stack trace looks like this:

Cannot access a disposed object. Object name: 'dbiSchedule'.
  at System.Windows.Forms.Control.CreateHandle()
  at System.Windows.Forms.Control.get_Handle()
  at System.Windows.Forms.Control.PointToScreen(Point p)
  at Dbi.WinControl.Schedule.dbiSchedule.a(Boolean A_0)
  at Dbi.WinControl.Schedule.dbiSchedule.a(Object A_0, EventArgs A_1)
  at System.Windows.Forms.Timer.OnTick(EventArgs e)
  at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
  at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

The dbiSchedule is a schedule control from Dbi-tech. There is a timer on the form that updates the schedule on the screen every few minutes.

Any ideas what is causing the exception and how I might go about fixing it? or even just being able to recreate it on demand?

Hej! Thanks for all the answers. We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.

It's a really annoying problem because if someone did come up with a solution that worked - I wouldn't be able to confirm the solution because I cannot recreate the problem manually.

OwnerDisplayName: Steve J


问:
javascript modify css class property while knowing only the class' name
Here's my css class:

```<code>.my-css-class-name
{
    display: block;
}
</code>```

And I have one element at my webpage that uses this class. I want to modify this element's "display" property.

I would happily do this by getting a handle to that element and then modifying what I need, BUT, I don't know the element's name - it's being randomly generated (it's a third-party extension).

So I figured I'm gonna have to get a handle to ".my-css-class-name" and modify that property directly.

How do I get there, cross-browser (major ones) solution?

Edit #1:

I'm looking for compatibility with newer browsers.

答: getElementByClassName is not possible (in older browsers) but there are work arounds including iterating through every element. See here for discussion Do we have getElementsByClassName in javascript?</p>

Body:
Here's my css class:

.my-css-class-name
{
    display: block;
}

And I have one element at my webpage that uses this class. I want to modify this element's "display" property.

I would happily do this by getting a handle to that element and then modifying what I need, BUT, I don't know the element's name - it's being randomly generated (it's a third-party extension).

So I figured I'm gonna have to get a handle to ".my-css-class-name" and modify that property directly.

How do I get there, cross-browser (major ones) solution?

Edit #1:

I'm looking for compatibility with newer browsers.


问:
azure blob returns 403 forbidden with correct access key
My test site has after a deploy started to get 403 forbidden back when trying to access files from the azure blob storage.
This is only a problem on our test environment, the new release works just fine in production. Both production and test is hosted in azure, and both use their own azure blob storage.

I have tried regenerating the access keys for the blob storage, without any luck.

I can use the access keys locally and connect to the test blob storage and access the files just fine.

If i try to change the test environment to use the production blob storage, i still get the 403 forbidden error.

Microsoft.WindowsAzure.Storage.StorageException: The remote server
returned an error: (403) Forbidden. ---> System.Net.WebException: The
remote server returned an error: (403) Forbidden. at
System.Net.HttpWebRequest.GetResponse() at
Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 677 --- End of inner exception stack trace --- at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand1
cmd, IRetryPolicy policy, OperationContext operationContext) in
c:\Program Files
(x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line
604 at
Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient.GetBlobReferenceFromServer(StorageUri
blobUri, AccessCondition accessCondition, BlobRequestOptions options,
OperationContext operationContext) in c:\Program Files
(x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlobClient.cs:line
563 at
Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer.GetBlobReferenceFromServer(String
blobName, AccessCondition accessCondition, BlobRequestOptions options,
OperationContext operationContext) in c:\Program Files
(x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlobContainer.cs:line
818 at ASP.XYZ in d:\XYZ.cshtml:line 27 Request Information
RequestID:fc137321-0001-00ce-02d2-de5736000000 RequestDate:Tue, 06 Jun
2017 14:41:21 GMT StatusMessage:Server failed to authenticate the
request. Make sure the value of Authorization header is formed
correctly including the signature.

It must be an issue on the azure app service that runs the test site. I just cannot see what it could be.

See gist here for some very simplified code https://gist.github.com/Skaanning/5cddf95a0d1ff210482d99a683e0be9c .

Edit
I have multiple other blob stores, but none of them work on the test site. They work fine on other environments though.

I tried scaling it up and down, without any luck. But then i tried changing from 32 bit to 64 bit and now it works! I will keep the question open, in case someone can explain what on earth happened here

答:
var img = container.GetBlobReference("someimage.png"); // this works just fine

  var img2 = container.GetBlobReferenceFromServer("someimage.png"); // this throws a 403

The first line will work fine. The reason is that it will not send request to server when we execute GetBlobReference method. When executing GetBlobReferenceFromServer method, it will send a request to server to get the blob content. It will throw 404 not found exception if the blob can't be found in blob server.

My test site has after a deploy started to get 403 forbidden back when trying to access files from the azure blob storage.

The 403 forbidden exception often caused by a wrong access key is used. Please print out the connection string which was used in your test environment.

```<code>Trace.Write(CloudConfigurationManager.GetSetting("blob.storage"));
</code>```

A Azure Storage connection string uses following format. Please make sure you have provided a right account name and key pair for the connection string. If you set account name1 and account key for account name2, it will cause the exception.

```<code>DefaultEndpointsProtocol=https;AccountName=[accountName];AccountKey=[accountKey];EndpointSuffix=core.windows.net
</code>```

Another thing would cause this issue is that the request to your storage server is rejected by your test server. Please check whether you have configured Dynamic IP Security in your web.config.

Edit 2017/6/7 4:26 PM

I suggest you take my upper suggestion. Please print out the connection string at runtime. If you set the connections string in both app setting in Azure portal and web.config. settings in Azure portal will override the settings in web.config.

Please also print out the current date time at runtime to check whether system time of your app instance is right. If the date or time of your system has been changed, 404 Forbidden also will happen.

The storage services ensure that a request is no older than 15 minutes by the time it reaches the service. This guards against certain security attacks, including replay attacks. When this check fails, the server returns response code 403 (Forbidden).

Reference: Authentication for the Azure Storage Services

Edit 2017/6/7 5:55 PM

Have you tried removing all the original files at your test server when deploying your release?

Body:
var img = container.GetBlobReference("someimage.png"); // this works just fine

  var img2 = container.GetBlobReferenceFromServer("someimage.png"); // this throws a 403

The first line will work fine. The reason is that it will not send request to server when we execute GetBlobReference method. When executing GetBlobReferenceFromServer method, it will send a request to server to get the blob content. It will throw 404 not found exception if the blob can't be found in blob server.

My test site has after a deploy started to get 403 forbidden back when trying to access files from the azure blob storage.

The 403 forbidden exception often caused by a wrong access key is used. Please print out the connection string which was used in your test environment.

Trace.Write(CloudConfigurationManager.GetSetting("blob.storage"));

A Azure Storage connection string uses following format. Please make sure you have provided a right account name and key pair for the connection string. If you set account name1 and account key for account name2, it will cause the exception.

DefaultEndpointsProtocol=https;AccountName=[accountName];AccountKey=[accountKey];EndpointSuffix=core.windows.net

Another thing would cause this issue is that the request to your storage server is rejected by your test server. Please check whether you have configured Dynamic IP Security in your web.config.

Edit 2017/6/7 4:26 PM

I suggest you take my upper suggestion. Please print out the connection string at runtime. If you set the connections string in both app setting in Azure portal and web.config. settings in Azure portal will override the settings in web.config.

Please also print out the current date time at runtime to check whether system time of your app instance is right. If the date or time of your system has been changed, 404 Forbidden also will happen.

The storage services ensure that a request is no older than 15 minutes by the time it reaches the service. This guards against certain security attacks, including replay attacks. When this check fails, the server returns response code 403 (Forbidden).

Reference: Authentication for the Azure Storage Services

Edit 2017/6/7 5:55 PM

Have you tried removing all the original files at your test server when deploying your release?


问:
Convert html anchor tag to mvc action link
I have this basic anchor tag inhtml

```<code><a href="signup.html" class="signup-button">CREER UN COMPTE</a>
</code>```

how can i convert it to mvc action link along with the css class.

答:
Code to Convert :

```<code><a href="signup.html" class="signup-button">CREER UN COMPTE</a>
</code>```

If I look at the above code, you have redirected to the simple html page i.e signup.html by using the anchor tag.

And if you want the same thing in mvc actionlink  , As per my knowledge , the same thing is not possible by using the mvc actionlink because if you look at the below overloads of action link at msdn .

https://msdn.microsoft.com/en-us/library/dd460522.aspx

```<code>public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    string protocol,
    string hostName,
    string fragment,
    Object routeValues,
    Object htmlAttributes
)
</code>```

It takes only the actionname and controller name for any redirection to happen.

Alternative solution:

If you changed that signup.html to the signup action by using the controller then you can easily call by using the below code.

```<code>@Html.ActionLink("CREER UN COMPTE", "signup", "AnyControllerName", protocol: null, hostName: null, fragment: "MyAnchor", routeValues: null, new {@class="signup-button"})
</code>```

Correct me if am wrong and hope that above information was helpful.

Thanks

Karthik

Body:
I have this basic anchor tag inhtml

CREER UN COMPTE

how can i convert it to mvc action link along with the css class.

Body:
Code to Convert :

<a href="signup.html" class="signup-button">CREER UN COMPTE</a>

If I look at the above code, you have redirected to the simple html page i.e signup.html by using the anchor tag.

And if you want the same thing in mvc actionlink  , As per my knowledge , the same thing is not possible by using the mvc actionlink because if you look at the below overloads of action link at msdn .

https://msdn.microsoft.com/en-us/library/dd460522.aspx

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    string protocol,
    string hostName,
    string fragment,
    Object routeValues,
    Object htmlAttributes
)

It takes only the actionname and controller name for any redirection to happen.

Alternative solution:

If you changed that signup.html to the signup action by using the controller then you can easily call by using the below code.

@Html.ActionLink("CREER UN COMPTE", "signup", "AnyControllerName", protocol: null, hostName: null, fragment: "MyAnchor", routeValues: null, new {@class="signup-button"})

Correct me if am wrong and hope that above information was helpful.

Thanks

Karthik


问:
Unable to create image using Azure VM
I need to generalize and capture a linux virtual machine.

I deployed the VM using ARM template. In ARM template, I used the following to get VHD stored in storage account

```<code>            "storageProfile": {
                "imageReference": {
                    "publisher": "[variables('imagePublisher')]",
                    "offer": "[variables('imageOffer')]",
                    "sku": "[variables('imageSku')]",
                    "version": "latest"
                },
                "osDisk": {
                    "name": "[parameters('virtualMachineName')]",
                    "createOption": "fromImage",
                    "vhd": {
                        "uri": "[concat(concat(reference(resourceId(variables('resourceGroupName'), 'Microsoft.Storage/storageAccounts', parameters('storageAccountName')), '2015-06-15').primaryEndpoints['blob'], 'vhds/'), parameters('virtualMachineName'), concat(uniqueString(resourceGroup().id), '.vhd'))]"
                    }
                },
                "dataDisks": []
            },
</code>```

Now I am following this document to create and image and VM.

When I execute the following command, I am getting error

```<code>az image create --resource-group myResourceGroup --name myImage --source myVM

The storage account containing blob https://testvmstorage.blob.core.windows.net/vhds/testvmyrg5wfer6xbcg.vhd is or has been encrypted. Copy the blob to an unencrypted storage account before importing.
</code>```

答:
When your storage account is encryption, you will get the error log. You could check it on Azure Portal.

Now, if you want to the VHD to create a image, you need create a non-encryption account and copy the VHD to it. You could use Azcopy to copy VHDs between containers. Just an example below:

```<code>AzCopy /Source:https://shuidisks446.blob.core.windows.net/vhds /Dest:https://shuidiag102.blob.core.windows.net/vhds /SourceKey:sGqtdFHQWQWYyf2tRWGF5jkeAEubTp13AVaeTM25QogxXE+K0Ezq1ulcs18qGVPhCEp6ULdLLbKVa7fMbUvYZg== /DestKey:iCjeS+eegjkSJXHjH2UqCkqXnUPiCGvxaOG0Ad2LoPgUnvBoWl9wQJtC1jc//lOj4CF7khpLQe791P4QeyTY6Q== /Pattern:shui20161222141315.vhd
</code>```

After the VHD transfers to new storage account, you could use the VHD to create a snapshot, then use the snapshot to create image.

Note: You could not create image with VHD directly.

You could use the following commands.

```<code>az snapshot create -g shui2 -n shuisna --source https://shui2.blob.core.windows.net/vhds/shui20170607110945.vhd
az image create -g shui2 -n shuiimage --source shuisna --os-type linux
</code>```

Title: Unable to create image using Azure VM

Body:
I need to generalize and capture a linux virtual machine.

I deployed the VM using ARM template. In ARM template, I used the following to get VHD stored in storage account

            "storageProfile": {
                "imageReference": {
                    "publisher": "[variables('imagePublisher')]",
                    "offer": "[variables('imageOffer')]",
                    "sku": "[variables('imageSku')]",
                    "version": "latest"
                },
                "osDisk": {
                    "name": "[parameters('virtualMachineName')]",
                    "createOption": "fromImage",
                    "vhd": {
                        "uri": "[concat(concat(reference(resourceId(variables('resourceGroupName'), 'Microsoft.Storage/storageAccounts', parameters('storageAccountName')), '2015-06-15').primaryEndpoints['blob'], 'vhds/'), parameters('virtualMachineName'), concat(uniqueString(resourceGroup().id), '.vhd'))]"
                    }
                },
                "dataDisks": []
            },

Now I am following this document to create and image and VM.

When I execute the following command, I am getting error

az image create --resource-group myResourceGroup --name myImage --source myVM

The storage account containing blob https://testvmstorage.blob.core.windows.net/vhds/testvmyrg5wfer6xbcg.vhd is or has been encrypted. Copy the blob to an unencrypted storage account before importing.

Body:
When your storage account is encryption, you will get the error log. You could check it on Azure Portal.

Now, if you want to the VHD to create a image, you need create a non-encryption account and copy the VHD to it. You could use Azcopy to copy VHDs between containers. Just an example below:

AzCopy /Source:https://shuidisks446.blob.core.windows.net/vhds /Dest:https://shuidiag102.blob.core.windows.net/vhds /SourceKey:sGqtdFHQWQWYyf2tRWGF5jkeAEubTp13AVaeTM25QogxXE+K0Ezq1ulcs18qGVPhCEp6ULdLLbKVa7fMbUvYZg== /DestKey:iCjeS+eegjkSJXHjH2UqCkqXnUPiCGvxaOG0Ad2LoPgUnvBoWl9wQJtC1jc//lOj4CF7khpLQe791P4QeyTY6Q== /Pattern:shui20161222141315.vhd

After the VHD transfers to new storage account, you could use the VHD to create a snapshot, then use the snapshot to create image.

Note: You could not create image with VHD directly.

You could use the following commands.

az snapshot create -g shui2 -n shuisna --source https://shui2.blob.core.windows.net/vhds/shui20170607110945.vhd
az image create -g shui2 -n shuiimage --source shuisna --os-type linux


问:
gulp-sass with browsersync inject not working
```<code>// variable
// -----------------------------------------------------------------------------

var gulp        = require('gulp');
var sass         = require('gulp-sass');
var browserSync = require('browser-sync').create();

// task
// -----------------------------------------------------------------------------

gulp.task('styles', function() {
  return gulp.src([
    './src/assets/styles/*.scss'
  ], {
    base: './src/assets/styles/'
  })
  .pipe(sass().on('error', sass.logError))
  .pipe(gulp.dest('./dist/assets/styles/'))
  .pipe(browserSync.stream());
});

gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: './dist/'
    }
  });

  gulp.watch('./dist/*.html').on('change', browserSync.reload);
  gulp.watch('./src/assets/styles/**/*.scss', ['styles']);
  gulp.watch('./dist/assets/scripts/*.js').on('change', browserSync.reload);
});
</code>```

How can make above code working? The scripts and html part working, but scss part not, when scss file change, styles task has start and finish with no error, the html file has body tag, but the browser do not inject the new css file.

答:
Check this example, it may help you with a few tweaks in paths:</p>

```<code>/**
 * This example:
 *  Uses the built-in BrowserSync server for HTML files
 *  Watches & compiles SASS files
 *  Watches & injects CSS files
 */
var browserSync = require('browser-sync');
var reload      = browserSync.reload;
var gulp        = require('gulp');
var sass        = require('gulp-sass');
var filter      = require('gulp-filter');

// Browser-sync task, only cares about compiled CSS
gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: "./"
        }
    });
});

// Sass task, will run when any SCSS files change.
gulp.task('sass', function () {
    return gulp.src('scss/styles.scss')
        .pipe(sass({includePaths: ['scss']})) // compile sass
        .pipe(gulp.dest('css')) // write to css dir
        .pipe(filter('**/*.css')) // filter the stream to ensure only CSS files passed.
        .pipe(reload({stream:true})); // inject into browsers
});

// Default task to be run with `gulp`
gulp.task('default', ['sass', 'browser-sync'], function () {
    gulp.watch("scss/*.scss", ['sass']);
});
</code>```

Body:
// variable
// -----------------------------------------------------------------------------

var gulp        = require('gulp');
var sass         = require('gulp-sass');
var browserSync = require('browser-sync').create();

// task
// -----------------------------------------------------------------------------

gulp.task('styles', function() {
  return gulp.src([
    './src/assets/styles/*.scss'
  ], {
    base: './src/assets/styles/'
  })
  .pipe(sass().on('error', sass.logError))
  .pipe(gulp.dest('./dist/assets/styles/'))
  .pipe(browserSync.stream());
});

gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: './dist/'
    }
  });

  gulp.watch('./dist/*.html').on('change', browserSync.reload);
  gulp.watch('./src/assets/styles/**/*.scss', ['styles']);
  gulp.watch('./dist/assets/scripts/*.js').on('change', browserSync.reload);
});

How can make above code working? The scripts and html part working, but scss part not, when scss file change, styles task has start and finish with no error, the html file has body tag, but the browser do not inject the new css file.

Body:
Check this example, it may help you with a few tweaks in paths:

/**
 * This example:
 *  Uses the built-in BrowserSync server for HTML files
 *  Watches & compiles SASS files
 *  Watches & injects CSS files
 */
var browserSync = require('browser-sync');
var reload      = browserSync.reload;
var gulp        = require('gulp');
var sass        = require('gulp-sass');
var filter      = require('gulp-filter');

// Browser-sync task, only cares about compiled CSS
gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: "./"
        }
    });
});

// Sass task, will run when any SCSS files change.
gulp.task('sass', function () {
    return gulp.src('scss/styles.scss')
        .pipe(sass({includePaths: ['scss']})) // compile sass
        .pipe(gulp.dest('css')) // write to css dir
        .pipe(filter('**/*.css')) // filter the stream to ensure only CSS files passed.
        .pipe(reload({stream:true})); // inject into browsers
});

// Default task to be run with `gulp`
gulp.task('default', ['sass', 'browser-sync'], function () {
    gulp.watch("scss/*.scss", ['sass']);
});


问:
Angular2 - 'router-outlet' is not a known element
I created routes with deep child paths. I added <router-outlet> to the AdminComponent component which I wrapped into NgModule. But after refreshing the page I got this error:

```<code>'router-outlet' is not a known element
</code>```

Maybe it occurred because I forgot import some module to admin.module.ts

Please help. Thanks.

app.routes.ts

export const routes: Routes = [
    {
        path: '',
        component: AppComponent,
        children: [
            {
                path: '',
                component: LoginComponent
            },
            {
                path: 'admin',
                component: AdminComponent
            },
            {
                path: 'user',
                component: UserComponent
            },
            {
                path: 'there',
                component: ThereComponent
            }
        ]
    }
]
```

<p><em>app.module.ts</em></p>

<pre class="lang-js prettyprint-override"><code>@NgModule({
    imports: [
        BrowserModule,
        AppRoutes,
        FormsModule,
        ReactiveFormsModule,
        HttpModule,
        RouterModule,
        TranslateModule.forRoot({
            provide: TranslateLoader,
            useFactory: (http: Http) => {
                return new TranslateStaticLoader(http, './src/assets/i18n', '.json')
            },
            deps: [Http]
        }),
        UserComponentModule,
        AdminComponentModule,
        LoginComponentModule,
        ThereComponentModule,
        DashboardComponentModule
    ],
    declarations: [
        AppComponent
    ],
    providers: [
        FormBuilder
    ],
    bootstrap: [AppComponent]
})
</code>```

admin.component.ts and admin.module.ts

//  admin.component.ts
import {Component} from "@angular/core";

@Component({
    selector: 'admin',
    template: "<router-outlet></router-outlet>",
})

export class AdminComponent {
    constructor() {

    }
}

//  admin.module.ts
const ADMIN_DECLARATION = [
    AdminComponent
];

@NgModule({
    imports: [
        BrowserModule,
        TranslateModule,
        FormsModule,
        ReactiveFormsModule
    ],
    declarations: [
        ADMIN_DECLARATION
    ],
    exports: [
        ADMIN_DECLARATION
    ],
    providers: [
        TranslateService,
        FormBuilder
    ]
})

export class AdminComponentModule {

}
```

答:
you did not export the RouterModule. </p>

<pre class="lang-typescript prettyprint-override"><code>@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
</code>```

Body:
I created routes with deep child paths. I added <router-outlet> to the AdminComponent component which I wrapped into NgModule. But after refreshing the page I got this error:

'router-outlet' is not a known element

Maybe it occurred because I forgot import some module to admin.module.ts

Please help. Thanks.

app.routes.ts

export const routes: Routes = [
    {
        path: '',
        component: AppComponent,
        children: [
            {
                path: '',
                component: LoginComponent
            },
            {
                path: 'admin',
                component: AdminComponent
            },
            {
                path: 'user',
                component: UserComponent
            },
            {
                path: 'there',
                component: ThereComponent
            }
        ]
    }
]

app.module.ts

@NgModule({
    imports: [
        BrowserModule,
        AppRoutes,
        FormsModule,
        ReactiveFormsModule,
        HttpModule,
        RouterModule,
        TranslateModule.forRoot({
            provide: TranslateLoader,
            useFactory: (http: Http) => {
                return new TranslateStaticLoader(http, './src/assets/i18n', '.json')
            },
            deps: [Http]
        }),
        UserComponentModule,
        AdminComponentModule,
        LoginComponentModule,
        ThereComponentModule,
        DashboardComponentModule
    ],
    declarations: [
        AppComponent
    ],
    providers: [
        FormBuilder
    ],
    bootstrap: [AppComponent]
})

admin.component.ts and admin.module.ts

//  admin.component.ts
import {Component} from "@angular/core";

@Component({
    selector: 'admin',
    template: "<router-outlet></router-outlet>",
})

export class AdminComponent {
    constructor() {

    }
}

//  admin.module.ts
const ADMIN_DECLARATION = [
    AdminComponent
];

@NgModule({
    imports: [
        BrowserModule,
        TranslateModule,
        FormsModule,
        ReactiveFormsModule
    ],
    declarations: [
        ADMIN_DECLARATION
    ],
    exports: [
        ADMIN_DECLARATION
    ],
    providers: [
        TranslateService,
        FormBuilder
    ]
})

export class AdminComponentModule {

}

Body:
you did not export the RouterModule.

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})


答:
Well, theoretically, it's easy.

```<code>document.getElementsByClassName("my-css-class-name")[0].style.display = "something";
</code>```

In case you need IE compatibility:

```<code>/*
    Developed by Robert Nyman, http://www.robertnyman.com
    Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag/* "a","div",... */, elm/*parent*/){
    if (document.getElementsByClassName) {
        getElementsByClassName = function (className, tag, elm) {
            elm = elm || document;
            var elements = elm.getElementsByClassName(className),
                nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
                returnElements = [],
                current;
            for(var i=0, il=elements.length; i<il; i+=1){
                current = elements[i];
                if(!nodeName || nodeName.test(current.nodeName)) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    else if (document.evaluate) {
        getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
                classesToCheck = "",
                xhtmlNamespace = "http://www.w3.org/1999/xhtml",
                namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
                returnElements = [],
                elements,
                node;
            for(var j=0, jl=classes.length; j<jl; j+=1){
                classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
            }
            try {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
            }
            catch (e) {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
            }
            while ((node = elements.iterateNext())) {
                returnElements.push(node);
            }
            return returnElements;
        };
    }
    else {
        getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
                classesToCheck = [],
                elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
                current,
                returnElements = [],
                match;
            for(var k=0, kl=classes.length; k<kl; k+=1){
                classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
            }
            for(var l=0, ll=elements.length; l<ll; l+=1){
                current = elements[l];
                match = false;
                for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
                    match = classesToCheck[m].test(current.className);
                    if (!match) {
                        break;
                    }
                }
                if (match) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    return getElementsByClassName(className, tag, elm);
};

getElementsByClassName("my-css-class-name")[0].style.display = "something";
</code>```

Title: javascript modify css class property while knowing only the class' name

Body:
Well, theoretically, it's easy.

document.getElementsByClassName("my-css-class-name")[0].style.display = "something";

In case you need IE compatibility:

/*
    Developed by Robert Nyman, http://www.robertnyman.com
    Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag/* "a","div",... */, elm/*parent*/){
    if (document.getElementsByClassName) {
        getElementsByClassName = function (className, tag, elm) {
            elm = elm || document;
            var elements = elm.getElementsByClassName(className),
                nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
                returnElements = [],
                current;
            for(var i=0, il=elements.length; i<il; i+=1){
                current = elements[i];
                if(!nodeName || nodeName.test(current.nodeName)) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    else if (document.evaluate) {
        getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
                classesToCheck = "",
                xhtmlNamespace = "http://www.w3.org/1999/xhtml",
                namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
                returnElements = [],
                elements,
                node;
            for(var j=0, jl=classes.length; j<jl; j+=1){
                classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
            }
            try {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
            }
            catch (e) {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
            }
            while ((node = elements.iterateNext())) {
                returnElements.push(node);
            }
            return returnElements;
        };
    }
    else {
        getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
                classesToCheck = [],
                elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
                current,
                returnElements = [],
                match;
            for(var k=0, kl=classes.length; k<kl; k+=1){
                classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
            }
            for(var l=0, ll=elements.length; l<ll; l+=1){
                current = elements[l];
                match = false;
                for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
                    match = classesToCheck[m].test(current.className);
                    if (!match) {
                        break;
                    }
                }
                if (match) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    return getElementsByClassName(className, tag, elm);
};

getElementsByClassName("my-css-class-name")[0].style.display = "something";


问:
Return an array of exp values with an ease parameter
I need a method to get an interval of integer distributed between a range of two integers (min, max) with an ease value (-100;100) to define the "acceleration" of this values from the left to the right.

How to use

```<code>foo(min, max, samples, ease);
</code>```

min is the start int (included)

max is the end int (included)

samples the number of values to returned

ease the ease from -100 to 100

In return I need an array of integer.

What it's expected

```<code>foo(5, 20, 4, 0); // [5, 10, 15, 20]
foo(5, 20, 4, 1.3); // [5, 7, 12, 20]
foo(5, 20, 4, 100); // [5, 16, 18, 20]
foo(5, 20, 4, -100); // [5, 7, 9, 20]
</code>```

From the top to the bottom (with fanciful returned values for the last three result) :

4 values from 5 to 20 with a linear progression.

4 values from 5 to 20 with a small progression.

4 values with a quick progression.

4 values with a very slow progression.

What I tried

I tried to create a javascript method with a sin curve but the return doesn't contain the start and last values and my ease value is probably (certainly, mandatory) incorrect :

```<code>function foo(min, max, samples, ease) {
  const ret = [];
  for (var i = min/max; i < 1; i += 1/samples) {
    ret.push(Math.round((1 - Math.sin((1 - i) * Math.PI / ease)) * max));
  }
  return ret;
}
</code>```

What is the best way to create a method like this?

答:
Instead of a sinewave, use exponential curves. Using powers of 3 you even get approximately the results you described (at the endpoints [-100, 100])

//simple linear interpolation
var interpolate = (a,b,t) => a*(1-t) + b*t;

function foo(min, max, samples, ease=0){
 var pow = interpolate(1, ease<0? 3: 1/3, Math.abs(+ease || 0)/100);
 var arr = Array(+samples);
 for(var i=0; i<arr.length; ++i)
  arr[i] = interpolate(min, max, Math.pow(i / (samples-1), pow));
 return arr;
}

function round(v){ return Math.round(v * 1E5)/1E5 }
foo(-100, 100, 11).forEach(ease => console.log("ease: %s values: [ %s ]", ease, foo(5, 20, 4, ease).map(round).join(", ")))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{top:0;max-height:100%!important}</code>```

Body:
I need a method to get an interval of integer distributed between a range of two integers (min, max) with an ease value (-100;100) to define the "acceleration" of this values from the left to the right.

How to use

foo(min, max, samples, ease);

min is the start int (included)

max is the end int (included)

samples the number of values to returned

ease the ease from -100 to 100

In return I need an array of integer.

What it's expected

foo(5, 20, 4, 0); // [5, 10, 15, 20]
foo(5, 20, 4, 1.3); // [5, 7, 12, 20]
foo(5, 20, 4, 100); // [5, 16, 18, 20]
foo(5, 20, 4, -100); // [5, 7, 9, 20]

From the top to the bottom (with fanciful returned values for the last three result) :

4 values from 5 to 20 with a linear progression.

4 values from 5 to 20 with a small progression.

4 values with a quick progression.

4 values with a very slow progression.

What I tried

I tried to create a javascript method with a sin curve but the return doesn't contain the start and last values and my ease value is probably (certainly, mandatory) incorrect :

function foo(min, max, samples, ease) {
  const ret = [];
  for (var i = min/max; i < 1; i += 1/samples) {
    ret.push(Math.round((1 - Math.sin((1 - i) * Math.PI / ease)) * max));
  }
  return ret;
}

What is the best way to create a method like this?

Body:
Instead of a sinewave, use exponential curves. Using powers of 3 you even get approximately the results you described (at the endpoints [-100, 100])

//simple linear interpolation
var interpolate = (a,b,t) => a*(1-t) + b*t;

function foo(min, max, samples, ease=0){
 var pow = interpolate(1, ease<0? 3: 1/3, Math.abs(+ease || 0)/100);
 var arr = Array(+samples);
 for(var i=0; i<arr.length; ++i)
  arr[i] = interpolate(min, max, Math.pow(i / (samples-1), pow));
 return arr;
}

function round(v){ return Math.round(v * 1E5)/1E5 }
foo(-100, 100, 11).forEach(ease => console.log("ease: %s values: [ %s ]", ease, foo(5, 20, 4, ease).map(round).join(", ")))

.as-console-wrapper{top:0;max-height:100%!important}


问:
Change navigation class/transition on user scroll
I have a navigation bar that I want to function in the following manner:

navigation positioned absolute so it can scroll with the rest of the content.

when scrolled 300px from the top it becomes fixed and transitions down from the top off-screen

when the scrolled back up it transitions up off-screen and scrolls back down as part of the content

code (in functions.php)

```<code>$(document).ready(function() {

  $(window).scroll(function () {
    var bannerHeight = $('#s-nav').height();
    console.log(bannerHeight);
  if ($(window).scrollTop() > bannerHeight) {
    $('#s-nav').addClass('stick');
  }
  if ($(window).scrollTop() < bannerHeight) {
    $('#s-nav').removeClass('stick');
  }
  });
});
</code>```

css

```<code>#s-nav {
  width: 100%;
  top: 0; right: 0; left: 0;
  position: absolute;
}

#s-nav.stick {
  position: fixed;
  top: 0; left: 0; right: 0;
  z-index: 999;
}
</code>```

html

```<code><nav id="s-nav"> navigation links </div>
</code>```

答:
You cannot have a position: absolute element that scrolls, as it needs to be relative to the content in order to be able to scroll.

Simply make sure that you use position: relative, and use a value of 300 when checking your comparisons in scrollTop():

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(window).scrollTop() > 300) {
      $('#s-nav').addClass('stick');
    }
    if ($(window).scrollTop() < 300) {
      $('#s-nav').removeClass('stick');
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#s-nav {
  position: relative;
  background: cyan; /* For clarity */
}

#s-nav.stick {
  position: fixed;
  top: 0; left: 0; right: 0;
  z-index: 999;
}</code>```

 Sticky

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec tellus justo. Phasellus sollicitudin nisl pellentesque tincidunt consequat. Cras pellentesque quis turpis ac ultricies. Curabitur tincidunt sapien eget elit faucibus vestibulum. Nulla feugiat tempor magna, vitae aliquet sapien pretium vel. Nullam dapibus sagittis diam, at mattis ipsum congue sit amet. Suspendisse pulvinar nulla in dui hendrerit, at porta turpis consectetur. Quisque fermentum augue a libero posuere, at commodo odio porttitor. Mauris a dui at augue sollicitudin mattis. Vestibulum luctus interdum nisi, ac aliquet enim tristique sed. Etiam blandit massa risus, vel semper ligula ultricies non. Vivamus suscipit augue vel congue ultricies. Donec ac ipsum lacinia, commodo enim vitae, dignissim sem. Proin scelerisque feugiat sem, eu elementum orci viverra nec. Proin tincidunt eleifend lorem scelerisque pulvinar.
Morbi varius lacinia lacinia. Vivamus facilisis ornare justo, in porttitor ipsum pulvinar id. Sed rutrum, ante et consequat scelerisque, nulla sem cursus lacus, non convallis massa justo in velit. Ut porttitor fermentum augue, non rhoncus sem semper eu. Curabitur id semper mauris. Pellentesque sit amet diam vel mauris blandit euismod sit amet ac magna. In sodales iaculis magna nec viverra.
Fusce congue urna sed nisi efficitur aliquet. Duis augue metus, aliquam lobortis ultrices laoreet, pulvinar in arcu. Suspendisse feugiat ex velit, ut elementum nisi luctus id. Cras condimentum sapien nec ante interdum, at tempus lorem gravida. Curabitur porttitor eros massa, vel varius turpis accumsan a. Sed porttitor convallis odio, vitae dapibus eros venenatis ut. Donec scelerisque metus molestie erat bibendum condimentum.
Nullam porttitor semper aliquam. Mauris volutpat augue ac diam tincidunt, at ullamcorper sapien laoreet. Nunc porta bibendum lacus imperdiet luctus. Proin ac massa commodo, egestas dui vehicula, bibendum arcu. Vivamus sed pulvinar nisi. Duis orci lectus, pulvinar sed consequat eget, vulputate at turpis. Praesent laoreet ligula nunc, id sollicitudin nisl volutpat sit amet. Vestibulum quis porttitor eros. Praesent in turpis justo. Vivamus pharetra porttitor neque quis maximus. Vestibulum ut euismod nisi. Aenean sit amet accumsan magna. Vestibulum dictum, augue quis commodo dapibus, nibh elit auctor arcu, id tempus libero diam non justo.
Maecenas urna leo, vehicula in turpis non, maximus mattis enim. Fusce sit amet est rutrum, posuere velit in, iaculis nunc. Fusce malesuada at felis a tincidunt. Nam maximus dictum vestibulum. Sed scelerisque eget nibh eget suscipit. Nulla lacus diam, tristique et justo quis, venenatis suscipit arcu. Etiam vestibulum at libero quis eleifend.

```

Hope this helps! :)

Body:
I have a navigation bar that I want to function in the following manner:

navigation positioned absolute so it can scroll with the rest of the content.

when scrolled 300px from the top it becomes fixed and transitions down from the top off-screen

when the scrolled back up it transitions up off-screen and scrolls back down as part of the content

code (in functions.php)

$(document).ready(function() {

  $(window).scroll(function () {
    var bannerHeight = $('#s-nav').height();
    console.log(bannerHeight);
  if ($(window).scrollTop() > bannerHeight) {
    $('#s-nav').addClass('stick');
  }
  if ($(window).scrollTop() < bannerHeight) {
    $('#s-nav').removeClass('stick');
  }
  });
});

css

#s-nav {
  width: 100%;
  top: 0; right: 0; left: 0;
  position: absolute;
}

#s-nav.stick {
  position: fixed;
  top: 0; left: 0; right: 0;
  z-index: 999;
}

html

 navigation links

Body:
You cannot have a position: absolute element that scrolls, as it needs to be relative to the content in order to be able to scroll.

Simply make sure that you use position: relative, and use a value of 300 when checking your comparisons in scrollTop():

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(window).scrollTop() > 300) {
      $('#s-nav').addClass('stick');
    }
    if ($(window).scrollTop() < 300) {
      $('#s-nav').removeClass('stick');
    }
  });
});

#s-nav {
  position: relative;
  background: cyan; /* For clarity */
}

#s-nav.stick {
  position: fixed;
  top: 0; left: 0; right: 0;
  z-index: 999;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="s-nav">
 Sticky
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec tellus justo. Phasellus sollicitudin nisl pellentesque tincidunt consequat. Cras pellentesque quis turpis ac ultricies. Curabitur tincidunt sapien eget elit faucibus vestibulum. Nulla feugiat tempor magna, vitae aliquet sapien pretium vel. Nullam dapibus sagittis diam, at mattis ipsum congue sit amet. Suspendisse pulvinar nulla in dui hendrerit, at porta turpis consectetur. Quisque fermentum augue a libero posuere, at commodo odio porttitor. Mauris a dui at augue sollicitudin mattis. Vestibulum luctus interdum nisi, ac aliquet enim tristique sed. Etiam blandit massa risus, vel semper ligula ultricies non. Vivamus suscipit augue vel congue ultricies. Donec ac ipsum lacinia, commodo enim vitae, dignissim sem. Proin scelerisque feugiat sem, eu elementum orci viverra nec. Proin tincidunt eleifend lorem scelerisque pulvinar.
Morbi varius lacinia lacinia. Vivamus facilisis ornare justo, in porttitor ipsum pulvinar id. Sed rutrum, ante et consequat scelerisque, nulla sem cursus lacus, non convallis massa justo in velit. Ut porttitor fermentum augue, non rhoncus sem semper eu. Curabitur id semper mauris. Pellentesque sit amet diam vel mauris blandit euismod sit amet ac magna. In sodales iaculis magna nec viverra.
Fusce congue urna sed nisi efficitur aliquet. Duis augue metus, aliquam lobortis ultrices laoreet, pulvinar in arcu. Suspendisse feugiat ex velit, ut elementum nisi luctus id. Cras condimentum sapien nec ante interdum, at tempus lorem gravida. Curabitur porttitor eros massa, vel varius turpis accumsan a. Sed porttitor convallis odio, vitae dapibus eros venenatis ut. Donec scelerisque metus molestie erat bibendum condimentum.
Nullam porttitor semper aliquam. Mauris volutpat augue ac diam tincidunt, at ullamcorper sapien laoreet. Nunc porta bibendum lacus imperdiet luctus. Proin ac massa commodo, egestas dui vehicula, bibendum arcu. Vivamus sed pulvinar nisi. Duis orci lectus, pulvinar sed consequat eget, vulputate at turpis. Praesent laoreet ligula nunc, id sollicitudin nisl volutpat sit amet. Vestibulum quis porttitor eros. Praesent in turpis justo. Vivamus pharetra porttitor neque quis maximus. Vestibulum ut euismod nisi. Aenean sit amet accumsan magna. Vestibulum dictum, augue quis commodo dapibus, nibh elit auctor arcu, id tempus libero diam non justo.
Maecenas urna leo, vehicula in turpis non, maximus mattis enim. Fusce sit amet est rutrum, posuere velit in, iaculis nunc. Fusce malesuada at felis a tincidunt. Nam maximus dictum vestibulum. Sed scelerisque eget nibh eget suscipit. Nulla lacus diam, tristique et justo quis, venenatis suscipit arcu. Etiam vestibulum at libero quis eleifend.
</p>

Hope this helps! :)


问:
What's an efficient way to perform operations with NA values in R?
I would like to perform operation on a data frame which ignores lines with NA values (However, I don't want to remove the rows with NA values, I still want them in the data frame). I have actually already managed to do this, but I am after a more computationally efficient method since mine is very, very slow.

Let's say for instance we have a data frame as follows:

```<code>Number    |   Object
  10      |   Car
  11      |   Book
  12      |   Pen
  13      |   Door
  NA      |   Computer
  14      |   Cup
  15      |   Book
</code>```

I wish to perform an operation on this data frame where I would like to access the previous/next Object in the data frame but only on the condition that the Number column does not have an NA value for that index. For example, let's say I am at index 4 in the Number column (which means that the 'Number' is 13 and the Object is Door), and I want to access the next object such that there is no NA value in the Number column. This means that since index 5 has NA in the Number column, I would instead go to index 6 since it has 14 in the Number column and therefore I will have Cup as the object instead of computer.

Now, as mentioned above, I've actually already implemented one such method to perform this task through basically using a combination of functions such as which() and min() and max() etc. but I am after a method/function which is much more computationally efficient since I have a lot of data to work with (the method I am using is very slow and inefficient since it needs to check through a large number of values). Is there a more computationally efficient way to accomplish this task? Thanks in advance.

答:
I'd advise you to look into the na function.

Here's a good source to start with:
HOW DOES R HANDLE MISSING VALUES?

Have a look at the complexity of below code:

```<code>a<-data.frame(c(15,25,35,NA,55),c("a","b","c","d","e"))
colnames(a)<-c("Number","Object")
a
i = 1
while(i<length(a$Number)-1){
  if (!is.na(a$Number[i])){
     if (!is.na(a$Number[i+1])){
        print(a$Object[i+1])
        i = i + 1
        }
     else{
        print(a$Object[i+2])
        i = i + 2
        }
  }
}
</code>```

Of course, you could deploy one-liner functions.

Body:
I would like to perform operation on a data frame which ignores lines with NA values (However, I don't want to remove the rows with NA values, I still want them in the data frame). I have actually already managed to do this, but I am after a more computationally efficient method since mine is very, very slow.

Let's say for instance we have a data frame as follows:

Number    |   Object
  10      |   Car
  11      |   Book
  12      |   Pen
  13      |   Door
  NA      |   Computer
  14      |   Cup
  15      |   Book

I wish to perform an operation on this data frame where I would like to access the previous/next Object in the data frame but only on the condition that the Number column does not have an NA value for that index. For example, let's say I am at index 4 in the Number column (which means that the 'Number' is 13 and the Object is Door), and I want to access the next object such that there is no NA value in the Number column. This means that since index 5 has NA in the Number column, I would instead go to index 6 since it has 14 in the Number column and therefore I will have Cup as the object instead of computer.

Now, as mentioned above, I've actually already implemented one such method to perform this task through basically using a combination of functions such as which() and min() and max() etc. but I am after a method/function which is much more computationally efficient since I have a lot of data to work with (the method I am using is very slow and inefficient since it needs to check through a large number of values). Is there a more computationally efficient way to accomplish this task? Thanks in advance.

Body:
I'd advise you to look into the na function.

Here's a good source to start with:
HOW DOES R HANDLE MISSING VALUES?

Have a look at the complexity of below code:

a<-data.frame(c(15,25,35,NA,55),c("a","b","c","d","e"))
colnames(a)<-c("Number","Object")
a
i = 1
while(i<length(a$Number)-1){
  if (!is.na(a$Number[i])){
     if (!is.na(a$Number[i+1])){
        print(a$Object[i+1])
        i = i + 1
        }
     else{
        print(a$Object[i+2])
        i = i + 2
        }
  }
}

Of course, you could deploy one-liner functions.