问:
Updating info on html page using Ajax in Django
I have a problem with Ajax and how can I update info on my HTML page without reloading it.

So, I have a function in my views.py file:

```<code>def index(request):
  some stuff
  context = {
      some stuff
  }
  return render(request, "header.html", context)
</code>```

And I just use variables from {context} in my header.html file. And the question is - how can I perform index function and send new variables to my header.html file without reloading it?

答:
First, create a new endpoint to get the desired data in whichever format. I prefer JSON.

New endpoint:

```<code># views.py

from django.http import JsonResponse
def new_endpoint(request):
    """Returns `JsonResponse` object"""

    # you can change the request method in the following condition.
    # I dont know what you're dealing with.
    if request.is_ajax() and request.method == 'GET':
        # main logic here setting the value of resp_data

        resp_data = {
            'html': 'stuff',
            # more data
        }

        return JsonResponse(resp_data, status=200)
</code>```

Then, you need to code the AJAX part calling this endpoint with the method, data, headers, etc. and finally, define the success callback method to get the desired data.

AJAX:

```<code>var data = {};
$.ajax({
  url: '/your-new-endpoint-url',
  type: 'GET',
  data: data,
  dataType: 'json',
  success: function(resp) {
    $('#changingElement').html(resp.html);
  }
});
</code>```

You can send any type of data from this new endpoint to change whatever element's html text or class name or styles, etc.

Body:
I have a problem with Ajax and how can I update info on my HTML page without reloading it.

So, I have a function in my views.py file:

def index(request):
  some stuff
  context = {
      some stuff
  }
  return render(request, "header.html", context)

And I just use variables from {context} in my header.html file. And the question is - how can I perform index function and send new variables to my header.html file without reloading it?

Body:
First, create a new endpoint to get the desired data in whichever format. I prefer JSON.

New endpoint:

# views.py

from django.http import JsonResponse
def new_endpoint(request):
    """Returns `JsonResponse` object"""

    # you can change the request method in the following condition.
    # I dont know what you're dealing with.
    if request.is_ajax() and request.method == 'GET':
        # main logic here setting the value of resp_data

        resp_data = {
            'html': 'stuff',
            # more data
        }

        return JsonResponse(resp_data, status=200)

Then, you need to code the AJAX part calling this endpoint with the method, data, headers, etc. and finally, define the success callback method to get the desired data.

AJAX:

var data = {};
$.ajax({
  url: '/your-new-endpoint-url',
  type: 'GET',
  data: data,
  dataType: 'json',
  success: function(resp) {
    $('#changingElement').html(resp.html);
  }
});

You can send any type of data from this new endpoint to change whatever element's html text or class name or styles, etc.


来源: stackexchange

问:
How to remove jar file from classpath during runtime?
I have a Apache Commons library (commons-io.jar) added to my project classpath and I want to remove this library classes from my classpath during runtime and then I want to add after some work.

Is there any way to remove all classes from classpath during runtime and add these classes after some operation?

```<code>public static void main(String [] args){

    //Some apache commons operations

    //Remove apache commons classes from classpath

    doSomeWork();

    //Add apache commons classes to classpath

}
</code>```

答:
You could use the maven-enforcer-plugin in your pom to force specific versions of the transitive dependencies.
Conflicting library version in a java maven project</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a Apache Commons library (commons-io.jar) added to my project classpath and I want to remove this library classes from my classpath during runtime and then I want to add after some work.

Is there any way to remove all classes from classpath during runtime and add these classes after some operation?

public static void main(String [] args){

    //Some apache commons operations

    //Remove apache commons classes from classpath

    doSomeWork();

    //Add apache commons classes to classpath

}


问:
How to get Distinct rows in Laravel
I have 6 Records in following Table

I Need to get Unique Leads id Columns Order by id DESC.

Following is my Query

```<code>Telecallerfirststep::WhereDate('created_at',date('Y-m-d'))->groupBy('leadsid')->OrderBy('id','DESC')->count();
</code>```

Its Return Number of Records is : 1

答:
Use php count after fetching result

```<code>$reault = Telecallerfirststep::whereDate('created_at',date('Y-m-d'))->groupBy('leadsid')->OrderBy('id','DESC');
echo $count = count($reault);
</code>```

I found similar issue MySql and SO

Title: How to get Distinct rows in Laravel

Body:
I have 6 Records in following Table

I Need to get Unique Leads id Columns Order by id DESC.

Following is my Query

Telecallerfirststep::WhereDate('created_at',date('Y-m-d'))->groupBy('leadsid')->OrderBy('id','DESC')->count();

Its Return Number of Records is : 1

Body:
Use php count after fetching result

$reault = Telecallerfirststep::whereDate('created_at',date('Y-m-d'))->groupBy('leadsid')->OrderBy('id','DESC');
echo $count = count($reault);

I found similar issue MySql and SO


问:
Oracle Add 1 hour in SQL
I am just trying to add 1 hour to a value, it is kind of complicated on where and why i am doing this but basically i just need to query something like this </p>

```<code>select DATE_ADD(hh,1,'2014-10-15 03:30:00 pm') from dual
</code>```

<p>I keep reading old articles that say to use dateAdd or date_add but I keep getting invalid identifier errors. </p>

答:
The calculation is simple

if you want to add 1 hour in the date .

every day have 24 hour , you can add .

```<code>select sysdate + 1/24 from dual;
</code>```

if you want 1 day to add

```<code>select sysdate + 24/24 from dual;

or

select sysdate + 1 from dual;

same as for 2, 3 , 4 day
</code>```

For static date you have the answer below.

Title: Oracle Add 1 hour in SQL

Body:
I am just trying to add 1 hour to a value, it is kind of complicated on where and why i am doing this but basically i just need to query something like this

select DATE_ADD(hh,1,'2014-10-15 03:30:00 pm') from dual

I keep reading old articles that say to use dateAdd or date_add but I keep getting invalid identifier errors.

Body:
The calculation is simple

if you want to add 1 hour in the date .

every day have 24 hour , you can add .

select sysdate + 1/24 from dual;

if you want 1 day to add

select sysdate + 24/24 from dual;

or

select sysdate + 1 from dual;

same as for 2, 3 , 4 day

For static date you have the answer below.


问:
ModuleNotFound Error in python script but only when imported into a parent script
On a windows machine with Anaconda installed. Script B runs correctly and produces the correct result. Script B is called from a Windows console app.

When script A imports script B, script B fails with the error "ModuleNotFoundError: No module named 'numpy'".

