问:
Why this SFINAE snippet is not working in g++, but working in MSVC?
In MSVC2017 this works fine, both static_asserts are NOT triggered as expected:

```<code>template <typename T>
struct do_have_size {
    template <typename = decltype(std::declval<T>().size())>
    static std::true_type check(T);
    static std::false_type check(...);
    using type = decltype(check(std::declval<T>()));
};

int main() {
    using TR = typename do_have_size<std::vector<int>>::type;
    using FL = typename do_have_size<int>::type;

    static_assert(std::is_same<TR, std::true_type>::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}
</code>```

However, if I compile in g++7.1 or clang 4.0 I get following compiler error:

```<code>In instantiation of 'struct do_have_size<int>':
20:39:   required from here
9:24: error: request for member 'size' in 'declval<do_have_size<int>::TP>()', which is of non-class type 'int'
</code>```

From my understanding of SFINAE, substition of true_type returning function should fail for int parameter and next function shall be chosen, like it is done in MSVC. Why clang and g++ are not compiling it at all?

I've compiled with -std=c++17 switch only, maybe something more is needed?

答:
I got it to work by using std::enable_if to SFINAE away the template version of check based on either the parameter or the return type. The condition I used was std::is_fundamental to exclude int, float and other non-class types from instantiating the template. I used the -std=c++1z flag to clang and gcc. I expect -std=c++14 should work too.

```<code>#include <type_traits>
#include <utility>
#include <vector>

template <typename T>
struct do_have_size {
    static std::false_type check(...);

    template <typename U = T, typename = decltype(std::declval<U>().size())>
    static std::true_type check(std::enable_if_t<!std::is_fundamental<U>::value, U>);

    // OR
    //template <typename U = T, typename = decltype(std::declval<U>().size())>
    //static auto check(U)
    //    -> std::enable_if_t<!std::is_fundamental<U>::value, std::true_type>;

    using type = decltype(check(std::declval<T>()));
};

int main() {
    using TR = typename do_have_size<std::vector<int>>::type;
    using FL = typename do_have_size<int>::type;

    static_assert(std::is_same<TR, std::true_type>::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}
</code>```

Body:
In MSVC2017 this works fine, both static_asserts are NOT triggered as expected:

template <typename T>
struct do_have_size {
    template <typename = decltype(std::declval<T>().size())>
    static std::true_type check(T);
    static std::false_type check(...);
    using type = decltype(check(std::declval<T>()));
};

int main() {
    using TR = typename do_have_size<std::vector<int>>::type;
    using FL = typename do_have_size<int>::type;

    static_assert(std::is_same
::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}

However, if I compile in g++7.1 or clang 4.0 I get following compiler error:

In instantiation of 'struct do_have_size<int>':
20:39:   required from here
9:24: error: request for member 'size' in 'declval<do_have_size<int>::TP>()', which is of non-class type 'int'

From my understanding of SFINAE, substition of true_type returning function should fail for int parameter and next function shall be chosen, like it is done in MSVC. Why clang and g++ are not compiling it at all?

I've compiled with -std=c++17 switch only, maybe something more is needed?

Body:
I got it to work by using std::enable_if to SFINAE away the template version of check based on either the parameter or the return type. The condition I used was std::is_fundamental to exclude int, float and other non-class types from instantiating the template. I used the -std=c++1z flag to clang and gcc. I expect -std=c++14 should work too.

#include <type_traits>
#include <utility>
#include <vector>

template <typename T>
struct do_have_size {
    static std::false_type check(...);

    template <typename U = T, typename = decltype(std::declval<U>().size())>
    static std::true_type check(std::enable_if_t<!std::is_fundamental<U>::value, U>);

    // OR
    //template <typename U = T, typename = decltype(std::declval<U>().size())>
    //static auto check(U)
    //    -> std::enable_if_t<!std::is_fundamental<U>::value, std::true_type>;

    using type = decltype(check(std::declval<T>()));
};

int main() {
    using TR = typename do_have_size<std::vector<int>>::type;
    using FL = typename do_have_size<int>::type;

    static_assert(std::is_same<TR, std::true_type>::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}


来源: stackexchange

问:
appwidget Never go to onUpdate
my Application widget Never go to the onUpdate function
i add 3000 mili for testings but except the first time you add it,
it never goes to the onUpdate function.

what am i doing wrong ?

my manifest file:

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="layout.ClockWidgetClass">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/clock_widget_class_info" />
    </receiver>
</application>
</code>```

my clockWidget:

```<code>/**
 * Implementation of App Widget functionality.
 */
public class ClockWidgetClass extends AppWidgetProvider {

    static void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager,
                                final int appWidgetId) {

        //getting shered prefrences
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String name = preferences.getString("randomString", "");
        if(!name.equalsIgnoreCase(""))
        {
            name = name;  /* Edit the value here*/
        }

        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.clock_widget_class);

        //set chosen design visible
        //set all visibility to 0
        views.setViewVisibility(R.id.AnalogClock0, View.INVISIBLE);
        views.setViewVisibility(R.id.AnalogClock1, View.INVISIBLE);
        views.setViewVisibility(R.id.AnalogClock2, View.INVISIBLE);
        views.setViewVisibility(R.id.AnalogClock3, View.INVISIBLE);

        //turning on the correct clock
        if (name.equals("1")) {
            views.setViewVisibility(R.id.AnalogClock0, View.VISIBLE);
        } else if (name.equals("2")) {
            views.setViewVisibility(R.id.AnalogClock1, View.VISIBLE);
        } else if (name.equals("3")) {
            views.setViewVisibility(R.id.AnalogClock2, View.VISIBLE);
        } else {
            views.setViewVisibility(R.id.AnalogClock3, View.VISIBLE);
        }

//        views.setTextViewText(R.id.appwidget_text, name);

        //updateting the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);

    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // Chain up to the super class so the onEnabled, etc callbacks get dispatched
        super.onReceive(context, intent);
        // Handle a different Intent
        Log.d("reciving", "onReceive()" + intent.getAction());

    }

}
</code>```

my Widget xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialKeyguardLayout="@layout/clock_widget_class"
    android:initialLayout="@layout/clock_widget_class"
    android:minHeight="110dp"
    android:minWidth="250dp"
    android:previewImage="@drawable/example_appwidget_preview"
    android:resizeMode="horizontal|vertical"
    android:updatePeriodMillis="3000"
    android:widgetCategory="home_screen"></appwidget-provider>
</code>```

答:
Never might not be correct. It just doesn't happen in the time you expect it to happen. With the documentation for updatePeriodMillis you'll find an important note:

Note: Updates requested with updatePeriodMillis will not be delivered more than once every 30 minutes.

So you might have to wait for this 30 minutes before another call to onUpdate() happens.

ContentLicense: CC BY-SA 3.0

Title: appwidget Never go to onUpdate

Body:
my Application widget Never go to the onUpdate function
i add 3000 mili for testings but except the first time you add it,
it never goes to the onUpdate function.

what am i doing wrong ?

my manifest file:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="layout.ClockWidgetClass">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/clock_widget_class_info" />
    </receiver>
</application>

my clockWidget:

/**
 * Implementation of App Widget functionality.
 */
public class ClockWidgetClass extends AppWidgetProvider {

    static void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager,
                                final int appWidgetId) {

        //getting shered prefrences
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String name = preferences.getString("randomString", "");
        if(!name.equalsIgnoreCase(""))
        {
            name = name;  /* Edit the value here*/
        }

        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.clock_widget_class);

        //set chosen design visible
        //set all visibility to 0
        views.setViewVisibility(R.id.AnalogClock0, View.INVISIBLE);
        views.setViewVisibility(R.id.AnalogClock1, View.INVISIBLE);
        views.setViewVisibility(R.id.AnalogClock2, View.INVISIBLE);
        views.setViewVisibility(R.id.AnalogClock3, View.INVISIBLE);

        //turning on the correct clock
        if (name.equals("1")) {
            views.setViewVisibility(R.id.AnalogClock0, View.VISIBLE);
        } else if (name.equals("2")) {
            views.setViewVisibility(R.id.AnalogClock1, View.VISIBLE);
        } else if (name.equals("3")) {
            views.setViewVisibility(R.id.AnalogClock2, View.VISIBLE);
        } else {
            views.setViewVisibility(R.id.AnalogClock3, View.VISIBLE);
        }

//        views.setTextViewText(R.id.appwidget_text, name);

        //updateting the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);

    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // Chain up to the super class so the onEnabled, etc callbacks get dispatched
        super.onReceive(context, intent);
        // Handle a different Intent
        Log.d("reciving", "onReceive()" + intent.getAction());

    }

}

my Widget xml file:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialKeyguardLayout="@layout/clock_widget_class"
    android:initialLayout="@layout/clock_widget_class"
    android:minHeight="110dp"
    android:minWidth="250dp"
    android:previewImage="@drawable/example_appwidget_preview"
    android:resizeMode="horizontal|vertical"
    android:updatePeriodMillis="3000"
    android:widgetCategory="home_screen"></appwidget-provider>


问:
Can't Select Checkbox, Selenium WebDriver
I am unable to select a checkbox with Selenium WebDriver in Java.
I tried by Xpath but no result.
WebDriver can't click on element.
I tried with Selenium IDE - recorder, no results.

