问:
How to get the value from XML in SQL
I could not find an error. Select s empty, but should be not...</p>

```<code>declare @xml xml =
'<ArrayOfFinancialDecimalKeyValue xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Quipu.CRMExtensions.BusinessLogicLayer.Financials.Models.Financials">
  <FinancialDecimalKeyValue>
    <ReferenceCode>fx_risk_lt_st_liabilities_currency3_realistic_percentage_input</ReferenceCode>
    <Value>5</Value>
    <AttributeName>fx_risk_lt_st_liabilities_currency3_realistic_percentage</AttributeName>
    <Type1>realistic_percentage</Type1>
    <Type2>currency3</Type2>
    <IsDivByZero i:nil="true" />
  </FinancialDecimalKeyValue>
  <FinancialDecimalKeyValue>
    <ReferenceCode>fx_risk_lt_st_liabilities_currency3_realistic2ndYear_percentage_input</ReferenceCode>
    <Value>5</Value>
    <AttributeName>fx_risk_lt_st_liabilities_currency3_realistic2ndYear_percentage</AttributeName>
    <Type1>realistic2ndYear_percentage</Type1>
    <Type2>currency3</Type2>
    <IsDivByZero i:nil="true" />
  </FinancialDecimalKeyValue>
</ArrayOfFinancialDecimalKeyValue>'

SELECT

       _xml.col.value('(ReferenceCode)[1]','varchar(150)') as [ReferenceCode],
       _xml.col.value('(Value)[1]','varchar(50)') as [Value],
       _xml.col.value('(AttributeName)[1]','varchar(50)') as [BalanceSheetExchangeRate],
       _xml.col.value('(Type1)[1]','varchar(50)') as [Type1]  ,
       _xml.col.value('(Type2)[1]','varchar(50)') as [Type2],
       _xml.col.value('(IsDivByZero)[1]','varchar(50)') as [IsDivByZero]

FROM   @xml.nodes('//FinancialDecimalKeyValue') as _xml(col)
</code>```

Title: How to get the value from XML in SQL

Body:
I could not find an error. Select s empty, but should be not...

declare @xml xml =
'<ArrayOfFinancialDecimalKeyValue xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Quipu.CRMExtensions.BusinessLogicLayer.Financials.Models.Financials">
  <FinancialDecimalKeyValue>
    <ReferenceCode>fx_risk_lt_st_liabilities_currency3_realistic_percentage_input</ReferenceCode>
    <Value>5</Value>
    <AttributeName>fx_risk_lt_st_liabilities_currency3_realistic_percentage</AttributeName>
    <Type1>realistic_percentage</Type1>
    <Type2>currency3</Type2>
    <IsDivByZero i:nil="true" />
  </FinancialDecimalKeyValue>
  <FinancialDecimalKeyValue>
    <ReferenceCode>fx_risk_lt_st_liabilities_currency3_realistic2ndYear_percentage_input</ReferenceCode>
    <Value>5</Value>
    <AttributeName>fx_risk_lt_st_liabilities_currency3_realistic2ndYear_percentage</AttributeName>
    <Type1>realistic2ndYear_percentage</Type1>
    <Type2>currency3</Type2>
    <IsDivByZero i:nil="true" />
  </FinancialDecimalKeyValue>
</ArrayOfFinancialDecimalKeyValue>'

SELECT

       _xml.col.value('(ReferenceCode)[1]','varchar(150)') as [ReferenceCode],
       _xml.col.value('(Value)[1]','varchar(50)') as [Value],
       _xml.col.value('(AttributeName)[1]','varchar(50)') as [BalanceSheetExchangeRate],
       _xml.col.value('(Type1)[1]','varchar(50)') as [Type1]  ,
       _xml.col.value('(Type2)[1]','varchar(50)') as [Type2],
       _xml.col.value('(IsDivByZero)[1]','varchar(50)') as [IsDivByZero]

FROM   @xml.nodes('//FinancialDecimalKeyValue') as _xml(col)

Body:
Your query is using a default namespace. There are several ways to deal with it, but the easiest was to use WITH XMLNAMESPACES:

;WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/Quipu.CRMExtensions.BusinessLogicLayer.Financials.Models.Financials')
SELECT

       _xml.col.value('(ReferenceCode)[1]','varchar(150)') as [ReferenceCode],
       _xml.col.value('(Value)[1]','varchar(50)') as [Value],
       _xml.col.value('(AttributeName)[1]','varchar(50)') as [BalanceSheetExchangeRate],
       _xml.col.value('(Type1)[1]','varchar(50)') as [Type1]  ,
       _xml.col.value('(Type2)[1]','varchar(50)') as [Type2],
       _xml.col.value('(IsDivByZero)[1]','varchar(50)') as [IsDivByZero]
FROM   @xml.nodes('//FinancialDecimalKeyValue') as _xml(col);

This returns

+-----------------------------------------------------------------------+-------+----------------------------------------------------+-----------------------------+-----------+-------------+
| ReferenceCode                                                         | Value | BalanceSheetExchangeRate                           | Type1                       | Type2     | IsDivByZero |
+-----------------------------------------------------------------------+-------+----------------------------------------------------+-----------------------------+-----------+-------------+
| fx_risk_lt_st_liabilities_currency3_realistic_percentage_input        | 5     | fx_risk_lt_st_liabilities_currency3_realistic_perc | realistic_percentage        | currency3 |             |
+-----------------------------------------------------------------------+-------+----------------------------------------------------+-----------------------------+-----------+-------------+
| fx_risk_lt_st_liabilities_currency3_realistic2ndYear_percentage_input | 5     | fx_risk_lt_st_liabilities_currency3_realistic2ndYe | realistic2ndYear_percentage | currency3 |             |
+-----------------------------------------------------------------------+-------+----------------------------------------------------+-----------------------------+-----------+-------------+

UPDATE

Your comments are not really clear for me... I get, that you try to use XMLNAMESPACES like you'd use a CTE. Well, if you need a CTE you can do this:

;WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/Quipu.CRMExtensions.BusinessLogicLayer.Financials.Models.Financials')
,CTE AS
(
    SELECT

           _xml.col.value('(ReferenceCode)[1]','varchar(150)') as [ReferenceCode],
           _xml.col.value('(Value)[1]','varchar(50)') as [Value],
           _xml.col.value('(AttributeName)[1]','varchar(50)') as [BalanceSheetExchangeRate],
           _xml.col.value('(Type1)[1]','varchar(50)') as [Type1]  ,
           _xml.col.value('(Type2)[1]','varchar(50)') as [Type2],
           _xml.col.value('(IsDivByZero)[1]','varchar(50)') as [IsDivByZero]
    FROM   @xml.nodes('//FinancialDecimalKeyValue') as _xml(col)
)
SELECT * FROM CTE;

