问:
How to schedule events with msql
I'm trying to make an event that will execute every 1 hour.

Here is the code.

```<code>mysql> DROP EVENT IF EXISTS `clean`;

CREATE EVENT IF NOT EXISTS `clean`
       ON SCHEDULE
         EVERY 1 HOUR
         STARTS '2017-07-07 16:00.00'
         DO
           SET @isTime = IF(table_name.programed_time = NOW(), 'y', 'n');
           IF @isTime = 'y' THEN DELETE FROM `cell_name`
             WHERE `cell_name` = 'value'
</code>```

I want the event to run only on Mondays at 16:00. So in my app I have the code to save the date of each 1st Monday of each month at 16:00 in a table.

But I'm having this error when I run this query.

```<code>Unknown type of declaration near to IF.
Something is wrong in its syntax near 'IF @isTime ='y'
THEN DELETE FROM `cell_name` WHERE `cell_name 'in the line
</code>```

Someone could tell me what I doing wrong.

答:
I found the best way to do what I want, without having to create variables or store the date in the database.

Here is the code I use.

```<code>DROP EVENT IF EXISTS `clean`;

DELIMITER //

CREATE EVENT IF NOT EXISTS `clean`
       ON SCHEDULE
         EVERY 1 DAY
         STARTS '2017-01-27 16:00.00'
         COMMENT 'EVENT runs daily at 4 pm. DELETE executed first Monday month'
         DO
           BEGIN
             IF (DAYOFMONTH(NOW()) BETWEEN 1 AND 7 AND
                 DAYNAME(NOW()) = 'Monday') THEN
               DELETE FROM `table_name`
               WHERE `cell_name` = 'value';
             END IF;
           END//

DELIMITER ;
</code>```

Title: How to schedule events with msql

Body:
I'm trying to make an event that will execute every 1 hour.

Here is the code.

mysql> DROP EVENT IF EXISTS `clean`;

CREATE EVENT IF NOT EXISTS `clean`
       ON SCHEDULE
         EVERY 1 HOUR
         STARTS '2017-07-07 16:00.00'
         DO
           SET @isTime = IF(table_name.programed_time = NOW(), 'y', 'n');
           IF @isTime = 'y' THEN DELETE FROM `cell_name`
             WHERE `cell_name` = 'value'

I want the event to run only on Mondays at 16:00. So in my app I have the code to save the date of each 1st Monday of each month at 16:00 in a table.

But I'm having this error when I run this query.

Unknown type of declaration near to IF.
Something is wrong in its syntax near 'IF @isTime ='y'
THEN DELETE FROM `cell_name` WHERE `cell_name 'in the line

Someone could tell me what I doing wrong.

Body:
I found the best way to do what I want, without having to create variables or store the date in the database.

Here is the code I use.

DROP EVENT IF EXISTS `clean`;

DELIMITER //

CREATE EVENT IF NOT EXISTS `clean`
       ON SCHEDULE
         EVERY 1 DAY
         STARTS '2017-01-27 16:00.00'
         COMMENT 'EVENT runs daily at 4 pm. DELETE executed first Monday month'
         DO
           BEGIN
             IF (DAYOFMONTH(NOW()) BETWEEN 1 AND 7 AND
                 DAYNAME(NOW()) = 'Monday') THEN
               DELETE FROM `table_name`
               WHERE `cell_name` = 'value';
             END IF;
           END//

DELIMITER ;


来源: stackexchange

问:
Change item ordering in sonata_type_model
In my Admin I'v defined this:

```<code> protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
    /* ... */
    ->add('camps', 'sonata_type_model', array(
        'btn_add'       => false,      //Specify a custom label
        'choices'        => $this->tema_service->getCampsDefinicio($this->getSubject()),
        'sortable'     => true,
        'multiple' => true,
            ), array(
                'placeholder' => 'No selected'
            ))

;
/* ... */
}
</code>```

Function getCampsDefinicio returns an array of items ordered. Inspite of it, the options appear sorted according its id.

What can I do to get it respect the order given?

It does not care if I have to override any template. In that case which files I have to look for/override?

答:
Finally I solved this.

I was a little confused.

The order in the choises array is respected only for selectionable items.

The order for the SELECTED items is defined by te ArrayCollection provided in the entity function

```<code>/**
 * Get camps
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getCamps()
{
   return $this->camps;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my Admin I'v defined this:

 protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
    /* ... */
    ->add('camps', 'sonata_type_model', array(
        'btn_add'       => false,      //Specify a custom label
        'choices'        => $this->tema_service->getCampsDefinicio($this->getSubject()),
        'sortable'     => true,
        'multiple' => true,
            ), array(
                'placeholder' => 'No selected'
            ))

;
/* ... */
}

Function getCampsDefinicio returns an array of items ordered. Inspite of it, the options appear sorted according its id.

What can I do to get it respect the order given?

It does not care if I have to override any template. In that case which files I have to look for/override?

Body:
Finally I solved this.

I was a little confused.

The order in the choises array is respected only for selectionable items.

The order for the SELECTED items is defined by te ArrayCollection provided in the entity function

/**
 * Get camps
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getCamps()
{
   return $this->camps;
}


问:
How to fix the image to a div when it's height is greater than its width?
In Facebook, when we post any size images, it shows perfectly on the timeline. How do they do this?

I have tried following.

Setting the image as background of the div.

CSS - width: 100%; height:auto;

Both did not work, All over the stack overflow there is no option for this,finally decided to add this.

答:
If your parent div has fixed dimensions you can use CSS to scale images while maintaining the aspect ratio for both landscape and portrait photos.

The images will always fit inside the div.

.container {
  width: 400px;
  height: 400px;
  text-align: center;
  background: red;
}

img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Landscape</h1>
<div class="container">
  <img src="https://unsplash.it/1600/800">
</div>
<h1>Portrait</h1>
<div class="container blue">
  <img src="https://unsplash.it/800/1600">
</div></code>```

Body:
If your parent div has fixed dimensions you can use CSS to scale images while maintaining the aspect ratio for both landscape and portrait photos.

The images will always fit inside the div.

.container {
  width: 400px;
  height: 400px;
  text-align: center;
  background: red;
}

img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}

<h1>Landscape</h1>
<div class="container">
  <img src="https://unsplash.it/1600/800">
</div>
<h1>Portrait</h1>
<div class="container blue">
  <img src="https://unsplash.it/800/1600">
</div>


问:
how to stop recursion and/or restart the current function with updated variables
I've got two arrays which are updating themselves and each other based on criteria (it is way longer to describe than I suspect the solution is).

What I end up with is a function which calls itself within a while loop. As you can imagine, this causes a ridiculous amount of recursion.

Here's an example (keeping it short)

```
var buildArray=firstFunction(new Array(), existingArray)

function firstFunction(thisArray, existingArray){
     for(test1=0; test1<existingArray.length; test1++){
         if(existingArray[test1][3]=='2'){
           secondFunction(thisArray, existingArray, test1);
        }
     }

function secondFunction(thisArray, existingArray, t1){
       for(test2=0; test2<thisArray.length; test2++){
          if(thisArray[test1]<=existingArray[test2][1] || thisArray[test1]>existingArray[test2[0]){
            // do a bunch of stuff to existingArray, now that existingArray has changed, the whole process needs to start again FROM THE BEGINNING!!!
     return firstFunction(new Array(), existingArray);

              // check that the value isn't already in the 'thisArray'
   var check= new Array(existingArray[test1]);
  else if (jQuery.inArray(check, thisArray==-1){
         // value isn't in the new array, so add it
        thisArray.push(check);
       // thisArray has changed. need to restart the the second function
       secondFunction(thisArray,existingArray);
     }

   }
 }

}
}
```

I was hoping that

```return secondFunction(thisArray, existingArray);
```

would reset and restart the function, but apparently that isn't happening.

Is there a way to stop the current function and loops and restart with the updated variables?

答:
Some things I noticed:

in secondFunction() you access test1 even though you have a parameter t1

the second call to secondFunction() doesn't contain that last parameter

the second call to secondFunction() doesn't have a return before it even though you mentioned it in your OP

there's a line else if (jQuery.inArray(check, thisArray==-1){, which is missing a ")"

there's a line if(thisArray[test1]<=existingArray[test2][1] || thisArray[test1]>existingArray[test2[0]){ missing a "]"