Here it is - html code for checkbox

I try:

1.

```<code>driver.findElement(By.xpath(".//form[@id='placeOrderForm1']/div[@class='terms right']/label")).click();
</code>```

2.

```<code>driver.findElement(By.id("Terms1")).click();
</code>```

3.

```<code>driver.findElement(By.cssSelector("label")).click();
</code>```

4.

```<code>driver.findElement(By.xpath("//div[3]/form/div/input")).click();
</code>```

Nothing works.
Please help.

答:
Your code seems correct. Specially this one -

driver.findElement(By.id("Terms1")).click();

It might be possible the element you are clicking is not visible in the page scroll. Try to move to the element first and then click.

Try with this -

```<code>WebElement elem = driver.findElement(By.id("Term1"));
Actions action = new Actions(driver).
action.moveToElement(elem).click().build().perform();
</code>```

Hope this help.

Body:
I am unable to select a checkbox with Selenium WebDriver in Java.
I tried by Xpath but no result.
WebDriver can't click on element.
I tried with Selenium IDE - recorder, no results.

Here it is - html code for checkbox

I try:

1.

driver.findElement(By.xpath(".//form[@id='placeOrderForm1']/div[@class='terms right']/label")).click();

2.

driver.findElement(By.id("Terms1")).click();

3.

driver.findElement(By.cssSelector("label")).click();

4.

driver.findElement(By.xpath("//div[3]/form/div/input")).click();

Nothing works.
Please help.

Body:
Your code seems correct. Specially this one -

driver.findElement(By.id("Terms1")).click();

It might be possible the element you are clicking is not visible in the page scroll. Try to move to the element first and then click.

Try with this -

WebElement elem = driver.findElement(By.id("Term1"));
Actions action = new Actions(driver).
action.moveToElement(elem).click().build().perform();

Hope this help.


问:
Opencart 2.2.0 for each category/subcategory display ONLY third level categories in category module
This may be a duplicate, but which ever answer I found, didn't solve my problem.  I have category structure like this: Category->Subcategory->Sub sub category. In my category module, I managed to show the whole structure (Category->Subcategory->Subsub category). But what I need is only Subsub categories to show for each Category or subcategory. My  category.php module file looks like this:

```<code><?php
class ControllerModuleCategory extends Controller {
    public function index() {
        $this->load->language('module/category');

        $data['heading_title'] = $this->language->get('heading_title');

        if (isset($this->request->get['path'])) {
            $parts = explode('_', (string)$this->request->get['path']);
        } else {
            $parts = array();
        }

        if (isset($parts[0])) {
            $data['category_id'] = $parts[0];
        } else {
            $data['category_id'] = 0;
        }

        if (isset($parts[1])) {
            $data['child_id'] = $parts[1];
        } else {
            $data['child_id'] = 0;
        }

        $this->load->model('catalog/category');

        $this->load->model('catalog/product');

        $data['categories'] = array();

        $categories = $this->model_catalog_category->getCategories(0);

        foreach ($categories as $category) {
            $children_data = array();

            if ($category['category_id'] == $data['category_id']) {
                $children = $this->model_catalog_category->getCategories($category['category_id']);

                foreach($children as $child) {
                    $children_data_2 = array();

                    $children_2 = $this->model_catalog_category->getCategories($child['category_id']);

                    foreach ($children_2 as $child_2) {
    $filter_data = array(
        'filter_category_id'  => $child_2['category_id'],
        'filter_sub_category' => true
    );

    $children_data_2[] = array(
        'category_id' => $child_2['category_id'],
        'name'        => $child_2['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
        'href'        => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'] . '_' . $child_2['category_id'])
    );
}

                    $filter_data = array('filter_category_id' => $child['category_id'], 'filter_sub_category' => true);

                    $children_data[] = array(
                        'category_id' => $child['category_id'],
                        'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                        'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
                            'children'    => $children_data_2 // insert this line

                    );
                }
            }

            $filter_data = array(
                'filter_category_id'  => $category['category_id'],
                'filter_sub_category' => true
            );

            $data['categories'][] = array(
                'category_id' => $category['category_id'],
                'name'        => $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                'children'    => $children_data,
                'href'        => $this->url->link('product/category', 'path=' . $category['category_id'])
            );
        }

        return $this->load->view('module/category', $data);
    }
}
</code>```

My category.tpl module file looks like this:

```<code><h3><?php echo "Potkategorije" ?></h3>
<div class="list-group">
<ul>
    <?php foreach ($categories as $category) { ?>
    <?php if ($category['category_id'] == $category_id) { ?>
    <li class="cat-active">
        <a href="<?php echo $category['href']; ?>" class="active"><?php echo $category['name']; ?></a>
    <?php } else { ?>
    <li>
        <a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a>
        <?php } ?>
        <?php if ($category['children']) { ?>
        <b class="cc"></b>
        <ul class="col-subcat">
            <?php foreach ($category['children'] as $child) { ?>
            <li>
                <?php if ($child['category_id'] == $child_id) { ?>
                <a href="<?php echo $child['href']; ?>" class="active"><?php echo $child['name']; ?></a>
                <?php } else { ?>
                <a href="<?php echo $child['href']; ?>"><?php echo $child['name']; ?></a>
                <?php } ?>
                <?php if ($child['children']) { ?>
                <b class="cc"></b>
                <ul class="col-subcat">
                    <?php foreach ($child['children'] as $child_2) { ?>
                    <li>
                        <?php if ($child_2['category_id'] == $child_id) { ?>
                        <a href="<?php echo $child_2['href']; ?>" class="active"><?php echo $child_2['name']; ?></a>
                        <?php } else { ?>
                        <a href="<?php echo $child_2['href']; ?>"><?php echo $child_2['name']; ?></a>
                        <?php } ?>
                    </li>
                    <?php } ?>
                </ul>
                <?php } ?>
            </li>
            <?php } ?>
        </ul>
        <?php } ?>
    </li>
    <?php } ?>
</ul>
</div>
</code>```

How to modify files to make this work? I appreciate your time, thanx.

答:
Thanx to a good man @Ahmed Ginani, who tried to help me, I relized what was my problem. I never defined current subcategory. Instead, I went on showing the whole structure all at once. So, I had to modify both of my files (php and tpl)  so that only subsubcategories for the current category/subcategory would display. I am  showing the correct files here.

Category.php:

```<code><?php
class ControllerModuleCategory extends Controller {
    public function index() {
        $this->load->language('module/category');

        $data['heading_title'] = $this->language->get('heading_title');

        if (isset($this->request->get['path'])) {
            $parts = explode('_', (string)$this->request->get['path']);
        } else {
            $parts = array();
        }

        if (isset($parts[0])) {
            $data['category_id'] = $parts[0];
        } else {
            $data['category_id'] = 0;
        }

        if (isset($parts[1])) {
            $data['child_id'] = $parts[1];
        } else {
            $data['child_id'] = 0;
        }

        $this->load->model('catalog/category');

        $this->load->model('catalog/product');

        $data['categories'] = array();

        $categories = $this->model_catalog_category->getCategories(0);

        foreach ($categories as $category) {
            $children_data = array();

            if ($category['category_id'] == $data['category_id']) {
                $children = $this->model_catalog_category->getCategories($category['category_id']);

                foreach($children as $child) {
                    $children_data_2 = array();

                    $children_2 = $this->model_catalog_category->getCategories($child['category_id']);

                    foreach ($children_2 as $child_2) {
    $filter_data = array(
        'filter_category_id'  => $child_2['category_id'],
        'filter_sub_category' =>  true
    );

    $children_data_2[] = array(
        'category_id' => $child_2['category_id'],
        'name'        => $child_2['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
        'href'        => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'] . '_' . $child_2['category_id']),

    );
}

                    $filter_data = array('filter_category_id' => $child['category_id'], 'filter_sub_category' => true);

                    $children_data[] = array(
                        'category_id' => $child['category_id'],
                        'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                        'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
                        'children'    => $children_data_2 // insert this line

                    );
                }
            }

            $filter_data = array(
                'filter_category_id'  => $category['category_id'],
                'filter_sub_category' => true
            );

            $data['categories'][] = array(
                'category_id' => $category['category_id'],
                'name'        => $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                'children'    => $children_data,
                'href'        => $this->url->link('product/category', 'path=' . $category['category_id'])
            );
        }

        return $this->load->view('module/category', $data);
    }
}
</code>```

Category.tpl:

```<code><div class="list-group">
 <ul id="menu">
    <?php foreach ($categories as $category) :

        if (!empty($category['children'])) :
        echo '<h3 style="margin-top:54px;">Potkategorije</h3>';
            echo '<ul>';
            foreach ($category['children'] as $category_level2) :
                if (!empty($category_level2['children']) && $category_level2['category_id'] == $child_id) :
                    echo '<ul>';
                    foreach ($category_level2['children'] as $category_level3) :
                        echo '<li style="list-style-type: none"><a href="'.$category_level3['href'].'">'.$category_level3['name'].'</a></li>';
                    endforeach;
                    echo '</ul>';
                endif;
                echo '</li>';
            endforeach;
            echo '</ul>';
        endif;
        echo '</li>';
    endforeach;
    echo '</ul>';
    ?>
</div>
</code>```

