问:
EditText: Disable Paste/Replace menu pop-up on Text Selection Handler click event
My goal is to have an EditText that has no fancy features, just the Text Selection Handler for moving the cursor more easily -- so no context menus or pop-ups.

I've disabled the appearance of the text editing function actionbar (copy/Paste etc.) by consuming the ActionMode Callback event, as per this solution.

The middle Middle Text Select Handle (see image below) still appears when text exists in the field and a click occurs within the text. Great! I want to keep this behaviour. What I DON'T want is the "PASTE" menu to appear when the Text Select Handle itself is clicked.

I have also disabled long-click input for the EditText by setting android:longClickable="false" in the styles XML. Disabling the long click prevents the "Paste/Replace" menu from appearing when the mouse is clicked and held (i.e. long touch), however when the mouse is clicked (single touch) within the text, the text selection handle appears, and when the text selection handle itself is clicked, then the "paste" menu option appears (when there's text in the clipboard). This is what I'm trying to prevent.

From what I can see from the source, the ActionPopupWindow is what pops up with the PASTE/REPLACE options. ActionPopupWindow is a protected variable (mActionPopupWindow) in the private abstract class HandleView within public class android.widget.Editor...

Short of disabling the clipboard service or editing the Android Source code, is there a way that I can prevent this from showing? I tried to define a new style for android:textSelectHandleWindowStyle, and set android:visibility to gone, but it didn't work (app froze for a while when it would otherwise have shown).

答:
I found a simple yet reliable way. The idea is the consume away the touch event, to prevent the touch event reach underlining default code.

To disable copy/paste popup.

To disable text selection handler.

Still showing cursor at end of text.

Still showing keyboard.

```<code>maskedEditText.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        focusAndShowKeyboard(view.getContext(), maskedEditText);
        // Consume the event.
        return true;
    }
});

private static void focusAndShowKeyboard(Context context, EditText editText) {
    editText.requestFocus();
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
</code>```

Note, blinking cursor is still showing at end of text. Just that the screenshot unable to capture it.

Body:
I found a simple yet reliable way. The idea is the consume away the touch event, to prevent the touch event reach underlining default code.

To disable copy/paste popup.

To disable text selection handler.

Still showing cursor at end of text.

Still showing keyboard.

maskedEditText.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        focusAndShowKeyboard(view.getContext(), maskedEditText);
        // Consume the event.
        return true;
    }
});

private static void focusAndShowKeyboard(Context context, EditText editText) {
    editText.requestFocus();
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}

Note, blinking cursor is still showing at end of text. Just that the screenshot unable to capture it.


来源: stackexchange

问:
spread syntax with map doesn't work
```<code>data.map(obj =>
        {person_name: obj.user.name,
        ...obj})
</code>```

Why above code failed?

my data look like this

```<code>[{user:{name:'hello'},age:1},{user:{name:'world'},age:1,{user:{name:'another_name'},age:1]
</code>```

I want to 'pull' the obj.user.name out from the nested obj.

答:
You can use Array.prototype.map() and directly return the desired object:

const data = [{user: {name: 'hello'},age: 1}, {user: {name: 'world'},age: 1},{user: {name: 'another_name'},age: 1}];
const result = data.map(obj => {
  return {
    person_name: obj.user.name,
    age: obj.age
  };
});

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

ContentLicense: CC BY-SA 3.0

Title: spread syntax with map doesn't work

Body:
data.map(obj =>
        {person_name: obj.user.name,
        ...obj})

Why above code failed?

my data look like this

[{user:{name:'hello'},age:1},{user:{name:'world'},age:1,{user:{name:'another_name'},age:1]

I want to 'pull' the obj.user.name out from the nested obj.

Body:
You can use Array.prototype.map() and directly return the desired object:

const data = [{user: {name: 'hello'},age: 1}, {user: {name: 'world'},age: 1},{user: {name: 'another_name'},age: 1}];
const result = data.map(obj => {
  return {
    person_name: obj.user.name,
    age: obj.age
  };
});

console.log(result);

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


问:
PHP sql statement where clause to multiple array values
How do i use where clause for array if value[3] has multiple data stored           </p>

```<code>$fsql="select * from Error where RptDatime = 201706091000 and partnumber like  ('$value[3]')";
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);

foreach($results as $row)
{
    $mac = $row['Machine'];
    $id = $row['Id'];
    echo 'ID:'.$id.'Machine Number :'.$mac;
}
</code>```

答:
I assume that you have array of numbers so, first you should validate for expected data and then to implode it into comma separated string.</p>

```<code>if(!isset($value[3])){
    return false;
}
if(!is_array($value[3])){
    return false;
}
foreach($value[3] as $number){
    if(!is_numeric($number)){
        return false;
    }
}
$numbers = implode(",",$value[3]);
$fsql=sprintf("select * from Error where RptDatime = 201706091000 and partnumber in  (%s)",$numbers);
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);

foreach($results as $row)
{
    $mac = $row['Machine'];
    $id = $row['Id'];
    echo 'ID:'.$id.'Machine Number :'.$mac;
}
</code>```

Body:
How do i use where clause for array if value[3] has multiple data stored

$fsql="select * from Error where RptDatime = 201706091000 and partnumber like  ('$value[3]')";
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);

foreach($results as $row)
{
    $mac = $row['Machine'];
    $id = $row['Id'];
    echo 'ID:'.$id.'Machine Number :'.$mac;
}

Body:
I assume that you have array of numbers so, first you should validate for expected data and then to implode it into comma separated string.

if(!isset($value[3])){
    return false;
}
if(!is_array($value[3])){
    return false;
}
foreach($value[3] as $number){
    if(!is_numeric($number)){
        return false;
    }
}
$numbers = implode(",",$value[3]);
$fsql=sprintf("select * from Error where RptDatime = 201706091000 and partnumber in  (%s)",$numbers);
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);

foreach($results as $row)
{
    $mac = $row['Machine'];
    $id = $row['Id'];
    echo 'ID:'.$id.'Machine Number :'.$mac;
}


问:
Transform a list to a string
What is the pythonic way to perform the below transformation?

[a, b, c] -> "'a', 'b', 'c'"

Where a, b, and c are all variables holding strings.

答:
Just turn it into a string the normal way and remove the brackets that you don't want?</p>

```<code>str(mylist)[1:-1]
</code>```

Title: Transform a list to a string

Body:
Just turn it into a string the normal way and remove the brackets that you don't want?

str(mylist)[1:-1]


问:
How can I compare two arrays to fill a third?
Imagine I have an array containing the following values:

```<code>$indexes = [ 'Hello' , 'Hoi', 'Ola' , 'Shalom' , 'Salaam'];
</code>```

Furthermore I also have  an incomplete array:

```<code>$values = ['Hello' => 2, 'Ola' => 20 ];
</code>```

How can I merge these arrays to get a result displaying all indexes with their values, and 0 when no value is found?

```<code>$desiredResult = [
 'Hello' => 2,
 'Hoi' => 0,
 'Ola' => 20 ,
 'Shalom' => 0,
 'Salaam' => 0
]
</code>```

答:
You can use array_merge and array_combine, live demo.</p>

```<code>$disiredResult = array_merge(
   array_combine($indexes, array_fill(0, count($indexes), 0)), $values
);
</code>```

Body:
Imagine I have an array containing the following values:

$indexes = [ 'Hello' , 'Hoi', 'Ola' , 'Shalom' , 'Salaam'];

Furthermore I also have  an incomplete array:

$values = ['Hello' => 2, 'Ola' => 20 ];

How can I merge these arrays to get a result displaying all indexes with their values, and 0 when no value is found?

$desiredResult = [
 'Hello' => 2,
 'Hoi' => 0,
 'Ola' => 20 ,
 'Shalom' => 0,
 'Salaam' => 0
]

Body:
You can use array_merge and array_combine, live demo.

$disiredResult = array_merge(
   array_combine($indexes, array_fill(0, count($indexes), 0)), $values
);


问:
More efficient Javascript
Looking for another eye on making the following Javascript more efficient.

The following JSON is produced from a Resteasy service:

```<code>var testing = {
   "com:klistret:cmdb:ci:pojo:successful":true,
   "com:klistret:cmdb:ci:pojo:count":1,
   "com:klistret:cmdb:ci:pojo:elements":{
      "com:klistret:cmdb:ci:pojo:id":123,
      "com:klistret:cmdb:ci:pojo:name":"Mars",
      "com:klistret:cmdb:ci:pojo:type":{
        "com:klistret:cmdb:ci:pojo:id":1,
        "com:klistret:cmdb:ci:pojo:name":"Environment"
      },
      "com:klistret:cmdb:ci:pojo:configuration":{
        "@www:w3:org:2001:XMLSchemainstance:type":"Environment",
        "@Watermark":"past",
        "com:klistret:cmdb:ci:commons:Name":"Mars"
      }
    }
 };
</code>```

Extended the Extjs JSONReader to handle key depths higher than 2 in the createAccessor method.  Wondering if there is a way to make the code more efficient?  The function below will be called like function(testing, "com:klistret:cmdb:ci:pojo:configuration.@Watermark") where the com:klistret:cmdb:ci:pojo:elements property is the root.

```<code>createAccessor : function(){
    var re = /[\[\.]/;

    return function(expr) {
        if(Ext.isEmpty(expr)){
            return Ext.emptyFn;
        }

        if(Ext.isFunction(expr)){
            return expr;
        }

        # THIS FUNCTION I WANT TO BE EFFICIENT
        return function(obj){
         while (String(expr).search(re) !== -1) {
 var i = String(expr).search(re);
 var key = expr.substring(0, i);

 if (obj.hasOwnProperty(key)) {
  obj = obj[key];
 }

 expr = expr.substring(i+1, expr.length);
}

            return obj[expr];
        };
    };
}()
</code>```

答:
This is what I use. I only allow dot annotation, mind:</p>

