text:
Q: Error executing SQL statement for report when print jasper file i modify an old project and i cannot identify what is wrong with this code.using below .jrxml it create .jasper file. when i print the jasper file (using this code
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,parameters,getConnection()); )  it show below error. please help me to resolve this.

this is top part of the Job.jrxml file
?xml version="1.0" encoding="UTF-8"  ?>

<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport
         name="Task"
         columnCount="1"
         printOrder="Vertical"
         orientation="Landscape"
         pageWidth="1275"
         pageHeight="630"
         columnWidth="1172"
         columnSpacing="0"
         leftMargin="23"
         rightMargin="80"
         topMargin="0"
         bottomMargin="0"
         whenNoDataType="AllSectionsNoDetail"
         isTitleNewPage="false"
         isSummaryNewPage="false">
    <property name="ireport.scriptlethandling" value="0" />
    <property name="ireport.encoding" value="UTF-8" />
    <import value="java.util.*" />
    <import value="net.sf.jasperreports.engine.*" />
    <import value="net.sf.jasperreports.engine.data.*" />
    <reportFont name="Arial_Normal" isDefault="true" fontName="Arial" size="12" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica" pdfEncoding="Cp1252" isPdfEmbedded="false"/>
    <reportFont name="Arial_Bold" isDefault="false" fontName="Arial" size="12" isBold="true" isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica-Bold" pdfEncoding="Cp1252" isPdfEmbedded="false"/>
    <reportFont name="Arial_Italic" isDefault="false" fontName="Arial" size="12" isBold="false" isItalic="true" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica-Oblique" pdfEncoding="Cp1252" isPdfEmbedded="false"/>
    <reportFont name="Courier" isDefault="false" fontName="Courier New" size="12" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica-Oblique" pdfEncoding="Cp1252" isPdfEmbedded="false"/>

    <parameter name="filter" isForPrompting="true" class="java.lang.String"/>
    <parameter name="dates" isForPrompting="false" class="java.lang.String"/>
    <parameter name="workFlow" isForPrompting="false" class="java.lang.String"/>
    <parameter name="workFlow1" isForPrompting="false" class="java.lang.String">
            <defaultValueExpression ><![CDATA["test"]]></defaultValueExpression>
    </parameter>
    <parameter name="userName" isForPrompting="false" class="java.lang.String"/>
    <queryString><![CDATA[SELECT A.initiatedTime, A.dueTime, A.completedTime, A.taskStatus,B.jobName,
                    C.taskName,  D.firstName||' '||D.lastName AlocatedUser , E.workflowName ,B.workflowdefinition
                    FROM T_JOB_TRANSACTION A , T_JOB_DEFINITION B ,T_TASK_DEFINITION C ,T_USER D ,T_WORKFLOW_DEFINITION E
                    WHERE A.jobDefinition=B.JobID
                    AND C.taskId=A.taskDefinition
                    AND D.userId= A.firstUser
                    AND B.workflowDefinition =E.workflowId
                    AND B.isSaved=0
                    AND c.isUsertask=1 $P!{filter} $P!{workFlow} $P!{workFlow1}
                    GROUP BY B.workflowDefinition, C.taskName, B.jobName, D.firstName||' '||D.lastName,
                    A.initiatedTime, A.dueTime, A.completedTime, A.taskStatus ,E.workflowName
                    UNION
                    SELECT A.initiatedTime, A.dueTime, A.completedTime, A.taskStatus, B.jobName,
                    C.taskName,  D.firstName||' '||D.lastName AlocatedUser , E.workflowName ,B.workflowdefinition
                    FROM T_JOB_TRANSACTION A , T_JOB_DEFINITION B ,T_TASK_DEFINITION C ,T_USER D ,T_WORKFLOW_DEFINITION E
                    WHERE A.jobDefinition=B.JobID
                    AND C.taskId=A.taskDefinition
                    AND D.userId= A.firstUser
                    AND B.workflowDefinition =E.workflowId
                    AND B.isSaved=0
                    AND c.isUsertask=1 $P!{userName}
                    AND B.isInitiated=1 AND B.isCancelled=0
                    AND E.workflowId IN (SELECT A.workflowID
                                         FROM T_SUB_WORKFLOW A, T_TASK_DEFINITION B
                                         WHERE A.TASK_ID = B.taskID
                                         AND B.isSubWfInvoke = 1 $P!{workFlow} $P!{workFlow1} )
                    GROUP BY B.workflowDefinition, C.taskName, B.jobName, D.firstName||' '||D.lastName,
                    A.initiatedTime, A.dueTime, A.completedTime, A.taskStatus ,E.workflowNameorder by completedTime]]></queryString>

    <field name="initiatedTime" class="java.sql.Timestamp"/>
    <field name="dueTime" class="java.sql.Timestamp"/>
    <field name="completedTime" class="java.sql.Timestamp"/>
    <field name="taskStatus" class="java.lang.String"/>
    <field name="jobName" class="java.lang.String"/>
    <field name="taskName" class="java.lang.String"/>
    <field name="AlocatedUser" class="java.lang.String"/>
    <field name="workflowName" class="java.lang.String"/>
    <field name="workflowdefinition" class="java.math.BigDecimal"/>

    <variable name="delay_time" class="java.lang.String" resetType="Report" calculation="Nothing">
        <variableExpression><![CDATA[String.valueOf((($F{completedTime}.getTime() - $F{dueTime}.getTime())>0) ? "True":"False")]]></variableExpression>
    </variable>
        <background>
            <band height="0"  isSplitAllowed="true" >
            </band>
        </background>
        <title>
            <band height="99"  isSplitAllowed="true" >
                <staticText>
                    <reportElement
                        x="5"
                        y="12"
                        width="958"
                        height="27"
                        key="staticText-2"/>
                    <box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    <textElement textAlignment="Center" verticalAlignment="Middle">

                    </textElement>
                <text><![CDATA[NSB]]></text>
                </staticText>
                <staticText>
                    <reportElement
                        x="152"
                        y="51"
                        width="673"
                        height="21"
                        key="staticText-3"/>
                    <box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    <textElement textAlignment="Center" verticalAlignment="Middle">

                    </textElement>
                <text><![CDATA[Task Details Reports]]></text>
                </staticText>
                <textField isStretchWithOverflow="false" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None"  hyperlinkTarget="Self" >
                    <reportElement
                        x="6"
                        y="73"
                        width="957"
                        height="18"
                        key="textField"/>
                    <box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    <textElement textAlignment="Center" verticalAlignment="Middle">

                    </textElement>
                <textFieldExpression   class="java.lang.String"><![CDATA[$P{dates}]]></textFieldExpression>
                </textField>
            </band>
        </title>
        <pageHeader>

this is the error when print report
 net.sf.jasperreports.engine.JRException: Error executing SQL statement for report : Job
10:27:49,838 ERROR TaskReportManager:181 - net.sf.jasperreports.engine.JRException: Error executing SQL statement for report : Job
java.sql.SQLException: ORA-00933: SQL command not properly ended

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:305)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:272)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:623)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:181)
    at oracle.jdbc.driver.T4CPreparedStatement.execute_for_describe(T4CPreparedStatement.java:420)
    at oracle.jdbc.driver.OracleStatement.execute_maybe_describe(OracleStatement.java:896)
    at oracle.jdbc.driver.T4CPreparedStatement.execute_maybe_describe(T4CPreparedStatement.java:452)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:986)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:2888)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:2929)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:478)
    at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:77)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:248)
    at com.affno.form.report.TaskReportManager.genReport(TaskReportManager.java:160)
    at com.affno.form.web.report.action.TaskReportAction.execute(TaskReportAction.java:412)
    at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at com.affno.common.filter.SessionCheckingFilter.doFilter(SessionCheckingFilter.java:140)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

NESTED BY :
java.sql.SQLException: ORA-00933: SQL command not properly ended

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:305)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:272)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:623)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:181)
    at oracle.jdbc.driver.T4CPreparedStatement.execute_for_describe(T4CPreparedStatement.java:420)
    at oracle.jdbc.driver.OracleStatement.execute_maybe_describe(OracleStatement.java:896)
    at oracle.jdbc.driver.T4CPreparedStatement.execute_maybe_describe(T4CPreparedStatement.java:452)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:986)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:2888)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:2929)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:478)
    at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:77)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:248)
    at com.affno.form.report.TaskReportManager.genReport(TaskReportManager.java:160)
    at com.affno.form.web.report.action.TaskReportAction.execute(TaskReportAction.java:412)
    at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at com.affno.common.filter.SessionCheckingFilter.doFilter(SessionCheckingFilter.java:140)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

NESTED BY :
net.sf.jasperreports.engine.JRException: Error executing SQL statement for report : Job
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:487)
    at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:77)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:248)
    at com.affno.form.report.TaskReportManager.genReport(TaskReportManager.java:160)
    at com.affno.form.web.report.action.TaskReportAction.execute(TaskReportAction.java:412)
    at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at com.affno.common.filter.SessionCheckingFilter.doFilter(SessionCheckingFilter.java:140)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: ORA-00933: SQL command not properly ended

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:305)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:272)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:623)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:181)
    at oracle.jdbc.driver.T4CPreparedStatement.execute_for_describe(T4CPreparedStatement.java:420)
    at oracle.jdbc.driver.OracleStatement.execute_maybe_describe(OracleStatement.java:896)
    at oracle.jdbc.driver.T4CPreparedStatement.execute_maybe_describe(T4CPreparedStatement.java:452)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:986)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:2888)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:2929)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:478)
    ... 33 more

A: As @Maheswaran Ravisankar commented, you have an error in your sql: ORA-00933: SQL command not properly ended
The easiest way for you to debug this error is to enable the logger for the JRJdbcQueryExecuter class, the property in the log.xml is:
<logger name="net.sf.jasperreports.engine.query.JRJdbcQueryExecuter">
    <level value="debug" />