in for(test1=0; test1<existingArray.length; test1++){ it should be for(var test1... to let the parser know it's a variable on its own in the recursion (assuming you want this to happen of course)

in for(test2=0; test2<thisArray.length; test2++){ it should be for(var test2... to let the parser know it's a variable on its own in the recursion (assuming you want this to happen of course)

...

I'm saying that you edited the code to post it here. That is fine of course, but it makes me believe that some part of the code is missing.

As far as the missing vars is concerned, that may be in your interest, but the parser may get confused. If there's no var the variable is defined at document-level, not at function-level nor at the innermost scope. I don't know if you aware of this or if it's an issue.

ContentLicense: CC BY-SA 2.5

Body:
I've got two arrays which are updating themselves and each other based on criteria (it is way longer to describe than I suspect the solution is).

What I end up with is a function which calls itself within a while loop. As you can imagine, this causes a ridiculous amount of recursion.

Here's an example (keeping it short)

var buildArray=firstFunction(new Array(), existingArray)

function firstFunction(thisArray, existingArray){
     for(test1=0; test1<existingArray.length; test1++){
         if(existingArray[test1][3]=='2'){
           secondFunction(thisArray, existingArray, test1);
        }
     }

function secondFunction(thisArray, existingArray, t1){
       for(test2=0; test2<thisArray.length; test2++){
          if(thisArray[test1]<=existingArray[test2][1] || thisArray[test1]>existingArray[test2[0]){
            // do a bunch of stuff to existingArray, now that existingArray has changed, the whole process needs to start again FROM THE BEGINNING!!!
     return firstFunction(new Array(), existingArray);

              // check that the value isn't already in the 'thisArray'
   var check= new Array(existingArray[test1]);
  else if (jQuery.inArray(check, thisArray==-1){
         // value isn't in the new array, so add it
        thisArray.push(check);
       // thisArray has changed. need to restart the the second function
       secondFunction(thisArray,existingArray);
     }

   }
 }

}
}

I was hoping that

return secondFunction(thisArray, existingArray);

would reset and restart the function, but apparently that isn't happening.

Is there a way to stop the current function and loops and restart with the updated variables?


问:
How to store uploaded files in a directory of the main domain from a subdomain upload form
please how can store uploaded file in my main domain directory should it be like this:</p>

```<code>move_uploaded_file(https://example.com/uploads)
</code>```

答:
This would be a quick and dirty way to do it( assuming you're in the root directory of your subdomain and your main domain is its own folder( if your main directory does not have its own folder remove the 2nd chdir)

Im assuming youre uploading an image. if not make the changes as necessary

```<code>chdir(dirname("../"));// this takes you up one level
chdir("main_directory");// use this only if main directory is inside a folder

 $filepath = getcwd() . DIRECTORY_SEPARATOR . 'images' .DIRECTORY_SEPARATOR;
                if (!file_exists($filepath)) {
                    mkdir($filepath, 0755);// this is only to create a new images folder if it doesnt exist
                }
                chdir($filepath);
                $filename = 'file_name_you_want';
                $info = pathinfo($_FILES['img']['name']);
                $ext = $info['extension'];
                $newname = $filename . "." . $ext;
                $types = array('image/jpeg', 'image/jpg', 'image/png');
                if (in_array($_FILES['img']['type'], $types)) {
                    if (move_uploaded_file($_FILES["img"]["tmp_name"], $newname)) {
                        $img_path = 'images' . DIRECTORY_SEPARATOR . $newname;

                    } else {
                         // do what needs to be done
                    }
</code>```

If youre using php 7 you might want to take a look at string

```<code> dirname ( string $path [, int $levels = 1 ] );// the 2nd param would be how many levels up you want to go and $path can be your current directory using __DIR__
</code>```

Body:
please how can store uploaded file in my main domain directory should it be like this:

move_uploaded_file(https://example.com/uploads)

Body:
This would be a quick and dirty way to do it( assuming you're in the root directory of your subdomain and your main domain is its own folder( if your main directory does not have its own folder remove the 2nd chdir)

Im assuming youre uploading an image. if not make the changes as necessary

chdir(dirname("../"));// this takes you up one level
chdir("main_directory");// use this only if main directory is inside a folder

 $filepath = getcwd() . DIRECTORY_SEPARATOR . 'images' .DIRECTORY_SEPARATOR;
                if (!file_exists($filepath)) {
                    mkdir($filepath, 0755);// this is only to create a new images folder if it doesnt exist
                }
                chdir($filepath);
                $filename = 'file_name_you_want';
                $info = pathinfo($_FILES['img']['name']);
                $ext = $info['extension'];
                $newname = $filename . "." . $ext;
                $types = array('image/jpeg', 'image/jpg', 'image/png');
                if (in_array($_FILES['img']['type'], $types)) {
                    if (move_uploaded_file($_FILES["img"]["tmp_name"], $newname)) {
                        $img_path = 'images' . DIRECTORY_SEPARATOR . $newname;

                    } else {
                         // do what needs to be done
                    }

If youre using php 7 you might want to take a look at string

 dirname ( string $path [, int $levels = 1 ] );// the 2nd param would be how many levels up you want to go and $path can be your current directory using __DIR__


问:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '5' for key 'PRIMARY'
Firtst of all, I added ten records into my databases manually. Then I ran the project, it went wrong like this: Duplicate entry '1' for key 'PRIMARY'. Then I refreshed the page nine times, it shown from "Duplicate entry '2' for key 'PRIMARY'" to "Duplicate entry '10' for key 'PRIMARY". Finally, the project became normal, which means I can insert item into the database from the eleven record on. What's wrong?

I use the hibernate in verison 5.10 final. And I will show my code block in the following:

My confusion is that the table created by the project did not set for auto_increatement. as following:
pictures
this is a picture

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>

        <property name="packagesToScan" value="com"/>

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.implicit_naming_strategy">legacy-jpa</prop>

                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>

                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
            </props>
        </property>

        <property name="sharedCacheMode" value="ENABLE_SELECTIVE"/>
    </bean>
```

<pre class="lang-java prettyprint-override"><code>import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import java.util.Date;

@Table(name = "sssp_empoyee")
@Entity
public class Employee {

    private Integer id;
    private String lastName;
    private String email;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birth;
    private Date crateTime;
    private Department department;

    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "increment")
    @Id
    public Integer getId() {

        return id;
    }

@Transactional
public void saveEmployee(Employee employee) {

    employee.setCrateTime(new Date());

    respository.saveAndFlush(employee);
}
</code>```

error info:

```<code>com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException    : Duplicate entry '5' for key 'PRIMARY'
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.__newInstance(DelegatingConstructorAccessorImpl.java:45)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
com.mysql.jdbc.Util.getInstance(Util.java:381)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3515)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3447)
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951)
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101)
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2554)
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1761)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2046)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1964)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1949)
com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2921)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3421)
org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295)
org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1300)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
com.sun.proxy.$Proxy35.flush(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
java.lang.reflect.Method.invoke(Method.java:498)
</code>```

答:
Modify your table structure, add auto_increment to the id of the column in your table, using the query below:

```<code>ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
</code>```

Body:
Firtst of all, I added ten records into my databases manually. Then I ran the project, it went wrong like this: Duplicate entry '1' for key 'PRIMARY'. Then I refreshed the page nine times, it shown from "Duplicate entry '2' for key 'PRIMARY'" to "Duplicate entry '10' for key 'PRIMARY". Finally, the project became normal, which means I can insert item into the database from the eleven record on. What's wrong?

I use the hibernate in verison 5.10 final. And I will show my code block in the following:

My confusion is that the table created by the project did not set for auto_increatement. as following:
pictures
this is a picture

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>

        <property name="packagesToScan" value="com"/>

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.implicit_naming_strategy">legacy-jpa</prop>

                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>

                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
            </props>
        </property>

        <property name="sharedCacheMode" value="ENABLE_SELECTIVE"/>
    </bean>

import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import java.util.Date;

@Table(name = "sssp_empoyee")
@Entity
public class Employee {

    private Integer id;
    private String lastName;
    private String email;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birth;
    private Date crateTime;
    private Department department;

    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "increment")
    @Id
    public Integer getId() {

        return id;
    }

@Transactional
public void saveEmployee(Employee employee) {

    employee.setCrateTime(new Date());

    respository.saveAndFlush(employee);
}

error info:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException    : Duplicate entry '5' for key 'PRIMARY'
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.__newInstance(DelegatingConstructorAccessorImpl.java:45)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
com.mysql.jdbc.Util.getInstance(Util.java:381)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3515)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3447)
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951)
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101)
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2554)
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1761)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2046)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1964)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1949)
com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2921)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3421)
org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295)
org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1300)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
com.sun.proxy.$Proxy35.flush(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
java.lang.reflect.Method.invoke(Method.java:498)

Body:
Modify your table structure, add auto_increment to the id of the column in your table, using the query below:

ALTER TABLE document MODIFY COLUMN document_id INT auto_increment


问:
windows authentication in ASP.Net
So, i have my virtual directory with Anonymous Access disabled. I allow users to login to my app through the windows server login.
I wish to know how i can, through the code, capture the username that is logging in.

Is this possible?

Thanks

答: HttpRequest.Current.User.Identity.Name or simply User.Identity.Name if you are in a Page should give you the name of the user currently logged in.

Title: windows authentication in ASP.Net


问:
can't open new activity when click on cardview but It shows toast only
I am using cardview for displaying items in gridview. I want to open a new activity but as per my code its shows the toast about the item position. I am not getting where i am making mistake so please help me. Help would be appreciate, thanks in advance.

DataModel.class

```<code>public class DataModel {

    public String text;
    public int drawable;
    public String color;

    public DataModel(String t, int d, String c )
    {
        text=t;
        drawable=d;
        color=c;
    }
}
</code>```

RecyclerViewAdapter.class

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    ArrayList<DataModel> mValues;
    Context mContext;
    protected ItemListener mListener;

    public RecyclerViewAdapter(Context context, ArrayList<DataModel> values, ItemListener itemListener) {

        mValues = values;
        mContext = context;
        mListener=itemListener;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView textView;
        public ImageView imageView;
        public RelativeLayout relativeLayout;
        DataModel item;

        public ViewHolder(View v) {

            super(v);

            v.setOnClickListener(this);
            textView = (TextView) v.findViewById(R.id.textView);
            imageView = (ImageView) v.findViewById(R.id.imageView);
            relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);

        }

        public void setData(DataModel item) {
            this.item = item;

            textView.setText(item.text);
            imageView.setImageResource(item.drawable);
            relativeLayout.setBackgroundColor(Color.parseColor(item.color));

        }

        @Override
        public void onClick(View view) {
            if (mListener != null) {
                mListener.onItemClick(item);
            }
        }
    }

    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_view_item, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder Vholder, int position) {
        Vholder.setData(mValues.get(position));

    }

    @Override
    public int getItemCount() {

        return mValues.size();
    }

    public interface ItemListener {
        void onItemClick(DataModel item);
    }

}
</code>```

MainActivity class

```<code>public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.ItemListener {

        RecyclerView recyclerView;
        ArrayList<DataModel> arrayList;

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

            recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            arrayList = new ArrayList<>();
            arrayList.add(new DataModel("Item 1", R.drawable.downtoearth, "#FFFFFF"));
            arrayList.add(new DataModel("Item 2", R.drawable.beer, "#3E51B1"));
            arrayList.add(new DataModel("Item 3", R.drawable.ferrari, "#673BB7"));
            arrayList.add(new DataModel("Item 4", R.drawable.jetpack_joyride, "#4BAA50"));
            arrayList.add(new DataModel("Item 5", R.drawable.three_d, "#F94336"));
            arrayList.add(new DataModel("Item 6", R.drawable.terraria, "#0A9B88"));

            RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, arrayList, this);
            recyclerView.setAdapter(adapter);

            /**
             AutoFitGridLayoutManager that auto fits the cells by the column width defined.
             **/

            AutoFitGridLayoutManager layoutManager = new AutoFitGridLayoutManager(this, 300);
            recyclerView.setLayoutManager(layoutManager);

            /**
             Simple GridLayoutManager that spans two columns
             **/
            GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
            recyclerView.setLayoutManager(manager);
        }

        @Override
        public void onItemClick(DataModel item) {

        //here toast is
        Toast.makeText(getApplicationContext(), item.text + " is clicked",
             Toast.LENGTH_SHORT).show();

        }
    }