```<code>Ext.override(Ext.data.JsonReader, {
  createAccessor: function() {
    return function(expr) {
      if (Ext.isEmpty(expr)) {
        return Ext.emptyFn;
      } else if (Ext.isFunction(expr)) {
        return expr;
      } else {
        return function(obj) {
          var parts = (expr || '').split('.'),
              result = obj,
              part,
              match;
          while (parts.length > 0 && result) {
            part = parts.shift();
            match = part.match(/^(.+?)(\[(\d+)\])?$/);
            result = result[match[1]];
            if (result && match[3]) {
              result = result[match[3]];
            }
          }
          return result;
        }
      }
    };
  }()
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: More efficient Javascript

Body:
Looking for another eye on making the following Javascript more efficient.

The following JSON is produced from a Resteasy service:

var testing = {
   "com:klistret:cmdb:ci:pojo:successful":true,
   "com:klistret:cmdb:ci:pojo:count":1,
   "com:klistret:cmdb:ci:pojo:elements":{
      "com:klistret:cmdb:ci:pojo:id":123,
      "com:klistret:cmdb:ci:pojo:name":"Mars",
      "com:klistret:cmdb:ci:pojo:type":{
        "com:klistret:cmdb:ci:pojo:id":1,
        "com:klistret:cmdb:ci:pojo:name":"Environment"
      },
      "com:klistret:cmdb:ci:pojo:configuration":{
        "@www:w3:org:2001:XMLSchemainstance:type":"Environment",
        "@Watermark":"past",
        "com:klistret:cmdb:ci:commons:Name":"Mars"
      }
    }
 };

Extended the Extjs JSONReader to handle key depths higher than 2 in the createAccessor method.  Wondering if there is a way to make the code more efficient?  The function below will be called like function(testing, "com:klistret:cmdb:ci:pojo:configuration.@Watermark") where the com:klistret:cmdb:ci:pojo:elements property is the root.

createAccessor : function(){
    var re = /[\[\.]/;

    return function(expr) {
        if(Ext.isEmpty(expr)){
            return Ext.emptyFn;
        }

        if(Ext.isFunction(expr)){
            return expr;
        }

        # THIS FUNCTION I WANT TO BE EFFICIENT
        return function(obj){
         while (String(expr).search(re) !== -1) {
 var i = String(expr).search(re);
 var key = expr.substring(0, i);

 if (obj.hasOwnProperty(key)) {
  obj = obj[key];
 }

 expr = expr.substring(i+1, expr.length);
}

            return obj[expr];
        };
    };
}()

Body:
This is what I use. I only allow dot annotation, mind:

Ext.override(Ext.data.JsonReader, {
  createAccessor: function() {
    return function(expr) {
      if (Ext.isEmpty(expr)) {
        return Ext.emptyFn;
      } else if (Ext.isFunction(expr)) {
        return expr;
      } else {
        return function(obj) {
          var parts = (expr || '').split('.'),
              result = obj,
              part,
              match;
          while (parts.length > 0 && result) {
            part = parts.shift();
            match = part.match(/^(.+?)(\[(\d+)\])?$/);
            result = result[match[1]];
            if (result && match[3]) {
              result = result[match[3]];
            }
          }
          return result;
        }
      }
    };
  }()
});


问:
Scala array to Java
I have this invocation from scala class to Java

```<code>  private def initSpringActorContext: ConfigurableApplicationContext = {
    val resourceLocations = Array[String]("aopContext.xml", "akkaContext.xml")
    new GenericXmlApplicationContext(resourceLocations))
  }
</code>```

And the java class expect

```<code> public GenericXmlApplicationContext(String... resourceLocations) {
        this.load(resourceLocations);
        this.refresh();
    }
</code>```

I´ve tried to cast this with import collection.JavaConverters._

But I cannot make it works with Arrays.

Any suggestion?

答:
GenericXmlApplicationContext constructor accepts varargs as an argument.

You can use : _* syntax to solve the problem.

```<code>private def initSpringActorContext: ConfigurableApplicationContext = {
    val resourceLocations = Array[String]("aopContext.xml", "akkaContext.xml")
    new GenericXmlApplicationContext(resourceLocations: _*))
  }
</code>```

: in this case is a hint to scala compiler about the type of the expression you have.

_* is a type annotation; it basically says accept any value of varargs (_ for any, * for varargs)

Update: As mentioned in the comment, : _* is a fixed syntax; so above deconstruction is only for explanation purposes.

Title: Scala array to Java

Body:
I have this invocation from scala class to Java

  private def initSpringActorContext: ConfigurableApplicationContext = {
    val resourceLocations = Array[String]("aopContext.xml", "akkaContext.xml")
    new GenericXmlApplicationContext(resourceLocations))
  }

And the java class expect

 public GenericXmlApplicationContext(String... resourceLocations) {
        this.load(resourceLocations);
        this.refresh();
    }

I´ve tried to cast this with import collection.JavaConverters._

But I cannot make it works with Arrays.

Any suggestion?

Body:
GenericXmlApplicationContext constructor accepts varargs as an argument.

You can use : _* syntax to solve the problem.

private def initSpringActorContext: ConfigurableApplicationContext = {
    val resourceLocations = Array[String]("aopContext.xml", "akkaContext.xml")
    new GenericXmlApplicationContext(resourceLocations: _*))
  }

: in this case is a hint to scala compiler about the type of the expression you have.

_* is a type annotation; it basically says accept any value of varargs (_ for any, * for varargs)

Update: As mentioned in the comment, : _* is a fixed syntax; so above deconstruction is only for explanation purposes.


问:
SQLITE add a column counting values in other columns
I have a sql table containing some values as in the example.

```<code> id value
 1  value1
 2  value2
 3  value3
 4  value1
 5  value2
 6  value1
</code>```

I need to add a column that have to increment a counter each time a "value1" is present.

```<code> id value  session
 1  value1    1
 2  value2    1
 3  value3    1
 4  value1    2
 5  value2    2
 6  value1    3
</code>```

Can you help me?
Thank you

答:
You can use sql subquery with agregation

Your table

```

    CREATE TABLE test (id integer PRIMARY KEY AUTOINCREMENT NOT NULL, value nvarchar (10));

```

Populate with data

```

    INSERT INTO test(value) values ('value1'),('value2'),
       ('value3'),('value1'),('value2'),('value3'),
       ('value1'),('value1'),('value2');

```

Enjoy

```

    SELECT a.id,a.value, (SELECT COUNT(b.id)
        FROM   test b
        WHERE  a.id>=b.id and b.value = 'value1') session
    FROM   test a
    ORDER  BY a.id;

```

Body:
I have a sql table containing some values as in the example.

 id value
 1  value1
 2  value2
 3  value3
 4  value1
 5  value2
 6  value1

I need to add a column that have to increment a counter each time a "value1" is present.

 id value  session
 1  value1    1
 2  value2    1
 3  value3    1
 4  value1    2
 5  value2    2
 6  value1    3

Can you help me?
Thank you

Body:
You can use sql subquery with agregation

Your table

    CREATE TABLE test (id integer PRIMARY KEY AUTOINCREMENT NOT NULL, value nvarchar (10));

Populate with data

    INSERT INTO test(value) values ('value1'),('value2'),
       ('value3'),('value1'),('value2'),('value3'),
       ('value1'),('value1'),('value2');

Enjoy

    SELECT a.id,a.value, (SELECT COUNT(b.id)
        FROM   test b
        WHERE  a.id>=b.id and b.value = 'value1') session
    FROM   test a
    ORDER  BY a.id;


问:
C# creating a ListBox application
Im suppose to create a windows app in C# using a ListBox object. I need to create an order form with 6 different things to be purchased. Can someone please show me how to code for a list box?</p>

答: Have a look at the ListBox class. This MSDN page has many examples. Take a look at the Items property which holds the list of items.</p>

Title: C# creating a ListBox application


答:
You can use built-in functions (see other answers), but you can of course also loop yourself.

```<code>function addKeys(&$arr, $keys, $value = 0) {
  foreach ($keys as $key) {
    if (!array_key_exists($key, $arr)) {
      $arr[$key] = $value;
    }
  }
  return $arr;
}
</code>```

Try it online!

Title: How can I compare two arrays to fill a third?

Body:
You can use built-in functions (see other answers), but you can of course also loop yourself.

function addKeys(&$arr, $keys, $value = 0) {
  foreach ($keys as $key) {
    if (!array_key_exists($key, $arr)) {
      $arr[$key] = $value;
    }
  }
  return $arr;
}

Try it online!


问:
How could I check if string is only match into an other string
I'm actually a beginner into web developpment.

I have a problem with my actual condition.

Exemple :

```<code>$rooms = 10;
</code>```

In my code, I check if $rooms is equal to 1,0 or 10 so :

```<code>if(strpos($rooms, '1')){echo 1;}
if(strpos($rooms, '0')){echo 0};
if(strpos($rooms, '10')){echo 10;}
</code>```

My result :

```<code>1
0
10
</code>```

My condition match for 1, 0 and 10, where I only need to match the number 10

How can I only pass into my third condition ?

Thx

答: use if($rooms=='10'){echo 10;} to check if it is equal

Body:
I'm actually a beginner into web developpment.

I have a problem with my actual condition.

Exemple :

$rooms = 10;

In my code, I check if $rooms is equal to 1,0 or 10 so :

if(strpos($rooms, '1')){echo 1;}
if(strpos($rooms, '0')){echo 0};
if(strpos($rooms, '10')){echo 10;}

My result :

1
0
10

My condition match for 1, 0 and 10, where I only need to match the number 10

How can I only pass into my third condition ?

Thx


问:
Static final field in a class vs Interface field in java
I need to create a 100 or more static final constants in my application and I can achieve this is following two ways as per my understanding:

Creating a simple java class and create static final field in that

Creating an interface an put all variable in that because all field in an interface is implicitly static final

I have these question in above approach:

Which one is right approach to achieve this?

Which one is memory efficient approach?

Is there any design pattern to achieve this?

答:
Have you considered approach with ENUM or it doesn't fit in your case?
I think, the approach with ENUM can gives you some benefits over constants.

Why use Enums instead of Constants?


问:
Replace a String in Javascript using regex
my input is
var email = "xyz+wex+rr%40gmail.com";

i need output as

xyz wex rr @ gmail.com

i have tried with this below regex , i can only remove + from my string how to replace %40 with @

email .replace(/+/g, " ");

答:
var email = "xyz+wex+rr%40gmail.com";
email = decodeURIComponent(email).replace(/\+/g, " ");
console.log(email);```

decodeURIComponent decodes things like %40. It only does not replace the + signs with spaces, so this is done with a RegEx, escaping the plus sign, which has a special meaning in RegEx.

Body:
var email = "xyz+wex+rr%40gmail.com";
email = decodeURIComponent(email).replace(/\+/g, " ");
console.log(email);

decodeURIComponent decodes things like %40. It only does not replace the + signs with spaces, so this is done with a RegEx, escaping the plus sign, which has a special meaning in RegEx.


