问:
Selenium WD | A non main class, does not recognize Chrome driver
I have 2 unrelated classes

1) the first, a Main class, I pasted here as a refference. It recognizes Chrome driver very well.

2) The second, a non-main class, Does not recognize my Chrome Driver for some reason

(?) If I open any class that is not a Main, chrome driver is not recognizes inside...Why is that?

Thanks?

Main class that works

```<code>import org.openqa.selenium.By;

//WebElement Practice

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.List;
import org.openqa.selenium.chrome.ChromeDriver;

public class SocketTestsFINAL2Dublicate {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        driver.get("https://www.investing.com");
        driver.navigate().refresh();
        driver.findElement(By.cssSelector("[href = '/markets/']")).click();;

        // list |

        int size = 1;
        for (int i = 0 ; i < size ; ++i) {

            List <WebElement> list2 = driver.findElements(By.cssSelector("[nowrap='nowrap']>a"));

            //Enter the stock page
            size = list2.size();
            Thread.sleep(3000);
            list2.get(i).click();

            Thread.sleep(2000);

            // Print instrument name
            WebElement instrumentName = driver.findElement(By.cssSelector("[class='float_lang_base_1 relativeAttr']"));
            System.out.println(instrumentName.getText());

            // Check if stock is opened/closed
            WebElement Status = null;
            if (Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-1")));
            {
                System.out.println("Stock is closed");
                driver.navigate().back();
            }

            // Stock is opened
            if (Status == driver.findElement(By.cssSelector(".inlineblock.greenClockBigIcon.middle.isOpenExchBig-1014")))
            {
                WebElement e3 = driver.findElement(By.id("last_last")); // Find Socket Element#1
                String newSocket = e3.getText();
                Thread.sleep(1);

                String printold = newSocket; // Old socket value for print on screen
                String lettersOnlynewSocket1 = newSocket.replaceAll("[\\W]", ""); // remove punctuations
                double CurrentSocketValue = Double.valueOf(lettersOnlynewSocket1); // !! Parsing from String to double

                double OldSocketValue = CurrentSocketValue ;

                Thread.sleep(90000);

                WebElement e4 = driver.findElement(By.id("last_last")); //  Find Socket Element#2
                newSocket = e4.getText();
                String printNew = newSocket; // New socket value for print on screen

                String lettersOnlynewSocket2 = newSocket.replaceAll("[\\W]", ""); // remove punctuations
                CurrentSocketValue = Double.valueOf(lettersOnlynewSocket2);

                // Status is : CurrentSocket = After waiting socket upated | oldSocket = Before socket update

                if (CurrentSocketValue == OldSocketValue ) // If socket is not updated - Print 'Fail'

                    System.out.println("Socket is not updated");

                else
                {
                    System.out.println("Socket is updated succesfully");
                }

                System.out.println("Current value is:" +printNew +"old value is:" +printold);
                driver.navigate().back();

            }

        }
    }
}
</code>```

But this, Non main class, does not work

```<code>    import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SocketNotMain {
    System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();

driver.get("https://www.investing.com");
driver.navigate().refresh();
driver.findElement(By.cssSelector("[href = '/markets/']")).click();;

    public boolean isAvailable ()
    {
        return false;

    }

}
</code>```

答:
As a sequence of the comment above by @Grasshopper Your non main class should be like this.</p>

```<code>  public class SocketNotMain {

    @Test
    public void testSomething() {
        System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        driver.get("https://www.investing.com");
        driver.navigate().refresh();
        driver.findElement(By.cssSelector("[href = '/markets/']")).click();
    }

}
</code>```

Body:
I have 2 unrelated classes

1) the first, a Main class, I pasted here as a refference. It recognizes Chrome driver very well.

2) The second, a non-main class, Does not recognize my Chrome Driver for some reason

(?) If I open any class that is not a Main, chrome driver is not recognizes inside...Why is that?

Thanks?

Main class that works

import org.openqa.selenium.By;

//WebElement Practice

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.List;
import org.openqa.selenium.chrome.ChromeDriver;

public class SocketTestsFINAL2Dublicate {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        driver.get("https://www.investing.com");
        driver.navigate().refresh();
        driver.findElement(By.cssSelector("[href = '/markets/']")).click();;

        // list |

        int size = 1;
        for (int i = 0 ; i < size ; ++i) {

            List <WebElement> list2 = driver.findElements(By.cssSelector("[nowrap='nowrap']>a"));

            //Enter the stock page
            size = list2.size();
            Thread.sleep(3000);
            list2.get(i).click();

            Thread.sleep(2000);

            // Print instrument name
            WebElement instrumentName = driver.findElement(By.cssSelector("[class='float_lang_base_1 relativeAttr']"));
            System.out.println(instrumentName.getText());

            // Check if stock is opened/closed
            WebElement Status = null;
            if (Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-1")));
            {
                System.out.println("Stock is closed");
                driver.navigate().back();
            }

            // Stock is opened
            if (Status == driver.findElement(By.cssSelector(".inlineblock.greenClockBigIcon.middle.isOpenExchBig-1014")))
            {
                WebElement e3 = driver.findElement(By.id("last_last")); // Find Socket Element#1
                String newSocket = e3.getText();
                Thread.sleep(1);

                String printold = newSocket; // Old socket value for print on screen
                String lettersOnlynewSocket1 = newSocket.replaceAll("[\\W]", ""); // remove punctuations
                double CurrentSocketValue = Double.valueOf(lettersOnlynewSocket1); // !! Parsing from String to double

                double OldSocketValue = CurrentSocketValue ;

                Thread.sleep(90000);

                WebElement e4 = driver.findElement(By.id("last_last")); //  Find Socket Element#2
                newSocket = e4.getText();
                String printNew = newSocket; // New socket value for print on screen

                String lettersOnlynewSocket2 = newSocket.replaceAll("[\\W]", ""); // remove punctuations
                CurrentSocketValue = Double.valueOf(lettersOnlynewSocket2);

                // Status is : CurrentSocket = After waiting socket upated | oldSocket = Before socket update

                if (CurrentSocketValue == OldSocketValue ) // If socket is not updated - Print 'Fail'

                    System.out.println("Socket is not updated");

                else
                {
                    System.out.println("Socket is updated succesfully");
                }

                System.out.println("Current value is:" +printNew +"old value is:" +printold);
                driver.navigate().back();

            }

        }
    }
}

But this, Non main class, does not work

    import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SocketNotMain {
    System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();

driver.get("https://www.investing.com");
driver.navigate().refresh();
driver.findElement(By.cssSelector("[href = '/markets/']")).click();;

    public boolean isAvailable ()
    {
        return false;

    }

}

Body:
As a sequence of the comment above by @Grasshopper Your non main class should be like this.

  public class SocketNotMain {

    @Test
    public void testSomething() {
        System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        driver.get("https://www.investing.com");
        driver.navigate().refresh();
        driver.findElement(By.cssSelector("[href = '/markets/']")).click();
    }

}


来源: stackexchange

问:
JS. using setTimeout in different places of function leads to different results
I learned JS and stuck with the behavior I can't explain or find answer at the web.

There are two similar functions:

```<code>  function count1(){
    if (i<(1e9+1)-1e6){
      setTimeout(count1,0)
    }
    do{
      i++
    } while(i%1e6!=0)

    if (i==1e9){
      console.log('Done1 in '+(Date.now()-start)+'ms')
    }
  }
  function count2(){

    do{
      i++
    } while(i%1e6!=0)

    if (i==1e9){
      console.log('Done2 in '+(Date.now()-start)+'ms')
    }
    if (i<(1e9+1)-1e6){
      setTimeout(count2,0)
    }
  }

  let start=Date.now();
  let i=0;
//  count1();
  count2();

  //why count2 is faster?

</script>
</code>```

In Chrome the count1 function takes arount 5000 ms, while the count2 takes around 8000 ms. As you can see the only difference is that the "setTimeout" code is located in different places. Would you please help me to understand why so tiny difference in code leads to so huge difference in time consuming.

Thanks in advance.

答: In the first function, you start the timer then execute the loop in parallel to the timer. In the second function, you start the timer after finishing the loop (serially) </p>

ContentLicense: CC BY-SA 3.0

Body:
I learned JS and stuck with the behavior I can't explain or find answer at the web.

There are two similar functions:

  function count1(){
    if (i<(1e9+1)-1e6){
      setTimeout(count1,0)
    }
    do{
      i++
    } while(i%1e6!=0)

    if (i==1e9){
      console.log('Done1 in '+(Date.now()-start)+'ms')
    }
  }
  function count2(){

    do{
      i++
    } while(i%1e6!=0)

    if (i==1e9){
      console.log('Done2 in '+(Date.now()-start)+'ms')
    }
    if (i<(1e9+1)-1e6){
      setTimeout(count2,0)
    }
  }

  let start=Date.now();
  let i=0;
//  count1();
  count2();

  //why count2 is faster?

</script>

In Chrome the count1 function takes arount 5000 ms, while the count2 takes around 8000 ms. As you can see the only difference is that the "setTimeout" code is located in different places. Would you please help me to understand why so tiny difference in code leads to so huge difference in time consuming.

Thanks in advance.


问:
How to fuzzy match movie titles with difflib and pandas?
I have 2 lists of potentially overlapping movie titles, but possibly written in a different form.

They are in 2 different dataframes from pandas. So I have tried to use the map() function with the fuzzywuzzy library like so:

```<code>df1.title.map(lambda x: process.extractOne(x, choices=df2.title, score_cutoff=95))
</code>```

Which gives some good quality results. But the time complexity is such that I can only run it on a very small subset of both data frames. When I try incrementing the size of the data frames then it rapidly becomes unusable.

Then I tried to replace fuzzywuzzy with difflib. And it is much faster. But I can't get the results I want.

At first I tried:

```<code>df1.title.map(lambda x: difflib.get_close_matches(x, df2.title, n=1)
</code>```

And that was fast but the quality of the results was poor. Even missing some simple uppercase / lowercase changes. Playing with the cutoff did not help.

So I thought I was using the wrong tool. In the docs and examples I saw get_close_matches used on single words. In titles there are various words.

Is SequenceMatcher a better choice?

And if yes, then how do I fit it into the map() so it does the same as the aforementioned functions: return only the best result, and only if the result is above a certain ratio?

答:
I have written a Python package which aims to solve this problem.  Amongst other things, it addresses the n^2 complexity of the problem (e.g. with two datasets of length 100, your code needs 10,000 comparisons).

You can install it using pip install fuzzymatcher

You can find the repo here and docs here.

Basic usage:

Given two dataframes df_left and df_right, which you want to fuzzy join, you can write the following:

```<code>from fuzzymatcher import link_table, left join

# Columns to match on from df_left
left_on = ["fname", "mname", "lname",  "dob"]

# Columns to match on from df_right
right_on = ["name", "middlename", "surname", "date"]

# The link table potentially contains several matches for each record
fuzzymatcher.link_table(df_left, df_right, left_on, right_on)
</code>```

Or if you just want to link on the closest match:

```<code>fuzzymatcher.fuzzy_left_join(df_left, df_right, left_on, right_on)
</code>```

Body:
I have 2 lists of potentially overlapping movie titles, but possibly written in a different form.

They are in 2 different dataframes from pandas. So I have tried to use the map() function with the fuzzywuzzy library like so:

df1.title.map(lambda x: process.extractOne(x, choices=df2.title, score_cutoff=95))

Which gives some good quality results. But the time complexity is such that I can only run it on a very small subset of both data frames. When I try incrementing the size of the data frames then it rapidly becomes unusable.

Then I tried to replace fuzzywuzzy with difflib. And it is much faster. But I can't get the results I want.

At first I tried:

df1.title.map(lambda x: difflib.get_close_matches(x, df2.title, n=1)

And that was fast but the quality of the results was poor. Even missing some simple uppercase / lowercase changes. Playing with the cutoff did not help.

So I thought I was using the wrong tool. In the docs and examples I saw get_close_matches used on single words. In titles there are various words.

Is SequenceMatcher a better choice?

And if yes, then how do I fit it into the map() so it does the same as the aforementioned functions: return only the best result, and only if the result is above a certain ratio?

Body:
I have written a Python package which aims to solve this problem.  Amongst other things, it addresses the n^2 complexity of the problem (e.g. with two datasets of length 100, your code needs 10,000 comparisons).

You can install it using pip install fuzzymatcher

You can find the repo here and docs here.

Basic usage:

Given two dataframes df_left and df_right, which you want to fuzzy join, you can write the following:

from fuzzymatcher import link_table, left join

# Columns to match on from df_left
left_on = ["fname", "mname", "lname",  "dob"]

# Columns to match on from df_right
right_on = ["name", "middlename", "surname", "date"]

# The link table potentially contains several matches for each record
fuzzymatcher.link_table(df_left, df_right, left_on, right_on)

Or if you just want to link on the closest match:

fuzzymatcher.fuzzy_left_join(df_left, df_right, left_on, right_on)


问:
DrawerNavigator inside StackNavigator using react-navigation
I am trying to replicate the below design but I cannot find much information on how to implement DrawerNavigator for a specific screen and hook it up with redux. DrawerNavigator to be independent of the routes. All I want is a profile pic, name of the user, log out button and app version

答:
I assume that your app is going to have 2 main navigators which are for authentication and main navigator. If you use react-navigation, you may want to wrap DrawerNavigator inside the StackNavigator, as illustrated below.

```<code>-StackNavigator
    -LoginScreen
    -DrawerNavigator
        -Settings
        -Logout
        -Credits
        -Join beta group
        -Send debug logs
</code>```

For starters, it is good to have a look at the tutorial from InfiniteRed where they put together a pretty decent tutorial, here. However, I believe the tutorial is a bit outdated as it is not compatible with the latest react-native version, at least for my case.

If you are already well-versed with redux and wish to integrate navigators into your app, you may want to have a look at kyaroru's neat implementation.

On the other hand, if you are using RNRF (I am on version 4.0.0-beta.22), this is the structure you may want to stick with, where DrawerComponent is just a pretty straightforward class.

```<code>export default class RouterComponent extends Component {
  render() {
    return (
      <Router>
        <Scene key="root" hideNavBar>
          <Scene key="splashScreen" component={SplashScreen} />
          <Scene key="auth" hideNavBar>
            <Scene key="signIn" component={SignIn} />
            <Scene key="signUp" component={SignUp} />
          </Scene>
          <Drawer
            hideNavBar
            key="drawer"
            contentComponent={DrawerComponent}
            drawerIcon={() => <Feather name="menu" size={24} color="#000" style={{ paddingLeft: 20 }} />}
            drawerWidth={300}>
            <Scene key="main">
              <Scene key="home" component={Home} title="Home" />
              <Scene key="profile" component={Profile} title="Profile" />
            </Scene>
          </Drawer>
        </Scene>
      </Router>
    )
  }
}

class DrawerComponent extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Drawer Content</Text>
        <TouchableOpacity onPress={Actions.home}>
          <Text>Home</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={Actions.profile}>
          <Text>Profile</Text>
        </TouchableOpacity>
      </View >
    );
  }
}
</code>```

Body:
I assume that your app is going to have 2 main navigators which are for authentication and main navigator. If you use react-navigation, you may want to wrap DrawerNavigator inside the StackNavigator, as illustrated below.

-StackNavigator
    -LoginScreen
    -DrawerNavigator
        -Settings
        -Logout
        -Credits
        -Join beta group
        -Send debug logs

For starters, it is good to have a look at the tutorial from InfiniteRed where they put together a pretty decent tutorial, here. However, I believe the tutorial is a bit outdated as it is not compatible with the latest react-native version, at least for my case.

If you are already well-versed with redux and wish to integrate navigators into your app, you may want to have a look at kyaroru's neat implementation.

On the other hand, if you are using RNRF (I am on version 4.0.0-beta.22), this is the structure you may want to stick with, where DrawerComponent is just a pretty straightforward class.

export default class RouterComponent extends Component {
  render() {
    return (
      <Router>
        <Scene key="root" hideNavBar>
          <Scene key="splashScreen" component={SplashScreen} />
          <Scene key="auth" hideNavBar>
            <Scene key="signIn" component={SignIn} />
            <Scene key="signUp" component={SignUp} />
          </Scene>
          <Drawer
            hideNavBar
            key="drawer"
            contentComponent={DrawerComponent}
            drawerIcon={() => <Feather name="menu" size={24} color="#000" style={{ paddingLeft: 20 }} />}
            drawerWidth={300}>
            <Scene key="main">
              <Scene key="home" component={Home} title="Home" />
              <Scene key="profile" component={Profile} title="Profile" />
            </Scene>
          </Drawer>
        </Scene>
      </Router>
    )
  }
}

class DrawerComponent extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Drawer Content</Text>
        <TouchableOpacity onPress={Actions.home}>
          <Text>Home</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={Actions.profile}>
          <Text>Profile</Text>
        </TouchableOpacity>
      </View >
    );
  }
}


问:
Magento CMS pages menu
I have modified the code from Magento static pages menu a little bit to include a class for the active menu link.

```<code><div>
<?php $collection = Mage::getModel('cms/page')->getCollection()->addStoreFilter(Mage::app()->getStore()->getId());?>
<?php  $collection->getSelect()
      ->where('is_active = 1'); ?>
<ul id="nav-top-list">
<?php foreach ($collection as $page): ?>
  <?php $PageData = $page->getData(); ?>
  <?php if($PageData['menu']!= 'false') { ?>
  <li>
    <a href="/<?php echo $PageData['identifier']?>"<?php if ($url == "/".$PageData['identifier']) { ?>class="active"<?php } ?>><?php echo $PageData['title'] ?></a>
  </li>
  <?php } ?>
<?php endforeach; ?>
</code>```

And I have added a new field to the CMS pages to specify if the page should be included in the menu by using true or false. Actually, as you can see above I am only checking for a setting of false, everything else will get a link. You'll need to add a new field to the cms_page table if you are going to use this.

```<code>        $fieldset->addField('menu', 'text', array(
        'name'      => 'menu',
        'label'     => Mage::helper('cms')->__('On Menu'),
        'title'     => Mage::helper('cms')->__('On Menu'),
        'required'  => true,
        'disabled'  => $isElementDisabled
    ));
</code>```

I have also added another field to the CMS pages named sortorder which contains a number for the order the links should be on the menu. Has anybody got any tips on how I could use the new sortorder field to sort the order of the menu links?

Cheers

答:
Have you tried something like?:</p>

```<code>$collection=Mage::getModel('cms/page')->getCollection()->addStoreFilter(
    Mage::app()->getStore()->getId())->setOrder('sortorder', 'asc');
</code>```

ContentLicense: CC BY-SA 2.5

Title: Magento CMS pages menu

Body:
I have modified the code from Magento static pages menu a little bit to include a class for the active menu link.

<?php $collection = Mage::getModel('cms/page')->getCollection()->addStoreFilter(Mage::app()->getStore()->getId());?>
<?php  $collection->getSelect()
      ->where('is_active = 1'); ?>

<?php foreach ($collection as $page): ?>
  <?php $PageData = $page->getData(); ?>
  <?php if($PageData['menu']!= 'false') { ?>

    <a href="/<?php echo $PageData['identifier']?>"<?php if ($url == "/".$PageData['identifier']) { ?>class="active"<?php } ?>><?php echo $PageData['title'] ?>

  <?php } ?>
<?php endforeach; ?>

And I have added a new field to the CMS pages to specify if the page should be included in the menu by using true or false. Actually, as you can see above I am only checking for a setting of false, everything else will get a link. You'll need to add a new field to the cms_page table if you are going to use this.

        $fieldset->addField('menu', 'text', array(
        'name'      => 'menu',
        'label'     => Mage::helper('cms')->__('On Menu'),
        'title'     => Mage::helper('cms')->__('On Menu'),
        'required'  => true,
        'disabled'  => $isElementDisabled
    ));

I have also added another field to the CMS pages named sortorder which contains a number for the order the links should be on the menu. Has anybody got any tips on how I could use the new sortorder field to sort the order of the menu links?

Cheers

Body:
Have you tried something like?:

$collection=Mage::getModel('cms/page')->getCollection()->addStoreFilter(
    Mage::app()->getStore()->getId())->setOrder('sortorder', 'asc');


问:
HOW TO sum two OR MULTIPLE ROWS SAME ID IN DjANGO?
```<code>Bill# | Product | Quantity | price1 | price2 | total
---------------------------------------------------
PK-20 | prod    | 2        | 1110   | 3700     | 2590
PK-20 | prod    | 2        | 550    | 3700     | 3145
PK-21 | prod    | 3        | 550    | 3700     | 3145
PK-21 | prod    | 3        | 550    | 3700     | 3145
</code>```

I need SUM of total column sum same ID. MY query is.

```<code>filtered_record = BillManagement.objects.filter(
    creation_date__range=[date, date1], **kwargs
).annotate(
    price=F('product__cost') - F('customerproductbill__discounted_price')
).annotate(total_spent=Sum('price')
).values_list(
    'bill_number',
    'product__product_name',
    'quantity',
    'distype__percentage_discount',
    'customerproductbill__discounted_price',
    'product__cost',
    'price',
    'customerservicebill__discounted_price',
    'total_spent'
).distinct()
</code>```

答:
Here is Answer</p>