</code>```

after edit i am getting error in the intent.putExtra command

@Override
    public void onItemClick(DataModel item) {

```<code>    Intent intent = new Intent(MainActivity.this, Yojana.class);
    intent.putExtra("dataitem", item);
    startActivity(intent);

}
</code>```

Yojana.class

public class Yojana extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_yojana);
    getIntent().getParcelableExtra("dataitem");

}
</code>```

logcaterror :

```<code>    Error:(56, 15) error: no suitable method found for
    putExtra(String,DataModel)
    method Intent.putExtra(String,boolean) is not applicable
    (argument mismatch; DataModel cannot be converted to boolean)
    method Intent.putExtra(String,byte) is not applicable
    (argument mismatch; DataModel cannot be converted to byte)
    method Intent.putExtra(String,char) is not applicable
    (argument mismatch; DataModel cannot be converted to char)
    method Intent.putExtra(String,short) is not applicable
    (argument mismatch; DataModel cannot be converted to short)
    method Intent.putExtra(String,int) is not applicable
    (argument mismatch; DataModel cannot be converted to int)
    method Intent.putExtra(String,long) is not applicable
    (argument mismatch; DataModel cannot be converted to long)
    method Intent.putExtra(String,float) is not applicable
    (argument mismatch; DataModel cannot be converted to float)
    method Intent.putExtra(String,double) is not applicable
    (argument mismatch; DataModel cannot be converted to double)
    method Intent.putExtra(String,String) is not applicable
    (argument mismatch; DataModel cannot be converted to String)
    method Intent.putExtra(String,CharSequence) is not applicable
    (argument mismatch; DataModel cannot be converted to CharSequence)
    method Intent.putExtra(String,Parcelable) is not applicable
    (argument mismatch; DataModel cannot be converted to Parcelable)
    method Intent.putExtra(String,Parcelable[]) is not applicable
    (argument mismatch; DataModel cannot be converted to Parcelable[])
    method Intent.putExtra(String,Serializable) is not applicable
   (argument mismatch; DataModel cannot be converted to Serializable)
   method Intent.putExtra(String,boolean[]) is not applicable
   (argument mismatch; DataModel cannot be converted to boolean[])
   method Intent.putExtra(String,double[]) is not applicable
   (argument mismatch; DataModel cannot be converted to double[])
   method Intent.putExtra(String,String[]) is not applicable
   (argument mismatch; DataModel cannot be converted to String[])
   method Intent.putExtra(String,CharSequence[]) is not applicable
   (argument mismatch; DataModel cannot be converted to CharSequence[])
   method Intent.putExtra(String,Bundle) is not applicable
   (argument mismatch; DataModel cannot be converted to Bundle)
</code>```

答:
It shows toast because you have written below code:

```<code>Toast.makeText(getApplicationContext(), item.text + " is clicked", Toast.LENGTH_SHORT).show();
</code>```

Insted you should write below code:

```<code>Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("dataitem", item);
startActivity(intent);
</code>```

Body:
I am using cardview for displaying items in gridview. I want to open a new activity but as per my code its shows the toast about the item position. I am not getting where i am making mistake so please help me. Help would be appreciate, thanks in advance.

DataModel.class

public class DataModel {

    public String text;
    public int drawable;
    public String color;

    public DataModel(String t, int d, String c )
    {
        text=t;
        drawable=d;
        color=c;
    }
}

RecyclerViewAdapter.class

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    ArrayList<DataModel> mValues;
    Context mContext;
    protected ItemListener mListener;

    public RecyclerViewAdapter(Context context, ArrayList<DataModel> values, ItemListener itemListener) {

        mValues = values;
        mContext = context;
        mListener=itemListener;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView textView;
        public ImageView imageView;
        public RelativeLayout relativeLayout;
        DataModel item;

        public ViewHolder(View v) {

            super(v);

            v.setOnClickListener(this);
            textView = (TextView) v.findViewById(R.id.textView);
            imageView = (ImageView) v.findViewById(R.id.imageView);
            relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);

        }

        public void setData(DataModel item) {
            this.item = item;

            textView.setText(item.text);
            imageView.setImageResource(item.drawable);
            relativeLayout.setBackgroundColor(Color.parseColor(item.color));

        }

        @Override
        public void onClick(View view) {
            if (mListener != null) {
                mListener.onItemClick(item);
            }
        }
    }

    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_view_item, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder Vholder, int position) {
        Vholder.setData(mValues.get(position));

    }

    @Override
    public int getItemCount() {

        return mValues.size();
    }

    public interface ItemListener {
        void onItemClick(DataModel item);
    }

}

MainActivity class