When script B is passed directly to Python executable, script B works and executes without error. (I'm new to python) Any help pointing me in the right direction would be appreciated.

Thanks

答: basteflp, thanks for your response. I managed to solve it. The module not found error was due to running the script outside of the a specific Anaconda environment. Running the script after loading the Anaconda environment resolved the error.</p>


问:
php - how select data from database and set to single row if duplicate
what I want to is when I select from database set the duplicate value into one row.

On my result, on genre column the data is not in one row.

So on the genre column, how to set the genre data into one row?

Example the result in one row :Drama, Western, Romance

Table (movie_genre):

Table (genre):

Result:

PHP/HTML code:

```<code><?php
 $categorySql = "SELECT DISTINCT movie.id,movie.name,genre.type,movie.price,movie.language,movie.subtitle,movie.director,movie.cast,movie.runningtime FROM movie INNER JOIN movie_genre ON movie.id = movie_genre.movie_id INNER JOIN genre ON genre.id = movie_genre.genre_id";

 if ($categoryStmt = $conn->prepare($categorySql)) {
/* execute query */
$categoryStmt->execute();

 $categoryStmt->bind_result($id, $name, $genre, $price, $language, $subtitle,
$director, $cast, $time);

$rows = array();

while ($categoryStmt->fetch()) {
    $row = array(
        'id' => $id,
        'name' => $name,
        'genre' => $genre,
        'price' => "RM " . $price,
        'language' => $language,
        'subtitle' => $subtitle,
        'director' => $director,
        'cast' => $cast,
        'runningtime' => $time . " mins"

    );
    $rows[] = $row;
}
}
$categoryStmt->close();
?>

<div class="movielisttable">
<table id="movielist_table">
    <tr id="">
        <th>ID:</th>
        <th>Movie Name</th>
        <th>Genre</th>
        <th>Price</th>
        <th>Language</th>
        <th>Subtitle</th>
        <th>Director</th>
        <th>Cast</th>
        <th>Running Time</th>
    </tr>
    <tbody>
    <?php
    foreach ($rows as &$value) {
        echo
        "<tr>
          <td>{$value['id'] }</td>
          <td>{$value['name']}</td>
          <td>{$value['genre']}</td>
          <td>{$value['price']}</td>
          <td>{$value['language']}</td>
          <td>{$value['subtitle']}</td>
          <td>{$value['director']}</td>
          <td>{$value['cast']}</td>
          <td>{$value['runningtime']}</td>

        </tr>\n";
    }
    ?>
</code>```

答:
Could be you are looking for group_concat  and group by</p>

```<code>  $categorySql = "SELECT
        movie.id
        ,movie.name
        , group_concat(genre.type) as type
        ,movie.price
        ,movie.language
        ,movie.subtitle
        ,movie.director
        ,movie.cast
        ,movie.runningtime
  FROM movie
  INNER JOIN movie_genre ON movie.id = movie_genre.movie_id
  INNER JOIN genre ON genre.id = movie_genre.genre_id
  GROUP BY  movie.id ";
</code>```

Body:
what I want to is when I select from database set the duplicate value into one row.

On my result, on genre column the data is not in one row.

So on the genre column, how to set the genre data into one row?

Example the result in one row :Drama, Western, Romance

Table (movie_genre):

Table (genre):

Result:

PHP/HTML code:

<?php
 $categorySql = "SELECT DISTINCT movie.id,movie.name,genre.type,movie.price,movie.language,movie.subtitle,movie.director,movie.cast,movie.runningtime FROM movie INNER JOIN movie_genre ON movie.id = movie_genre.movie_id INNER JOIN genre ON genre.id = movie_genre.genre_id";

 if ($categoryStmt = $conn->prepare($categorySql)) {
/* execute query */
$categoryStmt->execute();

 $categoryStmt->bind_result($id, $name, $genre, $price, $language, $subtitle,
$director, $cast, $time);

$rows = array();

while ($categoryStmt->fetch()) {
    $row = array(
        'id' => $id,
        'name' => $name,
        'genre' => $genre,
        'price' => "RM " . $price,
        'language' => $language,
        'subtitle' => $subtitle,
        'director' => $director,
        'cast' => $cast,
        'runningtime' => $time . " mins"

    );
    $rows[] = $row;
}
}
$categoryStmt->close();
?>

        ID:
        Movie Name
        Genre
        Price
        Language
        Subtitle
        Director
        Cast
        Running Time

    <?php
    foreach ($rows as &$value) {
        echo
        "

          {$value['id'] }
          {$value['name']}
          {$value['genre']}
          {$value['price']}
          {$value['language']}
          {$value['subtitle']}
          {$value['director']}
          {$value['cast']}
          {$value['runningtime']}

\n";
    }
    ?>

Body:
Could be you are looking for group_concat  and group by

  $categorySql = "SELECT
        movie.id
        ,movie.name
        , group_concat(genre.type) as type
        ,movie.price
        ,movie.language
        ,movie.subtitle
        ,movie.director
        ,movie.cast
        ,movie.runningtime
  FROM movie
  INNER JOIN movie_genre ON movie.id = movie_genre.movie_id
  INNER JOIN genre ON genre.id = movie_genre.genre_id
  GROUP BY  movie.id ";


问:
How can I able to display content in inventory seperated by commas in vue js?
My json data is

```<code>{ "status": true,
  "data": {
    "pid": 9,
    "Name": "Asok",
    "services": "3, 1, 2, 4, 5, 6",
    "inventory": ["specs", " Testing", "Lens", "Doctors", "Surgeon", "Medicines"]
  }
}
</code>```

Now I am using html as

```<code><div v-for="inv in data.inventory">{{inv}}</div>
</code>```

When I do this way, the data is printing downwards.. I need to display data seperated by commmas in a row??

答:
You can do that by using span instead of div like

```<code><span v-for="inv in data.inventory">{{inv}}, </span>
</code>```

Unfortunately, you will end up with a trailing comma :-/

Maybe this is one of those cases where you should do some JS-preprocessing and keep the template simple, like:

```<code><div>{{data.inventory.join(', ')}}</div>
</code>```

This will solve the trailing comma problem without much effort.

Body:
My json data is

{ "status": true,
  "data": {
    "pid": 9,
    "Name": "Asok",
    "services": "3, 1, 2, 4, 5, 6",
    "inventory": ["specs", " Testing", "Lens", "Doctors", "Surgeon", "Medicines"]
  }
}

Now I am using html as

{{inv}}

When I do this way, the data is printing downwards.. I need to display data seperated by commmas in a row??

Body:
You can do that by using span instead of div like

<span v-for="inv in data.inventory">{{inv}}, </span>

Unfortunately, you will end up with a trailing comma :-/

Maybe this is one of those cases where you should do some JS-preprocessing and keep the template simple, like:

<div>{{data.inventory.join(', ')}}</div>

This will solve the trailing comma problem without much effort.


问:
How does exponent work in complex data structure in python?
I was exploring complex data structure in python. I have done addition, subtraction, multiplication and division between two complex value in python IDLE. All of them makes sense but when I tried to exponent a complex value something strange came up. I have no idea how that happened! Can anyone explain to me what's going under the hood?

I was trying to understand the following code:

```<code>>>> w = complex(2, -3)
>>> v = complex(5)
>>> w ** v
(122+597j)
</code>```

So, I was wondering how w ** v evaluates to (122+597j). Thanks in advance.

答:
The answer you got is mathematically correct: https://www.wolframalpha.com/input/?i=(2-3i)%5E5

If you know how to multiply complex numbers, it is the same as w*w*w*w*w.

If you don't, here you go: http://mathworld.wolfram.com/ComplexMultiplication.html

Body:
I was exploring complex data structure in python. I have done addition, subtraction, multiplication and division between two complex value in python IDLE. All of them makes sense but when I tried to exponent a complex value something strange came up. I have no idea how that happened! Can anyone explain to me what's going under the hood?

I was trying to understand the following code:

>>> w = complex(2, -3)
>>> v = complex(5)
>>> w ** v
(122+597j)

So, I was wondering how w ** v evaluates to (122+597j). Thanks in advance.


问:
Stop Hibernate from updating collections when they have not changed
I have two entity beans defined as follows (unrelated stuff removed):

```<code>@Entity
@Table(...)
public class MasterItem implements java.io.Serializable {

  private Set<CriticalItems> criticalItemses = new HashSet<CriticalItems>(0);

  @OneToMany(fetch = FetchType.EAGER, mappedBy = "masterItem", orphanRemoval = true,
            cascade = {javax.persistence.CascadeType.DETACH})
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
    public Set<CriticalItems> getCriticalItemses() {
        return this.criticalItemses;
    }
}
</code>```

CriticalItems is defined as follows:

```<code>@Entity
@Table(...)
public class CriticalItems implements java.io.Serializable {

    private MasterItem masterItem;

    @ManyToOne(fetch = FetchType.LAZY, optional = false,
            cascade = {javax.persistence.CascadeType.DETACH})
    @Cascade({CascadeType.SAVE_UPDATE})
    @JoinColumn(name = "mi_item_id", nullable = false)
    public MasterItem getMasterItem() {
        return this.masterItem;
    }
}
</code>```

And in my DAO code - I have these methods:

```<code>public MasterItem load(int id) {
    MasterItem results = (MasterItem) getSessionFactory().getCurrentSession()
        .get("com.xxx.MasterItem", id);

}

public void save(MasterItem master) {
    // master has been changed by the UI since it
    getSessionFactory().getCurrentSession().saveOrUpdate(master);
}
</code>```

When I load a MasterItem, it loads correctly, and also loads the CriticalItems Set with data, as directed.  Then, I send this data to my UI, and get an updated copy back, which I then try to persist.   The user updates fields in the MasterItem object, but does not touch the CriticalItems Set or anything in it - it remains unmodified.

When my save() method is invoked, Hibernate is insisting on sending SQL updates for each item in the Set of CriticalItems, even though none of them have changed in any way.

After some digging, here's what I think is happening.  When I do a saveOrUpdate(), Hibernate sees my MasterItem object is in a detached state, so it tries to reload it from disk.  However, when doing so, it appears to be using a prepared statement (which was auto-created by Hibernate at start-up) and this prepared statement does not attempt to join to the CriticalItems data.

So Hibernate has my updated MasterItem object with a full Set of CriticalItems, but uses a MasterItem without collections as its "previousState" object.  Thus, all CriticalItems get updated via SQL (not inserted, which is interesting in itself).

Did I do something in my annotations that caused this behavior?  I know I can use an Interceptor to find out of the item has really changed, or changed the dirty flag to override Hibernate's default algorithm - but this seems to be something that Hibernate should just handle on its own without my intervention.

Any insight would be appreciated.

UPDATE:
Based on comments, I think I understand the difference between saveOrUpdate() and merge().  I realize that saveOrUpdate() will result in either an SQL INSERT or an SQL UPDATE in all cases, and that merge, in theory, will only issue updates if the object has changed from it's persistent state, but in order to determine that, Hibernate has to reload the object first via SQL SELECT.

So, I thought I could just go back into my code and change saveOrUpdate() to merge() and it would work, but that wasn't quite the case.

When I used merge(), I was getting

```<code>org.springframework.orm.hibernate3.HibernateSystemException: could not initialize proxy - no Session; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session
</code>```

but it worked fine if I changed back to saveOrUpdate().

I finally found out why - I didn't include CascadeType.MERGE in my @Cascade annotation (ugh).  Once I fixed that, the exception went away.

答:
try to add a revision column (optimistic locking) to your entities</p>

```<code>@Version
Date lastModified;
</code>```

Body:
I have two entity beans defined as follows (unrelated stuff removed):

@Entity
@Table(...)
public class MasterItem implements java.io.Serializable {

  private Set<CriticalItems> criticalItemses = new HashSet<CriticalItems>(0);

  @OneToMany(fetch = FetchType.EAGER, mappedBy = "masterItem", orphanRemoval = true,
            cascade = {javax.persistence.CascadeType.DETACH})
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
    public Set<CriticalItems> getCriticalItemses() {
        return this.criticalItemses;
    }
}

CriticalItems is defined as follows:

@Entity
@Table(...)
public class CriticalItems implements java.io.Serializable {

    private MasterItem masterItem;

    @ManyToOne(fetch = FetchType.LAZY, optional = false,
            cascade = {javax.persistence.CascadeType.DETACH})
    @Cascade({CascadeType.SAVE_UPDATE})
    @JoinColumn(name = "mi_item_id", nullable = false)
    public MasterItem getMasterItem() {
        return this.masterItem;
    }
}

And in my DAO code - I have these methods:

public MasterItem load(int id) {
    MasterItem results = (MasterItem) getSessionFactory().getCurrentSession()
        .get("com.xxx.MasterItem", id);

}

public void save(MasterItem master) {
    // master has been changed by the UI since it
    getSessionFactory().getCurrentSession().saveOrUpdate(master);
}

When I load a MasterItem, it loads correctly, and also loads the CriticalItems Set with data, as directed.  Then, I send this data to my UI, and get an updated copy back, which I then try to persist.   The user updates fields in the MasterItem object, but does not touch the CriticalItems Set or anything in it - it remains unmodified.

When my save() method is invoked, Hibernate is insisting on sending SQL updates for each item in the Set of CriticalItems, even though none of them have changed in any way.

After some digging, here's what I think is happening.  When I do a saveOrUpdate(), Hibernate sees my MasterItem object is in a detached state, so it tries to reload it from disk.  However, when doing so, it appears to be using a prepared statement (which was auto-created by Hibernate at start-up) and this prepared statement does not attempt to join to the CriticalItems data.

So Hibernate has my updated MasterItem object with a full Set of CriticalItems, but uses a MasterItem without collections as its "previousState" object.  Thus, all CriticalItems get updated via SQL (not inserted, which is interesting in itself).

Did I do something in my annotations that caused this behavior?  I know I can use an Interceptor to find out of the item has really changed, or changed the dirty flag to override Hibernate's default algorithm - but this seems to be something that Hibernate should just handle on its own without my intervention.

Any insight would be appreciated.

UPDATE:
Based on comments, I think I understand the difference between saveOrUpdate() and merge().  I realize that saveOrUpdate() will result in either an SQL INSERT or an SQL UPDATE in all cases, and that merge, in theory, will only issue updates if the object has changed from it's persistent state, but in order to determine that, Hibernate has to reload the object first via SQL SELECT.

So, I thought I could just go back into my code and change saveOrUpdate() to merge() and it would work, but that wasn't quite the case.

When I used merge(), I was getting

org.springframework.orm.hibernate3.HibernateSystemException: could not initialize proxy - no Session; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session

but it worked fine if I changed back to saveOrUpdate().

I finally found out why - I didn't include CascadeType.MERGE in my @Cascade annotation (ugh).  Once I fixed that, the exception went away.

Body:
try to add a revision column (optimistic locking) to your entities

@Version
Date lastModified;

ContentLicense: CC BY-SA 2.5


问:
How to remove index custom element in 2 dimensional array with empty value Javascript
Supposed I have 2 dimensional array in javascript and I want remove the empty element something like this [] in array, for example:

```<code>// like this
var newArray = [["test1", "test2"], ["test3", "test4"], []];

// or like this
var newArray= [["test1", "test2"], [], ["test3", "test4"]];
</code>```

and my code so far

```<code>var newArray= [["test1", "test2"], ["test3", "test4"], []];
for(var loop = 0; loop < newArray.length; loop++){
        if (newArray[loop] === null){
            // remove this empty element
            newArray[loop].slice();
        }
    }
console.log(newArray);
</code>```

And my output so far

```<code>[ [ 'test1', 'test2' ], [ 'test3', 'test4' ], [] ]
</code>```

How to remove that empty element? and when I print to the console the result that I want must:

```<code>[ [ 'test1', 'test2' ], [ 'test3', 'test4' ] ]
</code>```

Please help and thank you

答:
You can also use more basic splice method to delete the element of an array without leaving null or empty values.

You can use this code as:

```<code>var newArray = [["test1", "test2"], ["test3", "test4"], []];

for(var loop = 0; loop < newArray.length; loop++){
    var tempArray = newArray[loop];

    // safely check if empty value is actually an array or not, if array then only use length property so it doesn't get undefined
    if (Array.isArray(tempArray) && (tempArray.length == 0)) {
        newArray.splice(loop, 1);
        --loop;   // decrease the loop value by 1 because original array has its length decreased by 1
    }
}

console.log(newArray);

// [["test1","test2"],["test3","test4"]]
</code>```

Body:
Supposed I have 2 dimensional array in javascript and I want remove the empty element something like this [] in array, for example:

// like this
var newArray = [["test1", "test2"], ["test3", "test4"], []];

// or like this
var newArray= [["test1", "test2"], [], ["test3", "test4"]];

and my code so far

var newArray= [["test1", "test2"], ["test3", "test4"], []];
for(var loop = 0; loop < newArray.length; loop++){
        if (newArray[loop] === null){
            // remove this empty element
            newArray[loop].slice();
        }
    }
console.log(newArray);

And my output so far

[ [ 'test1', 'test2' ], [ 'test3', 'test4' ], [] ]

How to remove that empty element? and when I print to the console the result that I want must:

[ [ 'test1', 'test2' ], [ 'test3', 'test4' ] ]

Please help and thank you

Body:
You can also use more basic splice method to delete the element of an array without leaving null or empty values.

You can use this code as:

var newArray = [["test1", "test2"], ["test3", "test4"], []];

for(var loop = 0; loop < newArray.length; loop++){
    var tempArray = newArray[loop];

    // safely check if empty value is actually an array or not, if array then only use length property so it doesn't get undefined
    if (Array.isArray(tempArray) && (tempArray.length == 0)) {
        newArray.splice(loop, 1);
        --loop;   // decrease the loop value by 1 because original array has its length decreased by 1
    }
}

console.log(newArray);

// [["test1","test2"],["test3","test4"]]


问:
Postgres continuous cumulative count
assuming table a with data

```<code>| id | timestamp   |
|----|-------------|
| 1  | 12345677677 |
| 2  | 12345677677 |
| 3  | 12346600000 |
</code>```

I nee a query which returns the cumulative count at a given point in time

```<code>| timestamp   | count|
|-------------|------|
| 12345677677 | 2    |
| 12346600000 | 3    |
</code>```

so not the count() group by timestamp, but the count() group by timestamp + previous counts.

Thanks to @klin this works perfectly; However with the window function, I have a problem getting the distinct count(*) per day together with the cumulative sum in ONE query.

```<code>SELECT date_trunc('day', date_created) AS date,
       sum,
       count(*)
FROM   addon_user,
       (SELECT DISTINCT ON(date_trunc('day', date_created))
       date_trunc('day', date_created),
       count(*)
       OVER (
         ORDER BY date_trunc('day', date_created)) AS sum
        FROM   addon_user
) AS sub

GROUP  BY date,
          sum
ORDER  BY date ASC
</code>```

returns the Cartesian product:

```<code>timestamp  | count |sum
-------------+-------+---
12345677677 |     2|2
12345677677 |     2|5
12346600000 |     3|2
12346600000 |     3|5
</code>```

while I need the data in form of

```<code>timestamp  | count |sum
-------------+-------+---
12345677677 |     2|2
12346600000 |     3|5
</code>```

答:
Use count() as a window function with the order by clause. There is a nice feature in Postgres, distinct on to eliminate duplicate rows:

```<code>select distinct on(timestamp) timestamp, count(*) over (order by timestamp)
from my_table;

  timestamp  | count
-------------+-------
 12345677677 |     2
 12346600000 |     3
(2 rows)
</code>```

Title: Postgres continuous cumulative count

Body:
assuming table a with data

| id | timestamp   |
|----|-------------|
| 1  | 12345677677 |
| 2  | 12345677677 |
| 3  | 12346600000 |

I nee a query which returns the cumulative count at a given point in time

| timestamp   | count|
|-------------|------|
| 12345677677 | 2    |
| 12346600000 | 3    |

so not the count() group by timestamp, but the count() group by timestamp + previous counts.

Thanks to @klin this works perfectly; However with the window function, I have a problem getting the distinct count(*) per day together with the cumulative sum in ONE query.

SELECT date_trunc('day', date_created) AS date,
       sum,
       count(*)
FROM   addon_user,
       (SELECT DISTINCT ON(date_trunc('day', date_created))
       date_trunc('day', date_created),
       count(*)
       OVER (
         ORDER BY date_trunc('day', date_created)) AS sum
        FROM   addon_user
) AS sub

GROUP  BY date,
          sum
ORDER  BY date ASC

returns the Cartesian product:

timestamp  | count |sum
-------------+-------+---
12345677677 |     2|2
12345677677 |     2|5
12346600000 |     3|2
12346600000 |     3|5

while I need the data in form of

timestamp  | count |sum
-------------+-------+---
12345677677 |     2|2
12346600000 |     3|5

Body:
Use count() as a window function with the order by clause. There is a nice feature in Postgres, distinct on to eliminate duplicate rows:

select distinct on(timestamp) timestamp, count(*) over (order by timestamp)
from my_table;

  timestamp  | count
-------------+-------
 12345677677 |     2
 12346600000 |     3
(2 rows)


问:
Import complex data type(Array) from csv to snappydata
From my previous question I came to know the way one can insert array.

Now I want to insert a latge amount of data into the table. From this reference of snappydata i was able to import a large amount into the tables. But when i tried to import complex data type like Array it isn't supporting.

```<code>CSV sample:
'name',1,[1,2,4]
or
'name',1,array(1,2,4)
</code>```

Can anyone tell me how can I insert array into table from CSV file?

答: I solved the above question by converting the CSV to JSON. I followed the documentation for json to snappydata. </p>

Body:
From my previous question I came to know the way one can insert array.

Now I want to insert a latge amount of data into the table. From this reference of snappydata i was able to import a large amount into the tables. But when i tried to import complex data type like Array it isn't supporting.

CSV sample:
'name',1,[1,2,4]
or
'name',1,array(1,2,4)

Can anyone tell me how can I insert array into table from CSV file?


问:
Mapping and removing duplicates in Spark Scala?
I have a data set test.txt. It contain data like below

1::1::3
1::1::2
1::2::2
2::1::5
2::1::4
2::2::2
3::1::1
3::2::2
```

<p>I have created data-frame using the below code. </p>

<pre class="lang-scala prettyprint-override"><code>case class Rating(userId: Int, movieId: Int, rating: Float)
def parseRating(str: String): Rating = {
val fields = str.split("::")
assert(fields.size == 3)
Rating(fields(0).toInt, fields(1).toInt, fields(2).toFloat)
}

val ratings = spark.read.textFile("C:/Users/cravi/Desktop/test.txt").map(parseRating).toDF()
</code>```

But when I am trying to print the output I am getting below output

[1,1,3.0]
[1,1,2.0]
[1,2,2.0]
[2,1,2.0]
[2,1,4.0]
[2,2,2.0]
[3,1,1.0]
[3,2,2.0]
```

<p>But I want to print output like below I.e. removing duplicate combinations and instead of <code>field(2) value 1.0</code>.</p>

<pre class="lang-none prettyprint-override"><code>[1,1,1.0]
[1,2,1.0]
[2,1,1.0]
[2,2,1.0]
[3,1,1.0]
[3,2,1.0]
</code>```

答:
Once you have created a dataframe removing duplicates can be done by call .dropDuplicates(columnNames) and populating the third column with 1.0 can be done by using lit and withColumn functions.

To sum up, simple solution can be done as following

```<code>val ratings = sc.textFile("C:/Users/cravi/Desktop/test.txt")
    .map(line => line.split("::"))
    .filter(fields => fields.length == 3)
    .map(fields => Rating(fields(0).toInt, fields(1).toInt, 1.0f))
  .toDF().dropDuplicates("userId", "movieId")

ratings.show(false)
</code>```

which should give you

```<code>+------+-------+------+
|userId|movieId|rating|
+------+-------+------+
|3     |1      |1.0   |
|2     |2      |1.0   |
|1     |2      |1.0   |
|1     |1      |1.0   |
|2     |1      |1.0   |
|3     |2      |1.0   |
+------+-------+------+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a data set test.txt. It contain data like below

1::1::3
1::1::2
1::2::2
2::1::5
2::1::4
2::2::2
3::1::1
3::2::2

I have created data-frame using the below code.

case class Rating(userId: Int, movieId: Int, rating: Float)
def parseRating(str: String): Rating = {
val fields = str.split("::")
assert(fields.size == 3)
Rating(fields(0).toInt, fields(1).toInt, fields(2).toFloat)
}

val ratings = spark.read.textFile("C:/Users/cravi/Desktop/test.txt").map(parseRating).toDF()

But when I am trying to print the output I am getting below output

[1,1,3.0]
[1,1,2.0]
[1,2,2.0]
[2,1,2.0]
[2,1,4.0]
[2,2,2.0]
[3,1,1.0]
[3,2,2.0]

But I want to print output like below I.e. removing duplicate combinations and instead of field(2) value 1.0.

[1,1,1.0]
[1,2,1.0]
[2,1,1.0]
[2,2,1.0]
[3,1,1.0]
[3,2,1.0]

Body:
Once you have created a dataframe removing duplicates can be done by call .dropDuplicates(columnNames) and populating the third column with 1.0 can be done by using lit and withColumn functions.

To sum up, simple solution can be done as following

val ratings = sc.textFile("C:/Users/cravi/Desktop/test.txt")
    .map(line => line.split("::"))
    .filter(fields => fields.length == 3)
    .map(fields => Rating(fields(0).toInt, fields(1).toInt, 1.0f))
  .toDF().dropDuplicates("userId", "movieId")

ratings.show(false)

which should give you

+------+-------+------+
|userId|movieId|rating|
+------+-------+------+
|3     |1      |1.0   |
|2     |2      |1.0   |
|1     |2      |1.0   |
|1     |1      |1.0   |
|2     |1      |1.0   |
|3     |2      |1.0   |
+------+-------+------+


问:
Sinon usefaketimer an the spy called count miss
this is my code. I want to test the "doing" method and verify the this.obj.send called count with time interval.

My problem is when I stub the method of _fetchAllDatas and resolve. the this.obj.send could not called. and when the this.obj.send move to _fetchAllDatas outside. it can be called.

How can I deal with this problem ?? thanks ~

```<code>var sinon = require('sinon');

class A {
    constructor(obj){
        this.obj = obj;
        this.timer;
    }

    doing(){
        this.timer = setInterval(()=>{
            this._fetchAllDatas().then((data)=>{
                console.log('!!!',data);
                this.obj.send(data);
            });
        },1000)
    }

    stop(){
        clearInterval(this.timer);
    }

    _fetchAllDatas(){
        return Promise.resolve([]);
    }
}

var sandbox = sinon.sandbox.create();
var spy = { send: sandbox.spy()};
var a = new A(spy);
var stub = sandbox.stub(a,'_fetchAllDatas').resolves(['mark']);
var clock = sandbox.useFakeTimers();

a.doing();;
clock.tick(5000);
 sinon.assert.callCount(spy.send, 5); // error the count is zero. it should be 5 times
</code>```

答:
First, the result of "call count = 5 times within 5 seconds" will not happen as expected.
It's simply because the callback of the setInterval will be trigger after N(ms) of delay time;
That is, it will only happen four times within 5s duration, like the graph below:

```<code>x = not triggered
o = triggered

1s--1s--1s--1s--1s
x   o   o   o   o
^start          ^end
</code>```

Second, you will not get the right result from an async call right after a sync call.
When you calling a.doing();, it initiates a synchronize version of setInterval (Because of useFakeTimers)
that will calls a function this._fetchAllDatas()
that returns a Promise which runs an asynchronize callback,
which means this.obj.send(data) will be executed asynchronously.

Even if you use clock.tick(5000), it's still an asynchronize call.

That is, you should put your assertion at the right time after the Promise is truly resolved.

Body:
this is my code. I want to test the "doing" method and verify the this.obj.send called count with time interval.

My problem is when I stub the method of _fetchAllDatas and resolve. the this.obj.send could not called. and when the this.obj.send move to _fetchAllDatas outside. it can be called.

How can I deal with this problem ?? thanks ~

var sinon = require('sinon');

class A {
    constructor(obj){
        this.obj = obj;
        this.timer;
    }

    doing(){
        this.timer = setInterval(()=>{
            this._fetchAllDatas().then((data)=>{
                console.log('!!!',data);
                this.obj.send(data);
            });
        },1000)
    }

    stop(){
        clearInterval(this.timer);
    }

    _fetchAllDatas(){
        return Promise.resolve([]);
    }
}

var sandbox = sinon.sandbox.create();
var spy = { send: sandbox.spy()};
var a = new A(spy);
var stub = sandbox.stub(a,'_fetchAllDatas').resolves(['mark']);
var clock = sandbox.useFakeTimers();

a.doing();;
clock.tick(5000);
 sinon.assert.callCount(spy.send, 5); // error the count is zero. it should be 5 times

Body:
First, the result of "call count = 5 times within 5 seconds" will not happen as expected.
It's simply because the callback of the setInterval will be trigger after N(ms) of delay time;
That is, it will only happen four times within 5s duration, like the graph below:

x = not triggered
o = triggered

1s--1s--1s--1s--1s
x   o   o   o   o
^start          ^end

Second, you will not get the right result from an async call right after a sync call.
When you calling a.doing();, it initiates a synchronize version of setInterval (Because of useFakeTimers)
that will calls a function this._fetchAllDatas()
that returns a Promise which runs an asynchronize callback,
which means this.obj.send(data) will be executed asynchronously.

Even if you use clock.tick(5000), it's still an asynchronize call.

That is, you should put your assertion at the right time after the Promise is truly resolved.


问:
Array highest value or create next value?
I have an array of names and id's.

```<code>Array(
    0=>array(
        name=>New York,
        id=>45763448349,
        can=0
    ),
    1=>array(
        name=>New York2,
        id=>45763464566,
        can=0
    ),
    3=>array(
        name=>New York3,
        id=>45763464854,
        can=0
    ),
    4=>array(
        name=>New York4,
        id=>45763464955,
        can=0
    ),
    5=>array(
        name=>New York5,
        id=>45763464745,
        can=0
    ),
    6=>array(
        name=>New York6,
        id=>45763464235,
        can=1
    )
)
</code>```

For example (there will be different names (not all New York)) and I have an x variable with a name (for example x=New York) what I need to do is find the highest name and get the id and then make sure can is 1 otherwise specific the next highest name.

For example let's assume that I have x=New York so I look through the array and find that the highest array name is New York6. I see that can=1 so I just get the id. Now if can != 1 then I could specific New York7.

NOTE: This array will contain many different values (not all New York, I just used those for an example)

Now how on earth would I even get started?

答:
Since it's a multi-dimensional array (I'll call it $array) you probably have to loop through it once to find relevant data.</p>

```<code>$highest_id = array('id' => 0, 'count' => 0, 'can' => 0);
for each ( $array AS $key => $data )
{
  if ( substr($data['name'],0,strlen($x)) == $x )
  {
    $current_count = (int) substr($data['name'],strlen($x));
    if ( $current_count > $highest_id['count'] )
    {
      $highest_id = array('id' => $data['id'], 'count' => $current_count, 'can' => $data['can']);
    }
  }
}
if ( $highest_id['can'] == 1 )
{
  $id = $highest_id['id'];
}
else
{
 // can is not 1 => specify new $x
}
</code>```

Body:
I have an array of names and id's.

Array(
    0=>array(
        name=>New York,
        id=>45763448349,
        can=0
    ),
    1=>array(
        name=>New York2,
        id=>45763464566,
        can=0
    ),
    3=>array(
        name=>New York3,
        id=>45763464854,
        can=0
    ),
    4=>array(
        name=>New York4,
        id=>45763464955,
        can=0
    ),
    5=>array(
        name=>New York5,
        id=>45763464745,
        can=0
    ),
    6=>array(
        name=>New York6,
        id=>45763464235,
        can=1
    )
)

For example (there will be different names (not all New York)) and I have an x variable with a name (for example x=New York) what I need to do is find the highest name and get the id and then make sure can is 1 otherwise specific the next highest name.

For example let's assume that I have x=New York so I look through the array and find that the highest array name is New York6. I see that can=1 so I just get the id. Now if can != 1 then I could specific New York7.

NOTE: This array will contain many different values (not all New York, I just used those for an example)

Now how on earth would I even get started?

Body:
Since it's a multi-dimensional array (I'll call it $array) you probably have to loop through it once to find relevant data.

$highest_id = array('id' => 0, 'count' => 0, 'can' => 0);
for each ( $array AS $key => $data )
{
  if ( substr($data['name'],0,strlen($x)) == $x )
  {
    $current_count = (int) substr($data['name'],strlen($x));
    if ( $current_count > $highest_id['count'] )
    {
      $highest_id = array('id' => $data['id'], 'count' => $current_count, 'can' => $data['can']);
    }
  }
}
if ( $highest_id['can'] == 1 )
{
  $id = $highest_id['id'];
}
else
{
 // can is not 1 => specify new $x
}


问:
jQuery DatePicker not showing
Hello I'm trying to create a simple textbox with a datepicker that appears when a user clicks inside of the it.  I have the following loaded in my header:

```<code><link rel="stylesheet" href="css/start/jquery-ui-1.8.13.custom.css">
<script src="js/jquery-1.5.1.min.js"></script>
<script src="js/jquery-ui-1.8.13.custom.min.js" type="text/javascript"> </script><!-- Was missing closing tag
<script>
    $(function() {
        $( "#datepicker" ).datepicker();
    });
</script>
</code>```

And in my body, I have the following textbox:

```<code><body>

    <input id="datepicker" class="hasDatepicker" type="text">

</body>
</code>```

My problem is that when I try to click inside the text box, nothing happens.  I'm not sure what the problem might be.  Any suggestions are appreciated.

UPDATE:

Tried the CDN and also downloaded the entire jQuery UI package and still won't show.  Tried in both IE and Firefox.

UPDATE 2:

Was hoping that syntax error I corrected above would fix it, but no dice.

答:
I had the similar issue.
My resolution was to add z-index in .date-picker of datePicker.css

```<code>.date-picker {
position: absolute;
z-index:1000;/*********** MY Change *************/
font-size: 1em;
color: #CCC;
text-align: center;
cursor: default;

border: 1px solid #444;
border-radius: 2px;
margin: 6px 0;
background: #222;
box-shadow: 8px 8px 12px rgba(0, 0, 0, 0.2);}
</code>```

And with this change the Date Picker started displaying.

Title: jQuery DatePicker not showing

Body:
Hello I'm trying to create a simple textbox with a datepicker that appears when a user clicks inside of the it.  I have the following loaded in my header:

<link rel="stylesheet" href="css/start/jquery-ui-1.8.13.custom.css">

Body:
I had the similar issue.
My resolution was to add z-index in .date-picker of datePicker.css

.date-picker {
position: absolute;
z-index:1000;/*********** MY Change *************/
font-size: 1em;
color: #CCC;
text-align: center;
cursor: default;

border: 1px solid #444;
border-radius: 2px;
margin: 6px 0;
background: #222;
box-shadow: 8px 8px 12px rgba(0, 0, 0, 0.2);}

And with this change the Date Picker started displaying.


答:
div is a block element so use a inline one, like span. As for commas, add it on all elements except the last one, for example:

```<code><div>
   <span v-for="inv, index in data.inventory" v-if="index != data.inventory.length - 1">{{inv}},</span>
   <span v-else>{{inv}}</span>
</div>
</code>```

Working fiddle

Title: How can I able to display content in inventory seperated by commas in vue js?

Body:
My json data is

{ "status": true,
  "data": {
    "pid": 9,
    "Name": "Asok",
    "services": "3, 1, 2, 4, 5, 6",
    "inventory": ["specs", " Testing", "Lens", "Doctors", "Surgeon", "Medicines"]
  }
}

Now I am using html as

{{inv}}

When I do this way, the data is printing downwards.. I need to display data seperated by commmas in a row??

Body:
div is a block element so use a inline one, like span. As for commas, add it on all elements except the last one, for example:

<div>
   <span v-for="inv, index in data.inventory" v-if="index != data.inventory.length - 1">{{inv}},</span>
   <span v-else>{{inv}}</span>
</div>

Working fiddle


问:
sjPlot: set_labels() disappear
I have some scripts using sjPlot that I wrote last year and now I need to run these scripts again in a new machine, but they complain that set_labels() cannot be found. I have re-installed all the packages (newest versions).

Any clues?

答: Functions have been moved to the sjlabelled-package. Usually, this package should install along with sjPlot. If not, try re-installing sjPlot: install.packages("sjPlot", dependencies = T).

Title: sjPlot: set_labels() disappear


问:
Python regex search/findall. For a config format
I have a config file in the following format

```<code>[COMPONENT1]
KEY1=Value
KEY2=Value
KEY3=Value

[COMPONENT2]
KEY1=Value
KEY2=Value
KEY3=Value
KEY4=Value
</code>```

I am having trouble writing single line regex for re.findall(), where i can get list/tuple of "COMPONENT"(s) and its respective "KEY(n)" - "VALUE" pairs to iterate through.

so far i have tried the following regex

```<code>with open(conf,"r") as config:
    match = re.findall(r,"?:\[(\w+)\](?:\s*\n*)(?:(\w+(?:\s*=\s*).+)))", config.read())
</code>```

It's returning

```<code>Match 1
Group1: 'COMPONENT1'
Group2: 'KEY1=VALUE'

Match 2
Group1: 'COMPONENT2'
Group2: 'KEY1=VALUE'
</code>```

I am unable to formulate a regex that can show other 'Key=Value' pair.

Any help on this is really appreciated.

Note: This config format cannot be changed.

答:
This is not something I would suggest using regular expressions for. Regular expressions can be great, but when trying to work with something like a configuration file, they aren't very helpful in structuring what you want to read. Unless you can guarantee that every single relevant line will be structured similarly to [Section Name] or key=value, and only take up one line, and yadda yadda yadda, a regular expression will only complicate the parsing and use of a config file.

In the regular expression you shared, you will only match if and only if a [Section Name] is followed by a key=value pair. key=value pairs on their own lines are being ignored because they are not preceded by a [Section Name]. This is part of what makes using regular expressions a bit inappropriate for things like reading configurations; there are conditionals that arise when structuring your config file that must be dealt with in your regular expression, making it longer and more complicated than it needs to be for the task, or should be when someone needs to maintain it.

ConfigParser is a python module that allows you to easily read .ini-style config files, and I would suggest trying to use it as most of the hard work in reading arbitrary key=value pairs is already solved.

Body:
I have a config file in the following format

[COMPONENT1]
KEY1=Value
KEY2=Value
KEY3=Value

[COMPONENT2]
KEY1=Value
KEY2=Value
KEY3=Value
KEY4=Value

I am having trouble writing single line regex for re.findall(), where i can get list/tuple of "COMPONENT"(s) and its respective "KEY(n)" - "VALUE" pairs to iterate through.

so far i have tried the following regex

with open(conf,"r") as config:
    match = re.findall(r,"?:\[(\w+)\](?:\s*\n*)(?:(\w+(?:\s*=\s*).+)))", config.read())

It's returning

Match 1
Group1: 'COMPONENT1'
Group2: 'KEY1=VALUE'

Match 2
Group1: 'COMPONENT2'
Group2: 'KEY1=VALUE'

I am unable to formulate a regex that can show other 'Key=Value' pair.

Any help on this is really appreciated.

Note: This config format cannot be changed.


问:
The requested controller could not be mapped to an existing controller class. zf3 with routes to several controllers in one module
When i'm trying to create routes to several controllers in one module and i'm getting this

```<code>        'application' => [
            'type'    => Segment::class,
            'options' => [
                'route'    => '/application[/:action]',
                'defaults' => [
                    'controller' => Controller\IndexController::class,
                    'action'     => 'index',
                ],
            ],
        ],
        'vehicles' => [
            'type'    => Segment::class,
            'options' => [
                'route'    => '/vehicles[/:action]',
                'defaults' => [
                    'controller' => Controller\VehiclesController::class,
                    'action'     => 'index',
                ],
            ],
        ],
</code>```

Calling the indexAction() of IndexController works perfectly. However it doesn't work for VehiclesController. I tried to invoke VehiclesController in factories - unsuccessful.

```<code>'controllers' => [
    'factories' => [
        Controller\IndexController::class => InvokableFactory::class,
        Controller\VehiclesController::class => InvokableFactory::class,
    ],
    ],
</code>```

Using ServiceManager function

```<code>'controllers' => [
    'factories' => [
        Controller\VehiclesController::class => function($sm){
            $vehiclesService=$sm->get('Application\Model\VehiclesTable');
            return new Controller\VehiclesController($vehiclesService);
        }
    ],
],
</code>```

答:
May be you are doing something like below to invoke your controllers in your module.config.php

```<code>'controllers' => [
    'factories' => [
        Controller\IndexController::class => InvokableFactory::class,
        Controller\IndexController::class => InvokableFactory::class,
    ],
],
</code>```

Therefore, you may be using same controller name twice under factories key. It may be as above or different way.

So define them once under factories subkey of controllers key as the following

```<code>'controllers' => [
    'factories' => [
        Controller\IndexController::class => InvokableFactory::class,
        Controller\VehiclesController::class => InvokableFactory::class,
    ],
],
</code>```

Body:
When i'm trying to create routes to several controllers in one module and i'm getting this

        'application' => [
            'type'    => Segment::class,
            'options' => [
                'route'    => '/application[/:action]',
                'defaults' => [
                    'controller' => Controller\IndexController::class,
                    'action'     => 'index',
                ],
            ],
        ],
        'vehicles' => [
            'type'    => Segment::class,
            'options' => [
                'route'    => '/vehicles[/:action]',
                'defaults' => [
                    'controller' => Controller\VehiclesController::class,
                    'action'     => 'index',
                ],
            ],
        ],

Calling the indexAction() of IndexController works perfectly. However it doesn't work for VehiclesController. I tried to invoke VehiclesController in factories - unsuccessful.

'controllers' => [
    'factories' => [
        Controller\IndexController::class => InvokableFactory::class,
        Controller\VehiclesController::class => InvokableFactory::class,
    ],
    ],

Using ServiceManager function

'controllers' => [
    'factories' => [
        Controller\VehiclesController::class => function($sm){
            $vehiclesService=$sm->get('Application\Model\VehiclesTable');
            return new Controller\VehiclesController($vehiclesService);
        }
    ],
],

Body:
May be you are doing something like below to invoke your controllers in your module.config.php

'controllers' => [
    'factories' => [
        Controller\IndexController::class => InvokableFactory::class,
        Controller\IndexController::class => InvokableFactory::class,
    ],
],

Therefore, you may be using same controller name twice under factories key. It may be as above or different way.

So define them once under factories subkey of controllers key as the following

'controllers' => [
    'factories' => [
        Controller\IndexController::class => InvokableFactory::class,
        Controller\VehiclesController::class => InvokableFactory::class,
    ],
],


问:
Performance of OpenEdge concatenation
I have noticed in Progress (11.4) that repeated string concatenation can be very slow. For example in the following code.

```<code>DEF VAR i AS INT NO-UNDO.
DEF VAR c AS LONGCHAR NO-UNDO.

DO  i = 1 TO 1000000:
    c = c + STRING(i MOD 10).
END.
</code>```

From my experience in Java, I think the problem is that each time we are concatenating, we are copying c which is an O(n) operation, so the whole procedure is O(n^2). Java provides the StringBuilder class to solve this problem.

Is my analysis of the problem correct? And if so, is there a solution?

答:
This is a known issue - the following link also contains a work-around by buffering concatenations in character variables:

https://blog.abevoelker.com/introducing_bigcharacter/

Recognized by Progress and addressed in 11.7.2:

https://knowledgebase.progress.com/articles/Article/concatenating-to-longchar-takes-exponentially-longer

Title: Performance of OpenEdge concatenation

Body:
I have noticed in Progress (11.4) that repeated string concatenation can be very slow. For example in the following code.

DEF VAR i AS INT NO-UNDO.
DEF VAR c AS LONGCHAR NO-UNDO.

DO  i = 1 TO 1000000:
    c = c + STRING(i MOD 10).
END.

From my experience in Java, I think the problem is that each time we are concatenating, we are copying c which is an O(n) operation, so the whole procedure is O(n^2). Java provides the StringBuilder class to solve this problem.

Is my analysis of the problem correct? And if so, is there a solution?


问:
Using <q> element when referring to elements of a page in text
In a web app's help/instructions and error message we often need to refer to parts of a page.

Example: Enter your message in the "body" field.

Example: The "body" field's content cannot exceed 250 characters

Question: in terms of html markup, would it make sense to use the <q> element for the "body" word above? What would be the semantically correct markup to use?

```<code>Enter your message in the <q>body</q> field.
The <q>body</q> field's content cannot exceed 250 characters
</code>```

Looking for opinions, suggestions.

Notes:

Don't care about the use of quotation marks, I want something that is semantically correct, i.e. it give the right meaning.

Would like a simple tag that a tech writer/translator could easily deal with.

Would like to avoid body as it is long and give no semantic meaning to its contents.

Found this:

When referring to a word’s form rather than its meaning, use quotation marks to draw the reader’s attention

  http://termiumplus.gc.ca/tcdnstyl-chap?lang=fra&lettr=chapsect8&info0=8.11#zz8

Conclusion

Going to go with the good old body. I guess I was wishing for an html tag for something like "text references". Thanks for the feedback.

Marc

答:
I agree with akond.

Consider using one of this tags   <dfn>  <samp>  <var>  or  tag with a specific class attribute. I would prefer the latter.

Body:
In a web app's help/instructions and error message we often need to refer to parts of a page.

Example: Enter your message in the "body" field.

Example: The "body" field's content cannot exceed 250 characters

Question: in terms of html markup, would it make sense to use the <q> element for the "body" word above? What would be the semantically correct markup to use?

Enter your message in the <q>body</q> field.
The <q>body</q> field's content cannot exceed 250 characters

Looking for opinions, suggestions.

Notes:

Don't care about the use of quotation marks, I want something that is semantically correct, i.e. it give the right meaning.

Would like a simple tag that a tech writer/translator could easily deal with.

Would like to avoid body as it is long and give no semantic meaning to its contents.

Found this:

When referring to a word’s form rather than its meaning, use quotation marks to draw the reader’s attention

  http://termiumplus.gc.ca/tcdnstyl-chap?lang=fra&lettr=chapsect8&info0=8.11#zz8

Conclusion

Going to go with the good old body. I guess I was wishing for an html tag for something like "text references". Thanks for the feedback.

Marc

Body:
I agree with akond.

Consider using one of this tags <em> <strong> <dfn> <code> <samp> <kbd> <var> <cite> or <span> tag with a specific class attribute. I would prefer the latter.


问:
C# Combobox Selected.Index = -1 not working
It should reset the Combobox to no value, Combobox is in the same panel, but the code sets the index to 0 which is the first value of the data binded list.
It works on the second click though... ON the first click it sets the index to 0, on the second to -1.</p>
```<code>        if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
        {
           foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
            {
                if(C.SelectedIndex != -1)
                {
                    C.SelectedIndex = -1;
                }
            }
        }
</code>```

答:
thanks all for answers...in the end I solved the issue with a workaround. The problem was, that button of the code above needed two clicks to set index to -1.
On the first click it moved to 0 and on the second to -1. I dont know why tho...Another problem was i had a index changed event on combobox and i wanted to fire it only once - not twice.
I solved the problem this way...</p>

```<code>        if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
        {
           foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
            {
                if(C.SelectedIndex != -1)
                {
                    C.SelectedIndexChanged -= this.ComboBox_Promo_SelectedIndexChanged;
                    while (C.SelectedIndex != -1)
                    {
                        C.SelectedIndex = -1;
                    }
                    C.SelectedIndexChanged += this.ComboBox_Promo_SelectedIndexChanged;
                    this.ComboBox_Promo_SelectedIndexChanged(C, EventArgs.Empty);
                }
            }
        }
</code>```

Body:
It should reset the Combobox to no value, Combobox is in the same panel, but the code sets the index to 0 which is the first value of the data binded list.
It works on the second click though... ON the first click it sets the index to 0, on the second to -1.

        if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
        {
           foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
            {
                if(C.SelectedIndex != -1)
                {
                    C.SelectedIndex = -1;
                }
            }
        }

Body:
thanks all for answers...in the end I solved the issue with a workaround. The problem was, that button of the code above needed two clicks to set index to -1.
On the first click it moved to 0 and on the second to -1. I dont know why tho...Another problem was i had a index changed event on combobox and i wanted to fire it only once - not twice.
I solved the problem this way...

        if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
        {
           foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
            {
                if(C.SelectedIndex != -1)
                {
                    C.SelectedIndexChanged -= this.ComboBox_Promo_SelectedIndexChanged;
                    while (C.SelectedIndex != -1)
                    {
                        C.SelectedIndex = -1;
                    }
                    C.SelectedIndexChanged += this.ComboBox_Promo_SelectedIndexChanged;
                    this.ComboBox_Promo_SelectedIndexChanged(C, EventArgs.Empty);
                }
            }
        }


问:
Mule ESB: How to use MEL expression in Message Properties Key?
I'm using the message-properties component in mule. I need to set a dynamic key name as this is used to add custom headers to a http-request.

```<code><message-properties-transformer doc:name="Message Properties" scope="session">
    <add-message-property key="#[flowVars.name]" value="#[payload.split(":")[1]]"/>
</message-properties-transformer>
</code>```

When logging the output, it shows that the key has not evaluated the MEL expression contained inside:

```<code>SESSION scoped properties: #[flowVars.name]=Basic pokpogytg788t878
</code>```

Is there any way of setting a dynamic key name for a property in this component?

答:
I have faced similar situation,where I had to set dynamic message properties.
I tried several things to set it with message-properties-transformer , but to no luck.

There is some bug filed for similar issue,below is the link

Cannot use MEL expression as key in Message Properties transformer

After trying for sometime I got that working with some workaround.

You can try working it around with Expression component.

```<code>        <expression-component doc:name="Expression">
        <![CDATA[message.outboundProperties[flowVars.name]=payload.split(':')1];]]>
        </expression-component>