But I think, it's this what you are looking for:

;WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/Quipu.CRMExtensions.BusinessLogicLayer.Financials.Models.Financials')
SELECT _xml.col.value('(Value)[1]','varchar(50)') as [Value]
FROM   @xml.nodes('//FinancialDecimalKeyValue') as _xml(col)
WHERE _xml.col.value('(Type1)[1]','varchar(50)')='realistic_percentage'
  AND _xml.col.value('(ReferenceCode)[1]','varchar(150)')='fx_risk_lt_st_liabilities_currency3_realistic_percentage_input'

This would return just the value "5".

Better in performance was this:

DECLARE @code VARCHAR(100)='fx_risk_lt_st_liabilities_currency3_realistic_percentage_input';
DECLARE @type1 VARCHAR(100)='realistic_percentage';

;WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/Quipu.CRMExtensions.BusinessLogicLayer.Financials.Models.Financials')
SELECT @xml.value('(/ArrayOfFinancialDecimalKeyValue
                    /FinancialDecimalKeyValue[(ReferenceCode/text())[1]=sql:variable("@code") and (Type1/text())[1]=sql:variable("@type1")]
                    /Value/text())[1]','varchar(50)') as [Value];

The last one you read as: Dive into <ArrayOfFinancialDecimalKeyValue>. Then look for an element <FinancialDecimalKeyValue>, which fullfills the XQuery predicate and return its <Value>.

UPDATE 2

Might be, that you just got the syntax of INSERT INTO wrong?

Try this

DECLARE @TempTable TABLE(ReferenceCode VARCHAR(150),[Value] VARCHAR(50),BalanceSheetExchangeRate VARCHAR(50),Type1 VARCHAR(50),Type2 VARCHAR(50),IsDivByzero VARCHAR(50));

;WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/Quipu.CRMExtensions.BusinessLogicLayer.Financials.Models.Financials')
INSERT INTO @TempTable(ReferenceCode,[Value],BalanceSheetExchangeRate,Type1,Type2,IsDivByzero)
SELECT _xml.col.value('(ReferenceCode)[1]','varchar(150)') as [ReferenceCode],
       _xml.col.value('(Value)[1]','varchar(50)') as [Value],
       _xml.col.value('(AttributeName)[1]','varchar(50)') as [BalanceSheetExchangeRate],
       _xml.col.value('(Type1)[1]','varchar(50)') as [Type1]  ,
       _xml.col.value('(Type2)[1]','varchar(50)') as [Type2],
       _xml.col.value('(IsDivByZero)[1]','varchar(50)') as [IsDivByZero]
FROM   @xml.nodes('//FinancialDecimalKeyValue') as _xml(col);

SELECT * FROM @TempTable;


来源: stackexchange

问:
Error : java.lang.ClassNotFoundException: org.hibernate.cfg.AnnotationConfiguration
I am getting error java.lang.ClassNotFoundException: org.hibernate.cfg.AnnotationConfiguration while running a spring code from spring tool suite

I have already googled and checked stackoverflow for the resolution ,but no luck .

This is my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.thoughtworkstest</groupId>
<artifactId>supermarket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>supermarket</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.3.156</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>3.6.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.6.RELEASE</version>
    </dependency>

    <!-- Dependencies for SQLite -->
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.25.2</version>
    </dependency>
    <dependency>
        <groupId>net.kemitix</groupId>
        <artifactId>sqlite-dialect</artifactId>
        <version>0.1.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

This is app-context.xml

```<code><context:property-placeholder
  location="classpath:META-INF/spring/hibernate.properties"/>

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
 </bean>
 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses" value="com.test.market.model.ItemDetails" />
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
   </props>
  </property>
 </bean>

</beans>
</code>```

答:
You are using Spring Boot 2.1.3 which depends on Spring 5.1. The Spring 5.x line works only with Hibernate 5.x, support for earlier versions has been dropped.

The spring-boot-starter-data-jpa dependency already includes the hibernate-entitymanager dependency in a version that works with the other dependencies.

Annother is is that you are mixing jars/modules from different versions of Spring you are mixing 5.1.x and 3.0.6, that is always trouble as those are quite incompatible. Furthermore that dependency is also included in the spring-boot-starter-data-jpa.

So in short, you dependencies are a bit of mess.

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <!-- Dependencies for SQLite -->
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.25.2</version>
    </dependency>
    <dependency>
        <groupId>net.kemitix</groupId>
        <artifactId>sqlite-dialect</artifactId>
        <version>0.1.0</version>
    </dependency>
</dependencies>
</code>```

NOTE: Spring Boot can also manage the H2 version, hence you can remove the version tag from that.

You are using XML, however I would strongly suggest to ditch that and use JPA instead. With the current state of JPA there is no really a need to use plain Hibernate anymore. And if you really must, you can use EntityManager.unwrap(Session.class) to obtain the underlying session.

The added advantage is that you can now use the auto-configuration for JPA from Spring Boot. The properties in your hibernate.properties should go in the application.properties under the correct names.

```<code>spring.datasource.url= # your jdbc.url value
spring.datasource.username = # your jdbc.username value
spring.datasource.password = # your jdbc.password value