问:
Styling with QRadioButton and [type="..."]
I'm using Qt for styling my radio buttons and use the program WinCC OA. The problem is when I use

```<code>QRadioButton::indicator::unchecked
</code>```

all my radio buttons get this style. I want to give them different styles with types. But wherever I input my

```<code>[type="Radiobuttons_1"]
</code>```

in the code above the style is not accepted and my radio button lose their style.

How can I style them differently?

答:
Within WinCC OA, you have to define the TypeName of the RadioButtons within the Property dialog of the corresponding UI element in the GEDI application, in your case to "Radiobuttons_1".

Be aware that you can reload the stylesheets with Edit > Reload Stylesheet

Body:
I'm using Qt for styling my radio buttons and use the program WinCC OA. The problem is when I use

QRadioButton::indicator::unchecked

all my radio buttons get this style. I want to give them different styles with types. But wherever I input my

[type="Radiobuttons_1"]

in the code above the style is not accepted and my radio button lose their style.

How can I style them differently?


问:
Using Oracle user-defined object types in Apache Camel SQL-STORED Component
Does anybody have an example on how to use Oracle user-defined object types when calling a stored procedure via the Camel sql-stored component? The Camel documentation (http://camel.apache.org/sql-stored-procedure.html) provides only an example using built-in data types.

Here are my details:

I am trying to call the following procedure:

```<code>PROCEDURE get_eco_record(
      p_instance_id IN NUMBER,
      p_inparm IN InParm_rec,
      p_error_cd OUT NUMBER,
      p_error_message OUT VARCHAR2 )
</code>```

This is the definition of the InParm_rec object type:

```<code>CREATE OR REPLACE TYPE InParm_rec
AS
  object
  (
    part_no   VARCHAR2(75 BYTE) ,
    part_type VARCHAR2(100 BYTE) ,
    eff_date DATE,
    sub_name VARCHAR2(100),
    rec_type VARCHAR2(1)
    );
</code>```

答:
After some digging the answer is "No". However, the extension should be fairly straightforward. When using custom data types, declaration of each SqlParameter needs to have (at least) three parameters - parameter_name, Oracle_type and custom_data_type_name. In my example, the declaration of the attributes should be as follows:

```<code>    declareParameter(new SqlParameter("p_instance_id", OracleTypes.INTEGER));
        declareParameter(new SqlParameter("p_inparm",OracleTypes.ARRAY, "InParm_rec"));
        declareParameter(new SqlOutParameter("p_error_cd", OracleTypes.INTEGER));
        declareParameter(new SqlOutParameter("p_error_message", OracleTypes.VARCHAR));
</code>```

Going back to Camel SQL Stored Procedure Component - the component is declaring the procedure parameters in Class

```<code>org.apache.camel.component.sql.stored.TemplateStoredProcedure
</code>```

Here is the code snippet that handles declaration of procedure parameters:

```<code>for (Object parameter : template.getParameterList()) {
    if (parameter instanceof InputParameter) {
        InputParameter inputParameter = (InputParameter) parameter;
        declareParameter(new SqlParameter(inputParameter.getName(), inputParameter.getSqlType()));
        inputParameterList.add(inputParameter);

    } else if (parameter instanceof OutParameter) {
        OutParameter outParameter = (OutParameter) parameter;
        declareParameter(new SqlOutParameter(outParameter.getOutValueMapKey(), outParameter.getSqlType()));
        setFunction(false);
    }
}
</code>```

The code currently supports only two parameters (parameter_name, Oracle_type). The code would have to be extended to add the third parameter (custom_data_type_name). The additional parameter would have to be applied to user-named types like: STRUCT, DISTINCT, JAVA_OBJECT, named array types.

Another parameter that might be needed is "scale" which is applicable to NUMERIC and DECIMAL data types.

The best approach would be to inspect the org.springframework.jdbc.core.SqlParameter and org.springframework.jdbc.core.SqlOutParameter classes and extend Camel Sql-Stored to support all their options.

Body:
Does anybody have an example on how to use Oracle user-defined object types when calling a stored procedure via the Camel sql-stored component? The Camel documentation (http://camel.apache.org/sql-stored-procedure.html) provides only an example using built-in data types.

Here are my details:

I am trying to call the following procedure:

PROCEDURE get_eco_record(
      p_instance_id IN NUMBER,
      p_inparm IN InParm_rec,
      p_error_cd OUT NUMBER,
      p_error_message OUT VARCHAR2 )

This is the definition of the InParm_rec object type:

CREATE OR REPLACE TYPE InParm_rec
AS
  object
  (
    part_no   VARCHAR2(75 BYTE) ,
    part_type VARCHAR2(100 BYTE) ,
    eff_date DATE,
    sub_name VARCHAR2(100),
    rec_type VARCHAR2(1)
    );

Body:
After some digging the answer is "No". However, the extension should be fairly straightforward. When using custom data types, declaration of each SqlParameter needs to have (at least) three parameters - parameter_name, Oracle_type and custom_data_type_name. In my example, the declaration of the attributes should be as follows:

    declareParameter(new SqlParameter("p_instance_id", OracleTypes.INTEGER));
        declareParameter(new SqlParameter("p_inparm",OracleTypes.ARRAY, "InParm_rec"));
        declareParameter(new SqlOutParameter("p_error_cd", OracleTypes.INTEGER));
        declareParameter(new SqlOutParameter("p_error_message", OracleTypes.VARCHAR));

Going back to Camel SQL Stored Procedure Component - the component is declaring the procedure parameters in Class

org.apache.camel.component.sql.stored.TemplateStoredProcedure

Here is the code snippet that handles declaration of procedure parameters:

for (Object parameter : template.getParameterList()) {
    if (parameter instanceof InputParameter) {
        InputParameter inputParameter = (InputParameter) parameter;
        declareParameter(new SqlParameter(inputParameter.getName(), inputParameter.getSqlType()));
        inputParameterList.add(inputParameter);

    } else if (parameter instanceof OutParameter) {
        OutParameter outParameter = (OutParameter) parameter;
        declareParameter(new SqlOutParameter(outParameter.getOutValueMapKey(), outParameter.getSqlType()));
        setFunction(false);
    }
}

The code currently supports only two parameters (parameter_name, Oracle_type). The code would have to be extended to add the third parameter (custom_data_type_name). The additional parameter would have to be applied to user-named types like: STRUCT, DISTINCT, JAVA_OBJECT, named array types.

Another parameter that might be needed is "scale" which is applicable to NUMERIC and DECIMAL data types.

The best approach would be to inspect the org.springframework.jdbc.core.SqlParameter and org.springframework.jdbc.core.SqlOutParameter classes and extend Camel Sql-Stored to support all their options.


问:
Passing state data with google actions
I am developing a Google Actions project for Google Home using api.ai.

Is it possible to pass a state parameter as part of the response to api.ai and have it included in the next request?

The Amazon Alexa API handles such a flow and it came in handy.

Thanks

EDIT:

I did not mention this before: I have api.ai sending requests to a webhook after google assistant triggers my intents. The response api.ai expects is defined here. I've tried including extra fields in the response but these are not included in any future intent requests from api.ai. I've also tried adding fields and values to the google specific portion of the response (defined here) to no avail.

As an example of what I am interested in, when responding to Alexa requests we can include a json field "sessionAttributes" which are then passed by Amazon in any future requests that are part of that interaction.

In this instance I query a database key on the first intent (which is subsequently used to pull a record) and pass that key in sessionAttributes to avoid performing that lookup for every intent request I receive.

答:
The equivalent that you are looking for to sessionAttributes in Alexa dev depends on whether you are using an API.ai webhook or a conversation webhook. Reference this doc for more info on the differences.

Since you are using API.ai, assuming you are using the Node.js client library, use the snippet below. 'Contexts' can store data, not just serve as a flag of sorts to establish where you are in a conversation. Call setContext just before you call 'ask' and close out your webhook fulfillment.

app.setContext('<context name>', <lifespan of context>, <JSON to store>)

Then for the next round of fulfillment, retrieve the JSON from the parameters object within the Context. Get it with:

var myContext = app.getContext('<context name>')

Reference the examples in these docs for more info.

Title: Passing state data with google actions


问:
Verify submitted Django form in view
I have a view, which expects a POST request. The post request should contain data submitted through a Django form.

The Django form looks something like this:

```<code>class SubmitForm(forms.Form):
    title = forms.CharField(max_length=100)
    comment = forms.CharField(max_length=255)
</code>```

I know I have access to the submitted data with request.POST["title"] and  request.POST["comment"]. So I can theoretically check if they're set and valid manually.

But is there a way to use .is_valid() (Link to Django documentation), to validate the submitted form?

One possibility would be to create a form in the view, fill it with the submitted data and then check it for validity.

```<code>data = {'title': request.POST["title"],
        'comment': request.POST["comment"]}
f = SubmitForm(data)
f.is_valid()
# True/False
</code>```

Is there a direct way to use is_valid() on a submitted Django form?

答:
You can pass request.POST as Form argument directly:

```<code>form = PostForm(request.POST or None)
if form.is_valid():
    ....
</code>```

Title: Verify submitted Django form in view

Body:
I have a view, which expects a POST request. The post request should contain data submitted through a Django form.

The Django form looks something like this:

class SubmitForm(forms.Form):
    title = forms.CharField(max_length=100)
    comment = forms.CharField(max_length=255)

I know I have access to the submitted data with request.POST["title"] and  request.POST["comment"]. So I can theoretically check if they're set and valid manually.

But is there a way to use .is_valid() (Link to Django documentation), to validate the submitted form?

One possibility would be to create a form in the view, fill it with the submitted data and then check it for validity.

data = {'title': request.POST["title"],
        'comment': request.POST["comment"]}
f = SubmitForm(data)
f.is_valid()
# True/False

Is there a direct way to use is_valid() on a submitted Django form?

Body:
You can pass request.POST as Form argument directly:

form = PostForm(request.POST or None)
if form.is_valid():
    ....


问:
How can I get 'ng serve -o' to launch a page other than index.html?
Our angular app will be embedded in an iframe when in production. In development, we have a file, host.html, which has an iframe whose src is the angular app's index page. We can 'ng serve' and then manually bring up host.html and it works fine.

But, 'ng serve -o' wants to open up the app index file; how do I make it open host.html instead?

答:
So I don't think angular cli supports opening an arbitrary page with the -o option, but you could make your own npm script that does what you want.

Try opening package.json and editing the scripts section to update the start script like so (mac version):

```<code>"scripts": {
    "ng": "ng",

    // where localhost:4200 is your dev host and port, respectively
    "start": "ng serve && open http://localhost:4200/host.html",

    "build": "ng build",
    ...
  },
</code>```

Depending on what platform you're using, the script would need to be written differently:

```<code>// Windows
"start":"ng serve & start http://localhost:4200/host.html"

// Mac
"start":"ng serve && open http://localhost:4200/host.html"

// Linux
"start":"ng serve && xdg-open http://localhost:4200/host.html"
</code>```

Then, instead of using ng serve to start your app, use npm start.

Reference: used this SO answer for the platform specific open commands.

Body:
So I don't think angular cli supports opening an arbitrary page with the -o option, but you could make your own npm script that does what you want.

Try opening package.json and editing the scripts section to update the start script like so (mac version):

"scripts": {
    "ng": "ng",

    // where localhost:4200 is your dev host and port, respectively
    "start": "ng serve && open http://localhost:4200/host.html",

    "build": "ng build",
    ...
  },

Depending on what platform you're using, the script would need to be written differently:

// Windows
"start":"ng serve & start http://localhost:4200/host.html"

// Mac
"start":"ng serve && open http://localhost:4200/host.html"

// Linux
"start":"ng serve && xdg-open http://localhost:4200/host.html"

Then, instead of using ng serve to start your app, use npm start.

Reference: used this SO answer for the platform specific open commands.


答: Perhaps google for "c# listbox tutorial"</p>

Title: C# creating a ListBox application

Body: Im suppose to create a windows app in C# using a ListBox object. I need to create an order form with 6 different things to be purchased. Can someone please show me how to code for a list box?


问:
While scrolling tableview my waves animation getting halts in iOS
I am doing iOS application with Objective-C, in that I am doing some voice recording and translating audio to speech, speech to audio. That speech/audio data showing in tableview. Its like how Siri doing in iPhone.

My issue is, I am displaying view top tableview and under UItableview showing animationview, its UIview object. Animationview working fine, but if I . scroll up/down the tableview, animationview getting distrub/halting the animation and after I release the tableview, its working fine again.

I tried to run it on Main thread again, but no use, still same issue happening.

My code is following :

```<code>-(void)startAnimation{

    animationTimer =  [NSTimer scheduledTimerWithTimeInterval:0.009 target:self selector:@selector(refreshAnimationView:) userInfo:nil repeats:YES];

}

- (void)refreshAnimationView:(NSTimer*)theTimer {

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ // Your code to run on the main queue/thread

        //animation code here

          }
      }];
}
</code>```

Can anyone suggest me how to handle this.

答:
Try adding your timer for NSRunLoopCommonModes after you create it.

[NSRunLoop.mainRunLoop addTimer:animationTimer forMode:NSRunLoopCommonModes];

Body:
I am doing iOS application with Objective-C, in that I am doing some voice recording and translating audio to speech, speech to audio. That speech/audio data showing in tableview. Its like how Siri doing in iPhone.

My issue is, I am displaying view top tableview and under UItableview showing animationview, its UIview object. Animationview working fine, but if I . scroll up/down the tableview, animationview getting distrub/halting the animation and after I release the tableview, its working fine again.

I tried to run it on Main thread again, but no use, still same issue happening.

My code is following :

-(void)startAnimation{

    animationTimer =  [NSTimer scheduledTimerWithTimeInterval:0.009 target:self selector:@selector(refreshAnimationView:) userInfo:nil repeats:YES];

}

- (void)refreshAnimationView:(NSTimer*)theTimer {

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ // Your code to run on the main queue/thread

        //animation code here

          }
      }];
}