</logger>

With the logger enable you will see the actual query that is executed and you can debug in a Oracle IDE (or post query on SO, if you can't find the error).
For more information about how to configure the log see Jakarta Commons Logging.


text:
Q: Is there anything better than NFS for sharing directories between linux guests on VMWare? What are relevant the trade offs for file sharing options between a group of virtualised linux machines running on the same VMWare box?
E.g. high throughput, low latency etc.
I have mainly used NFS. VMWare used hgfs by default. How do they compare?
Are there any other options worth considering (e.g. sshfs).
Background
We have an application that on physical machines distributes work to slaves via a NFS mounted directory shared on the master.
This configuration is easy to replicate on VMWare. And seems to give adequate performance. However, I was wondering if there is a better way of sharing the directory between linux guests running under VMWare?
I gather shared folders on VMWare use hgfs. Would this be better? Is this the best option?
By better here. I mean likely to give the best performance on the current hardware, which is a single VMWare host.
If so how do I enable it? Despite having installed VMWare tools there doesn't seem to be an option to enable sharing. In VM settings/ properties / options - VMWare tools is listed as shutdown. The entry for shared folders shown on various sites I've googled doesn't exist.

A: Go with NFS! It will be more portable, if you drop Vmware or scale to several physical servers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HighcharteR: plotband and plotline not working I am trying to chart a daily value series in highcharteR marking a vertical line (plotline)  and a period of dates (plotband) in the chart.
I researched several SO question and reach this script, but I found the following issues:
1) plotband not ploted
2) ploline not ploted
3) xaxis should be dates are converted in a way that I not understand.
My reproducible code is:
library(highcharter)

t <- seq(from=as.Date('2017-01-01'), to=as.Date('2018-06-30'), by='days')
d <- runif(n = 546, min = 1, max = 10)
df <- data.frame(t,d)

highchart(type = 'stock')%>%
  hc_add_series(name = "Value", type='line', color = "blue",data = df$d) %>%
  hc_xAxis(categories = df$t,
           type = 'date',
           plotLines = list(
           list(
               label = list(text = "This is a plotLine"),
           color = "#FF0000",
           width = 5,
           value = datetime_to_timestamp(as.Date('2017-01-10', tz = 'UTC'))
         )
       ),
       plotBands = list(
                      list(
                         label = list(text = "This is a plotBand"),
                         color = "rgba(100, 0, 0, 0.1)",
                         from = datetime_to_timestamp(as.Date('2017-02-01', tz = 'UTC')),
                         to = datetime_to_timestamp(as.Date('2017-02-10', tz = 'UTC'))
         )
       )
)

Obtained output is :

Any help/advice would be appreciated!

A: You can try to use XTS package to accomplish this:
library(highcharter)
library(xts)
t <- seq(from = as.Date("2017-01-01"), to = as.Date("2018-06-30"), by = "days")
d <- runif(n = 546, min = 1, max = 10)
df <- data.frame(d)
df <- xts(df, order.by = t)

highchart(type = "stock") %>%
  hc_add_series(name = "Value", type = "line", color = "blue", data = df$d) %>%
  hc_xAxis(
    categories = df$t,
    type = "date",
    plotLines = list(
      list(
        label = list(text = "This is a plotLine"),
        color = "#FF0000",
        width = 5,
        value = datetime_to_timestamp(as.Date("2017-01-10", tz = "UTC"))
      )
    ),
    plotBands = list(
      list(
        label = list(text = "This is a plotBand"),
        color = "rgba(100, 0, 0, 0.1)",
        from = datetime_to_timestamp(as.Date("2017-02-01", tz = "UTC")),
        to = datetime_to_timestamp(as.Date("2017-02-10", tz = "UTC"))
      )
    )
  )


text:
Q: SQL Server Extend dynamic SQL query with where part fetched from Stored Procedure I have a stored procedure that creates a dynamic SQL Query. I use sp_executesql, to have it SQL injection safe.
I have a second stored procedure that generates a where logic.
For example if I run the second procedure EXECUTE dbo.getWhereLogic @FilterID, @parOutput = @WhereLogic OUTPUT it will return as output (1 = 1)
I want to extend my first stored procedure with this where logic.
Let's assume that @SQLQuery = "Select * FROM Blabla Where 1 = 1" and @WhereLogic = (1=1)
If I do it like this:
SET @SQLQuery = @SQLQuery + ' AND ' + @WhereLogic
It will work, but it is not SQL injection safe.
If I do it like this:
SET @SQLQuery = @SQLQuery + ' AND @WhereLogic'
I get an error that there is a non-boolean type defined. There is a comparison missing. I've tried a couple of possibilities.
I think running the second procedure with sp_executesql will have no effect. That procedure returns the WhereLogic as varchar without problems, even if I simulate an SQL injection attack.
The two procedures are too long and complex to post it here. The main problem is also without code example clear.
To put the second procedure in the first and have a logical where query would be a possibility, but then I have to re write the second stored procedure and it was a lot of work :-( This should be the last option.
If someone has faced this problem already, I would appreciate an answer.
Links to other posts would be helpfull too.
Thanks in advance!
EDIT:
I try to create later a dbfiddle example.

A: Typical things you can make SQL injection safe:

*

*Values
DECLARE @UserSuppliedValue varchar(32) = 'foo';

DECLARE @sql nvarchar(max) = N'SELECT ... FROM dbo.bar
  WHERE value = @value;';
EXEC sys.sp_executesql @sql, N'@value', @UserSuppliedValue;

*Entities, like table/column names
DECLARE @UserSuppliedTable  = N'dbo.bar',
        @UserSuppliedColumn = N'foo';

IF EXISTS -- make sure table exists
(
  SELECT 1 FROM sys.tables
    WHERE [object_id] = OBJECT_ID(@UserSuppliedTable)
)
AND EXISTS -- or make sure both exist
(
  SELECT 1 FROM sys.columns
    WHERE [object_id] = OBJECT_ID(@UserSuppliedTable)
      AND name = @UserSuppliedColumn
)
BEGIN
  DECLARE @sql nvarchar(max) = N'SELECT '
    + QUOTENAME(@UserSuppliedColumn) + N' FROM '
    + @UserSuppliedTable + N';';
  EXEC sys.sp_executesql @sql;
END

I listed both there for illustration but you would only need one or the other in most scenarios.
If you're trying to pass an entire WHERE clause to a dynamic SQL statement, there's little you can do to make that injection safe, except maybe try to execute it with PARSEONLY to make sure it's not garbage. That doesn't help prevent valid SQL injection commands but it does at least help prevent utter garbage.
DECLARE @where nvarchar(max) = N' WHERE junk;'

DECLARE @sql  nvarchar(max) = N'SELECT * FROM sys.objects ' + @where;
DECLARE @test nvarchar(max) = N'SET PARSEONLY ON;' + @sql;

DECLARE @hr int;
BEGIN TRY
  EXEC @hr = sys.sp_executesql @test;
  EXEC sys.sp_executesql @sql;
END TRY
BEGIN CATCH
  PRINT N'Statement was garbage.';
END CATCH;

If @where were the following...
DECLARE @where nvarchar(max) = N' WHERE 1=1; DROP TABLE dbo.bobby;';

...then this parsing trick doesn't work (since parsing just validates syntax, not object existence or permissions).
So you need to put proper logic into the stored procedure that produces @where and make sure there are appropriate controls, permissions, and auditing around that stored procedure, as well as reducing the permissions of the user/group executing the final @sql - this should not be sa, for example.
I've written a little about this topic:

*

*Protecting Yourself from SQL Injection in SQL Server - Part 1

*Protecting Yourself from SQL Injection in SQL Server - Part 2

A: Given the constraints, I think the only solution is to use SQL Security to protect against SQL injection attacks.  You only need to prevent SQL injection from untrusted users.
So long as the procedures that accepts the WHERE clause can't be called by regular users, and you properly handle user-supplied strings, it should be safe.


text:
Q: Настройка программно RelativeLayout У меня есть CardView
 <androidx.cardview.widget.CardView
        android:id="@+id/cardview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="10dp"
        android:layout_toRightOf="@id/user_picture"
        android:layout_marginStart="5dp"
        android:layout_marginTop="10dp"
        android:background="@color/user_message"
        android:layout_marginLeft="5dp"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginRight="10dp">

В силу особенности кода мне надо передвинуть его влево в XML Это строка
android:layout_alignParentEnd="true"

Но мне нужно это сделать программно, но как это сделать, никак не могу найти

A:         val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
        params.addRule(RelativeLayout.ALIGN_PARENT_END)
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
        cardview.layoutParams = params

В первой строчке укажите параметры вашего контейнера где находится CardView


text:
Q: python cgi on IIS How do you set up IIS so that you can call python scripts from asp pages?
Ok, so I found the answer to that question here: http://support.microsoft.com/kb/276494
So on to my next question: How do you call a cgi script from within classic asp (vb) code? Particularly one which is not in the web root directory.

A: You could also do it this way.

A: I don't believe that VBScript as hosted by IIS has any way of executing an external process.  If you are using python as an AXscripting engine then you could just use the sys module.  If the script you're calling is actually meant to be a cgi script you'll have to mimic all the environment variables that the cgi uses.  The alternative is to put the script on the python path, import it and hope that it is modular enough that you can call the pieces you need and bypass the cgi handling code.


text:
Q: Use fitted value from regression on subset of features as independent variable I am working with a relatively large data set with 2K columns and many variables can be grouped together (a logistic regression). So I am thinking can I use fitted value from regression on subset of features as independent variable?.
For example
Instead of:
Y ~ X1 + X2 + X3 + Z1 + Z2 + Z3
Can I use Y ~ X1 + X2 + X3 and Y ~ Z1 + Z2 + Z3
then use the fitted value Y1 and Y2 from those two models to do: Y ~ Y1 + Y2
Please correct me if there is any issue with this method. Thanks!

A: I think what you are saying is that you have two types of columns... type 1 and type 2.  You have a target variable $y$ to estimate.  What you are suggesting to do is to estimate $y_1$ with the type 1 columns, then $y_2$ with the type 2 columns, and finally estimate $y$ as a function of $\hat y_1$ and $\hat y_2$.
Although this is certainly possible, you don't indicate why would you be interested in doing this.   If you want to do dimensionality reduction, I would recommend you to do PCA instead, and then regress $y$ into the principal components.
The problem of your approach is that you are introducing unnecessary noise for the estimation of the parameters.


text:
Q: Converting a tuple of integral_constants to a constexpr tuple of ints Suppose I have a tuple of hana::integral_constants like so:
auto tuple_of_int_const = hana::make_tuple(hana::integral_constant<int,0>(),
                                           hana::integral_constant<int,1>());

I am trying to now produce a constexpr tuple of ints from this like so:
constexpr auto constexpr_tuple = hana::make_tuple(0,1);

My attempt:
#include "boost/hana.hpp"

using namespace boost;

auto tuple_of_int_const = hana::make_tuple(hana::integral_constant<int,0>(),
                                           hana::integral_constant<int,1>());

constexpr auto tuple = hana::transform(tuple_of_int_const,[](auto x){ return x(); });

The problem is that lambda's are not constexpr.......so the question is this:
How do I convert a tuple of integral_constants to a constexpr lambda?
Note:
I am using c++14

A: Boost.Hana has the function value_of as part of the Constant concept.
#include <boost/hana.hpp>

namespace hana = boost::hana;

int main() {
  auto tuple_of_int_const = hana::make_tuple(hana::integral_constant<int,0>(),
                                             hana::integral_constant<int,1>());

  constexpr auto tuple = hana::transform(tuple_of_int_const, hana::value_of);

  static_assert(hana::make_tuple(0, 1) == tuple, "");
}

A: You might create regular template function:
template <typename ... Ts>
constexpr auto tuple_transform(std::tuple<Ts...>)
{
    return std::make_tuple(Ts{}()...);
}

Demo


text:
Q: Jquery - if contains is not working right I have a block of code to check a  tag. if it contain a string in there then alert TRUE, otherwise alert FALSE.
But I always get alert TRUE. even though its not TRUE???..heres my code below.
hopefully someone can help me find the solution to this.

Hmmm, Its not working??

Jquery code
if($("h1:contains('Help me please')")) {
alert('TRUE');
} else {
alert('FALSE');
}

Link to my jsfiddle

A: The jQuery selector used by you always return a jQuery wrapper object which will be always a truthy value.
Instead what you can do is to use .is() to test whether any of the elements passed satisfied the passed selector
if ($("h1").is(":contains('Help me please')")) {
    alert('TRUE');
} else {
    alert('FALSE');
}

Demo: Fiddle
Or you can check the length of the elements found by the jQuery object
if ($("h1:contains('Help me please')").length) {
    alert('TRUE');
} else {
    alert('FALSE');
}

Demo: Fiddle

A: $("h1:contains('Help me please')") returns an object
and if(object) evaluates to true
so you can do
if ($("h1:contains('Help me please')").length > 0)

or
if ($("h1").is(":contains('Help me please')"))

instead


text:
Q: How to send a parameter to a trigger function from an external resource I have a trigger that executes before delete to audit changes in tables. The problem I have is that one of the fields I save in the xtable_audit table is the user id (of an user table) that is used in the web application. How can I send that external iduser from the web application to the trigger function when a delete occurs in any table that has that trigger?

A: You could use the set_config() and current_setting() functions for that. In the application just after establishing the database connection you call something like
select set_config('myapp.app_user','johnny',false);

to set a custom configuration variable for the session. In the trigger you then use
select into v_actualuser current_setting('myapp.app_user');

to retrieve the value.
This blog post even has a sample trigger for your viewing pleasure.


text:
Q: SSIS configuration options where test & production are on the same server I'm new to SSIS, my project is still in the early stages, with only dev & test environments on separate servers. The production environment will be on the same server as test (I don't have a say in that!). I have a number of packages that each have an SQL Agent job to schedule them and I need a way to handle package configurations for dev, test & production.
I know I can store 2 versions of the packages in different directories within MSDB on the same server but what is the best way to implement test & production on the same server with the least amount of manual work to deploy to production?
I could deploy the packages to 2 different locations in MSDB and create a job for each package (1 for test, 1 for prod) but how do I set up package configuration so the package itself doesn't need to change between environments?

