问:
Building from and uploading to a local Python repository without writing credentials to disk
I have a Python build pipeline set up, with a Jfrog Artifactory Python repository serving our internal packages.

The pipeline uses this repository to resolve internal dependencies and upload build artefacts.

This is currently done with python setup.py bdist_wheel sdist upload -r local. This command actually requires the credentials to be on disk twice; once for resolving local dependencies via ~/.pydistutils.cfg:

```<code>[easy_install]
index_url=https://username:password@artifactory/api/repo/path/simple
</code>```

...and again in ~/.pypirc for uploading the build package:

```<code>[distutils]
index-servers = local

[local]
repository: https://artifactory/api/repo/path
username: build_agent
password: ****
</code>```

For security reasons I would like the username and password to never touch the disk. We already have a secure way of injecting secrets into the build environment from (Hashicorp) Vault, and I'd like to leverage this for the Artifactory credentials.

However, while I can set PIP_INDEX_URL for installing packages with pip, there is no equivalent for setuptools that I can see. Without these files defined, the command python setup.py sdist results in a stack trace the following error:

```<code>distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('local-package==0.0.3')
</code>```

Clearly, it is attempting to resolve a local dependency on public pypi, which is undesirable for a number of reasons (the local repository proxies pypi, so we should never read public pypi to prevent hijacking).

Essentially then my question is; how can I build and upload a python package, which has dependencies in a local repository, to that local repository, using credentials that are in environment variables and not in ~/.pypirc or ~/.pydistutils.cfg?

Additional background

The original implementation baked .pypirc and .pydistutils.cfg in the build agent AMI, which is built with Packer.

The problem with this, is that the username and password for the repository is essentially readable in plain text by anyone with access to the AWS account and the ability to download or create a new instance using the image.

That's easy, just add a build step which sets up pypirc before starting the build you say! I would like to avoid this approach, because it is brittle in the sense that it creates a global run-time build dependency. In future, someone could setup a job assuming the config files have already been created without doing so themselves, and it will almost always work because another job has run first. I can't remove the file after each build, because there could be concurrent builds requiring the file to be present.

答:
I've found a solution, but it's not particularly pretty.

First problem is setup_requires. Because it calls easy_install so early in the process, it's difficult to override; even creating a Distribution subclass and overriding the fetch_egg method didn't help. The workaround I've settled on for now is to wrap the setup method and preinstall them via pip (with PIP_INDEX_URL set):

```<code>from setuptools import setup

def _setup(**kwargs):
    requires = kwargs.get('setup_requires') or []

    for req in requires:
        pip.main(['install', req])

    return setup(**kwargs)

_setup(
    name='mypackage',
    ...
)
</code>```

This is only needed for packages that specify local dependencies in setup_requires, and python setup.py install remains broken. As pip does the installation in tox (deps = .[test] in the [testenv] section) and never use setup.py to install, a broken install command isn't a problem.

The second problem was uploading. Rather than do the upload with setup.py upload, I'm shifting this task to twine. Recent versions of twine read TWINE_USERNAME, TWINE_PASSWORD, and TWINE_REPOSITORY_URL from the environment if they are not in the traditional config files.

Anyway, I would love to find a more elegant solution to the first problem, especially one that didn't leave setup.py install broken, but for now this will do.

Body:
I have a Python build pipeline set up, with a Jfrog Artifactory Python repository serving our internal packages.

The pipeline uses this repository to resolve internal dependencies and upload build artefacts.

This is currently done with python setup.py bdist_wheel sdist upload -r local. This command actually requires the credentials to be on disk twice; once for resolving local dependencies via ~/.pydistutils.cfg:

[easy_install]
index_url=https://username:password@artifactory/api/repo/path/simple

...and again in ~/.pypirc for uploading the build package:

[distutils]
index-servers = local

[local]
repository: https://artifactory/api/repo/path
username: build_agent
password: ****

For security reasons I would like the username and password to never touch the disk. We already have a secure way of injecting secrets into the build environment from (Hashicorp) Vault, and I'd like to leverage this for the Artifactory credentials.

However, while I can set PIP_INDEX_URL for installing packages with pip, there is no equivalent for setuptools that I can see. Without these files defined, the command python setup.py sdist results in a stack trace the following error:

distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('local-package==0.0.3')

Clearly, it is attempting to resolve a local dependency on public pypi, which is undesirable for a number of reasons (the local repository proxies pypi, so we should never read public pypi to prevent hijacking).

Essentially then my question is; how can I build and upload a python package, which has dependencies in a local repository, to that local repository, using credentials that are in environment variables and not in ~/.pypirc or ~/.pydistutils.cfg?

Additional background

The original implementation baked .pypirc and .pydistutils.cfg in the build agent AMI, which is built with Packer.

The problem with this, is that the username and password for the repository is essentially readable in plain text by anyone with access to the AWS account and the ability to download or create a new instance using the image.

That's easy, just add a build step which sets up pypirc before starting the build you say! I would like to avoid this approach, because it is brittle in the sense that it creates a global run-time build dependency. In future, someone could setup a job assuming the config files have already been created without doing so themselves, and it will almost always work because another job has run first. I can't remove the file after each build, because there could be concurrent builds requiring the file to be present.

Body:
I've found a solution, but it's not particularly pretty.

First problem is setup_requires. Because it calls easy_install so early in the process, it's difficult to override; even creating a Distribution subclass and overriding the fetch_egg method didn't help. The workaround I've settled on for now is to wrap the setup method and preinstall them via pip (with PIP_INDEX_URL set):

from setuptools import setup

def _setup(**kwargs):
    requires = kwargs.get('setup_requires') or []

    for req in requires:
        pip.main(['install', req])

    return setup(**kwargs)

_setup(
    name='mypackage',
    ...
)

This is only needed for packages that specify local dependencies in setup_requires, and python setup.py install remains broken. As pip does the installation in tox (deps = .[test] in the [testenv] section) and never use setup.py to install, a broken install command isn't a problem.

The second problem was uploading. Rather than do the upload with setup.py upload, I'm shifting this task to twine. Recent versions of twine read TWINE_USERNAME, TWINE_PASSWORD, and TWINE_REPOSITORY_URL from the environment if they are not in the traditional config files.

Anyway, I would love to find a more elegant solution to the first problem, especially one that didn't leave setup.py install broken, but for now this will do.


来源: stackexchange

问:
How to execute delete raw query in codeigniter
I have sql query for delete multiple record from database </p>

```<code>$sql="delete from users where id IN(4,5,6..)";
</code>```

<p>How to run this query in codeigniter </p>

答:
Create a function in you model

```<code>function rowDelete($ids)
{
   $this->db->where_in('id', $ids);
   $this->db->delete('testimonials');
}
</code>```

And call that in your controller

```<code>$this->your_model->rowDelete($ids) // $ids = array(4,5,6);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have sql query for delete multiple record from database

$sql="delete from users where id IN(4,5,6..)";

How to run this query in codeigniter

Body:
Create a function in you model

function rowDelete($ids)
{
   $this->db->where_in('id', $ids);
   $this->db->delete('testimonials');
}

And call that in your controller

$this->your_model->rowDelete($ids) // $ids = array(4,5,6);


问:
finding child div id which is clicked in a div tag
I have code in html like

```<code><div id="edit" ng-click="editFunction($event)">
  <span id="1">
    click1
  </span>
  <span id="2">
    click2
  </span>
  <span id="3">
    click3
  </span>
  <span id="4">
    click4
  </span>
  ....
</div>
</code>```

in controller.js

```<code>myDIV.controller('control',function($scope){
 $scope.editFunction($event){
   alert($event.target.id);
}

});
</code>```

When user clicks in the div tag he should click on any of the span tags. Using the code we are able to get the div id.
But actually I need to know which span is clicked. Means id="1" or 2 or 3 ...
Thank you.

答:
you can use clickevent, this might work:</p>

```<code>    <div id="edit" ng-click="editFunction($event)">
  <span id="1" class="click">
    click1
  </span>
  <span id="2" class="click">
    click2
  </span>
  <span id="3" class="click">
    click3
  </span>
  <span id="4" class="click">
    click4
  </span>
  ....
</div>

    $('.click').on('click', function(event) {
    alert($(event.target).attr('id'));
    });
</code>```

Body:
I have code in html like

    click1

    click2

    click3

    click4

  ....

in controller.js

myDIV.controller('control',function($scope){
 $scope.editFunction($event){
   alert($event.target.id);
}

});

When user clicks in the div tag he should click on any of the span tags. Using the code we are able to get the div id.
But actually I need to know which span is clicked. Means id="1" or 2 or 3 ...
Thank you.

Body:
you can use clickevent, this might work:

    <div id="edit" ng-click="editFunction($event)">
  <span id="1" class="click">
    click1
  </span>
  <span id="2" class="click">
    click2
  </span>
  <span id="3" class="click">
    click3
  </span>
  <span id="4" class="click">
    click4
  </span>
  ....
</div>

    $('.click').on('click', function(event) {
    alert($(event.target).attr('id'));
    });


问:
Can I deploy COTS application in Openshift Container
I need to migrate my on-premise applications to Openshift Containers that will be hosted in AWS IaaS environment. When looking for possibilities of hosting COTS (Commercial off the shelf) applications in Openshift Containers, I am unable to reach a solution.
Can you please share your knowledge and if possible, any use-case, sample procedure. </p>

答:
Take a look at OpenShift Primed for the Red Hat certified ISV programme:

https://hub.openshift.com/primed

Although re-reading your question it seems to be more around "can I containerise my existing application".  Which is something relatively straightforward to do technically, but you will need to check with the vendor on the support and licensing conditions for this.


问:
The server was unable to process the request due to an internal error. in WCF error
I have written my service in framework 4.0 using C#. It's an simple method which returns a value

The Web.config is like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <machineKey validationKey="0E1F430D6FFFA91FBEDAEC1D2DDAAC2127EB055DBAFB78328C5BDE83249A94EA66400453B" decryptionKey="A13EACEAAABBECF2D06619924A8" validation="SHA1" decryption="AES" />
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="DecryptCookie.Service1">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8732/Design_Time_Addresses/WCFandEFService/ProductService/" />
          </baseAddresses>
        </host>
        <endpoint address=""  binding="wsHttpBinding"    contract="DecryptCookie.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract = "IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
</code>```