Can anyone suggest me how to handle this.


问:
How to get the current products in cart in Magento?

I need to get the currently products in cart to estimate how many
  products are in ? I used the below code but it gave me this error
  message
  > Fatal error: Call to undefined method
  Mage_Sales_Model_Resource_Quote_Item_Collection::getAllItems()

Code:

```<code>    <?php

      require 'app/Mage.php';
      Mage::app();

     if (!Mage::isInstalled()) {
        echo "Application is not installed yet, please complete install wizard first.";

}

     $cart =Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection();
           foreach ($cart->getAllItems() as $item) {
                   $productName = $item->getProduct()->getName();
                   $productPrice = $item->getProduct()->getPrice();

          print($item);

}
</code>```

答:
Try with this below code.

$totalItems = Mage::getSingleton('checkout/cart')->getQuote()->getItemsCount();

For more details refer this link : http://www.magebuzz.com/blog/magento-get-product-quantity-in-cart/

Body:
I need to get the currently products in cart to estimate how many
  products are in ? I used the below code but it gave me this error
  message
  > Fatal error: Call to undefined method
  Mage_Sales_Model_Resource_Quote_Item_Collection::getAllItems()

Code:

    <?php

      require 'app/Mage.php';
      Mage::app();

     if (!Mage::isInstalled()) {
        echo "Application is not installed yet, please complete install wizard first.";

}

     $cart =Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection();
           foreach ($cart->getAllItems() as $item) {
                   $productName = $item->getProduct()->getName();
                   $productPrice = $item->getProduct()->getPrice();

          print($item);

}


问:
Multiple buttons in HeroCard
I'd like to have multiple buttons on HeroCard
and be able to press all buttons one after another
but when I press click button program jumps to next function in waterfall
and expects next action instead of button action again
what should I do in this case?

```<code>bot.dialog("/showCards", [
    (session) => {
        const msg = new Message(session)
            .textFormat(TextFormat.xml)
            .attachmentLayout(AttachmentLayout.carousel)
            .attachments([{
                title: "title",
                url: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png"
            }].map(obj =>
                new HeroCard(session)
                    .title(obj.title)
                    .images([
                        CardImage.create(session, obj.url)
                            .tap(CardAction.showImage(session, obj.url)),
                    ])
                    .buttons([
                        CardAction.openUrl(session, obj.url),
                        CardAction.imBack(session, `click`, "Click"),
                        CardAction.imBack(session, `clack`, "Clack")
                    ])
            ));
        Prompts.choice(session, msg, ["click", "clack"]);

    },
    (session, results) => {
        // todo use results.response.entity
    }
]);
</code>```

答:
You could also use CardAction.dialogAction and link every button to a beginDialogAction.

```<code>let card = new builder.HeroCard(session)
    .title(title)
    .subtitle(subtitle)
    .buttons([builder.CardAction.dialogAction(session, 'dialogAAction', 'dataYouNeedInDialogA', 'ButtonTitleA'), builder.CardAction.dialogAction(session, 'dialogBAction', 'dataYouNeedInDialogA', 'ButtonTitleB')]);

let msg = new builder.Message(session)
    .attachments([card])

session.endDialog(msg);
// use one of these two to either end the dialog and start a new one  or to stay in the current dialog and wait for user input
session.send(msg);

// don't forget to add the dialogs to your bot / library later in your code (outside your current dialog)
bot.dialog('dialogA', dialogA); // initialized somewhere in your code
bot.dialog('dialogB', dialogB);
bot.beginDialogAction('dialogAAction', 'dialogA');
bot.beginDialogAction('dialogBAction', 'dialogB', {
onSelectAction: (session, args, next) => {
    // you might want to clear the dialogStack if the button is pressed. Otherwise, if the button is pressed multiple times, instances of dialogB are pilled up on the dialog stack.
    session.clearDialogStack();
    next();
  }
});
</code>```

In my opinion, this is the best way to achieve the behaviour you described so far. All buttons work whenever the user presses them, even if they scroll back in the conversation and press the same button again. The only trade-off is that you have to pass data to the new dialog and can not use dialogData throughout the whole flow. Nevertheless, I think it's worth it because ensures consistent UX throughout the usage of the bot.

Hope this helps. You can build click and clack dialogs, link them to actions and pass the data that you need. The user would be able to press click, clack, click and the bot would still work. :)

Title: Multiple buttons in HeroCard

Body:
I'd like to have multiple buttons on HeroCard
and be able to press all buttons one after another
but when I press click button program jumps to next function in waterfall
and expects next action instead of button action again
what should I do in this case?

bot.dialog("/showCards", [
    (session) => {
        const msg = new Message(session)
            .textFormat(TextFormat.xml)
            .attachmentLayout(AttachmentLayout.carousel)
            .attachments([{
                title: "title",
                url: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png"
            }].map(obj =>
                new HeroCard(session)
                    .title(obj.title)
                    .images([
                        CardImage.create(session, obj.url)
                            .tap(CardAction.showImage(session, obj.url)),
                    ])
                    .buttons([
                        CardAction.openUrl(session, obj.url),
                        CardAction.imBack(session, `click`, "Click"),
                        CardAction.imBack(session, `clack`, "Clack")
                    ])
            ));
        Prompts.choice(session, msg, ["click", "clack"]);

    },
    (session, results) => {
        // todo use results.response.entity
    }
]);

Body:
You could also use CardAction.dialogAction and link every button to a beginDialogAction.

let card = new builder.HeroCard(session)
    .title(title)
    .subtitle(subtitle)
    .buttons([builder.CardAction.dialogAction(session, 'dialogAAction', 'dataYouNeedInDialogA', 'ButtonTitleA'), builder.CardAction.dialogAction(session, 'dialogBAction', 'dataYouNeedInDialogA', 'ButtonTitleB')]);

let msg = new builder.Message(session)
    .attachments([card])

session.endDialog(msg);
// use one of these two to either end the dialog and start a new one  or to stay in the current dialog and wait for user input
session.send(msg);

// don't forget to add the dialogs to your bot / library later in your code (outside your current dialog)
bot.dialog('dialogA', dialogA); // initialized somewhere in your code
bot.dialog('dialogB', dialogB);
bot.beginDialogAction('dialogAAction', 'dialogA');
bot.beginDialogAction('dialogBAction', 'dialogB', {
onSelectAction: (session, args, next) => {
    // you might want to clear the dialogStack if the button is pressed. Otherwise, if the button is pressed multiple times, instances of dialogB are pilled up on the dialog stack.
    session.clearDialogStack();
    next();
  }
});

In my opinion, this is the best way to achieve the behaviour you described so far. All buttons work whenever the user presses them, even if they scroll back in the conversation and press the same button again. The only trade-off is that you have to pass data to the new dialog and can not use dialogData throughout the whole flow. Nevertheless, I think it's worth it because ensures consistent UX throughout the usage of the bot.

