问:
No numbered pagination custom post type
I have a problem showing numbered pagination on only one of my Wordpress pages.

```<code><?php
/**
 * Template Name: Sale template
 */
?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
    'post_type' => array(
        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

    ),
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'paged' => $paged,
    'meta_query' => array(
        'key' => 'prijsknaller',
        'value' => '1',
        'compare' => '==',
        //'type'    => 'date',
    ),
);
$query = new WP_Query($args);
?>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="product-overview">

                    <?php if ($query->have_posts()) :
                        while ($query->have_posts()) : $query->the_post(); ?>
                            <div class="col-md-3">
                                <div class="featured-block">
                                    <div class="featured-block-image">
                                        <a href="<?php the_permalink(); ?>"><img src="<?php the_field('productafbeelding'); ?>"
                                                                                alt="<?php the_title(); ?>"></a>
                                    </div>
                                    <div class="featured-block-info">
                                        <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                                        <?php if (get_field('prijs_oud')) : ?>
                                            <span class="oud"><?php the_field('prijs_oud'); ?></span>
                                        <?php endif; ?>
                                        <span class="nieuw"><?php the_field('prijs_nieuw'); ?></span> p/m<sub>2</sub>
                                    </div>
                                </div>
                            </div>

                        <?php endwhile; ?>
                    <?php endif; ?>
                    <?php the_posts_pagination(array(
                        'prev_text' => '«',
                        'next_text' => '»',
                    )); ?>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

The query returns about 70 products, so I would expect it to show at least 7 numbers. However, it does not show any pagination.

答:
try this code it surely help you</p>

```<code>     $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

 $args = array(
    'post_type'      => array (
                        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

                        ),
    'posts_per_page' => 5,
    'post_status'    => 'publish',
    'paged'          => $paged,
    'meta_query'     => array (
                            'key' => 'prijsknaller',
                            'value' => '1' ,
                            'compare' => '==',
                            //'type'    => 'date',
                             ),
    );
$wp_query = new WP_Query( $args );
</code>```

Title: No numbered pagination custom post type

Body:
I have a problem showing numbered pagination on only one of my Wordpress pages.

<?php
/**
 * Template Name: Sale template
 */
?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
    'post_type' => array(
        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

    ),
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'paged' => $paged,
    'meta_query' => array(
        'key' => 'prijsknaller',
        'value' => '1',
        'compare' => '==',
        //'type'    => 'date',
    ),
);
$query = new WP_Query($args);
?>

                    <?php if ($query->have_posts()) :
                        while ($query->have_posts()) : $query->the_post(); ?>

                                        <a href="<?php the_permalink(); ?>"><img src="<?php the_field('productafbeelding'); ?>"
                                                                                alt="<?php the_title(); ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                                        <?php if (get_field('prijs_oud')) : ?>
                                            <?php the_field('prijs_oud'); ?>
                                        <?php endif; ?>
                                        <?php the_field('prijs_nieuw'); ?> p/m2

                        <?php endwhile; ?>
                    <?php endif; ?>
                    <?php the_posts_pagination(array(
                        'prev_text' => '«',
                        'next_text' => '»',
                    )); ?>

The query returns about 70 products, so I would expect it to show at least 7 numbers. However, it does not show any pagination.

Body:
try this code it surely help you

     $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

 $args = array(
    'post_type'      => array (
                        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

                        ),
    'posts_per_page' => 5,
    'post_status'    => 'publish',
    'paged'          => $paged,
    'meta_query'     => array (
                            'key' => 'prijsknaller',
                            'value' => '1' ,
                            'compare' => '==',
                            //'type'    => 'date',
                             ),
    );
$wp_query = new WP_Query( $args );


来源: stackexchange

问:
SQL Server 2005. Full Text Search. Need Thesaurus working with NEAR/AND/OR keywords
does anyone know if it's possible to do a thesaurus search
together with NEAR or AND/OR keywords.
Here is an example of the type of query I want to run:

```<code>    SELECT Title, RANK
            FROM Item INNER JOIN
            CONTAINSTABLE(Item, Title, 'FORMSOF(Thesaurus, "red" NEAR "wine")') AS KEY_TBL
            ON Item.ItemID = KEY_TBL.[KEY]
    ORDER BY RANK DESC
</code>```

....But I get the error message:

Syntax error near 'NEAR' in the full-text search condition 'FORMSOF(Thesaurus, "red" NEAR "wine")'.

答:
Near and FormsOf don't work well with each other. Read the following link
Is it possible to combine NEAR and FORMSOF together in a fulltext search?

use IsAbout

```<code>SELECT   K.RANK, name, Description
FROM      Diagnosis AS C
INNER JOIN
CONTAINSTABLE(diagnosis,name, 'ISABOUT (
FORMSOF(Thesaurus, "red"),
FORMSOF(Thesaurus, "wine"))', 50) AS K
ON C.ID = K.[KEY];
GO
</code>```

ContentLicense: CC BY-SA 2.5

Body:
does anyone know if it's possible to do a thesaurus search
together with NEAR or AND/OR keywords.
Here is an example of the type of query I want to run:

    SELECT Title, RANK
            FROM Item INNER JOIN
            CONTAINSTABLE(Item, Title, 'FORMSOF(Thesaurus, "red" NEAR "wine")') AS KEY_TBL
            ON Item.ItemID = KEY_TBL.[KEY]
    ORDER BY RANK DESC

....But I get the error message:

Syntax error near 'NEAR' in the full-text search condition 'FORMSOF(Thesaurus, "red" NEAR "wine")'.

Body:
Near and FormsOf don't work well with each other. Read the following link
Is it possible to combine NEAR and FORMSOF together in a fulltext search?

use IsAbout

SELECT   K.RANK, name, Description
FROM      Diagnosis AS C
INNER JOIN
CONTAINSTABLE(diagnosis,name, 'ISABOUT (
FORMSOF(Thesaurus, "red"),
FORMSOF(Thesaurus, "wine"))', 50) AS K
ON C.ID = K.[KEY];
GO

ContentLicense: CC BY-SA 3.0


问:
How to use Retrofit2 to parse json into class with subclass(es)
How to convert given json response

```<code>{
    "name" : "John",
    "surname" : "Doe",
    "location" : {
        "name" : "Paris",
        "desc" : "Welcome to Paris"
    }
}
</code>```

into

```<code>class Person
{
    String name;
    String surname;
    Location location;  // new Location(String name, String desc)
}
</code>```

It's all about nested Location class that is inside Person class

答:
First get an API and get its JSON output by Advance REST Client which is a Chrome Extension. Now put that output to JSON to POJO converter
and you'll get your POJO Classes. Paste them to your project. Make an interface`

```<code>/**
 * Get Data
 *
 * @param body Holds the JSON payloads
 * @return Formatted data
 */
@POST("JobSpotAPI/getUserInterviewSchedule")
Call<POJOClass> getData(@Body JsonObject body);
</code>```

and setup a Client

```<code>public class RetrofitClient {
private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl) {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
</code>```

Create a Recycler view setup its adapter and all. Just add a few new methods like-

```<code> public void updateAnswers(List<Item> items) {
    mItems = items;
    notifyDataSetChanged();
}

private Item getItem(int adapterPosition) {
    return mItems.get(adapterPosition);
}
</code>```

Setup Utility class to call the interface.

```<code>public class ApiUtils {

public static final String BASE_URL = "https://base_url/";

public static Interface_name methodName() {
    return RetrofitClient.getClient(BASE_URL).create(Interface_name.class);
}}
</code>```

Declare the Interface in your Activity

```<code>Interface_name obj = ApiUtils.methodName();
</code>```

If you have some payloads then attach them to you request. Before that you need a JSON string to pass to API request. To make a JSON Payload.

```<code>  private JsonObject makeJsonObjectPayload() {
    JsonObject requestBean = new JsonObject();
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    return requestBean;
</code>```

Pass the API request

```<code>obj.getData(makeJsonObjectPayload()).enqueue(new Callback<POJOClass>() {
    @Override
    public void onResponse(Call<POJOClass> call, Response<POJOClass> response) {

        if(response.isSuccessful()) {
            mAdapter.updateAnswers(response.body().getItems());
            Log.d("MainActivity", "posts loaded from API");
        }else {
            int statusCode  = response.code();
            // handle request errors depending on status code
        }
    }

    @Override
    public void onFailure(Call<UserDataPOJOClass> call, Throwable t) {
        //showErrorMessage();
        Log.d("API ERROR",""+t.getMessage());
        Log.d("MainActivity", "error loading from API");

    }
});
</code>```

Body:
How to convert given json response

{
    "name" : "John",
    "surname" : "Doe",
    "location" : {
        "name" : "Paris",
        "desc" : "Welcome to Paris"
    }
}

into

class Person
{
    String name;
    String surname;
    Location location;  // new Location(String name, String desc)
}

It's all about nested Location class that is inside Person class

Body:
First get an API and get its JSON output by Advance REST Client which is a Chrome Extension. Now put that output to JSON to POJO converter
and you'll get your POJO Classes. Paste them to your project. Make an interface`

/**
 * Get Data
 *
 * @param body Holds the JSON payloads
 * @return Formatted data
 */
@POST("JobSpotAPI/getUserInterviewSchedule")
Call<POJOClass> getData(@Body JsonObject body);

and setup a Client