```<code>SELECT DISTINCT "billing_billmanagement"."creation_date",
                    "billing_billmanagement"."bill_number",
                    "auth_user"."first_name",
                    "billing_billmanagement"."quantity",
                    SUM(DISTINCT("billing_customerproductbill"."discounted_price")),
                     array_agg(distinct(CASE
                      WHEN "inventory_product"."product_name" = "product_name"
                    THEN "product_name"
                      ELSE 'NULL'
                      END))
                      AS "product",
                      array_agg(distinct(CASE
                      WHEN "billing_customerproductbill"."bill_id" = "billing_customerproductbill"."bill_id"
                      THEN "billing_customerproductbill"."discounted_price"
                      END))
                      AS "Product_Discount",
                      array_agg(distinct(CASE
                     WHEN "services_service"."name" = "name"
                    THEN "name"
                      ELSE 'NULL'
                     END)) AS "service",
                      array_agg(distinct(CASE
                      WHEN "billing_customerservicebill"."bill_id" = "billing_customerservicebill"."bill_id"
                       THEN "billing_customerservicebill"."discounted_price"
                       END))
                       AS "SERVICE_DISCOUNT",
                        SUM(DISTINCT("billing_customerservicebill"."discounted_price")),
                       "billing_billmanagement"."total_amount",
                       "billing_customer"."first_name"
    FROM "billing_billmanagement"
    INNER JOIN "users_staffuser" ON ("billing_billmanagement"."staff_id" = "users_staffuser"."id")
    INNER JOIN "auth_user" ON ("users_staffuser"."user_id" = "auth_user"."id")
    LEFT OUTER JOIN "billing_customerproductbill" ON ("billing_billmanagement"."id" = "billing_customerproductbill"."bill_id")
    LEFT OUTER JOIN "inventory_product" ON ("billing_customerproductbill"."product_id" = "inventory_product"."id")
    LEFT OUTER JOIN "billing_customerservicebill" ON ("billing_billmanagement"."id" = "billing_customerservicebill"."bill_id")
    LEFT OUTER JOIN "services_service" ON ("billing_customerservicebill"."service_id" = "services_service"."id")
    LEFT OUTER JOIN "billing_customer" ON ("billing_billmanagement"."customer_id" = "billing_customer"."id")
    WHERE "billing_billmanagement"."creation_date" BETWEEN '2017-11-01' AND '2017-12-02'
    group by billing_billmanagement.creation_date,billing_billmanagement.bill_number, auth_user.first_name, billing_billmanagement.quantity,
             billing_billmanagement.total_amount,billing_customer.first_name
    ORDER BY "billing_billmanagement"."creation_date" ASC
</code>```

Body:
Bill# | Product | Quantity | price1 | price2 | total
---------------------------------------------------
PK-20 | prod    | 2        | 1110   | 3700     | 2590
PK-20 | prod    | 2        | 550    | 3700     | 3145
PK-21 | prod    | 3        | 550    | 3700     | 3145
PK-21 | prod    | 3        | 550    | 3700     | 3145

I need SUM of total column sum same ID. MY query is.

filtered_record = BillManagement.objects.filter(
    creation_date__range=[date, date1], **kwargs
).annotate(
    price=F('product__cost') - F('customerproductbill__discounted_price')
).annotate(total_spent=Sum('price')
).values_list(
    'bill_number',
    'product__product_name',
    'quantity',
    'distype__percentage_discount',
    'customerproductbill__discounted_price',
    'product__cost',
    'price',
    'customerservicebill__discounted_price',
    'total_spent'
).distinct()

Body:
Here is Answer

SELECT DISTINCT "billing_billmanagement"."creation_date",
                    "billing_billmanagement"."bill_number",
                    "auth_user"."first_name",
                    "billing_billmanagement"."quantity",
                    SUM(DISTINCT("billing_customerproductbill"."discounted_price")),
                     array_agg(distinct(CASE
                      WHEN "inventory_product"."product_name" = "product_name"
                    THEN "product_name"
                      ELSE 'NULL'
                      END))
                      AS "product",
                      array_agg(distinct(CASE
                      WHEN "billing_customerproductbill"."bill_id" = "billing_customerproductbill"."bill_id"
                      THEN "billing_customerproductbill"."discounted_price"
                      END))
                      AS "Product_Discount",
                      array_agg(distinct(CASE
                     WHEN "services_service"."name" = "name"
                    THEN "name"
                      ELSE 'NULL'
                     END)) AS "service",
                      array_agg(distinct(CASE
                      WHEN "billing_customerservicebill"."bill_id" = "billing_customerservicebill"."bill_id"
                       THEN "billing_customerservicebill"."discounted_price"
                       END))
                       AS "SERVICE_DISCOUNT",
                        SUM(DISTINCT("billing_customerservicebill"."discounted_price")),
                       "billing_billmanagement"."total_amount",
                       "billing_customer"."first_name"
    FROM "billing_billmanagement"
    INNER JOIN "users_staffuser" ON ("billing_billmanagement"."staff_id" = "users_staffuser"."id")
    INNER JOIN "auth_user" ON ("users_staffuser"."user_id" = "auth_user"."id")
    LEFT OUTER JOIN "billing_customerproductbill" ON ("billing_billmanagement"."id" = "billing_customerproductbill"."bill_id")
    LEFT OUTER JOIN "inventory_product" ON ("billing_customerproductbill"."product_id" = "inventory_product"."id")
    LEFT OUTER JOIN "billing_customerservicebill" ON ("billing_billmanagement"."id" = "billing_customerservicebill"."bill_id")
    LEFT OUTER JOIN "services_service" ON ("billing_customerservicebill"."service_id" = "services_service"."id")
    LEFT OUTER JOIN "billing_customer" ON ("billing_billmanagement"."customer_id" = "billing_customer"."id")
    WHERE "billing_billmanagement"."creation_date" BETWEEN '2017-11-01' AND '2017-12-02'
    group by billing_billmanagement.creation_date,billing_billmanagement.bill_number, auth_user.first_name, billing_billmanagement.quantity,
             billing_billmanagement.total_amount,billing_customer.first_name
    ORDER BY "billing_billmanagement"."creation_date" ASC


问:
How to get output from python2 subprocess which run a script using multiprocessing?
Here is my demo code. It contains two scripts.

The first is main.py, it will call print_line.py with subprocess module.

The second is print_line.py, it prints something to the stdout.

main.py

```<code>import subprocess

p = subprocess.Popen('python2 print_line.py',
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     close_fds=True,
                     shell=True,
                     universal_newlines=True)

while True:
    line = p.stdout.readline()
    if line:
        print(line)
    else:
        break
</code>```

print_line.py

```<code>from multiprocessing import Process, JoinableQueue, current_process

if __name__ == '__main__':
    task_q = JoinableQueue()

    def do_task():
        while True:
            task = task_q.get()
            pid = current_process().pid
            print 'pid: {}, task: {}'.format(pid, task)
            task_q.task_done()

    for _ in range(10):
        p = Process(target=do_task)
        p.daemon = True
        p.start()

    for i in range(100):
        task_q.put(i)

    task_q.join()
</code>```

Before, print_line.py is written with threading and Queue module, everything is fine. But now, after changing to multiprocessing module, the main.py cannot get any output from print_line. I tried to use Popen.communicate() to get the output or set preexec_fn=os.setsid inPopen(). Neither of them work.

So, here is my question:

Why subprocess cannot get the output with multiprocessing? why it is ok with threading?

If I comment out stdout=subprocess.PIPE and stderr=subprocess.PIPE, the output is printed in my console. Why? How does this happen?

Is there any chance to get the output from print_line.py?

答:
Curious.

In theory this should work as it is, but it does not. The reason being somewhere in the deep, murky waters of buffered IO. It seems that the output of a subprocess of a subprocess can get lost if not flushed.

You have two workarounds:

One is to use flush() in your print_line.py:

```<code>def do_task():
    while True:
        task = task_q.get()
        pid = current_process().pid
        print 'pid: {}, task: {}'.format(pid, task)
        sys.stdout.flush()
        task_q.task_done()
</code>```

This will fix the issue as you will flush your stdout as soon as you have written something to it.

Another option is to use -u flag to Python in your main.py:

```<code>p = subprocess.Popen('python2 -u print_line.py',
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     close_fds=True,
                     shell=True,
                     universal_newlines=True)
</code>```

-u will force stdin and stdout to be completely unbuffered in print_line.py, and children of print_line.py will then inherit this behaviour.

These are workarounds to the problem. If you are interested in the theory why this happens, it definitely has something to do with unflushed stdout being lost if subprocess terminates, but I am not the expert in this.

Body:
Here is my demo code. It contains two scripts.

The first is main.py, it will call print_line.py with subprocess module.

The second is print_line.py, it prints something to the stdout.

main.py

import subprocess

p = subprocess.Popen('python2 print_line.py',
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     close_fds=True,
                     shell=True,
                     universal_newlines=True)

while True:
    line = p.stdout.readline()
    if line:
        print(line)
    else:
        break

print_line.py

from multiprocessing import Process, JoinableQueue, current_process

if __name__ == '__main__':
    task_q = JoinableQueue()

    def do_task():
        while True:
            task = task_q.get()
            pid = current_process().pid
            print 'pid: {}, task: {}'.format(pid, task)
            task_q.task_done()

    for _ in range(10):
        p = Process(target=do_task)
        p.daemon = True
        p.start()

    for i in range(100):
        task_q.put(i)

    task_q.join()

Before, print_line.py is written with threading and Queue module, everything is fine. But now, after changing to multiprocessing module, the main.py cannot get any output from print_line. I tried to use Popen.communicate() to get the output or set preexec_fn=os.setsid inPopen(). Neither of them work.

So, here is my question:

Why subprocess cannot get the output with multiprocessing? why it is ok with threading?

If I comment out stdout=subprocess.PIPE and stderr=subprocess.PIPE, the output is printed in my console. Why? How does this happen?

Is there any chance to get the output from print_line.py?

Body:
Curious.

In theory this should work as it is, but it does not. The reason being somewhere in the deep, murky waters of buffered IO. It seems that the output of a subprocess of a subprocess can get lost if not flushed.

You have two workarounds:

One is to use flush() in your print_line.py:

def do_task():
    while True:
        task = task_q.get()
        pid = current_process().pid
        print 'pid: {}, task: {}'.format(pid, task)
        sys.stdout.flush()
        task_q.task_done()

This will fix the issue as you will flush your stdout as soon as you have written something to it.

Another option is to use -u flag to Python in your main.py:

p = subprocess.Popen('python2 -u print_line.py',
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     close_fds=True,
                     shell=True,
                     universal_newlines=True)

-u will force stdin and stdout to be completely unbuffered in print_line.py, and children of print_line.py will then inherit this behaviour.

These are workarounds to the problem. If you are interested in the theory why this happens, it definitely has something to do with unflushed stdout being lost if subprocess terminates, but I am not the expert in this.


问:
Print settings in AutoCAD
I wanted to know how to print the AutoCAD file so that only the numbers displayed in the DIMENSIONS and the DIMENSION'S lines are not displayed.
And how to increase the size of the DIMENSION'S text.
I do not know much about English, so I would apologize if I wrote a mistake. Thanks;</p>

答:
Did not anyone understand me? Or was there no answer to my question?
If you've used SolidWorks before, you might have seen that when you want to print a map or project, there is an option available, which if you select it, the DIMENSION lines will hide, but their numbers will still be displayed.
I mean, this is such a feature for AutoCAD. Is AutoCAD Capable? How to use this feature?</p>

Title: Print settings in AutoCAD