spring.jpa.database-platform = # your hibernate.dialect value
spring.jpa.show-sql = # your hibernate.show_sql value
</code>```

NOTE: You don't need to specify the driver-classname property as Spring Boot and JDBC will detect that based on the given jdbc-url.

TIP: Make sure that your @SpringBootApplication annotated class is in the com.test.market package, as recommended by the Spring Boot team, so it will detect all your classes, including your @Entity annotated classes.

Your code, you might need to change to use EntityManager instead of SessionFactory and Session but that should be a minor change.

ContentLicense: CC BY-SA 4.0

Body:
I am getting error java.lang.ClassNotFoundException: org.hibernate.cfg.AnnotationConfiguration while running a spring code from spring tool suite

I have already googled and checked stackoverflow for the resolution ,but no luck .

This is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
    <relativePath />
</parent>
<groupId>com.thoughtworkstest</groupId>
<artifactId>supermarket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>supermarket</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.3.156</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>3.6.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.6.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.25.2</version>
    </dependency>
    <dependency>
        <groupId>net.kemitix</groupId>
        <artifactId>sqlite-dialect</artifactId>
        <version>0.1.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

This is app-context.xml

<context:property-placeholder
  location="classpath:META-INF/spring/hibernate.properties"/>

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
 </bean>
 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses" value="com.test.market.model.ItemDetails" />
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
   </props>
  </property>
 </bean>

</beans>

Body:
You are using Spring Boot 2.1.3 which depends on Spring 5.1. The Spring 5.x line works only with Hibernate 5.x, support for earlier versions has been dropped.

The spring-boot-starter-data-jpa dependency already includes the hibernate-entitymanager dependency in a version that works with the other dependencies.

Annother is is that you are mixing jars/modules from different versions of Spring you are mixing 5.1.x and 3.0.6, that is always trouble as those are quite incompatible. Furthermore that dependency is also included in the spring-boot-starter-data-jpa.

So in short, you dependencies are a bit of mess.

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <!-- Dependencies for SQLite -->
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.25.2</version>
    </dependency>
    <dependency>
        <groupId>net.kemitix</groupId>
        <artifactId>sqlite-dialect</artifactId>
        <version>0.1.0</version>
    </dependency>
</dependencies>

NOTE: Spring Boot can also manage the H2 version, hence you can remove the version tag from that.

You are using XML, however I would strongly suggest to ditch that and use JPA instead. With the current state of JPA there is no really a need to use plain Hibernate anymore. And if you really must, you can use EntityManager.unwrap(Session.class) to obtain the underlying session.

The added advantage is that you can now use the auto-configuration for JPA from Spring Boot. The properties in your hibernate.properties should go in the application.properties under the correct names.

spring.datasource.url= # your jdbc.url value
spring.datasource.username = # your jdbc.username value
spring.datasource.password = # your jdbc.password value

spring.jpa.database-platform = # your hibernate.dialect value
spring.jpa.show-sql = # your hibernate.show_sql value

NOTE: You don't need to specify the driver-classname property as Spring Boot and JDBC will detect that based on the given jdbc-url.

TIP: Make sure that your @SpringBootApplication annotated class is in the com.test.market package, as recommended by the Spring Boot team, so it will detect all your classes, including your @Entity annotated classes.

Your code, you might need to change to use EntityManager instead of SessionFactory and Session but that should be a minor change.


问:
Can not fully remove Fabric & Crashlytics
Trying to remove fabric from an IOS project I'm working on. I have removed it from the pod file(s) and did a pod install. (When saying fabric onwards I mean both fabric and crashlytics)

I have removed any references to Fabric in the code by searching the project with  cmd+shift+f. And clean the build folder.

Then when building I get the following error:

/Users/just_user/Library/Developer/Xcode/DerivedData/TheApp-epakvsyxjlzjjfclvjqwrljowaio/Build/Intermediates.noindex/TheAppMobile.build/Debug-iphoneos/TheAppMobile.build/Script-CF862497221C49250071D547.sh: line 2: /Users/just_user/Projects/TheApp/app/TheAppMobile/../Pods/Fabric/run: No such file or directory
  Command PhaseScriptExecution failed with a nonzero exit code

So obviously some reference left somewhere.

So I used Finder to search the project for any references to Fabric which resulted in a lot of references still there not visible via Xcode. I removed all of those references too.

Then cleaned cache of cocoapods, re-installed the pods again. Cleaned build folder and the result is the same as the error above.

Then I deleted the "Users/just_user/Library/Developer/Xcode/DerivedData/TheApp-epakvsyxjlzjjfclvjqwrljowaio/" folder and cleaned and build everything again. Nope, error still there.

What else could it be which isn't visible through xcode and finder searches that keeps a reference to Fabric?

答: From the error, it seems you forgot to remove Run script phase for Fabric under Build phases for your target:


问:
Following is a dynamic form code which can insert data by adding multiple inputs from user in row but I want it in column. How do I do it?
I downloaded the following code from internet. This code will add extra inputs from the user but it will create a new row in the database. I want this to be inserted in different columns of a row. How do I do it?

I have created fields for insertion in the Column.

```<code><form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name"
class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add
More</button>
</td></tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info"
value="Submit" />
</form>

<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
    i++;
    $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});

$(document).on('click', '.btn_remove', function(){
    var button_id = $(this).attr("id");
    $('#row'+button_id+'').remove();
});

$('#submit').click(function(){
    $.ajax({
        url:"name.php",
        method:"POST",
        data:$('#add_name').serialize(),
        success:function(data)
        {
            alert(data);
            $('#add_name')[0].reset();
        }
    });
});

});
</script>
</code>```

And this is the name.php

```<code><?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$number = count($_POST["name"]);
if($number > 1)
{
for($i=0; $i<$number; $i++)
{
    if(trim($_POST["name"][$i] != ''))
    {
        $sql = "INSERT INTO tbl_name(namec) VALUES('".mysqli_real_escape_string($connect, $_POST["name"][$i])."')";
        mysqli_query($connect, $sql);
    }
}
echo "Data Inserted";
}
else
{
echo "Please Enter Name";
}
?>
</code>```

答:
As per your comments, I am assuming that there will be 4 names max. You can do the work as below:-

```<code><?php
 $connect = mysqli_connect("localhost", "root", "", "testing");
 $number = count($_POST["name"]);
 $db_col_names = array('namea','nameb','namec','named');
 $names = array();

 if($number > 1)
 {
      for($i=0; $i<$number; $i++)
      {
           if(trim($_POST["name"][$i]) != '')
           {
                $names[] = mysqli_real_escape_string($connect, $_POST["name"][$i]); //get all the values from from in an array
           }
      }
      $names = implode("','", $names); //make all the values as string to pass in insert query
      $db_col_names = array_slice($db_col_names, 0, $number); //slice the DB columns to the names length entered
      $db_col_names = implode("`,`", $db_col_names ); //make all the values as string to pass in insert query

      $sql = "INSERT INTO tbl_name(`".$db_col_names."`) VALUES('".$names."')";
      mysqli_query($connect, $sql);

      echo "Data Inserted";
 }
 else
 {
      echo "Please Enter Name";
 }