Hope this helps. You can build click and clack dialogs, link them to actions and pass the data that you need. The user would be able to press click, clack, click and the bot would still work. :)


问:
Delete rows and keep only last value in android sqlite
To keep things simple, here's a sample structure:

```<code>    id   |      otherId   |        date       | actionId  |
__________________________________________________________
    1             30          09.06.2017 10:22     5
    2             30          09.06.2017 10:24     5
    3             31          09.06.2017 10:24     4
    4             32          09.06.2017 10:25     2
    5             32          09.06.2017 10:26     2
</code>```

The id is autoincremented field.
As you may see, otherId=30 value has 2 rows and I need to only have the most recent one. So keep the row with id=2 and delete all others.Same goes for otherId=32.

Is there a simple way to run a sql command to achieve this or only by going and checking row by row?

答:
You want to delete all rows for wich a row with the same otherId but a larger id value exists. In SQL:

```<code>DELETE FROM MyTable
WHERE EXISTS (SELECT *
              FROM MyTable AS T2
              WHERE T2.otherId = MyTable.otherId
                AND T2.id      > MyTable.id);
</code>```

Body:
To keep things simple, here's a sample structure:

    id   |      otherId   |        date       | actionId  |
__________________________________________________________
    1             30          09.06.2017 10:22     5
    2             30          09.06.2017 10:24     5
    3             31          09.06.2017 10:24     4
    4             32          09.06.2017 10:25     2
    5             32          09.06.2017 10:26     2

The id is autoincremented field.
As you may see, otherId=30 value has 2 rows and I need to only have the most recent one. So keep the row with id=2 and delete all others.Same goes for otherId=32.

Is there a simple way to run a sql command to achieve this or only by going and checking row by row?

Body:
You want to delete all rows for wich a row with the same otherId but a larger id value exists. In SQL:

DELETE FROM MyTable
WHERE EXISTS (SELECT *
              FROM MyTable AS T2
              WHERE T2.otherId = MyTable.otherId
                AND T2.id      > MyTable.id);


问:
Processing: Moving multiple shapes in the same direction
So I am trying to make multiple shapes move in the same direction using PVector values. The problem I am facing is that in order to make the object I wan (in this case a crude illustration of a fly) I need to rotate the objects. Doing so makes vector math add in the direction of the rotation of the object. Is there some function or math I can use to normalize the angular velocity of each shape?

class tFly{

boolean count=false;
boolean countTwo=false;
boolean move=false;
PVector location;
PVector velocity;

  tFly(){
   location= new PVector(0,0);
  velocity = new PVector(1,1);
  }
void flap(){//flap wings if moving, else keep them still

  if(move==false){
  pushMatrix(); //wings
noStroke();

translate(235,285);
rotate(radians(25));
ellipse(location.x,location.y,25,50);

popMatrix();

pushMatrix(); //wings
noStroke();

translate(263,285);
rotate(radians(340));
ellipse(location.x,location.y,25,50);

popMatrix();

  }else{
pushMatrix(); //wings
noStroke();
translate(235,285);
if(count==false){
rotate(radians(49));
ellipse(location.x,location.y,25,50);
count=true;
}else{
rotate(radians(21));
ellipse(location.x,location.y,25,50);
count=false;
}

popMatrix();

pushMatrix(); //wings
noStroke();
translate(263,285);
if(countTwo==false){
rotate(radians(320));
ellipse(location.x,location.y,25,50);
countTwo=true;
}else{
rotate(radians(340));
ellipse(location.x,location.y,25,50);
countTwo=false;
}

popMatrix();
}
}
void display(){
  fill(0);
ellipse(location.x+250,location.y+265,20,50);

ellipse(location.x+250,location.y+280,25,34);
pushMatrix();

translate(240,230);
rotate(radians(70));
rect(location.x,location.y,15,.5);
popMatrix();

pushMatrix();
translate(262,232);
rotate(radians(110));
rect(location.x,location.y,15,.5);
popMatrix();

pushMatrix();
translate(230,260);
rotate(radians(40));
rect(location.x,location.y,15,.5);
popMatrix();

pushMatrix();
translate(270,262);
rotate(radians(140));
rect(location.x,location.y,15,.5);
popMatrix();

pushMatrix();
translate(240,285);
rotate(radians(120));
rect(location.x,location.y,15,.5);
popMatrix();

pushMatrix();
translate(260,285);
rotate(radians(50));
rect(location.x,location.y,15,.5);
popMatrix();

fill(255,0,0);

ellipse(location.x+240,location.y+250,20,18);
ellipse(location.x+260,location.y+250,20,18);
fill(128,128,128,127);

flap();

}
void update(){
location.add(velocity);

}

}
```

<p>Here is how I use this in setup and draw </p>

<pre class="lang-java prettyprint-override"><code>tFly fly;

void setup(){
size(500,500);
background(255);
fly=new tFly();
}

void draw(){
background(255);
  ellipseMode(CENTER);

fly.display();
fly.update();

}
</code>```

答:
You're already getting the hang of pushMatrix()/popMatrix()...why not nest all the drawing calls from display() within a separate pushMatrix()/popMatrix() call and simple translate that whole group ?

```<code>class tFly {

  boolean count=false;
  boolean countTwo=false;
  boolean move=true;
  PVector location;
  PVector velocity;

  tFly() {
    location= new PVector(0, 0);
    velocity = new PVector(1, 1);
  }
  void flap() {//flap wings if moving, else keep them still

    if (move==false) {
      pushMatrix(); //wings
      noStroke();

      translate(235, 285);
      rotate(radians(25));
      ellipse(0, 0, 25, 50);

      popMatrix();

      pushMatrix(); //wings
      noStroke();

      translate(263, 285);
      rotate(radians(340));
      ellipse(0, 0, 25, 50);

      popMatrix();
    } else {
      pushMatrix(); //wings
      noStroke();
      translate(235,285);
      if (count==false) {
        rotate(radians(49));
        ellipse(0, 0, 25, 50);
        count=true;
      } else {
        rotate(radians(21));
        ellipse(0, 0, 25, 50);
        count=false;
      }

      popMatrix();

      pushMatrix(); //wings
      noStroke();
      translate(263, 285);
      if (countTwo==false) {
        rotate(radians(320));
        ellipse(0, 0, 25, 50);
        countTwo=true;
      } else {
        rotate(radians(340));
        ellipse(0, 0, 25, 50);
        countTwo=false;
      }

      popMatrix();
    }
  }
  void display() {
    pushMatrix();
    translate(location.x, location.y);

    fill(0);
    ellipse(250, 265, 20, 50);

    ellipse(250, 280, 25, 34);
    pushMatrix();

    translate(240, 230);
    rotate(radians(70));
    rect(0, 0, 15, .5);
    popMatrix();

    pushMatrix();
    translate(262, 232);
    rotate(radians(110));
    rect(0, 0, 15, .5);
    popMatrix();

    pushMatrix();
    translate(230, 260);
    rotate(radians(40));
    rect(0, 0, 15, .5);
    popMatrix();

    pushMatrix();
    translate(270, 262);
    rotate(radians(140));
    rect(0, 0, 15, .5);
    popMatrix();

    pushMatrix();
    translate(240, 285);
    rotate(radians(120));
    rect(0, 0, 15, .5);
    popMatrix();

    pushMatrix();
    translate(260, 285);
    rotate(radians(50));
    rect(0, 0, 15, .5);
    popMatrix();

    fill(255, 0, 0);

    ellipse(240, 250, 20, 18);
    ellipse(260, 250, 20, 18);
    fill(128, 128, 128, 127);

    flap();

    popMatrix();
  }
  void update() {
    location.add(velocity);
  }
}

tFly fly;

void setup() {
  size(500, 500);
  background(255);
  fly=new tFly();
}

void draw() {
  background(255);
  ellipseMode(CENTER);

  fly.display();
  fly.update();
}
</code>```

Body:
So I am trying to make multiple shapes move in the same direction using PVector values. The problem I am facing is that in order to make the object I wan (in this case a crude illustration of a fly) I need to rotate the objects. Doing so makes vector math add in the direction of the rotation of the object. Is there some function or math I can use to normalize the angular velocity of each shape?

class tFly{

boolean count=false;
boolean countTwo=false;
boolean move=false;
PVector location;
PVector velocity;

  tFly(){
   location= new PVector(0,0);
  velocity = new PVector(1,1);
  }
void flap(){//flap wings if moving, else keep them still

  if(move==false){
  pushMatrix(); //wings
noStroke();

translate(235,285);
rotate(radians(25));
ellipse(location.x,location.y,25,50);

popMatrix();

pushMatrix(); //wings
noStroke();

translate(263,285);
rotate(radians(340));
ellipse(location.x,location.y,25,50);

popMatrix();

  }else{
pushMatrix(); //wings
noStroke();
translate(235,285);
if(count==false){
rotate(radians(49));
ellipse(location.x,location.y,25,50);
count=true;
}else{
rotate(radians(21));
ellipse(location.x,location.y,25,50);
count=false;
}

popMatrix();

pushMatrix(); //wings
noStroke();
translate(263,285);
if(countTwo==false){
rotate(radians(320));
ellipse(location.x,location.y,25,50);
countTwo=true;
}else{
rotate(radians(340));
ellipse(location.x,location.y,25,50);
countTwo=false;
}

popMatrix();
}
}
void display(){
  fill(0);
ellipse(location.x+250,location.y+265,20,50);

ellipse(location.x+250,location.y+280,25,34);
pushMatrix();

translate(240,230);
rotate(radians(70));
rect(location.x,location.y,15,.5);
popMatrix();

pushMatrix();
translate(262,232);
rotate(radians(110));
rect(location.x,location.y,15,.5);
popMatrix();

pushMatrix();
translate(230,260);
rotate(radians(40));
rect(location.x,location.y,15,.5);
popMatrix();

pushMatrix();
translate(270,262);
rotate(radians(140));
rect(location.x,location.y,15,.5);
popMatrix();

pushMatrix();
translate(240,285);
rotate(radians(120));
rect(location.x,location.y,15,.5);
popMatrix();

pushMatrix();
translate(260,285);
rotate(radians(50));
rect(location.x,location.y,15,.5);
popMatrix();

fill(255,0,0);

ellipse(location.x+240,location.y+250,20,18);
ellipse(location.x+260,location.y+250,20,18);
fill(128,128,128,127);

flap();

}
void update(){
location.add(velocity);

}

}