问:
Can a class with all private members be a POD class?
I've heard before that POD types cannot have private data -- but according to the C++0x draft I have the requirement is looser (emphasis mine):

has the same access control (Clause 11) for all non-static data members

which seems to suggest that private data is okay so long as it's all private. I don't have a copy of C++03 though to check...

Would then, WindowsApi::Uuid be a POD class?

```<code>namespace WindowsApi
{
    class Uuid
    {
        union
        {
            ::UUID asUuid; //Win32's UUID struct
            unsigned __int64 asInt64s[2];
            unsigned __int32 asInt32s[4];
        };
    public:
        Uuid() {}
        Uuid(::UUID sourceStructure) : asUuid(sourceStructure) {}
        operator ::UUID() { return asUuid; }
    };
}
</code>```

答:
According to my n3225 C++0x draft, WindowsApi::Uuid is a POD class.

From page 219:
A POD struct is a class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types).

A trivial class is a class that has a trivial default constructor and is trivially copyable:

A trivially copyable class is a class that:

has no non-trivial copy constructors (12.8),

has no non-trivial move constructors (12.8),

has no non-trivial copy assignment operators (13.5.3, 12.8),

has no non-trivial move assignment operators (13.5.3, 12.8), and

has a trivial destructor (12.4).

A standard-layout class is a class that:

has no non-static data members of type non-standard-layout class (or array of such types) or reference,

has no virtual functions (10.3) and no virtual base classes (10.1),

has the same access control (Clause 11) for all non-static data members,

has no non-standard-layout base classes,

either has no non-static data members in the most-derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and

has no base classes of the same type as the first non-static data member.

Since WindowsApi doesn't violate any of these constraints, it will be a valid POD class under C++0x.  As AndreyT mentions, this is a more generous wording than C++03.

Body:
I've heard before that POD types cannot have private data -- but according to the C++0x draft I have the requirement is looser (emphasis mine):

has the same access control (Clause 11) for all non-static data members

which seems to suggest that private data is okay so long as it's all private. I don't have a copy of C++03 though to check...

Would then, WindowsApi::Uuid be a POD class?

namespace WindowsApi
{
    class Uuid
    {
        union
        {
            ::UUID asUuid; //Win32's UUID struct
            unsigned __int64 asInt64s[2];
            unsigned __int32 asInt32s[4];
        };
    public:
        Uuid() {}
        Uuid(::UUID sourceStructure) : asUuid(sourceStructure) {}
        operator ::UUID() { return asUuid; }
    };
}


问:
Php pdo rollBack() not working for update statement
I use PHP PDO transaction. I have insert and update statements and I would like to rollback the transaction when rowCount() return 0. Please see the sample code below.

```<code><?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '', array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false
));

$userIds = [1,2,""];
$paymentAmounts = [10.50,20.50,30.50];
$error = array();

$pdo->beginTransaction();

try
{
    foreach($userIds as $key => $userId )
    {
        $sql = "INSERT INTO payments (user_id, amount) VALUES (?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(
                $userId,
                $paymentAmounts[$key]
            )
        );

        if($stmt->rowCount() <= 0)
        {
            $error[] = ["Error occurred in userId: ".$userId];
        }

        $sql = "UPDATE users SET credit = ? WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(
                $paymentAmounts[$key],
                $userId
            )
        );
        if($stmt->rowCount() <= 0)
        {
            $error[] = ["Error occurred in userId: ".$userId];
        }
    }
    if(!empty($error))
    {
        $displayError = implode(",", $error);
        throw new Exception($displayError);
    }

    // It should not reach here, if there is an error.
    $pdo->commit();

}
catch(Exception $e){
    echo $e->getMessage(); // displayError
    $pdo->rollBack(); // <<<==== It should rollback both Insert and Update to original state
}
?>
</code>```

I have $userIds array. For userId 1 and 2, rowCount() will return 1 for both Insert and Update. But for empty userId, rowCount() will return 0. If rowCount() is 0, I assign the error message into $error[]. If $error is not empty, it will catch in Exception and roll back the transaction for all the $userIds.

My expected result is when $error is not empty, will throw exception and rollback in the catch. It should suppose to remove the records in table payments for userIds (1,2) and update back the original credit value in table users for userIds (1,2).

The result that I get is when the code reaches to $pdo->rollBack(), it only removes the inserted records from the payments table and it did not update back the original credit value into users table for userIds (1,2).

Can you advise on what is the issue with the code?
Thank you.

========== Query for Create Tables and Insert statement ==========

```<code>-- CREATE TABLE "payments" -------------------------------
CREATE TABLE `payments` (
    `id` BigInt( 11 ) UNSIGNED AUTO_INCREMENT NOT NULL,
    `user_id` BigInt( 11 ) UNSIGNED NOT NULL,
    `amount` VarChar( 20 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
    PRIMARY KEY ( `id` ) )
CHARACTER SET = latin1
COLLATE = latin1_swedish_ci
ENGINE = InnoDB
AUTO_INCREMENT = 1;
-- -------------------------------------------------------------

-- CREATE TABLE "users" -------------------------------
CREATE TABLE `users` (
    `id` BigInt( 11 ) UNSIGNED AUTO_INCREMENT NOT NULL,
    `credit` VarChar( 20 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
    PRIMARY KEY ( `id` ) )
CHARACTER SET = latin1
COLLATE = latin1_swedish_ci
ENGINE = InnoDB
AUTO_INCREMENT = 1;
-- -------------------------------------------------------------

INSERT INTO `users` ( `credit`, `id`)
VALUES ( '5', 1 ),( '10', 2 ),( '15', 3 );
</code>```

答:
```<code>$dbport =   3306;
$dbhost =   'localhost';
$dbuser =   'root';
$dbpwd  =   'xxx';
$dbname =   'xxx';

$options=array(
    PDO::ATTR_CURSOR                    =>  PDO::CURSOR_SCROLL,
    PDO::ATTR_PERSISTENT                =>  FALSE,
    PDO::MYSQL_ATTR_USE_BUFFERED_QUERY  =>  TRUE,
    PDO::MYSQL_ATTR_INIT_COMMAND        =>  'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_unicode_ci\', @@sql_mode = STRICT_ALL_TABLES, @@foreign_key_checks = 1'
);

$dsn='mysql:host='.$dbhost.';port='.$dbport.';dbname='.$dbname;
$dbo=new PDO( $dsn, $dbuser, $dbpwd, $options );

        $userIds = array(1,2,3,4,5,6);
        $paymentAmounts = array( 25,30,55,30,45,44 );

        try {

            $dbo->beginTransaction();

            if( count( $userIds )!=count( $paymentAmounts ) ) throw new Exception( sprintf('Unbalanced source arrays: $userids:%d, $paymentAmounts:%d',count( $userIds ),count( $paymentAmounts )));

            foreach( $userIds as $key => $userId ){

                $sql = "insert into payments ( user_id, amount ) values ( ?, ? )";
                $stmt = $dbo->prepare( $sql );
                if( $stmt ){
                    $stmt->execute( array( $userId, $paymentAmounts[ $key ] ) );
                    if( $stmt->rowCount() <= 0 ) throw new Exception( sprintf('Query #1 -> Error occurred in userId: %d count: %d', $userId, $stmt->rowCount() ) );
                } else {
                    throw new Exception( sprintf('Query #1 Prepare method failed @ %d for %d', $paymentAmounts[ $key ], $userId ) );
                }

                $sql = "update users set credit = credit + ? where id = ?";
                $stmt = $dbo->prepare( $sql );
                if( $stmt ) {
                    $stmt->execute( array( $paymentAmounts[ $key ], $userId ) );
                    if( $stmt->rowCount() <= 0 ) throw new Exception( sprintf('Query #2 -> Error occurred in userId: %d count: %d', $userId, $stmt->rowCount() ) );
                } else {
                    throw new Exception( sprintf('Query #2 Prepare method failed @ %d for %d', $paymentAmounts[ $key ], $userId ) );
                }
            }
            $dbo->commit();
        }catch( Exception $e ){
            echo 'Exception Raised: '.$e->getMessage();
            $dbo->rollBack();
        }
</code>```

Before Test 1

```<code>mysql> select * from payments;
Empty set (0.00 sec)

mysql> select * from users;
+------+--------+
| id   | credit |
+------+--------+
|    1 | 0      |
|    2 | 0      |
|    3 | 0      |
|    4 | 0      |
|    5 | 0      |
|    6 | 0      |
+------+--------+
6 rows in set (0.00 sec)
</code>```

After Test #1

```<code>mysql> select * from payments;
+----+---------+--------+
| id | user_id | amount |
+----+---------+--------+
|  1 |       1 | 25     |
|  2 |       2 | 30     |
|  3 |       3 | 55     |
|  4 |       4 | 30     |
|  5 |       5 | 45     |
|  6 |       6 | 44     |
+----+---------+--------+
6 rows in set (0.00 sec)

mysql> select * from users;
+------+--------+
| id   | credit |
+------+--------+
|    1 | 25     |
|    2 | 30     |
|    3 | 55     |
|    4 | 30     |
|    5 | 45     |
|    6 | 44     |
+------+--------+
7 rows in set (0.00 sec)
</code>```

Test #2 ~ deliberately cause an exception - mismatched array lengths using this data:

```<code>        $userIds = array(1,2,3,4,5,6);
        $paymentAmounts = array( 25,30,55,30,45,44,21 );/* <----- extra item to cause exception */
</code>```

This causes the exception:

```<code>Exception Raised: Unbalanced source arrays: $userids:6, $paymentAmounts:7

mysql> select * from users;
+----+--------+
| id | credit |
+----+--------+
|  1 | 25     |
|  2 | 30     |
|  3 | 55     |
|  4 | 30     |
|  5 | 45     |
|  6 | 44     |
+----+--------+
6 rows in set (0.00 sec)
</code>```

The same data as before - the query did not get committed to db after an exception.

Test #3 - fudged query with fake column name

```<code>$sql = "update users set credit = boomerang + ? where id = ?";/* <----- ficticious column cause exception */
</code>```

This causes exception

```<code>Exception Raised: Query #2 -> Error occurred in userId: 1 count: 0

mysql> select * from users;
+----+--------+
| id | credit |
+----+--------+
|  1 | 25     |
|  2 | 30     |
|  3 | 55     |
|  4 | 30     |
|  5 | 45     |
|  6 | 44     |
+----+--------+
6 rows in set (0.00 sec)
</code>```

Again, a quick check reveals no change to the data so it looks like the whole process is working as it should

Body:
I use PHP PDO transaction. I have insert and update statements and I would like to rollback the transaction when rowCount() return 0. Please see the sample code below.

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '', array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false
));

$userIds = [1,2,""];
$paymentAmounts = [10.50,20.50,30.50];
$error = array();

$pdo->beginTransaction();