?>
</code>```

Hope this will do the work which you need. If any more modifications needed or any issue, do let me know in comments

Body:
I downloaded the following code from internet. This code will add extra inputs from the user but it will create a new row in the database. I want this to be inserted in different columns of a row. How do I do it?

I have created fields for insertion in the Column.

<form name="add_name" id="add_name">

<input type="text" name="name[]" placeholder="Enter your Name"
class="form-control name_list" />
<button type="button" name="add" id="add" class="btn btn-success">Add
More</button>

<input type="button" name="submit" id="submit" class="btn btn-info"
value="Submit" />
</form>

And this is the name.php

<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$number = count($_POST["name"]);
if($number > 1)
{
for($i=0; $i<$number; $i++)
{
    if(trim($_POST["name"][$i] != ''))
    {
        $sql = "INSERT INTO tbl_name(namec) VALUES('".mysqli_real_escape_string($connect, $_POST["name"][$i])."')";
        mysqli_query($connect, $sql);
    }
}
echo "Data Inserted";
}
else
{
echo "Please Enter Name";
}
?>

Body:
As per your comments, I am assuming that there will be 4 names max. You can do the work as below:-

<?php
 $connect = mysqli_connect("localhost", "root", "", "testing");
 $number = count($_POST["name"]);
 $db_col_names = array('namea','nameb','namec','named');
 $names = array();

 if($number > 1)
 {
      for($i=0; $i<$number; $i++)
      {
           if(trim($_POST["name"][$i]) != '')
           {
                $names[] = mysqli_real_escape_string($connect, $_POST["name"][$i]); //get all the values from from in an array
           }
      }
      $names = implode("','", $names); //make all the values as string to pass in insert query
      $db_col_names = array_slice($db_col_names, 0, $number); //slice the DB columns to the names length entered
      $db_col_names = implode("`,`", $db_col_names ); //make all the values as string to pass in insert query

      $sql = "INSERT INTO tbl_name(`".$db_col_names."`) VALUES('".$names."')";
      mysqli_query($connect, $sql);

      echo "Data Inserted";
 }
 else
 {
      echo "Please Enter Name";
 }
?>

Hope this will do the work which you need. If any more modifications needed or any issue, do let me know in comments


问:
What is php's performance on directly accessing array's row with key specified
I have a question regarding array's performance.... how does php handle array keys? I mean if I do something like $my_city = $cities[15]; .... does php directly access the exact row item in $cities array or does php iterate trough array until it finds the matched row?

and if it access the row directly... is there a difference in performance between an array with 100 rows and array with 100,000 rows?

like in this example
$my_city = $cities[15];

答: PHP's arrays are implemented as hash tables, so the elements are accessed as directly as possible, without iterating through everything. Read more about the algorithm here: http://en.wikipedia.org/wiki/Hash_table</p>

ContentLicense: CC BY-SA 3.0


问:
How to get the result by define divide function using pandas?
```<code>def set_div(a,b):
    if a==0:
        if b==0:
            return 0
        else:
            return 10**6
    else:
        return b/a
</code>```

df:

```<code>    a       b
0   0.0     0.0
1   30000.0 0.0
2   0.0     0.0
3   32700.0 10000.0
4   51700.0 0.0
</code>```

dtypes of col a and b are float64.

```<code>df['c'] = df[['a','b']].apply(lambda x:set_div(x[0],x[1]))
</code>```

but it returns KeyError: (0, 'occurred at index a').

I don't understand the error, please explain and how to get my result.

答:
You can get the result you want directly by using numpy where in this way:

```<code>df['c'] = numpy.where(df.a == 0, numpy.where(df.b == 0, 0, 10**6), df.b/df.a)

print(df)
</code>```

The output is:

```<code>       a      b        c
0      0      0  0.00000
1  30000      0  0.00000
2      0      0  0.00000
3  32700  10000  0.30581
4  51700      0  0.00000
</code>```

If you want to use your defined method itself, then you will have to add the parameter axis=1 when calling the apply method so that it operates row-wise instead of column-wise.

Body:
def set_div(a,b):
    if a==0:
        if b==0:
            return 0
        else:
            return 10**6
    else:
        return b/a

df:

    a       b
0   0.0     0.0
1   30000.0 0.0
2   0.0     0.0
3   32700.0 10000.0
4   51700.0 0.0

dtypes of col a and b are float64.

df['c'] = df[['a','b']].apply(lambda x:set_div(x[0],x[1]))

but it returns KeyError: (0, 'occurred at index a').

I don't understand the error, please explain and how to get my result.

Body:
You can get the result you want directly by using numpy where in this way:

df['c'] = numpy.where(df.a == 0, numpy.where(df.b == 0, 0, 10**6), df.b/df.a)

print(df)

The output is:

       a      b        c
0      0      0  0.00000
1  30000      0  0.00000
2      0      0  0.00000
3  32700  10000  0.30581
4  51700      0  0.00000

If you want to use your defined method itself, then you will have to add the parameter axis=1 when calling the apply method so that it operates row-wise instead of column-wise.


问:
comapare files that are on remote directory and local directory using python
I got a code on this site to download files from remote directory from the server. Now I want modify this code so it compares the files and lists that are on remote directory and not on local directory. It lists the uncommon files between remote directory and local directory .
Is this possible?
Please help.  Thanks in Advance

```<code>import os
import pysftp
import socket
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

IP = "192.168.X.X"
myUsername = "user"
port = 22
myPassword = "password"