A: You have several options:

*

*Create a package configuration table as described here and here.  This could work well if you are running the packages on the same server.

*Override the connection settings in the SQL Server Agent Job.  This could work well enough, but it can be difficult to manage if every job has to override connection settings.

*Use the package configuration XML file and run your packages through the agent via DTEXEC.  This seems like overkill to me if the packages are on the same server.

*Use a variable in the package that inspects the store it is running under to determine which database to use.  This is a theory that I haven't tested.  If I am correct, the advantage of this approach is that you don't need to setup anything outside of the package.  The downside is that it may be difficult or impossible to implement, particularly when you have to consider how the package will run locally in BIDS during testing.


text:
Q: why my computer's resource exhausted while has lots of memory? My computer configuration is : WINDOWS XP, 2G memory,
I had a bad habit, when I browse a webpage I like, I will not close it, just let it live in my IE8, for I may want to read this page later!
So my IE always spend most of my memory. When there's 30 plus tab in my IE, and some word documents open, then if I click 'My Computer' desktop icon, the explorer sometimes don't show menu etc, Seems not enough resource, If I close some documents, the explorer back to normal. But when I use tool to see how much memory left, the tool shows 1G left,
Then what happened to my computer. Does anyone use web browser like my kind?

A: It sounds like you're running out of USER objects.  USER objects represent user interface elements like desktops, windows, menus, cursors and icons.  There are upper limits on the number of USER objects in Windows, and when you reach those limits, you will typically see strange behaviour, similar to what you describe.  You can use the freeware Process Explorer from SysInternals/Microsoft to confirm that this is the problem and definitively identify the offending process.
Mark Russinovich has written an excellent overview of USER and GDI objects and their limits in Windows.
Unfortunately, even after you've confirmed that IE is causing the problem, the only solution will be to close IE, thus freeing up the USER resources, then run IE again.
As a long-term solution, I recommend using IE's Favorites feature to create shortcuts to the web sites you like.  You can organize your Favorites into a tree structure that makes it easy to group sites by task or topic.  That way you don't have to leave your favorite sites open in the browser all the time and you won't deplete your system's resources.

A: Your Windows XP might not have enough Virtual Memory.
Press [WIN]+[PAUSE] key combo to get into "System Properties" window, then  select the "Advanced" tab. Then under the "Performance" section press the "Settings Button", the "Performance Options" window will pop up.
On the "Performance Options" Window select the "Advanced" tab... and then click on the button "Change" under the "Virtual memory" section, this will popup the "Virtual Memory" window.
Under the "Virtual Memory" window, in section "Paging file size for selected drive" make sure the option "System managed size" is selected and press the button "set" (if enabled).
Press "OK" buttons to close all the opened windows.
Note: The name of the windows/buttons might vary in your language.

A: I am using Firefox and I have 22 websites in my Tab now and I don't face this issue. May be you are temporarily out of cache memory . You may make your IE Pages Work offline and Refresh them When you need them. so that they take less time and resource when you start your IE. Additionally this kind of Windows behavior is seen when you have less space in Windows installed drive. Make sure you have enough space in Windows drive.


text:
Q: Does RAM always use a big Mux to 'read' from its addresses? I've designed a 64 bit (16 words * 4-Bits at each location) RAM in logic simulation software, using simple registers. I had to create a 16-to-1, 4-bit wide Mux (no mean feat) in order to 'select' one of these registers, and retrieve the 4-bit output. Does this mean larger RAM modules, e.g a 1KB module of say 128 words, and 8-Bits at each location, would need a 128-to-1, 8-bit wide Mux to select the output? This seems insane for larger amounts of RAM, often present on microcontrollers and the like. Is this simply scaled up as you go? e.g. 1MB of 32,768 addressable locations holding 32 bits each, would need a 32,768 to 1 Mux, with each channel a width of 32 bits?

A: Yes, but...
Typically RAM is made as a 2D grid, so instead of a 65536:1 mux, you have two 256:1 muxes. One of them selects the row from the grid, and one of them selects the column. The row-select wires and the column-select wires form a grid. Each individual storage bit is only triggered when the row-select and the column-select are both activated at the same time.
Or
Actually, there's only a 256:1 mux, and all 256 bits in that row are activated. There is circuitry at one end of the grid which supports reading and writing 256 bits at a time. When you ask the RAM chip to write 8 bits, it will actually read 256 bits, overwrite 8, then write 256. This is useful with DRAM, since the entire row gets refreshed.
Other combinations are possible, like 512 rows of 128 bits for 65536 bits.

A: A multiplexer can be implemented in several ways. You are assuming that the multiplexer is assembled from AND/OR gates (or NAND or NOR) but that is not how the output multiplexer for a memory is made.
These kinds of multiplexers use high-impedance (tristate) drivers onto a common bus. The control logic selects which inputs should be routed to the outputs and enables their drivers. The drivers for all other inputs are placed in a high-impedance state. This kind of design is done at the transistor level, not by wiring up AND and OR gates.
A similar scheme that you could investigate is called "wired-OR" logic.