public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.ItemListener {

        RecyclerView recyclerView;
        ArrayList<DataModel> arrayList;

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

            recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            arrayList = new ArrayList<>();
            arrayList.add(new DataModel("Item 1", R.drawable.downtoearth, "#FFFFFF"));
            arrayList.add(new DataModel("Item 2", R.drawable.beer, "#3E51B1"));
            arrayList.add(new DataModel("Item 3", R.drawable.ferrari, "#673BB7"));
            arrayList.add(new DataModel("Item 4", R.drawable.jetpack_joyride, "#4BAA50"));
            arrayList.add(new DataModel("Item 5", R.drawable.three_d, "#F94336"));
            arrayList.add(new DataModel("Item 6", R.drawable.terraria, "#0A9B88"));

            RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, arrayList, this);
            recyclerView.setAdapter(adapter);

            /**
             AutoFitGridLayoutManager that auto fits the cells by the column width defined.
             **/

            AutoFitGridLayoutManager layoutManager = new AutoFitGridLayoutManager(this, 300);
            recyclerView.setLayoutManager(layoutManager);

            /**
             Simple GridLayoutManager that spans two columns
             **/
            GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
            recyclerView.setLayoutManager(manager);
        }

        @Override
        public void onItemClick(DataModel item) {

        //here toast is
        Toast.makeText(getApplicationContext(), item.text + " is clicked",
             Toast.LENGTH_SHORT).show();

        }
    }

after edit i am getting error in the intent.putExtra command

@Override
    public void onItemClick(DataModel item) {

    Intent intent = new Intent(MainActivity.this, Yojana.class);
    intent.putExtra("dataitem", item);
    startActivity(intent);

}

Yojana.class

public class Yojana extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_yojana);
    getIntent().getParcelableExtra("dataitem");

}

logcaterror :

    Error:(56, 15) error: no suitable method found for
    putExtra(String,DataModel)
    method Intent.putExtra(String,boolean) is not applicable
    (argument mismatch; DataModel cannot be converted to boolean)
    method Intent.putExtra(String,byte) is not applicable
    (argument mismatch; DataModel cannot be converted to byte)
    method Intent.putExtra(String,char) is not applicable
    (argument mismatch; DataModel cannot be converted to char)
    method Intent.putExtra(String,short) is not applicable
    (argument mismatch; DataModel cannot be converted to short)
    method Intent.putExtra(String,int) is not applicable
    (argument mismatch; DataModel cannot be converted to int)
    method Intent.putExtra(String,long) is not applicable
    (argument mismatch; DataModel cannot be converted to long)
    method Intent.putExtra(String,float) is not applicable
    (argument mismatch; DataModel cannot be converted to float)
    method Intent.putExtra(String,double) is not applicable
    (argument mismatch; DataModel cannot be converted to double)
    method Intent.putExtra(String,String) is not applicable
    (argument mismatch; DataModel cannot be converted to String)
    method Intent.putExtra(String,CharSequence) is not applicable
    (argument mismatch; DataModel cannot be converted to CharSequence)
    method Intent.putExtra(String,Parcelable) is not applicable
    (argument mismatch; DataModel cannot be converted to Parcelable)
    method Intent.putExtra(String,Parcelable[]) is not applicable
    (argument mismatch; DataModel cannot be converted to Parcelable[])
    method Intent.putExtra(String,Serializable) is not applicable
   (argument mismatch; DataModel cannot be converted to Serializable)
   method Intent.putExtra(String,boolean[]) is not applicable
   (argument mismatch; DataModel cannot be converted to boolean[])
   method Intent.putExtra(String,double[]) is not applicable
   (argument mismatch; DataModel cannot be converted to double[])
   method Intent.putExtra(String,String[]) is not applicable
   (argument mismatch; DataModel cannot be converted to String[])
   method Intent.putExtra(String,CharSequence[]) is not applicable
   (argument mismatch; DataModel cannot be converted to CharSequence[])
   method Intent.putExtra(String,Bundle) is not applicable
   (argument mismatch; DataModel cannot be converted to Bundle)

Body:
It shows toast because you have written below code:

Toast.makeText(getApplicationContext(), item.text + " is clicked", Toast.LENGTH_SHORT).show();

Insted you should write below code:

Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("dataitem", item);
startActivity(intent);


问:
Read binary stdout data like screencap data from adb shell?
Is it possible to read binary stdout from an adb shell command?  For example, all examples of how to use screencap include two steps:

```<code>adb shell screencap -p /sdcard/foo.png
adb pull /sdcard/foo.png
</code>```

However, the service supports writing to stdout.  You can for instance, do the following:

```<code>adb shell "screencap -p > /sdcard/foo2.png"
adb pull /sdcard/foo2.png
</code>```

And this works equally well.  But, what about reading the output across ADB?  What I want to do is the following:

```<code>adb shell screencap -p > foo3.png
</code>```

And avoid the intermediate write to the SD card.  This generates something that looks like a PNG file (running strings foo3.png generates something with an IHDR, IEND, etc.) and is approximately the same size, but the file is corrupted as far as image readers are concerned.

I have also attempted to do this using ddmlib in java and the results are the same.  I would be happy to use any library necessary.  My goal is to reduce total time to get the capture.  On my device, using the two-command solution, it takes about 3 seconds to get the image.  Using ddmlib and capturing stdout takes less than 900ms, but it doesn't work!

Is it possible to do this?

EDIT: Here is the hexdump of two files.  The first one, screen.png came from stdout and is corrupted.  The second one, xscreen is from the two-command solution and works.  The images should be visually identical.

```<code>$ hexdump -C screen.png | head
00000000  89 50 4e 47 0d 0d 0a 1a  0d 0a 00 00 00 0d 49 48  |.PNG..........IH|
00000010  44 52 00 00 02 d0 00 00  05 00 08 06 00 00 00 6e  |DR.............n|
00000020  ce 65 3d 00 00 00 04 73  42 49 54 08 08 08 08 7c  |.e=....sBIT....||
00000030  08 64 88 00 00 20 00 49  44 41 54 78 9c ec bd 79  |.d... .IDATx...y|
00000040  9c 1d 55 9d f7 ff 3e 55  75 f7 de b7 74 77 d2 d9  |..U...>Uu...tw..|
00000050  bb b3 27 10 48 42 16 c0  20 01 86 5d 14 04 11 dc  |..'.HB.. ..]....|
00000060  78 44 9d c7 d1 d1 11 78  70 7e 23 33 8e 1b 38 33  |xD.....xp~#3..83|
00000070  ea 2c 8c 8e 0d 0a 08 a8  23 2a 0e 10 82 ac c1 40  |.,......#*.....@|
00000080  12 02 81 24 64 ef ec 5b  ef fb 5d 6b 3b bf 3f ea  |...$d..[..]k;.?.|
00000090  de db dd 49 27 e9 ee 74  77 3a e3 79 bf 5e 37 e7  |...I'..tw:.y.^7.|

$ hexdump -C xscreen.png | head
00000000  89 50 4e 47 0d 0a 1a 0a  00 00 00 0d 49 48 44 52  |.PNG........IHDR|
00000010  00 00 02 d0 00 00 05 00  08 06 00 00 00 6e ce 65  |.............n.e|
00000020  3d 00 00 00 04 73 42 49  54 08 08 08 08 7c 08 64  |=....sBIT....|.d|
00000030  88 00 00 20 00 49 44 41  54 78 9c ec 9d 77 98 1c  |... .IDATx...w..|
00000040  c5 99 ff 3f d5 dd 93 37  27 69 57 5a e5 55 4e 08  |...?...7'iWZ.UN.|
00000050  24 a1 00 58 18 04 26 08  8c 01 83 31 38 c0 19 9f  |$..X..&....18...|
00000060  ef 7c c6 3e 1f 70 f8 7e  67 ee 71 e2 b0 ef ce f6  |.|.>.p.~g.q.....|
00000070  f9 ec 73 04 1b 1c 31 60  23 84 30 22 88 a0 40 10  |..s...1`#.0"..@.|
00000080  08 65 69 95 d3 4a 9b c3  c4 4e f5 fb a3 67 66 77  |.ei..J...N...gfw|
00000090  a5 95 b4 bb da a4 73 7d  9e 67 55 f3 ed 50 5d dd  |......s}.gU..P].|
</code>```

Just at quick glance it seems like a couple of extra 0x0d (13) bytes get added.  Carriage return?? Does that ring any bells?  Is it mixing in some blank lines?

答:
This command worked for me on Windows OS:

```<code>adb exec-out screencap -p > test.png && dos2unix.exe -f test.png
</code>```

But you want to use this:
https://sourceforge.net/projects/dos2unix/

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to read binary stdout from an adb shell command?  For example, all examples of how to use screencap include two steps:

adb shell screencap -p /sdcard/foo.png
adb pull /sdcard/foo.png

However, the service supports writing to stdout.  You can for instance, do the following:

adb shell "screencap -p > /sdcard/foo2.png"
adb pull /sdcard/foo2.png

And this works equally well.  But, what about reading the output across ADB?  What I want to do is the following:

adb shell screencap -p > foo3.png

And avoid the intermediate write to the SD card.  This generates something that looks like a PNG file (running strings foo3.png generates something with an IHDR, IEND, etc.) and is approximately the same size, but the file is corrupted as far as image readers are concerned.

I have also attempted to do this using ddmlib in java and the results are the same.  I would be happy to use any library necessary.  My goal is to reduce total time to get the capture.  On my device, using the two-command solution, it takes about 3 seconds to get the image.  Using ddmlib and capturing stdout takes less than 900ms, but it doesn't work!

Is it possible to do this?

EDIT: Here is the hexdump of two files.  The first one, screen.png came from stdout and is corrupted.  The second one, xscreen is from the two-command solution and works.  The images should be visually identical.

$ hexdump -C screen.png | head
00000000  89 50 4e 47 0d 0d 0a 1a  0d 0a 00 00 00 0d 49 48  |.PNG..........IH|
00000010  44 52 00 00 02 d0 00 00  05 00 08 06 00 00 00 6e  |DR.............n|
00000020  ce 65 3d 00 00 00 04 73  42 49 54 08 08 08 08 7c  |.e=....sBIT....||
00000030  08 64 88 00 00 20 00 49  44 41 54 78 9c ec bd 79  |.d... .IDATx...y|
00000040  9c 1d 55 9d f7 ff 3e 55  75 f7 de b7 74 77 d2 d9  |..U...>Uu...tw..|
00000050  bb b3 27 10 48 42 16 c0  20 01 86 5d 14 04 11 dc  |..'.HB.. ..]....|
00000060  78 44 9d c7 d1 d1 11 78  70 7e 23 33 8e 1b 38 33  |xD.....xp~#3..83|
00000070  ea 2c 8c 8e 0d 0a 08 a8  23 2a 0e 10 82 ac c1 40  |.,......#*.....@|
00000080  12 02 81 24 64 ef ec 5b  ef fb 5d 6b 3b bf 3f ea  |...$d..[..]k;.?.|
00000090  de db dd 49 27 e9 ee 74  77 3a e3 79 bf 5e 37 e7  |...I'..tw:.y.^7.|

$ hexdump -C xscreen.png | head
00000000  89 50 4e 47 0d 0a 1a 0a  00 00 00 0d 49 48 44 52  |.PNG........IHDR|
00000010  00 00 02 d0 00 00 05 00  08 06 00 00 00 6e ce 65  |.............n.e|
00000020  3d 00 00 00 04 73 42 49  54 08 08 08 08 7c 08 64  |=....sBIT....|.d|
00000030  88 00 00 20 00 49 44 41  54 78 9c ec 9d 77 98 1c  |... .IDATx...w..|
00000040  c5 99 ff 3f d5 dd 93 37  27 69 57 5a e5 55 4e 08  |...?...7'iWZ.UN.|
00000050  24 a1 00 58 18 04 26 08  8c 01 83 31 38 c0 19 9f  |$..X..&....18...|
00000060  ef 7c c6 3e 1f 70 f8 7e  67 ee 71 e2 b0 ef ce f6  |.|.>.p.~g.q.....|
00000070  f9 ec 73 04 1b 1c 31 60  23 84 30 22 88 a0 40 10  |..s...1`#.0"..@.|
00000080  08 65 69 95 d3 4a 9b c3  c4 4e f5 fb a3 67 66 77  |.ei..J...N...gfw|
00000090  a5 95 b4 bb da a4 73 7d  9e 67 55 f3 ed 50 5d dd  |......s}.gU..P].|