Here is how I use this in setup and draw

tFly fly;

void setup(){
size(500,500);
background(255);
fly=new tFly();
}

void draw(){
background(255);
  ellipseMode(CENTER);

fly.display();
fly.update();

}

Body:
You're already getting the hang of pushMatrix()/popMatrix()...why not nest all the drawing calls from display() within a separate pushMatrix()/popMatrix() call and simple translate that whole group ?

class tFly {

  boolean count=false;
  boolean countTwo=false;
  boolean move=true;
  PVector location;
  PVector velocity;

  tFly() {
    location= new PVector(0, 0);
    velocity = new PVector(1, 1);
  }
  void flap() {//flap wings if moving, else keep them still

    if (move==false) {
      pushMatrix(); //wings
      noStroke();

      translate(235, 285);
      rotate(radians(25));
      ellipse(0, 0, 25, 50);

      popMatrix();

      pushMatrix(); //wings
      noStroke();

      translate(263, 285);
      rotate(radians(340));
      ellipse(0, 0, 25, 50);

      popMatrix();
    } else {
      pushMatrix(); //wings
      noStroke();
      translate(235,285);
      if (count==false) {
        rotate(radians(49));
        ellipse(0, 0, 25, 50);
        count=true;
      } else {
        rotate(radians(21));
        ellipse(0, 0, 25, 50);
        count=false;
      }

      popMatrix();

      pushMatrix(); //wings
      noStroke();
      translate(263, 285);
      if (countTwo==false) {
        rotate(radians(320));
        ellipse(0, 0, 25, 50);
        countTwo=true;
      } else {
        rotate(radians(340));
        ellipse(0, 0, 25, 50);
        countTwo=false;
      }

      popMatrix();
    }
  }
  void display() {
    pushMatrix();
    translate(location.x, location.y);

    fill(0);
    ellipse(250, 265, 20, 50);

    ellipse(250, 280, 25, 34);
    pushMatrix();

    translate(240, 230);
    rotate(radians(70));
    rect(0, 0, 15, .5);
    popMatrix();

    pushMatrix();
    translate(262, 232);
    rotate(radians(110));
    rect(0, 0, 15, .5);
    popMatrix();

    pushMatrix();
    translate(230, 260);
    rotate(radians(40));
    rect(0, 0, 15, .5);
    popMatrix();

    pushMatrix();
    translate(270, 262);
    rotate(radians(140));
    rect(0, 0, 15, .5);
    popMatrix();

    pushMatrix();
    translate(240, 285);
    rotate(radians(120));
    rect(0, 0, 15, .5);
    popMatrix();

    pushMatrix();
    translate(260, 285);
    rotate(radians(50));
    rect(0, 0, 15, .5);
    popMatrix();

    fill(255, 0, 0);

    ellipse(240, 250, 20, 18);
    ellipse(260, 250, 20, 18);
    fill(128, 128, 128, 127);

    flap();

    popMatrix();
  }
  void update() {
    location.add(velocity);
  }
}

tFly fly;

void setup() {
  size(500, 500);
  background(255);
  fly=new tFly();
}

void draw() {
  background(255);
  ellipseMode(CENTER);

  fly.display();
  fly.update();
}


问:
PHP sql statement where clause to multiple array values
How do i use where clause for array if value[3] has multiple data stored           </p>

```<code>$fsql="select * from Error where RptDatime = 201706091000 and partnumber like  ('$value[3]')";
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);

foreach($results as $row)
{
    $mac = $row['Machine'];
    $id = $row['Id'];
    echo 'ID:'.$id.'Machine Number :'.$mac;
}
</code>```

答:
You can use regex function instead of like. Below is the sample code for you.

```<code>$partnumner = [];

    foreach($value[3] as $v)
    {
        $partnumber[] = "*.".$v.".*";
    }

    $fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP  '".implode("|",$partnumber)."'";
</code>```

If you still wish to use like, you can follow the answer here

Body:
How do i use where clause for array if value[3] has multiple data stored

$fsql="select * from Error where RptDatime = 201706091000 and partnumber like  ('$value[3]')";
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);

foreach($results as $row)
{
    $mac = $row['Machine'];
    $id = $row['Id'];
    echo 'ID:'.$id.'Machine Number :'.$mac;
}

Body:
You can use regex function instead of like. Below is the sample code for you.

$partnumner = [];

    foreach($value[3] as $v)
    {
        $partnumber[] = "*.".$v.".*";
    }

    $fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP  '".implode("|",$partnumber)."'";

If you still wish to use like, you can follow the answer here


问:
jquery .css script doesn't work
Morning,
I'm trying to display a div onmouseover. I created a function but i don't know what is wrong. Could you help me please.

The HTML code:

```<code><!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="utf-8">
    <title> PHOTOGALLERY</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <link rel="stylesheet" href="css/smoothness/jquery-ui-
         1.9.2.custom.css"/>
    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script src="http://malsup.github.com/jquery.cycle2.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.9.2.custom.js">
    </script>
    <script>
        function show_img_container() {
            $("#image_container").css("display", "block");
        }
    </script>
</head>
<body>
    <div id="div_container">
        <div id="div_image" class="cycle-slideshow">
            <img src="images/2.jpg" style="height:100%; width:100%">
            <img src="images/3.jpg" style="height:100%; width:100%">
            <img src="images/4.jpg" style="height:100%; width:100%">
            <img src="images/5.jpg" style="height:100%; width:100%">
        </div>
        <div id="image_container" onmouseover="show_img_container()"></div>
    </div>
</body>
</html>
</code>```

In the css file i have a image_container id where the attribute display is set to 'none';

答:
If you only want to show the
 on hover you wouldn't need any JS you could try someting like this:

div {
    display: none;
}