I truly hope this helps someone, cheers!

Body:
This may be a duplicate, but which ever answer I found, didn't solve my problem.  I have category structure like this: Category->Subcategory->Sub sub category. In my category module, I managed to show the whole structure (Category->Subcategory->Subsub category). But what I need is only Subsub categories to show for each Category or subcategory. My  category.php module file looks like this:

<?php
class ControllerModuleCategory extends Controller {
    public function index() {
        $this->load->language('module/category');

        $data['heading_title'] = $this->language->get('heading_title');

        if (isset($this->request->get['path'])) {
            $parts = explode('_', (string)$this->request->get['path']);
        } else {
            $parts = array();
        }

        if (isset($parts[0])) {
            $data['category_id'] = $parts[0];
        } else {
            $data['category_id'] = 0;
        }

        if (isset($parts[1])) {
            $data['child_id'] = $parts[1];
        } else {
            $data['child_id'] = 0;
        }

        $this->load->model('catalog/category');

        $this->load->model('catalog/product');

        $data['categories'] = array();

        $categories = $this->model_catalog_category->getCategories(0);

        foreach ($categories as $category) {
            $children_data = array();

            if ($category['category_id'] == $data['category_id']) {
                $children = $this->model_catalog_category->getCategories($category['category_id']);

                foreach($children as $child) {
                    $children_data_2 = array();

                    $children_2 = $this->model_catalog_category->getCategories($child['category_id']);

                    foreach ($children_2 as $child_2) {
    $filter_data = array(
        'filter_category_id'  => $child_2['category_id'],
        'filter_sub_category' => true
    );

    $children_data_2[] = array(
        'category_id' => $child_2['category_id'],
        'name'        => $child_2['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
        'href'        => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'] . '_' . $child_2['category_id'])
    );
}

                    $filter_data = array('filter_category_id' => $child['category_id'], 'filter_sub_category' => true);

                    $children_data[] = array(
                        'category_id' => $child['category_id'],
                        'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                        'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
                            'children'    => $children_data_2 // insert this line

                    );
                }
            }

            $filter_data = array(
                'filter_category_id'  => $category['category_id'],
                'filter_sub_category' => true
            );

            $data['categories'][] = array(
                'category_id' => $category['category_id'],
                'name'        => $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                'children'    => $children_data,
                'href'        => $this->url->link('product/category', 'path=' . $category['category_id'])
            );
        }

        return $this->load->view('module/category', $data);
    }
}

My category.tpl module file looks like this:

<?php echo "Potkategorije" ?>

    <?php foreach ($categories as $category) { ?>
    <?php if ($category['category_id'] == $category_id) { ?>

        <a href="<?php echo $category['href']; ?>" class="active"><?php echo $category['name']; ?>
    <?php } else { ?>

        <a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?>
        <?php } ?>
        <?php if ($category['children']) { ?>

            <?php foreach ($category['children'] as $child) { ?>

                <?php if ($child['category_id'] == $child_id) { ?>
                <a href="<?php echo $child['href']; ?>" class="active"><?php echo $child['name']; ?>
                <?php } else { ?>
                <a href="<?php echo $child['href']; ?>"><?php echo $child['name']; ?>
                <?php } ?>
                <?php if ($child['children']) { ?>

                    <?php foreach ($child['children'] as $child_2) { ?>

                        <?php if ($child_2['category_id'] == $child_id) { ?>
                        <a href="<?php echo $child_2['href']; ?>" class="active"><?php echo $child_2['name']; ?>
                        <?php } else { ?>
                        <a href="<?php echo $child_2['href']; ?>"><?php echo $child_2['name']; ?>
                        <?php } ?>

                    <?php } ?>

                <?php } ?>

            <?php } ?>

        <?php } ?>

    <?php } ?>

How to modify files to make this work? I appreciate your time, thanx.

Body:
Thanx to a good man @Ahmed Ginani, who tried to help me, I relized what was my problem. I never defined current subcategory. Instead, I went on showing the whole structure all at once. So, I had to modify both of my files (php and tpl)  so that only subsubcategories for the current category/subcategory would display. I am  showing the correct files here.

Category.php:

<?php
class ControllerModuleCategory extends Controller {
    public function index() {
        $this->load->language('module/category');

        $data['heading_title'] = $this->language->get('heading_title');

        if (isset($this->request->get['path'])) {
            $parts = explode('_', (string)$this->request->get['path']);
        } else {
            $parts = array();
        }

        if (isset($parts[0])) {
            $data['category_id'] = $parts[0];
        } else {
            $data['category_id'] = 0;
        }

        if (isset($parts[1])) {
            $data['child_id'] = $parts[1];
        } else {
            $data['child_id'] = 0;
        }

        $this->load->model('catalog/category');

        $this->load->model('catalog/product');

        $data['categories'] = array();

        $categories = $this->model_catalog_category->getCategories(0);

        foreach ($categories as $category) {
            $children_data = array();

            if ($category['category_id'] == $data['category_id']) {
                $children = $this->model_catalog_category->getCategories($category['category_id']);

                foreach($children as $child) {
                    $children_data_2 = array();

                    $children_2 = $this->model_catalog_category->getCategories($child['category_id']);

                    foreach ($children_2 as $child_2) {
    $filter_data = array(
        'filter_category_id'  => $child_2['category_id'],
        'filter_sub_category' =>  true
    );

    $children_data_2[] = array(
        'category_id' => $child_2['category_id'],
        'name'        => $child_2['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
        'href'        => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'] . '_' . $child_2['category_id']),

    );
}

                    $filter_data = array('filter_category_id' => $child['category_id'], 'filter_sub_category' => true);

                    $children_data[] = array(
                        'category_id' => $child['category_id'],
                        'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                        'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
                        'children'    => $children_data_2 // insert this line

                    );
                }
            }

            $filter_data = array(
                'filter_category_id'  => $category['category_id'],
                'filter_sub_category' => true
            );

            $data['categories'][] = array(
                'category_id' => $category['category_id'],
                'name'        => $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                'children'    => $children_data,
                'href'        => $this->url->link('product/category', 'path=' . $category['category_id'])
            );
        }

        return $this->load->view('module/category', $data);
    }
}

Category.tpl:

<div class="list-group">
 <ul id="menu">
    <?php foreach ($categories as $category) :