Just at quick glance it seems like a couple of extra 0x0d (13) bytes get added.  Carriage return?? Does that ring any bells?  Is it mixing in some blank lines?

Body:
This command worked for me on Windows OS:

adb exec-out screencap -p > test.png && dos2unix.exe -f test.png

But you want to use this:
https://sourceforge.net/projects/dos2unix/


问:
how to get the request_id from the below json string in C#
Please help, I'm stuck with this

```<code>using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     var result = streamReader.ReadToEnd();
     Console.WriteLine(result);
}
</code>```

output :

```<code>{
    "request_number":"REQ0010201",
    "request_id":"b1c8ba46db3ffa807ea0f4e9bf9619ca",
    "sys_id":"35c8ba46db3ffa807ea0f4e9bf9619ca"
}
</code>```

But I want output as only request_id to be printed  : b1c8ba46db3ffa807ea0f4e9bf9619ca

答:
if You Are Sure That The Request Id Will Always By The Second Attr in The Json Object Then You Can Do Some String Manipulation
string.Split(',') Will Return Array Of Strings Split By The Comma , Now We Know That The Request Id Is The Second Eelment In This Array So string.Split(',')[1] Should return The Following String "request_id":"b1c8ba46db3ffa807ea0f4e9bf9619ca"

if U Chain Another Split But this Time With Colon and Got The Second Member Of The Out Put Array It Will Be The Id Value string.Split(':')[1]

If You Don't Want The Quotation Mark You Can Do String.Replace("\"",string.Empty)

So Your Code Should be
 JsonObject.Split(',')[1].Split(':')[1].Replace("\"",string.Empty)

You Could Split By The Colon From The First Time But I Want To Explain More

if You Don't Like That You Can Use NewtonSoft.Json Package To Deserialize The Json Object To Previously Created R

Body:
Please help, I'm stuck with this

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     var result = streamReader.ReadToEnd();
     Console.WriteLine(result);
}

output :

{
    "request_number":"REQ0010201",
    "request_id":"b1c8ba46db3ffa807ea0f4e9bf9619ca",
    "sys_id":"35c8ba46db3ffa807ea0f4e9bf9619ca"
}

But I want output as only request_id to be printed  : b1c8ba46db3ffa807ea0f4e9bf9619ca


问:
Redis: weird protocol/network errors
I'm running Redis and connecting from Ruby using ezmobius's Redis gem[1].

Periodically (about once a day) I get a series of exceptions in my Rails app caused by Redis returning strange results.

They are often triggered by an exception such at this:

```<code>Redis::ProtocolError: Protocol error, got '3' as initial reply byte
</code>```

or

```<code>Redis::ProtocolError: Protocol error, got '9' as initial reply byte
</code>```

or sometimes

```<code>Errno::EAGAIN: Resource temporarily unavailable - Timeout reading from the socket
</code>```

It usually requires a restart of my Rails servers to clear up the connection problem. I'm running Fedora Core 8, Rails 2.3.8, Redis gem 2.0.3. I've got the system_timer gem installed. Anybody got any ideas how I can stop these errors?

[1]Redis gem

答:
I had a slightly similar issue with

```<code>Errno::EAGAIN: Resource temporarily unavailable - Timeout reading from the socket
</code>```

Turns out, my redis-server had a timeout set to 300 seconds on connections. After 5 minutes, redis was killing the connection to my workers and they were logging the error above.

If your socket timeouts are happening every x seconds, its no doubt redis killing your 'idle' connection!

Title: Redis: weird protocol/network errors

Body:
I'm running Redis and connecting from Ruby using ezmobius's Redis gem[1].

Periodically (about once a day) I get a series of exceptions in my Rails app caused by Redis returning strange results.

They are often triggered by an exception such at this:

Redis::ProtocolError: Protocol error, got '3' as initial reply byte

or

Redis::ProtocolError: Protocol error, got '9' as initial reply byte

or sometimes

Errno::EAGAIN: Resource temporarily unavailable - Timeout reading from the socket

It usually requires a restart of my Rails servers to clear up the connection problem. I'm running Fedora Core 8, Rails 2.3.8, Redis gem 2.0.3. I've got the system_timer gem installed. Anybody got any ideas how I can stop these errors?

[1]Redis gem

Body:
I had a slightly similar issue with

Errno::EAGAIN: Resource temporarily unavailable - Timeout reading from the socket

Turns out, my redis-server had a timeout set to 300 seconds on connections. After 5 minutes, redis was killing the connection to my workers and they were logging the error above.

If your socket timeouts are happening every x seconds, its no doubt redis killing your 'idle' connection!


问:
Solr OR query on a text field
How to perform a simple query on a text field with an OR condition? Something like name:ABC OR name:XYZ so the resulting set would contain only those docs where name is exactly "XYZ" or "ABC"
Dug tons of manuals, cannot figure this out.
I use Solr 5.5.0

Update: Upgraded to Solr 6.6.0, still cannot figure it out. Below are illustrations to demonstrate my issue:

This works:

This works too:

This still works:

But this does not! Omg why!?

答:
Your syntax is right, but what you're asking for isn't what text fields are made for. A text field is tokenized (split into multiple tokens), and each token is searched by itself. So if the text inserted is "ABC DEF GHI", it will be split into three separate tokens, namely "ABC", "DEF" and "GHI". So when you're searching field:ABC, you're really asking for any document that has the token "ABC" somewhere.