a:hover + div {
    display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><a>Hover over me!</a>
<div>Stuff shown on hover</div></code>```

To explain further:

Since you're using display: none; on the container the mousehover won't take affect since the
 can't be found by the event since it's not displaying in the first place.

Hope this helps!

Title: jquery .css script doesn't work

Body:
Morning,
I'm trying to display a div onmouseover. I created a function but i don't know what is wrong. Could you help me please.

The HTML code:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title> PHOTOGALLERY</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <link rel="stylesheet" href="css/smoothness/jquery-ui-
         1.9.2.custom.css"/>

In the css file i have a image_container id where the attribute display is set to 'none';

Body:
If you only want to show the <div> on hover you wouldn't need any JS you could try someting like this:

div {
    display: none;
}

a:hover + div {
    display: block;
}

<a>Hover over me!</a>
<div>Stuff shown on hover</div>

To explain further:

Since you're using display: none; on the container the mousehover won't take affect since the <div> can't be found by the event since it's not displaying in the first place.

Hope this helps!


问:
Transform a list to a string
What is the pythonic way to perform the below transformation?

[a, b, c] -> "'a', 'b', 'c'"

Where a, b, and c are all variables holding strings.

答:
All other solutions are valid, I think, but here's mine:

```<code>final_string = ""
for item in list:
    if item != list[-1]:
        final_string += "'" + item + "', "
    else:
        final_string += "'" + item
</code>```

Not very concise, but I think it's important to understand the process. This is the kind of thing I would write first when writing a new program, and refine it later. I like to know exactly what's going on, and sometimes single line solutions can cloud that a little. But I'd refactor eventually.

Title: Transform a list to a string

Body:
All other solutions are valid, I think, but here's mine:

final_string = ""
for item in list:
    if item != list[-1]:
        final_string += "'" + item + "', "
    else:
        final_string += "'" + item

Not very concise, but I think it's important to understand the process. This is the kind of thing I would write first when writing a new program, and refine it later. I like to know exactly what's going on, and sometimes single line solutions can cloud that a little. But I'd refactor eventually.


问:
Dart: cannot assigna type with generics to a Type variable
If I try to assign a type with generics to a Type variable I get an error, but if I use a runtimeType variable everything works fine.

```<code>  Type t = List;
  //Type t1 = List<int>;  // ERROR !!!
  Type t2 = new List<int>().runtimeType;
  print('$t $t2');  //> List List<int>
</code>```

Is it a bug or there is something I'm not getting?

答:
Your first line is surprising, but, yes, it works. Class literals have type "Type":

```<code>print((List).runtimeType);
--> TypeImpl

print(List is Type);
--> true
</code>```

The problem with the rest of your snippet is exactly the issue you found on github:

https://github.com/dart-lang/sdk/issues/11923

-- that class literals cannot use generics. You'll have to get an instance and use runtimeType to get the type you want here.

Body:
If I try to assign a type with generics to a Type variable I get an error, but if I use a runtimeType variable everything works fine.

  Type t = List;
  //Type t1 = List<int>;  // ERROR !!!
  Type t2 = new List<int>().runtimeType;
  print('$t $t2');  //> List List<int>

Is it a bug or there is something I'm not getting?

Body:
Your first line is surprising, but, yes, it works. Class literals have type "Type":

print((List).runtimeType);
--> TypeImpl

print(List is Type);
--> true

The problem with the rest of your snippet is exactly the issue you found on github:

https://github.com/dart-lang/sdk/issues/11923

-- that class literals cannot use generics. You'll have to get an instance and use runtimeType to get the type you want here.


问:
Changing global variable using stat.c
I am trying to print logs dynamically. What I have done is I have a debug variable which I set in my own stat_my.c file.  Below is show_stat function.

```<code>extern int local_debug_lk;

static int show_stat(struct seq_file *p, void *v)
{
        int temp=0;
        if(local_debug_lk == 0)
        {
                seq_printf(p,"local_debug_lk=0, enabling,int_num=%d\n",int_num);
                local_debug_lk=1;
        }
        else
        {
        seq_printf(p,"local_debug_lk=:%d,int_num=%d\n",local_debug_lk,int_num);
                while(temp<int_num){
                seq_printf(p,"%d\n",intr_list_seq[temp]);
                temp++;
                }

                local_debug_lk=0;
                int_num=0;

        }

        return 0;
}
</code>```

Driver file

```<code>int local_debug_lk, int_num;

  isr_root(...){
/*
logic to extract IRQ number, saved in vect variable
*/

                     if(local_debug_lk && (int_num < 50000)){
                        intr_list_seq[int_num]=vect;
                         int_num++;
     }
</code>```

What I expect is when I do "cat /proc/show_stat", first it will enable local_debug_lk flag and whenever an interrupt occurs in driver file, it will be stored in intr_list_seq[] array. and when I do "cat /proc/stat_my" second time, it should print IRQ sequence and disable IRQ recording by setting local_debug_lk=0.

But…what's happening is, I am always getting
"local_debug_lk=0, enabling,int_num=0" log on cat; i.e. local_debug_lk is always zero; it never gets enabled.

Also, when my driver is not running, it works fine!
On two consecutive "cat /proc/stat_my", first value is set to 1 and then 0 again.

Is it possible my driver is not picking latest updated value of local_debug_lk variable?

Could you please let me know what I am doing wrong here?

答:
It could be more calls to .show function than readings from the file (with cat /proc/show_stat). Moreover underlying system expects stable results from .show: if called with the same parameters, the function should print the same information to the seq_file.

Because of that, switching a flag in the .show function has a little sence, and making the function's output dependent on this flag is simply wrong.

Generally, changing any kernel state when a file is read is not what expected by the user. It is better to use write functionality for that.

Function .show actually prints information into temporary kernel buffer. If everything goes OK, information from the buffer is transmitted into user buffer and eventually is printed by cat. But if kernel buffer is too small, information printed into it is discarded. In that case underlying system allocates bigger buffer, and call .show again.

Also, .show is rerun if user buffer is too small to accomodate all information printed.

Title: Changing global variable using stat.c

Body:
I am trying to print logs dynamically. What I have done is I have a debug variable which I set in my own stat_my.c file.  Below is show_stat function.

extern int local_debug_lk;

static int show_stat(struct seq_file *p, void *v)
{
        int temp=0;
        if(local_debug_lk == 0)
        {
                seq_printf(p,"local_debug_lk=0, enabling,int_num=%d\n",int_num);
                local_debug_lk=1;
        }
        else
        {
        seq_printf(p,"local_debug_lk=:%d,int_num=%d\n",local_debug_lk,int_num);
                while(temp<int_num){
                seq_printf(p,"%d\n",intr_list_seq[temp]);
                temp++;
                }

                local_debug_lk=0;
                int_num=0;

        }

        return 0;
}

Driver file

int local_debug_lk, int_num;

  isr_root(...){
/*
logic to extract IRQ number, saved in vect variable
*/

                     if(local_debug_lk && (int_num < 50000)){
                        intr_list_seq[int_num]=vect;
                         int_num++;
     }

What I expect is when I do "cat /proc/show_stat", first it will enable local_debug_lk flag and whenever an interrupt occurs in driver file, it will be stored in intr_list_seq[] array. and when I do "cat /proc/stat_my" second time, it should print IRQ sequence and disable IRQ recording by setting local_debug_lk=0.

But…what's happening is, I am always getting
"local_debug_lk=0, enabling,int_num=0" log on cat; i.e. local_debug_lk is always zero; it never gets enabled.

Also, when my driver is not running, it works fine!
On two consecutive "cat /proc/stat_my", first value is set to 1 and then 0 again.

Is it possible my driver is not picking latest updated value of local_debug_lk variable?

Could you please let me know what I am doing wrong here?


问:
SQL Using to_char(null), to_number(null), etc in set operators with Oracle
I'm a student entering the world of SQL for the first time and I cannot find any clear and understandable documentation on how to use to_somedatatype(null) to substitute for missing columns in a UNION, INTERSECT, etc.  I'm using the HR schema that comes build in with Oracle Database for my first few projects and the following query works (I get a list of the employee_id numbers for only those employees with dependents):

```<code>SELECT employee_id "Employees with Dependents"
FROM employees
INTERSECT
SELECT relative_id
FROM dependents;
</code>```

However, as soon as I want to include the names of the employees and dependent birth dates, I'm stuck.  This variation perform an error-free search but yields no results (outputs "no rows selected"):

```<code>SELECT e.employee_id "Employees with Dependents",
  e.first_name,
  e.last_name,
  to_date(NULL) "Dependent Birthdate"
FROM employees e
INTERSECT
SELECT d.relative_id,
  TO_CHAR(NULL),
  TO_CHAR(NULL),
  d.birthdate
FROM dependents d;
</code>```

Several variations replacing to_date with to_number or just plain null and to_char with to_varchar2 or null fail to produce any rows.

What I'd like to produce is a single row for each dependent which displays the guardian's employee number, first name, last name, and the birth date of the dependent.  I'm confident that my problem is the use of these null placeholders, combined with limited understanding of set operators in general. (My understanding is that, when I used a null placeholder like to_date(null), it will not be included in the comparison since there's nothing there to be compared to.)

Can someone please explain to me how to properly use these placeholders?

答:
You must match the data type (using the TO_CHAR function or
any other conversion functions) when columns do not exist in
one or the other table. for example:

SELECT location_id, department_name "Department",
 TO_CHAR(NULL) "Warehouse location"
FROM departments
UNION
SELECT location_id, TO_CHAR(NULL) "Department",
 state_province
FROM locations;

let you relate with your scenario

Body:
I'm a student entering the world of SQL for the first time and I cannot find any clear and understandable documentation on how to use to_somedatatype(null) to substitute for missing columns in a UNION, INTERSECT, etc.  I'm using the HR schema that comes build in with Oracle Database for my first few projects and the following query works (I get a list of the employee_id numbers for only those employees with dependents):

SELECT employee_id "Employees with Dependents"
FROM employees
INTERSECT
SELECT relative_id
FROM dependents;

However, as soon as I want to include the names of the employees and dependent birth dates, I'm stuck.  This variation perform an error-free search but yields no results (outputs "no rows selected"):

SELECT e.employee_id "Employees with Dependents",
  e.first_name,
  e.last_name,
  to_date(NULL) "Dependent Birthdate"
FROM employees e
INTERSECT
SELECT d.relative_id,
  TO_CHAR(NULL),
  TO_CHAR(NULL),
  d.birthdate
FROM dependents d;

Several variations replacing to_date with to_number or just plain null and to_char with to_varchar2 or null fail to produce any rows.

What I'd like to produce is a single row for each dependent which displays the guardian's employee number, first name, last name, and the birth date of the dependent.  I'm confident that my problem is the use of these null placeholders, combined with limited understanding of set operators in general. (My understanding is that, when I used a null placeholder like to_date(null), it will not be included in the comparison since there's nothing there to be compared to.)

Can someone please explain to me how to properly use these placeholders?


问:
Login to Vbulletin forum with python
I'd like to scrape a board which I am currently an active member of. But for this to happen I have to be logged in. I have seen various posts but did not understand the logic behind it. Also did not find a working solution.

This is the  site where I want to login.

I Understand that somehow I have to populate the password and username field and generate a md5hash password on the "flye". But I don 't have any clue how to start this. And do not understand what the login procedure looks like. My question is what do I have to do to figure this out. Which things do I need to take in consideration? How do I start? What are your overall recommondentions?

I am using Python 3.6 and I am a noob who tries to learn python.

My dear regards

答:
Hi i Did Some Googling for your problem i found "Tonakai" who posted His script Login into a vBulletin Board it's a python 2 script u can easly use it on python 2 by making few changes This is the scipt :</p>

```<code>    //
import hashlib
import requests

username = 'yourusername'
password = 'yourpassword'
BASE_URL = 'http://www.example.com'
session = requests.Session()
session.post(BASE_URL + 'login.php?do=login', {
'vb_login_username':        config.username, //vb_login_username is the variable vBulletin uses when you input your Username for logging in
'vb_login_password':        '',//Same for the password
'vb_login_md5password':     hashlib.md5(config.password.encode()).hexdigest(),//vBulletin uses MD5 encode
'vb_login_md5password_utf': hashlib.md5(config.password.encode()).hexdigest(),

'cookieuser': 1, //That allows you to stay logged in as a real nerd
'do': 'login',
's': '',
'securitytoken': 'guest'
})
</code>```

Title: Login to Vbulletin forum with python

Body:
Hi i Did Some Googling for your problem i found "Tonakai" who posted His script Login into a vBulletin Board it's a python 2 script u can easly use it on python 2 by making few changes This is the scipt :

    //
import hashlib
import requests

username = 'yourusername'
password = 'yourpassword'
BASE_URL = 'http://www.example.com'
session = requests.Session()
session.post(BASE_URL + 'login.php?do=login', {
'vb_login_username':        config.username, //vb_login_username is the variable vBulletin uses when you input your Username for logging in
'vb_login_password':        '',//Same for the password
'vb_login_md5password':     hashlib.md5(config.password.encode()).hexdigest(),//vBulletin uses MD5 encode
'vb_login_md5password_utf': hashlib.md5(config.password.encode()).hexdigest(),

'cookieuser': 1, //That allows you to stay logged in as a real nerd
'do': 'login',
's': '',
'securitytoken': 'guest'
})


问:
How could I check if string is only match into an other string
I'm actually a beginner into web developpment.

I have a problem with my actual condition.

Exemple :

```<code>$rooms = 10;
</code>```

In my code, I check if $rooms is equal to 1,0 or 10 so :

```<code>if(strpos($rooms, '1')){echo 1;}
if(strpos($rooms, '0')){echo 0};
if(strpos($rooms, '10')){echo 10;}
</code>```

My result :

```<code>1
0
10
</code>```

My condition match for 1, 0 and 10, where I only need to match the number 10

How can I only pass into my third condition ?

Thx

答:
You can do this with regex, and surrounding the word with \b word boundary

preg_match("~\bMures\b~",$string)

example:

```<code>$rooms = '10';
if ( preg_match("~\b10\b~",$rooms) )
   echo "matched";
else
   echo "no match";
</code>```

Body:
I'm actually a beginner into web developpment.

I have a problem with my actual condition.

Exemple :

$rooms = 10;

In my code, I check if $rooms is equal to 1,0 or 10 so :

if(strpos($rooms, '1')){echo 1;}
if(strpos($rooms, '0')){echo 0};
if(strpos($rooms, '10')){echo 10;}

My result :

1
0
10

My condition match for 1, 0 and 10, where I only need to match the number 10

How can I only pass into my third condition ?

Thx

Body:
You can do this with regex, and surrounding the word with \b word boundary

preg_match("~\bMures\b~",$string)

example:

$rooms = '10';
if ( preg_match("~\b10\b~",$rooms) )
   echo "matched";
else
   echo "no match";


问:
Publish test utils from maven project
I created a library in maven that can be extended by implementing some interfaces. To test the default implementation I have written some hamcrest matchers that currently live in src/test/java.

However, I think they might be useful for users of the library if they want to test their customization.

So how can I make them available? Moving them to src/main would require to make hamcrest a runtime dependency and I don't want that.

答:
There is a way to create a test jar and install it into the repository using the command 'mvn jar:test-jar'.  This jar can then be referenced by other projects using the test-jar modifier in the dependency block.

If you want to have this jar built and installed as part of your your normal 'mvn install' build add the following plugin config to your pom:

From http://maven.apache.org/guides/mini/guide-attached-tests.html

```<code><project>
  <build>
    <plugins>
     <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-jar-plugin</artifactId>
       <version>2.2</version>
       <executions>
         <execution>
           <goals>
             <goal>test-jar</goal>
           </goals>
         </execution>
       </executions>
     </plugin>
    </plugins>
  </build>
</project>
</code>```

Then other projects can reference the test jar as follows:

```<code><dependency>
  <groupId>com.myco.app</groupId>
  <artifactId>foo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <type>test-jar</type>
  <scope>test</scope>
</dependency>
</code>```

Title: Publish test utils from maven project

Body:
There is a way to create a test jar and install it into the repository using the command 'mvn jar:test-jar'.  This jar can then be referenced by other projects using the test-jar modifier in the dependency block.

If you want to have this jar built and installed as part of your your normal 'mvn install' build add the following plugin config to your pom:

From http://maven.apache.org/guides/mini/guide-attached-tests.html

<project>
  <build>
    <plugins>
     <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-jar-plugin</artifactId>
       <version>2.2</version>
       <executions>
         <execution>
           <goals>
             <goal>test-jar</goal>
           </goals>
         </execution>
       </executions>
     </plugin>
    </plugins>
  </build>
</project>

Then other projects can reference the test jar as follows:

<dependency>
  <groupId>com.myco.app</groupId>
  <artifactId>foo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <type>test-jar</type>
  <scope>test</scope>
</dependency>


问:
Insert object in c++ list
I have the follow program in c++. The objective is receive some logs (that came from filedata variable), parse the logs, and save them to object list.

The part to do the parse its working good. But i have a problem when i iterate the parsed vector and try to save some elements to the list. I can get the elements (for example: elements.at(0) i get the first column (timestamp) but when i save to my list, we save two times the log (in this case the filedata only have two logs), but we save two time the SAME log.

My cpp program:

```<code>#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <list>

class UserLogRecord
{
public:
  std::string timestamp;
  std::string id;
  std::string name;
  std::string data;
};

std::vector<std::string> explode(std::string const & s, char delim)
{
  std::vector<std::string> result;
  std::istringstream iss(s); // sequence of characters
  for (std::string token; std::getline(iss, token, delim); )
  {
    result.push_back(std::move(token)); //transfer token to vector
  }
  return result;
}

int main()
{
  const char* filedata =
  "1496843100;2017-06-07 13:45:00;000002D8;2600;user1\n"
  "9999999999;2017-06-07 13:45:00;000002D9;2800;user2";

  std::vector<std::string> lines = explode(filedata,'\n');

  std::list<UserLogRecord* > userLogRecords;
  UserLogRecord* userLogRecord = new UserLogRecord;

  //vector
  for(int i = 0; i < lines.size(); i++)
  {
    std::vector<std::string> elements = explode(lines[i], ';');
    userLogRecord->timestamp = elements.at(0);
    userLogRecord->id = elements.at(2);
    userLogRecord->name = elements.at(4);
    userLogRecord->data = elements.at(3);
    userLogRecords.push_back(userLogRecord);
  }

  //list of logs
  std::list<UserLogRecord* >::const_iterator itLog = userLogRecords.begin();
  while (itLog != userLogRecords.end())
  {
    std::cout << '\n' + (*itLog)->timestamp + '\n';
    std::cout << (*itLog)->id + '\n';
    std::cout << (*itLog)->name + '\n';
    std::cout << (*itLog)->data + '\n';
    ++itLog;
  }

  return 0;
}
</code>```

Output (when iterate the list):

```<code>9999999999
000002D9
user2
2800

9999999999
000002D9
user2
2800
</code>```

Expected output:

```<code>1496843100
000002D8
user1
2600

9999999999
000002D9
user2
2800
</code>```

My program save two logs (this part is 'good', i only have two logs) but its save always the same (curiously it is the last log)

答:
You are only using one UserLogRecord and simply modifying the data instead of adding a new element in the list.

std::list::push_back is adding a copy of a pointer to UserLogRecord which remains the same for all the iterations of the loop. The same pointer is pushed multiple times in the list and therefore all elements have the same data.

The following code would fix the issue. A new UserLogRecord is created for each iteration. You must however remember to free the allocated memory with delete when you don't need it anymore.

```<code>//vector
for(int i = 0; i < lines.size(); i++)
{
    UserLogRecord* userLogRecord = new UserLogRecord;

    std::vector<std::string> elements = explode(lines[i], ';');
    userLogRecord->timestamp = elements.at(0);
    userLogRecord->id = elements.at(2);
    userLogRecord->name = elements.at(4);
    userLogRecord->data = elements.at(3);
    userLogRecords.push_back(userLogRecord);
}
</code>```

Title: Insert object in c++ list

Body:
I have the follow program in c++. The objective is receive some logs (that came from filedata variable), parse the logs, and save them to object list.

The part to do the parse its working good. But i have a problem when i iterate the parsed vector and try to save some elements to the list. I can get the elements (for example: elements.at(0) i get the first column (timestamp) but when i save to my list, we save two times the log (in this case the filedata only have two logs), but we save two time the SAME log.

My cpp program:

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <list>

class UserLogRecord
{
public:
  std::string timestamp;
  std::string id;
  std::string name;
  std::string data;
};

std::vector<std::string> explode(std::string const & s, char delim)
{
  std::vector<std::string> result;
  std::istringstream iss(s); // sequence of characters
  for (std::string token; std::getline(iss, token, delim); )
  {
    result.push_back(std::move(token)); //transfer token to vector
  }
  return result;
}

int main()
{
  const char* filedata =
  "1496843100;2017-06-07 13:45:00;000002D8;2600;user1\n"
  "9999999999;2017-06-07 13:45:00;000002D9;2800;user2";

  std::vector<std::string> lines = explode(filedata,'\n');

  std::list<UserLogRecord* > userLogRecords;
  UserLogRecord* userLogRecord = new UserLogRecord;

  //vector
  for(int i = 0; i < lines.size(); i++)
  {
    std::vector<std::string> elements = explode(lines[i], ';');
    userLogRecord->timestamp = elements.at(0);
    userLogRecord->id = elements.at(2);
    userLogRecord->name = elements.at(4);
    userLogRecord->data = elements.at(3);
    userLogRecords.push_back(userLogRecord);
  }

  //list of logs
  std::list<UserLogRecord* >::const_iterator itLog = userLogRecords.begin();
  while (itLog != userLogRecords.end())
  {
    std::cout << '\n' + (*itLog)->timestamp + '\n';
    std::cout << (*itLog)->id + '\n';
    std::cout << (*itLog)->name + '\n';
    std::cout << (*itLog)->data + '\n';
    ++itLog;
  }

  return 0;
}

Output (when iterate the list):

9999999999
000002D9
user2
2800

9999999999
000002D9
user2
2800

Expected output:

1496843100
000002D8
user1
2600

9999999999
000002D9
user2
2800

My program save two logs (this part is 'good', i only have two logs) but its save always the same (curiously it is the last log)

Body:
You are only using one UserLogRecord and simply modifying the data instead of adding a new element in the list.

std::list::push_back is adding a copy of a pointer to UserLogRecord which remains the same for all the iterations of the loop. The same pointer is pushed multiple times in the list and therefore all elements have the same data.

The following code would fix the issue. A new UserLogRecord is created for each iteration. You must however remember to free the allocated memory with delete when you don't need it anymore.

//vector
for(int i = 0; i < lines.size(); i++)
{
    UserLogRecord* userLogRecord = new UserLogRecord;

    std::vector<std::string> elements = explode(lines[i], ';');
    userLogRecord->timestamp = elements.at(0);
    userLogRecord->id = elements.at(2);
    userLogRecord->name = elements.at(4);
    userLogRecord->data = elements.at(3);
    userLogRecords.push_back(userLogRecord);
}


问:
insert <button> to the end of layer styled text-overflow:ellipsis
I'm trying to add [read more] button to multiple line ellipsis layer.

```<code><p class="description">this is long text.this is long text. <button type="button">expand</button></p>

.description {
  width: 300px;
  text-overflow: ellipsis;
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.description button {
  margin: 0; padding: 0 0 0 10px;
  background-color: transparent; border-width: 0; outline-width: 0;
  font-size: 14px; color: #3f8f7b;
}
</code>```

https://jsfiddle.net/redhork7/symuzrmt/

the result should be like,

```<code>this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text...   [more button]
</code>```

is it possible?

答:
I've just found javascript library for adding more button after ellipsis(...).

http://dotdotdot.frebsite.nl

it supports the option, jQuery.dotdotdot({ 'after': '.classname' }) for add button.

Body:
I'm trying to add [read more] button to multiple line ellipsis layer.

this is long text.this is long text. <button type="button">expand</button>

.description {
  width: 300px;
  text-overflow: ellipsis;
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.description button {
  margin: 0; padding: 0 0 0 10px;
  background-color: transparent; border-width: 0; outline-width: 0;
  font-size: 14px; color: #3f8f7b;
}

https://jsfiddle.net/redhork7/symuzrmt/

the result should be like,

this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text...   [more button]

is it possible?


问:
How to Double a number using service in angular js?
I am writing an application in which i want to double a number using service call in angularjs but its not working...

Below is my code..

```<code><!DOCTYPE html>
<html ng-app="myApp">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
        <body>
            <div ng-controlller="myCrtl">
                <input ng-model='num'>  {{double(num)}}
            </div>
                <script>
                    var app=angular.module('myApp',[]);

                    app.service('abc',function(){
                        this.myFun=function(value){
                            return value * 2
                        }
                    });

                    app.controller('myCrtl',['$scope','abc',function($scope,abc){
                        $scope.double=abc.myFun(num);
                    }])
                </script>
        </body>
</html>
</code>```

答: Use {{2*num}} if you want to double the number. why do you go for complex things.

Body:
I am writing an application in which i want to double a number using service call in angularjs but its not working...

Below is my code..

<!DOCTYPE html>

                <input ng-model='num'>  {{double(num)}}