When I try to consume the service, I am getting an error like this:

```<code>Error: The server was unable to process the request due to an internal error.
For more information about the error, either turn on
IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from
the configuration behavior) on the server in   order to send the exception
information back to the client, or turn on tracing as per the Microsoft .NET
Framework 3.0 SDK documentation and inspect the server trace
logs.System.Exception {System.ServiceModel.FaultException}
</code>```

I am not sure what the problem is.

答:
you can try adding diagnostics your web.config file to get logs:

```<code> <system.diagnostics>
      <sources>
        <source name="System.ServiceModel"
                switchValue="All"
                propagateActivity="true">
          <listeners>
            <add name="traceListener"
                type="System.Diagnostics.XmlWriterTraceListener"
                initializeData= "D:\AppLogs\Traces.svclog" />
          </listeners>
        </source>
      </sources>
    </system.diagnostics>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have written my service in framework 4.0 using C#. It's an simple method which returns a value

The Web.config is like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <machineKey validationKey="0E1F430D6FFFA91FBEDAEC1D2DDAAC2127EB055DBAFB78328C5BDE83249A94EA66400453B" decryptionKey="A13EACEAAABBECF2D06619924A8" validation="SHA1" decryption="AES" />
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="DecryptCookie.Service1">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8732/Design_Time_Addresses/WCFandEFService/ProductService/" />
          </baseAddresses>
        </host>
        <endpoint address=""  binding="wsHttpBinding"    contract="DecryptCookie.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract = "IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

When I try to consume the service, I am getting an error like this:

Error: The server was unable to process the request due to an internal error.
For more information about the error, either turn on
IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from
the configuration behavior) on the server in   order to send the exception
information back to the client, or turn on tracing as per the Microsoft .NET
Framework 3.0 SDK documentation and inspect the server trace
logs.System.Exception {System.ServiceModel.FaultException}

I am not sure what the problem is.

Body:
you can try adding diagnostics your web.config file to get logs:

 <system.diagnostics>
      <sources>
        <source name="System.ServiceModel"
                switchValue="All"
                propagateActivity="true">
          <listeners>
            <add name="traceListener"
                type="System.Diagnostics.XmlWriterTraceListener"
                initializeData= "D:\AppLogs\Traces.svclog" />
          </listeners>
        </source>
      </sources>
    </system.diagnostics>


问:
How to handle sql rollback function in php
The following is my code to insert the personal and address details of an employee in SQL database:

```<code><?php
include_once 'config.php';

$name = $_POST['name'];
$age = $_POST['age'];
$salary = $_POST['salary'];
$street = $_POST['street'];
$area = $_POST['area'];
$city = $_POST['city'];
$nation = $_POST['nation'];

//Inserts the personal details.
$personal_details = "INSERT INTO `tbl_personal_details`(`pk_emp_id`, `name`, `age`, `salary`)"
        . " VALUES (NULL,'$name', '$age', $salary')";

if ($conn->query($personal_details)) {
    $fk_emp_id = mysqli_insert_id($conn);

    //Inserts the address details.
    $address_details = "INSERT INTO `tbl_address_details`(`pk_add_id`,`fk_emp_id`, `street`, `area`, `city`, `nation`)"
            . " VALUES (NULL,'$fk_emp_id','$street','$area', '$city', $nation')";
    if ($conn->query($address_details)) {
        echo "Employee successflly added.";
    } else {
        //Rolls back the personal details if error in inserting the address details.
        $personal_details->rollback();
        echo "Error in inserting the address values. " . $conn->error;
    }
} else {
    echo "Error in inserting the personal details." . $conn->error;
}
?>
</code>```

Is this the right way of inserting the data of an employee into the database.
And if so, is my rollback function correct to handle the error while inserting the address details of the employee.

Any help would be great.
Thanks in advance.

答: A common error condition would be that the record does not insert due to data errors. I don't see a place where any SQL errors are trapped and piped to a file, or displayed on the screen.  There's the potential for errors based on existing records, PK or FK is not unique.... You need to capture those errors so you can either diagnose a problem, or clean your data.  </p>

Body:
The following is my code to insert the personal and address details of an employee in SQL database:

<?php
include_once 'config.php';

$name = $_POST['name'];
$age = $_POST['age'];
$salary = $_POST['salary'];
$street = $_POST['street'];
$area = $_POST['area'];
$city = $_POST['city'];
$nation = $_POST['nation'];

//Inserts the personal details.
$personal_details = "INSERT INTO `tbl_personal_details`(`pk_emp_id`, `name`, `age`, `salary`)"
        . " VALUES (NULL,'$name', '$age', $salary')";

if ($conn->query($personal_details)) {
    $fk_emp_id = mysqli_insert_id($conn);

    //Inserts the address details.
    $address_details = "INSERT INTO `tbl_address_details`(`pk_add_id`,`fk_emp_id`, `street`, `area`, `city`, `nation`)"
            . " VALUES (NULL,'$fk_emp_id','$street','$area', '$city', $nation')";
    if ($conn->query($address_details)) {
        echo "Employee successflly added.";
    } else {
        //Rolls back the personal details if error in inserting the address details.
        $personal_details->rollback();
        echo "Error in inserting the address values. " . $conn->error;
    }
} else {
    echo "Error in inserting the personal details." . $conn->error;
}
?>

Is this the right way of inserting the data of an employee into the database.
And if so, is my rollback function correct to handle the error while inserting the address details of the employee.

Any help would be great.
Thanks in advance.


问:
Highchart to show progress percentages in horizontal bars with real time data?
I want to display the progress of completion of different subjects on a single chart ,where the data of this progress would be fetched in real time from the database .
This progress would be in terms of percentages and i want it to be plotted as horizontal bars. something like this:

I have tried this :

```<code>    <ChartAreas>
        <asp:ChartArea Name="ChartArea1">
            <AxisX Title="Subject Code" IsLabelAutoFit="True" >
            <LabelStyle Angle="-90" Interval="1" />
                <MajorGrid Enabled="false" />
            </AxisX>
            <AxisY Title="Progress %" Interval="10" IsLabelAutoFit="True" >

                <MajorGrid Enabled="false" />
            </AxisY>
        </asp:ChartArea>
    </ChartAreas>
</code>```

code-behind:

```<code>     if (!IsPostBack)
        {
            Chart5.Visible = true;
            connection.Open();
            DataTable dt = new DataTable();

            SqlCommand cmd = new SqlCommand("select distinct sub_code from [dbname].[dbo].[xyz]",connection);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);

            foreach (DataRow row in dt.Rows)
            {
                sub_code = row["sub_code"].ToString();
                SqlCommand cmd1 = new SqlCommand("select  checked_percent, unchecked_percent From(select COUNT(*) * 100.0 / (select count(*)from[xyz].[dbo].[xyz] where sub_code = @sub_code) as checked_percent from[dbname].[dbo].[xyz]  where CheckBy is not null and sub_code = @sub_code )checked,(select COUNT(*) * 100.0 / (select count(*)from[dbname].[dbo].[xyz] where sub_code = @sub_code)as unchecked_percent from[dbname].[dbo].[xyz]  where CheckBy is  null and sub_code = @sub_code)unchecked", connection);
                cmd1.Parameters.AddWithValue("@sub_code", sub_code);

                SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
                DataSet ds = new DataSet();
                da1.Fill(ds);

                DataTable ChartData = ds.Tables[0];
                Chart5.DataSource = ChartData;
                Chart5.Series[0].Points.DataBind(ChartData.DefaultView, "sub_code");

                DataPoint dp = new DataPoint(0, Convert.ToDouble(ChartData.Rows[0]["unchecked_percent"]));
                dp.Label = string.Format("unchecked\n{0:0.00}%", ChartData.Rows[0]["unchecked_percent"]);
                Chart5.Series[0].Points.Add(dp);

                dp = new DataPoint(0, Convert.ToDouble(ChartData.Rows[0]["checked_percent"]));
                dp.Label = string.Format("checked\n{0:0.00}%", ChartData.Rows[0]["checked_percent"]);
                Chart5.Series[1].Points.Add(dp);
                connection.Close();

            }

        }
</code>```

I need the y-axis to display the sub_codes but not getting that.

答:
In Highcharts I'd follow these steps:

Create two percentage stacked bar series (stacking: percent). The first one will hold the actual value (e.g. 78) and the second one will be the difference between the first one and 100 (e.g. 22).

Disable tooltip for the second series using this code in options: tooltip.pointFormat: false

Configure dataLabels so that the're on the right side of the bars and they show the percent sign along with the number.

To understand live updating in Highcharts see the charts from Dynamic charts section of this page: https://www.highcharts.com/demo

API references:

https://api.highcharts.com/highcharts/plotOptions.series.stacking

https://api.highcharts.com/highcharts/series.bar.dataLabels

https://api.highcharts.com/highcharts/series.bar.tooltip.pointFormat

Body:
I want to display the progress of completion of different subjects on a single chart ,where the data of this progress would be fetched in real time from the database .
This progress would be in terms of percentages and i want it to be plotted as horizontal bars. something like this:

I have tried this :

    <ChartAreas>
        <asp:ChartArea Name="ChartArea1">
            <AxisX Title="Subject Code" IsLabelAutoFit="True" >
            <LabelStyle Angle="-90" Interval="1" />
                <MajorGrid Enabled="false" />
            </AxisX>
            <AxisY Title="Progress %" Interval="10" IsLabelAutoFit="True" >

                <MajorGrid Enabled="false" />
            </AxisY>
        </asp:ChartArea>
    </ChartAreas>

code-behind:

     if (!IsPostBack)
        {
            Chart5.Visible = true;
            connection.Open();
            DataTable dt = new DataTable();

            SqlCommand cmd = new SqlCommand("select distinct sub_code from [dbname].[dbo].[xyz]",connection);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);

            foreach (DataRow row in dt.Rows)
            {
                sub_code = row["sub_code"].ToString();
                SqlCommand cmd1 = new SqlCommand("select  checked_percent, unchecked_percent From(select COUNT(*) * 100.0 / (select count(*)from[xyz].[dbo].[xyz] where sub_code = @sub_code) as checked_percent from[dbname].[dbo].[xyz]  where CheckBy is not null and sub_code = @sub_code )checked,(select COUNT(*) * 100.0 / (select count(*)from[dbname].[dbo].[xyz] where sub_code = @sub_code)as unchecked_percent from[dbname].[dbo].[xyz]  where CheckBy is  null and sub_code = @sub_code)unchecked", connection);
                cmd1.Parameters.AddWithValue("@sub_code", sub_code);

                SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
                DataSet ds = new DataSet();
                da1.Fill(ds);

                DataTable ChartData = ds.Tables[0];
                Chart5.DataSource = ChartData;
                Chart5.Series[0].Points.DataBind(ChartData.DefaultView, "sub_code");

                DataPoint dp = new DataPoint(0, Convert.ToDouble(ChartData.Rows[0]["unchecked_percent"]));
                dp.Label = string.Format("unchecked\n{0:0.00}%", ChartData.Rows[0]["unchecked_percent"]);
                Chart5.Series[0].Points.Add(dp);

                dp = new DataPoint(0, Convert.ToDouble(ChartData.Rows[0]["checked_percent"]));
                dp.Label = string.Format("checked\n{0:0.00}%", ChartData.Rows[0]["checked_percent"]);
                Chart5.Series[1].Points.Add(dp);
                connection.Close();

            }

        }

I need the y-axis to display the sub_codes but not getting that.


问:
.htaccess issue in wordpress 4.8.2
I am having images issue in my Wordpress version 4.8.2.

There is an .htaccess file in wp-content folder public_html/wp-content/.htaccess. When I rename or delete this file images work fine but the site breaks down

.htaccess

```<code> # BEGIN WordPress
  <IfModule mod_rewrite.c>
     RewriteEngine On
     RewriteBase /
     RewriteRule ^index\.php$ - [L]
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule . /index.php [L]
  </IfModule>