Since you want to perform an exact match, you want to query against a field that is defined as a string field, as this will keep the value verbatim (including casing, so the matching will be case sensitive). You can tell Solr to index the same content into multiple fields by adding a copyFile instruction, telling it to take the content submitted for field foo and also copying it into field bar, allowing you to perform both an exact match if needed and a more general search if necessary.

If you need to perform exact, but case insensitive, searches, you can use a KeywordTokenizer - the KeywordTokenizer does nothing, keeping the whole string as a single token, before allowing you to add filters to the analysis chain. By adding a LowercaseFilter you tell Solr to lowercase the string as well before storing it (or querying for it).

You can use the "Analysis" page under the Solr admin page to experiment and see how content for your field is being processed for each step.

After that querying as string_field:ABC OR string_field:XYZ should do what you want (or string_field:(ABC OR XYZ) or a few other ways to express the same.

Title: Solr OR query on a text field


问:
grouping by values in another dataframe
I have two dataframes A and B. Both have same structure(row count, column count, column names and indexes). A is filled with data, and B contains flags(True or False) corresponding to the data in A. I want to create another dataframe C which has values of A whenever the corresponding flag in B is True. How should i go about the same. I believe i have to use some sort of a group by but I am a complete newbee in python/pandas.  </p>

答:
Something like this?</p>

```<code>>>A = pd.DataFrame({'col1':[2,3,4,5],'col2':['a','b','c','d']})
>>A

col1    col2
0   2   a
1   3   b
2   4   c
3   5   d

>>B = pd.DataFrame({'col1':[True, True, False, False],'col2':[False, False,True,True]})
>>B

col1    col2
0   True    False
1   True    False
2   False   True
3   False   True

>>C = A[B]

col1    col2
0   2.0 NaN
1   3.0 NaN
2   NaN c
3   NaN d
</code>```

Title: grouping by values in another dataframe

Body:
Something like this?

>>A = pd.DataFrame({'col1':[2,3,4,5],'col2':['a','b','c','d']})
>>A

col1    col2
0   2   a
1   3   b
2   4   c
3   5   d

>>B = pd.DataFrame({'col1':[True, True, False, False],'col2':[False, False,True,True]})
>>B

col1    col2
0   True    False
1   True    False
2   False   True
3   False   True

>>C = A[B]

col1    col2
0   2.0 NaN
1   3.0 NaN
2   NaN c
3   NaN d


问:
Go package with a loaded once set of data
I am writing a post code location lookup package, it loads in all uk postcodes from a csv, I would like to only load the data once I would like to know what is the best pattern to achieve this with Go.

```<code>type Location struct {
    Latitude float64
    Longitude float64
}

var postCodeCache = make(map[string]Location)
</code>```

These are my data types, currently I have a function called LoadData and LookupPostCode(). Ideally I would want to import my package and it would automatically load the data if it was not already loaded.

答:
You've got two options:

The simplest is load the data in main before any other processing starts. If probability that you will read the data is very high and there is no other reason to avoid doing it immediately, why not?

Load the data with sync.Once. Something like:

```<code>var dataLoaded sync.Once
var data DataType = nil

func LookupPostCode(some_args) {
    once.Do(func() {
        data = LoadData(some_subset_of_some_args)
    })
    // and here I know, that data are loaded
}
</code>```

Body:
I am writing a post code location lookup package, it loads in all uk postcodes from a csv, I would like to only load the data once I would like to know what is the best pattern to achieve this with Go.

type Location struct {
    Latitude float64
    Longitude float64
}

var postCodeCache = make(map[string]Location)

These are my data types, currently I have a function called LoadData and LookupPostCode(). Ideally I would want to import my package and it would automatically load the data if it was not already loaded.

Body:
You've got two options:

The simplest is load the data in main before any other processing starts. If probability that you will read the data is very high and there is no other reason to avoid doing it immediately, why not?

Load the data with sync.Once. Something like:

var dataLoaded sync.Once
var data DataType = nil

func LookupPostCode(some_args) {
    once.Do(func() {
        data = LoadData(some_subset_of_some_args)
    })
    // and here I know, that data are loaded
}


问:
using Microsoft interop to fill a letter in Word C#
I am Trying out a Program to Fill a Letter in Microsoft Word using Interop in C#.
I have hard coded all the Text that is to be filled in word in my program.

but While running my program I could see that I am not able to use the normal copy and paste option in my computer. While doing so it pastes the text that is copied by my program in clipboard. Is there a solution for this Problem

答:
When modifying a Word document with interop, I use the "replace bookmark" functionality. You define bookmarks in your model .doc then replace them with text at runtim with I wrote this function

```<code>Public Shared Sub ReplaceBookmarkText(ByVal doc As Microsoft.Office.Interop.Word.Document, ByVal bookmarkName As String, ByVal text As String)
    If (doc.Bookmarks.Exists(bookmarkName)) Then
        Dim range As Microsoft.Office.Interop.Word.Range = doc.Bookmarks(bookmarkName).Range
        range.Text = text
        doc.Bookmarks.Add(bookmarkName, range)
    End If
End Sub
</code>```

Body:
When modifying a Word document with interop, I use the "replace bookmark" functionality. You define bookmarks in your model .doc then replace them with text at runtim with I wrote this function

Public Shared Sub ReplaceBookmarkText(ByVal doc As Microsoft.Office.Interop.Word.Document, ByVal bookmarkName As String, ByVal text As String)
    If (doc.Bookmarks.Exists(bookmarkName)) Then
        Dim range As Microsoft.Office.Interop.Word.Range = doc.Bookmarks(bookmarkName).Range
        range.Text = text
        doc.Bookmarks.Add(bookmarkName, range)
    End If
End Sub


问:
Python os.walk memory issue
I programmed a scanner that looks for certain files on all hard drives of a system that gets scanned. Some of these systems are pretty old, running Windows 2000 with 256 or 512 MB of RAM but the file system structure is complex as some of them serve as file servers.

I use os.walk() in my script to parse all directories and files.

Unfortunately we noticed that the scanner consumes a lot of RAM after some time of scanning and we figured out that the os.walk function alone uses about 50 MB of RAM after 2h of walk over the file system. This RAM usage increases over the time. We had about 90 MB of RAM after 4 hours of scanning.

Is there a way to avoid this behaviour? We also tried "betterwalk.walk()" and "scandir.walk()". The result was the same.
Do we have to write our own walk function that removes already scanned directory and file objects from memory so that the garbage collector can remove them from time to time?

Thanks

答:
Generators are better solutions as they do lazy computations
here is one example of implementation.

```<code>import os
import fnmatch

#this may or may not be implemented
def list_dir(path):
    for name in os.listdir(path):
        yield os.path.join(path, name)

#modify this to take some pattern as input
def os_walker(top):
    for root,dlist,flist in os.walk(top):
        for name in fnmatch.filter(flist, '*.py'):
            yield os.path.join(root, name)

all_dirs = list_dir("D:\\tuts\\pycharm")

for l in all_dirs:
    for name in os_walker(l):
        print(name)
</code>```

Thanks to David Beazley

Title: Python os.walk memory issue

Body:
Generators are better solutions as they do lazy computations
here is one example of implementation.

import os
import fnmatch

#this may or may not be implemented
def list_dir(path):
    for name in os.listdir(path):
        yield os.path.join(path, name)

#modify this to take some pattern as input
def os_walker(top):
    for root,dlist,flist in os.walk(top):
        for name in fnmatch.filter(flist, '*.py'):
            yield os.path.join(root, name)

all_dirs = list_dir("D:\\tuts\\pycharm")

for l in all_dirs:
    for name in os_walker(l):
        print(name)

Thanks to David Beazley


问:
Grab Nested Objects.length inside of object Javascript
```<code>//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];

function lookUpProfile(firstNames, prop){
// Only change code below this line

  for (var i=0; i<contacts.length; i++){
    if(contacts[i].firstName == firstNames){
      for (var j=0; j<contacts[i].length; j++){
        if(contacts[i][j] == prop){
          return contacts[i][j].prop;
        } else {
          return "No such property";
        }
      }
    } else{
       return "No such contact";
    }

  }
  // Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");
</code>```

The above code doesn't work, specifically on the line with the for (var j=0; j<contacts[i].length; j++) line, as contacts[i].length is undefined, when I ran console.log statements into my code

How exactly do you define the length of an javascript object that is nested inside of another object?

reference example https://www.freecodecamp.org/challenges/profile-lookup

答:
The Object prototype does not define a length function, that is why it is undefined. However, you can get an array of every (own) property key in your object using Object.keys:

```<code>var props = Object.keys(contracts[i]);

for (var j = 0; j < props.length; j++) {
  // etc.
}
</code>```

Body:
//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];

function lookUpProfile(firstNames, prop){
// Only change code below this line

  for (var i=0; i<contacts.length; i++){
    if(contacts[i].firstName == firstNames){
      for (var j=0; j<contacts[i].length; j++){
        if(contacts[i][j] == prop){
          return contacts[i][j].prop;
        } else {
          return "No such property";
        }
      }
    } else{
       return "No such contact";
    }

  }
  // Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");

The above code doesn't work, specifically on the line with the for (var j=0; j<contacts[i].length; j++) line, as contacts[i].length is undefined, when I ran console.log statements into my code

How exactly do you define the length of an javascript object that is nested inside of another object?

reference example https://www.freecodecamp.org/challenges/profile-lookup

Body:
The Object prototype does not define a length function, that is why it is undefined. However, you can get an array of every (own) property key in your object using Object.keys:

var props = Object.keys(contracts[i]);

for (var j = 0; j < props.length; j++) {
  // etc.
}


问:
How can I display two lists with each li element vertically under each other?
I have two separate lists (however I'm open for an example on how to just have one). The first list is information (such as 'title', 'length' 'release date') and the second list is the answers to the information (such as '50 Shades of Grey', '50 minutes' and '2015').

Here is my desired output and as you can see, the answers to the information is vertically centered under the information:

(Note there could be more information such as members of the cast, the budget e.g)

I have tried using Flex however the two lists are displayed separately on top of each other:

ul {
   white-space:nowrap;
}

li {
   display: flex;
   justify-content: center;
   flex-direction: column;
   text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>Title</li>
<li>Length</li>
<li>Release Date</li>
</ul>
<ul>
<li>50 Shades of Grey</li>
<li>50 minutes</li>
<li>2015</li>
</ul></code>```

答:
You can use CSS table-layout for this. You have to set display: table-row on ul and display: table-cell on li. Also you should add text-align: center on li.

ul {
  display: table-row;
}

li {
  display: table-cell;
  text-align: center;
  padding: 10px 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Title</li>
  <li>Length</li>
  <li>Release Date</li>
</ul>
<ul>
  <li>50 Shades of Grey</li>
  <li>50 minutes</li>
  <li>2015</li>
</ul></code>```

You can also use Flexbox for this you just have to set flex: 1 on each li. This will work if you have equal number of li's in each ul, if not use table-layout.

ul {
  display: flex;
  list-style: none;
}

li {
  flex: 1;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Title</li>
  <li>Length</li>
  <li>Release Date</li>
</ul>
<ul>
  <li>50 Shades of Grey</li>
  <li>50 minutes</li>
  <li>2015</li>
</ul></code>```

Body:
I have two separate lists (however I'm open for an example on how to just have one). The first list is information (such as 'title', 'length' 'release date') and the second list is the answers to the information (such as '50 Shades of Grey', '50 minutes' and '2015').

Here is my desired output and as you can see, the answers to the information is vertically centered under the information:

(Note there could be more information such as members of the cast, the budget e.g)

I have tried using Flex however the two lists are displayed separately on top of each other:

ul {
   white-space:nowrap;
}

li {
   display: flex;
   justify-content: center;
   flex-direction: column;
   text-align: center;
}

Title

Length

Release Date

50 Shades of Grey

50 minutes

2015

Body:
You can use CSS table-layout for this. You have to set display: table-row on ul and display: table-cell on li. Also you should add text-align: center on li.

ul {
  display: table-row;
}

li {
  display: table-cell;
  text-align: center;
  padding: 10px 20px;
}

<ul>
  <li>Title</li>
  <li>Length</li>
  <li>Release Date</li>
</ul>
<ul>
  <li>50 Shades of Grey</li>
  <li>50 minutes</li>
  <li>2015</li>
</ul>

You can also use Flexbox for this you just have to set flex: 1 on each li. This will work if you have equal number of li's in each ul, if not use table-layout.

ul {
  display: flex;
  list-style: none;
}

li {
  flex: 1;
  text-align: center;
}

<ul>
  <li>Title</li>
  <li>Length</li>
  <li>Release Date</li>
</ul>
<ul>
  <li>50 Shades of Grey</li>
  <li>50 minutes</li>
  <li>2015</li>
</ul>


问:
CoreMediaIO, incorrectly updated properties kCMIODevicePropertyDeviceIsRunningSomewhere
I need to receive an event when some process starts using the camera. I did this through CMIOObjectGetPropertyData.
But it does not work correctly, the correct value is only the first time it is accessed.

I also tried to use the CMIOObjectAddPropertyListenerBlock but he did not work it from me. Tell me please, what am I doing wrong? I will be very grateful.

```<code>while (1)
{
    UInt32 value = 0;
    UInt32 valuePropertySize = sizeof(flag);
    CMIOObjectPropertyAddress opa = {kCMIODevicePropertyDeviceIsRunningSomewhere,
        kAudioObjectPropertyScopeWildcard, kAudioObjectPropertyElementMaster};

    OSStatus result = CMIOObjectGetPropertyData(device, &opa, 0, NULL, sizeof(UInt32), &valuePropertySize, &value);
    NSLog(@"%d : %d", result, value);
    sleep(1);
}
</code>```

答:
I also had the same problem. Getting data with CMIOObjectGetPropertyData worked but registering a listener block with CMIOObjectAddPropertyListenerBlock never received any event.

The solution to the issue was totally unrelated to the CMIO* code.
Basically, I forgot to start the run loop, and that prevented receiving events.

Please take a look here: currentRunLoop

Adding a simple [[NSRunLoop currentRunLoop] run]; fixed the issue for me

Body:
I need to receive an event when some process starts using the camera. I did this through CMIOObjectGetPropertyData.
But it does not work correctly, the correct value is only the first time it is accessed.

I also tried to use the CMIOObjectAddPropertyListenerBlock but he did not work it from me. Tell me please, what am I doing wrong? I will be very grateful.

while (1)
{
    UInt32 value = 0;
    UInt32 valuePropertySize = sizeof(flag);
    CMIOObjectPropertyAddress opa = {kCMIODevicePropertyDeviceIsRunningSomewhere,
        kAudioObjectPropertyScopeWildcard, kAudioObjectPropertyElementMaster};

    OSStatus result = CMIOObjectGetPropertyData(device, &opa, 0, NULL, sizeof(UInt32), &valuePropertySize, &value);
    NSLog(@"%d : %d", result, value);
    sleep(1);
}


问:
'Program.CalculateTax(double)':not all code paths return a value'
I' ve  got error on this code. Its said "Not all code paths return Value"
Please hel me fix this. Thanks</p>

```<code>public static double subtotal;

public static void Main(String[] args)
{
  subtotal = 15.00;
  Console.WriteLine($"Subtotal : {subtotal}");

  double total = subtotal + CalculateTax(7);
  Console.WriteLine($"Total : {total}");
}

public static double CalculateTax(double taxRate)
{
  double tax = subtotal * taxRate;
  Console.WriteLine($"Tax: {tax}");
}
</code>```

答:
try this</p>

```<code>public static double CalculateTax(double taxRate)
{
    double tax = subtotal * taxRate;
    Console.WriteLine($"Tax: {tax}");
    return tax;
}
</code>```

Body:
I' ve  got error on this code. Its said "Not all code paths return Value"
Please hel me fix this. Thanks

public static double subtotal;

public static void Main(String[] args)
{
  subtotal = 15.00;
  Console.WriteLine($"Subtotal : {subtotal}");

  double total = subtotal + CalculateTax(7);
  Console.WriteLine($"Total : {total}");
}

public static double CalculateTax(double taxRate)
{
  double tax = subtotal * taxRate;
  Console.WriteLine($"Tax: {tax}");
}

Body:
try this

public static double CalculateTax(double taxRate)
{
    double tax = subtotal * taxRate;
    Console.WriteLine($"Tax: {tax}");
    return tax;
}


问:
Circle bullets for background with CSS and HTML
The code in CodePen here provides bullets, stripes and some squares. I want circles. I found this source but I don't know how to implement it.

Code also here

```<code>@import url(https://fonts.googleapis.com/css?family=Oswald);
div {
text-align: center;
font: bold 21px 'Oswald',sans-serif;
text-shadow: 1px 1px 0 #fff, 2px 2px 0 #999;
text-transform: uppercase;
}
.dotted {
padding: 2.25em 1.6875em;
background-image: -webkit-repeating-radial-gradient(45px 45px, circle cover, rgba(0,0,0,.90), rgba(0,0,0,.90) 2px, transparent 0px, transparent 100%);
background-image: -moz-repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
background-image: -ms-repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
background-image: repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
-webkit-background-size: 9px 9px;
-moz-background-size: 9px 9px;
background-size: 9px 9px;
}
</code>```

答:
You can do this by changing the radius, notice the rgba(0,0,0,0.5) 4px instead of rgba(0,0,0,0.5) 1px on the first line about background-image:.

Code

```<code>.dotted {
  padding: 2.25em 1.6875em;
  background-image: -webkit-repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,0.5) 4px, transparent 1px, transparent 100%);
  background-image: -moz-repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
  background-image: -ms-repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
  background-image: repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
  -webkit-background-size: 3px 3px;
  -moz-background-size: 3px 3px;
  background-size: 10px 10px;
  }
</code>```

Body:
The code in CodePen here provides bullets, stripes and some squares. I want circles. I found this source but I don't know how to implement it.

Code also here

@import url(https://fonts.googleapis.com/css?family=Oswald);
div {
text-align: center;
font: bold 21px 'Oswald',sans-serif;
text-shadow: 1px 1px 0 #fff, 2px 2px 0 #999;
text-transform: uppercase;
}
.dotted {
padding: 2.25em 1.6875em;
background-image: -webkit-repeating-radial-gradient(45px 45px, circle cover, rgba(0,0,0,.90), rgba(0,0,0,.90) 2px, transparent 0px, transparent 100%);
background-image: -moz-repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
background-image: -ms-repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
background-image: repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
-webkit-background-size: 9px 9px;
-moz-background-size: 9px 9px;
background-size: 9px 9px;
}

Body:
You can do this by changing the radius, notice the rgba(0,0,0,0.5) 4px instead of rgba(0,0,0,0.5) 1px on the first line about background-image:.

Code

.dotted {
  padding: 2.25em 1.6875em;
  background-image: -webkit-repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,0.5) 4px, transparent 1px, transparent 100%);
  background-image: -moz-repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
  background-image: -ms-repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
  background-image: repeating-radial-gradient(center center, rgba(0,0,0,.2), rgba(0,0,0,.2) 1px, transparent 1px, transparent 100%);
  -webkit-background-size: 3px 3px;
  -moz-background-size: 3px 3px;
  background-size: 10px 10px;
  }


问:
Trouble displaying % in NSRunAlertPanel
I am developing an Desktop application where I want to show a message in alert panel using NSRunAlertPanel.
I am doing the following things:

```<code>NSString *title = @"% Test";
NSString *message = @"% Test Message";
NSRunAlertPanel(title, message, @"Ok" ,@"Cancel" ,nil);
</code>```

The alert panel show the title properly. i.e % Test
But, the message is est Message; I want to display % Test Message.

How do I solve this problem?

Thanks in advance.

答:
Try this :

```<code>NSString *title = @"% Test";
NSString *message = @"%% Test Message";
NSRunAlertPanel(title, message, @"Ok" ,@"Cancel" ,nil);
</code>```

Why?

NSRunAlertPanel uses NSBeginAlertSheet. Looking at the documentation for NSBeginAlertSheet you can see that there are more parameters after msg (specified by the ...).

This tells us that title is just a string literally displayed but the message can have format parameters the same way that [NSString stringWithFormat:] does.

The way that a string specifies that there is going to be a parameter is by using a % character i.e. %i means 'put an integer here', %@ means 'put an object's description here'. You've just put a % by itself, which gets things very confused!

The double %% means this percent isn't me telling you that I want you to put anything special in there, I really just want the % please.

Title: Trouble displaying % in NSRunAlertPanel

Body:
I am developing an Desktop application where I want to show a message in alert panel using NSRunAlertPanel.
I am doing the following things:

NSString *title = @"% Test";
NSString *message = @"% Test Message";
NSRunAlertPanel(title, message, @"Ok" ,@"Cancel" ,nil);

The alert panel show the title properly. i.e % Test
But, the message is est Message; I want to display % Test Message.

How do I solve this problem?

Thanks in advance.

Body:
Try this :

NSString *title = @"% Test";
NSString *message = @"%% Test Message";
NSRunAlertPanel(title, message, @"Ok" ,@"Cancel" ,nil);

Why?

NSRunAlertPanel uses NSBeginAlertSheet. Looking at the documentation for NSBeginAlertSheet you can see that there are more parameters after msg (specified by the ...).

This tells us that title is just a string literally displayed but the message can have format parameters the same way that [NSString stringWithFormat:] does.

The way that a string specifies that there is going to be a parameter is by using a % character i.e. %i means 'put an integer here', %@ means 'put an object's description here'. You've just put a % by itself, which gets things very confused!

The double %% means this percent isn't me telling you that I want you to put anything special in there, I really just want the % please.


问:
Can boost's interprocess segment manager allocators be themselves shared with other processes?
I am creating a shared interprocess map using boost::interprocess.
For this I create an allocator from the segment_manager of the shared memory segment where the map is located.

The element value type of the map is a basic_string which is itself templated to use a char allocator created from the same segment manager.
In one process I create the map and in the other I search for an item using the maps iterator in that process and in some cases I call map::erase with the iterator.

This causes an access violation exception and I know that I am making the call with a valid iterator.
The access violation occurs in the call to the destructor of the basic_string that is the 'second' of the 'pair' pointed to by the iterator.
When I perform the same erase operation using an iterator in the writing process immediately after insertion there is no access violation.

It looks as though the reading process is trying to release the memory of the element using the element's allocator, which was created in the writing process whereas that allocator is only valid in the process that created it.

Does this mean that the allocators themselves cannot be shared?

I would have expected that allocator to be usable in both processes as its state should contain only relative pointers that are valid in both processes.
If not, how can I share elements that use shared memory (heap) allocations between processes?
Should I have created those allocators in a special way in the writing process before passing them to the basic_string elements to allow me to use them in anerase operation in another process?

What else might be causing the access violation?

答:
Yes, the allocators provided by boost for use with shared memory can be used by other processes.
I will present the short of it first and then explain a little better what the original problem was.

In short - I was using basic_string instantiated with the char, char_traits and the shared memory allocator. I should have used boosts boost::interprocess::basic_string instead.

Here is a little more detail.

In my code I am creating a shared map using boost's interprocess map. The elements in that map were strings.
I used boosts segment manager correctly to create an allocator for the map and I used the same segment manager to create a char allocator for the strings that are placed in that map.

However, the strings I was creating and storing in the map were of templated type std::basic_string. I was correctly providing this template with the allocator type and I was correctly providing the allocator instance to the string in its constructor.

Moreover, the string that was stored in the map could be read by another processor that opened the shared memory. However, when the reading process tried to erase the entry, so deleting the string there was an access violation.

After replacing the basic_string with boost::interprocess::basic_string this problem disappeared.

Had I known that boost has its own basic_string in the interprocess namespace I would certainly have used it; I already knew that I need to use boost's map instead of the std one. I just wasn't aware that there was a interprocess::basic_string

As a side note, I would still be interested to know why the std containers are clearly not appropriate for use with allocators of shared memory even though they do provide template parameters that allow implementors to specify which allocator should be used


问:
Why does SQL Management Studio add a cross join?
I sometimes need to run basic updates on a join. For example:

```<code>UPDATE t1 SET col1 = 'val1'
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.ID = t2.t1_id
WHERE t2.col3 = 'val3'
</code>```

This works perfectly, but for some reason, in MS SQL Management Studio Express, it wants to convert this to

```<code>UPDATE t1 SET col1 = 'val1'
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.ID = t2.t1_id
CROSS JOIN t2
WHERE t2.col3 = 'val3'
</code>```

It adds a crossjoin for some reason that I don't understand.

Now my question is: Why does Management Studio think this is what I meant? It must have a genuine use, otherwise it wouldn't suggest it. Yet I have no idea how and when (and why).

答: According to MSDN a cross join like that is equivalent to an inner join.  Perhaps it uses cross joins because a cross join can be used to create cartesian products as well as simpler joins - whereas an inner join is more limited.</p>

Body:
I sometimes need to run basic updates on a join. For example:

UPDATE t1 SET col1 = 'val1'
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.ID = t2.t1_id
WHERE t2.col3 = 'val3'

This works perfectly, but for some reason, in MS SQL Management Studio Express, it wants to convert this to

UPDATE t1 SET col1 = 'val1'
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.ID = t2.t1_id
CROSS JOIN t2
WHERE t2.col3 = 'val3'

It adds a crossjoin for some reason that I don't understand.

Now my question is: Why does Management Studio think this is what I meant? It must have a genuine use, otherwise it wouldn't suggest it. Yet I have no idea how and when (and why).