try
{
    foreach($userIds as $key => $userId )
    {
        $sql = "INSERT INTO payments (user_id, amount) VALUES (?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(
                $userId,
                $paymentAmounts[$key]
            )
        );

        if($stmt->rowCount() <= 0)
        {
            $error[] = ["Error occurred in userId: ".$userId];
        }

        $sql = "UPDATE users SET credit = ? WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(
                $paymentAmounts[$key],
                $userId
            )
        );
        if($stmt->rowCount() <= 0)
        {
            $error[] = ["Error occurred in userId: ".$userId];
        }
    }
    if(!empty($error))
    {
        $displayError = implode(",", $error);
        throw new Exception($displayError);
    }

    // It should not reach here, if there is an error.
    $pdo->commit();

}
catch(Exception $e){
    echo $e->getMessage(); // displayError
    $pdo->rollBack(); // <<<==== It should rollback both Insert and Update to original state
}
?>

I have $userIds array. For userId 1 and 2, rowCount() will return 1 for both Insert and Update. But for empty userId, rowCount() will return 0. If rowCount() is 0, I assign the error message into $error[]. If $error is not empty, it will catch in Exception and roll back the transaction for all the $userIds.

My expected result is when $error is not empty, will throw exception and rollback in the catch. It should suppose to remove the records in table payments for userIds (1,2) and update back the original credit value in table users for userIds (1,2).

The result that I get is when the code reaches to $pdo->rollBack(), it only removes the inserted records from the payments table and it did not update back the original credit value into users table for userIds (1,2).

Can you advise on what is the issue with the code?
Thank you.

========== Query for Create Tables and Insert statement ==========

-- CREATE TABLE "payments" -------------------------------
CREATE TABLE `payments` (
    `id` BigInt( 11 ) UNSIGNED AUTO_INCREMENT NOT NULL,
    `user_id` BigInt( 11 ) UNSIGNED NOT NULL,
    `amount` VarChar( 20 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
    PRIMARY KEY ( `id` ) )
CHARACTER SET = latin1
COLLATE = latin1_swedish_ci
ENGINE = InnoDB
AUTO_INCREMENT = 1;
-- -------------------------------------------------------------

-- CREATE TABLE "users" -------------------------------
CREATE TABLE `users` (
    `id` BigInt( 11 ) UNSIGNED AUTO_INCREMENT NOT NULL,
    `credit` VarChar( 20 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
    PRIMARY KEY ( `id` ) )
CHARACTER SET = latin1
COLLATE = latin1_swedish_ci
ENGINE = InnoDB
AUTO_INCREMENT = 1;
-- -------------------------------------------------------------

INSERT INTO `users` ( `credit`, `id`)
VALUES ( '5', 1 ),( '10', 2 ),( '15', 3 );

Body:
$dbport =   3306;
$dbhost =   'localhost';
$dbuser =   'root';
$dbpwd  =   'xxx';
$dbname =   'xxx';

$options=array(
    PDO::ATTR_CURSOR                    =>  PDO::CURSOR_SCROLL,
    PDO::ATTR_PERSISTENT                =>  FALSE,
    PDO::MYSQL_ATTR_USE_BUFFERED_QUERY  =>  TRUE,
    PDO::MYSQL_ATTR_INIT_COMMAND        =>  'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_unicode_ci\', @@sql_mode = STRICT_ALL_TABLES, @@foreign_key_checks = 1'
);

$dsn='mysql:host='.$dbhost.';port='.$dbport.';dbname='.$dbname;
$dbo=new PDO( $dsn, $dbuser, $dbpwd, $options );

        $userIds = array(1,2,3,4,5,6);
        $paymentAmounts = array( 25,30,55,30,45,44 );

        try {

            $dbo->beginTransaction();

            if( count( $userIds )!=count( $paymentAmounts ) ) throw new Exception( sprintf('Unbalanced source arrays: $userids:%d, $paymentAmounts:%d',count( $userIds ),count( $paymentAmounts )));

            foreach( $userIds as $key => $userId ){

                $sql = "insert into payments ( user_id, amount ) values ( ?, ? )";
                $stmt = $dbo->prepare( $sql );
                if( $stmt ){
                    $stmt->execute( array( $userId, $paymentAmounts[ $key ] ) );
                    if( $stmt->rowCount() <= 0 ) throw new Exception( sprintf('Query #1 -> Error occurred in userId: %d count: %d', $userId, $stmt->rowCount() ) );
                } else {
                    throw new Exception( sprintf('Query #1 Prepare method failed @ %d for %d', $paymentAmounts[ $key ], $userId ) );
                }

                $sql = "update users set credit = credit + ? where id = ?";
                $stmt = $dbo->prepare( $sql );
                if( $stmt ) {
                    $stmt->execute( array( $paymentAmounts[ $key ], $userId ) );
                    if( $stmt->rowCount() <= 0 ) throw new Exception( sprintf('Query #2 -> Error occurred in userId: %d count: %d', $userId, $stmt->rowCount() ) );
                } else {
                    throw new Exception( sprintf('Query #2 Prepare method failed @ %d for %d', $paymentAmounts[ $key ], $userId ) );
                }
            }
            $dbo->commit();
        }catch( Exception $e ){
            echo 'Exception Raised: '.$e->getMessage();
            $dbo->rollBack();
        }

Before Test 1

mysql> select * from payments;
Empty set (0.00 sec)

mysql> select * from users;
+------+--------+
| id   | credit |
+------+--------+
|    1 | 0      |
|    2 | 0      |
|    3 | 0      |
|    4 | 0      |
|    5 | 0      |
|    6 | 0      |
+------+--------+
6 rows in set (0.00 sec)

After Test #1

mysql> select * from payments;
+----+---------+--------+
| id | user_id | amount |
+----+---------+--------+
|  1 |       1 | 25     |
|  2 |       2 | 30     |
|  3 |       3 | 55     |
|  4 |       4 | 30     |
|  5 |       5 | 45     |
|  6 |       6 | 44     |
+----+---------+--------+
6 rows in set (0.00 sec)

mysql> select * from users;
+------+--------+
| id   | credit |
+------+--------+
|    1 | 25     |
|    2 | 30     |
|    3 | 55     |
|    4 | 30     |
|    5 | 45     |
|    6 | 44     |
+------+--------+
7 rows in set (0.00 sec)

Test #2 ~ deliberately cause an exception - mismatched array lengths using this data:

        $userIds = array(1,2,3,4,5,6);
        $paymentAmounts = array( 25,30,55,30,45,44,21 );/* <----- extra item to cause exception */

This causes the exception:

Exception Raised: Unbalanced source arrays: $userids:6, $paymentAmounts:7

mysql> select * from users;
+----+--------+
| id | credit |
+----+--------+
|  1 | 25     |
|  2 | 30     |
|  3 | 55     |
|  4 | 30     |
|  5 | 45     |
|  6 | 44     |
+----+--------+
6 rows in set (0.00 sec)

The same data as before - the query did not get committed to db after an exception.

Test #3 - fudged query with fake column name

$sql = "update users set credit = boomerang + ? where id = ?";/* <----- ficticious column cause exception */

This causes exception

Exception Raised: Query #2 -> Error occurred in userId: 1 count: 0

mysql> select * from users;
+----+--------+
| id | credit |
+----+--------+
|  1 | 25     |
|  2 | 30     |
|  3 | 55     |
|  4 | 30     |
|  5 | 45     |
|  6 | 44     |
+----+--------+
6 rows in set (0.00 sec)

Again, a quick check reveals no change to the data so it looks like the whole process is working as it should


问:
Does GeoServer support OGC publish/subscribe standard?
According to http://www.opengeospatial.org/standards/pubsub only SOAP extension is supported. Does GeoServer's WFS support OGC publish/subscribe standard (GeoServer supports WFS over KVP)?</p>

答: No, GeoServer only supports WMS, WFS, WCS, WMTS and WPS.</p>


问:
System.GC doesnt work on create method
I'm using System.GC  (GC.CollectorOn xamarin) for clearing Garbage collector.
But unfortunately after i will open the activity more than five times i will get error Java.Lang.outof memory. Why this happened? System.GC doesnt click dynamic all my garbage collector?Here is my Code:</p>

```<code>protected override void OnCreate(Bundle savedInstanceState) {
    base.OnCreate(savedInstanceState);
    RequestWindowFeature(WindowFeatures.NoTitle);
    SetContentView(Resource.Layout.CatalogItem);
    imageview = FindViewById < ImageView > (Resource.Id.ItemImageView);

    GC.Collect();
    GC.WaitForPendingFinalizers();
    dpPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "student.db3");
    db = new SQLiteConnection(dpPath);
    var table = db.Query < CatalogItemClass > ("select  ItemImg,_id,InventoryItemName,InventoryItemPrice from CatalogItemClass where CategoryID=1  ");

    foreach(var item in table) {
        Image = item.ItemImg;
    }

    if (Image != null) {
        Bitmap decodedByte = BitmapFactory.DecodeByteArray(Image, 0, Image.Length);
        imageview.SetImageBitmap(decodedByte);
    }
}
</code>```

答:
But unfortunately after i will open the activity more than five times i will get error Java.Lang.outof memory.

As @elmorabea said, there is something that is leaking memory, memory leak will  causes fewer and fewer available Heaps and triggers GC frequently, but the can't recycle these resource and finally OOM happened. In this situation, execute GC won't be able to help you.

So when i'm pressing back press i run FinishAffinity.Then in next activity i run system.gc

You have destroy the object that causes leaking memory so the GC could work again. You could use Android Device Monitor to find what objects is leaking memory :

Solution :

Solve your memory leak issue.

Load your bitmap efficiently.

You could read this document, this recipe shows you how you can load large images into memory without the application throwing an OutOfMemoryException by loading a smaller subsampled version in memory.

Suggestion :

Store image to Sqlite Database is not best practice, you could store images in storage, make them private then keep them inside your app folder and save the path to the Database.

Then you could use some library like Glide and Picasso to load the image, they did a great job when load image. As their document said, fast and efficient image loading for Android, they could help you to solve the OOM problem.

Title: System.GC doesnt work on create method

Body:
I'm using System.GC  (GC.CollectorOn xamarin) for clearing Garbage collector.
But unfortunately after i will open the activity more than five times i will get error Java.Lang.outof memory. Why this happened? System.GC doesnt click dynamic all my garbage collector?Here is my Code:

protected override void OnCreate(Bundle savedInstanceState) {
    base.OnCreate(savedInstanceState);
    RequestWindowFeature(WindowFeatures.NoTitle);
    SetContentView(Resource.Layout.CatalogItem);
    imageview = FindViewById < ImageView > (Resource.Id.ItemImageView);

    GC.Collect();
    GC.WaitForPendingFinalizers();
    dpPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "student.db3");
    db = new SQLiteConnection(dpPath);
    var table = db.Query < CatalogItemClass > ("select  ItemImg,_id,InventoryItemName,InventoryItemPrice from CatalogItemClass where CategoryID=1  ");

    foreach(var item in table) {
        Image = item.ItemImg;
    }

    if (Image != null) {
        Bitmap decodedByte = BitmapFactory.DecodeByteArray(Image, 0, Image.Length);
        imageview.SetImageBitmap(decodedByte);
    }
}


问:
WPF MVVM DataGrid Row to Another DataGrid
In my WPF application using MVVM, I have one DataGrid (dgSelectCase) filled with a bound ObservableCollection from my ViewModel. A Button appears in the first column that, when clicked, should add the selected row to the second DataGrid (dgCaseSelected).

The View DataContext is bound to the ViewModel in its code behind, and I know it works because the other Controls on the page (Comboboxes, Textboxes, etc.) work perfectly. The "Add" Button Command in dgSelectCase is bound to the AddTo method in the ViewModel and the "Remove" Button Command in dgCaseSelected is bound to the RemoveFrom method in the ViewModel.

The "Add" Button is not working, but, more importantly, it looks like I have selection Binding issues in the dgSelectCase DataGrid because I get a red box around the DataGrid when I click on a row. Where have I gone wrong? Thanks for any and all help, as I'm still learning.... slowly :).  Following are Code Snippets.

XAML

```<code>        <DataGrid>
            <DataGrid.Columns>
            <DataGridTemplateColumn Header="Select">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Add" Command="{Binding AddTo}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn Header="Fac ID #" Binding="{Binding FacilityIDNum}"/>
            <DataGridTextColumn Header="OP Case #" Binding="{Binding CaseBookingNum}"/>
            <DataGridTextColumn Header="Booking Type #" Binding="{Binding BookingTypeNum}"/>
            <DataGridTextColumn Header="Booking Type" Binding="{Binding BookingType}"/>
            </DataGrid.Columns>
        </DataGrid>

        <DataGrid x:Name="dgCaseSelected"
              AutoGenerateColumns="False"
              ItemsSource="{Binding DGCaseBookingsSelected}"
              >
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Select">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Remove" Command="{Binding RemoveFrom}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Fac ID #" Binding="{Binding FacilityIDNum}"/>
                <DataGridTextColumn Header="OP Case #" Binding="{Binding CaseBookingNum}"/>
                <DataGridTextColumn Header="Booking Type #" Binding="{Binding BookingTypeNum}"/>
                <DataGridTextColumn Header="Booking Type" Binding="{Binding BookingType}"/>
            </DataGrid.Columns>
        </DataGrid>
</code>```

VIEWMODEL

```<code>    private ObservableCollection<DGCaseBookings> _dgCaseBookingsList;
    private ObservableCollection<DGCaseBookings> _dgSelectedCaseBookings;
    private ObservableCollection<DGCaseBookings> _dgCaseBookingsSelected;

    public ObservableCollection<DGCaseBookings> DGCaseBookingsList
    {
        get { return _dgCaseBookingsList; }
        set
        {
            SetProperty(ref _dgCaseBookingsList, value, () => DGCaseBookingsList);
        }
    }

    public ObservableCollection<DGCaseBookings> DGSelectedCaseBookings
    {
        get { return _dgSelectedCaseBookings; }
        set
        {
            SetProperty(ref _dgSelectedCaseBookings, value, () => DGSelectedCaseBookings);
        }
    }

    public ObservableCollection<DGCaseBookings> DGCaseBookingsSelected
    {
        get { return _dgCaseBookingsSelected; }
        set
        {
            SetProperty(ref _dgCaseBookingsSelected, value, () => DGCaseBookingsSelected);
        }
    }

    public CMBookingSelectVM() : base()
    {
        DGCaseBookingsList = new ObservableCollection<DGCaseBookings>();
        DGCaseBookingsSelected = new ObservableCollection<DGCaseBookings>();
    }

    private void fillDGCaseBookingswithFacility()
    {
        using (MySqlConnection con = new MySqlConnection(dbConnectionString))
        {
            DGCaseBookingsList = new ObservableCollection<DGCaseBookings>();
            con.Open();
            string Query = ///SELECT STATEMENT WORKS FINE///
            MySqlCommand createCommand = new MySqlCommand(Query, con);
            MySqlDataReader dr = createCommand.ExecuteReader();
            int count = 1;
            while (dr.Read())
            {
                int FacilityIDNum = dr.GetInt32(0);
                int CaseBookingNum = dr.GetInt32(1);
                int BookingTypeNum = dr.GetInt32(2);
                string BookingType = dr.GetString(3);
                DGCaseBookings dgcb = new DGCaseBookings(count, FacilityIDNum, CaseBookingNum, BookingTypeNum, BookingType);
                DGCaseBookingsList.Add(dgcb);
                count++;
            }
            con.Close();
        }
    }

    public void AddTo(DGCaseBookings dgcb)
    {
        if (dgcb != null)
        {
            DGCaseBookingsSelected.Add(dgcb);
            DGCaseBookingsList.Remove(dgcb);
        }
    }

    public void RemoveFrom(DGCaseBookings dgcb)
    {
        if (dgcb != null)
        {
            DGCaseBookingsList.Add(dgcb);
            DGCaseBookingsSelected.Remove(dgcb);
        }
    }
</code>```

答:
First of all, you didn't mentioned in your code how you are trying to bind the selected items property of the datagrid to your collection (as a matter of facts you are actually didn't even set the itemsource for the first datagrid), and i think you didn't do that since you actually can't bind the SelectedItems property of the datagrid since it's a readonly property. From now on you have only 2 choice. Find a workaround to send the selected items to your viewmodel, or work on a single row. As for the second approach you can simply do this:

```<code>    <DataGrid ItemsSource="{Binding DGCaseBookingsList}" SelectedItem="{Binding MyItem}" SelectionMode = "Single" SelectionUnit="FullRow">
        <DataGrid.Columns>
        <DataGridTemplateColumn Header="Select">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Content="Add" Command="{Binding AddTo}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Fac ID #" Binding="{Binding FacilityIDNum}"/>
        <DataGridTextColumn Header="OP Case #" Binding="{Binding CaseBookingNum}"/>
        <DataGridTextColumn Header="Booking Type #" Binding="{Binding BookingTypeNum}"/>
        <DataGridTextColumn Header="Booking Type" Binding="{Binding BookingType}"/>
        </DataGrid.Columns>
    </DataGrid>
</code>```

in your VM delete DGSelectedCaseBookings and add the following:

```<code>private DGCaseBookings myItem = new DGCaseBookings();
public DGCaseBookings MyItem
{
    get { return myItem; }
    set
    {
        SetProperty(ref myItem, value, () => MyItem);
    }
}
</code>```

From there you will handle this object using the command of your buttons. Just be sure to implement INotifyPropertyChanged or you won't see any change in your UI.

If you aim to a multiple selection, then the easiest way is to work on the selection changed event of your datagrids. From there you can do something like this.

```<code>private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
     MyVM vm = this.DataContext as MyVM;
     DataGrid s = sender as DataGrid;
     vm.DGSelectedCaseBookings = s.SelectedItems;
}
</code>```

Body:
In my WPF application using MVVM, I have one DataGrid (dgSelectCase) filled with a bound ObservableCollection from my ViewModel. A Button appears in the first column that, when clicked, should add the selected row to the second DataGrid (dgCaseSelected).

The View DataContext is bound to the ViewModel in its code behind, and I know it works because the other Controls on the page (Comboboxes, Textboxes, etc.) work perfectly. The "Add" Button Command in dgSelectCase is bound to the AddTo method in the ViewModel and the "Remove" Button Command in dgCaseSelected is bound to the RemoveFrom method in the ViewModel.

The "Add" Button is not working, but, more importantly, it looks like I have selection Binding issues in the dgSelectCase DataGrid because I get a red box around the DataGrid when I click on a row. Where have I gone wrong? Thanks for any and all help, as I'm still learning.... slowly :).  Following are Code Snippets.

XAML

        <DataGrid>
            <DataGrid.Columns>
            <DataGridTemplateColumn Header="Select">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Add" Command="{Binding AddTo}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn Header="Fac ID #" Binding="{Binding FacilityIDNum}"/>
            <DataGridTextColumn Header="OP Case #" Binding="{Binding CaseBookingNum}"/>
            <DataGridTextColumn Header="Booking Type #" Binding="{Binding BookingTypeNum}"/>
            <DataGridTextColumn Header="Booking Type" Binding="{Binding BookingType}"/>
            </DataGrid.Columns>
        </DataGrid>

        <DataGrid x:Name="dgCaseSelected"
              AutoGenerateColumns="False"
              ItemsSource="{Binding DGCaseBookingsSelected}"
              >
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Select">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Remove" Command="{Binding RemoveFrom}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Fac ID #" Binding="{Binding FacilityIDNum}"/>
                <DataGridTextColumn Header="OP Case #" Binding="{Binding CaseBookingNum}"/>
                <DataGridTextColumn Header="Booking Type #" Binding="{Binding BookingTypeNum}"/>
                <DataGridTextColumn Header="Booking Type" Binding="{Binding BookingType}"/>
            </DataGrid.Columns>
        </DataGrid>

VIEWMODEL

    private ObservableCollection<DGCaseBookings> _dgCaseBookingsList;
    private ObservableCollection<DGCaseBookings> _dgSelectedCaseBookings;
    private ObservableCollection<DGCaseBookings> _dgCaseBookingsSelected;

    public ObservableCollection<DGCaseBookings> DGCaseBookingsList
    {
        get { return _dgCaseBookingsList; }
        set
        {
            SetProperty(ref _dgCaseBookingsList, value, () => DGCaseBookingsList);
        }
    }

    public ObservableCollection<DGCaseBookings> DGSelectedCaseBookings
    {
        get { return _dgSelectedCaseBookings; }
        set
        {
            SetProperty(ref _dgSelectedCaseBookings, value, () => DGSelectedCaseBookings);
        }
    }

    public ObservableCollection<DGCaseBookings> DGCaseBookingsSelected
    {
        get { return _dgCaseBookingsSelected; }
        set
        {
            SetProperty(ref _dgCaseBookingsSelected, value, () => DGCaseBookingsSelected);
        }
    }

    public CMBookingSelectVM() : base()
    {
        DGCaseBookingsList = new ObservableCollection<DGCaseBookings>();
        DGCaseBookingsSelected = new ObservableCollection<DGCaseBookings>();
    }

    private void fillDGCaseBookingswithFacility()
    {
        using (MySqlConnection con = new MySqlConnection(dbConnectionString))
        {
            DGCaseBookingsList = new ObservableCollection<DGCaseBookings>();
            con.Open();
            string Query = ///SELECT STATEMENT WORKS FINE///
            MySqlCommand createCommand = new MySqlCommand(Query, con);
            MySqlDataReader dr = createCommand.ExecuteReader();
            int count = 1;
            while (dr.Read())
            {
                int FacilityIDNum = dr.GetInt32(0);
                int CaseBookingNum = dr.GetInt32(1);
                int BookingTypeNum = dr.GetInt32(2);
                string BookingType = dr.GetString(3);
                DGCaseBookings dgcb = new DGCaseBookings(count, FacilityIDNum, CaseBookingNum, BookingTypeNum, BookingType);
                DGCaseBookingsList.Add(dgcb);
                count++;
            }
            con.Close();
        }
    }

    public void AddTo(DGCaseBookings dgcb)
    {
        if (dgcb != null)
        {
            DGCaseBookingsSelected.Add(dgcb);
            DGCaseBookingsList.Remove(dgcb);
        }
    }

    public void RemoveFrom(DGCaseBookings dgcb)
    {
        if (dgcb != null)
        {
            DGCaseBookingsList.Add(dgcb);
            DGCaseBookingsSelected.Remove(dgcb);
        }
    }