# END WordPress

php_value upload_max_filesize 128M
php_value post_max_size 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value memory_limit 256M
</code>```

答: .htaccess will be on root not in wp-content folder . it should be in public_html</p>

Title: .htaccess issue in wordpress 4.8.2

Body:
I am having images issue in my Wordpress version 4.8.2.

There is an .htaccess file in wp-content folder public_html/wp-content/.htaccess. When I rename or delete this file images work fine but the site breaks down

.htaccess

 # BEGIN WordPress
  <IfModule mod_rewrite.c>
     RewriteEngine On
     RewriteBase /
     RewriteRule ^index\.php$ - [L]
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule . /index.php [L]
  </IfModule>
# END WordPress

php_value upload_max_filesize 128M
php_value post_max_size 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value memory_limit 256M


问:
How to pass a dynamic value in angular2-counto
I'm using the following library:

https://github.com/izupet/angular2-counto

I'm getting an error when I pass a dynamic value.

So in my component app.component.html:

If I use interpolation:

```<code><div counto [step]="30" [countTo]="'{{value}}'" [countFrom]="0 [duration]="4" (countoChange)="counto = $event" (countoEnd)="onCountoEnd()">{{counto | currency:'EUR':true:'1.2-2'}}</div>
</code>```

I get an error related with the double braces syntax:

```<code>[countTo]="'{{value}}'"
</code>```

Otherwise, without them it works:

```<code> [countTo]="10"
</code>```

Here for [countTo] attribute passing the value from component.

For app.component.ts

```<code>export class AppComponent {

  value=10;

}
</code>```

答:
The correct sintax is:

[countTo]="value"

without {{}} and without single quotes

This is because, countTo Input from library extects a number.

Body:
I'm using the following library:

https://github.com/izupet/angular2-counto

I'm getting an error when I pass a dynamic value.

So in my component app.component.html:

If I use interpolation:

{{counto | currency:'EUR':true:'1.2-2'}}

I get an error related with the double braces syntax:

[countTo]="'{{value}}'"

Otherwise, without them it works:

 [countTo]="10"

Here for [countTo] attribute passing the value from component.

For app.component.ts

export class AppComponent {

  value=10;

}


问:
In JavaScript, how to conditionally add a member to an object?
I would like to create an object with a member added conditionally.
The simple approach is:

```<code>var a = {};
if (someCondition)
    a.b = 5;
</code>```

Now, I would like to write a more idiomatic code. I am trying:

```<code>a = {
    b: (someCondition? 5 : undefined)
};
</code>```

But now, b is a member of a whose value is undefined. This is not the desired result.

Is there a handy solution?

Update

I seek for a solution that could handle the general case with several members.

```<code>a = {
  b: (conditionB? 5 : undefined),
  c: (conditionC? 5 : undefined),
  d: (conditionD? 5 : undefined),
  e: (conditionE? 5 : undefined),
  f: (conditionF? 5 : undefined),
  g: (conditionG? 5 : undefined),
 };
</code>```

答:
What about using Enhanced Object Properties and only set the property if it is truthy, e.g.:

```<code>[isConditionTrue() && 'propertyName']: 'propertyValue'
</code>```

So if the condition is not met it doesn't create the preferred property and thus you can discard it.
See: http://es6-features.org/#ComputedPropertyNames

UPDATE:
It is even better to follow the approach of Axel Rauschmayer in his blog article about conditionally adding entries inside object literals and arrays (http://2ality.com/2017/04/conditional-literal-entries.html):

```<code>const arr = [
  ...(isConditionTrue() ? [{
    key: 'value'
  }] : [])
];

const obj = {
  ...(isConditionTrue() ? {key: 'value'} : {})
};
</code>```

Quite helped me a lot.

Body:
I would like to create an object with a member added conditionally.
The simple approach is:

var a = {};
if (someCondition)
    a.b = 5;

Now, I would like to write a more idiomatic code. I am trying:

a = {
    b: (someCondition? 5 : undefined)
};

But now, b is a member of a whose value is undefined. This is not the desired result.

Is there a handy solution?

Update

I seek for a solution that could handle the general case with several members.

a = {
  b: (conditionB? 5 : undefined),
  c: (conditionC? 5 : undefined),
  d: (conditionD? 5 : undefined),
  e: (conditionE? 5 : undefined),
  f: (conditionF? 5 : undefined),
  g: (conditionG? 5 : undefined),
 };

Body:
What about using Enhanced Object Properties and only set the property if it is truthy, e.g.:

[isConditionTrue() && 'propertyName']: 'propertyValue'

So if the condition is not met it doesn't create the preferred property and thus you can discard it.
See: http://es6-features.org/#ComputedPropertyNames

UPDATE:
It is even better to follow the approach of Axel Rauschmayer in his blog article about conditionally adding entries inside object literals and arrays (http://2ality.com/2017/04/conditional-literal-entries.html):

const arr = [
  ...(isConditionTrue() ? [{
    key: 'value'
  }] : [])
];

const obj = {
  ...(isConditionTrue() ? {key: 'value'} : {})
};

Quite helped me a lot.


问:
Reading SMS using Appium on Android
I am trying to automated a flow where I can read sms and then parse the SMS to read the OTP and enter it in another webapp. Looked through all forums but couldn't find an answer.

I am writing code in java and trying to run a webapp on android device using appium.

Can someone suggest how to do it?

答:
If you want to read sms from device in Appium session there is a good approach described in discuss.appium.io

I think you can create several sessions in one test: 1 - to get sms with native app, 2 - open webApp in mobile browser and do whatever you need

Title: Reading SMS using Appium on Android


问:
jQuery Template - Executing JS code inside the template
I am trying to learn more about jQuery templates but cant seem to execute any JS calls inside the template.

```<code><script id="log-item" type="text/x-jquery-tmpl">
 {{if title.length }}
   <h3 style="padding-bottom:5px;">${ title }</h3>
 {{/if}}
 objectToString(${ detail });
</script>
</code>```

Note that my objectToString() function is never called, just rendered out as a string.  I tried wrapping it in {{ }} on a whim but no luck.  Anyone out there who can help?

答:
I am not sure where you have your objectToString is located, but if you see the reference here, you see them adding the necessary helper function into the .tmpl( method).

Here is an example... I tried to make it similar to what you have in the question...

```<code><!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Test jquery Templates</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
  <script type='text/javascript' src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>
  <script id="testTemplate" type="text/x-jquery-tmpl">
    {{if title.length}}
      <h3>${title}</h3>
      <p>Detail: ${$item.objectToString("detail")}</p>
    {{/if}}
  </script>
  <div id="bookList"></div>
  <script type='text/javascript'>
    $(function(){
      var book = [
        { title: "Goodnight, World!",
          detail: { author: "Jojo Mojo", synopsis : "What the ..." }},
        { title: "Rainbow",
          detail: { author: "Cookie", synopsis : "Huh?" }}
      ];

      $("#testTemplate").tmpl(book, {
        objectToString : function(key) {
          var detail = this.data[key];
          return detail.author +  " " + detail.synopsis;
        }
      }).appendTo("#bookList");
  });
  </script>
</body>
</html>
</code>```

You can see it here.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to learn more about jQuery templates but cant seem to execute any JS calls inside the template.

Note that my objectToString() function is never called, just rendered out as a string.  I tried wrapping it in {{ }} on a whim but no luck.  Anyone out there who can help?

Body:
I am not sure where you have your objectToString is located, but if you see the reference here, you see them adding the necessary helper function into the .tmpl( method).

Here is an example... I tried to make it similar to what you have in the question...

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Test jquery Templates</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
  <script type='text/javascript' src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>
  <script id="testTemplate" type="text/x-jquery-tmpl">
    {{if title.length}}
      <h3>${title}</h3>
      <p>Detail: ${$item.objectToString("detail")}</p>
    {{/if}}
  </script>
  <div id="bookList"></div>
  <script type='text/javascript'>
    $(function(){
      var book = [
        { title: "Goodnight, World!",
          detail: { author: "Jojo Mojo", synopsis : "What the ..." }},
        { title: "Rainbow",
          detail: { author: "Cookie", synopsis : "Huh?" }}
      ];

      $("#testTemplate").tmpl(book, {
        objectToString : function(key) {
          var detail = this.data[key];
          return detail.author +  " " + detail.synopsis;
        }
      }).appendTo("#bookList");
  });
  </script>
</body>
</html>

You can see it here.


问:
Class component is rerendering in loop
I'm trying to build a simple youtube app using youtube-api-search. There's two main portion of the app ie. VideoDetail & VideoList. VideoDetail is intended to show/play the video whereas VideoList is for displaying a list of five videos with their titles.

Now, the issue is, top section of my app ie. is getting re-rendered continuously inside a loop. I cant figure out why that is. I app is really simple it doesn't even have any lifecycle methods. Please help me to figure out the error.

App.js (It is imported into index.js where it gets rendered)

```<code>import React, { Component } from 'react';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';