try:
    with pysftp.Connection(host=IP, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
        try:
            r=str(socket.gethostbyaddr(IP))
            print("connection successful with "+r)

            def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
                for entry in sftp.listdir(remotedir):
                    remotepath = remotedir + "/" + entry
                    localpath = os.path.join(localdir, entry)
                    mode = sftp.stat(remotepath).st_mode
                    if S_ISDIR(mode):
                        try:
                            os.mkdir(localpath, mode=777)
                        except OSError:
                            pass
                        get_r_portable(sftp, remotepath, localpath, preserve_mtime)
                    elif S_ISREG(mode):
                        sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

            remote_path = input("enter the remote_path: ")
            local_path = input("enter the local_path: ")

            get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
        except socket.herror:
            print("Unknown host")
except:
    print("connection failed")
</code>```

Outcome should be the uncommon files that are present in remote directory and not in local directory.

答:
```<code>def getFilesList(path):
files = []
for (dirpath, dirnames, filenames) in os.walk(path):
    files.extend(filenames)
    return files
ServerFiles = getFilesList(Srverpath)
LocalFiles = getFilesList(Lclpath)
fileDiffList = []
for file in ServerFiles:
    if file in LocalFiles:
        pass
    else:
        fileDiffList.append(file)
</code>```

We can get the uncommon files by using 2 separate lists.
Call getFilesList method twice by passing your server path and local file path.
At the end your 'fileDiffList' will have file names

Body:
I got a code on this site to download files from remote directory from the server. Now I want modify this code so it compares the files and lists that are on remote directory and not on local directory. It lists the uncommon files between remote directory and local directory .
Is this possible?
Please help.  Thanks in Advance

import os
import pysftp
import socket
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

IP = "192.168.X.X"
myUsername = "user"
port = 22
myPassword = "password"

try:
    with pysftp.Connection(host=IP, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
        try:
            r=str(socket.gethostbyaddr(IP))
            print("connection successful with "+r)

            def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
                for entry in sftp.listdir(remotedir):
                    remotepath = remotedir + "/" + entry
                    localpath = os.path.join(localdir, entry)
                    mode = sftp.stat(remotepath).st_mode
                    if S_ISDIR(mode):
                        try:
                            os.mkdir(localpath, mode=777)
                        except OSError:
                            pass
                        get_r_portable(sftp, remotepath, localpath, preserve_mtime)
                    elif S_ISREG(mode):
                        sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

            remote_path = input("enter the remote_path: ")
            local_path = input("enter the local_path: ")

            get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
        except socket.herror:
            print("Unknown host")
except:
    print("connection failed")

Outcome should be the uncommon files that are present in remote directory and not in local directory.

Body:
def getFilesList(path):
files = []
for (dirpath, dirnames, filenames) in os.walk(path):
    files.extend(filenames)
    return files
ServerFiles = getFilesList(Srverpath)
LocalFiles = getFilesList(Lclpath)
fileDiffList = []
for file in ServerFiles:
    if file in LocalFiles:
        pass
    else:
        fileDiffList.append(file)

We can get the uncommon files by using 2 separate lists.
Call getFilesList method twice by passing your server path and local file path.
At the end your 'fileDiffList' will have file names


问:
Connecting to SSH using a bash script
I am trying to write a bash script to make things faster. Is it not possible to connect to the server with the code below in a bash script? I can't make it work, even though it works in the terminal.

```<code>#!/bin/bash -x
echo "Starting connection script"
sh -i /home/EC2_KEY_HEHE.pem ubuntu@ec2-IP.blabla.amazonaws.com
</code>```

What I get when I run is a not found output for each line in the pem file,

```<code>$ /home/EC2_KEY_HEHE.pem: 1: /home/EC2_KEY_HEHE.pem: -----BEGIN: not found
$ /home/EC2_KEY_HEHE.pem: 1: /home/EC2_KEY_HEHE.pem: adsnaleAFemasdsdsdnds: not foundMadfdasfdasfnda;vonraada
...
</code>```

答: you are calling sh which is kind of shell change it to ssh

Title: Connecting to SSH using a bash script

Body:
I am trying to write a bash script to make things faster. Is it not possible to connect to the server with the code below in a bash script? I can't make it work, even though it works in the terminal.

#!/bin/bash -x
echo "Starting connection script"
sh -i /home/EC2_KEY_HEHE.pem ubuntu@ec2-IP.blabla.amazonaws.com

What I get when I run is a not found output for each line in the pem file,

$ /home/EC2_KEY_HEHE.pem: 1: /home/EC2_KEY_HEHE.pem: -----BEGIN: not found
$ /home/EC2_KEY_HEHE.pem: 1: /home/EC2_KEY_HEHE.pem: adsnaleAFemasdsdsdnds: not foundMadfdasfdasfnda;vonraada
...


问:
How to create a 302 GET request with postman?
In postman I want to create a GET request that returns a 302 status code (along with a Location response header). I have been trying to replicate the original request from the browser inspector, but I always get a 200 response (and no Location response header).

How can I get the desired response with the Location response header?

答: Please try to turn off automatical redirects (File->Settings: General Tab):


问:
Append values from dataframe column to list
I have a dataframe with several columns, and I want to append to an empty list the values of one column, so that the desired output would be the following:

```<code>empty_list = [value_1,value_2,value_3...]
</code>```

I have tried the following:

```<code>df = pd.DataFrame({'country':['a','b','c','d'],
      'gdp':[1,2,3,4],
      'iso':['x','y','z','w']})
a_list = []

a_list.append(df['iso'])
a_list.append(df['iso'].values)
a_list.append(df['iso'].tolist())
</code>```

Either way, I get a list with lists, numpy arrays or series inside it, and I would like to have directly the records.

答:
extend does what you ask for . If you try do this with append, you can do something like:

```<code>import itertools
a_list = []
a_list.append(df.iso.tolist())
a_list.append(df.country.tolist())
a_list=list(itertools.chain.from_iterable(a_list))
print(a_list)
</code>```

Output

```<code>['x', 'y', 'z', 'w', 'a', 'b', 'c', 'd']
</code>```

Body:
I have a dataframe with several columns, and I want to append to an empty list the values of one column, so that the desired output would be the following:

empty_list = [value_1,value_2,value_3...]

I have tried the following:

df = pd.DataFrame({'country':['a','b','c','d'],
      'gdp':[1,2,3,4],
      'iso':['x','y','z','w']})
a_list = []

a_list.append(df['iso'])
a_list.append(df['iso'].values)
a_list.append(df['iso'].tolist())

Either way, I get a list with lists, numpy arrays or series inside it, and I would like to have directly the records.

Body:
extend does what you ask for . If you try do this with append, you can do something like:

import itertools
a_list = []
a_list.append(df.iso.tolist())
a_list.append(df.country.tolist())
a_list=list(itertools.chain.from_iterable(a_list))
print(a_list)

Output

['x', 'y', 'z', 'w', 'a', 'b', 'c', 'd']


问:
My Bootstrap CSS link doesn't work for me?
I have a problem with the Bootstrap link which usually goes into the HTML file:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</code>```

It makes my navbar looks like:

(I need at least 10 reputation to post images, so I have to post the direct link)
https://i.imgur.com/dANnzzG.png

and after I remove the link:

(I need at least 10 reputation to post images, so I have to post the direct link)
 https://i.imgur.com/EpnZCeK.png

But as you can see on the 2 picture, if I dont have the link, the stuff down the navbar ins't in the right position anymore. Please Help.

EDIT:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="row">
  <div class="col-6">
      <app-list-employees></app-list-employees>
</div>
  <div class="col-6">
     <div><app-book-employee></app-book-employee></div>
     <p></p>
    <div><app-calendar-books></app-calendar-books></div>
  </div>
</div>
</code>```

That's the code for the component.

答:
In the root of your project is the angular.json file.
If you want to use a CDN for bootstrap (like you use now), look for the styles object in this file (probaply between line 25 and 35), in there you can add your link. it should look like this:

```<code> "projects": {
      "architect": {
        "build": {
          "styles": [
            "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          ]
        }
      }
    }
</code>```

Body:
I have a problem with the Bootstrap link which usually goes into the HTML file:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

It makes my navbar looks like:

(I need at least 10 reputation to post images, so I have to post the direct link)
https://i.imgur.com/dANnzzG.png

and after I remove the link:

(I need at least 10 reputation to post images, so I have to post the direct link)
 https://i.imgur.com/EpnZCeK.png

But as you can see on the 2 picture, if I dont have the link, the stuff down the navbar ins't in the right position anymore. Please Help.

EDIT:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

      <app-list-employees></app-list-employees>

<app-book-employee></app-book-employee>

<app-calendar-books></app-calendar-books>

That's the code for the component.

Body:
In the root of your project is the angular.json file.
If you want to use a CDN for bootstrap (like you use now), look for the styles object in this file (probaply between line 25 and 35), in there you can add your link. it should look like this:

 "projects": {
      "architect": {
        "build": {
          "styles": [
            "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          ]
        }
      }
    }


问:
What is the best approach to store menu items in a web application?
I am going to develop a web application using J2EE. I need to implement a menubar for my application (like any other menubar) and I want to know what is the best approach to storing menu items in my application. For example:

Storing menu and submenu info in DB and retrieving them.

Using another structures like a XML file.

...

Thanks in advance.

答:
In my recent project we've stored navigation objects in DB.

Pros:

security (if user role has been changed you can receive real-time response with new navigation)

no reasons to deal with security in Front (pros for front-end developers)

Cons:

to many requests (especially if this very high loaded system)

big amount of work for Back end developers


问:
defining global const string variable to be accessed by threads in function calls
Allow a constant string to be globally accessed by various threads calling a function.

I have the following code which chooses a random char from a list of chars (the permitted alphabet) and appends it to form a random word. I am using this for a genetic algorithm but when I am trying to parallelize it to make it faster (homework assignment) but it ends up going slower. After asking my professor and fixing most of the problems, the last detail is that my alphabet doesn't allow multiple threads to read at the same time.

I have tried defining GENES then using #pragma omp threadprivate(GENES) which is the command that my professor said would work.

I tried

```<code>const string GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ"
#pragma omp threadprivate(GENES)
</code>```

Which returns this when compiled.

```<code>error: ‘GENES’ declared ‘threadprivate’ after first use
</code>```

I also tried

```<code>string GENES;
#pragma omp threadprivate(GENES)
GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ;
</code>```

which returns:

```<code>error: ‘GENES’ declared ‘threadprivate’ after first use
#pragma omp threadprivate(GENES)
                             ^
error: ‘GENES’ does not name a type
GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ 1234567890, .-;:_!\"#%&/()=?@${[]}";
</code>```

Finally I tried defining GENES in the threads and passing them as a parameter or hard encoding them into the function. All of these make the program slower.

I expected the program to go faster, but it actually goes slower, from 0.5 sec to 1-3 sec after adding threads. I checked and this is not due to the time in creating the threads.

This should be fixed by making the string accessible by all threads but I can't seem to compile and run any solutions I have found successfully.

答:
my alphabet doesn't allow multiple threads to read at the same time.

That's not true.

It is perfectly fine to read from a std::string with multiple threads! Since this it is const, no thread can actually write to it1. It is both correct and fast2.

In C++ in general, const loosely implies thread-safe. Keep GENES shared, this is most likely not the reason for your performance issue.

If you aim to figure out your performance issues, I suggest using appropriate performance analysis tools for your platform that are aware of threading / OpenMP. If you want to ask a question on how to improve your program's parallel performance please make sure to

Include a minimal, reproducible example. That doesn't mean to include your entire program. But a minimal version that exhibits the performance issue.

Share your specific measurement results and methodology.

Tell us how you compile the program and the specifications of the system you run it on (CPU & memory)

1: Assuming no evil const_casts

2: Unless you put a mutable global variable on the same cache-line, which seems rather unlikely.

Body:
Allow a constant string to be globally accessed by various threads calling a function.

I have the following code which chooses a random char from a list of chars (the permitted alphabet) and appends it to form a random word. I am using this for a genetic algorithm but when I am trying to parallelize it to make it faster (homework assignment) but it ends up going slower. After asking my professor and fixing most of the problems, the last detail is that my alphabet doesn't allow multiple threads to read at the same time.

I have tried defining GENES then using #pragma omp threadprivate(GENES) which is the command that my professor said would work.

I tried

const string GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ"
#pragma omp threadprivate(GENES)

Which returns this when compiled.

error: ‘GENES’ declared ‘threadprivate’ after first use

I also tried

string GENES;
#pragma omp threadprivate(GENES)
GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ;

which returns:

error: ‘GENES’ declared ‘threadprivate’ after first use
#pragma omp threadprivate(GENES)
                             ^
error: ‘GENES’ does not name a type
GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ 1234567890, .-;:_!\"#%&/()=?@${[]}";

Finally I tried defining GENES in the threads and passing them as a parameter or hard encoding them into the function. All of these make the program slower.

I expected the program to go faster, but it actually goes slower, from 0.5 sec to 1-3 sec after adding threads. I checked and this is not due to the time in creating the threads.

This should be fixed by making the string accessible by all threads but I can't seem to compile and run any solutions I have found successfully.


问:
GetWindowTextLength returns 0 when text is in the edit control
I'm writing a text editor and am having some issues with saving files as utf-8.
I have a function that reads text from a rich edit control and writes it to a file
using a flag passed to the function which depends on a user setting. It can be utf-16, ascii, or utf-8. Both utf-16 and ascii file writing segments work fine and produce valid files.
The problem lies in that in the following block of code the call to GetWindowTextLength always returns 0. So, the result is that nothing ever gets retrieved from the window or written to the file.

```<code> HANDLE hFile;
 if ((hFile = CreateFile (pstrFileName, GENERIC_WRITE, 0,
      NULL, CREATE_ALWAYS, 0, NULL)) == INVALID_HANDLE_VALUE) {
      return FALSE;
 }

 int    iLength = 0;
 DWORD  dwBytesWritten = 0;

 switch (encoding) {

/*other text encoding cases*/

     case ID_SETTINGS_UTF_8: {
        try {
            iLength = GetWindowTextLength(hwndEdit);  //returns 0

            unique_ptr<wchar_t> wide_buf(new wchar_t[iLength + 1]);
            GetWindowTextW(hwndEdit, wide_buf.get(), iLength + 1);

            int bytes_needed = WideCharToMultiByte(CP_UTF8, WC_COMPOSITECHECK |
                WC_DEFAULTCHAR | WC_NO_BEST_FIT_CHARS, wide_buf.get(), -1,
                NULL, 0, NULL, NULL);

            unique_ptr<char> utf8_buf(new char[bytes_needed]);

            WideCharToMultiByte(CP_UTF8, WC_COMPOSITECHECK |
                WC_DEFAULTCHAR | WC_NO_BEST_FIT_CHARS, wide_buf.get(), -1,
                utf8_buf.get(), bytes_needed, NULL, NULL);

            WriteFile(hFile, utf8_buf.get(), bytes_needed,
                        &dwBytesWritten, NULL);

            if (bytes_needed != dwBytesWritten) {
                        CloseHandle (hFile);
                         return FALSE;
            }

             CloseHandle (hFile) ;
             return TRUE;
        } catch (bad_alloc& ba) {
            UNREFERENCED_PARAMETER(ba);
            CloseHandle (hFile);
            return FALSE;
        }
    }
    break;
</code>```

答:
You corrupt the heap. new[] must be matched by delete[], not delete.

It's simpler to just use std::vector:

```<code>std::vector<wchar_t> wide_buf(iLength + 1);
//...
std::vectorchar> utf8_buf(bytes_needed);
</code>```

Body:
I'm writing a text editor and am having some issues with saving files as utf-8.
I have a function that reads text from a rich edit control and writes it to a file
using a flag passed to the function which depends on a user setting. It can be utf-16, ascii, or utf-8. Both utf-16 and ascii file writing segments work fine and produce valid files.
The problem lies in that in the following block of code the call to GetWindowTextLength always returns 0. So, the result is that nothing ever gets retrieved from the window or written to the file.

 HANDLE hFile;
 if ((hFile = CreateFile (pstrFileName, GENERIC_WRITE, 0,
      NULL, CREATE_ALWAYS, 0, NULL)) == INVALID_HANDLE_VALUE) {
      return FALSE;
 }

 int    iLength = 0;
 DWORD  dwBytesWritten = 0;

 switch (encoding) {

/*other text encoding cases*/

     case ID_SETTINGS_UTF_8: {
        try {
            iLength = GetWindowTextLength(hwndEdit);  //returns 0

            unique_ptr<wchar_t> wide_buf(new wchar_t[iLength + 1]);
            GetWindowTextW(hwndEdit, wide_buf.get(), iLength + 1);

            int bytes_needed = WideCharToMultiByte(CP_UTF8, WC_COMPOSITECHECK |
                WC_DEFAULTCHAR | WC_NO_BEST_FIT_CHARS, wide_buf.get(), -1,
                NULL, 0, NULL, NULL);

            unique_ptr<char> utf8_buf(new char[bytes_needed]);

            WideCharToMultiByte(CP_UTF8, WC_COMPOSITECHECK |
                WC_DEFAULTCHAR | WC_NO_BEST_FIT_CHARS, wide_buf.get(), -1,
                utf8_buf.get(), bytes_needed, NULL, NULL);

            WriteFile(hFile, utf8_buf.get(), bytes_needed,
                        &dwBytesWritten, NULL);

            if (bytes_needed != dwBytesWritten) {
                        CloseHandle (hFile);
                         return FALSE;
            }

             CloseHandle (hFile) ;
             return TRUE;
        } catch (bad_alloc& ba) {
            UNREFERENCED_PARAMETER(ba);
            CloseHandle (hFile);
            return FALSE;
        }
    }
    break;

Body:
You corrupt the heap. new[] must be matched by delete[], not delete.

It's simpler to just use std::vector:

std::vector<wchar_t> wide_buf(iLength + 1);
//...
std::vectorchar> utf8_buf(bytes_needed);


问:
Toggle database value from View on button click Laravel
I am using Laravel framework as a backend API and a few blade PHP files for the front end, specifically for the authentication and the admin panel from the /admin route.
In /admin, I display a list of all registered users and buttons next to them. (This page is only visible for users that have their value in Admin column set as true). I want to toggle the Admin status of a user, either promoting or demoting them by clicking the button next to the user name.
For this, I tried to use a form submit with get method.
I have a method defined inside UserController like this:

```<code>public function setAdmin($id) {
    $user = User::find($id);
    $user->admin = !$user->admin;
    if($user->save()) {
        echo "Changed";
    }
    else {
        echo "Could not be changed";
    }
}
</code>```

I want to call this method from the view on the click of a button.

I tried using a Form to send a request by specifying the action, but it gave an error saying the values passed are less than the expected number of parameters.

```<code>{!! Form::open(['action' => ['UserController@setAdmin', $user->id], 'method' => 'POST']) !!}
{{  Form::submit('Submit', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}
</code>```

I have a route set up explicitly to call this action

```<code>Route::post('/admin/users/setAdmin', 'UserController@setAdmin')
</code>```

Although I am not sure if I have to set an explicit route for this action or if it's possible to call a controller function directly from a view without defining the route.

I have iterated through User Model to display all users:

```<code>@if(count($users) > 0)
    @foreach($users as $user)
        <div class="card">
            {{ $user }}
        </div>

        {!! Form::open(['action' => ['UserController@setAdmin', $user->id], 'method' => 'POST']) !!}
        {{  Form::submit('Submit', ['class' => 'btn btn-primary']) }}
        {!! Form::close() !!}
    @endforeach
@else
    <h2>No users found!</h2>
@endif
</code>```

EDIT: Added the foreach section of the blade file. Also I modified the 'action' part of the Form::open() parameters, it was a mistype, the parameters error is still there.

Can someone explain how this can be done?

答:
You are trying to pass a parameter to your route but there is any within its declaration. You need to add it in your route path:

Route::post('/admin/users/setAdmin/{id}', 'UserController@setAdmin')
```

<hr>

<p>If you don't want to have an URL like this, you should add a hidden input to your form containing your ID:</p>

<pre class="lang-html prettyprint-override"><code>{!! Form::open(['action' => ['UserController@setAdmin'], 'method' => 'POST']) !!}

{{ Form::hidden('id', $user->id) }}
{{ Form::submit('Submit', ['class' => 'btn btn-primary']) }}

{!! Form::close() !!}
</code>```

And in your controller's method:

use Request;

/* ... */

public function setAdmin(Request $request) {
    $user = User::find($request->id);

    /* ... */
}
```

Body:
I am using Laravel framework as a backend API and a few blade PHP files for the front end, specifically for the authentication and the admin panel from the /admin route.
In /admin, I display a list of all registered users and buttons next to them. (This page is only visible for users that have their value in Admin column set as true). I want to toggle the Admin status of a user, either promoting or demoting them by clicking the button next to the user name.
For this, I tried to use a form submit with get method.
I have a method defined inside UserController like this:

public function setAdmin($id) {
    $user = User::find($id);
    $user->admin = !$user->admin;
    if($user->save()) {
        echo "Changed";
    }
    else {
        echo "Could not be changed";
    }
}

I want to call this method from the view on the click of a button.

I tried using a Form to send a request by specifying the action, but it gave an error saying the values passed are less than the expected number of parameters.

{!! Form::open(['action' => ['UserController@setAdmin', $user->id], 'method' => 'POST']) !!}
{{  Form::submit('Submit', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}

I have a route set up explicitly to call this action

Route::post('/admin/users/setAdmin', 'UserController@setAdmin')

Although I am not sure if I have to set an explicit route for this action or if it's possible to call a controller function directly from a view without defining the route.

I have iterated through User Model to display all users:

@if(count($users) > 0)
    @foreach($users as $user)

            {{ $user }}

        {!! Form::open(['action' => ['UserController@setAdmin', $user->id], 'method' => 'POST']) !!}
        {{  Form::submit('Submit', ['class' => 'btn btn-primary']) }}
        {!! Form::close() !!}
    @endforeach
@else

No users found!

@endif

EDIT: Added the foreach section of the blade file. Also I modified the 'action' part of the Form::open() parameters, it was a mistype, the parameters error is still there.

Can someone explain how this can be done?

Body:
You are trying to pass a parameter to your route but there is any within its declaration. You need to add it in your route path:

Route::post('/admin/users/setAdmin/{id}', 'UserController@setAdmin')

If you don't want to have an URL like this, you should add a hidden input to your form containing your ID:

{!! Form::open(['action' => ['UserController@setAdmin'], 'method' => 'POST']) !!}

{{ Form::hidden('id', $user->id) }}
{{ Form::submit('Submit', ['class' => 'btn btn-primary']) }}

{!! Form::close() !!}

And in your controller's method:

use Request;

/* ... */

public function setAdmin(Request $request) {
    $user = User::find($request->id);

    /* ... */
}


问:
Serial Communication issue in hardware interface with python platform
I have one hardware which uses Asynchronous serial interface protocol, 9600 baud rate, #Start bits  1,#Data bits    8, #Stop bits   1, Parity   None.
When I am communicating my hardware with a python script using a cp2102 device that time hardware doesn't respond but when I try to communicate the same hardware with Arduino nano then it works properly.

Working Arduino code:

```<code>void volt_currentTest()
{
 Serial.write(0xDD);
 Serial.write(0xA5);
 Serial.write(0x03);
 Serial.write(0x00);
 Serial.write(0xFF);
 Serial.write(0xFD);
 Serial.write(0x77);

  while(c != 0x77)
  {
    if(Serial.available())
    {
      if((c = Serial.read()) != -1)
      {
           Serial.println(c , HEX);
        d[i] = c;
        i++;
      }
    }
  }
}
</code>```

Python code:

```<code>import serial
ser = serial.Serial(
    'COM9', 9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE
)

'''data = b'\xdd\xa5\x03\x00\xff\xfd\x77'
ser.write(data)'''

ser.write(b'\xDD')
ser.write(b'\xA5')
ser.write(b'\x03')
ser.write(b'\x00')
ser.write(b'\xFF')
ser.write(b'\xFD')
ser.write(b'\x77')

'''
ser.write('\xDD\r\n'.encode())
ser.write('\xA5\r\n'.encode())
ser.write('\x03\r\n'.encode())
ser.write('\x00\r\n'.encode())
ser.write('\xFF\r\n'.encode())
ser.write('\xFD\r\n'.encode())
ser.write('\x77\r\n'.encode())
'''

while True:
    response = ser.read()

    '''response = ser.readline()
      '''
     print(response)
</code>```

So Anyone having an idea why it's not working .....

答:
You probably need to call ser.flush() after all the write()s, but before the 'while' loop.

Python's serial.Serial uses buffered I/O by default – all your writes wait until you call flush(), after which they're sent in one batch.

OwnerDisplayName: Unknown

Body:
I have one hardware which uses Asynchronous serial interface protocol, 9600 baud rate, #Start bits  1,#Data bits    8, #Stop bits   1, Parity   None.
When I am communicating my hardware with a python script using a cp2102 device that time hardware doesn't respond but when I try to communicate the same hardware with Arduino nano then it works properly.

Working Arduino code:

void volt_currentTest()
{
 Serial.write(0xDD);
 Serial.write(0xA5);
 Serial.write(0x03);
 Serial.write(0x00);
 Serial.write(0xFF);
 Serial.write(0xFD);
 Serial.write(0x77);

  while(c != 0x77)
  {
    if(Serial.available())
    {
      if((c = Serial.read()) != -1)
      {
           Serial.println(c , HEX);
        d[i] = c;
        i++;
      }
    }
  }
}

Python code:

import serial
ser = serial.Serial(
    'COM9', 9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE
)

'''data = b'\xdd\xa5\x03\x00\xff\xfd\x77'
ser.write(data)'''

ser.write(b'\xDD')
ser.write(b'\xA5')
ser.write(b'\x03')
ser.write(b'\x00')
ser.write(b'\xFF')
ser.write(b'\xFD')
ser.write(b'\x77')

'''
ser.write('\xDD\r\n'.encode())
ser.write('\xA5\r\n'.encode())
ser.write('\x03\r\n'.encode())
ser.write('\x00\r\n'.encode())
ser.write('\xFF\r\n'.encode())
ser.write('\xFD\r\n'.encode())
ser.write('\x77\r\n'.encode())
'''

while True:
    response = ser.read()

    '''response = ser.readline()
      '''
     print(response)

So Anyone having an idea why it's not working .....

OwnerDisplayName: grawity