public class RetrofitClient {
private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl) {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

Create a Recycler view setup its adapter and all. Just add a few new methods like-

 public void updateAnswers(List<Item> items) {
    mItems = items;
    notifyDataSetChanged();
}

private Item getItem(int adapterPosition) {
    return mItems.get(adapterPosition);
}

Setup Utility class to call the interface.

public class ApiUtils {

public static final String BASE_URL = "https://base_url/";

public static Interface_name methodName() {
    return RetrofitClient.getClient(BASE_URL).create(Interface_name.class);
}}

Declare the Interface in your Activity

Interface_name obj = ApiUtils.methodName();

If you have some payloads then attach them to you request. Before that you need a JSON string to pass to API request. To make a JSON Payload.

  private JsonObject makeJsonObjectPayload() {
    JsonObject requestBean = new JsonObject();
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    return requestBean;

Pass the API request

obj.getData(makeJsonObjectPayload()).enqueue(new Callback<POJOClass>() {
    @Override
    public void onResponse(Call<POJOClass> call, Response<POJOClass> response) {

        if(response.isSuccessful()) {
            mAdapter.updateAnswers(response.body().getItems());
            Log.d("MainActivity", "posts loaded from API");
        }else {
            int statusCode  = response.code();
            // handle request errors depending on status code
        }
    }

    @Override
    public void onFailure(Call<UserDataPOJOClass> call, Throwable t) {
        //showErrorMessage();
        Log.d("API ERROR",""+t.getMessage());
        Log.d("MainActivity", "error loading from API");

    }
});


问:
generate dynamic variable name in for loop php
I am trying to generate variable name dynamically in php for loop.
I want call a function within for loop and want to pass iterated values.
What I tried is:

```<code>for ($i=1, $j=1; $i<=16 ; $i++, $j++) {
    $a='arrtreelevel_1';
    $b='0';
    $newname = $a.$j.$b;
    echo $newname,"<br>";
    echo $arrtreelevel_1[0];
    $arrtreelevel_2.$i = profiledetails($newname);
}
</code>```

My problem is '$newname' variable printing $arrtreelevel_1[0] as a text not taking the value, and $arrtreelevel_11[0] returns the actual value.
I tried with echo ${'arrtreelevel_1$i'} also which printing nothing. Assist me with any solution please.

Thanks in advance.

答:
Use $$ to make runtime php variable. Replace this line

```<code>$arrtreelevel_2.$i = profiledetails($newname);
</code>```

To

```<code>$tempvar = $arrtreelevel_2.$i;
$$tempvar = profiledetails($newname);
</code>```

Body:
I am trying to generate variable name dynamically in php for loop.
I want call a function within for loop and want to pass iterated values.
What I tried is:

for ($i=1, $j=1; $i<=16 ; $i++, $j++) {
    $a='arrtreelevel_1';
    $b='0';
    $newname = $a.$j.$b;
    echo $newname,"
";
    echo $arrtreelevel_1[0];
    $arrtreelevel_2.$i = profiledetails($newname);
}

My problem is '$newname' variable printing $arrtreelevel_1[0] as a text not taking the value, and $arrtreelevel_11[0] returns the actual value.
I tried with echo ${'arrtreelevel_1$i'} also which printing nothing. Assist me with any solution please.

Thanks in advance.

Body:
Use $$ to make runtime php variable. Replace this line

$arrtreelevel_2.$i = profiledetails($newname);

To

$tempvar = $arrtreelevel_2.$i;
$$tempvar = profiledetails($newname);


问:
Bluemix Services: Configuring WebSphere Application to use dashDB for Analytics
I'm using dashDB for Anayltics as a service for my Bluemix and I also added the SQL and data needed. But when I tried to start the application, I can't login. It seems that Bluemix can't find the dashDB...

My question is, when you add a service to a Bluemix app, does it automatically configure to enable the app to use the service such as "dashDB for Analytic" or do I have to manually configure something.

Addtional:

I'm trying to change the database used from DB2 to dashDB...I have changed the databaseName, password, user, portnumber, driverType to the ones I see in the Environment variables.

```<code><applicationMonitor updateTrigger="mbean"/>
<jdbcDriver id="DB2JCC" libraryRef="DB2Library">
</jdbcDriver>
<dataSource id="jdbc/defaultDS" jndiName="jdbc/defaultDS" jdbcDriverRef="DB2JCC" statementCacheSize="60" type="javax.sql.ConnectionPoolDataSource" transactional="true">
    <properties databaseName="database_name" password="{xor}ZmdpOztrPT5oaDtp" user="username" serverName="host_name" portNumber="port_number" driverType="4"/>
</dataSource>

<!-- <variable name="" value=""/> -->
<library id="DB2Library">
    <fileset dir="C:\Program Files\IBM\SQLLIB\java" includes="db2jcc4.jar, db2jcc_license_cu.jar"/>
</library>
</code>```

答:
I'm assuming by application you are referring to a Bluemix cloud foundry application.

When you configure an application to use a service, the applications gets injected with environment variables from the service, but it is up to you to write the code to connect to the database using those environment variables.

See here for more information: https://console.bluemix.net/docs/cli/vcapsvc.html

Body:
I'm using dashDB for Anayltics as a service for my Bluemix and I also added the SQL and data needed. But when I tried to start the application, I can't login. It seems that Bluemix can't find the dashDB...

My question is, when you add a service to a Bluemix app, does it automatically configure to enable the app to use the service such as "dashDB for Analytic" or do I have to manually configure something.

Addtional:

I'm trying to change the database used from DB2 to dashDB...I have changed the databaseName, password, user, portnumber, driverType to the ones I see in the Environment variables.

<applicationMonitor updateTrigger="mbean"/>
<jdbcDriver id="DB2JCC" libraryRef="DB2Library">
</jdbcDriver>
<dataSource id="jdbc/defaultDS" jndiName="jdbc/defaultDS" jdbcDriverRef="DB2JCC" statementCacheSize="60" type="javax.sql.ConnectionPoolDataSource" transactional="true">
    <properties databaseName="database_name" password="{xor}ZmdpOztrPT5oaDtp" user="username" serverName="host_name" portNumber="port_number" driverType="4"/>
</dataSource>

<library id="DB2Library">
    <fileset dir="C:\Program Files\IBM\SQLLIB\java" includes="db2jcc4.jar, db2jcc_license_cu.jar"/>
</library>


问:
AppleScript Editor, write message to the "Result" window
I am using the Mac OS X Apple Script Editor and (while debugging) instead of writing a lot of display dialog statements, I'd like to write the results of some calculation in the window below, called "Result" (I have the German UI here, so the translation is a guess). So is there a write/print statement that I can use for putting messages in the "standard out" window? I am not asking to put the messages in a logfile on the file system, it is purely temporary.

答:
Log is the correct way of doing this; however, if your user base is more familiar with shell script you can do the following.

```<code>set val to 123
do shell script "echo The value: " & val
</code>```

Output

```<code>Result:
"The value: 123"
</code>```

With this approach you don’t constantly have to telling users that they need to enable ‘Show Log’

Body:
Log is the correct way of doing this; however, if your user base is more familiar with shell script you can do the following.

set val to 123
do shell script "echo The value: " & val

Output

Result:
"The value: 123"

With this approach you don’t constantly have to telling users that they need to enable ‘Show Log’


问:
How to change the permissions to be allowed to change notifications subscriptions
On our Visual Studio Team Services there is some default setup, that everyone in the "Project Collection Valid Users" get an email notification each time a queued build completes or fails.

I would like to be able to change this on my non super-admin account, but what permissions in the security tab is related to this permission?

Below is a screenshot of the not so descriptive error, that I get, when I try to set up a new subscription.

答:
The alert permissions are documented here. (Notifications have recently been renamed from alert).

Alert permissions

There are no UI permissions associated with managing email notifications or alerts. Instead, they can be managed using the TFSSecurity command line tool.

By default:

Members of the team project level Contributors group can subscribe to alerts for themselves.

Members of the Project Collection Administrators group, or users who have the Edit collection-level information can set alerts in that collection for others or for a team.

Members of the Project Administrators group, or users who have the Edit project-level information can set alerts in that team project for others or for a team.

And:

Team administrator role

For each team that you add, you can assign one or more team members as administrators. The team admin role isn't a group with a set of defined permissions. Instead, the team admin role is tasked with managing the following team assets.

Create and manage team alerts

Can add and modify alerts so that the team can receive email notifications as changes occur to work items, code reviews, source control files, and builds. For details, see Manage team alerts.

There is no UI associated with managing alert permissions. Instead, you can use TFSSecurity to manage alerts in TFS.


问:
CSS Blend Background with Parent Background
I have a div identified by #front.

It is inside a div identified by #back.

#back is a canvas that constantly changes.

I'd like #front, a square, plain square to take the colour of the parent and invert it.

E.g. if the background is white, the square should be black.
If the background is black, the square should be white. If the background is partially white and partially black, the square should be partially black and partially white.

I have tried background-blend-mode: overlay and mix-blend-mode: screen on the #front element but these had no effect.

Is this possible in any way?

HTML:

CSS:

```<code>#back {
   position:absolute;
   top:0;
   bottom:0;
   left:0;
   right:0;
   background-image:url('http://example.com/image.png');
   background-size:cover;
}

#front {
   width:100px;
   height:100px;
   display:block;
}
</code>```

答:
Here's one idea using SCSS: https://codepen.io/panchroma/pen/dRqVVQ

CSS (SCSS)

```<code>// set background color here
$color: pink;

body {
  background-color: $color;
}
.child {
  background-color: invert($color);
}
</code>```

op mentioned that color of back (canvas, or body in your case) will change constantly...

OP hasn't detailed how the the colour of the canvas will actually be changed. What I'm thinking is that if you manipulate $color then there are ways of automatically recompiling SCSS.

scssphp might be one possibility and here's how one developer used it to convert SCSS to CSS on the fly. There are WordPress SCSS to CSS plugins as well, maybe there's one which would be a good match for what's required.

Body:
I have a div identified by #front.

It is inside a div identified by #back.

#back is a canvas that constantly changes.

I'd like #front, a square, plain square to take the colour of the parent and invert it.

E.g. if the background is white, the square should be black.
If the background is black, the square should be white. If the background is partially white and partially black, the square should be partially black and partially white.

I have tried background-blend-mode: overlay and mix-blend-mode: screen on the #front element but these had no effect.

Is this possible in any way?

HTML:

CSS:

#back {
   position:absolute;
   top:0;
   bottom:0;
   left:0;
   right:0;
   background-image:url('http://example.com/image.png');
   background-size:cover;
}

#front {
   width:100px;
   height:100px;
   display:block;
}

Body:
Here's one idea using SCSS: https://codepen.io/panchroma/pen/dRqVVQ

CSS (SCSS)

// set background color here
$color: pink;

body {
  background-color: $color;
}
.child {
  background-color: invert($color);
}

op mentioned that color of back (canvas, or body in your case) will change constantly...

OP hasn't detailed how the the colour of the canvas will actually be changed. What I'm thinking is that if you manipulate $color then there are ways of automatically recompiling SCSS.

scssphp might be one possibility and here's how one developer used it to convert SCSS to CSS on the fly. There are WordPress SCSS to CSS plugins as well, maybe there's one which would be a good match for what's required.


问:
How to disable gzip for just one handler .ashx
I am running a website using IIS6 and i wrote a simple generic handler which return smaller images when it receive image url as query string. My problem is that the server is applying gzip to some file types such as .aspx and .ashx.

And that made my response image from the handler appear with lower quality because they are compressed.

How can i disable gzip for just this handler file, i hope for a solution without editing the IIS.

Is that possible?

答:
This worked for me - in the ProcessRequest method:

```<code>context.Request.Headers.Remove("Accept-Encoding")
</code>```

I assume that this makes IIS think that the client does not support GZip (or other compression methods) and therefore sends the response uncompressed.

Yes - it is a hack (generally you should not mess with the request headers) but it is by far the simplest solution I have seen.

I personally needed this because a simple 5 character plain text response to an Ajax call ended up being 124 bytes long after GZip "compression".

This answers the title of this question. However for your scenario with images - it really shouldn't make any difference as GZip is lossless (uncompressed data = original).

Body:
This worked for me - in the ProcessRequest method:

context.Request.Headers.Remove("Accept-Encoding")

I assume that this makes IIS think that the client does not support GZip (or other compression methods) and therefore sends the response uncompressed.

Yes - it is a hack (generally you should not mess with the request headers) but it is by far the simplest solution I have seen.

I personally needed this because a simple 5 character plain text response to an Ajax call ended up being 124 bytes long after GZip "compression".

This answers the title of this question. However for your scenario with images - it really shouldn't make any difference as GZip is lossless (uncompressed data = original).


问:
Pandas: How to find a particular pattern in a dataframe column?
I'd like to find a particular pattern in a pandas dataframe column, and return the corresponding index values in order to subset the dataframe.

Here's a sample dataframe with a possible pattern:

Snippet to produce dataframe:

```<code>import pandas as pd
import numpy as np

Observations = 10
Columns = 2
np.random.seed(123)
df = pd.DataFrame(np.random.randint(90,110,size=(Observations, Columns)),
                  columns = ['ColA','ColB'])
datelist = pd.date_range(pd.datetime(2017, 7, 7).strftime('%Y-%m-%d'),
                         periods=Observations).tolist()
df['Dates'] = datelist
df = df.set_index(['Dates'])

pattern = [100,90,105]
print(df)
</code>```

Dataframe:

```<code>            ColA  ColB
Dates
2017-07-07   103    92
2017-07-08    92    96
2017-07-09   107   109
2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
2017-07-13    90   104
2017-07-14    90   105
2017-07-15   109   104
2017-07-16    94    90
</code>```

Here, the pattern of interest occurs in Column A on the dates 2017-07-10 to 2017-07-12, and that's what I'd like to end up with:

Desired output:

```<code>2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
</code>```

If the same pattern occurs several times, I would like to subset the dataframe the same way, and also count how many times the pattern occurs, but I hope that's more straight forward as long as I get the first step sorted out.

Thank you for any suggestions!

答:
```<code>for col in df:
    index = df[col][(df[col] == pattern[0]) & (df[col].shift(-1) == pattern[1]) & (df[col].shift(-2) == pattern[2])].index
    if not index.empty: print(index)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to find a particular pattern in a pandas dataframe column, and return the corresponding index values in order to subset the dataframe.

Here's a sample dataframe with a possible pattern:

Snippet to produce dataframe:

import pandas as pd
import numpy as np

Observations = 10
Columns = 2
np.random.seed(123)
df = pd.DataFrame(np.random.randint(90,110,size=(Observations, Columns)),
                  columns = ['ColA','ColB'])
datelist = pd.date_range(pd.datetime(2017, 7, 7).strftime('%Y-%m-%d'),
                         periods=Observations).tolist()
df['Dates'] = datelist
df = df.set_index(['Dates'])

pattern = [100,90,105]
print(df)

Dataframe:

            ColA  ColB
Dates
2017-07-07   103    92
2017-07-08    92    96
2017-07-09   107   109
2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
2017-07-13    90   104
2017-07-14    90   105
2017-07-15   109   104
2017-07-16    94    90

Here, the pattern of interest occurs in Column A on the dates 2017-07-10 to 2017-07-12, and that's what I'd like to end up with:

Desired output:

2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99

If the same pattern occurs several times, I would like to subset the dataframe the same way, and also count how many times the pattern occurs, but I hope that's more straight forward as long as I get the first step sorted out.

Thank you for any suggestions!


问:
Call BeanShell function from BeanShell Programs like PreProcessor, PostProcessor, Assertion, etc
Pre-requisite:

Inside JMeter bin folder, I have edited BeanShellFunction.bshrc file to add my function as follows

```<code>String getMyString()
{
    return "MyString";
}
</code>```

I have enabled the BeanShellFunction.bshrc from jmeter.properties file as

beanshell.function.init = BeanShellFunction.bshrc

When I use the following syntax to call function it works fine.

```<code>${__BeanShell(getMyString())}
</code>```

It works fine for below case:

Question:

How can I call the same function from BeanShell Programs like PreProcessor, PostProcessor, Assertion, etc.?

Analysis:

I tried with following but no luck:

```<code>String myStr = getMyString();
</code>```

It gives an error as:

Assertion error: true

  Assertion failure: false

  Assertion failure message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``  String myStr = getMyString();  print("MyStr: "+myStr);'' : Typed variable declaration : Command not found: getMyString()

答:
From this SO post I found the solution: Calling Jmeter Functions from BeanShell Assertion Script

Solution

For each BeanShell Program type there are different beanshell.*.init properties defined in bin/user.properties:

beanshell.function.init=BeanShellFunction.bshrc

  beanshell.preprocessor.init=BeanShellSampler.bshrc
  beanshell.postprocessor.init=BeanShellSampler.bshrc
  beanshell.assertion.init=BeanShellFunction.bshrc

Hence the same function which needs to be called from any program(preprocessor, postprocessor, etc) we need to copy the function to every .bshrc file OR use same .bshrc file for every program init property.

Syntax to use:

You need use the same syntax used for sending URL parameter:

```<code>String myStr = "${__BeanShell(getMyString())}";
</code>```

This automatically calls the beanshell method from defined .bshrc file.

For Advance Scripting

If your BeanShell function accepts a parameter:

```<code>String getMyString(String strParam)
{
    return "MyString: "+strParam;
}
</code>```

And you want to pass a property as a parameter to the BeanShell function, you can use following syntax:

```<code>String myStr = "${__BeanShell(getMyString("${__P(param1)}"))}";
</code>```

Believe me it works and it does not give any syntax error.

Body:
Pre-requisite:

Inside JMeter bin folder, I have edited BeanShellFunction.bshrc file to add my function as follows

String getMyString()
{
    return "MyString";
}

I have enabled the BeanShellFunction.bshrc from jmeter.properties file as

beanshell.function.init = BeanShellFunction.bshrc

When I use the following syntax to call function it works fine.

${__BeanShell(getMyString())}

It works fine for below case:

Question:

How can I call the same function from BeanShell Programs like PreProcessor, PostProcessor, Assertion, etc.?

Analysis:

I tried with following but no luck:

String myStr = getMyString();

It gives an error as:

Assertion error: true

  Assertion failure: false

  Assertion failure message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``  String myStr = getMyString();  print("MyStr: "+myStr);'' : Typed variable declaration : Command not found: getMyString()

Body:
From this SO post I found the solution: Calling Jmeter Functions from BeanShell Assertion Script

Solution

For each BeanShell Program type there are different beanshell.*.init properties defined in bin/user.properties:

beanshell.function.init=BeanShellFunction.bshrc

  beanshell.preprocessor.init=BeanShellSampler.bshrc
  beanshell.postprocessor.init=BeanShellSampler.bshrc
  beanshell.assertion.init=BeanShellFunction.bshrc

Hence the same function which needs to be called from any program(preprocessor, postprocessor, etc) we need to copy the function to every .bshrc file OR use same .bshrc file for every program init property.

Syntax to use:

You need use the same syntax used for sending URL parameter:

String myStr = "${__BeanShell(getMyString())}";

This automatically calls the beanshell method from defined .bshrc file.

For Advance Scripting

If your BeanShell function accepts a parameter:

String getMyString(String strParam)
{
    return "MyString: "+strParam;
}

And you want to pass a property as a parameter to the BeanShell function, you can use following syntax:

String myStr = "${__BeanShell(getMyString("${__P(param1)}"))}";

Believe me it works and it does not give any syntax error.


问:
How does work function overload resolving with variadic arguments?
```<code>#define FALSE 0
#define TRUE  1

#define IDS_MYSTR 123

void FnVariadic(const long nIDS, ...)
{
  std::cout << "WITHOUT option IDS" << std::endl;
}

void FnVariadic(const bool bOption, const long nIDS, ...)
{
  std::cout << "WITH option IDS" << std::endl;
}

void FnVariadic(const char *pStr, ...)
{
  std::cout << "WITHOUT option STR" << std::endl;
}

void FnVariadic(const bool bOption, const char *pStr, ...)
{
  std::cout << "WITH option STR" << std::endl;
}

int main()
{
  FnVariadic(FALSE, IDS_MYSTR, "abc");
  //FnVariadic(IDS_MYSTR, FALSE, "abc"); //???
  FnVariadic(TRUE, IDS_MYSTR, "abc");
  FnVariadic(IDS_MYSTR, TRUE, "abc");    //???

  FnVariadic(FALSE, "abc%s", "abc");
  //FnVariadic("abc%d%s", FALSE, "abc");
  FnVariadic(TRUE, "abc%s", "abc");
  //FnVariadic("abc%d%s", TRUE, "abc");

  system("pause");

  return 0;
}
</code>```

Can anybody explain how does work here funtion overload resolving?
 The surprising thing is there;

```<code>  //FnVariadic(IDS_MYSTR, FALSE, "abc"); //???
  FnVariadic(IDS_MYSTR, TRUE, "abc");    //???