const API_KEY = 'AIzaSyC----key------N7khtCs';

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      videos: [],
      selectedVideo: null
     };
     console.log('sth.');
    YTSearch({key: API_KEY, term: 'surfboards'}, (videos) => {
      this.setState({
        videos: videos,
        selectedVideo: videos[0]
      });
    });
  }

  render(){
    return (
      <div>
        {console.log('indexx')}

        <VideoDetail video={this.state.selectedVideo} />
        <VideoList
          onVideoSelect={selectedVideo => this.setState({selectedVideo})}
          videos={this.state.videos}
        />
      </div>
    );
  };
}

export default App;
</code>```

video_detail.js

```<code>import React from 'react';

const VideoDetail = ({video}) => {    //accesssing props elements direcly

    if(!video){
        return <div>Loading Details</div>;
    }

    const videoId = video.id.videoId;
    const url = `https//www.youtube.com/embed/${videoId}`;

    return (
        <div className="video-detail col-md-8">
            <div className="embed-responsive embed-responsive-16by9">
                <iframe className="embed-responsive-item" src={url}></iframe>
            </div>
            <div className="details">
                <div>{video.snippet.title}</div>
                <div>{video.snippet.description}</div>
            </div>
        </div>
    );
};

export default VideoDetail;
</code>```

video_list.js

```<code>import React from 'react';
import VideoListItem from './video_list_item';

const VideoList = props => {
    const videoItems = props.videos.map((video) => {
        console.log(video);
        return (
            <VideoListItem
                onVideoSelect={props.onVideoSelect}
                key={video.etag}
                video={video} />
            );
    });

    return (
        <ul className="col-md-4 list-group">
            {videoItems}
        </ul>
    );
};

export default VideoList;
</code>```

video_list_item.js

```<code>import React from 'react';

const VideoListItem = ({video, onVideoSelect}) => {    //pulling from props
    const imageUrl = video.snippet.thumbnails.default.url;

    return(
        <li onClick={() => onVideoSelect(video)} className="list-group-item">
            <div className="video-list media">
                <div className="media-left">
                    <img className="media-object" src={imageUrl} />
                </div>
                <div className="media-body">
                    <div className="media-heading">{video.snippet.title}</div>
                </div>
            </div>
        </li>
    );
}

export default VideoListItem;
</code>```

Someone, please explain me what is the issue here. I want to understand.

答:
Finally figured out the issue:

I was because : was not present in the url.

const url = https://www.youtube.com/embed/${videoId};

Title: Class component is rerendering in loop

Body:
I'm trying to build a simple youtube app using youtube-api-search. There's two main portion of the app ie. VideoDetail & VideoList. VideoDetail is intended to show/play the video whereas VideoList is for displaying a list of five videos with their titles.

Now, the issue is, top section of my app ie. is getting re-rendered continuously inside a loop. I cant figure out why that is. I app is really simple it doesn't even have any lifecycle methods. Please help me to figure out the error.

App.js (It is imported into index.js where it gets rendered)

import React, { Component } from 'react';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';

const API_KEY = 'AIzaSyC----key------N7khtCs';

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      videos: [],
      selectedVideo: null
     };
     console.log('sth.');
    YTSearch({key: API_KEY, term: 'surfboards'}, (videos) => {
      this.setState({
        videos: videos,
        selectedVideo: videos[0]
      });
    });
  }

  render(){
    return (

        {console.log('indexx')}

        <VideoDetail video={this.state.selectedVideo} />
        <VideoList
          onVideoSelect={selectedVideo => this.setState({selectedVideo})}
          videos={this.state.videos}
        />

    );
  };
}

export default App;

video_detail.js

import React from 'react';

const VideoDetail = ({video}) => {    //accesssing props elements direcly

    if(!video){
        return
Loading Details
;
    }

    const videoId = video.id.videoId;
    const url = `https//www.youtube.com/embed/${videoId}`;

    return (

{video.snippet.title}

{video.snippet.description}

    );
};

export default VideoDetail;

video_list.js

import React from 'react';
import VideoListItem from './video_list_item';

const VideoList = props => {
    const videoItems = props.videos.map((video) => {
        console.log(video);
        return (
            <VideoListItem
                onVideoSelect={props.onVideoSelect}
                key={video.etag}
                video={video} />
            );
    });

    return (

            {videoItems}

    );
};

export default VideoList;

video_list_item.js

import React from 'react';

const VideoListItem = ({video, onVideoSelect}) => {    //pulling from props
    const imageUrl = video.snippet.thumbnails.default.url;

    return(

 onVideoSelect(video)} className="list-group-item">

{video.snippet.title}

    );
}

export default VideoListItem;

Someone, please explain me what is the issue here. I want to understand.


问:
Convert XML to Json Array when only one object Java
I have one XML which i need to convert to JSON when in XML we have more than one element its creating proper jsonArray but when single element not creating the array can any one please help me how we can get array in case of single element

```<code>String TEST_XML_STRING = "<Items><Item><Name>Stack</Name><Name>OverFlow</Name></Item></Items>";
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
// output - {"Items":{"Item":{"Name":["Stack","OverFlow"]}}}
</code>```

when

```<code>String TEST_XML_STRING = "<Items><Item><Name>Stack</Name></Item></Items>";
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
// output - {"Items":{"Item":{"Name":"Stack"}}}
</code>```

but it should be {"Items":{"Item":[{"Name":"Stack"}]}}

答:
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

It's available on Maven Central.

Example

```<code>import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj("/Items/Item")
        .attribute("name", "Name")
        .build();

    ObjectNode result = parser.apply(document);
    return result;
  }
}
</code>```

It will return a Jackson ObjectNode, with the following json:

```<code>{"name":"Stack"}
</code>```

You can also create a parser that will return nested ObjectNodes or ArrayNodes to whatever JSON structure you desire.

Body:
I have one XML which i need to convert to JSON when in XML we have more than one element its creating proper jsonArray but when single element not creating the array can any one please help me how we can get array in case of single element

String TEST_XML_STRING = "<Items><Item><Name>Stack</Name><Name>OverFlow</Name></Item></Items>";
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
// output - {"Items":{"Item":{"Name":["Stack","OverFlow"]}}}

when

String TEST_XML_STRING = "<Items><Item><Name>Stack</Name></Item></Items>";
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
// output - {"Items":{"Item":{"Name":"Stack"}}}

but it should be {"Items":{"Item":[{"Name":"Stack"}]}}

Body:
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

It's available on Maven Central.

Example

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj("/Items/Item")
        .attribute("name", "Name")
        .build();

    ObjectNode result = parser.apply(document);
    return result;
  }
}

It will return a Jackson ObjectNode, with the following json:

{"name":"Stack"}

You can also create a parser that will return nested ObjectNodes or ArrayNodes to whatever JSON structure you desire.


问:
Need help in validating 50 fields in JSON
I have a JSON file with almost 50 fields in it and I need to validate each one of them through automation. Also I have the test data for all 50 fields to be validated in an excel sheet. </p>

<p>The logic I am stuck here is I cannot place all 50 field's data in the excel cells since it will make my sheet look bulk. Any suggestions on how I can validate this ? </p>

答: Can you use Python/Java/C# etc to directly read the excel sheet (or export the excel sheet to a CSV file) then write code to validate the JSON against the read data?  You don't have to put the validation result back into the excel sheet, do you?</p>

Body:
I have a JSON file with almost 50 fields in it and I need to validate each one of them through automation. Also I have the test data for all 50 fields to be validated in an excel sheet.

The logic I am stuck here is I cannot place all 50 field's data in the excel cells since it will make my sheet look bulk. Any suggestions on how I can validate this ?


问:
VBA Excel TimeValue() input possibilities
new here. Read a lot of topics but really can't figure this out.
I'm converting a string from a userform textbox to a double, representing a time. Current code works pretty good:

```<code>Dim startingTime As Double, endingTime As Double
Dim totalTime As Double
On Error Resume Next
With textbox_inMyUserform
TimeValue(.Value)
    If Err.Number <> 0 Then
        startingTime = CDbl(.Value)
        Err.Clear
        On Error GoTo 0
    Else
        On Error GoTo 0
        startingTime = 24 * TimeValue(.Value)
    End If
End With
</code>```

the TimeValue(.value) checks if the format is correct. No error means that function is used in else, an error makes the if run a normal Cdbl(.value).

Works great, except... decimals apparantly don't trigger an error. "5" becomes 5 because of an error on TimeValue, "5:30" becomes 5,5 because no error on TimeValue but "5.5" and "5,5" don't trigger errors giving respective results of 5.0833333 and 0 through the TimeValue(.value). I expect errors on those strings?

My solution now would be to just not use decimals, but I wan't to know what's wrong.

Thanks.

update

So based on the answer of Slai I got it to work. Apparently TimeValue() in VBA and TIMEVALUE() inside of excel behave differently. Also I put my originally planned 'if not IsError()' back in.

```<code>Dim startingTime As Double, endingTime As Double
Dim totalTime As Double
With textbox_starttijd
    If Not IsError(Evaluate("TIMEVALUE(""" & .Value & """)")) Then
        startingTime = 24 * TimeValue(.Value)
    ElseIf .Value <> vbNullString Then
        startingTime = CDbl(.Value)
    Else
        startingTime = 0
    End If
End With
With textbox_eindtijd
    If Not IsError(Evaluate("TIMEVALUE(""" & .Value & """)")) Then
        endingTime = 24 * TimeValue(.Value)
    ElseIf .Value <> vbNullString Then
        endingTime = CDbl(.Value)
    Else
        endingTime = 0
    End If
End With
totalTime = endingTime - startingTime
</code>```