        if (!empty($category['children'])) :
        echo '<h3 style="margin-top:54px;">Potkategorije</h3>';
            echo '<ul>';
            foreach ($category['children'] as $category_level2) :
                if (!empty($category_level2['children']) && $category_level2['category_id'] == $child_id) :
                    echo '<ul>';
                    foreach ($category_level2['children'] as $category_level3) :
                        echo '<li style="list-style-type: none"><a href="'.$category_level3['href'].'">'.$category_level3['name'].'</a></li>';
                    endforeach;
                    echo '</ul>';
                endif;
                echo '</li>';
            endforeach;
            echo '</ul>';
        endif;
        echo '</li>';
    endforeach;
    echo '</ul>';
    ?>
</div>

I truly hope this helps someone, cheers!


问:
Resize then crop PHP
Ok, basically I want all images to be 170x170px squares.
Thus if an image is not a square i want it to be resized, and then cropped in the middle..

I have spent numerous hours playing with this and I am getting nowhere.. I have gotten it to crop a section of the bigger image etc, but i specifically need the image to be resized, then cropped..

Any help would be greatly appreciated.

```<code>// get image size of img
$x = @getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];

if($sw > $sh) // Horizontal Rectangle?
{
  $newwidth = ($sw/$sh)*170;
  $newheight=170;
  $x_pos = ($sw - $sh) / 2;
  $x_pos = ceil($x_pos);
  $y_pos=0;
}

else if($sh > $sw) // Vertical Rectangle?
{
  $newheight = ($sh/$sw)*170;
  $newwidth=170;
  $y_pos = ($sh - $sw) / 2;
  $y_pos = ceil($y_pos);
  $x_pos=0;
}
else //Already Square
{
  $newheight=170;
  $newwidth=170;
}

$im = @ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = @ImageCreateFromPNG ($img) or // or PNG Image
$im = @ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF

if (!$im) {
  // We get errors from PHP's ImageCreate functions...
  // So let's echo back the contents of the actual image.
  readfile ($img);
} else {
  // Create the resized image destination
  $thumb = @ImageCreateTrueColor (170, 170);
  // Copy from image source, resize it, and paste to image destination
  imagecopyresampled($thumb, $im, 0, 0, 180, $y_pos, 170, 170, $newwidth,
    $newheight);
}
</code>```

答:
Needs some work, but it should give you enough to start with.

```<code>function crop($filename, $width, $height)
{
    // image resource, assuming it's PNG
    $resource = imagecreatefrompng($filename);
    // resource dimensions
    $size = array(
        0 => imagesx($resource),
        1 => imagesy($resource),
    );
    // sides
    $longer  = (int)($size[0]/$width > $size[1]/$height);
    $shorter = (int)(!$longer);
    // ugly hack to avoid condition for imagecopyresampled()
    $src = array(
        $longer  => 0,
        $shorter => ($size[$shorter]-$size[$longer])/2,
    );
    // new image resource
    $new = imagecreatetruecolor($width, $height);
    // do the magic
    imagecopyresampled($new, $resource,
        0,  0,
        $src[0], $src[1],
        $width, $height,
        $size[$longer], $size[$longer]
    );

    // save it or something else :)
}
</code>```

Edit: Trying to explain "ugly hack" above.

Two parameters in question are $src_x and $src_y, taken from manual:

imagecopyresampled() will take an rectangular area from src_image of
  width src_w and height src_h at position (src_x,src_y) and place it in
  a rectangular area of dst_image of width dst_w and height dst_h at
  position (dst_x,dst_y).

Meaning if $filename's width is longer, src_x has to be 0, and if height is longer, src_y has to be 0. Translated into code, it would look something like this:

```<code>$src = ($size[$shorter]-$size[$longer])/2;

if ( $longer === 1 )
{
    imagecopyresampled($new, $resource,
        0,  0,
        $src, 0,
        $width, $height,
        $size[$longer], $size[$longer]
    );
}
else
{
    imagecopyresampled($new, $resource,
        0,  0,
        0, $src,
        $width, $height,
        $size[$longer], $size[$longer]
    );
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Resize then crop PHP

Body:
Ok, basically I want all images to be 170x170px squares.
Thus if an image is not a square i want it to be resized, and then cropped in the middle..

I have spent numerous hours playing with this and I am getting nowhere.. I have gotten it to crop a section of the bigger image etc, but i specifically need the image to be resized, then cropped..

Any help would be greatly appreciated.

// get image size of img
$x = @getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];

if($sw > $sh) // Horizontal Rectangle?
{
  $newwidth = ($sw/$sh)*170;
  $newheight=170;
  $x_pos = ($sw - $sh) / 2;
  $x_pos = ceil($x_pos);
  $y_pos=0;
}

else if($sh > $sw) // Vertical Rectangle?
{
  $newheight = ($sh/$sw)*170;
  $newwidth=170;
  $y_pos = ($sh - $sw) / 2;
  $y_pos = ceil($y_pos);
  $x_pos=0;
}
else //Already Square
{
  $newheight=170;
  $newwidth=170;
}

$im = @ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = @ImageCreateFromPNG ($img) or // or PNG Image
$im = @ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF

if (!$im) {
  // We get errors from PHP's ImageCreate functions...
  // So let's echo back the contents of the actual image.
  readfile ($img);
} else {
  // Create the resized image destination
  $thumb = @ImageCreateTrueColor (170, 170);
  // Copy from image source, resize it, and paste to image destination
  imagecopyresampled($thumb, $im, 0, 0, 180, $y_pos, 170, 170, $newwidth,
    $newheight);
}

Body:
Needs some work, but it should give you enough to start with.

function crop($filename, $width, $height)
{
    // image resource, assuming it's PNG
    $resource = imagecreatefrompng($filename);
    // resource dimensions
    $size = array(
        0 => imagesx($resource),
        1 => imagesy($resource),
    );
    // sides
    $longer  = (int)($size[0]/$width > $size[1]/$height);
    $shorter = (int)(!$longer);
    // ugly hack to avoid condition for imagecopyresampled()
    $src = array(
        $longer  => 0,
        $shorter => ($size[$shorter]-$size[$longer])/2,
    );
    // new image resource
    $new = imagecreatetruecolor($width, $height);
    // do the magic
    imagecopyresampled($new, $resource,
        0,  0,
        $src[0], $src[1],
        $width, $height,
        $size[$longer], $size[$longer]
    );

    // save it or something else :)
}

Edit: Trying to explain "ugly hack" above.

Two parameters in question are $src_x and $src_y, taken from manual:

imagecopyresampled() will take an rectangular area from src_image of
  width src_w and height src_h at position (src_x,src_y) and place it in
  a rectangular area of dst_image of width dst_w and height dst_h at
  position (dst_x,dst_y).

Meaning if $filename's width is longer, src_x has to be 0, and if height is longer, src_y has to be 0. Translated into code, it would look something like this:

$src = ($size[$shorter]-$size[$longer])/2;

if ( $longer === 1 )
{
    imagecopyresampled($new, $resource,
        0,  0,
        $src, 0,
        $width, $height,
        $size[$longer], $size[$longer]
    );
}
else
{
    imagecopyresampled($new, $resource,
        0,  0,
        0, $src,
        $width, $height,
        $size[$longer], $size[$longer]
    );
}


问:
Logcat shows random/irrelevant errors
It's so annoying when logcat shows errors which are not related to my app at all. I turned off my app in the emulator and still this error will print after every 15-20 seconds

```<code>06-08 18:22:50.685 2350-14664/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
                                                                                com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
                                                                                Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
                                                                                at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
                                                                                at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
                                                                                at java.io.InputStream.read(InputStream.java:101)
                                                                                at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
                                                                                at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
</code>```

It makes debugging a bit tedious and I really want to do something about it.

EDIT-Even after using the filter I get random googlequicksearchbox errors

```<code>06-08 18:20:34.728 2350-14241/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -1
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -1.
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-08 18:20:39.760 1306-3296/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
06-08 18:20:39.762 1306-1691/? E/AudioFlinger: openRecord() permission denied: recording not allowed
</code>```

PS: I am not using any voice related stuff in my app.

答: You could use pidcat (https://github.com/JakeWharton/pidcat) - Pidcat is a colored logcat script which only shows log entries for a specific application package.</p>

Title: Logcat shows random/irrelevant errors

Body:
It's so annoying when logcat shows errors which are not related to my app at all. I turned off my app in the emulator and still this error will print after every 15-20 seconds

06-08 18:22:50.685 2350-14664/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
                                                                                com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
                                                                                Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
                                                                                at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
                                                                                at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
                                                                                at java.io.InputStream.read(InputStream.java:101)
                                                                                at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
                                                                                at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)

It makes debugging a bit tedious and I really want to do something about it.

EDIT-Even after using the filter I get random googlequicksearchbox errors

06-08 18:20:34.728 2350-14241/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -1
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -1.
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-08 18:20:39.760 1306-3296/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
06-08 18:20:39.762 1306-1691/? E/AudioFlinger: openRecord() permission denied: recording not allowed

PS: I am not using any voice related stuff in my app.


问:
C# DataGridView - Table is not populating
I'm trying to display data that I pull from text files within my program.cs  to a DataGridView, but the table remains blank when I run the code.

Another problem I have is that when the form opens it stops running through the code.

Basically what the code does is it downloads .zip files from an sftp server, unzips a text file, reads through the file adding each line to an array and splits a certain line into an array. I'm trying to get the variables from that array to appear on a DataGridView in my form.

Here is my code:

```<code>class Machine
{
    public string MacNum { get; set; }
    public string CashCount { get; set; }
    public string VendCount { get; set; }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        string zipTemp = (@"C:\Users\mark\Desktop\Project Dex\zipTemp\");

        string machineCashCount = ("");
        string hostIP = ("0.0.0.0");
        string userName = ("UN");
        string passWord = ("PW");
        string remotePath = (@"/home/dex/RESPONSE/PROCESSED");
        string localPath = (@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");

        Application.Run(new Form1());
        DataGridView dataGridView = new DataGridView();
        IList<Machine> machines = new BindingList<Machine>();
        dataGridView.DataSource = machines;

        SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = hostIP,
            UserName = userName,
            Password = passWord,
            PortNumber = 22,
            SshHostKeyFingerprint = "ssh-rsa 2048 96:48:96:52:8c:e7:de:c6:e1:00:08:7e:db:ad:e4:06"
        };

        using (Session session = new Session())
        {
            session.Open(sessionOptions);

            TransferOptions transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;

            session.GetFiles(remotePath, @"C:\Users\mark\Desktop\Project Dex\Temp\").Check();
        }

        DirectoryInfo directorySelected = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");
        List<string> fileNames = new List<string>();

        foreach (FileInfo fileInfo in directorySelected.GetFiles("*.zip"))
        {
            fileNames.Add(fileInfo.Name);
        }

        foreach (string fileName in fileNames)
        {
            string zipFilePath = localPath + fileName;

            using (ZipFile zip1 = ZipFile.Read(zipFilePath))
            {
                var selection = (from e in zip1.Entries
                                 where (e.FileName).StartsWith("01e")
                                 select e);

                Directory.CreateDirectory(zipTemp);

                foreach (var e in selection)
                {
                    e.Extract(zipTemp, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            DirectoryInfo dexDirect = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\zipTemp\");
            List<string> dexName = new List<string>();

            foreach (FileInfo dexInfo in dexDirect.GetFiles("*.dex"))
            {
                dexName.Add(dexInfo.Name);
            }

            foreach (string dexNames in dexName)
            {
                string dexFilePath = zipTemp + dexNames;

                string[] lines = System.IO.File.ReadAllLines(dexFilePath);

                foreach (string line in lines)
                {
                    machineCashCount = Array.Find(lines,
                        element => element.StartsWith("VA1", StringComparison.Ordinal));
                }
                string[] MCC1 = machineCashCount.Split('*');
                string[] nm = dexNames.Split('.');

                int nam = int.Parse(nm[0], System.Globalization.NumberStyles.HexNumber);

                // Console.WriteLine((nam + (":") + "Total cash count: ") + MCC1[1]);
                // Console.WriteLine((nam + (":") + "Number of paid vends: ") + MCC1[2]);

                Machine m = new Machine();

                m.MacNum = nm[0];
                m.CashCount = MCC1[1];
                m.VendCount = MCC1[2];
                machines.Add(m);
            }
        }

        Application.Run(new Form1());
    }
}
</code>```

Form1:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void Form1_Load(object sender, EventArgs e)
    {

    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {

    }
}
</code>```

答:
1.Delete

```<code> Application.Run(new Form1());
 DataGridView dataGridView = new DataGridView();
</code>```

and

```<code>dataGridView.DataSource = machines;
</code>```

2.At the end change

```<code>Application.Run(new Form1());
</code>```

to

```<code>Application.Run(new Form1(machines));
</code>```

3.Add constructor to Form1:

```<code> public Form1(IList<Machine> machines)
 {
     InitializeComponent();
     dataGridView1.DataSource = machines;
 }
</code>```

Body:
I'm trying to display data that I pull from text files within my program.cs  to a DataGridView, but the table remains blank when I run the code.

Another problem I have is that when the form opens it stops running through the code.

Basically what the code does is it downloads .zip files from an sftp server, unzips a text file, reads through the file adding each line to an array and splits a certain line into an array. I'm trying to get the variables from that array to appear on a DataGridView in my form.

Here is my code:

class Machine
{
    public string MacNum { get; set; }
    public string CashCount { get; set; }
    public string VendCount { get; set; }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        string zipTemp = (@"C:\Users\mark\Desktop\Project Dex\zipTemp\");

        string machineCashCount = ("");
        string hostIP = ("0.0.0.0");
        string userName = ("UN");
        string passWord = ("PW");
        string remotePath = (@"/home/dex/RESPONSE/PROCESSED");
        string localPath = (@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");

        Application.Run(new Form1());
        DataGridView dataGridView = new DataGridView();
        IList<Machine> machines = new BindingList<Machine>();
        dataGridView.DataSource = machines;

        SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = hostIP,
            UserName = userName,
            Password = passWord,
            PortNumber = 22,
            SshHostKeyFingerprint = "ssh-rsa 2048 96:48:96:52:8c:e7:de:c6:e1:00:08:7e:db:ad:e4:06"
        };

        using (Session session = new Session())
        {
            session.Open(sessionOptions);

            TransferOptions transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;

            session.GetFiles(remotePath, @"C:\Users\mark\Desktop\Project Dex\Temp\").Check();
        }

        DirectoryInfo directorySelected = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");
        List<string> fileNames = new List<string>();

        foreach (FileInfo fileInfo in directorySelected.GetFiles("*.zip"))
        {
            fileNames.Add(fileInfo.Name);
        }

        foreach (string fileName in fileNames)
        {
            string zipFilePath = localPath + fileName;

            using (ZipFile zip1 = ZipFile.Read(zipFilePath))
            {
                var selection = (from e in zip1.Entries
                                 where (e.FileName).StartsWith("01e")
                                 select e);

                Directory.CreateDirectory(zipTemp);

                foreach (var e in selection)
                {
                    e.Extract(zipTemp, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            DirectoryInfo dexDirect = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\zipTemp\");
            List<string> dexName = new List<string>();

            foreach (FileInfo dexInfo in dexDirect.GetFiles("*.dex"))
            {
                dexName.Add(dexInfo.Name);
            }

            foreach (string dexNames in dexName)
            {
                string dexFilePath = zipTemp + dexNames;

                string[] lines = System.IO.File.ReadAllLines(dexFilePath);

                foreach (string line in lines)
                {
                    machineCashCount = Array.Find(lines,
                        element => element.StartsWith("VA1", StringComparison.Ordinal));
                }
                string[] MCC1 = machineCashCount.Split('*');
                string[] nm = dexNames.Split('.');

                int nam = int.Parse(nm[0], System.Globalization.NumberStyles.HexNumber);

                // Console.WriteLine((nam + (":") + "Total cash count: ") + MCC1[1]);
                // Console.WriteLine((nam + (":") + "Number of paid vends: ") + MCC1[2]);

                Machine m = new Machine();

                m.MacNum = nm[0];
                m.CashCount = MCC1[1];
                m.VendCount = MCC1[2];
                machines.Add(m);
            }
        }

        Application.Run(new Form1());
    }
}

Form1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void Form1_Load(object sender, EventArgs e)
    {

    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {

    }
}

Body:
1.Delete

 Application.Run(new Form1());
 DataGridView dataGridView = new DataGridView();

and

dataGridView.DataSource = machines;

2.At the end change

Application.Run(new Form1());

to

Application.Run(new Form1(machines));

3.Add constructor to Form1:

 public Form1(IList<Machine> machines)
 {
     InitializeComponent();
     dataGridView1.DataSource = machines;
 }


问:
how to merge two data frame with out adding duplicates in Python?
I have a dataframe looks like:

```<code>    x   y   z
1   3   7   1
2   7   5   2
3   8   2   3
</code>```

and other dataframe looks like:

```<code>    x   y   z
1   7   5   4
2   8   2   8
3   4   5   5
4   7   3   7
5   9   5   3
6   3   7   9
</code>```

Now I want to merge the two frames, and the frame after merge to be looked like this:

```<code>    x   y   z
1   3   7   1
2   7   5   2
3   8   2   3
4   4   5   5
5   7   3   7
6   9   5   3
</code>```

答:
Concatenate, then dedupe</p>

```<code>pandas.concat([df1,df2]).drop_duplicates().reset_index(drop=True)
</code>```

Body:
I have a dataframe looks like:

    x   y   z
1   3   7   1
2   7   5   2
3   8   2   3

and other dataframe looks like:

    x   y   z
1   7   5   4
2   8   2   8
3   4   5   5
4   7   3   7
5   9   5   3
6   3   7   9

Now I want to merge the two frames, and the frame after merge to be looked like this:

    x   y   z
1   3   7   1
2   7   5   2
3   8   2   3
4   4   5   5
5   7   3   7
6   9   5   3

Body:
Concatenate, then dedupe

pandas.concat([df1,df2]).drop_duplicates().reset_index(drop=True)


问:
node.js execute system command synchronously
I need in node.js function

```<code>result = execSync('node -v');
</code>```

that will synchronously execute the given command line and return all stdout'ed by that command text.

ps. Sync is wrong. I know. Just for personal use.

UPDATE

Now we have mgutz's solution which gives us exit code, but not stdout! Still waiting for a more precise answer.

UPDATE

mgutz updated his answer and the solution is here :)

Also, as dgo.a mentioned, there is stand-alone module exec-sync

UPDATE 2014-07-30

ShellJS lib arrived. Consider this is the best choice for now.

UPDATE 2015-02-10

AT LAST! NodeJS 0.12 supports execSync natively.

See official docs

答:
This is not possible in Node.js, both child_process.spawn and child_process.exec were built from the ground up to be async.

For details see: https://github.com/ry/node/blob/master/lib/child_process.js

If you really want to have this blocking, then put everything that needs to happen afterwards in a callback, or build your own queue to handle this in a blocking fashion, I suppose you could use Async.js for this task.

Or, in case you have way too much time to spend, hack around in Node.js it self.

Body:
I need in node.js function

result = execSync('node -v');

that will synchronously execute the given command line and return all stdout'ed by that command text.

ps. Sync is wrong. I know. Just for personal use.

UPDATE

Now we have mgutz's solution which gives us exit code, but not stdout! Still waiting for a more precise answer.

UPDATE

mgutz updated his answer and the solution is here :)

Also, as dgo.a mentioned, there is stand-alone module exec-sync

UPDATE 2014-07-30

ShellJS lib arrived. Consider this is the best choice for now.

UPDATE 2015-02-10

AT LAST! NodeJS 0.12 supports execSync natively.

See official docs


问:
Running a git command with wildcard works in bash but not through Process
I want to run git check-ignore using sys.process.Process. This works in the shell (bash):

```<code>$ cd /home/me/Documents/Foo
$ git check-ignore *
target
</code>```

There is a directory /home/me/Documents/Foo/target that is being ignored through /home/me/Documents/Foo/.gitignore.

The same doesn't work when I run this through sys.process:

```<code>import scala.sys.process._
val workingDir = new java.io.File("/home/me/Documents/Foo")
Process(Seq("git", "check-ignore", "*"), workingDir).!
</code>```

It gives return code 1, meaning that no file matched. If I specify the particular name, it works:

```<code>Process(Seq("git", "check-ignore", "target"), workingDir).!
</code>```

This prints target and returns code zero.

So why doesn't the wildcard * work here, and how do I make it work (given that I want to list all ignored files and I have no prior knowledge what those files would be)?

答:
This problem is same as How to run unix / shell commands with wildcards using Java?, You can implement it in Scala too, maybe like:

```<code>Process(Seq("bash", "-c", "git check-ignore *"), workingDir).!
</code>```

Body:
I want to run git check-ignore using sys.process.Process. This works in the shell (bash):

$ cd /home/me/Documents/Foo
$ git check-ignore *
target

There is a directory /home/me/Documents/Foo/target that is being ignored through /home/me/Documents/Foo/.gitignore.

The same doesn't work when I run this through sys.process:

import scala.sys.process._
val workingDir = new java.io.File("/home/me/Documents/Foo")
Process(Seq("git", "check-ignore", "*"), workingDir).!

It gives return code 1, meaning that no file matched. If I specify the particular name, it works:

Process(Seq("git", "check-ignore", "target"), workingDir).!

This prints target and returns code zero.

So why doesn't the wildcard * work here, and how do I make it work (given that I want to list all ignored files and I have no prior knowledge what those files would be)?

Body:
This problem is same as How to run unix / shell commands with wildcards using Java?, You can implement it in Scala too, maybe like:

Process(Seq("bash", "-c", "git check-ignore *"), workingDir).!


问:
SAS-use of lead function
Suppose the dataset has three columns

```<code>Date   Region   Price
01-03    A        1
01-03    A        2
01-03    B        3
01-03    B        4
01-03    A        5
01-04    B        4
01-04    B        6
01-04    B        7
</code>```

I try to get the lead price by date and region through following code.

```<code>data want;
set have;
by _ric date_l_;
do until (eof);
set have(firstobs=2 keep=price rename=(price=lagprice)) end=eof;
end;
if last.date_l_ then call missing(lagprice);
run;
</code>```

However, the WANT only have one observations. Then I create new_date=date and try another code:

```<code>data want;
set have nobs=nobs;
  do _i = _n_ to nobs until (new_date ne Date);
  if eof1=0 then
  set have (firstobs=2 keep=price rename=(price=leadprice)) end=eof1;
  else leadprice=.;
  end;
run;
</code>```

With this code, SAS is working slowly. So I think this code is also not appropriate. Could anyone give some suggestions? Thanks

答:
You can use proc expand to generate leads on numeric variables by group. Try the following method instead:

Step 1: Sort by Region, Date

```<code>proc sort data=have;
    by Region Date;
run;
</code>```

Step 2: Create a new ID variable to denote observation numbers

Because you have multiple values per date per region, we need to generate a new ID variable so that proc expand uses lead by observation number rather than by date.

```<code>data have2;
    set have;

    _ID_ = _N_;
run;
</code>```

Step 3: Run proc expand by region with the lead transformation

lead will do exactly as it sounds. You can lead by as many values as you'd like, as long as the data supports it. In this case, we are leading by one observation.

```<code>proc expand data=have2
            out=want;
    by Region;
    id _ID_;
    convert Price = Lead_Price / transform=(lead 1) ;
run;
</code>```

Title: SAS-use of lead function

Body:
Suppose the dataset has three columns

Date   Region   Price
01-03    A        1
01-03    A        2
01-03    B        3
01-03    B        4
01-03    A        5
01-04    B        4
01-04    B        6
01-04    B        7

I try to get the lead price by date and region through following code.

data want;
set have;
by _ric date_l_;
do until (eof);
set have(firstobs=2 keep=price rename=(price=lagprice)) end=eof;
end;
if last.date_l_ then call missing(lagprice);
run;

However, the WANT only have one observations. Then I create new_date=date and try another code:

data want;
set have nobs=nobs;
  do _i = _n_ to nobs until (new_date ne Date);
  if eof1=0 then
  set have (firstobs=2 keep=price rename=(price=leadprice)) end=eof1;
  else leadprice=.;
  end;
run;

With this code, SAS is working slowly. So I think this code is also not appropriate. Could anyone give some suggestions? Thanks

Body:
You can use proc expand to generate leads on numeric variables by group. Try the following method instead:

Step 1: Sort by Region, Date

proc sort data=have;
    by Region Date;
run;

Step 2: Create a new ID variable to denote observation numbers

Because you have multiple values per date per region, we need to generate a new ID variable so that proc expand uses lead by observation number rather than by date.

data have2;
    set have;

    _ID_ = _N_;
run;

Step 3: Run proc expand by region with the lead transformation

lead will do exactly as it sounds. You can lead by as many values as you'd like, as long as the data supports it. In this case, we are leading by one observation.

proc expand data=have2
            out=want;
    by Region;
    id _ID_;
    convert Price = Lead_Price / transform=(lead 1) ;
run;


问:
Change the X-Frame-Options to allow all domains
I am trying to use some site of mine as an iframe from a different site of mine.

My problem is- the other site is always consistently changes his IP address and does not have an domain name.

So, I read that you can allo a specific domain by adding this lint to the /etc/nginx/nginx.conf:

```<code> add_header X-Frame-Options "ALLOW-FROM https://subdomain.example.com/";
</code>```

My question is: It is possible to allow my site to be imported as an iframe from all IP addressed and domains? What should I write in order to achieve this?

I am using Ubuntu 16.04 and nginx 1.10.0.

答:
If you set it, then you can only set it to DENY, SAMEORIGIN, or ALLOW-FROM (a specific origin).

Allowing all domains is the default. Don't set the X-Frame-Options header at all if you want that.

Note that the successor to X-Frame-Options — CSP's frame-ancestors directive — accepts a list of allowed origins so you can easily allow some origins instead of none, one or all.

Body:
I am trying to use some site of mine as an iframe from a different site of mine.

My problem is- the other site is always consistently changes his IP address and does not have an domain name.

So, I read that you can allo a specific domain by adding this lint to the /etc/nginx/nginx.conf:

 add_header X-Frame-Options "ALLOW-FROM https://subdomain.example.com/";

My question is: It is possible to allow my site to be imported as an iframe from all IP addressed and domains? What should I write in order to achieve this?

I am using Ubuntu 16.04 and nginx 1.10.0.

ContentLicense: CC BY-SA 4.0


问:
export all the data into excel sheet of a particular user who has logged using php and Mysql
I want to export only those records which a particular  user has entered. For example: I have logged in by user id - user_test and i have few records which i have entered. for the same when the record is saved into the database my login name is also being saved along with the record. When i want to fetch and display the data of the particular user in session its working fine. but when i am using the same query for downloading the report i am not getting any error, the page is getting download with blank fields. Here is the code i am using for downloading the records in excel sheet. </p>

```<code><?php
include_once 'classes/admin-class.php';
$admin = new itg_admin();
$admin->_authenticate();
$ten = $_SESSION['admin_login'];
?>
<?php
    $host="localhost";
    $username="root";
    $password="";
    $dbname="kuidfc_project_monitoring";
    $con = new mysqli($host, $username, $password,$dbname);

    $sql_data="SELECT * from user_daily_records WHERE users = '" . $admin->get_nicename() . "';";
    $result_data=$con->query($sql_data);
    $results=array();
    $filename = "Daily_Report.xls"; // File Name
    // Download file
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Type: application/vnd.ms-excel");

    $flag = false;
    while ($row = mysqli_fetch_assoc($result_data)) {
        if (!$flag) {
            // display field/column names as first row
            echo implode("\t", array_keys($row)) . "\r\n";
            $flag = true;
        }
        echo implode("\t", array_values($row)) . "\r\n";
    }
    ?>
</code>```

答:
```<code>"SELECT * FROM daily_progress_demo WHERE users = '" . $admin->get_nicename() . "'  ORDER BY startdate DESC ;"
</code>```

I just sort by order in query it worked. Everything is coming perfect.

Body:
I want to export only those records which a particular  user has entered. For example: I have logged in by user id - user_test and i have few records which i have entered. for the same when the record is saved into the database my login name is also being saved along with the record. When i want to fetch and display the data of the particular user in session its working fine. but when i am using the same query for downloading the report i am not getting any error, the page is getting download with blank fields. Here is the code i am using for downloading the records in excel sheet.

<?php
include_once 'classes/admin-class.php';
$admin = new itg_admin();
$admin->_authenticate();
$ten = $_SESSION['admin_login'];
?>
<?php
    $host="localhost";
    $username="root";
    $password="";
    $dbname="kuidfc_project_monitoring";
    $con = new mysqli($host, $username, $password,$dbname);

    $sql_data="SELECT * from user_daily_records WHERE users = '" . $admin->get_nicename() . "';";
    $result_data=$con->query($sql_data);
    $results=array();
    $filename = "Daily_Report.xls"; // File Name
    // Download file
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Type: application/vnd.ms-excel");

    $flag = false;
    while ($row = mysqli_fetch_assoc($result_data)) {
        if (!$flag) {
            // display field/column names as first row
            echo implode("\t", array_keys($row)) . "\r\n";
            $flag = true;
        }
        echo implode("\t", array_values($row)) . "\r\n";
    }
    ?>

Body:
"SELECT * FROM daily_progress_demo WHERE users = '" . $admin->get_nicename() . "'  ORDER BY startdate DESC ;"

I just sort by order in query it worked. Everything is coming perfect.


问:
REST API: adapt a curl post to powershell
I try to adapt a working curl command to powershell

this is the working curl from postman:

```<code>curl -X POST \
  https://test.portal.com/api/v1/login \
  -H 'authorization: Basic ADSFws343==' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'postman-token: 06944eab-3634-dd34-4634-0966bd8872c5' \
  -F 'user[email]=xxx@xxx.com' \
  -F 'user[password]=xxx'
</code>```

This creates the following raw data

```<code>POST /api/v1/login HTTP/1.1
cache-control: no-cache
Postman-Token: 80b2b345-6f5d-4c63-bedf-c65038b1e5df
Authorization: Basic ADSFws343==
User-Agent: PostmanRuntime/3.0.11-hotfix.2
Accept: */*
Host: test.portal.com
accept-encoding: gzip, deflate
content-type: multipart/form-data; boundary=--------------------------266295771457397823506834
content-length: 309
Connection: close

----------------------------266295771457397823506834
Content-Disposition: form-data; name="user[email]"

xxx@xxx.com
----------------------------266295771457397823506834
Content-Disposition: form-data; name="user[password]"

xxx
----------------------------266295771457397823506834--
</code>```

and I get the following response:

```<code>HTTP/1.1 201 Created
Server: nginx/1.8.0
Date: Tue, 06 Jun 2017 13:42:54 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Status: 201 Created
Cache-Control: max-age=0, private, must-revalidate
X-XSS-Protection: 1; mode=block
X-Request-Id: d1dd86e7-325a-43d5-bfda-46a9df4cc660
ETag: W/"3b793a3a1971dac89b48633e0e031237"
X-Frame-Options: SAMEORIGIN
X-Runtime: 0.115464
X-Content-Type-Options: nosniff
X-Powered-By: Phusion Passenger 5.1.4
</code>```

with the expected data in the body.

Now I struggle to adapt the code to powershell

```<code>[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$boundary = "--------------------------210183530616764504332035"
$URL = "https://test.portal.com/api/v1/login"
$email = "xxx@xxx.com"
$password= "xxx"

$headers = @{
    "cache-control"="no-cache";
    "Postman-Token"="3cf33ce8-716e-4ac1-b2da-c46df65d5307"
    Authorization="Basic ADSFws343==";
    "content-type"="multipart/form-data; boundary=$boundary"
    "User-Agent"="PostmanRuntime/3.0.11-hotfix.2"
    "Accept"="*/*"
    "accept-encoding"="gzip, deflate"
}

$LF = "`n"
$bodyLines = (
    "--$boundary",
    "Content-Disposition: form-data; name=`"user[email]`"$LF",
    $email,
    "--$boundary",
    "Content-Disposition: form-data; name=`"user[password]`"$LF",
    $password,
    "--$boundary--$LF"
    ) -join $LF

$response = Invoke-RestMethod -Uri $URL -Headers $headers -Method Post -TimeoutSec 20 -Body $bodyLines -DisableKeepAlive
</code>```

This throws an exception:

```<code>Invoke-RestMethod : Incomplete response received from application
</code>```

and creates the following raw data

```<code>POST https://test.portal.com/api/v1/login HTTP/1.1
Content-Type: multipart/form-data; boundary=--------------------------210183530616764504332065
Accept: */*
Postman-Token: 3cf33ce8-716e-4ac1-b2da-c46df65d5307
Authorization: Basic ADSFws343==
accept-encoding: gzip, deflate
cache-control: no-cache
User-Agent: PostmanRuntime/3.0.11-hotfix.2
Host: test.portal.com
Content-Length: 300
Connection: Close

----------------------------210183530616764504332065
Content-Disposition: form-data; name="user[email]"

xxx@xxx.com
----------------------------210183530616764504332065
Content-Disposition: form-data; name="user[password]"

xxx
----------------------------210183530616764504332065--
</code>```

and this response

```<code>HTTP/1.1 502 Bad Gateway
Server: nginx/1.8.0
Date: Tue, 06 Jun 2017 14:02:23 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 54
Connection: close
Status: 502 Bad Gateway
cache-control: no-cache, no-store, must-revalidate

<h2>Incomplete response received from application</h2>
</code>```

Where is my fault or what is missing? The only difference in the Raw Data is the somehow shorter content-length. even the boundarys have the same length as the postman curl

Thank you for taking your time

Edit: Changed the Headers to hash-table without effect and changed the powershell code to simulate the postman curl more accurate

Final Solution: Problem was the wrong format of the body. Changing

```<code>$LF = "`n"
</code>```

to

```<code>$LF = "`r`n"
</code>```

fixed the problem!

答:
The body of the multipart/formdata has the wrong format, needs to be CR LF instead of just LF.

Change

```<code>$LF = "`n"
</code>```

to

```<code>$LF = "`r`n"
</code>```

to make it work

Body:
I try to adapt a working curl command to powershell

this is the working curl from postman:

curl -X POST \
  https://test.portal.com/api/v1/login \
  -H 'authorization: Basic ADSFws343==' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'postman-token: 06944eab-3634-dd34-4634-0966bd8872c5' \
  -F 'user[email]=xxx@xxx.com' \
  -F 'user[password]=xxx'

This creates the following raw data

POST /api/v1/login HTTP/1.1
cache-control: no-cache
Postman-Token: 80b2b345-6f5d-4c63-bedf-c65038b1e5df
Authorization: Basic ADSFws343==
User-Agent: PostmanRuntime/3.0.11-hotfix.2
Accept: */*
Host: test.portal.com
accept-encoding: gzip, deflate
content-type: multipart/form-data; boundary=--------------------------266295771457397823506834
content-length: 309
Connection: close

----------------------------266295771457397823506834
Content-Disposition: form-data; name="user[email]"

xxx@xxx.com
----------------------------266295771457397823506834
Content-Disposition: form-data; name="user[password]"

xxx
----------------------------266295771457397823506834--

and I get the following response:

HTTP/1.1 201 Created
Server: nginx/1.8.0
Date: Tue, 06 Jun 2017 13:42:54 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Status: 201 Created
Cache-Control: max-age=0, private, must-revalidate
X-XSS-Protection: 1; mode=block
X-Request-Id: d1dd86e7-325a-43d5-bfda-46a9df4cc660
ETag: W/"3b793a3a1971dac89b48633e0e031237"
X-Frame-Options: SAMEORIGIN
X-Runtime: 0.115464
X-Content-Type-Options: nosniff
X-Powered-By: Phusion Passenger 5.1.4

with the expected data in the body.

Now I struggle to adapt the code to powershell

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$boundary = "--------------------------210183530616764504332035"
$URL = "https://test.portal.com/api/v1/login"
$email = "xxx@xxx.com"
$password= "xxx"

$headers = @{
    "cache-control"="no-cache";
    "Postman-Token"="3cf33ce8-716e-4ac1-b2da-c46df65d5307"
    Authorization="Basic ADSFws343==";
    "content-type"="multipart/form-data; boundary=$boundary"
    "User-Agent"="PostmanRuntime/3.0.11-hotfix.2"
    "Accept"="*/*"
    "accept-encoding"="gzip, deflate"
}

$LF = "`n"
$bodyLines = (
    "--$boundary",
    "Content-Disposition: form-data; name=`"user[email]`"$LF",
    $email,
    "--$boundary",
    "Content-Disposition: form-data; name=`"user[password]`"$LF",
    $password,
    "--$boundary--$LF"
    ) -join $LF

$response = Invoke-RestMethod -Uri $URL -Headers $headers -Method Post -TimeoutSec 20 -Body $bodyLines -DisableKeepAlive

This throws an exception:

Invoke-RestMethod : Incomplete response received from application

and creates the following raw data

POST https://test.portal.com/api/v1/login HTTP/1.1
Content-Type: multipart/form-data; boundary=--------------------------210183530616764504332065
Accept: */*
Postman-Token: 3cf33ce8-716e-4ac1-b2da-c46df65d5307
Authorization: Basic ADSFws343==
accept-encoding: gzip, deflate
cache-control: no-cache
User-Agent: PostmanRuntime/3.0.11-hotfix.2
Host: test.portal.com
Content-Length: 300
Connection: Close

----------------------------210183530616764504332065
Content-Disposition: form-data; name="user[email]"

xxx@xxx.com
----------------------------210183530616764504332065
Content-Disposition: form-data; name="user[password]"

xxx
----------------------------210183530616764504332065--

and this response

HTTP/1.1 502 Bad Gateway
Server: nginx/1.8.0
Date: Tue, 06 Jun 2017 14:02:23 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 54
Connection: close
Status: 502 Bad Gateway
cache-control: no-cache, no-store, must-revalidate

Incomplete response received from application

Where is my fault or what is missing? The only difference in the Raw Data is the somehow shorter content-length. even the boundarys have the same length as the postman curl

Thank you for taking your time

Edit: Changed the Headers to hash-table without effect and changed the powershell code to simulate the postman curl more accurate

Final Solution: Problem was the wrong format of the body. Changing

$LF = "`n"

to

$LF = "`r`n"

fixed the problem!

Body:
The body of the multipart/formdata has the wrong format, needs to be CR LF instead of just LF.

Change

$LF = "`n"

to

$LF = "`r`n"

to make it work


问:
YouTube API Reflecting Wrong Content
We are trying to pull in posts for the hashtag #smartson on YouTube using the search endpoint in the v3 data API.

However, the following two posts are not appearing in the API results:

(1) https://www.youtube.com/watch?v=F93wt8fZ-vE

(2) https://www.youtube.com/watch?v=BIWXU3IsssY

If you follow both those links and view the description section, you'll notice they both contain the hashtag #smartson as the very first word of the description. Yet they don't show up in the API results when searching that hashtag.

I can, however, retrieve those posts by looking up the channel in which they are published (using the YouTube channel endpoint). Here is the response I get back for those two posts:

```<code>    {
       "kind":"youtube#searchResult",
       "etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/OIp6j6IiBd2nWkNA4H-3Dj6xGtw\"",
       "id":{
          "kind":"youtube#video",
          "videoId":"BIWXU3IsssY"
       },
       "snippet":{
          "publishedAt":"2017-06-05T10:47:48.000Z",
          "channelId":"UCYEsDVnEY3xiuuzDFW6g41w",
          "title":"clasohlsonworkwea",
          "description":"smartson #clasohlsonworkwear #testimonial Sitter jätte bra men lite för små knäskydd.",
          "thumbnails":{
             "default":{
                "url":"https://i.ytimg.com/vi/BIWXU3IsssY/default.jpg",
                "width":120,
                "height":90
             },
             "medium":{
                "url":"https://i.ytimg.com/vi/BIWXU3IsssY/mqdefault.jpg",
                "width":320,
                "height":180
             },
             "high":{
                "url":"https://i.ytimg.com/vi/BIWXU3IsssY/hqdefault.jpg",
                "width":480,
                "height":360
             }
          },
          "channelTitle":"Jörgen Lyckebay",
          "liveBroadcastContent":"none"
       }
    },
    {
       "kind":"youtube#searchResult",
       "etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/CaSiQ6lYASTi7Eia0cHbF9Gwkz4\"",
       "id":{
          "kind":"youtube#video",
          "videoId":"F93wt8fZ-vE"
       },
       "snippet":{
          "publishedAt":"2017-06-05T08:21:06.000Z",
          "channelId":"UCYEsDVnEY3xiuuzDFW6g41w",
          "title":"clasohlsonworkwear",
          "description":"smartson #clasohlsonworkwear #testimonial Första testet med byxorna o klev på knapparna gör om som f..",
          "thumbnails":{
             "default":{
                "url":"https://i.ytimg.com/vi/F93wt8fZ-vE/default.jpg",
                "width":120,
                "height":90
             },
             "medium":{
                "url":"https://i.ytimg.com/vi/F93wt8fZ-vE/mqdefault.jpg",
                "width":320,
                "height":180
             },
             "high":{
                "url":"https://i.ytimg.com/vi/F93wt8fZ-vE/hqdefault.jpg",
                "width":480,
                "height":360
             }
          },
          "channelTitle":"Jörgen Lyckebay",
          "liveBroadcastContent":"none"
       }
    },
    {
       "kind":"youtube#searchResult",
       "etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/EYuQkgOEkur8iziKcJuAx76XkmU\"",
       "id":{
          "kind":"youtube#video",
          "videoId":"pW_RJqX0WGM"
       },
       "snippet":{
          "publishedAt":"2017-04-26T15:41:54.000Z",
          "channelId":"UCYEsDVnEY3xiuuzDFW6g41w",
          "title":"Båt motor",
          "description":"Renoverad båtmotor 2.",
          "thumbnails":{
             "default":{
                "url":"https://i.ytimg.com/vi/pW_RJqX0WGM/default.jpg",
                "width":120,
                "height":90
             },
             "medium":{
                "url":"https://i.ytimg.com/vi/pW_RJqX0WGM/mqdefault.jpg",
                "width":320,
                "height":180
             },
             "high":{
                "url":"https://i.ytimg.com/vi/pW_RJqX0WGM/hqdefault.jpg",
                "width":480,
                "height":360
             }
          },
          "channelTitle":"Jörgen Lyckebay",
          "liveBroadcastContent":"none"
       }
}
</code>```

In that API response, the description begins simply with the word "smartson," not the hashtag.

Any insight on why the API is not in sync with the public YouTube.com link?

答:
Use the Videos.list. Tried it and it doesn't ignore the hashtag.

Tried it in the API explorer and here's what I got:

```<code>"description": " . . .Tap tap tap.\n\n######tapper\n#hashtag\n#dont ignore\n##doublehashtag",
</code>```

The youtube api returned the complete description, no omissions.

Title: YouTube API Reflecting Wrong Content

Body:
We are trying to pull in posts for the hashtag #smartson on YouTube using the search endpoint in the v3 data API.

However, the following two posts are not appearing in the API results:

(1) https://www.youtube.com/watch?v=F93wt8fZ-vE

(2) https://www.youtube.com/watch?v=BIWXU3IsssY

If you follow both those links and view the description section, you'll notice they both contain the hashtag #smartson as the very first word of the description. Yet they don't show up in the API results when searching that hashtag.

I can, however, retrieve those posts by looking up the channel in which they are published (using the YouTube channel endpoint). Here is the response I get back for those two posts:

    {
       "kind":"youtube#searchResult",
       "etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/OIp6j6IiBd2nWkNA4H-3Dj6xGtw\"",
       "id":{
          "kind":"youtube#video",
          "videoId":"BIWXU3IsssY"
       },
       "snippet":{
          "publishedAt":"2017-06-05T10:47:48.000Z",
          "channelId":"UCYEsDVnEY3xiuuzDFW6g41w",
          "title":"clasohlsonworkwea",
          "description":"smartson #clasohlsonworkwear #testimonial Sitter jätte bra men lite för små knäskydd.",
          "thumbnails":{
             "default":{
                "url":"https://i.ytimg.com/vi/BIWXU3IsssY/default.jpg",
                "width":120,
                "height":90
             },
             "medium":{
                "url":"https://i.ytimg.com/vi/BIWXU3IsssY/mqdefault.jpg",
                "width":320,
                "height":180
             },
             "high":{
                "url":"https://i.ytimg.com/vi/BIWXU3IsssY/hqdefault.jpg",
                "width":480,
                "height":360
             }
          },
          "channelTitle":"Jörgen Lyckebay",
          "liveBroadcastContent":"none"
       }
    },
    {
       "kind":"youtube#searchResult",
       "etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/CaSiQ6lYASTi7Eia0cHbF9Gwkz4\"",
       "id":{
          "kind":"youtube#video",
          "videoId":"F93wt8fZ-vE"
       },
       "snippet":{
          "publishedAt":"2017-06-05T08:21:06.000Z",
          "channelId":"UCYEsDVnEY3xiuuzDFW6g41w",
          "title":"clasohlsonworkwear",
          "description":"smartson #clasohlsonworkwear #testimonial Första testet med byxorna o klev på knapparna gör om som f..",
          "thumbnails":{
             "default":{
                "url":"https://i.ytimg.com/vi/F93wt8fZ-vE/default.jpg",
                "width":120,
                "height":90
             },
             "medium":{
                "url":"https://i.ytimg.com/vi/F93wt8fZ-vE/mqdefault.jpg",
                "width":320,
                "height":180
             },
             "high":{
                "url":"https://i.ytimg.com/vi/F93wt8fZ-vE/hqdefault.jpg",
                "width":480,
                "height":360
             }
          },
          "channelTitle":"Jörgen Lyckebay",
          "liveBroadcastContent":"none"
       }
    },
    {
       "kind":"youtube#searchResult",
       "etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/EYuQkgOEkur8iziKcJuAx76XkmU\"",
       "id":{
          "kind":"youtube#video",
          "videoId":"pW_RJqX0WGM"
       },
       "snippet":{
          "publishedAt":"2017-04-26T15:41:54.000Z",
          "channelId":"UCYEsDVnEY3xiuuzDFW6g41w",
          "title":"Båt motor",
          "description":"Renoverad båtmotor 2.",
          "thumbnails":{
             "default":{
                "url":"https://i.ytimg.com/vi/pW_RJqX0WGM/default.jpg",
                "width":120,
                "height":90
             },
             "medium":{
                "url":"https://i.ytimg.com/vi/pW_RJqX0WGM/mqdefault.jpg",
                "width":320,
                "height":180
             },
             "high":{
                "url":"https://i.ytimg.com/vi/pW_RJqX0WGM/hqdefault.jpg",
                "width":480,
                "height":360
             }
          },
          "channelTitle":"Jörgen Lyckebay",
          "liveBroadcastContent":"none"
       }
}

In that API response, the description begins simply with the word "smartson," not the hashtag.

Any insight on why the API is not in sync with the public YouTube.com link?

Body:
Use the Videos.list. Tried it and it doesn't ignore the hashtag.

Tried it in the API explorer and here's what I got:

"description": " . . .Tap tap tap.\n\n######tapper\n#hashtag\n#dont ignore\n##doublehashtag",

The youtube api returned the complete description, no omissions.


答:
Use concat + drop_duplicates with define columns for check duplicates x and y + reset_index for remove duplicated index values:

```<code>df = pd.concat([df1,df2]).drop_duplicates(['x','y']).reset_index(drop=True)
print (df)
   x  y  z
0  3  7  1
1  7  5  2
2  8  2  3
3  4  5  5
4  7  3  7
5  9  5  3
</code>```

Title: how to merge two data frame with out adding duplicates in Python?

Body:
Use concat + drop_duplicates with define columns for check duplicates x and y + reset_index for remove duplicated index values:

df = pd.concat([df1,df2]).drop_duplicates(['x','y']).reset_index(drop=True)
print (df)
   x  y  z
0  3  7  1
1  7  5  2
2  8  2  3
3  4  5  5
4  7  3  7
5  9  5  3