</code>```

Second one compiles but not the first one.

(Commented lines mean does not compile.)

I'm using VS2017, and it seems;

First 3 calls uses void FnVariadic(const bool bOption, const long nIDS, ...) and last 2 calls uses void FnVariadic(const bool bOption, const char *pStr, ...)

It is also intresting there. What i expected is that the overloads without boolean parameter should be called.

答:
Ellipses are the last resort in overload resolution, if there is a better match then the function call will be resolved to that match.  Your function calls (non commented) all involve an integer literal as the first argument.  And since your macros, when replaced are all viable candidates for conversions to bool, you have two candidates

```<code>void FnVariadic(const bool bOption, const long nIDS, ...)
void FnVariadic(const bool bOption, const char *pStr, ...)
</code>```

And then in the first three you provide integer literals as the second argument.  So the first overload between the two above is called.  And in the last 2 you provide string literals (which are decayable to const char*) and therefore the second overload is called between the two above.

As to why the commented lines do not compile

```<code>// FnVariadic(IDS_MYSTR, FALSE, "abc"); //???
</code>```

This does not compile because the second argument is ambiguous, a 0 has special meaning unfortunately, it can resolve to both a const char* as well as a const long

```<code>// FnVariadic("abc%d%s", FALSE, "abc");
</code>```

Same for this one, the FALSE is ambiguous

```<code>// FnVariadic("abc%d%s", TRUE, "abc");
</code>```

Here the conversion to bool for "abc%d%s" and the matching of "abc" to the ellipses has the same precedence, and therefore it is ambiguous.

For your reference, it is almost always better to use compile time variadic templates over C style variadics.

Body:
#define FALSE 0
#define TRUE  1

#define IDS_MYSTR 123

void FnVariadic(const long nIDS, ...)
{
  std::cout << "WITHOUT option IDS" << std::endl;
}

void FnVariadic(const bool bOption, const long nIDS, ...)
{
  std::cout << "WITH option IDS" << std::endl;
}

void FnVariadic(const char *pStr, ...)
{
  std::cout << "WITHOUT option STR" << std::endl;
}

void FnVariadic(const bool bOption, const char *pStr, ...)
{
  std::cout << "WITH option STR" << std::endl;
}

int main()
{
  FnVariadic(FALSE, IDS_MYSTR, "abc");
  //FnVariadic(IDS_MYSTR, FALSE, "abc"); //???
  FnVariadic(TRUE, IDS_MYSTR, "abc");
  FnVariadic(IDS_MYSTR, TRUE, "abc");    //???

  FnVariadic(FALSE, "abc%s", "abc");
  //FnVariadic("abc%d%s", FALSE, "abc");
  FnVariadic(TRUE, "abc%s", "abc");
  //FnVariadic("abc%d%s", TRUE, "abc");

  system("pause");

  return 0;
}

Can anybody explain how does work here funtion overload resolving?
 The surprising thing is there;

  //FnVariadic(IDS_MYSTR, FALSE, "abc"); //???
  FnVariadic(IDS_MYSTR, TRUE, "abc");    //???

Second one compiles but not the first one.

(Commented lines mean does not compile.)

I'm using VS2017, and it seems;

First 3 calls uses void FnVariadic(const bool bOption, const long nIDS, ...) and last 2 calls uses void FnVariadic(const bool bOption, const char *pStr, ...)

It is also intresting there. What i expected is that the overloads without boolean parameter should be called.

Body:
Ellipses are the last resort in overload resolution, if there is a better match then the function call will be resolved to that match.  Your function calls (non commented) all involve an integer literal as the first argument.  And since your macros, when replaced are all viable candidates for conversions to bool, you have two candidates

void FnVariadic(const bool bOption, const long nIDS, ...)
void FnVariadic(const bool bOption, const char *pStr, ...)

And then in the first three you provide integer literals as the second argument.  So the first overload between the two above is called.  And in the last 2 you provide string literals (which are decayable to const char*) and therefore the second overload is called between the two above.

As to why the commented lines do not compile

// FnVariadic(IDS_MYSTR, FALSE, "abc"); //???

This does not compile because the second argument is ambiguous, a 0 has special meaning unfortunately, it can resolve to both a const char* as well as a const long

// FnVariadic("abc%d%s", FALSE, "abc");

Same for this one, the FALSE is ambiguous

// FnVariadic("abc%d%s", TRUE, "abc");

Here the conversion to bool for "abc%d%s" and the matching of "abc" to the ellipses has the same precedence, and therefore it is ambiguous.

For your reference, it is almost always better to use compile time variadic templates over C style variadics.


问:
jqGrid Unload and jqGrid Destroy
I'm having an issue on jqGrid Unload and Destroy functions.

I have called jqGrid Unload and re-create the jqGrid. However, the row ID still running. For example, I have added 2 rows(ID: 0 and 1) into jqGrid(1st time), then Unload and re-create the jqGrid(2nd time) but when I'm inserting a new row of data, the row ID is 2 instead of 0.

I have also tried jqGrid Destroy but I'm not able to re-create the jqGrid through calling my function of jqGrid creation.

The following is my codes to Unload and re-create:

$.jgrid.gridUnload("#jqgrid");
    alert("Un load");
    loadScript("js/plugin/jqgrid/grid.locale-en.min.js", pagefunction);```

答:
Please specify the version used in order to get correct answer. GridUnload function was modified hard in our Guriddo jqGrid release, where the old one has a lot of problems.

Kind Regards

Title: jqGrid Unload and jqGrid Destroy


问:
CJ Date: Classic VB Wizard Upgrade or Should Re-design?
Should I run a classic VB6 app thru the upgrade wizard in VS08 or should I re-design it from scratch.

The database is a mess.

Originally designed in ACCESS and imported to MS SQL SERVER.

The main entities are e.g. ROLLER_SKATES and RENTALS. If you would like to rent a pair of roller skates you can. So this more or less comprises an Inventory system for the roller skates.

Now you have 2 different skating rings. Skate-B1 and Skate-Z9, and you keep redundant and duplicate data from the previously mentioned entities in the skating ring tables as well.

It's a nightmare.

At least the tables have row ID's. But no explicit foreign keys, just implicit columns identically named that "seem" to correspond to each other. But the rest of the table's attributes all default to NULL.

Considering what C.J Date says about Types in his book SQL and the Relation Model, isn't it desirable to have CHECK CONSTRAINTS on attributes?

And, the data is all over the place, e.g., Roller skate serial number is G123 and then in another instance it is G-123. Get the drift?

What should I do?

答:
The more complicated the project, the LESS likely you'll want to just upgrade and continue as is.

.Net provides so many more features than VB6 did, and while sure, it'll basically run vb6 code, there's no point in upgrading to .net if you're not actually going to USE .net and its features.

If the app is as messy as you say, converting to .net is a great time to both redesign to remove old inefficiencies and logical goofiness, and leverage the new things you're allowed in .net.  Even if it's not a TOTAL redesign, at least thinking about the app in terms of .net will improve it.

Unless the application is trivial in size/complexity, redo it.  And if the app isn't large or complres... redo it :)


问:
svg background-size in pixels displaying wrong on Win 10 Chrome
I've created a svg image:

```<code><svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 6 6"><style>.st0{opacity:.4;fill:#61ffb0;enable-background:new}</style><path class="st0" d="M0 0h1v1H0z"/></svg>
</code>```

I've then used it as a background of a div:

```<code>.dotted_bg_dark {
    background-image: url(img/pattern-green.svg);
    background-size: 6px;
}

.darkbg {
    background-color: #212734;
    color: #fff;
}

<div class="darkbg dotted_bg_dark" style="height:500px;">Hello World</div>
</code>```

This is displayed correctly (Google Chrome on MacOS):

However, on Google Chrome on Windows 10 does this (note the diagonal scan line):

Why is this happening and how do I fix it?

答:
Open your .svg file, find the  tag at the beginning and add the following property inside it: </p>

```<code>preserveAspectRatio="none"
</code>```