</code>```

Not only you can read dynamic values from payload/variables.But you can also call your custom java/groovy methods in it.

Try below code snippet,and let us know if that works for you.

```<code>    <flow name="testFlow">
        <http:listener config-ref="HTTP_Listener_Configuration"
            path="/test" doc:name="HTTP" allowedMethods="POST" />
        <set-variable variableName="name" value="#["test"]"
            doc:name="name" />
        <expression-component doc:name="Expression">
        <![CDATA[message.outboundProperties[flowVars.name]=payload.split(':')1];]]>
        </expression-component>
    </flow>
</code>```

Body:
I'm using the message-properties component in mule. I need to set a dynamic key name as this is used to add custom headers to a http-request.

<message-properties-transformer doc:name="Message Properties" scope="session">
    <add-message-property key="#[flowVars.name]" value="#[payload.split(":")[1]]"/>
</message-properties-transformer>

When logging the output, it shows that the key has not evaluated the MEL expression contained inside:

SESSION scoped properties: #[flowVars.name]=Basic pokpogytg788t878

Is there any way of setting a dynamic key name for a property in this component?

Body:
I have faced similar situation,where I had to set dynamic message properties.
I tried several things to set it with message-properties-transformer , but to no luck.

There is some bug filed for similar issue,below is the link

Cannot use MEL expression as key in Message Properties transformer

After trying for sometime I got that working with some workaround.

You can try working it around with Expression component.

        <expression-component doc:name="Expression">
        <![CDATA[message.outboundProperties[flowVars.name]=payload.split(':')1];]]>
        </expression-component>

Not only you can read dynamic values from payload/variables.But you can also call your custom java/groovy methods in it.

Try below code snippet,and let us know if that works for you.

    <flow name="testFlow">
        <http:listener config-ref="HTTP_Listener_Configuration"
            path="/test" doc:name="HTTP" allowedMethods="POST" />
        <set-variable variableName="name" value="#[&quot;test&quot;]"
            doc:name="name" />
        <expression-component doc:name="Expression">
        <![CDATA[message.outboundProperties[flowVars.name]=payload.split(':')1];]]>
        </expression-component>
    </flow>