Body:
First of all, you didn't mentioned in your code how you are trying to bind the selected items property of the datagrid to your collection (as a matter of facts you are actually didn't even set the itemsource for the first datagrid), and i think you didn't do that since you actually can't bind the SelectedItems property of the datagrid since it's a readonly property. From now on you have only 2 choice. Find a workaround to send the selected items to your viewmodel, or work on a single row. As for the second approach you can simply do this:

    <DataGrid ItemsSource="{Binding DGCaseBookingsList}" SelectedItem="{Binding MyItem}" SelectionMode = "Single" SelectionUnit="FullRow">
        <DataGrid.Columns>
        <DataGridTemplateColumn Header="Select">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Content="Add" Command="{Binding AddTo}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Fac ID #" Binding="{Binding FacilityIDNum}"/>
        <DataGridTextColumn Header="OP Case #" Binding="{Binding CaseBookingNum}"/>
        <DataGridTextColumn Header="Booking Type #" Binding="{Binding BookingTypeNum}"/>
        <DataGridTextColumn Header="Booking Type" Binding="{Binding BookingType}"/>
        </DataGrid.Columns>
    </DataGrid>

in your VM delete DGSelectedCaseBookings and add the following:

private DGCaseBookings myItem = new DGCaseBookings();
public DGCaseBookings MyItem
{
    get { return myItem; }
    set
    {
        SetProperty(ref myItem, value, () => MyItem);
    }
}

From there you will handle this object using the command of your buttons. Just be sure to implement INotifyPropertyChanged or you won't see any change in your UI.

If you aim to a multiple selection, then the easiest way is to work on the selection changed event of your datagrids. From there you can do something like this.

private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
     MyVM vm = this.DataContext as MyVM;
     DataGrid s = sender as DataGrid;
     vm.DGSelectedCaseBookings = s.SelectedItems;
}


问:
Accessing localhost (xampp) from another computer over LAN network - how to?
I have just set up a wi-fi network at home. I have all my files on my desktop computer (192.168.1.56) and want to access localhost over there from another computer (192.168.1.2).

On my desktop I can access localhost through the normal http://localhost. Apache is running on port 80 as usual.

What do I have to do to achieve this? There is documentation on the net but they either don't work or are too fragmented and confusing to understand.

I think I have to make changes to my apache's httpd.conf file and the hosts file. Any ideas as to what changes to make?

答:
Replace
Require Local with Require all granted in xampp\apache\conf\extra\httpd-xampp.conf file.

ContentLicense: CC BY-SA 4.0


问:
Can I call VariantChangeType on an input BSTR VARIANT?
I have a COM object written in C++ with a method using the following signature. Assume that the variant contains a BSTR (just VT_BSTR, not VT_BYREF | VT_BSTR).

```<code>HRESULT myfunc(/*[in]*/ VARIANT param)
</code>```

I want to change the type to something else. If the first parameter of VariantChangeType is the same as the second, the "variant will be converted in place."

So, can I convert in place?

```<code>HRESULT myfunc(/*[in]*/ VARIANT param)
{
    VariantChangeType(&param, param, 0, VT_I4);
}
</code>```

Or should I copy to a second variant?

```<code>HRESULT myfunc(/*[in]*/ VARIANT param)
{
    VARIANT temp;
    VariantInit(&temp);
    VariantChangeType(&temp, param, 0, VT_I4);
}
</code>```

My understanding is that the latter is required, since the former would free the BSTR, which is owned by the client and should be freed by the client.

答:
The inplace conversion is save. You don't need a temporal variant.

I use it in all of my ATL COM code with something like this:

```<code>CComVariant v;
GetSomeData(v);  // Assume v returns a VT_BSTR variant.
HRESULT hr = v.ChangeType(VT_I4);
if (FAILED(hr))
    ...
</code>```

This code translates into an inplace conversion in the discussed way.
Internally the result is calculated with VarI4FromBSTR before the old VARIANT BSTR usage count value is decremented.

I validated this in some debug sessions because I wasn't sure about this too.

EDIT And finally I found the statement in the MSDN that confirms this.

For VT_BSTR, there is only one owner for the string. All strings in
  variants must be allocated with the SysAllocString function. When
  releasing or changing the type of a variant with the VT_BSTR type,
  SysFreeString is called on the contained string.

That the code works in the answer of @jveazey It has nothing to do with BSTR caching. There is a real inplace conversion!

Body:
I have a COM object written in C++ with a method using the following signature. Assume that the variant contains a BSTR (just VT_BSTR, not VT_BYREF | VT_BSTR).

HRESULT myfunc(/*[in]*/ VARIANT param)

I want to change the type to something else. If the first parameter of VariantChangeType is the same as the second, the "variant will be converted in place."

So, can I convert in place?

HRESULT myfunc(/*[in]*/ VARIANT param)
{
    VariantChangeType(&param, param, 0, VT_I4);
}

Or should I copy to a second variant?

HRESULT myfunc(/*[in]*/ VARIANT param)
{
    VARIANT temp;
    VariantInit(&temp);
    VariantChangeType(&temp, param, 0, VT_I4);
}

My understanding is that the latter is required, since the former would free the BSTR, which is owned by the client and should be freed by the client.

Body:
The inplace conversion is save. You don't need a temporal variant.

I use it in all of my ATL COM code with something like this:

CComVariant v;
GetSomeData(v);  // Assume v returns a VT_BSTR variant.
HRESULT hr = v.ChangeType(VT_I4);
if (FAILED(hr))
    ...

This code translates into an inplace conversion in the discussed way.
Internally the result is calculated with VarI4FromBSTR before the old VARIANT BSTR usage count value is decremented.

I validated this in some debug sessions because I wasn't sure about this too.

EDIT And finally I found the statement in the MSDN that confirms this.

For VT_BSTR, there is only one owner for the string. All strings in
  variants must be allocated with the SysAllocString function. When
  releasing or changing the type of a variant with the VT_BSTR type,
  SysFreeString is called on the contained string.

That the code works in the answer of @jveazey It has nothing to do with BSTR caching. There is a real inplace conversion!


问:
Inheriting a T4 template from a custom base class, providing Visual Studio 2010 SDK is not installed
I have a system of T4 templates — executed at run-time, not at compile-time — which generate the skeletons of many classes in my app. All these templates reside in a generator tool which is used from time to time to pre-generate new classes into the destination app. The tool contains a configuration class whose properties parameterize the output of all T4 templates.

Originally the configuration class was a static class. However, as the class generator tool grows, it's better to make it non-static and rather make a new instance for each use. The problem is how to pass this instance to the instances of T4 templates. The natural way seems to be inheriting them from a common base which would be provisioned with the configuration class instance.

The problem is that the TextTransformation class, which would have been inherited by my custom T4 base class, is located in an assembly which (according to sources like this SO question) doesn't ship with Visual Studio 2010. Instead it's provided within the Visual Studio 2010 SDK.

The base class generated by VS2010, although itself having no ancestor, isn't partial so there's no way to 'inject' the custom ancestor via another partial declaration.

Thus the question is: Is there a way to inherit a run-time-executed T4 template from a custom base class without the need to install Visual Studio 2010 SDK?

Disclaimer: I'm not very familiar with T4, so I might be completely wrong about how to approach the problem. Hence any other architectural advice is welcome, although my aim isn't to create a super-architected generator — it's just a helper tool, which shall be simple and understandable to the occasional reader.

答:
The solution is actually very simple — the base class can be implemented as a T4 template itself and inherited. Like this:

Base template:

```<code><#@ template language="C#" #>
<#+

    public Config Config { get; set; }

#>
</code>```

Inherited template:

```<code><#@ template language="C#" inherits="BaseTemplate" #>
...
<#= Config.SomeProperty #>
...
</code>```

Once the template is instantiated the properties declared in the base template are provisioned to the actual configuration.

Body:
The solution is actually very simple — the base class can be implemented as a T4 template itself and inherited. Like this:

Base template:

<#@ template language="C#" #>
<#+

    public Config Config { get; set; }

#>

Inherited template:

<#@ template language="C#" inherits="BaseTemplate" #>
...
<#= Config.SomeProperty #>
...

Once the template is instantiated the properties declared in the base template are provisioned to the actual configuration.


问:
instanceof function parameter returns false in Typescript/Angular
I'm trying to find out how to get the type of an Object if it was passed as a parameter in my function.

For example you have following code

```<code>getTypeOfAnimal(animal){
   console.log(animal instanceof Cat)
   console.log(animal instanceof Bear)
}
</code>```