text:
Q: Crear Código HTML desde C# en la vista Estoy trabajando en un proyecto de facturación, y tengo una vista creando la factura y su respectivo detalle.
Necesito que cuando el usuario de clic en el botón Agregar Producto, Repita todo el código tr Registrodeproducto

                    @Html.DropDownList("Producto", null, htmlAttributes: new { @class = "form-control input-sm", placeholder = "Selecione el Producto" })
                    @Html.TextBoxFor(model => model.NumeroFactura, new { @class = "form-control  input-sm", placeholder = "Referencia", @readonly = 1, @required = 1 })
                    @Html.TextBoxFor(model => model.NumeroFactura, new { @class = "form-control  input-sm", placeholder = "Cantidad", @required = 1 })
                    @Html.TextBoxFor(model => model.NumeroFactura, new { @class = "form-control  input-sm", placeholder = "Precio Venta Unitario", @required = 1 })
                    @Html.TextBoxFor(model => model.NumeroFactura, new { @class = "form-control  input-sm", placeholder = "Subtotal", @readonly = 1, @required = 1 })

He intentado de varias formas pero no lo logro....
Codigo HTML generado por la aplicación:

                        Producto

                        Referencia

                        Cantidad

                        Precio

                        Subtotal

                        Acciones

                    <select class="form-control input-sm" id="Producto" name="Producto" placeholder="Selecione el Producto"><option value="101">Cocacola 350</option>

Camisa


text:
Q: Read multi lists related data with Entity Framework 6 using ViewModels I want using EF 6 on my MVC 5 MarketPlace project. I have many related rows at my Database. When I using the Context Models Everything fine but I cant use ViewModels for accessing related data. I am newbie so I read about Lazy, Eager, and Explicit Loading of Related Data. When codes calling to controller with a ID then target row and relates responded as well, but I want list all of my Categories rows and they related rows at Home Index so I need a little tips please if is possible.

Model
    public partial class Category : Repository.Pattern.Ef6.Entity
{
    public Category()
    {
        this.CategoryPictures = new List<CategoryPicture>();
        this.CategoryListingTypes = new List<CategoryListingType>();
        this.CategoryStats = new List<CategoryStat>();
        this.Listings = new List<Listing>();
        this.MetaCategories = new List<MetaCategory>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int Parent { get; set; }
    public bool Enabled { get; set; }
    public int Ordering { get; set; }
    public virtual ICollection<CategoryListingType> CategoryListingTypes { get; set; }
    public virtual ICollection<CategoryStat> CategoryStats { get; set; }
    public virtual ICollection<Listing> Listings { get; set; }
    public virtual ICollection<CategoryPicture> CategoryPictures { get; set; }
    public virtual ICollection<MetaCategory> MetaCategories { get; set; }
}

ViewModel

    public class CategoryItemModel
{
    public List<ListingItemModel> CategoryListings { get; set; }
    public List<Category> CategoryOthers { get; set; }
    public Category CategoryCurrent { get; set; }
    public string UrlPicture { get; set; }
    public List<CategoryPictureModel> Pictures { get; set; }
}

Category Details Controller

 public virtual async Task<ActionResult> Category(int id)
    {
        var itemQuery = await _categoryService.Query(x => x.ID == id)
            .Include(x => x.CategoryPictures)
            .Include(x => x.CategoryListingTypes)
            .Include(x => x.Listings)
            .Include(x => x.CategoryStats)
            .SelectAsync();

        var item = itemQuery.FirstOrDefault();
        if (item == null)
            return new HttpNotFoundResult();

        var itemsList = _listingService.Queryable()
            .Where(x => x.CategoryID == id
                && (x.Enabled != false || x.Active != false)
                && (x.EndDate >= DateTime.Now || x.StartDate <= DateTime.Now))
                .ToList();

        var itemsModel = new List<ListingItemModel>();
        foreach (var list in itemsList.OrderByDescending(x => x.Created))
        {
            itemsModel.Add(new ListingItemModel()
            {
                ListingCurrent = list,
                UrlPicture = list.ListingPictures.Count == 0 ? ImageHelper.GetListingImagePath(0) : ImageHelper.GetListingImagePath(list.ListingPictures.OrderBy(x => x.Ordering).FirstOrDefault().PictureID)
            });
        }

        var pictures = await _categoryPictureservice.Query(x => x.CategoryID == id).SelectAsync();

        var picturesModel = pictures.Select(x =>
            new CategoryPictureModel()
            {
                ID = x.PictureID,
                Url = ImageHelper.GetCategoryImagePath(x.PictureID),
                CategoryID = x.CategoryID,
                Ordering = x.Ordering
            }).OrderBy(x => x.Ordering).ToList();

        var itemModel = new CategoryItemModel()
        {
            CategoryCurrent = item,
            CategoryListings = itemsModel,
            Pictures = picturesModel

        };

        return View("~/Views/Listing/Category.cshtml", itemModel);
    }

Please I want List all of my categories with they related data's (Pics, Listings, Stats).
Very Thanks for any tips.

A:
I want List all of my categories with they related data's (Pics, Listings, Stats)

Then run ToList on your query:
    var  categories = await _categoryService.Query(x => x.ID == id)
        .Include(x => x.CategoryPictures)
        .Include(x => x.CategoryListingTypes)
        .Include(x => x.Listings)
        .Include(x => x.CategoryStats)
        .ToList();

A:  public virtual async Task<ActionResult> Categories()
    {
        var items = await _categoryService.GetAll()
            .Include(x => x.CategoryPictures)
            .Include(x => x.CategoryListingTypes)
            .Include(x => x.Listings)
            .Include(x => x.CategoryStats)
            .ToListAsync();

        return View(items);
    }


text:
Q: how to move or copy specific file quantities to other directory I would like to know how to move or copy specific number of files to another directory.
For example: If I have 880 files in directory A and want to move or copy 150 files from A to directory B and also 150-300 files from A to directory C.
I already tried this command
$ find . -maxdepth 1 -type f | head -150 | xargs cp -t "$destdir"

But this is copying 880 files to directory B

A: A possible solution to mv 150 files:
mv `find ./ -maxdepth 1 -type f | head -n 150` "$destdir"

Swap out mv for cp to copy instead.
Here is a test case:
mkdir d1 d2
cd d1
touch a b c d e f g h i j k l m n o p
cd ../
mv `find ./d1 -type f | head -n 5` ./d2/

And the result:
ls d1 d2
d1:
b  c  d  e  g  h  i  k  m  n  o

d2:
a  f  j  l  p

Edit:
Here is a simple script that will answer your comment:
#!/bin/sh
# NOTE: This will ONLY WORK WITH mv.
# It will NOT work with cp.
#
# How many files to move
COUNT=150
# The dir with all the files
DIR_MASTER="/path/to/dir/with/files"
# Slave dir list - no spaces in the path or directories!!!
DIR_SLAVES="/path/to/dirB /path/to/dirC /path/to/dirD"

for d in $DIR_SLAVES
do
    echo "Moving ${COUNT} to ${d}..."
    mv `find ${DIR_MASTER} -maxdepth 1 -type f | head -n ${COUNT}` "${d}"
done

exit

NOTE: The sample script has not been tested, but should work.

A: In case your shell supports process substitution then you could try this:
The first 150 feiles will be copied over to destdir_B and the NEXT 300 to destdir_C. Any remaining would remain untouched.
{
   head -n 150 | xargs -t cp -t "$destdir_B"
   head -n 300 | xargs -t cp -t "$destdir_C"
} <(find . -maxdepth 1 -type f)

This comes with the usual caveats of not being able to handle exotic filenames.
And when you don't have <(...) you could save find output to a file then redirect that file into the {...}
HTH


text:
Q: Añadir al carrito variaciones página principal y categoría woocommerce Mi sitio tiene el plugin woocommerce y tendría que mostrar la opción de las variaciones del producto tanto en la página principal como en sus respectivas categorías.
El código que tengo hasta ahora (encontrado en este link de stack) consigue mostrarlo pero me dice al añadirlo que debo de visitar la página del producto para poder añadirlo al carrito.
He probado añadiendo las propiedades action  al form pero nada.
Mi functions.php
add_filter( 'woocommerce_loop_add_to_cart_link', 'woo_display_variation_dropdown_on_shop_page' );