Update 2

might as well keep this code up to date: an empty textbox in the userform throws an error at 'CDbl(.value)' so I updated the code above with an ElseIf that checks against vbNullString and the Else sets my time to 0 so the string now is never empty.

答:
You can probably use the Excel TIMEVALUE function instead :

```<code>For Each s In Split("5:30 5.5 5,5 5 a")
    v = Evaluate("TIMEVALUE(""" & s & """)")
    Debug.Print s, IsNumeric(s), IsError(v), VarType(v), TypeName(v), v
Next
</code>```

results in:

```<code>s             IsNumeric(s)  IsError(v)    VarType(v)    TypeName(v)   v
5:30          False         False          5            Double         0.229166666666667
5.5           True          True           10           Error         Error 2015
5,5           True          True           10           Error         Error 2015
5             True          True           10           Error         Error 2015
a             False         True           10           Error         Error 2015
</code>```

Body:
new here. Read a lot of topics but really can't figure this out.
I'm converting a string from a userform textbox to a double, representing a time. Current code works pretty good:

Dim startingTime As Double, endingTime As Double
Dim totalTime As Double
On Error Resume Next
With textbox_inMyUserform
TimeValue(.Value)
    If Err.Number <> 0 Then
        startingTime = CDbl(.Value)
        Err.Clear
        On Error GoTo 0
    Else
        On Error GoTo 0
        startingTime = 24 * TimeValue(.Value)
    End If
End With

the TimeValue(.value) checks if the format is correct. No error means that function is used in else, an error makes the if run a normal Cdbl(.value).

Works great, except... decimals apparantly don't trigger an error. "5" becomes 5 because of an error on TimeValue, "5:30" becomes 5,5 because no error on TimeValue but "5.5" and "5,5" don't trigger errors giving respective results of 5.0833333 and 0 through the TimeValue(.value). I expect errors on those strings?

My solution now would be to just not use decimals, but I wan't to know what's wrong.

Thanks.

update

So based on the answer of Slai I got it to work. Apparently TimeValue() in VBA and TIMEVALUE() inside of excel behave differently. Also I put my originally planned 'if not IsError()' back in.