<p>[Source][http://www.yootheme.com/support/question/6801?order=modified]</p>

Body:
I've created a svg image:

<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 6 6"><path class="st0" d="M0 0h1v1H0z"/></svg>

I've then used it as a background of a div:

.dotted_bg_dark {
    background-image: url(img/pattern-green.svg);
    background-size: 6px;
}

.darkbg {
    background-color: #212734;
    color: #fff;
}

Hello World

This is displayed correctly (Google Chrome on MacOS):

However, on Google Chrome on Windows 10 does this (note the diagonal scan line):

Why is this happening and how do I fix it?

Body:
Open your .svg file, find the  tag at the beginning and add the following property inside it:

preserveAspectRatio="none"

[Source][http://www.yootheme.com/support/question/6801?order=modified]


问:
javascript bootstrap-multiselect get all selected values on button click
I want to get all selected values of bootstrap-multiselect on button click.

My JSP page code is given below

```<code><script type="text/javascript">
    $(document).ready(function() {
        $('#ddlPermission').multiselect({
            buttonWidth : '100%',
            maxHeight : 100,
            includeSelectAllOption : true,
            dropRight : true
        });
    });

    function myFunction() {
        var allVal=$("ddlPermission").val();
        alert(allVal);
        return false;
    }
</script>
<body>
    <select id="ddlPermission" multiple="multiple" name="permission_ddl">
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        <option value="D">D</option>
    </select>
    <input type="submit" name="btnSubmit" id="btnSubmit" onclick="myFunction()" class="button active" value="Submit">
</body>
</code>```

I am using Java JSP.

答:
```<code>$(".buttonClass").click(function(){

    var selectedText = [];
    var selectedValues = [];
    $('#ddlPermission :selected').each(function(i, value){
        selectedValues[i] = value;
        selectedText[i] = $(value).text();

    });

});
</code>```

selectedValues array will contain all the values of the selected options,

selectedText array will contain all the text of the selected options

Body:
I want to get all selected values of bootstrap-multiselect on button click.

My JSP page code is given below

    <select id="ddlPermission" multiple="multiple" name="permission_ddl">
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        <option value="D">D</option>
    </select>
    <input type="submit" name="btnSubmit" id="btnSubmit" onclick="myFunction()" class="button active" value="Submit">

I am using Java JSP.

Body:
$(".buttonClass").click(function(){

    var selectedText = [];
    var selectedValues = [];
    $('#ddlPermission :selected').each(function(i, value){
        selectedValues[i] = value;
        selectedText[i] = $(value).text();

    });

});

selectedValues array will contain all the values of the selected options,

selectedText array will contain all the text of the selected options


问:
How to count function calls using decorators?
I'm refreshing my memory about some python features that I didn't get yet, I'm learning from this python tutorial and there's an example that I don't fully understand. It's about a decorator counting calls to a function, here's the code:

```<code>def call_counter(func):
    def helper(x):
        helper.calls += 1
        return func(x)
    helper.calls = 0
    return helper

@call_counter
def succ(x):
    return x + 1

if __name__ == '__main__':
    print(succ.calls)
    for i in range(10):
        print(succ(i))
    print(succ.calls)
</code>```

What I don't get here is why do we increment the calls of the function wrapper (helper.calls += 1) instead of the function calls itself, and why does it actually working?

答:
When you decorate a function you "substitute" you're function with the wrapper.

In this example, after the decoration, when you call succ you are actually calling helper. So if you are counting calls you have to increase the helper calls.

You can check that once you decorate a function the name is binded tho the wrapper by checking the attribute _name_ of the decorated function:

```<code>def call_counter(func):
    def helper(*args, **kwargs):
        helper.calls += 1
        print(helper.calls)
        return func(*args, **kwargs)
    helper.calls = 0
    return helper

@call_counter
def succ(x):
    return x + 1

succ(0)
>>> 1
succ(1)
>>> 2
print(succ.__name__)
>>> 'helper'
print(succ.calls)
>>> 2
</code>```

Body:
I'm refreshing my memory about some python features that I didn't get yet, I'm learning from this python tutorial and there's an example that I don't fully understand. It's about a decorator counting calls to a function, here's the code:

def call_counter(func):
    def helper(x):
        helper.calls += 1
        return func(x)
    helper.calls = 0
    return helper

@call_counter
def succ(x):
    return x + 1

if __name__ == '__main__':
    print(succ.calls)
    for i in range(10):
        print(succ(i))
    print(succ.calls)

What I don't get here is why do we increment the calls of the function wrapper (helper.calls += 1) instead of the function calls itself, and why does it actually working?

Body:
When you decorate a function you "substitute" you're function with the wrapper.

In this example, after the decoration, when you call succ you are actually calling helper. So if you are counting calls you have to increase the helper calls.

You can check that once you decorate a function the name is binded tho the wrapper by checking the attribute _name_ of the decorated function:

def call_counter(func):
    def helper(*args, **kwargs):
        helper.calls += 1
        print(helper.calls)
        return func(*args, **kwargs)
    helper.calls = 0
    return helper

@call_counter
def succ(x):
    return x + 1

succ(0)
>>> 1
succ(1)
>>> 2
print(succ.__name__)
>>> 'helper'
print(succ.calls)
>>> 2


问:
Change text from input id
I'm trying to change the text of whatever is existing with whatever is typed in the input. I try to take it from the id="text" but it doesn't work and just displays text.</p>

```<code><input type="text" class="form-control" id="text" placeholder="Type your text here.....">

<div class="form-group">
    <button>submit</button>
</div>
<div class="form-group" id="response">
    ```Type some text in the above text field, then log the text out here on button click```
</div>

<script>
    $('button').click(function() {
        $("#response").text("#text");
    });
</script>
</code>```

答:
As of now you are just passing string #text thus it is displayed. Use .val()to get the value from input, then set it.

```<code> $("#response").text($("#text").val());
</code>```

Title: Change text from input id

Body:
I'm trying to change the text of whatever is existing with whatever is typed in the input. I try to take it from the id="text" but it doesn't work and just displays text.

<input type="text" class="form-control" id="text" placeholder="Type your text here.....">

    <button>submit</button>

Type some text in the above text field, then log the text out here on button click

Body:
As of now you are just passing string #text thus it is displayed. Use .val()to get the value from input, then set it.

 $("#response").text($("#text").val());


问:
Equivalent of Index options (using index) in Oracle to SQL Server 2014
I need to move the data from Oracle database to MS SQL Server 2014.
But I got the problem with this "USING INDEX" statement which help me in oracle to add some constraint. I would like to know if someone could provide me and equivalence of "USING INDEX" in Sql Server.</p>

```<code>CONSTRAINT "MESSAGE_LOG_RECORD_PK" PRIMARY KEY ("RECORD_NO")
**USING INDEX** PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1   BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)   TABLESPACE "DATA"  ENABLE,
</code>```

答:
It seems using index creates index in specified table space as per the parameters you specified..

so you can do below while creating the table,so that sql server will configure index as per default parameters

```<code>create table t1
(
id int not null primary key
)
</code>```

or else you can use below syntax to add constraint to table once table is created

```<code>CREATE CLUSTERED INDEX [indxname] ON [dbo].[table1]
(
    id
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
</code>```

if you leave filegroup option,it will create the index in same filegroup as table is created

I suggest using the first approach and leave defaults or else you can explore the options here :https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql

Body:
I need to move the data from Oracle database to MS SQL Server 2014.
But I got the problem with this "USING INDEX" statement which help me in oracle to add some constraint. I would like to know if someone could provide me and equivalence of "USING INDEX" in Sql Server.

CONSTRAINT "MESSAGE_LOG_RECORD_PK" PRIMARY KEY ("RECORD_NO")
**USING INDEX** PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1   BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)   TABLESPACE "DATA"  ENABLE,

Body:
It seems using index creates index in specified table space as per the parameters you specified..

so you can do below while creating the table,so that sql server will configure index as per default parameters

create table t1
(
id int not null primary key
)

or else you can use below syntax to add constraint to table once table is created

CREATE CLUSTERED INDEX [indxname] ON [dbo].[table1]
(
    id
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

if you leave filegroup option,it will create the index in same filegroup as table is created

I suggest using the first approach and leave defaults or else you can explore the options here :https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql


答:
As @Shaggi already pointed out. Acc to standard,

Before nullptr was introduced, zero (0) was used as a notation for the
  null pointer. For example:

```<code>int* x = 0; // x gets the value nullptr
</code>```

No object is allocated with the address 0, and 0 (the all-zeros bit
  pattern) is the most common representation of nullptr. Zero (0) is an
  int. However, the standard conversions (§10.5.2.3) allow 0 to be used
  as a constant of pointer or pointer-to-member type

```<code>FnVariadic(IDS_MYSTR, FALSE, "abc");
                        ^~~~const char * OR const long. This is ambiguous.
</code>```

as you have both

```<code>void FnVariadic(const bool bOption, const long nIDS, ...)
void FnVariadic(const bool bOption, const char *pStr, ...)
</code>```

Title: How does work function overload resolving with variadic arguments?

Body:
As @Shaggi already pointed out. Acc to standard,

Before nullptr was introduced, zero (0) was used as a notation for the
  null pointer. For example:

int* x = 0; // x gets the value nullptr

No object is allocated with the address 0, and 0 (the all-zeros bit
  pattern) is the most common representation of nullptr. Zero (0) is an
  int. However, the standard conversions (§10.5.2.3) allow 0 to be used
  as a constant of pointer or pointer-to-member type

FnVariadic(IDS_MYSTR, FALSE, "abc");
                        ^~~~const char * OR const long. This is ambiguous.

as you have both

void FnVariadic(const bool bOption, const long nIDS, ...)
void FnVariadic(const bool bOption, const char *pStr, ...)


答:
Maybe this way:

```<code>SELECT *
  FROM Log_Customer
 WHERE Customer_Id = 2
   AND Log_Id = (SELECT Max(Log_Id)
                   FROM Log_Customer
                  WHERE Customer_Id = 2)
</code>```

A sub-select usually isn't bad as far as the execution plan is concerned.

Title: what will be the simple mysql query for this

Body:
I want to get the customer info where customer id should be 2 and the log_id should be maximum value
i tried below query but it is fetching first record found.

What will be the simple query

mysql> select * from log_customer where customer_id =2 group by customer_id having max(log_id);
+--------+------------+-------------+---------------------+-----------+----------+
| log_id | visitor_id | customer_id | login_at            | logout_at | store_id |
+--------+------------+-------------+---------------------+-----------+----------+
|      2 |         56 |           2 | 2010-02-19 19:34:45 | NULL      |        1 |
+--------+------------+-------------+---------------------+-----------+----------+
1 row in set (0.00 sec)

mysql> select * from log_customer where customer_id =2 limit 5;
+--------+------------+-------------+---------------------+---------------------+----------+
| log_id | visitor_id | customer_id | login_at            | logout_at           | store_id |
+--------+------------+-------------+---------------------+---------------------+----------+
|      2 |         56 |           2 | 2010-02-19 19:34:45 | NULL                |        1 |
|      3 |        114 |           2 | 2010-02-23 17:31:55 | NULL                |        1 |
|     31 |       1854 |           2 | 2010-03-08 18:31:28 | 2010-03-08 18:56:49 |        1 |
|     32 |       1992 |           2 | 2010-03-09 01:12:43 | NULL                |        1 |
|     33 |       2304 |           2 | 2010-03-09 14:42:39 | NULL                |        1 |
+--------+------------+-------------+---------------------+---------------------+----------+

Please do not suggest order by log_id desc I don't want to get in this way

Body:
Maybe this way:

SELECT *
  FROM Log_Customer
 WHERE Customer_Id = 2
   AND Log_Id = (SELECT Max(Log_Id)
                   FROM Log_Customer
                  WHERE Customer_Id = 2)

A sub-select usually isn't bad as far as the execution plan is concerned.


问:
Python: Why my function returns None and then executes
So, I have a function which basically does this:

```<code>import os
import json
import requests
from openpyxl import load_workbook

def function(data):
    statuslist = []
    for i in range(len(data[0])):
        result = performOperation(data[0][i])
        if result in satisfying_results:
            print("its okay")
            statuslist.append("Pass")
        else:
            print("absolutely not okay")
            statuslist.append("Fail" + result)
    return statuslist
</code>```

Then, I invoke the function like this (I've added error handling to check what will happen after stumbling upon the reason for me asking this question), and was actually amazed by the results, as the function returns None, and then executes:

```<code>statuslist = function(data)
print(statuslist)
try:
    for i in range(len(statuslist)):
        anotherFunction(i)
        print("Confirmation that it is working")
except TypeError:
    print("This is utterly nonsense I think")
</code>```

The output of the program is then as follows:

```<code>None
This is utterly nonsense I think
its okay
its okay
its okay
absolutely not okay
its okay
</code>```

There is only single return statement at the end of the function, the function is not recursive, its pretty straightforward and top-down(but parses a lot of data in the meantime).

From the output log, it appears that the function first returns None, and then is properly executed. I am puzzled, and I were unable to find any similar problems over the internet (maybe I phrase the question incorrectly).
Even if there were some inconsistency in the code, I'd still expect it to return [] instead.

After changing the initial list to statuslist = ["WTF"], the return is [].
To rule out the fact that I have modified the list in some other functions performed in the function(data), I have changed the name of the initial list several times - the results are consistently beyond my comprehension

I will be very grateful on tips in debugging the issue. Why does the function return the value first, and is executed after?

答:
While being unable to write the code which would at the same time present what happened in my code in full spectrum, be readable, and wouldn't interfere with no security policies of the company, I have re-wrote it in a simpler form (the original code has been written while I had 3 months of programming experience), and the issue does not reproduce anymore. I guess there had be some level of nesting of functions that I have misinterpreted, and this re-written code, doing pretty much the same, correctly returns me the expected list.

Thank you everyone for your time and suggestions.

So, the answer appears to be: You do not understand your own code, make it simpler.

Body:
So, I have a function which basically does this:

import os
import json
import requests
from openpyxl import load_workbook

def function(data):
    statuslist = []
    for i in range(len(data[0])):
        result = performOperation(data[0][i])
        if result in satisfying_results:
            print("its okay")
            statuslist.append("Pass")
        else:
            print("absolutely not okay")
            statuslist.append("Fail" + result)
    return statuslist

Then, I invoke the function like this (I've added error handling to check what will happen after stumbling upon the reason for me asking this question), and was actually amazed by the results, as the function returns None, and then executes:

statuslist = function(data)
print(statuslist)
try:
    for i in range(len(statuslist)):
        anotherFunction(i)
        print("Confirmation that it is working")
except TypeError:
    print("This is utterly nonsense I think")

The output of the program is then as follows:

None
This is utterly nonsense I think
its okay
its okay
its okay
absolutely not okay
its okay

There is only single return statement at the end of the function, the function is not recursive, its pretty straightforward and top-down(but parses a lot of data in the meantime).

From the output log, it appears that the function first returns None, and then is properly executed. I am puzzled, and I were unable to find any similar problems over the internet (maybe I phrase the question incorrectly).
Even if there were some inconsistency in the code, I'd still expect it to return [] instead.

After changing the initial list to statuslist = ["WTF"], the return is [].
To rule out the fact that I have modified the list in some other functions performed in the function(data), I have changed the name of the initial list several times - the results are consistently beyond my comprehension

I will be very grateful on tips in debugging the issue. Why does the function return the value first, and is executed after?


问:
generate dynamic variable name in for loop php
I am trying to generate variable name dynamically in php for loop.
I want call a function within for loop and want to pass iterated values.
What I tried is:

```<code>for ($i=1, $j=1; $i<=16 ; $i++, $j++) {
    $a='arrtreelevel_1';
    $b='0';
    $newname = $a.$j.$b;
    echo $newname,"<br>";
    echo $arrtreelevel_1[0];
    $arrtreelevel_2.$i = profiledetails($newname);
}
</code>```

My problem is '$newname' variable printing $arrtreelevel_1[0] as a text not taking the value, and $arrtreelevel_11[0] returns the actual value.
I tried with echo ${'arrtreelevel_1$i'} also which printing nothing. Assist me with any solution please.

Thanks in advance.

答:
you need to use double quotes instead of single quotes </p>

```<code>${"arrtreelevel_2$i"}=profiledetails($newname);
</code>```

Body:
I am trying to generate variable name dynamically in php for loop.
I want call a function within for loop and want to pass iterated values.
What I tried is:

for ($i=1, $j=1; $i<=16 ; $i++, $j++) {
    $a='arrtreelevel_1';
    $b='0';
    $newname = $a.$j.$b;
    echo $newname,"
";
    echo $arrtreelevel_1[0];
    $arrtreelevel_2.$i = profiledetails($newname);
}

My problem is '$newname' variable printing $arrtreelevel_1[0] as a text not taking the value, and $arrtreelevel_11[0] returns the actual value.
I tried with echo ${'arrtreelevel_1$i'} also which printing nothing. Assist me with any solution please.

Thanks in advance.

Body:
you need to use double quotes instead of single quotes

${"arrtreelevel_2$i"}=profiledetails($newname);


问:
Trying to use a numericupdown not in a void
I am trying to make an integer = numericupdown not within a method. What I am trying to say is I want to initialize an integer that can be used every where in the main form.

```<code>int number1 = Convert.ToInt32(numericUpDown1.Value);
</code>```

I want to define it before I call any events so I can use it everywhere. Thanks

答:
I see at least 2 options:

1: declare it as a field and initialize in constructor after InitializeCompoenent()

```<code>int number1;
public MyForm()
{
    InitializeComponent();
    number1 = Convert.ToInt32(numericUpDown1.Value);
}
</code>```

2: Create a property returning what you want

```<code>int number1
{
    get { return Convert.ToInt32(numericUpDown1.Value); }
}
</code>```

Body:
I am trying to make an integer = numericupdown not within a method. What I am trying to say is I want to initialize an integer that can be used every where in the main form.

int number1 = Convert.ToInt32(numericUpDown1.Value);

I want to define it before I call any events so I can use it everywhere. Thanks

Body:
I see at least 2 options:

1: declare it as a field and initialize in constructor after InitializeCompoenent()

int number1;
public MyForm()
{
    InitializeComponent();
    number1 = Convert.ToInt32(numericUpDown1.Value);
}

2: Create a property returning what you want

int number1
{
    get { return Convert.ToInt32(numericUpDown1.Value); }
}


问:
Which is better in umbraco elasticsearch or lucene
I understand that generally speaking Elastic search is better to use in most cases but i would like to know specifically for Umbraco, whether it is as good to use or not? Or if lucene is better </p>

答:
I've not use elastic search before, but I use Umbraco a lot and I use lucene, mainly via Examine which uses lucene.

Read about Examine here https://our.umbraco.org/documentation/reference/searching/examine/

See an example of some advanced search I set up in Umbraco using Examine here
http://www.codeshare.co.uk/blog/how-to-search-by-document-type-and-property-in-umbraco/


问:
Call different servlets based on User input
Is this feasible technically?

I have a jsp page with a text value and submit button.

Single jsp is associated with multiple servlets.

User gives value in text value, that is servlet name.

Based on that textvalue, the servlet has to be called.

Example

Jsp

servelt name: * user input*
submit

Servlet1, servlet 2, servlet3 --> associated with jsp (is that first of all doable)

then if user enters: servlet1 as servlet name, then only that servlet has to be called.

答:
Use jquery like @Scary Wombat suggested, it's very helpful.

Click of submit button in your form will have to change action attribute of the form.

You can do something like this:

Note: Servlet resources are unavailable, I used sample names.

$("#submitBtn").click (function () {
alert($("#form1").attr("action")+" before");
$("#form1").attr("action",$("#className").val());
alert($("#form1").attr("action")+" after");
$("#form1").submit();
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" action="Class1">
<input type="text" id="className"/>
<input type="submit" value="submit" id="submitBtn">
</form></code>```

Body:
Use jquery like @Scary Wombat suggested, it's very helpful.

Click of submit button in your form will have to change action attribute of the form.

You can do something like this:

Note: Servlet resources are unavailable, I used sample names.

$("#submitBtn").click (function () {
alert($("#form1").attr("action")+" before");
$("#form1").attr("action",$("#className").val());
alert($("#form1").attr("action")+" after");
$("#form1").submit();
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" action="Class1">
<input type="text" id="className"/>
<input type="submit" value="submit" id="submitBtn">
</form>


问:
How to avoid duplicate "using" code
I have a wcf api and wish to wrap all requests inside a transaction

Currently my code looks like this in each endpoint

```<code>public MyCompleteList ReadOrganisations()
    {
        MyCompleteList resp = new MyCompleteList ();
        try
        {
            using (TransactionScope scope = new TransactionScope())
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    DC_Base browser_request = new DC_Base(PROJECT);
                    browser_request.cmd_user_id = coreDb.GetUserIDFromLoginName(PROJECT,
                        HttpContext.Current.User.Identity.Name);
                    resp =
                        new MyCompleteList (coreSc.User_Read_All_Organisations(browser_request, utils,
                            validation, coreSc, coreDb));
                    scope.Complete();
                }
                else
                {
                    resp.SetResponseNotLoggedIn();
                }

            }
        }
        catch (TransactionAbortedException ex)
        {
            resp.SetResponseServerError();
        }
        catch (ApplicationException ex)
        {
            resp.SetResponseServerError();
        }
        return resp;
    }
</code>```

As you can see if I am to use the "using" transaction scope part in every endpoint (approx 300) its going to be a lot of duplicated code.

is there anyway to reduce the amount of duplication?

答:
1- Create a ServiceBase class as follows

```<code>public class ServiceBase
    {

       protected void ExecuteOperation(Action codetoExecute)
        {
            try
            {
                 using (TransactionScope scope = new TransactionScope())
                {
                    codetoExecute.Invoke();
                    scope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                // handle exception
            }
            catch (ApplicationException ex)
            {
                // handle exception
            }
        }
    }
</code>```

2- Each new service must inherits from ServiceBase and call ExecuteOperation instead. Code as follows:

```<code>ExecuteOperation(() =>
            {
                 // Custom code here
            });
</code>```

3- Atomic transactions are useful when executing operations that dont expect results in return.

Title: How to avoid duplicate "using" code

Body:
I have a wcf api and wish to wrap all requests inside a transaction

Currently my code looks like this in each endpoint

public MyCompleteList ReadOrganisations()
    {
        MyCompleteList resp = new MyCompleteList ();
        try
        {
            using (TransactionScope scope = new TransactionScope())
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    DC_Base browser_request = new DC_Base(PROJECT);
                    browser_request.cmd_user_id = coreDb.GetUserIDFromLoginName(PROJECT,
                        HttpContext.Current.User.Identity.Name);
                    resp =
                        new MyCompleteList (coreSc.User_Read_All_Organisations(browser_request, utils,
                            validation, coreSc, coreDb));
                    scope.Complete();
                }
                else
                {
                    resp.SetResponseNotLoggedIn();
                }

            }
        }
        catch (TransactionAbortedException ex)
        {
            resp.SetResponseServerError();
        }
        catch (ApplicationException ex)
        {
            resp.SetResponseServerError();
        }
        return resp;
    }

As you can see if I am to use the "using" transaction scope part in every endpoint (approx 300) its going to be a lot of duplicated code.

is there anyway to reduce the amount of duplication?

Body:
1- Create a ServiceBase class as follows

public class ServiceBase
    {

       protected void ExecuteOperation(Action codetoExecute)
        {
            try
            {
                 using (TransactionScope scope = new TransactionScope())
                {
                    codetoExecute.Invoke();
                    scope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                // handle exception
            }
            catch (ApplicationException ex)
            {
                // handle exception
            }
        }
    }

2- Each new service must inherits from ServiceBase and call ExecuteOperation instead. Code as follows:

ExecuteOperation(() =>
            {
                 // Custom code here
            });

3- Atomic transactions are useful when executing operations that dont expect results in return.


答:
 $('button').click(function() {

    $("#response").text($("#text").val());

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="text" class="form-control" id="text" placeholder="Type your text here.....">

  <div class="form-group">
    <button>submit</button>
  </div>
  <div class="form-group" id="response">
    ```Type some text in the above text field, then log the text out here on button click```
  </div>

<script>

</script></code>```

Title: Change text from input id

Body:
 $('button').click(function() {

    $("#response").text($("#text").val());

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="text" class="form-control" id="text" placeholder="Type your text here.....">

  <div class="form-group">
    <button>submit</button>
  </div>
  <div class="form-group" id="response">
    <pre>Type some text in the above text field, then log the text out here on button click</pre>
  </div>

<script>

</script>


问:
laravel middleware within __construct
I'm using https://github.com/appstract/laravel-multisite which is working fine.

Within my controllers methods, I can var_dump current_site()  and the correct information is displayed.

My issue is that within my controller __construct method the current_site function returns null i.e the multi_site object hasn't yet been setup.

```<code>public function __construct()
{
    //this returns null
    var_dump(current_Site());
}

public function index()
{
    //this works
    var_dump(current_Site());
}
</code>```

I assuming the constructor is called before the routing has been done and therefore thats the issue, but I wanted to only call the current_site function once and have the controller know which site was being used from the start, so all methods etc would know.

I think this is just a lack of knowledge on my part rather than a code issue...any guidance ?

My route groups as like this

```<code>'domain' => 'dealer1.'.config('multisite.host'),
'as' => 'dealer1.',
'middleware' => 'site:dealer1'
</code>```

I know this is todo with middleware not being done before the __construct being called but should I call it by doing

```<code>  $this->middleware('CurrentSite');
</code>```

wWhat step should I do next?

Edit

I've changed my code to

```<code> public function __construct()
    {

        $this->middleware(function ($request, $next) {
            //this dumps correctly
            var_dump(current_Site() );
               $this->currentSite = current_Site();
            return $next($request);
        });
        //this is null
       //var_dump($this->currentSite);
       //die("here");

    }
</code>```

答:
You could try something like:

```<code>public function __construct()
{
    $this->middleware(function ($request, $next) {
        var_dump(current_Site());

        return $next($request);
    });
}
</code>```

https://laravel.com/docs/master/controllers#controller-middleware

Hope this helps!

Title: laravel middleware within __construct

Body:
I'm using https://github.com/appstract/laravel-multisite which is working fine.

Within my controllers methods, I can var_dump current_site()  and the correct information is displayed.

My issue is that within my controller __construct method the current_site function returns null i.e the multi_site object hasn't yet been setup.

public function __construct()
{
    //this returns null
    var_dump(current_Site());
}

public function index()
{
    //this works
    var_dump(current_Site());
}

I assuming the constructor is called before the routing has been done and therefore thats the issue, but I wanted to only call the current_site function once and have the controller know which site was being used from the start, so all methods etc would know.

I think this is just a lack of knowledge on my part rather than a code issue...any guidance ?

My route groups as like this

'domain' => 'dealer1.'.config('multisite.host'),
'as' => 'dealer1.',
'middleware' => 'site:dealer1'

I know this is todo with middleware not being done before the __construct being called but should I call it by doing

  $this->middleware('CurrentSite');

wWhat step should I do next?

Edit

I've changed my code to

 public function __construct()
    {

        $this->middleware(function ($request, $next) {
            //this dumps correctly
            var_dump(current_Site() );
               $this->currentSite = current_Site();
            return $next($request);
        });
        //this is null
       //var_dump($this->currentSite);
       //die("here");

    }

Body:
You could try something like:

public function __construct()
{
    $this->middleware(function ($request, $next) {
        var_dump(current_Site());

        return $next($request);
    });
}

https://laravel.com/docs/master/controllers#controller-middleware

Hope this helps!


问:
App freezing when clicked on done button after selecting row from UIPickerView
I have view consisting of UIPickerView and Done button and it is assigned as inputView to textField. After selecting any row from picker view and clicking Done app is un-expectingly freezing. I have attached stack trace screen shot at the time freeze. Please let know if this due something weird thread action.

答:
Finally this issue resolved. I had below code in my - (void)keyboardWillHide:(NSNotification *)notification notification method which was causing app to freeze.

```<code>    [UIView animateWithDuration:keyboardAnimationDuration.floatValue animations:^{

    self.tableView.contentInset = UIEdgeInsetsZero;

    self.tableView.scrollIndicatorInsets =  UIEdgeInsetsZero;

    }];
</code>```

App freeze issue is resolved after removing [UIView animateWithDuration:keyboardAnimationDuration.floatValue animations:^{}];

Finally, below code worked and now app is not freezing anymore.

```<code>    self.tableView.contentInset = UIEdgeInsetsZero;

    self.tableView.scrollIndicatorInsets =  UIEdgeInsetsZero;
</code>```

Body:
Finally this issue resolved. I had below code in my - (void)keyboardWillHide:(NSNotification *)notification notification method which was causing app to freeze.

    [UIView animateWithDuration:keyboardAnimationDuration.floatValue animations:^{

    self.tableView.contentInset = UIEdgeInsetsZero;

    self.tableView.scrollIndicatorInsets =  UIEdgeInsetsZero;

    }];

App freeze issue is resolved after removing [UIView animateWithDuration:keyboardAnimationDuration.floatValue animations:^{}];

Finally, below code worked and now app is not freezing anymore.

    self.tableView.contentInset = UIEdgeInsetsZero;

    self.tableView.scrollIndicatorInsets =  UIEdgeInsetsZero;


问:
Cannot drop tablespace in oracle
HI,

problem 1

When i try to drop the tablespace using drop tablespace command, it fails and error message is the tablespace not exist.

when i do select * from dba_tablespaces, i can see the tablespace name.

Problem 2
when i try to connect the oracle using aquadata, i get "connection failed:- no more data to read from socket"

please suggest

答:
"when i execute query select * from
  dba_tablespaces, the tablespace name
  is shown in lower case."

By default Oracle SQL is case insensitive.  That is, both of these statements are equivalent:

```<code>drop tablespace TS1 including contents
/

drop tablespace ts1 including contents
/
</code>```

However, when it comes to storing metadata Oracle uses UPPER CASE for object names.  This doesn't matter unless when we created the database objects we wrapped their names in double-quotes.  At that point Oracle becomes case sensitive.

It appears such is your situation.  So you need to issue the command with the tablespace name in double quote:

```<code>drop tablespace "ts1" including contents
/
</code>```

Title: Cannot drop tablespace in oracle

Body:
"when i execute query select * from
  dba_tablespaces, the tablespace name
  is shown in lower case."

By default Oracle SQL is case insensitive.  That is, both of these statements are equivalent:

drop tablespace TS1 including contents
/

drop tablespace ts1 including contents
/

However, when it comes to storing metadata Oracle uses UPPER CASE for object names.  This doesn't matter unless when we created the database objects we wrapped their names in double-quotes.  At that point Oracle becomes case sensitive.

It appears such is your situation.  So you need to issue the command with the tablespace name in double quote:

drop tablespace "ts1" including contents
/


问:
How to install Realm in android studio offline?
I want to install Realm in android studio without internet access . I want to download a file like a jar file and add it to my project . Is it possible , how ?</p>

答: You may download it from here https://bintray.com/realm/maven/realm-android-library/3.4.0#files/io%2Frealm%2Frealm-android-library%2F3.4.0


问:
Visualization & Dashboard return no results found, while discover tab successfully displays results?
I have a problem with Kibana: Dashboard and visualizations don't show any results!

As you can see in this screenshot, in the discover tab I get some results! Which means data exists in my index "as-*". right? But I used a trick in order to display this data :

1) I changed the range to "Today" ==> it shows no result found !

2) I clicked "New" button ==> then i get my data displayed!
Is there an other way "more proper" to get data displayed?

Then in the my dashboard (or visualization) I can't get any results!! even if the range is the same as discover tab!

I restarted Kibana ==> no changes!
I deleted as-* then I created it => no changes!

I'm using Curator to create daily index and logstash to index the data into ES!

I'm stuck here ! I ll be glad if you can help me figure it out !
Thank you very much!

答:
I am fairly new to elasticsearch and Kibana, but here are three mistakes that I made in the past:

Are you using the correct index? Make sure that the index you have chosen for the logs that are displayed on the visualise page and for the actual visualisations is the same.

Correct timeperiod: does the time period you have chosen contain the data you are looking for? Or did you happen to have zero logs during that time?

Correct filters and aggregations: when you were making the visualisations, did they show any results? Or were they empty from the beginning? Maybe one of your filters or aggregations is wrong and it's excluding the results you're expecting to see.

Not sure if this is any help, hope you've sold the problem by now :)


问:
Best practice for BAPI commit and rollback?
I am using C# to call BAPI to communicate with SAP. I am new to this topic so I want to clarify some of the concept.

Q1: If I call BAPI_GOODSMVT_CREATE, should I check RETURN table or MAT_DOC field of items table to see whether it is succeed or failed?

Q2: If it is failed, need I call BAPI_TRANSACTION_ROLLBACK, or just ignore it(because without BAPI_TRANSACTION_COMMIT, data will not be saved)?

Q3: I found sometimes, even if there is error message, if I continue call BAPI_TRANSACTION_COMMIT, the data will be saved. But sometimes it won't.

Thanks in advance.

答:
Check RETURN table. If it's OK, issue a BAPI_TRANSACTION_COMMIT with the WAIT flag. If it's not OK, issue a BAPI_TRANSACTION_ROLLBACK.

Check RETURN from BAPI_TRANSACTION_COMMIT as there may be errors there as well (for example a database update issue).


问:
Bitmap scaling while keeping centered
I'm developing an image viewer on embedded system(stm32f4) with multi-touch support. To put into perspective image viewer should have similar functionality like something you find on your smartphone.
I have completed the image scaling and pinch/zoom gesture recognition part. But it only scales from the source image origin coordinates. So if my origin(x,y[0, 0]) is top left then it will scale following that point. And if I want to look something up in bottom right corner I have to use pinch gesture and the move to location I want which is undesirable.Here's how it looks
http://i.imgur.com/IWR4wls.gifv
. It should follow center of 2 fingers.

How can I achieve scaling while following center of 2 fingers? My attempts to do it resulted in working but jumpy, shaky version basically unusable.

My scaling works by having source image always opened(in ram) taking source image [x,y] coordinates and rect i want to zoom [w,h] scaling that rect to display [w,h] and displaying it. Moving(pan gesture) is done by moving zoomRect [x,y] coordinates in source image. That means every time I move finger I have to move zoomedRect (increase [x,y]) scale that zoomedRect and display it. So fully scaled image is not being stored because of limited ram.

```<code>Source image width,height[640, 480]:
+-------------------------------+
|   zoomedRect                  |
|   +--------------+            |
|   |              |            |
|   |              |            |
|   |              |            |
|   |              |            |
|   |              |            |
|   +--------------+            |
|                               |
|                               |
|                               |
+-------------------------------+

I take zoomedRect i.e. x,y[50, 50] width,height[160, 120]
and scale it to display size w,h[640x480]
Display:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
+-------------------------------+
</code>```

Here's what I have/can calculate:

Center of 2 fingers.

Translate center of 2 fingers to source image(even when zoomed in).

Scale in fraction(1.32, 1.45...) and (source image width|height)/(zoomedRect width|height).

Edit:

I have tried to calculate center point when 2 fingers touched and then use that center for future calculations and that's the reason why all the jumping and shaking happen. But maybe there is an error on my side so I'll add some relevant code.
As I mentioned earlier I change zoomRect width, height to scale image

```<code>newWidth = tempWidth / scale;
newHeight = tempHeight / scale;
</code>```

So after zooming I need to also move near center and I do that by calculating how much scale changed
(lastWidth - newWidth)

```<code>newSourceX = newSourceX + ((int16_t)lastWidth - newWidth);
newSourceY = newSourceY + ((int16_t)lastHeight - newHeight);
</code>```

Now we need to stop at calculated center between the 2 fingers and not get out of bounds [0, 0]:

```<code>#define LIMIT(value, min, max) (value < min ? min : (value > max ? max : value))
newSourceX = LIMIT(newSourceX + ((int16_t)lastWidth - newWidth), 0, centerSourceX);
newSourceY = LIMIT(newSourceY + ((int16_t)lastHeight - newHeight), 0, centerSourceY);
</code>```

So far so good but it is not properly centered

```<code>Calculate center between two fingers on Display and translate to Source.
Because it's fully zoomed out(Source and Display are identical)
centers are also in identical positions.
Display/Source:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                centerPos      |
|                     *         |
|                               |
|                               |
+-------------------------------+

So if we zoom in zoomRect will be newWidth / 2 and newHeight / 2 further than needed.

Source:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                centerPos      |
|                     *---------+
|                     | zoomRect|
|                     |         |
+---------------------+---------+

To account for this I modify code as follows:
newSourceX = LIMIT(newSourceX + ((int16_t)lastWidth - newWidth), 0, centerSourceX - newWidth / 2);
newSourceY = LIMIT(newSourceY + ((int16_t)lastHeight - newHeight), 0, centerSourceY - newHeight / 2);

Success!!! Or not?

Source:
+-------------------------------+
|                               |
|                               |
|                               |
|             zoomRect          |
|                +---------+    |
|                |centerPos|    |
|                |     *   |    |
|                +---------+    |
|                               |
+-------------------------------+

When zooming from 1:1 it works perfectly but when I want to zoom again when
I'm zoomed in a little bit the "jump" happens because:
newSourceX + ((int16_t)lastWidth - newWidth) > centerSourceX - newWidth / 2
</code>```

Result: http://i.imgur.com/x1t6X2q.gifv

答:
You have source picture,  and source coordinates (x,y) are transformed in screen coordinates with affine transformation. I assume that scaling is uniform. At the beginning Scale=1;  dx, dy=0

```<code>ScrX = (x - dx) * Scale
ScrY = (y - dy) * Scale
</code>```

So we see piece of source image that was cut from dx,dy point and extended by Scale times.

Example for dx=1,dy=1, Scale=2. Left rect is source, right one is screen.

Let we begin (b prefix) zooming in screen positions of fingers (bx0, by0) and (bx1, by1) - opposite rectangle corners. And end (or intermediate) positions (e prefix)are (ex0, ey0) and (ex1, ey1)

Let diagonals of rectangle correspond to scale degree:

```<code>eScale = bScale * Sqrt(((ex1-ex0)^2 + (ey1-ey0)^2) / ((bx1-bx0)^2 + (by1-by0)^2))
//use Math.Hypot or Vector.Length if available
</code>```

So we have got new scale.

And we have beginning and ending central points

```<code> bcx = (bx0 + bx1) / 2
 bcy = (by0 + by1) / 2
 ecx = (ex0 + ex1) / 2
 ecy = (ey0 + ey1) / 2
</code>```

Both these screen points should correspond to the same source coordinate

```<code>bcx = (xx - bdx) * bScale
ecx = (xx - edx) * eScale
</code>```

excluding xx we get

```<code>edx = bdx + bcx / bScale - ecx / eScale
</code>```

and similar formula for edy

So we have got new shift parameters.

Title: Bitmap scaling while keeping centered

Body:
I'm developing an image viewer on embedded system(stm32f4) with multi-touch support. To put into perspective image viewer should have similar functionality like something you find on your smartphone.
I have completed the image scaling and pinch/zoom gesture recognition part. But it only scales from the source image origin coordinates. So if my origin(x,y[0, 0]) is top left then it will scale following that point. And if I want to look something up in bottom right corner I have to use pinch gesture and the move to location I want which is undesirable.Here's how it looks
http://i.imgur.com/IWR4wls.gifv
. It should follow center of 2 fingers.

How can I achieve scaling while following center of 2 fingers? My attempts to do it resulted in working but jumpy, shaky version basically unusable.

My scaling works by having source image always opened(in ram) taking source image [x,y] coordinates and rect i want to zoom [w,h] scaling that rect to display [w,h] and displaying it. Moving(pan gesture) is done by moving zoomRect [x,y] coordinates in source image. That means every time I move finger I have to move zoomedRect (increase [x,y]) scale that zoomedRect and display it. So fully scaled image is not being stored because of limited ram.

Source image width,height[640, 480]:
+-------------------------------+
|   zoomedRect                  |
|   +--------------+            |
|   |              |            |
|   |              |            |
|   |              |            |
|   |              |            |
|   |              |            |
|   +--------------+            |
|                               |
|                               |
|                               |
+-------------------------------+

I take zoomedRect i.e. x,y[50, 50] width,height[160, 120]
and scale it to display size w,h[640x480]
Display:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
+-------------------------------+

Here's what I have/can calculate:

Center of 2 fingers.

Translate center of 2 fingers to source image(even when zoomed in).

Scale in fraction(1.32, 1.45...) and (source image width|height)/(zoomedRect width|height).

Edit:

I have tried to calculate center point when 2 fingers touched and then use that center for future calculations and that's the reason why all the jumping and shaking happen. But maybe there is an error on my side so I'll add some relevant code.
As I mentioned earlier I change zoomRect width, height to scale image

newWidth = tempWidth / scale;
newHeight = tempHeight / scale;

So after zooming I need to also move near center and I do that by calculating how much scale changed
(lastWidth - newWidth)

newSourceX = newSourceX + ((int16_t)lastWidth - newWidth);
newSourceY = newSourceY + ((int16_t)lastHeight - newHeight);

Now we need to stop at calculated center between the 2 fingers and not get out of bounds [0, 0]:

#define LIMIT(value, min, max) (value < min ? min : (value > max ? max : value))
newSourceX = LIMIT(newSourceX + ((int16_t)lastWidth - newWidth), 0, centerSourceX);
newSourceY = LIMIT(newSourceY + ((int16_t)lastHeight - newHeight), 0, centerSourceY);

So far so good but it is not properly centered

Calculate center between two fingers on Display and translate to Source.
Because it's fully zoomed out(Source and Display are identical)
centers are also in identical positions.
Display/Source:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                centerPos      |
|                     *         |
|                               |
|                               |
+-------------------------------+

So if we zoom in zoomRect will be newWidth / 2 and newHeight / 2 further than needed.

Source:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                centerPos      |
|                     *---------+
|                     | zoomRect|
|                     |         |
+---------------------+---------+

To account for this I modify code as follows:
newSourceX = LIMIT(newSourceX + ((int16_t)lastWidth - newWidth), 0, centerSourceX - newWidth / 2);
newSourceY = LIMIT(newSourceY + ((int16_t)lastHeight - newHeight), 0, centerSourceY - newHeight / 2);

Success!!! Or not?

Source:
+-------------------------------+
|                               |
|                               |
|                               |
|             zoomRect          |
|                +---------+    |
|                |centerPos|    |
|                |     *   |    |
|                +---------+    |
|                               |
+-------------------------------+

When zooming from 1:1 it works perfectly but when I want to zoom again when
I'm zoomed in a little bit the "jump" happens because:
newSourceX + ((int16_t)lastWidth - newWidth) > centerSourceX - newWidth / 2

Result: http://i.imgur.com/x1t6X2q.gifv

Body:
You have source picture,  and source coordinates (x,y) are transformed in screen coordinates with affine transformation. I assume that scaling is uniform. At the beginning Scale=1;  dx, dy=0

ScrX = (x - dx) * Scale
ScrY = (y - dy) * Scale

So we see piece of source image that was cut from dx,dy point and extended by Scale times.

Example for dx=1,dy=1, Scale=2. Left rect is source, right one is screen.

Let we begin (b prefix) zooming in screen positions of fingers (bx0, by0) and (bx1, by1) - opposite rectangle corners. And end (or intermediate) positions (e prefix)are (ex0, ey0) and (ex1, ey1)

Let diagonals of rectangle correspond to scale degree:

eScale = bScale * Sqrt(((ex1-ex0)^2 + (ey1-ey0)^2) / ((bx1-bx0)^2 + (by1-by0)^2))
//use Math.Hypot or Vector.Length if available

So we have got new scale.

And we have beginning and ending central points

 bcx = (bx0 + bx1) / 2
 bcy = (by0 + by1) / 2
 ecx = (ex0 + ex1) / 2
 ecy = (ey0 + ey1) / 2

Both these screen points should correspond to the same source coordinate

bcx = (xx - bdx) * bScale
ecx = (xx - edx) * eScale

excluding xx we get

edx = bdx + bcx / bScale - ecx / eScale

and similar formula for edy

So we have got new shift parameters.


问:
Elegant Python function to convert CamelCase to snake_case?
Example:</p>

```<code>>>> convert('CamelCase')
'camel_case'
</code>```

答:
Avoiding libraries and regular expressions:

def camel_to_snake(s):
    return ''.join(['_'+c.lower() if c.isupper() else c for c in s]).lstrip('_')
```
<pre class="lang-py prettyprint-override"><code>>>> camel_to_snake('ThisIsMyString')
'this_is_my_string'
</code>```

Body:
Example:

>>> convert('CamelCase')
'camel_case'

Body:
Avoiding libraries and regular expressions:

def camel_to_snake(s):
    return ''.join(['_'+c.lower() if c.isupper() else c for c in s]).lstrip('_')

>>> camel_to_snake('ThisIsMyString')
'this_is_my_string'