 function woo_display_variation_dropdown_on_shop_page() {

   global $product;

  if( $product->is_type( 'variable' )) {

  $attribute_keys = array_keys( $product->get_attributes() );
  ?>

  <form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->id ); ?>" data-product_variations="<?php echo htmlspecialchars( json_encode( $product->get_available_variations() ) ) ?>">
    <?php do_action( 'woocommerce_before_variations_form' ); ?>

    <?php if ( empty( $product->get_available_variations() ) && false !== $product->get_available_variations() ) : ?>

<?php _e( 'This product is currently out of stock and unavailable.', 'woocommerce' ); ?>

    <?php else : ?>

                  <?php foreach ( $product->get_variation_attributes() as $attribute_name => $options ) : ?>

              <label for="<?php echo sanitize_title( $attribute_name ); ?>"><?php echo wc_attribute_label( $attribute_name ); ?>

                <?php
                  $selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( urldecode( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ) : $product->get_variation_default_attribute( $attribute_name );
                  wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
                  echo end( $attribute_keys ) === $attribute_name ? apply_filters( 'woocommerce_reset_variations_link', '' . __( 'Clear', 'woocommerce' ) . '' ) : '';
                ?>

          <?php endforeach;?>

      <?php do_action( 'woocommerce_before_add_to_cart_button' ); ?>

        <?php
          /**
           * woocommerce_before_single_variation Hook.
           */
          do_action( 'woocommerce_before_single_variation' );

          /**
           * woocommerce_single_variation hook. Used to output the cart button and placeholder for variation data.
           * @since 2.4.0
           * @hooked woocommerce_single_variation - 10 Empty div for variation data.
           * @hooked woocommerce_single_variation_add_to_cart_button - 20 Qty and cart button.
           */
          do_action( 'woocommerce_single_variation' );

          /**
           * woocommerce_after_single_variation Hook.
           */
          do_action( 'woocommerce_after_single_variation' );
        ?>

      <?php do_action( 'woocommerce_after_add_to_cart_button' ); ?>
    <?php endif; ?>

    <?php do_action( 'woocommerce_after_variations_form' ); ?>
  </form>

  <?php } else {

  echo sprintf( '%s',
      esc_url( $product->add_to_cart_url() ),
      esc_attr( isset( $quantity ) ? $quantity : 1 ),
      esc_attr( $product->id ),
      esc_attr( $product->get_sku() ),
      esc_attr( isset( $class ) ? $class : 'button' ),
      esc_html( $product->add_to_cart_text() )
    );

  }

}

Y las capturas de cómo aparece la tienda:

Y este es el error que me produce cuando elijo la variación correspondiente:


text:
Q: Running mysqld with root privilege As we know running mysql with root privilege is not recommended which leads to privilege escalation using UDF's.
I'm trying to setup a machine to demonstrate this and I wanted to run mysqld as root user.
MySQL UDF exploitation for more info.
Im running ubuntu 21.04 and with mysql-server
mysql version:
mysql  Ver 8.0.25-0ubuntu0.21.04.1 for Linux on x86_64 ((Ubuntu))

Changing the file ownership to root
chown -R root /var/lib/mysql

/etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
user        = root
pid-file    = /var/run/mysqld/mysqld.pid
socket  = /var/run/mysqld/mysqld.sock
port        = 3306
datadir = /var/lib/mysql

I am getting error
mysql.service - MySQL Community Server
     Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2021-05-25 08:29:56 PDT; 23s ago
    Process: 2413 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
    Process: 2421 ExecStart=/usr/sbin/mysqld (code=exited, status=1/FAILURE)
   Main PID: 2421 (code=exited, status=1/FAILURE)
     Status: "Server startup in progress"
      Error: 13 (Permission denied)

However, If I change the file permissions of /var/lib/mysql back to mysql user the service starts.
Please let me know the solution how I can run it as root.
If I am doing anything wrong please suggest clear steps.
Ref:

A: The mysqld service runs as the mysql user by default as is specified in the service file. There is no reason to run it as root as doing so wouldn't provide anything that isn't there with it running as the mysql user. PostgreSQL and MongoDB also run as their respective users and not as root.
There's no reason to fix what isn't broken.


text:
Q: Proper format of json for Highchart.js with multiple series I have examples json data for Higcharts USD currency:
https://cdn.jsdelivr.net/gh/highcharts/highcharts@v7.0.0/samples/data/usdeur.json
So i added simply one value to data, there not show in a chart.
[
    [
        1167609600000,
        50,
        30
    ],
    [
        1167609600001,
        60,
        40
    ],
    [
        1167609600002,
        70,
        50
    ]
]

My code:

function myFunction() { Highcharts.getJSON(
  'http://192.168.0.157/log1.json',   function (data) {
Highcharts.chart('container', {
  chart: {
    zoomType: 'x',        backgroundColor:"#e7ecea"
  },
  title: {
    text: 'Pomiary'
  },
  subtitle: {
    text: document.ontouchstart === undefined ?
      'select' : 'Pinch the chart to zoom in'
  },
  xAxis: {
    type: 'datetime'
  },
  yAxis: {
    title: {
      text: 'Exchange rate'
    }
  },
  legend: {
    enabled: false
  },
  plotOptions: {
    area: {
      fillColor: {

        stops: [
          [0, Highcharts.getOptions().colors[0]],
          [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
        ]
      },
      marker: {
        radius: 2
      },
      lineWidth: 1,
      states: {
        hover: {
          lineWidth: 1
        }
      },
      threshold: null
    }
  },

  series: [{
    type: 'area',
    name: 'speed',
    data: data
  },    {
    type: 'area',
    name: 'speed2',
    data: data
  }]
});   } );

};

How i can add next series?

A: The simplest way is to use keys property:
series: [{
  data: data
}, {
  keys: ['x', 'someValue', 'y'],
  data: data
}]

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4797/
API Reference: https://api.highcharts.com/highcharts/series.line.keys


text:
Q: How do you know if memcached is doing anything? I'm testing out using memcached to cache django views.  How can I tell if memcached is actually caching anything from the Linux command line?

A: From the command line, try the command below:
echo stats | nc 127.0.0.1 11211

If it doesn't return anything, memcache isn't running. Otherwise it should return a bunch of stats including uptime (and hit and miss counts)
The reference article is here,
https://www.percona.com/blog/2008/11/26/a-quick-way-to-get-memcached-status/
To see changes every 2 seconds:
watch "echo stats | nc 127.0.0.1 11211"

A: Memcached can actually write to a logfile on its own, without having to resort to restarting it manually. The /etc/init.d/memcached init script (/usr/lib/systemd/system/memcached.service on EL7+; ugh) can call memcached with the options specified in /etc/memcached.conf (or /etc/sysconfig/memcached on EL5+). Among these options are verbosity and log file path.
In short, you just need to add (or uncomment) these two lines to that conf/sysconfig file...
-vv
logfile /path/to/log

...and restart the daemon with service memcached restart(EL3-7) or /etc/init.d/memcached restart(debuntus)
And then you can monitor this log in the traditional way, like tail -f /path/to/log, for example.

A: In Bash, you can check the statistics of memcache by this command:
exec 3<>/dev/tcp/localhost/11211; printf "stats\nquit\n" >&3; cat <&3

To flush the cache, use memflush command:
echo flush_all >/dev/tcp/localhost/11211

and check if the stats increased.
To dump all the cached objects, use memdump or memcdump command (part of memcached/libmemcached package):
memcdump --servers=localhost:11211

or:
memdump --servers=localhost:11211

If you're using PHP, to see whether is supported, check by: php -i | grep memcached.

Tracing
To check what memcached process is exactly processing, you can use network sniffers or debuggers (e.g. strace on Linux or dtrace/dtruss on Unix/OS X) for that. Check some examples below.
Strace
sudo strace -e read,write -fp $(pgrep memcached)

To format output in a better way, check: How to parse strace in shell into plain text?
Dtruss
Dtruss is a dtrace wrapper which is available on Unix systems. Run it as:
sudo dtruss -t read -fp $(pgrep memcached)

Tcpdump
sudo tcpdump -i lo0 -s1500 -w- -ln port 11211 | strings -10

A: You could use the official perl script:
memcached-tool 127.0.0.1:11211 stats

Or just use telnet and the stats command e.g.:
# telnet localhost [memcacheport]
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
stats
STAT pid 2239
STAT uptime 10228704
STAT time 1236714928
STAT version 1.2.3
STAT pointer_size 32
STAT rusage_user 2781.185813
STAT rusage_system 2187.764726
STAT curr_items 598669
STAT total_items 31363235
STAT bytes 37540884
STAT curr_connections 131
STAT total_connections 8666
STAT connection_structures 267
STAT cmd_get 27
STAT cmd_set 30694598
STAT get_hits 16
STAT get_misses 11
STAT evictions 0
STAT bytes_read 2346004016
STAT bytes_written 388732988
STAT limit_maxbytes 268435456
STAT threads 4
END

A: I know this question is old, but here is another useful approach for testing memcached with django:
As @Jacob mentioned, you can start memcached in very verbose mode (not as a daemon):
memcached -vv

To test your django cache config, you can use the low-level cache api.

*

*First, start up the python interpreter and load your django project settings:
python manage.py shell

*From the shell, you can use the low-level cache api to test your memcache server:
from django.core.cache import cache
cache.set('test', 'test value')

If your cache configuration is correct, you should see output in memcache similar to this:
<32 set :1:test 0 300 10
>32 STORED

A: For extend Node's response, you can use socat UNIX-CONNECT:/var/run/memcached.sock STDIN to debug a unix socket.
Example:
$ socat UNIX-CONNECT:/var/run/memcached.sock STDIN
stats
STAT pid 931
STAT uptime 10
STAT time 1378574384
STAT version 1.4.13
STAT libevent 2.0.19-stable
STAT pointer_size 32
STAT rusage_user 0.000000
STAT rusage_system 0.015625
STAT curr_connections 1
STAT total_connections 2
STAT connection_structures 2

A: Start memcache not as a daemon but normal, so just run memcached -vv for very verbose.  You will see when get's and sets come in to the memcache server.

A: You can test memcached or any server by below script
lsof -i :11211 | grep 'LISTEN'>/dev/null 2>/dev/null;echo $?

if it returns 0 then the server is actually running or if 1 its not so if you want to know that the server is actually running on some port use the following script
lsof -i :11211 | grep 'LISTEN'>/dev/null 2>/dev/null;
if [ $? -eq 0]; then
    echo "Your memcache server is running"
else
    echo "No its not running"
fi

A: Simple way to test for memcache working was to sneak in a commented out timestamp on every page served up.  If the timestamp stayed the same on multiple requests to a page, then the page was being cached by memcache.
In Django settings, I also setup the cache mechanism to use a file cache on the filesystem (really slow), but after hitting up the pages I could see that there were actual cache files being placed in the file path so I could confirm caching was active in Django.
I used both these steps to work out my caching problem. I actually did not have caching turned on correctly in Django.  The newer method to activate caching is using the 'django.middleware.cache.CacheMiddleware' middleware (not the middleware with two middleware pieces that have to be the first/last middleware settings.)

A: Can you use curl to fetch a page a few hundred times and time the results? You could also look at running a process on the server that simulates heavy CPU/disk load while doing this.

A: I wrote an expect script is-memcached-running that tests if memcached is running on a host/port combination (run as is-memcached-running localhost 11211):
#! /usr/bin/env expect
set timeout 1
set ip [lindex $argv 0]
set port [lindex $argv 1]
spawn telnet $ip $port
expect "Escape character is '^]'."
send stats\r
expect "END"
send quit\r
expect eof

If you run your system from a Makefile rule, you could make your startup depend on a make target that asserts it is up and running (or helps you get that state). It is verbose when the check fails to make it easy for us to debug failed ci runs, installs memcached when it's missing, and is brief and to the point otherwise:
#! /bin/bash
if [[ "$(type -P memcached)" ]]; then
  echo 'memcached installed; checking if it is running'
  memcached_debug=`mktemp memcache-check.XXXXX`
  if is-memcached-running localhost 11211 >$memcached_debug 2>&1; then
    echo 'Yep; memcached online'
  else
    cat $memcached_debug
    echo
    echo '****** Error: memcached is not running! ******'
    if [[ "$OSTYPE" =~ ^darwin ]]; then
      echo
      echo 'Instructions to auto-spawn on login (or just start now) are shown'
      echo 'at the end of a "brew install memcached" run (try now, if you did'
      echo 'not do so already) or, if you did, after a "brew info memcached".'
      echo
    fi
    exit 1
  fi
  rm -f $memcached_debug
else
  echo memcached was not found on your system.

  if [[ "$OSTYPE" =~ ^darwin ]]; then
    brew install memcached
  elif [[ "$OSTYPE" =~ ^linux ]]; then
    sudo apt-get install memcached
  else
    exit 1
  fi
fi

A: Following Aryashree post, this helped me to get an error if memcached not running locally:
import subprocess

port = 11211
res = subprocess.Popen(f"echo stats | nc 127.0.0.1 {port}",
        shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

if res.stdout:
    lines = res.stdout.read()
    lineArr = lines.split('\r\n')
    pidlineArr = lineArr[0].split(' ')
    pid = pidlineArr[-1]
    print(f"[MemCached] pid {pid} Running on port {port}")

else:
    raise RuntimeError(f"No Memcached is present on port {port}")

A: I'm using Mezzanine and the only answer that worked for me was Jacobs answer. So stopping the daemon and running memcached -vv

A: If you're using RHEL or Centos 8
To get memcached log stuff to /var/log/messages (quick without rotation)
https://serverfault.com/questions/208538/how-to-specify-the-log-file-for-memcached-on-rhel-centos/1054741#1054741


text:
Q: How to find td value with same tr's ID in jQuery I have an HTML table with rows made with a foreach loop like this:
@foreach (var item in Model) {

                @Html.DisplayFor(modelItem => item.StartDate)

                @Html.DisplayFor(modelItem => item.InternalMedicineCode)

                @Html.DisplayFor(modelItem => item.Tbl_InternalMedicine.InternalMedicineName)

                @Html.DisplayFor(modelItem => item.Dose)

                @Html.DisplayFor(modelItem=>item.IdTherapyRegistration)

When I click on a row, I want to alert the value of the cell that is hidden and its id is td1. I don't know how to do it with jQuery. My jQuery function code is:
$(document).ready(function () {

        $("#myTable").on('click', 'tr', function () {
            var currentRow = $(this).closest("tr");

            var col1 = currentRow.find("td:eq(4)").text();
            alert(col1);
        });
    });

but I can't get this id.

A: You should have defined the event on td and not tr.

$(document).ready(function () {

        $("#myTable tr").(function (){
            var currentRow = $(this);

            var col1 = currentRow.find("td:eq(4)").text();
            alert(col1);
        });
    });

A: If your are able to use a class instead of an id, on your tr, here is the solution.
First, replace this:

By this:

And then, update your jQuery function like this:

$(document).ready(function () {

  $(".tr-clickable").on("click", function() {
    var currentRow = $(this);
    var col1 = currentRow.find("td:eq(4)").text();

    alert(col1);
  })

});


text:
Q: Is it possible to enter a missing sequence number into another table, on exception in a Trigger Below is the code which I have written in the exception part of my before insert trigger.

CREATE OR REPLACE TRIGGER ORGANIZATIONS_TAB_BI_TRG
    BEFORE INSERT ON ORGANIZATIONS_TAB
    FOR EACH ROW
DECLARE
    -- variables
    lv_CurrentUserID VARCHAR2(30):= NULL;
BEGIN
   -- Getting the current session user id
    SELECT USER
      INTO lv_CurrentUserID
      FROM DUAL;
    IF :NEW.ORG_ID IS NULL THEN
      SELECT TO_NUMBER(TO_CHAR(SYSDATE,'RRRR')||LPAD(ORGANIZATIONS_SEQ.NEXTVAL,6,0) ORG_ID
        INTO :NEW.ORG_ID
        FROM DUAL;
    END IF;
EXCEPTION
  WHEN OTHERS THEN
        SEQ_AUDIT_PKG.InsertMissingSequence('ORGANIZATIONS_SEQ',
                      ORGANIZATIONS_SEQ.CURRVAL,
                          SYSDATE,
                          SYSDATE,
                          lv_CurrentUserID,
                          'Sequence Missed due to :'||SQLERRM);
END;
Can we do this for storing the missing sequence numbers to keep a track?
The SEQ_AUDIT_PKG.InsertMissingSequence is as follows:

PROCEDURE InsertMissingSequence(P_SEQ_NAME IN MISSED_SEQ_LOG.SEQUENCE_NAME%TYPE,
                                             P_SEQ_NUMBER IN MISSED_SEQ_LOG.SEQUENCE_NUM%TYPE,
                                             P_SEQ_DT IN MISSED_SEQ_LOG.SEQUENCE_DT%TYPE,
                                             P_CREATION_DT IN MISSED_SEQ_LOG.CREATION_DT%TYPE,
                                             P_CREATED_UID IN MISSED_SEQ_LOG.CREATED_UID%TYPE,
                                             P_REMARKS IN MISSED_SEQ_LOG.REMARKS%TYPE) IS
  BEGIN
    -- Inserting records into the Missing Sequence Log
    INSERT INTO MISSED_SEQ_LOG (SEQUENCE_NAME,SEQUENCE_NUM,SEQUENCE_DT,CREATION_DT,CREATED_UID,REMARKS)
           VALUES(P_SEQ_NAME,P_SEQ_NUMBER,P_SEQ_DT,P_CREATION_DT,P_CREATED_UID,P_REMARKS);
  EXCEPTION
    WHEN OTHERS THEN
      NULL;
  END InsertMissingSequence;

A: EXCEPTION
  WHEN OTHERS THEN
        SEQ_AUDIT_PKG.Inse...

is a bad idea, because 'when others' could be anything. eg, you might have a datafile corruption, or an out of memory error.  You dont want to be doing a sequence audit in that respect.  Similarly, when that primary trigger fails, you want to be sending that back to the calling program, not telling them that "Hey, all is well" (which is when WHEN-OTHERS typically will do).
You would need your SEQ_AUDIT_PKG.InsertMissingSequence to be an autonomous transaction so that you could log the information outside the transaction scope of the trigger.
But having said all that ..... just dont do it :-)
Sequences have gaps...period.  You can

*

*nocache them

*pin them in the shared pool

*carefully police shutdown abort commands

*capture unused ones with an autonomous transaction

and you'll still eventually get some missing and any promises you've made about no gaps become moot.  And the complexity cost toward meeting this goal is just not worth it.


text:
Q: Cassandra refuses to run query with where clause I have 2 Cassandra nodes. I have a table with 3 text fields (all keys) and 2 counters. RF is 2.
I added another counter column to table. Mistakenly, I issued drop on that column. I reverted application back to old version to not use the column.
I have added another counter column, to replace the dropped one, with a different name. I changed application to use that new column.
Now, all my queries that have where clause fail with this error:

ReadFailure: Error from server: code=1300 [Replica(s) failed to execute read] message="Operation failed - received 0 responses and 2 failures" info={'failures': 2, 'received_responses': 0, 'required_responses': 1, 'consistency': 'ONE'}

And I see this in debug.log:

java.lang.IllegalStateException: [payable, revenue, to_pay, value] is not a subset of [revenue to_pay value]

payable is the old column, that was dropped, and to_pay is the new column.
What is happening?
Cassandra version is 3.11.
PS. I tried repairing, and it is running. Will it help?
EDIT:
Table schema:
CREATE TABLE backend_platform_prod.stats_counters (
    date text,
    key text,
    revenue counter,
    to_pay counter,
    value counter,
    PRIMARY KEY (date, key)
) WITH CLUSTERING ORDER BY (key ASC)
    AND bloom_filter_fp_chance = 0.01
    AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';

There was a payable counter field, that is dropped.
I tried backing up data with copy to, dropping table and recreating it, and restoring with copy from. It is working now, although some data seems missing (not very important).
I see payable column in system_schema.dropped_columns, but not in system_schema.columns.

A: Please check in System_schema keyspace .if the column is still existing delete that row.


text:
Q: PInvoke and EntryPointNotFoundException I can't understand what is wrong with a pinvoke below which results into an EntryPointNotFoundException:
A function in C with a structure declaration:
    extern "C"__declspec (dllimport) __stdcall
    LONG NET_DVR_Login_V30 (char *sDVRIP,  WORD wDVRPort,  char *sUserName,
                        char *sPassword,  LPNET_DVR_DEVICEINFO_V30 lpDeviceInfo);

    typedef struct
    {
        BYTE sSerialNumber[48];
        BYTE byAlarmInPortNum;
        BYTE byAlarmOutPortNum;
        BYTE byDiskNum;
        BYTE byDVRType;
        BYTE byChanNum;
        BYTE byStartChan;
        BYTE byAudioChanNum;
        BYTE byIPChanNum;
        BYTE byZeroChanNum;
        BYTE byMainProto;
        BYTE bySubProto;
        BYTE bySupport;
        BYTE byRes1[20];
    }NET_DVR_DEVICEINFO_V30,  *LPNET_DVR_DEVICEINFO_V30;

The import in C#, the structure declaration and the pinvoke:
    [DllImport("SDK.dll", SetLastError = true,
        CallingConvention = CallingConvention.StdCall)]
        public extern static int NET_DVR_Login_V30(
            [MarshalAs(UnmanagedType.LPStr)] string sDVRIP,
            ushort wDVRPort,
            [MarshalAs(UnmanagedType.LPStr)] string sUserName,
            [MarshalAs(UnmanagedType.LPStr)] string sPassword,
            ref NET_DVR_DEVICEINFO_V30 lpDeviceInfo);

    [StructLayout(LayoutKind.Sequential,
        CharSet = CharSet.Ansi)]
        public struct NET_DVR_DEVICEINFO_V30
        {
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 48)]
            public string sSerialNumber;
            public byte byAlarmOutPortNum;
            public byte byDiskNum;
            public byte byDVRType;
            public byte byChanNum;
            public byte byStartChan;
            public byte byAudioChanNum;
            public byte byIPChanNum;
            public byte byZeroChanNum;
            public byte byMainProto;
            public byte bySubProto;
            public byte bySupport;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
            public string byRes1;
        }

           NET_DVR_DEVICEINFO_V30 deviceInfo = new NET_DVR_DEVICEINFO_V30();
           int result = Functions.NET_DVR_Login_V30(ip, port, user,
                                                 password, ref deviceInfo);

I inspected the function name via dumpbin and it is not mangled. So I wonder why an EntryPointNotFoundException occurs, if anything were wrong with the parameters for example, a PInvokeStackImbalance error would occur, let's say.
Any ideas what could be wrong with this pinvoke?

A: There is a tool called Dependency Walker (depends.exe) that will help debug this issue by displaying the import/export table of your SDK.DLL - I'd take a look at that. One other thing that might (this seems suspect to me) be happening is, that since you're using char*, .NET is adding an "A" on the end of your function name. That could be balderdash though.

A: Clearly there is a name mismatch. You therefore need to make sure that both sides of the interface use the same name:

*

*When exporting the function from the DLL as stdcall it will be decorated. You can avoid this decoration by using a .def file.

*When importing using P/Invoke you need to suppress the addition of a W or A suffix. Do so by setting the ExactSpelling field of the DllImportAttribute to true.


text:
Q: Не могу настроить проверку ввода python Ребят, есть задача:
На стандартном потоке ввода задаются два целых числа, не меньшие -32000 и не большие 32000. На стандартный поток вывода напечатайте сумму этих чисел.
Числа задаются по одному в строке. Пробельные символы перед числом и после него отсутствуют. Пустые строки в вводе отсутствуют.
Не могу понять, как проверять числа на заданные критерии.
if(type(a)!=int): - не будет работать, так как на входе всегда string.
isdigit() тоже не работает, так как не пропускает знак "-".
Я понимаю, что решение какое-то простое и очевидное, видимо, в силу неопытности - жестко туплю :(

A: тут должно быть все понятно:
>>> x= "-32"
>>> y="32"
>>> print x-y
  File "<stdin>", line 1
    print x-y
          ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(x-y)?
>>> print(x-y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>> print(int(x)+int(y))
0
>>> type (x)
<class 'str'>
>>> type (int(x))
<class 'int'>

A: res=[]
while True:
   if len(res)>=2:
       break
   i=int(input('num'))
   if -32000<i<32000:
       res.append(i)
    else:
        print('wrong input')


text:
Q: Recorded CodedUI can't find recorded Controls So I've gone and used the Code generator in Visual Studio to generate a coded UI test.  We have a wpf application with an TreeList.  I record it going to the first box, entering in a value, then clicking in the second box, and it types in a new value.  Nothing super fancy.
public void RecordedMethod1()
{
    #region Variable Declarations
    WpfCell uIItemCell = this.UIWindowWindow.UIEntityTesterControlCustom.UIEntityTesterTreeListTree.UIEntityTesterTreeListTreeItem.UIItemCell;
    WpfEdit uIInvoice1InvoiceIDEdiEdit = this.UIWindowWindow.UIEntityTesterControlCustom.UIEntityTesterTreeListTree.UIEntityTesterTreeListTreeItem.UIItemCell.UIInvoice1InvoiceIDEdiEdit;
    WpfCell uIItemCell1 = this.UIWindowWindow.UIEntityTesterControlCustom.UIEntityTesterTreeListTree.UIEntityTesterTreeListTreeItem.UIItemCell1;
    WpfEdit uI_localTextBoxEdit = this.UIWindowWindow.UIEntityTesterControlCustom.UIEntityTesterTreeListTree.UIEntityTesterTreeListTreeItem.UIItemCell11.UI_localTextBoxEdit;
    #endregion

    // Click cell
    Mouse.Click(uIItemCell, new Point(92, 18));

    // Type '1' in 'Invoice:1/InvoiceID|Editor' text box
    uIInvoice1InvoiceIDEdiEdit.Text = this.RecordedMethod1Params.UIInvoice1InvoiceIDEdiEditText;

    // Click cell
    Mouse.Click(uIItemCell1, new Point(136, 9));

    // Type '2/1/2012' in '_localTextBox' text box
    uI_localTextBoxEdit.Text = this.RecordedMethod1Params.UI_localTextBoxEditText;
}

#region Properties
public virtual RecordedMethod1Params RecordedMethod1Params
{
    get
    {
        if ((this.mRecordedMethod1Params == null))
        {
            this.mRecordedMethod1Params = new RecordedMethod1Params();
        }
        return this.mRecordedMethod1Params;
    }
}

It crashes with this error on the first Mouse.Click() call
Microsoft.VisualStudio.TestTools.UITest.Extension.UITestControlNotFoundException was unhandled by user code
HResult=-268111872
Message=The playback failed to find the control with the given search properties. Additional Details:
TechnologyName:  'UIA'
FrameworkId:  'Wpf'
ControlType:  'Custom'
ClassName:  'Uia.EntityTesterControl'
AutomationId:  'EntityTesterControl'
Search may have failed at 'Test Suite Tools' Custom as it may have virtualized children. If the control being searched is descendant of 'Test Suite Tools' Custom then including it as the parent container may solve the problem.
Source=Microsoft.VisualStudio.TestTools.UITesting
BasicMessage=The playback failed to find the control with the given search properties.
RootElement=""
StackTrace:
at Microsoft.VisualStudio.TestTools.UITesting.Playback.MapControlNotFoundException(COMException ex, IPlaybackContext context)
at Microsoft.VisualStudio.TestTools.UITesting.Playback.MapAndThrowComException(COMException innerException, IPlaybackContext context)
at Microsoft.VisualStudio.TestTools.UITesting.Playback.MapAndThrowException(Exception exception, IPlaybackContext context)
at Microsoft.VisualStudio.TestTools.UITesting.Playback.MapAndThrowException(Exception exception, String queryId)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.FindFirstDescendant(String queryId, Int32 maxDepth, Int32& timeLeft)
at Microsoft.VisualStudio.TestTools.UITesting.SearchHelper.GetUITestControlRecursive(Boolean useCache, Boolean alwaysSearch, ISearchArgument searchArg, IList`1 windowTitles, Int32& timeLeft)
at Microsoft.VisualStudio.TestTools.UITesting.SearchHelper.GetUITestControlRecursive(Boolean useCache, Boolean alwaysSearch, ISearchArgument searchArg, IList`1 windowTitles, Int32& timeLeft)
at Microsoft.VisualStudio.TestTools.UITesting.SearchHelper.GetUITestControlRecursive(Boolean useCache, Boolean alwaysSearch, ISearchArgument searchArg, IList`1 windowTitles, Int32& timeLeft)
at Microsoft.VisualStudio.TestTools.UITesting.SearchHelper.GetUITestControlRecursive(Boolean useCache, Boolean alwaysSearch, ISearchArgument searchArg, IList`1 windowTitles, Int32& timeLeft)
at Microsoft.VisualStudio.TestTools.UITesting.SearchHelper.GetElement(Boolean useCache, ISearchArgument searchArg)
at Microsoft.VisualStudio.TestTools.UITesting.SearchHelper.Search(ISearchArgument searchArg)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.FindInternal()
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.FindPrivate()
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.<Find>b__37()
at Microsoft.VisualStudio.TestTools.UITesting.CodedUITestMethodInvoker.InvokeMethod[T](Func`1 function, UITestControl control, Boolean firePlaybackErrorEvent, Boolean logAsAction)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.Find()
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.GetPropertyPrivate(String propertyName)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.<>c__DisplayClass3b.<GetProperty>b__3a()
at Microsoft.VisualStudio.TestTools.UITesting.CodedUITestMethodInvoker.InvokeMethod[T](Func`1 function, UITestControl control, Boolean firePlaybackErrorEvent, Boolean logAsAction)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.GetProperty(String propertyName)
at Microsoft.VisualStudio.TestTools.UITesting.ALUtility.GetTechElementFromUITestControl(UITestControl uiTestControl)
at Microsoft.VisualStudio.TestTools.UITesting.ActionExecutorManager.GetActionExecutor(UITestControl uiControl)
at Microsoft.VisualStudio.TestTools.UITesting.Mouse.ClickImplementation(UITestControl control, MouseButtons button, ModifierKeys modifierKeys, Point relativeCoordinate)
at Microsoft.VisualStudio.TestTools.UITesting.Mouse.<>c__DisplayClass6.<Click>b__5()
at Microsoft.VisualStudio.TestTools.UITesting.CodedUITestMethodInvoker.InvokeMethod[T](Func`1 function, UITestControl control, Boolean firePlaybackErrorEvent, Boolean logAsAction)
at Microsoft.VisualStudio.TestTools.UITesting.Mouse.Click(UITestControl control, MouseButtons button, ModifierKeys modifierKeys, Point relativeCoordinate)
at Microsoft.VisualStudio.TestTools.UITesting.Mouse.Click(UITestControl control, Point relativeCoordinate)
at RoadExercises.UIMap.RecordedMethod1() in c:\Users\dtan\Documents\Visual Studio 2013\Projects\CodedUITestProject1\CodedUITestProject1\UIMap.Designer.cs:line 46
at RoadExercises.RoadExercises.IrVerifyFillInField(String p1, String p2) in c:\Users\dtan\Documents\Visual Studio 2013\Projects\CodedUITestProject1\CodedUITestProject1\RoadExercises.cs:line 169
at RoadExercises.RoadExercises.RoadExercise1b() in c:\Users\dtan\Documents\Visual Studio 2013\Projects\CodedUITestProject1\CodedUITestProject1\RoadExercises.cs:line 139
InnerException: System.Runtime.InteropServices.COMException
HResult=-2147467259
Message=Error HRESULT E_FAIL has been returned from a call to a COM component.
Source=Microsoft.VisualStudio.TestTools.UITest.Playback
ErrorCode=-2147467259
StackTrace:
at Microsoft.VisualStudio.TestTools.UITest.Playback.Engine.IScreenElement.FindAllDescendants(String bstrQueryId, Object& pvarResKeys, Int32 cResKeys, Int32 nMaxDepth)
at Microsoft.VisualStudio.TestTools.UITest.Playback.ScreenElement.FindAllScreenElement(String queryId, Int32 depth, Boolean singleQueryId, Boolean throwException, Boolean resetSkipStep)
at Microsoft.VisualStudio.TestTools.UITest.Playback.ScreenElement.FindScreenElement(String queryId, Int32 depth, Boolean resetSkipStep)
at Microsoft.VisualStudio.TestTools.UITest.Playback.ScreenElement.FindScreenElement(String queryId, Int32 depth)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.FindFirstDescendant(String queryId, Int32 maxDepth, Int32& timeLeft)
InnerException:

As far as I can tell (when I did various slow steps/null checks).  The control for UIEntityTesterTreeListTree can't be found.  It looks like it's not located under the path that was mapped.  Apparently the path for this isn't a simple case of UIWindowWindow.UIEntityTesterControlCustom.UIEntityTesterTree, but instead there's a few more sub areas it has to go through before then.
I've tried to remap it a few times, but no luck.  I'd rather not hard code it, so hoping someone here can help me find the issue/way to fix this.
Thanks!

A: You'll have to edit the search properties of the WpfCell to be sure that they're using correct values.  The Coded UI Test Builder can often be too specific to work all the time, and I've found that editing the values down to the least common denominator is the best practice.   Here's  a good place to start.
I don't have much experience modifying the search properties to look for locations in the tree by position, as I've found it makes the code more complicated and isn't always, in my experience, very stable.  If some element gets added or moved in development, it will break all of your code and you'll have to go back and change the parameters for all of your mappings.  My suggestion would be to have the developer add an identifying property (unique name tag, for instance) to the elements so that you can specify that in your search instead.
If you're comfortable with c#, it may be easier to code your mapping instead.  If you have a specific property for the element, that will make it easier, of course.  For example:
<wpfelement>
    <subElement name='someElement'>
        <button name='oneButton'>Click me.</button>
    </subElement>
</wpfelement>
<wpfelement>
    <subElement name='someOtherElement'>
        <button name='secondButton'>Click me.</button>
    </subElement>
</wpfelement>

would be found in your map by:
public WpfButton UIItemCell
{
    get
    {
        WfpButton target = new WpfButton(parentElement);
        target.SearchProperties["name"] = "secondButton";
        return target;
    }
}

This way, no matter where the element is in your tree, the Coded UI engine will find it with ease.  If there aren't any identifying properties for the cell you want, it would be helpful to add them to the UI, but you can also navigate from the closest parent that has an identifier using element.GetChildren() and filtering from there.


text:
Q: Value cannot be send to database For my application, while registering, user must choose gender by using the radio button(RadioGroup)
After they choose it and fill up the register form, all data including gender should be store into phpmyAdmin.
And I have to store as a string the value for RadioButton.
Unfortunately, all the data are not be send and even after I click the send button nothing happen.
    package com.example.prime.try;

import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Struct;

public class Register extends AppCompatActivity {

    private RadioGroup radioGroupGender;
    private RadioButton radioButtonGender;
    private String userGender = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        final EditText etName = (EditText) findViewById(R.id.etName);
        final EditText etAge = (EditText) findViewById(R.id.etAge);
        final TextView tvGender = (TextView) findViewById(R.id.tvGender);
        final EditText etNationality = (EditText) findViewById(R.id.etNationality);
        final EditText etEmail = (EditText) findViewById(R.id.etEmail);
        final RadioGroup radioGroupGender = (RadioGroup) findViewById(R.id.radioGroupGender);
        final RadioButton rbMale = (RadioButton) findViewById(R.id.rbMale);
        final RadioButton rbFemale = (RadioButton) findViewById(R.id.rbFemale);
        final Button bSend = (Button) findViewById(R.id.bSend);

        final int selectedId = radioGroupGender.getCheckedRadioButtonId();
        radioButtonGender = (RadioButton) findViewById(selectedId);
        //final String userGender = Integer.toString(radioButtonGender.getId());
        //final String userGender = radioButtonGender.getText().toString();
        //final String userGender = String.valueOf(radioButtonGender.getId());

        //final String userGender = {((RadioButton) findViewById(radioGroupGender.getCheckedRadioButtonId())).getText().toString()};

        bSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String name = etName.getText().toString();
                final int age = Integer.parseInt(etAge.getText().toString());
                final String nationality = etNationality.getText().toString();
                final String email = etEmail.getText().toString();

                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            boolean success = jsonResponse.getBoolean("success");

                            if (success) {
                                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                startActivity(intent);
                                //Intent intent = new Intent(Register.this, MainActivity.class);
                                //Register.this.startActivity(intent);

                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                                builder.setMessage("Register Failed")
                                        .setNegativeButton("Retry", null)
                                        .create()
                                        .show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };

                radioGroupGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged (RadioGroup radioGroupGender,int checkedId){
                        int id = radioGroupGender.getCheckedRadioButtonId();
                        RadioButton rb = (RadioButton) findViewById(id);

                        String userGender = rb.getText().toString();

                    }
                });

                RegisterRequest registerRequest = new RegisterRequest(name, age, userGender, nationality, email, responseListener);
                RequestQueue queue = Volley.newRequestQueue(Register.this);
                queue.add(registerRequest);
            }
        });
    }

    public String RadioButtonClicked(View view) {

        String userGender = "";
        boolean checked = ((RadioButton) view).isChecked();

        switch (view.getId()) {
            case R.id.rbFemale:
                if (checked)
                    userGender = "Female";
                break;
            case R.id.rbMale:
                if (checked)
                    userGender = "Male";
                break;
        }
        return userGender;
    }

}

And this is the php file, thank you for your help in advance :)
    <?php
    $con = mysqli_connect("bio.000webhostapp.com", "anonymous12345", "animals89", "testing1235");

    $name = $_POST["name"];
    $age = $_POST["age"];
    $Gend = $_POST["userGender"];
    $nationality = $_POST["nationality"];
    $email = $_POST["email"];

    $statement = mysqli_prepare($con, "INSERT INTO user (name, age, Gend, nationality, email) VALUES (?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "sssss", $name, $age, $Gend, $nationality, $email);
    mysqli_stmt_execute($statement);

    $response = array();
    $response["success"] = true;

    echo json_encode($response);

?>


text:
Q: Nginx Configuration to bind a range of ports to 80 and set proxy_pass to a number route I can only run traffic through port 80 on my server.
What I am looking to do:

*

*port 8080 to bind to /8080

*port 8081 to bind to /8081

*and so on

Can I do this be done programatically in the conf file or do I need to time-consumingly set a location configuration for each of the individual ports?


text:
Q: Negative production for end of life treatment process I am currently working with the ecoinvent 3.6 database in Brightway and I have a question about the end of life treatment processes. I found out that some of these treatment processes have a negative production amount and give negative results when tested. For the same processes opened in Simapro, the production amount is positive and the LCA score is also positive. Screenshot of an activity details in Brightway
Screenshot of the result for this activity in Brightway
Screenshot of the activity details in Simapro
Screenshot of the result for this activity in Simapro
Is there an explanation for this ? And is it possible to know which processes are concerned ? Than you very much for your answer.

A: it is a thorny sign convention issue. One needs to be aware of these conventions because different LCA softwares and databases can have different conventions.
if you look into the same dataset in ecoinvent website you'll see that the reference product is -1 waste polypropylene. What that means is that it treats 1 kg of polypropylene.
Following the same convention the production flow of that activity on brightway is -1 (unlike normal "production" activities that have a positive production). To be consistent, the use of waste treatment services has also a negative amount (if you look into technosphere exchanges you'll see waste with - sign).
I think simapro treats them differently, and flips the sign of waste treatment activities, that is why you see it positive. It then flips the sign at some point in the calculation.
A good explanation is probably buried in the LCA mailing list somewhere, but I could not find it.


text:
Q: How to stop XMLReader throwing Invalid XML Character Exception So I have some XML:
<key>my tag</key><value>my tag value and my invalid Character</Value>
and an XMLReader:
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
     while (reader.Read())
     {
         //do my thing
     }
}

I have implemented the CleanInvalidCharacters method from here but as the "&#xB" is not yet encoded it doesn't get removed.
The error is being thrown at the reader.Read(); line with exception:

hexadecimal value 0x0B, is an invalid character.

A: The problem is that you don't have XML -- you have some string that sure looks like XML but unfortunately doesn't really qualify. Fortunately you can tell XmlReader to be more lenient:
using (XmlReader reader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings { CheckCharacters = false }))
{
     while (reader.Read())
     {
         //do my thing
     }
}

Note that you will still end up with XML that, when serialized, might produce problems further down the line, so you may wish to filter the characters out afterwards anyway as you're reading it.