animal could be either an instanceof a Cat or a Bear. The animal passed in from my form always returns false (also if the Object's structure seems to match one of a Cat or a Bear).

Is there a way to get the type properly?

答:
The root of the problem is this line

also if the Object's structure seems to match one of a Cat or a Bear

The object structure won't matter here. The instanceof checks whether the object was created using a constructor of Cat or Bear, e.g. new Cat() (and actually if both extend Animal then the instanceof Animal would be true for both).

Normally TypeScript uses duck typing to resolve whether the interface is matching the object structure and this is where the similar object structure could work. However instanceof is JavaScript (because is executed in the runtime), so there is no much more TypeScript can do there. That is why it does not work as you might have expected.

Body:
I'm trying to find out how to get the type of an Object if it was passed as a parameter in my function.

For example you have following code

getTypeOfAnimal(animal){
   console.log(animal instanceof Cat)
   console.log(animal instanceof Bear)
}

animal could be either an instanceof a Cat or a Bear. The animal passed in from my form always returns false (also if the Object's structure seems to match one of a Cat or a Bear).

Is there a way to get the type properly?


问:
prerender.io headless chrome won't start
I'm trying to start prerender with headless chrome(v62) on my Centos7 sistem but it won't start.
When running "node server.js" I get:

2017-11-23T08:50:08.329Z Starting Prerender

2017-11-23T08:50:08.331Z Starting Chrome

2017-11-23T08:50:08.343Z Prerender server accepting requests on port 3000

2017-11-23T08:50:08.392Z Chrome connection closed... restarting Chrome

2017-11-23T08:50:08.392Z Chrome died immediately after restart... stopping Prerender

Does anyone know what could be the cause?
Thank you very much

答:
you can also add --no-sandbox to run Chrome as root.

vim $(which google-chrome)

then add --no-sandbox to the last line, make it like

exec -a "$0" "$HERE/chrome" "$@" --no-sandbox


问:
Quickfix/C++ - Ordering fields
I'm currently trying to speak in FIX using Quickfix/C++ to a Financial Market.
This market rejects my message (a RegistrationInstruction, msgtype=o), telling me that a field is not in the correct place.

The problem is that the specified tag (#29 LastCapacity) is sent by quickfix between field SecurityIDSource #22 and SecurityID #48 and the market tell me that the Instrument "component" should be sent as defined by the specifications which is:

```<code>Start <instrument>
55 Symbol
48 SecurityID
22 SecurityIDSource
167SecurityType
end <Instrument>
</code>```

Then Tag #29 Should not appear inside this component.

Do you have any idea how may I tell quickfix to not send #29 between #22 and #48 ?

Thank you very much

答: To resolve the problem, I used an existing repeating group inside the message and add the Tag #29 inside it, and initialize it only on the last element of the inserted group elements (I could not copy-paste nor send code outside, sorry).</p>

Title: Quickfix/C++ - Ordering fields

Body:
I'm currently trying to speak in FIX using Quickfix/C++ to a Financial Market.
This market rejects my message (a RegistrationInstruction, msgtype=o), telling me that a field is not in the correct place.

The problem is that the specified tag (#29 LastCapacity) is sent by quickfix between field SecurityIDSource #22 and SecurityID #48 and the market tell me that the Instrument "component" should be sent as defined by the specifications which is:

Start <instrument>
55 Symbol
48 SecurityID
22 SecurityIDSource
167SecurityType
end <Instrument>

Then Tag #29 Should not appear inside this component.

Do you have any idea how may I tell quickfix to not send #29 between #22 and #48 ?

Thank you very much


问:
How to get process id in the method called by activiti:expression
We are using Activiti to build our Workflow and all of its tasks is defined as ServiceTask. Currently, all of the tasks uses activiti:expression shown as below:

```<code>activiti:expression="${etcx.runThis('first variable','second variable')}"
</code>```

Now, what we want to achieve is to obtain the process id of which this caller ServiceTask belongs to. To be more precise, it would be like calling the etcx.runThis('first variable','second variable','processid') in all ServiceTask. But, we think this would be a bit clumsy process because the users of our workflow have to add processid manually. How can we get currently running processid?

答:
I managed to solve my problem and successfully obtained the workflow ID with the following:</p>

```<code>String workflowID = Context.getExecutionContext().getProcessDefinition().getId();
</code>```

Body:
We are using Activiti to build our Workflow and all of its tasks is defined as ServiceTask. Currently, all of the tasks uses activiti:expression shown as below:

activiti:expression="${etcx.runThis('first variable','second variable')}"

Now, what we want to achieve is to obtain the process id of which this caller ServiceTask belongs to. To be more precise, it would be like calling the etcx.runThis('first variable','second variable','processid') in all ServiceTask. But, we think this would be a bit clumsy process because the users of our workflow have to add processid manually. How can we get currently running processid?

Body:
I managed to solve my problem and successfully obtained the workflow ID with the following:

String workflowID = Context.getExecutionContext().getProcessDefinition().getId();


问:
VC Dimension with rectangles with horizontal and vertical edges
I am learning theory of machine learning and have some confusion about VC dimensions. According to the text book, the VC dimension of 2D axis-aligned rectangles is 4 which means it cannot shatter 5 points.

I found an example here: Cornell

However I still cannot understand this example. What if we use a rectangle like this (the red one)

Then we can classify this point out of them. Why is this incorrect?

答: We are supposed to draw the rectangle containing +ve examples only for any combination of the given 5 points. Here you see that, for any combination of the given points, a rectangle that corresponds to the points with maximum x-coordinate, minimum x-coordinate, maximum y-coordinate, and minimum y-coordinate will always contain the fifth point also. Hence, the set of 5 points cannot be shattered.</p>


问:
Typescript decorators with inheritance
I am playing around with Typescript decorators and they seem to behave quite differently than what I'd expect when used alongside with class inheritance.

Suppose I have the following code:

```<code>class A {
    @f()
    propA;
}

class B extends A {
    @f()
    propB;
}

class C extends A {
    @f()
    propC;
}

function f() {
    return (target, key) => {
        if (!target.test) target.test = [];
        target.test.push(key);
    };
}

let b = new B();
let c = new C();

console.log(b['test'], c['test']);
</code>```

Which outputs:

```<code>[ 'propA', 'propB', 'propC' ] [ 'propA', 'propB', 'propC' ]
</code>```

Though I'd expect this:

```<code>[ 'propA', 'propB' ] [ 'propA', 'propC' ]
</code>```

So, it seems that target.test is shared between A, B and C. And my understanding of what is going on here is as follow:

Since B extends A, new B() triggers the instantiation of A first, which triggers the evaluation of f for A. Since target.test is undefined, it is initialized.

f is then evaluated for B, and since it extends A, A is instantiated first. So, at that time, target.test (target being B) references test defined for A. So, we push propB in it. At this point, things go as expected.

Same as step 2, but for C. This time, when C evaluates the decorator, I would expect it to have a new object for test, different than that defined for B. But the log proves me wrong.

Can anyone explain to me why this is happening (1) and how would I implement f such that A and B have separate test properties ?

I guess you'd call that an "instance specific" decorator ?

答:
@user5365075 I ran into the exact same issue when working with method decorators, and your fix worked.

Here is a decorator I am using in one of my packages (with an object instead of an array):

```<code>export function property(options) {
    return (target, name) => {
        // Note: This is a workaround due to a similar bug described here:
        // https://stackoverflow.com/questions/43912168/typescript-decorators-with-inheritance

        if (!Object.getOwnPropertyDescriptor(target, '_sqtMetadata')) {
            target._sqtMetadata = {}
        }

        if (target._sqtMetadata.properties) {
            target._sqtMetadata.properties[name] = options.type
        } else {
            target._sqtMetadata.properties = { [name]: options.type }
        }

        const parentTarget = Object.getPrototypeOf(target)
        const parentData = parentTarget._sqtMetadata

        if (parentData) {
            if (parentData.properties) {
                Object.keys(parentData.properties).forEach((key) => {
                    if (!target._sqtMetadata.properties[key]) {
                        target._sqtMetadata.properties[key] = parentData.properties[key]
                    }
                })
            }
        }
    }
}
</code>```

I can confirm the same behavior exists for class decorators as well.

Title: Typescript decorators with inheritance

Body:
I am playing around with Typescript decorators and they seem to behave quite differently than what I'd expect when used alongside with class inheritance.

Suppose I have the following code:

class A {
    @f()
    propA;
}

class B extends A {
    @f()
    propB;
}

class C extends A {
    @f()
    propC;
}

function f() {
    return (target, key) => {
        if (!target.test) target.test = [];
        target.test.push(key);
    };
}

let b = new B();
let c = new C();

console.log(b['test'], c['test']);

Which outputs:

[ 'propA', 'propB', 'propC' ] [ 'propA', 'propB', 'propC' ]

Though I'd expect this:

[ 'propA', 'propB' ] [ 'propA', 'propC' ]

So, it seems that target.test is shared between A, B and C. And my understanding of what is going on here is as follow:

Since B extends A, new B() triggers the instantiation of A first, which triggers the evaluation of f for A. Since target.test is undefined, it is initialized.

f is then evaluated for B, and since it extends A, A is instantiated first. So, at that time, target.test (target being B) references test defined for A. So, we push propB in it. At this point, things go as expected.

Same as step 2, but for C. This time, when C evaluates the decorator, I would expect it to have a new object for test, different than that defined for B. But the log proves me wrong.

Can anyone explain to me why this is happening (1) and how would I implement f such that A and B have separate test properties ?

I guess you'd call that an "instance specific" decorator ?

Body:
@user5365075 I ran into the exact same issue when working with method decorators, and your fix worked.

Here is a decorator I am using in one of my packages (with an object instead of an array):

export function property(options) {
    return (target, name) => {
        // Note: This is a workaround due to a similar bug described here:
        // https://stackoverflow.com/questions/43912168/typescript-decorators-with-inheritance

        if (!Object.getOwnPropertyDescriptor(target, '_sqtMetadata')) {
            target._sqtMetadata = {}
        }

        if (target._sqtMetadata.properties) {
            target._sqtMetadata.properties[name] = options.type
        } else {
            target._sqtMetadata.properties = { [name]: options.type }
        }

        const parentTarget = Object.getPrototypeOf(target)
        const parentData = parentTarget._sqtMetadata

        if (parentData) {
            if (parentData.properties) {
                Object.keys(parentData.properties).forEach((key) => {
                    if (!target._sqtMetadata.properties[key]) {
                        target._sqtMetadata.properties[key] = parentData.properties[key]
                    }
                })
            }
        }
    }
}

I can confirm the same behavior exists for class decorators as well.


问:
Hosting Sharepoint and SQL Server off same server
Is it possible to host Sharepoint and SQL Server off the same server for small time testing. Environment would be set up for purely education purposes. Non-production. Thanks.</p>

答: Yes. We do this also. Works like a charm.</p>


问:
No Basic authentication possible for Jira Rest API with R
I am currently despairing of the basic authentication of the Jira Rest API. Here is my example code:

```<code>  #username = jiraname and not the mailadd
  credentials <- "username:password"
  credentials <- base64_enc(credentials)
  header_auth <- paste0("Basic ",credentials)

  url <- "https://host/jira/rest/api/2/issue/ABC-123"

  res <- GET(url, add_headers(Authorization = header_auth), accept_json())

  parsed_json <- content(res, "parsed")
  parsed_json <- enframe(unlist(parsed_json, recursive = TRUE, use.names = TRUE))
</code>```

That is just one example of what I tried...
The answer is always:

```<code>1 errorMessages1 Sie haben nicht die Berechtigung, den den Vorgang zu sehen. (You don't have the permission to see this issue)
2 errorMessages2                                      Anmeldung erforderlich (Login required)
</code>```

I tried the same URL in my browser (where I am logged in obviously) and I get the expected result.

What am I doing wrong?

Greetings

EDIT:
Jira is running on an Apache Server. Is there anything to consider?

答:
To what I understand, you are using the wrong API to BASE64 encode the username:password string replaced with the actual credentials. As per the documentation, this is the correct API to use for R.

Documentation link and here

Using base64enc instead of base64_enc should solve your problem.

Hope this helps!

Body:
I am currently despairing of the basic authentication of the Jira Rest API. Here is my example code:

  #username = jiraname and not the mailadd
  credentials <- "username:password"
  credentials <- base64_enc(credentials)
  header_auth <- paste0("Basic ",credentials)

  url <- "https://host/jira/rest/api/2/issue/ABC-123"

  res <- GET(url, add_headers(Authorization = header_auth), accept_json())

  parsed_json <- content(res, "parsed")
  parsed_json <- enframe(unlist(parsed_json, recursive = TRUE, use.names = TRUE))

That is just one example of what I tried...
The answer is always:

1 errorMessages1 Sie haben nicht die Berechtigung, den den Vorgang zu sehen. (You don't have the permission to see this issue)
2 errorMessages2                                      Anmeldung erforderlich (Login required)

I tried the same URL in my browser (where I am logged in obviously) and I get the expected result.

What am I doing wrong?

Greetings

EDIT:
Jira is running on an Apache Server. Is there anything to consider?