Dim startingTime As Double, endingTime As Double
Dim totalTime As Double
With textbox_starttijd
    If Not IsError(Evaluate("TIMEVALUE(""" & .Value & """)")) Then
        startingTime = 24 * TimeValue(.Value)
    ElseIf .Value <> vbNullString Then
        startingTime = CDbl(.Value)
    Else
        startingTime = 0
    End If
End With
With textbox_eindtijd
    If Not IsError(Evaluate("TIMEVALUE(""" & .Value & """)")) Then
        endingTime = 24 * TimeValue(.Value)
    ElseIf .Value <> vbNullString Then
        endingTime = CDbl(.Value)
    Else
        endingTime = 0
    End If
End With
totalTime = endingTime - startingTime

Update 2

might as well keep this code up to date: an empty textbox in the userform throws an error at 'CDbl(.value)' so I updated the code above with an ElseIf that checks against vbNullString and the Else sets my time to 0 so the string now is never empty.

Body:
You can probably use the Excel TIMEVALUE function instead :

For Each s In Split("5:30 5.5 5,5 5 a")
    v = Evaluate("TIMEVALUE(""" & s & """)")
    Debug.Print s, IsNumeric(s), IsError(v), VarType(v), TypeName(v), v
Next

results in:

s             IsNumeric(s)  IsError(v)    VarType(v)    TypeName(v)   v
5:30          False         False          5            Double         0.229166666666667
5.5           True          True           10           Error         Error 2015
5,5           True          True           10           Error         Error 2015
5             True          True           10           Error         Error 2015
a             False         True           10           Error         Error 2015


问:
Paste to virtual terminal
In a Ubuntu host system I have installed qemu and created a virtual machine with CentOS. The CentOS installation does not have an X server, just a virtual terminal. I would like to be able to copy strings from the host system to the virtual terminal of the virtual machine.

What I found so far is the suggestion to install spice-vdagent. If I understand correctly however, spice-vdagent requires an X server, which I don't have installed.

So, how can I paste strings to the virtual terminal (if possible at all)?

答:
You have to enable clipboard in your virtual machine manager software (VirtualBox or VmWare).

In Vbox you have to install Guest Additions iso. In VmWare you have to enable it in the virtual machine's options.

Title: Paste to virtual terminal


问:
PHPMailer: IsHTML is true, but fails
I have this code:

$mail->Host = gethostbyname('tls://'.$dados[1]->US_ENVIO_SMTP);

```<code>    $mail->Port = $dados[1]->US_ENVIO_PORTA;
    $mail->Username = $dados[1]->US_ENVIO_EMAIL;
    $mail->Password = $dados[1]->US_ENVIO_SENHA;
    $mail->SetFrom($dados[1]->US_ENVIO_EMAIL, $dados[1]->US_NOME);
    $mail->AddReplyTo($dados[1]->US_ENVIO_EMAIL, $dados[1]->US_NOME);
    $mail->Subject = $this->input->post('EM_ASSUNTO'); //Assunto do e-mail.
    $mail->Body = $css.$this->input->post("EM_DESCRICAO")."<br>".$this->input->post("EM_CONTEUDO");
    $mail->IsHTML(true);
</code>```

What I'm doing in $mail-> Body is set CSS and HTML.

The problem:

Gmail is receiving all code like this:

```<code>    <!--[if IE]><html xmlns="http://www.w3.org/1999/xhtml" class="ie-browser" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><![endif]--><!--[if !IE]><!--><!--<![endif]--> <!--[if gte mso 9]><xml> 96 </xml><![endif]--> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width"> <!--[if !mso]><!--><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--> <title>E-mail template 1</title> <style type="text/css" id="media-query"> body { margin: 0; padding: 0; } table, tr, td { vertical-align: top; border-collapse: collapse; } .ie-browser table, .mso-container table { table-layout: fixed; } * { line-height: inherit; } a[x-apple-data-detectors=true] { color: inherit !important; text-decoration: none !important; } [owa] .img-container div, [owa] .img-container button { display: block !important; } [owa] .fullwidth button { width: 100% !important; } .ie-browser .col, [owa] .block-grid .col { display: table-cell; float: none !important; vertical-align: top; } .ie-browser .num12, .ie-browser .block-grid, [owa] .num12, [owa] .block-grid { width: 500px !important; } .ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font, .ExternalClass td, .ExternalClass div { line-height: 100%; } .ie-browser .mixed-two-up .num4, [owa] .mixed-two-up .num4 { width: 164px !important; } .ie-browser .mixed-two-up .num8, [owa] .mixed-two-up .num8 { width: 328px !important; } .ie-browser .block-grid.two-up .col, [owa] .block-grid.two-up .col { width: 250px !important; } .ie-browser .block-grid.three-up .col, [owa] .block-grid.three-up .col { width: 166px !important; } .ie-browser .block-grid.four-up .col, [owa] .block-grid.four-up .col { width: 125px !important; } .ie-browser .block-grid.five-up .col, [owa] .block-grid.five-up .col { width: 100px !important; } .ie-browser .block-grid.six-up .col, [owa] .block-grid.six-up .col { width: 83px !important; } .ie-browser .block-grid.seven-up .col, [owa] .block-grid.seven-up .col { width: 71px !important; } .ie-browser .block-grid.eight-up .col, [owa] .block-grid.eight-up .col { width: 62px !important; } .ie-browser .block-grid.nine-up .col, [owa] .block-grid.nine-up .col { width: 55px !important; } .ie-browser .block-grid.ten-up .col, [owa] .block-grid.ten-up .col { width: 50px !important; } .ie-browser .block-grid.eleven-up .col, [owa] .block-grid.eleven-up .col { width: 45px !important; } .ie-browser .block-grid.twelve-up .col, [owa] .block-grid.twelve-up .col { width: 41px !important; } @media only screen and (min-width: 520px) { .block-grid { width: 500px !important; } .block-grid .col { display: table-cell; Float: none !important; vertical-align: top; } .block-grid .col.num12 { width: 500px !important; } .block-grid.mixed-two-up .col.num4 { width: 164px !important; } .block-grid.mixed-two-up .col.num8 { width: 328px !important; } .block-grid.two-up .col { width: 250px !important; } .block-grid.three-up .col { width: 166px !important; } .block-grid.four-up .col { width: 125px !important; } .block-grid.five-up .col { width: 100px !important; } .block-grid.six-up .col { width: 83px !important; } .block-grid.seven-up .col { width: 71px !important; } .block-grid.eight-up .col { width: 62px !important; } .block-grid.nine-up .col { width: 55px !important; } .block-grid.ten-up .col { width: 50px !important; } .block-grid.eleven-up .col { width: 45px !important; } .block-grid.twelve-up .col { width: 41px !important; } } @media (max-width: 520px) { .block-grid, .col { min-width: 320px !important; max-width: 100% !important; } .block-grid { width: calc(100% - 40px) !important; } .col { width: 100% !important; } .col > div { margin: 0 auto; } img.fullwidth { max-width: 100% !important; } } </style> <!--[if mso]> <body class="mso-container" style="background-color:#FFFFFF;"> <![endif]--> <!--[if !mso]><!--> <!--<![endif]-->
<!--[if (mso)|(IE)]>
<![endif]-->
<!--[if (mso)|(IE)]>
<![endif]--> <!--[if (mso)|(IE)]>   <![endif]-->
<!--[if (!mso)&(!IE)]><!-->
<!--<![endif]-->
<!--[if mso]>
<![endif]--> Image <!--[if mso]>
<![endif]-->
<!--[if (!mso)&(!IE)]><!-->
<!--<![endif]-->
<!--[if (mso)|(IE)]>    <![endif]-->
<!--[if (!mso)&(!IE)]><!-->
<!--<![endif]--> <!--[if mso]>
<![endif]-->
(51) 9991-2580
<!--[if mso]>
<![endif]--> <!--[if (!mso)&(!IE)]><!-->
<!--<![endif]-->
<!--[if (mso)|(IE)]>
<![endif]-->
<!--[if (mso)|(IE)]>
<![endif]--> <!--[if (mso)|(IE)]>   <![endif]-->
<!--[if (!mso)&(!IE)]><!-->
<!--<![endif]-->   <!--[if (!mso)&(!IE)]><!-->
<!--<![endif]-->
<!--[if (mso)|(IE)]>
</code>```

Anyone had this problem?

答:
The problem was getting body with:

```<code>$body = $this->input->post('html_field');
</code>```

That can be fixed by using:

```<code>$body = $_POST['html_field'];
</code>```

If you use Codeigniter or similar, that can also help you.

Title: PHPMailer: IsHTML is true, but fails

Body:
I have this code:

$mail->Host = gethostbyname('tls://'.$dados[1]->US_ENVIO_SMTP);

    $mail->Port = $dados[1]->US_ENVIO_PORTA;
    $mail->Username = $dados[1]->US_ENVIO_EMAIL;
    $mail->Password = $dados[1]->US_ENVIO_SENHA;
    $mail->SetFrom($dados[1]->US_ENVIO_EMAIL, $dados[1]->US_NOME);
    $mail->AddReplyTo($dados[1]->US_ENVIO_EMAIL, $dados[1]->US_NOME);
    $mail->Subject = $this->input->post('EM_ASSUNTO'); //Assunto do e-mail.
    $mail->Body = $css.$this->input->post("EM_DESCRICAO")."
".$this->input->post("EM_CONTEUDO");
    $mail->IsHTML(true);

What I'm doing in $mail-> Body is set CSS and HTML.

The problem:

Gmail is receiving all code like this:

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>E-mail template 1</title>

 Image

(51) 9991-2580

Body:
The problem was getting body with:

$body = $this->input->post('html_field');

That can be fixed by using:

$body = $_POST['html_field'];

If you use Codeigniter or similar, that can also help you.


问:
Get the number of lines of code in a R script
I would like to know if there is a way to count the number of lines in a R script.

Ignoring lines of comment.

I didn't find a solution on the Internet. But maybe I missed something.

答:
Example sctipt tester.R with 8 lines, one commented:

```<code>x <- 3
x+1

x+2

#x+4

x*x
</code>```

Function to count lines without comments:

```<code>foo <- function(path) {
  rln <- read_lines(path)
  rln <- rln[-grep(x = trimws(rln) , pattern = '^#')]
  rln <- rln[ trimws(rln) != '']
  return(length(rln))
}
</code>```

Test run:

```<code>> foo('tester.R')
[1] 7
</code>```

Body:
Example sctipt tester.R with 8 lines, one commented:

x <- 3
x+1

x+2

#x+4

x*x

Function to count lines without comments:

foo <- function(path) {
  rln <- read_lines(path)
  rln <- rln[-grep(x = trimws(rln) , pattern = '^#')]
  rln <- rln[ trimws(rln) != '']
  return(length(rln))
}

Test run:

> foo('tester.R')
[1] 7


问:
How to update variable in IO/access variable made in if statement in haskell
I have some code where I create an object at the beginning. Then I want to run various updates on the object depending on different commands.

```<code>main = do
    putStrLn "Enter command, c x y, d x y"
    s <- getLine
    let object = newObject
    if head s == 'c' then
        let object2 = updateObject object s in
        print object
    else if head s == 'd' then
        let object2 = updateObject object s in
        print object
    else do
        print "Error, try again"
        main
    putStrLn "Enter new command"
    c <- getLine
    print $ updateObject object2 c
</code>```

Error:

```<code>Variable not in scope: object2 :: Object
</code>```

How do I make the object "global" for the main function so that changes done to the object inside the if statements can be used later?

How can I do this in a better way?

答:
Don't try to do too much in main, if and else logic shouldn't exist there. Move all that stuff to a different function and keep main clean and easy.
The if and else logic I use here is valid because it is directly related to the flow of the appliation, rather than a domain choice (i.e. domain = should I update via this function or this function vs application = is this input I got valid for my program, should I terminate or not).

Try this:

```<code>    main = do
        putStrLn "Enter command, c x y, d x y"
        s <- getLine
        if not $ validateInput s then
             print "Error, try again"
             main
        else do
            let object = newObject
            updateObject object s
            print object

updateObject :: a -> String -> a
updateObject object s
          | head s == 'c' = --do updates here
          | head s == 's' = --do updates here
</code>```

Also try to create a console loop so you can easier deal with "Enter new Command" situations. Move away from main as soon as you can.

Body:
I have some code where I create an object at the beginning. Then I want to run various updates on the object depending on different commands.

main = do
    putStrLn "Enter command, c x y, d x y"
    s <- getLine
    let object = newObject
    if head s == 'c' then
        let object2 = updateObject object s in
        print object
    else if head s == 'd' then
        let object2 = updateObject object s in
        print object
    else do
        print "Error, try again"
        main
    putStrLn "Enter new command"
    c <- getLine
    print $ updateObject object2 c

Error:

Variable not in scope: object2 :: Object

How do I make the object "global" for the main function so that changes done to the object inside the if statements can be used later?

How can I do this in a better way?

Body:
Don't try to do too much in main, if and else logic shouldn't exist there. Move all that stuff to a different function and keep main clean and easy.
The if and else logic I use here is valid because it is directly related to the flow of the appliation, rather than a domain choice (i.e. domain = should I update via this function or this function vs application = is this input I got valid for my program, should I terminate or not).

Try this:

    main = do
        putStrLn "Enter command, c x y, d x y"
        s <- getLine
        if not $ validateInput s then
             print "Error, try again"
             main
        else do
            let object = newObject
            updateObject object s
            print object

updateObject :: a -> String -> a
updateObject object s
          | head s == 'c' = --do updates here
          | head s == 's' = --do updates here

Also try to create a console loop so you can easier deal with "Enter new Command" situations. Move away from main as soon as you can.


问:
String compare strange bug
I have strange bug in my code. I have variable type and when I load that from class Settings ( implements persistable ) it has value "CPU 21" (type="CPU 21"), but when I try
 if(type=="CPU 21") the condition is false. How is that possible ? </p>

答:
you need to use equals(); to compare String values
replace

```<code>if(type=="CPU 21")
</code>```

with

```<code>if("CPU 21".equals(type))
</code>```

== will compare two reference variable. while equals will check the object's equality
Also See

java-string-equals-versus ==

Title: String compare strange bug

Body:
you need to use equals(); to compare String values
replace

if(type=="CPU 21")

with

if("CPU 21".equals(type))

== will compare two reference variable. while equals will check the object's equality
Also See

java-string-equals-versus ==


问:
LINQ Aggregate algorithm explained
This might sound lame, but  I have not been able to find a really good explanation of Aggregate.

Good means short, descriptive, comprehensive with a small and clear example.

答:
Everyone has given his explanation. My explanation is like that.

Aggregate method applies a function to each item of a collection. For example, let's have collection { 6, 2, 8, 3 } and the function Add (operator +) it does (((6+2)+8)+3) and returns 19

```<code>var numbers = new List<int> { 6, 2, 8, 3 };
int sum = numbers.Aggregate(func: (result, item) => result + item);
// sum: (((6+2)+8)+3) = 19
</code>```

In this example there is passed named method Add instead of lambda expression.

```<code>var numbers = new List<int> { 6, 2, 8, 3 };
int sum = numbers.Aggregate(func: Add);
// sum: (((6+2)+8)+3) = 19

private static int Add(int x, int y) { return x + y; }
</code>```

Title: LINQ Aggregate algorithm explained

Body:
Everyone has given his explanation. My explanation is like that.

Aggregate method applies a function to each item of a collection. For example, let's have collection { 6, 2, 8, 3 } and the function Add (operator +) it does (((6+2)+8)+3) and returns 19

var numbers = new List<int> { 6, 2, 8, 3 };
int sum = numbers.Aggregate(func: (result, item) => result + item);
// sum: (((6+2)+8)+3) = 19

In this example there is passed named method Add instead of lambda expression.

var numbers = new List<int> { 6, 2, 8, 3 };
int sum = numbers.Aggregate(func: Add);
// sum: (((6+2)+8)+3) = 19

private static int Add(int x, int y) { return x + y; }


问:
Get property Type and convert String to corresponding Type
I am using CSOM to update some Task of a Project Server Project.

Which property has to be updated is not defined the code finds out dynamically what to update based on the property name as String.

For better understanding I wore a simplified version of my code

```<code>//fieldName = "ActualWorkTimeSpan"; value = "16:00:00";
private void Start(string fieldName, string value)
{
    DraftTask draftTask = GetDraftTask();

    Update(draftTask, fieldName, value);

    PublishAndCheckin(draftTask);
}

private static void Update(DraftTask draftTask, string fieldName, string value)
{
    // skip updating if field is Equal
    if (GetPropValue(draftTask, fieldName).ToString() == value)
        return;

    // update of the task
    SetPropValue(draftTask, fieldName, value);

}

private static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

private static void SetPropValue(DraftTask src, string propName, object value)
{
    src.GetType().GetProperty(propName).SetValue(src, value);
}
</code>```

I can use GetPropValue() without problem but for SetPropValue() I would need the value to be in the right type.

In this case it would be "System.TimeSpan" for the property "ActualWorkTimeSpan". So I would need to convert the string "15:00:00" to TimeSpan.

It would be easy to do if it were TimeSpan every time, but I could be that the Field "Cost" is set to be updated.

```<code>Update(draftTask, "Cost", "500");
</code>```

So my question is if it is Possible to find out what type the field has and than convert my value to the same type.

答:
The simplest option is to change the method signature to be generic or take an  object type and actually pass in the correct data type in the first place. For example:

```<code>private static void Update(DraftTask draftTask, string fieldName, object value)
{
    //snip
}
</code>```

Or generic:

```<code>private static void Update<T>(DraftTask draftTask, string fieldName, T value)
{
    //snip
}
</code>```

And now you call it with the correct type, for example:

```<code>var timeSpan = new TimeSpan(...);
Update(ref draftTask, "ActualWorkTimeSpan", timeSpan);
</code>```

Body:
I am using CSOM to update some Task of a Project Server Project.

Which property has to be updated is not defined the code finds out dynamically what to update based on the property name as String.

For better understanding I wore a simplified version of my code

//fieldName = "ActualWorkTimeSpan"; value = "16:00:00";
private void Start(string fieldName, string value)
{
    DraftTask draftTask = GetDraftTask();

    Update(draftTask, fieldName, value);

    PublishAndCheckin(draftTask);
}

private static void Update(DraftTask draftTask, string fieldName, string value)
{
    // skip updating if field is Equal
    if (GetPropValue(draftTask, fieldName).ToString() == value)
        return;

    // update of the task
    SetPropValue(draftTask, fieldName, value);

}

private static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

private static void SetPropValue(DraftTask src, string propName, object value)
{
    src.GetType().GetProperty(propName).SetValue(src, value);
}

I can use GetPropValue() without problem but for SetPropValue() I would need the value to be in the right type.

In this case it would be "System.TimeSpan" for the property "ActualWorkTimeSpan". So I would need to convert the string "15:00:00" to TimeSpan.

It would be easy to do if it were TimeSpan every time, but I could be that the Field "Cost" is set to be updated.

Update(draftTask, "Cost", "500");

So my question is if it is Possible to find out what type the field has and than convert my value to the same type.

Body:
The simplest option is to change the method signature to be generic or take an  object type and actually pass in the correct data type in the first place. For example:

private static void Update(DraftTask draftTask, string fieldName, object value)
{
    //snip
}

Or generic:

private static void Update<T>(DraftTask draftTask, string fieldName, T value)
{
    //snip
}

And now you call it with the correct type, for example:

var timeSpan = new TimeSpan(...);
Update(ref draftTask, "ActualWorkTimeSpan", timeSpan);


问:
Arranging 3 red balls, 2 blue balls, and 2 green balls so that no two adjacent balls are of the same color
I want to arrange 3 red balls, 2 blue balls, and 2 green balls in a line so that no two balls of the same color are adjacent. If there are no such restrictions, then the number of such unique arrangements is

.

Below is the code in R that I used to solve this problem. The idea is to get all 210 unique arrangement, then count the cases where two adjacent cells in a row are of the same color. With this algorithm, I get 38 as the answer. I feel that my code is such an ugly hack. How would you do this in R (or your preferred language)?

```<code>colors <- c("R", "R", "R", "B", "B", "G", "G")
n <- 1:10000
x <- matrix(rep(NA, times=70000), ncol=7)
for (i in n) x[i,] <- sample(colors)
x <- unique(x)
rows <- nrow(x)
y <- rep(NA, times =rows)
for (i in 1:rows) {
  y[i] <- x[i,1]==x[i,2] |
    x[i,2]==x[i,3] |
    x[i,3]==x[i,4] |
    x[i,4]==x[i,5] |
    x[i,5]==x[i,6] |
    x[i,6] == x[i,7]
  }
table(y)
## y
## FALSE  TRUE
##    38   172
</code>```

答:
You could as well use run length encoding:</p>

```<code>library(DescTools)
# 3 red balls, 2 blue balls, and 2 green
m <- Permn(rep(c("R","B","G"), times=c(3,2,2)))

# use run length encoding to find adjacent elements
table(apply(m, 1, function(x)
            (length(rle(x)$lengths)!=7)))
</code>```

Body:
I want to arrange 3 red balls, 2 blue balls, and 2 green balls in a line so that no two balls of the same color are adjacent. If there are no such restrictions, then the number of such unique arrangements is

.

Below is the code in R that I used to solve this problem. The idea is to get all 210 unique arrangement, then count the cases where two adjacent cells in a row are of the same color. With this algorithm, I get 38 as the answer. I feel that my code is such an ugly hack. How would you do this in R (or your preferred language)?

colors <- c("R", "R", "R", "B", "B", "G", "G")
n <- 1:10000
x <- matrix(rep(NA, times=70000), ncol=7)
for (i in n) x[i,] <- sample(colors)
x <- unique(x)
rows <- nrow(x)
y <- rep(NA, times =rows)
for (i in 1:rows) {
  y[i] <- x[i,1]==x[i,2] |
    x[i,2]==x[i,3] |
    x[i,3]==x[i,4] |
    x[i,4]==x[i,5] |
    x[i,5]==x[i,6] |
    x[i,6] == x[i,7]
  }
table(y)
## y
## FALSE  TRUE
##    38   172

Body:
You could as well use run length encoding:

library(DescTools)
# 3 red balls, 2 blue balls, and 2 green
m <- Permn(rep(c("R","B","G"), times=c(3,2,2)))

# use run length encoding to find adjacent elements
table(apply(m, 1, function(x)
            (length(rle(x)$lengths)!=7)))


问:
C# : Removing Columns from Datatable
Suppose I have two tables

Table 1 with following columns (Dots to represent columns in between)

```<code>id int
name varchar
.
.
.
.
LastChanged datetime
</code>```

Table 2 with following columns

```<code>id int
Address varchar
.
.
.
.
LastChanged datetime
</code>```

I executed a query like below in C# and stored the result in a Datatable.

```<code>select * from table1 t1
inner join  table2 t2
on t1.id=t2.id
</code>```

Now I don't want the column LastChanged  in the result.

LastChanged column is present in both tables. Since Datatable doesn't allow duplicate column names, one of the LastChanged column in result is renamed to LastChanged1

So when I try to remove the column using

```<code>if (table.Columns.Contains("LastChanged"))
                table.Columns.Remove("LastChanged");
</code>```

Only one LastChanged is removed. The other one remains.

One solution is to eliminate LastChanged in the query itself
by specifying the required columns.
But it makes query long since almost all columns except LastChanged is needed in result.

Is there a solution in C#?

答:
Read carefully: Bad habits to kick : using SELECT * / omitting the column list

However, to answer the question, you could do this LINQ approach:

```<code>string colName = "LastChanged";
var lastChangedColumnList = table.Columns.Cast<DataColumn>()
  .Where(c => c.ColumnName.StartsWith(colName) && c.ColumnName.Substring(colName.Length).All(char.IsDigit))
  .ToList();

foreach(DataColumn col in lastChangedColumnList)
    table.Columns.Remove(col);
</code>```

Title: C# : Removing Columns from Datatable

Body:
Suppose I have two tables

Table 1 with following columns (Dots to represent columns in between)

id int
name varchar
.
.
.
.
LastChanged datetime

Table 2 with following columns

id int
Address varchar
.
.
.
.
LastChanged datetime

I executed a query like below in C# and stored the result in a Datatable.

select * from table1 t1
inner join  table2 t2
on t1.id=t2.id

Now I don't want the column LastChanged  in the result.

LastChanged column is present in both tables. Since Datatable doesn't allow duplicate column names, one of the LastChanged column in result is renamed to LastChanged1

So when I try to remove the column using

if (table.Columns.Contains("LastChanged"))
                table.Columns.Remove("LastChanged");

Only one LastChanged is removed. The other one remains.

One solution is to eliminate LastChanged in the query itself
by specifying the required columns.
But it makes query long since almost all columns except LastChanged is needed in result.

Is there a solution in C#?

Body:
Read carefully: Bad habits to kick : using SELECT * / omitting the column list

However, to answer the question, you could do this LINQ approach:

string colName = "LastChanged";
var lastChangedColumnList = table.Columns.Cast<DataColumn>()
  .Where(c => c.ColumnName.StartsWith(colName) && c.ColumnName.Substring(colName.Length).All(char.IsDigit))
  .ToList();

foreach(DataColumn col in lastChangedColumnList)
    table.Columns.Remove(col);


问:
Getting Z and X at output for a basic Full Adder
I have been designing a basic full adder with two half adder modules and trying to test it with a testbench. There are no compile errors, but at the output (Waveform), I get Z and X for Sum and Carry. I am stuck and not sure what next to look at to correct this error.

Any advice in what next steps (or some pointers) to be checked in order to rectify this would be helpful.

Here is the Verilog code for the Full Adder:

module half_adder(x,y,S,C);
input x,y;
output S,C;

xor G1(S,x,y);
and G2(C,x,y);

endmodule

module full_adder(x,y,z,S,C);
input x,y,z;
output S,C;
wire S1,C1,C2;

half_adder HA1(S1,C1,x,y);
half_adder HA2(S,C2,S1,z);
or G3(C,C1,C2);

endmodule
```

<p>Testbench for the above:</p>

<pre class="lang-html prettyprint-override"><code>module tb_fulladder;
wire S,C;
reg x,y,z;

full_adder DUT(x,y,z,S,C);

initial
begin
x=1'b0;y=1'b0;z=1'b0;
#50
x=1'b0;y=1'b0;z=1'b1;
#50
x=1'b0;y=1'b1;z=1'b0;
#50
x=1'b0;y=1'b1;z=1'b1;
#50
x=1'b1;y=1'b0;z=1'b0;
#50
x=1'b1;y=1'b0;z=1'b1;
#50
x=1'b1;y=1'b1;z=1'b0;
#50
x=1'b1;y=1'b1;z=1'b1;
end

initial
#500
$finish;

endmodule
</code>```

Here is the waveform:

答:
You made a mistake in your connections to half_adder. You need to change the order of the port signals. Change:

```<code>half_adder HA1(S1,C1,x,y);
half_adder HA2(S,C2,S1,z);
</code>```

to:

```<code>half_adder HA1 (x,y,S1,C1);
half_adder HA2 (S1,z,S,C2);
</code>```

I discovered this by looking at the waveforms for the internal full and half adder signals.

This is why it is better to use connection-by-name instead of connection-by-position.  For example, use:

```<code>half_adder HA1 (.x(x), .y(y), .S(S1), .C(C1));
</code>```

Using this syntax, the port order does not matter.  Refer to the free IEEE Std 1800-2012, 23.3.2 Module instantiation syntax.

Body:
I have been designing a basic full adder with two half adder modules and trying to test it with a testbench. There are no compile errors, but at the output (Waveform), I get Z and X for Sum and Carry. I am stuck and not sure what next to look at to correct this error.

Any advice in what next steps (or some pointers) to be checked in order to rectify this would be helpful.

Here is the Verilog code for the Full Adder:

module half_adder(x,y,S,C);
input x,y;
output S,C;

xor G1(S,x,y);
and G2(C,x,y);

endmodule

module full_adder(x,y,z,S,C);
input x,y,z;
output S,C;
wire S1,C1,C2;

half_adder HA1(S1,C1,x,y);
half_adder HA2(S,C2,S1,z);
or G3(C,C1,C2);

endmodule

Testbench for the above:

module tb_fulladder;
wire S,C;
reg x,y,z;

full_adder DUT(x,y,z,S,C);

initial
begin
x=1'b0;y=1'b0;z=1'b0;
#50
x=1'b0;y=1'b0;z=1'b1;
#50
x=1'b0;y=1'b1;z=1'b0;
#50
x=1'b0;y=1'b1;z=1'b1;
#50
x=1'b1;y=1'b0;z=1'b0;
#50
x=1'b1;y=1'b0;z=1'b1;
#50
x=1'b1;y=1'b1;z=1'b0;
#50
x=1'b1;y=1'b1;z=1'b1;
end

initial
#500
$finish;

endmodule

Here is the waveform:

Body:
You made a mistake in your connections to half_adder. You need to change the order of the port signals. Change:

half_adder HA1(S1,C1,x,y);
half_adder HA2(S,C2,S1,z);

to:

half_adder HA1 (x,y,S1,C1);
half_adder HA2 (S1,z,S,C2);

I discovered this by looking at the waveforms for the internal full and half adder signals.

This is why it is better to use connection-by-name instead of connection-by-position.  For example, use:

half_adder HA1 (.x(x), .y(y), .S(S1), .C(C1));

Using this syntax, the port order does not matter.  Refer to the free IEEE Std 1800-2012, 23.3.2 Module instantiation syntax.


问:
Cannot set state to location.pathname in React Router V4
I'm trying to set the state of my component to the current pathname of the URL. Specifically, I want to do this in my ResponsiveDrawer component defined in App.js as:

```<code>class App extends Component {
  render() {
    return (
      <Router>
        <ResponsiveDrawer>
          <div className="App">
            <Route exact path="/" component={Administrator} />
            <Route path="/admin" component={Administrator} />
            <Route exact path="/jobs" component={Jobs} />
            <Route path="/jobs/:id" render={({match}) => <ViewJob id={match.params.id} />} />
            <Route path="/entries/:jobId/:entryId" render={({match}) => <Entry jobId={match.params.jobId} entryId={match.params.entryId} />} />
            <Route exact path="/reports" component={Reports} />
            <Route path="/reports/:jobId" render={({match}) => <JobReport id={match.params.jobId} />} />
            <Route path="/reports/activity" component={ActivityReport} />
          </div>
         </ResponsiveDrawer>
     </Router>

    );
  }
}
</code>```

Now, in the ResponsiveDrawer component I have the following code to that should trigger when the URL changes:

```<code>class ResponsiveDrawer extends React.Component {
  constructor() {
    super();
    this.state = {
      mobileOpen: false,
      adminOpen: true,
      jobsOpen: false,
      reportsOpen: false,
      activePath: ''
    };
    this.setActiveState = this.setActiveState.bind(this);
    this.isActiveFunc = this.isActiveFunc.bind(this);
  }

  setActiveState = (path) => {
    this.setState({activePath: path});
  };

  isActiveFunc = (match, location) => {
    console.log(location.pathname)
    this.setActiveState(location.pathname);
    return match
  };

  render() {
      <NavLink isActive={this.isActiveFunc} className={classes.subLink} to={{ pathname: "/admin/users" }}>
         <ListItem button className={classes.nested}>
         <ListItemText inset primary="Users" />
         </ListItem>
       </NavLink>
</code>```

This correctly logs the current location every time the NavLink is clicked. However, when I try to set the state to the value of the location.pathname I get the following error:

proxyConsole.js:54 Warning: Cannot update during an existing state
  transition (such as within render or another component's
  constructor). Render methods should be a pure function of props and
  state; constructor side-effects are an anti-pattern, but can be moved
  to componentWillMount.

And my browser goes into an infinite loop and crashes

Any ideas?

答:
You can see from this line,

https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/NavLink.js#L34

That the function passed in on isActive is immediately invoked in the NavLink render function.

setState is obviously should not be used in the render because that could cause an infinite render loop.

You should look to use componentWillReceiveProps instead.

Body:
I'm trying to set the state of my component to the current pathname of the URL. Specifically, I want to do this in my ResponsiveDrawer component defined in App.js as:

class App extends Component {
  render() {
    return (
      <Router>
        <ResponsiveDrawer>

            <Route exact path="/" component={Administrator} />
            <Route path="/admin" component={Administrator} />
            <Route exact path="/jobs" component={Jobs} />
            <Route path="/jobs/:id" render={({match}) => <ViewJob id={match.params.id} />} />
            <Route path="/entries/:jobId/:entryId" render={({match}) => <Entry jobId={match.params.jobId} entryId={match.params.entryId} />} />
            <Route exact path="/reports" component={Reports} />
            <Route path="/reports/:jobId" render={({match}) => <JobReport id={match.params.jobId} />} />
            <Route path="/reports/activity" component={ActivityReport} />

         </ResponsiveDrawer>
     </Router>

    );
  }
}

Now, in the ResponsiveDrawer component I have the following code to that should trigger when the URL changes:

class ResponsiveDrawer extends React.Component {
  constructor() {
    super();
    this.state = {
      mobileOpen: false,
      adminOpen: true,
      jobsOpen: false,
      reportsOpen: false,
      activePath: ''
    };
    this.setActiveState = this.setActiveState.bind(this);
    this.isActiveFunc = this.isActiveFunc.bind(this);
  }

  setActiveState = (path) => {
    this.setState({activePath: path});
  };

  isActiveFunc = (match, location) => {
    console.log(location.pathname)
    this.setActiveState(location.pathname);
    return match
  };

  render() {
      <NavLink isActive={this.isActiveFunc} className={classes.subLink} to={{ pathname: "/admin/users" }}>
         <ListItem button className={classes.nested}>
         <ListItemText inset primary="Users" />
         </ListItem>
       </NavLink>

This correctly logs the current location every time the NavLink is clicked. However, when I try to set the state to the value of the location.pathname I get the following error:

proxyConsole.js:54 Warning: Cannot update during an existing state
  transition (such as within render or another component's
  constructor). Render methods should be a pure function of props and
  state; constructor side-effects are an anti-pattern, but can be moved
  to componentWillMount.

And my browser goes into an infinite loop and crashes

Any ideas?


问:
How to make remove class function asynchronously?
I'm using a custom directive for the images in my angular app, In the directive, I want to add placeholder image until the image loads and the placeholder image has to be applied with a 'no-image' class. This is what I have done:

```<code>loadImage(image: string) {
    let defaultImage = this._getLocalResource(this._NO_IMAGE);
    this.currentElement.className = 'no-image';
    this.currentElement.src = defaultImage;
    const img = new Image();
    if (image) {
        img.src = image;
    } else {
        img.src = defaultImage;
    }
    img.onload = () => {
        this.currentElement.classList.remove('no-image');
        this.currentElement.src = img.src;
    };
    img.onerror = err => {
        this.currentElement.class = 'no-image';
        this.currentElement.src = defaultImage;
    };
}
</code>```

My problem is when the image loads(inside onload function) the removing of class 'no-image' is taking some time and the loaded image is rendered with the class 'no-image' for a fraction of sec. This is causing unpleasant user experience.

Is there any way that I can assign the loaded image to currentElement.src after the class has been removed successfully, or is there any async way to remove the class?

答:
You can try delay the
this.currentElement.src = img.src;
line by settimeout</p>

Body:
I'm using a custom directive for the images in my angular app, In the directive, I want to add placeholder image until the image loads and the placeholder image has to be applied with a 'no-image' class. This is what I have done:

loadImage(image: string) {
    let defaultImage = this._getLocalResource(this._NO_IMAGE);
    this.currentElement.className = 'no-image';
    this.currentElement.src = defaultImage;
    const img = new Image();
    if (image) {
        img.src = image;
    } else {
        img.src = defaultImage;
    }
    img.onload = () => {
        this.currentElement.classList.remove('no-image');
        this.currentElement.src = img.src;
    };
    img.onerror = err => {
        this.currentElement.class = 'no-image';
        this.currentElement.src = defaultImage;
    };
}

My problem is when the image loads(inside onload function) the removing of class 'no-image' is taking some time and the loaded image is rendered with the class 'no-image' for a fraction of sec. This is causing unpleasant user experience.

Is there any way that I can assign the loaded image to currentElement.src after the class has been removed successfully, or is there any async way to remove the class?


问:
"Semaphore must not be currently signaled or in a wait state"
I'm learning Vulkan. I wrote a simple program that renders a single 3D mesh object on screen. The problem is i get thousands complaint (for each frame rendered) from a validation layer, saying "DS(ERROR): object: 0x1 type: 5 location: 9900 msgCode: 373295628: vkAcquireNextImageKHR: Semaphore must not be currently signaled or in a wait state."
I wrote my code based on the premise that the semaphore that queue submission waits upon, is unsignaled after returning from vkQueueSubmit and is ready for use in the next frame's vkAcquireNextImageKHR. That seems however not to be the case.
Rendering is done without a problem though and i get the image that i want, but i care to fix any inconsistencies that validation layers report.

答:
I wrote my code based on the premise that the semaphore that queue submission waits upon, is unsignaled after returning from vkQueueSubmit.

No, Your assumption is wrong. Semaphore is unsignaled when the batch of work that signals it is finished and another batch of work, that waits on this semaphore, is started. But this happens in the background, on the hardware. From the application's perspective You don't know when this happens, unless You synchronize Your application with the GPU (either through vkDeviceWaitIdle(), vkQueueWaitIdle() commands or, more preferably, by using fences).

vkQueueSubmit() function returns almost immediately. But You don't know when the batch of submitted work is going to be processed by the hardware. It may be performed immediately or maybe there is some very large submission that is still being processed and Your new submission must wait for it to complete. You just don't know when this happens and You cannot make any assumptions - You need to perform some form of synchronization to be sure.

What's more - it may (and probably will) work most of the time. But there may be a hardware on which the way You do it may not generate correct results. So it is better to fix problems reported by Validation Layers.

Have a look at two code samples from the Vulkan Cookbook: the one about preparing a single frame of animation and about synchronizing presentation of multiple frames.