问:
after join the two tables I want to pivot the the table to get the result as per the img attached. but I'm getting an error
enter image description here

```<code>select  t1.action, t1.AttributeName,t1.AttributeValue,t2.istotal_indicator
from tbl_ss_orderitems_IC t1

   join
 Tbl_ECC_breakdowns t2

 on t1.[Action]= t2.ECC_Charge_Actiontype

   PIVOT(MAX(t1.AttributeValue) FOR t1.AttributeName
   IN (
   ChargeAmount
   ,Currency
   ,Quantity
   ,UnitOfMeasure
   ,UnitRate

   )) AS PIVOT_1
</code>```

error//Msg 8156, Level 16, State 1, Line 219 The column 'Id' was
  specified multiple times for 'PIVOT_1'. Msg 4104, Level 16, State 1,
  Line 206 The multi-part identifier "t1.action" could not be bound. Msg
  4104, Level 16, State 1, Line 206 The multi-part identifier
  "t1.AttributeName" could not be bound. Msg 4104, Level 16, State 1,
  Line 206 The multi-part identifier "t1.AttributeValue" could not be
  bound. Msg 4104, Level 16, State 1, Line 206 The multi-part identifier
  "t2.istotal_indicator" could not be bound.

答:
Try to use subquery before PIVOT

```<code>SELECT *
FROM
  (
    select  t1.action, t1.AttributeName,t1.AttributeValue,t2.istotal_indicator
    from tbl_ss_orderitems_IC t1
    join Tbl_ECC_breakdowns t2 on t1.[Action]= t2.ECC_Charge_Actiontype
  ) q
PIVOT(MAX(AttributeValue) FOR AttributeName IN (ChargeAmount,Currency,Quantity,UnitOfMeasure,UnitRate)) p
</code>```

Body:
enter image description here

select  t1.action, t1.AttributeName,t1.AttributeValue,t2.istotal_indicator
from tbl_ss_orderitems_IC t1

   join
 Tbl_ECC_breakdowns t2

 on t1.[Action]= t2.ECC_Charge_Actiontype

   PIVOT(MAX(t1.AttributeValue) FOR t1.AttributeName
   IN (
   ChargeAmount
   ,Currency
   ,Quantity
   ,UnitOfMeasure
   ,UnitRate

   )) AS PIVOT_1

error//Msg 8156, Level 16, State 1, Line 219 The column 'Id' was
  specified multiple times for 'PIVOT_1'. Msg 4104, Level 16, State 1,
  Line 206 The multi-part identifier "t1.action" could not be bound. Msg
  4104, Level 16, State 1, Line 206 The multi-part identifier
  "t1.AttributeName" could not be bound. Msg 4104, Level 16, State 1,
  Line 206 The multi-part identifier "t1.AttributeValue" could not be
  bound. Msg 4104, Level 16, State 1, Line 206 The multi-part identifier
  "t2.istotal_indicator" could not be bound.

Body:
Try to use subquery before PIVOT

SELECT *
FROM
  (
    select  t1.action, t1.AttributeName,t1.AttributeValue,t2.istotal_indicator
    from tbl_ss_orderitems_IC t1
    join Tbl_ECC_breakdowns t2 on t1.[Action]= t2.ECC_Charge_Actiontype
  ) q
PIVOT(MAX(AttributeValue) FOR AttributeName IN (ChargeAmount,Currency,Quantity,UnitOfMeasure,UnitRate)) p


来源: stackexchange

问:
Error while using PhantomJS in Selenium: NoSuchMethodError org/openqa/selenium/browserlaunchers/Proxies
I am trying to run very simple Java automation test case using PhantomJS. I am using following version:

selenium-server-standalone3.8.1.jar

PhantomJS 2.1.1 version for Windows

PhantomJSdriver.jar 1.1. version

My code desired capabilities and driver launch is as follow:

```<code>        DesiredCapabilities caps = new DesiredCapabilities();
        ((DesiredCapabilities) caps).setJavascriptEnabled(true);
        ((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
        ((DesiredCapabilities) caps).setCapability(
                PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
                "C:/Program Files/phantomjs-2.1.1-windows/bin/phantomjs.exe"   //java web start / jnpl file...
                // "/Controller/phantomjs.exe"
        );

        //SET enabled javascript for php script on WEB page to transform it to picture:
        caps.setJavascriptEnabled(true);
        String [] phantomJsArgs = {"--web-security=no", "--ignore-ssl-errors=yes"};
        caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, phantomJsArgs);

        //CREATING WEB driver
        WebDriver driver = new PhantomJSDriver(caps);
</code>```

However, I get this error:

Exception in thread "main" java.lang.NoClassDefFoundError:
  org/openqa/selenium/browserlaunchers/Proxies  at
  org.openqa.selenium.phantomjs.PhantomJSDriverService.createDefaultService(PhantomJSDriverService.java:178)
    at
  org.openqa.selenium.phantomjs.PhantomJSDriver.(PhantomJSDriver.java:99)
    at HD_PhantomJSTest1.main(HD_PhantomJSTest1.java:33) Caused by:
  java.lang.ClassNotFoundException:
  org.openqa.selenium.browserlaunchers.Proxies  at
  java.net.URLClassLoader$1.run(URLClassLoader.java:372)    at
  java.net.URLClassLoader$1.run(URLClassLoader.java:361)    at
  java.security.AccessController.doPrivileged(Native Method)    at
  java.net.URLClassLoader.findClass(URLClassLoader.java:360)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 3 more

答:
java.lang.NoClassDefFoundError

java.lang.NoClassDefFoundError is observed when Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.

As an example, if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw java.lang.NoClassDefFoundError.

From your Test Bed information, I am not sure about the inclusion of PhantomJSdriver.jar 1.1. version. Current implementation of PhantomJS doesn't need any additional jar as such. Relevant Selenium JARs resolves the required dependencies. So you can remove the PhantomJSdriver.jar 1.1. version.

Other than that, I don't see any such error in your code. However after a bit of code formatting I executed your code with my configuration and was SUCCESS as follows:

```<code>@Test
public void verifyFacebookTitle()
{
    DesiredCapabilities caps = new DesiredCapabilities();
    ((DesiredCapabilities) caps).setJavascriptEnabled(true);
    ((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
    ((DesiredCapabilities) caps).setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
    caps.setJavascriptEnabled(true);
    String [] phantomJsArgs = {"--web-security=no", "--ignore-ssl-errors=yes"};
    caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, phantomJsArgs);
    WebDriver driver = new PhantomJSDriver(caps);
    driver.get("https://www.facebook.com/");
    System.out.println(driver.getTitle());
    driver.quit();
}
</code>```

Output on my console :

```<code>INFO: Detected dialect: OSS
Facebook – log in or sign up
[INFO  - 2017-12-06T08:24:22.972Z] ShutdownReqHand - _handle - About to shutdown
PASSED: verifyFacebookTitle

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run very simple Java automation test case using PhantomJS. I am using following version:

selenium-server-standalone3.8.1.jar

PhantomJS 2.1.1 version for Windows

PhantomJSdriver.jar 1.1. version

My code desired capabilities and driver launch is as follow:

        DesiredCapabilities caps = new DesiredCapabilities();
        ((DesiredCapabilities) caps).setJavascriptEnabled(true);
        ((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
        ((DesiredCapabilities) caps).setCapability(
                PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
                "C:/Program Files/phantomjs-2.1.1-windows/bin/phantomjs.exe"   //java web start / jnpl file...
                // "/Controller/phantomjs.exe"
        );

        //SET enabled javascript for php script on WEB page to transform it to picture:
        caps.setJavascriptEnabled(true);
        String [] phantomJsArgs = {"--web-security=no", "--ignore-ssl-errors=yes"};
        caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, phantomJsArgs);

        //CREATING WEB driver
        WebDriver driver = new PhantomJSDriver(caps);

However, I get this error:

Exception in thread "main" java.lang.NoClassDefFoundError:
  org/openqa/selenium/browserlaunchers/Proxies  at
  org.openqa.selenium.phantomjs.PhantomJSDriverService.createDefaultService(PhantomJSDriverService.java:178)
    at
  org.openqa.selenium.phantomjs.PhantomJSDriver.(PhantomJSDriver.java:99)
    at HD_PhantomJSTest1.main(HD_PhantomJSTest1.java:33) Caused by:
  java.lang.ClassNotFoundException:
  org.openqa.selenium.browserlaunchers.Proxies  at
  java.net.URLClassLoader$1.run(URLClassLoader.java:372)    at
  java.net.URLClassLoader$1.run(URLClassLoader.java:361)    at
  java.security.AccessController.doPrivileged(Native Method)    at
  java.net.URLClassLoader.findClass(URLClassLoader.java:360)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 3 more

Body:
java.lang.NoClassDefFoundError

java.lang.NoClassDefFoundError is observed when Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.

As an example, if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw java.lang.NoClassDefFoundError.

From your Test Bed information, I am not sure about the inclusion of PhantomJSdriver.jar 1.1. version. Current implementation of PhantomJS doesn't need any additional jar as such. Relevant Selenium JARs resolves the required dependencies. So you can remove the PhantomJSdriver.jar 1.1. version.

Other than that, I don't see any such error in your code. However after a bit of code formatting I executed your code with my configuration and was SUCCESS as follows:

@Test
public void verifyFacebookTitle()
{
    DesiredCapabilities caps = new DesiredCapabilities();
    ((DesiredCapabilities) caps).setJavascriptEnabled(true);
    ((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
    ((DesiredCapabilities) caps).setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
    caps.setJavascriptEnabled(true);
    String [] phantomJsArgs = {"--web-security=no", "--ignore-ssl-errors=yes"};
    caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, phantomJsArgs);
    WebDriver driver = new PhantomJSDriver(caps);
    driver.get("https://www.facebook.com/");
    System.out.println(driver.getTitle());
    driver.quit();
}

Output on my console :

INFO: Detected dialect: OSS
Facebook – log in or sign up
[INFO  - 2017-12-06T08:24:22.972Z] ShutdownReqHand - _handle - About to shutdown
PASSED: verifyFacebookTitle

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================


问:
Tune Spark, set executors and memory driver for reading large csv file
I am wondering how to choose the best settings to run tune me Spark Job.
Basically I am just reading a big csv file into a DataFrame and count some string occurrences.

The input file is over 500 GB. The spark job seems too slow..

terminal Progress Bar:

```<code>[Stage1:=======>                      (4174 + 50) / 18500]
</code>```

NumberCompletedTasks: (4174) takes around one hour.

NumberActiveTasks: (50), I believe I can control with setting.
--conf spark.dynamicAllocation.maxExecutors=50  (tried with different values).

TotalNumberOfTasks: (18500), why is this fixed? what does it mean, is it only related to file size?
Since I am reading a csv just with little logic, how can I optimize the Spark Job?

I also tried changing :

```<code> --executor-memory 10g
 --driver-memory 12g
</code>```

答:
Number of partitions = Number of tasks.
If you have 18500 partitions, then spark will run 18500 tasks to process those.

Are you just reading the file and doing a filter out of it? Do you perform any Wide transformations? If you perform wide transformation, then the number of partition in the resulting RDD is controlled by the property "spark.sql.shuffle.partitions". If this is set to 18500, then your resultant RDD will have 18500 partitions and as a result 18500 tasks.

Secondly, spark.dynamicAllocation.maxExecutors represents the Upper bound for the number of executors if dynamic allocation is enabled. From what I can see, you have 5 nodes, 10 executors per node [Total 50 executors] and 1 core per executor [If you are running in YARN, then 1 core per executor is default].

To run your job faster: If possible reduce the number of shuffle partition via property spark.sql.shuffle.partitions and increase the number of core per executor [5 core per executor is the recommended one].

Body:
I am wondering how to choose the best settings to run tune me Spark Job.
Basically I am just reading a big csv file into a DataFrame and count some string occurrences.

The input file is over 500 GB. The spark job seems too slow..

terminal Progress Bar:

[Stage1:=======>                      (4174 + 50) / 18500]

NumberCompletedTasks: (4174) takes around one hour.

NumberActiveTasks: (50), I believe I can control with setting.
--conf spark.dynamicAllocation.maxExecutors=50  (tried with different values).

TotalNumberOfTasks: (18500), why is this fixed? what does it mean, is it only related to file size?
Since I am reading a csv just with little logic, how can I optimize the Spark Job?

I also tried changing :

 --executor-memory 10g
 --driver-memory 12g


问:
react-select handle onChange with props
I am using react-select in a child component but wanting to store the Select value in a state in the parent.

I appreciate that I have to store onChange in state and then pass this to the Select value, but I would like to keep this temporary onChange state in the child component not the parent.

So the question is how do I set the parent state (coming in on a prop) from the onChange state in the child.

Parent Component

```<code>campaignName (campaign){
  //will setState here
   console.log(campaign)
  }
...
<FormGroup>
  <Campaign
    campaignName={this.campaignName.bind(this)}
    campaignOptions={code in here that sets option}
   />
</FormGroup>
</code>```

Child Component

```<code>updateValue (newValue) {
    this.setState({
        selectValue: newValue,
  // how do I set the parent state from this
    });

<Select
   onChange={this.updateValue}
   value={this.props.campaignName}
   options={this.props.campaignOptions}
/>
</code>```

答:
Pass the function directly from parent to child that will handle the onChange:

Parent Component

```<code>handleSelect(e) {
   this.setState({
       selectValue: e.target.value,
   });
}

render() {
    <ChildComponent selectOnChange={this.handleSelect} />
}
</code>```

Child Component

```<code><Select
   onChange={this.props.selectOnChange}
   value={this.props.campaignName}
/>
</code>```

OR (if you want the method to stay on the child)

```<code>updateValue(e) {
   this.props.selectOnChange(e); //call the passed props here
}

<Select
   onChange={this.updateValue}
   value={this.props.campaignName}
/>
</code>```

Title: react-select handle onChange with props

Body:
I am using react-select in a child component but wanting to store the Select value in a state in the parent.

I appreciate that I have to store onChange in state and then pass this to the Select value, but I would like to keep this temporary onChange state in the child component not the parent.

So the question is how do I set the parent state (coming in on a prop) from the onChange state in the child.

Parent Component

campaignName (campaign){
  //will setState here
   console.log(campaign)
  }
...
<FormGroup>
  <Campaign
    campaignName={this.campaignName.bind(this)}
    campaignOptions={code in here that sets option}
   />
</FormGroup>

Child Component

updateValue (newValue) {
    this.setState({
        selectValue: newValue,
  // how do I set the parent state from this
    });

<Select
   onChange={this.updateValue}
   value={this.props.campaignName}
   options={this.props.campaignOptions}
/>

Body:
Pass the function directly from parent to child that will handle the onChange:

Parent Component

handleSelect(e) {
   this.setState({
       selectValue: e.target.value,
   });
}

render() {
    <ChildComponent selectOnChange={this.handleSelect} />
}

Child Component

<Select
   onChange={this.props.selectOnChange}
   value={this.props.campaignName}
/>

OR (if you want the method to stay on the child)

updateValue(e) {
   this.props.selectOnChange(e); //call the passed props here
}

<Select
   onChange={this.updateValue}
   value={this.props.campaignName}
/>


问:
how to add info window to custom overlay in google maps like normal marker
I am new to google maps javascript Api.I have added custom marker using custom overlay in my application.now i want to add infoWindow to custom marker.i am able to add alert using addDomListener method please find my below code

```<code>if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (pos) {
      var myLatLng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
      // var userObj = {}

      function CustomMarker(latlng, map, imageSrc) {
        this.latlng_ = latlng;
        this.imageSrc = imageSrc;

        // Once the LatLng and text are set, add the overlay to the map.  This will
        // trigger a call to panes_changed which should in turn call draw.
        this.setMap(map);
      }

      CustomMarker.prototype = new google.maps.OverlayView();

      CustomMarker.prototype.draw = function () {
        // Check if the div has been created.
        var div = this.div_;
        if (!div) {
            // Create a overlay text DIV
            div = this.div_ = document.createElement('div');
            // Create the DIV representing our CustomMarker
            div.className = "customMarker"

            var img = document.createElement("img");
            img.src = this.imageSrc;
            div.appendChild(img);
            google.maps.event.addDomListener(div, "click", function (event) {
                google.maps.event.trigger(me, "click");
            });

            // Then add the overlay to the DOM
            var panes = this.getPanes();
            panes.overlayImage.appendChild(div);
        }

        // Position the overlay
        var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
        console.log("ss :"+point.x)
        if (point) {
            div.style.left = point.x + 'px';
            div.style.top = point.y + 'px';
        }
      };

      CustomMarker.prototype.remove = function () {
        // Check if the overlay was on the map and needs to be removed.
        if (this.div_) {
            this.div_.parentNode.removeChild(this.div_);
            this.div_ = null;
        }
      };

      CustomMarker.prototype.getPosition = function () {
        return this.latlng_;
      };
      CustomMarker.prototype.setPosition = function (latlng_) {
        this.latlng_=latlng_;
        this.draw();
      };
      var map = new google.maps.Map(document.getElementById("map"), {
        zoom: 15,
        center:myLatLng
      });
      UserService.GetCurrent().then(function (user) {
        $scope.user = user;
        currentUser = user
        user.lat = myLatLng;
        user.mission = room;
        socket.emit('subscribe', user);
       interval= setInterval(getNewCords, 2000);
      //  $interval.cancel(interval);
       console.log("ssa :"+angular.toJson(interval))
      });
      var infowindow = new google.maps.InfoWindow();

      socket.on('userList', function (userList) {
        for (var i = 0; i < markers.length; i++) {
          markers[i].setMap(null);
        }
        console.log(userList[i].icon);
        for (var i = 0; i < userList.length; i++) {
          marker[userList[i].pseudoName]= new CustomMarker(new google.maps.LatLng(userList[i].lat.lat,userList[i].lat.lng), map,  userList[i].icon)
          markers.push(marker[userList[i].pseudoName]);

        }

      });

    })

  } else {
    alert('Geo Location feature is not supported in this browser.');
  }
</code>```

please find my custom marker reference
custom marker

find below js fiddle credits to Alexey Zuev custom overlay example

答:
I added the info window code to your fiddle. Your posted code seems different.
Anyway, I modified your initialize() function into this.

```<code>function initialize() {
    var myLatlng = new google.maps.LatLng(-33.9,151.2),
    mapOptions = {
      zoom: 15,
      center: myLatlng,
      disableDefaultUI: true
    };

    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  var markers = [
    {
      latLan: new google.maps.LatLng(-33.9,151.2),
      icon: 'cutlery',
      color: '#346698',
      fontSize: '35px'
    },
    {
        latLan: new google.maps.LatLng(-33.8939,151.207333),
      icon: 'anchor',
      color: '#B90C13',
      fontSize: '35px'
    },
    {
      latLan: new google.maps.LatLng(-33.895,151.195),
      icon: 'automobile',
      color: '#39A00F',
      fontSize: '35px'
    },
    {
      latLan: new google.maps.LatLng(-33.905,151.195),
      icon: 'headphones',
      color: '#000',
      fontSize: '35px'
    },
     {
        latLan: new google.maps.LatLng(-33.9039,151.207333),
      icon: 'child',
      color: '#26C2C3',
      fontSize: '35px'
    },
  ]

  markers.forEach(function(item) {
    var markerstemp = new FontAwesomeMarker(
      item.latLan,
      map,
      {
        icon: item.icon,
        color: item.color,
        fontSize: item.fontSize
      }
    );

    //info window code starts here
    var infoWindow = new google.maps.InfoWindow();
    (function (markerstemp) {
                google.maps.event.addListener(markerstemp, "click", function (e) {
                    //Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
                    infoWindow.setContent("\<div style = \'width:auto;color:#000;font-size:12px;font-weight:500;padding:5px;\'\>Aww\</div\>");
                    infoWindow.open(map, markerstemp);
                });
            })(markerstemp);
  });
}
</code>```

To test that, copy that code above and replace it to your initialize() function from the fiddle you've posted.

Body:
I am new to google maps javascript Api.I have added custom marker using custom overlay in my application.now i want to add infoWindow to custom marker.i am able to add alert using addDomListener method please find my below code

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (pos) {
      var myLatLng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
      // var userObj = {}

      function CustomMarker(latlng, map, imageSrc) {
        this.latlng_ = latlng;
        this.imageSrc = imageSrc;

        // Once the LatLng and text are set, add the overlay to the map.  This will
        // trigger a call to panes_changed which should in turn call draw.
        this.setMap(map);
      }

      CustomMarker.prototype = new google.maps.OverlayView();

      CustomMarker.prototype.draw = function () {
        // Check if the div has been created.
        var div = this.div_;
        if (!div) {
            // Create a overlay text DIV
            div = this.div_ = document.createElement('div');
            // Create the DIV representing our CustomMarker
            div.className = "customMarker"

            var img = document.createElement("img");
            img.src = this.imageSrc;
            div.appendChild(img);
            google.maps.event.addDomListener(div, "click", function (event) {
                google.maps.event.trigger(me, "click");
            });

            // Then add the overlay to the DOM
            var panes = this.getPanes();
            panes.overlayImage.appendChild(div);
        }

        // Position the overlay
        var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
        console.log("ss :"+point.x)
        if (point) {
            div.style.left = point.x + 'px';
            div.style.top = point.y + 'px';
        }
      };

      CustomMarker.prototype.remove = function () {
        // Check if the overlay was on the map and needs to be removed.
        if (this.div_) {
            this.div_.parentNode.removeChild(this.div_);
            this.div_ = null;
        }
      };

      CustomMarker.prototype.getPosition = function () {
        return this.latlng_;
      };
      CustomMarker.prototype.setPosition = function (latlng_) {
        this.latlng_=latlng_;
        this.draw();
      };
      var map = new google.maps.Map(document.getElementById("map"), {
        zoom: 15,
        center:myLatLng
      });
      UserService.GetCurrent().then(function (user) {
        $scope.user = user;
        currentUser = user
        user.lat = myLatLng;
        user.mission = room;
        socket.emit('subscribe', user);
       interval= setInterval(getNewCords, 2000);
      //  $interval.cancel(interval);
       console.log("ssa :"+angular.toJson(interval))
      });
      var infowindow = new google.maps.InfoWindow();

      socket.on('userList', function (userList) {
        for (var i = 0; i < markers.length; i++) {
          markers[i].setMap(null);
        }
        console.log(userList[i].icon);
        for (var i = 0; i < userList.length; i++) {
          marker[userList[i].pseudoName]= new CustomMarker(new google.maps.LatLng(userList[i].lat.lat,userList[i].lat.lng), map,  userList[i].icon)
          markers.push(marker[userList[i].pseudoName]);

        }

      });

    })

  } else {
    alert('Geo Location feature is not supported in this browser.');
  }

please find my custom marker reference
custom marker

find below js fiddle credits to Alexey Zuev custom overlay example

Body:
I added the info window code to your fiddle. Your posted code seems different.
Anyway, I modified your initialize() function into this.

function initialize() {
    var myLatlng = new google.maps.LatLng(-33.9,151.2),
    mapOptions = {
      zoom: 15,
      center: myLatlng,
      disableDefaultUI: true
    };

    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  var markers = [
    {
      latLan: new google.maps.LatLng(-33.9,151.2),
      icon: 'cutlery',
      color: '#346698',
      fontSize: '35px'
    },
    {
        latLan: new google.maps.LatLng(-33.8939,151.207333),
      icon: 'anchor',
      color: '#B90C13',
      fontSize: '35px'
    },
    {
      latLan: new google.maps.LatLng(-33.895,151.195),
      icon: 'automobile',
      color: '#39A00F',
      fontSize: '35px'
    },
    {
      latLan: new google.maps.LatLng(-33.905,151.195),
      icon: 'headphones',
      color: '#000',
      fontSize: '35px'
    },
     {
        latLan: new google.maps.LatLng(-33.9039,151.207333),
      icon: 'child',
      color: '#26C2C3',
      fontSize: '35px'
    },
  ]

  markers.forEach(function(item) {
    var markerstemp = new FontAwesomeMarker(
      item.latLan,
      map,
      {
        icon: item.icon,
        color: item.color,
        fontSize: item.fontSize
      }
    );

    //info window code starts here
    var infoWindow = new google.maps.InfoWindow();
    (function (markerstemp) {
                google.maps.event.addListener(markerstemp, "click", function (e) {
                    //Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
                    infoWindow.setContent("\<div style = \'width:auto;color:#000;font-size:12px;font-weight:500;padding:5px;\'\>Aww\</div\>");
                    infoWindow.open(map, markerstemp);
                });
            })(markerstemp);
  });
}

To test that, copy that code above and replace it to your initialize() function from the fiddle you've posted.


问:
Printing in WPF
I know how to invoke the print dialog and do other things. My question is : what is the best practice to print a WPF page.

To invoke another page with all
margins, formatting and layout worked
out. And then call the print on that

To invoke a user control with all
margins, formatting and layout worked
out. And then call the print on that

To invoke a window with all
margins, formatting and layout worked
out. And then call the print on that

Or any other preferred way of
doing this.

Please let me know how you approach printing ?

答:
In WPF you have many options to print. The question which one is best suited dependes IMO extremely on the content to be printed and the desired quality.

Printing visual

If ouy want to print something that looks exactly like the representation in the UI, then you could try printing directly the visual that builds the root-content of your print-content. If you have positioning problems and have to correct properties of this visual, I would recommend to created a memory-copy of it, transform the copy and then print out this copy. Printing out visuals has IMO many drawbacks. I seldom use it except for short hacks and mini-tools. If I use, I mostly have to create the mentioned invisible copy and print out this. If you go this way, take care that you have to call Measure and Arrange from code.

Printing FlowDocument

Another possiblity is to print out a FlowDocument. If you have something that fits into FlowDocuments, I find this an easy way to create nice content to print out. Mostly if you have some simple reports, list ith some images, this way is a nice way. The print-quality is good and many complex operations will be done for you automatically as long as you don't want to override behaviour, and also this is possible. The quality of such print-out's is IMO very good.

XPS Printing

Hovever if you have complex content and you want it to print out nicely, you have to build XPS-content and print it over the XPS Print Path. This way, you have all possibilities and options, the qualitity is very good but you have the most work to do. I don't like it much, but mostly it's the way I take to print.

I assume, that your question mainly concerns the first block, however I think it could be helpfull to see which options you have, if printing the visual is not enought (for me it's very seldom enough). Hope this answers your question.

Title: Printing in WPF

ContentLicense: CC BY-SA 2.5


问:
SQL Server Union performance improvement
I have a table like this:

This table has over 400k rows.

I am getting the values with a SQL Server function as below; actually I would like to get the last update record.

```<code>ALTER FUNCTION [dbo].[FncGetName]
    (@Season VARCHAR(30),
     @NameCode VARCHAR(30))
RETURNS VARCHAR(150)
AS
BEGIN
    DECLARE @Name VARCHAR(150)

    SET @Name = (SELECT TOP 1 Names.Name
                 FROM
                     (SELECT
                          CASE
                             WHEN Name1Unidecode IS NOT NULL
                                THEN Name1Unidecode
                                ELSE Name1
                          END AS Name
                      FROM
                          Persons
                      WHERE
                          Season IS NOT NULL
                          AND Season = @Season
                          AND Name1Code LIKE @NameCode + '%'
                      GROUP BY
                          Name1, Name1Unidecode

                      UNION

                      SELECT
                          CASE
                             WHEN Name2Unidecode IS NOT NULL
                                THEN Name2Unidecode
                                ELSE Name2
                          END AS Name
                      FROM
                          Persons
                      WHERE
                          Season IS NOT NULL
                          AND Season = @Season
                          AND Name2Code LIKE @NameCode + '%'
                      GROUP BY
                          Name2, Name2Unidecode) AS Names
             )

    RETURN @Name
END
</code>```

This is the SELECT query:

```<code>SELECT
    ID, ISNULL(dbo.FncGetName(Season , NameCode),ShortName) AS Name
FROM
    Table1
</code>```

So is there any approach to improve the performance?

EDITED

I have created 2 Index for UNION's SELECT query as below and performance improved.

```<code>CREATE NONCLUSTERED INDEX [Index_Name1] ON [dbo].[Person]
(
    [Season] DESC,
    [Name1Code] DESC,
    [Name1 DESC,
    [Name1Unidecode] DESC
)

CREATE NONCLUSTERED INDEX [Index_Name2] ON [dbo].[Person]
(
    [Season] DESC,
    [Name2Code] DESC,
    [Name2 DESC,
    [Name2Unidecode] DESC
)
</code>```

答:
I believe that you should use the following query instead of the original one

```<code>    SELECT TOP 1
            coalesce(Name1Unidecode, Name1, Name2Unidecode, Name2) AS Name
    FROM Persons
    WHERE Season IS NOT NULL
            AND Season = @Season
            AND (Name2Code LIKE @NameCode + '%' OR Name1Code LIKE @NameCode + '%')
   ORDER BY update desc
</code>```

I'm assuming that only one value is not NULL in attributes Name1Unidecode, Name1, Name2Unidecode, Name2. If it is not true, adjust it according to your data.

Moreover, if you have an indexes Person(Season, Name2Code, update) and Person(Season, Name1Code, update) then it should be really fast.

Body:
I have a table like this:

This table has over 400k rows.

I am getting the values with a SQL Server function as below; actually I would like to get the last update record.

ALTER FUNCTION [dbo].[FncGetName]
    (@Season VARCHAR(30),
     @NameCode VARCHAR(30))
RETURNS VARCHAR(150)
AS
BEGIN
    DECLARE @Name VARCHAR(150)

    SET @Name = (SELECT TOP 1 Names.Name
                 FROM
                     (SELECT
                          CASE
                             WHEN Name1Unidecode IS NOT NULL
                                THEN Name1Unidecode
                                ELSE Name1
                          END AS Name
                      FROM
                          Persons
                      WHERE
                          Season IS NOT NULL
                          AND Season = @Season
                          AND Name1Code LIKE @NameCode + '%'
                      GROUP BY
                          Name1, Name1Unidecode

                      UNION

                      SELECT
                          CASE
                             WHEN Name2Unidecode IS NOT NULL
                                THEN Name2Unidecode
                                ELSE Name2
                          END AS Name
                      FROM
                          Persons
                      WHERE
                          Season IS NOT NULL
                          AND Season = @Season
                          AND Name2Code LIKE @NameCode + '%'
                      GROUP BY
                          Name2, Name2Unidecode) AS Names
             )

    RETURN @Name
END

This is the SELECT query:

SELECT
    ID, ISNULL(dbo.FncGetName(Season , NameCode),ShortName) AS Name
FROM
    Table1

So is there any approach to improve the performance?

EDITED

I have created 2 Index for UNION's SELECT query as below and performance improved.

CREATE NONCLUSTERED INDEX [Index_Name1] ON [dbo].[Person]
(
    [Season] DESC,
    [Name1Code] DESC,
    [Name1 DESC,
    [Name1Unidecode] DESC
)

CREATE NONCLUSTERED INDEX [Index_Name2] ON [dbo].[Person]
(
    [Season] DESC,
    [Name2Code] DESC,
    [Name2 DESC,
    [Name2Unidecode] DESC
)

Body:
I believe that you should use the following query instead of the original one

    SELECT TOP 1
            coalesce(Name1Unidecode, Name1, Name2Unidecode, Name2) AS Name
    FROM Persons
    WHERE Season IS NOT NULL
            AND Season = @Season
            AND (Name2Code LIKE @NameCode + '%' OR Name1Code LIKE @NameCode + '%')
   ORDER BY update desc

I'm assuming that only one value is not NULL in attributes Name1Unidecode, Name1, Name2Unidecode, Name2. If it is not true, adjust it according to your data.

Moreover, if you have an indexes Person(Season, Name2Code, update) and Person(Season, Name1Code, update) then it should be really fast.


问:
Prevent Superuser from deleting/removing/editing User Email in Django Admin
I am using django-allauth for User signup and login purposes. Users can login using both username and email.

```<code># settings.py

# Custom User Model
AUTH_USER_MODEL = 'users.User'

# ask for either username or email during login
ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
# Set Email field as required during signup
ACCOUNT_EMAIL_REQUIRED = True
# Set email versification necessary before creating account
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
# Don't ask for username while signing up.
# Users can later edit/change username in their profile.
# If username is not set, use email to log in.
ACCOUNT_USERNAME_REQUIRED = False
# Login the user after email-confirmations
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
</code>```

I have a users app which implements a custom User Model as shown.

```<code># users/models.py

class User(AbstractUser):

    name = models.CharField(blank=True, max_length=255)

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': self.username})
</code>```

Using this setup, I am able to make user login via both email and username. However, the problem being the fact that Superuser is able to edit/remove 'email' in Django Admin. I don't want such behaviours. (An attempt to remove username however gives an "field required" error.)

My question now is,
How to prevent the Admin from editing the user information. i.e make 'username' and 'email' read-only fields.

答:
You can make a custom Model admin for user and add readonly_fields = ('email',)

```<code>@admin.register(User)
class UserAdmin(DjangoUserAdmin):

fieldsets = (
    (None, {'fields': ('email', 'password')}),
    (_('Personal info'), {'fields': ('first_name', 'last_name')}),
    (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser','role',
                                   'groups', 'user_permissions')}),
    (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('email', 'password1', 'password2'),
    }),
)
list_display = ('email', 'first_name', 'last_name', 'is_staff')
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email',)
readonly_fields = ('email',)
</code>```

Body:
I am using django-allauth for User signup and login purposes. Users can login using both username and email.

# settings.py

# Custom User Model
AUTH_USER_MODEL = 'users.User'

# ask for either username or email during login
ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
# Set Email field as required during signup
ACCOUNT_EMAIL_REQUIRED = True
# Set email versification necessary before creating account
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
# Don't ask for username while signing up.
# Users can later edit/change username in their profile.
# If username is not set, use email to log in.
ACCOUNT_USERNAME_REQUIRED = False
# Login the user after email-confirmations
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True

I have a users app which implements a custom User Model as shown.

# users/models.py

class User(AbstractUser):

    name = models.CharField(blank=True, max_length=255)

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': self.username})

Using this setup, I am able to make user login via both email and username. However, the problem being the fact that Superuser is able to edit/remove 'email' in Django Admin. I don't want such behaviours. (An attempt to remove username however gives an "field required" error.)

My question now is,
How to prevent the Admin from editing the user information. i.e make 'username' and 'email' read-only fields.

Body:
You can make a custom Model admin for user and add readonly_fields = ('email',)

@admin.register(User)
class UserAdmin(DjangoUserAdmin):

fieldsets = (
    (None, {'fields': ('email', 'password')}),
    (_('Personal info'), {'fields': ('first_name', 'last_name')}),
    (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser','role',
                                   'groups', 'user_permissions')}),
    (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('email', 'password1', 'password2'),
    }),
)
list_display = ('email', 'first_name', 'last_name', 'is_staff')
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email',)
readonly_fields = ('email',)


问:
VBA: InStr "OR" issue
I am having issue with my InStr "OR" code. This code: If InStr(items, "harmo") Or InStr(items, "pointt") Then count_of_Harmo = count_of_Harmo + 1
is able to execute well (Highlighted in red below) but this one doesn't ElseIf InStr(items, "addi") Or InStr(items, "add-i") Or InStr(items, "plug") Then count_of_Addi = count_of_Addi + 1(Highlighted in blue below). Please don't mind the other results/counts on the image below as i was not able to capture the whole page as it I think it is relevant to the case. Please see the full code below too. Thank you.

```<code>Option Compare Text

Public Sub Keywords_Outlook()

Dim row_number As Long
Dim count_of_Harmo As Long
Dim count_of_Room As Long
Dim count_of_Skyp As Long
Dim count_of_Detach As Long
Dim count_of_Wire As Long
Dim count_of_Addi As Long
Dim count_of_crash As Long
Dim count_of_share As Long
Dim count_of_signa As Long
Dim count_of_passw As Long
Dim count_of_follo_and_ops As Long
Dim count_of_follo_and_req As Long
Dim count_of_others As Long
Dim items As Variant
Dim cursht As String 'for the macro to run in any sheet
cursht = ActiveSheet.Name 'for the macro to run in any sheet

row_number = 1
count_of_Harmo = 0
count_of_Room = 0
count_of_Skyp = 0
count_of_Detach = 0
count_of_Wire = 0
count_of_Addi = 0
count_of_crash = 0
count_of_share = 0
count_of_signa = 0
count_of_passw = 0
count_of_follo_and_ops = 0
count_of_follo_and_req = 0
count_of_others = 0
count_of_all = 0

Do

row_number = row_number + 1
items = Sheets(cursht).Range("N" & row_number)

    If InStr(items, "harmo") Or InStr(items, "pointt") Then
        count_of_Harmo = count_of_Harmo + 1
    ElseIf InStr(items, "room") Then
        count_of_Room = count_of_Room + 1
    ElseIf InStr(items, "skyp") Then
        count_of_Skyp = count_of_Skyp + 1
    ElseIf InStr(items, "detach") Then
        count_of_Detach = count_of_Detach + 1
    ElseIf InStr(items, "wire") Then
        count_of_Wire = count_of_Wire + 1
    ElseIf InStr(items, "addi") Or InStr(items, "add-i") Or InStr(items, "plug") Then
        count_of_Addi = count_of_Addi + 1
    ElseIf InStr(items, "crash") Or InStr(items, "car") Then
        count_of_crash = count_of_crash + 1
    ElseIf InStr(items, "share") Then
        count_of_share = count_of_share + 1
    ElseIf InStr(items, "signa") Then
        count_of_signa = count_of_signa + 1
    ElseIf InStr(items, "passw") Then
        count_of_passw = count_of_passw + 1
    ElseIf Trim(items) Like "*followu*" And Trim(items) Like "*ops*" Then
        count_of_follo_and_ops = count_of_follo_and_ops + 1
    ElseIf Trim(items) Like "*followu*" And Trim(items) Like "*req*" Then
        count_of_follo_and_req = count_of_follo_and_req + 1

    ElseIf items <> "" Then
        count_of_others = count_of_others + 1
    End If

Loop Until items = ""

count_of_all = count_of_Harmo + count_of_Room + count_of_Skyp + count_of_Detach + count_of_Wire + count_of_Addi + count_of_crash + count_of_signa + count_of_passw + count_of_follo_and_ops + count_of_follo_and_req + count_of_others

Range("N2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_Harmo
ActiveCell.Offset(5, 0).Value = count_of_Room
ActiveCell.Offset(6, 0).Value = count_of_Skyp
ActiveCell.Offset(7, 0).Value = count_of_Detach
ActiveCell.Offset(8, 0).Value = count_of_Wire
ActiveCell.Offset(9, 0).Value = count_of_Addi
ActiveCell.Offset(10, 0).Value = count_of_crash
ActiveCell.Offset(11, 0).Value = count_of_share
ActiveCell.Offset(12, 0).Value = count_of_signa
ActiveCell.Offset(13, 0).Value = count_of_passw
ActiveCell.Offset(14, 0).Value = count_of_follo_and_ops
ActiveCell.Offset(15, 0).Value = count_of_follo_and_req
ActiveCell.Offset(16, 0).Value = count_of_others
ActiveCell.Offset(18, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Outlook Keywords"
ActiveCell.Offset(4, 1).Value = "Harmo"
ActiveCell.Offset(5, 1).Value = "Room"
ActiveCell.Offset(6, 1).Value = "Skyp"
ActiveCell.Offset(7, 1).Value = "Detach"
ActiveCell.Offset(8, 1).Value = "Wire"
ActiveCell.Offset(9, 1).Value = "Addi or add-i or plug"
ActiveCell.Offset(10, 1).Value = "Crash"
ActiveCell.Offset(11, 1).Value = "Share"
ActiveCell.Offset(12, 1).Value = "Signa"
ActiveCell.Offset(13, 1).Value = "passw"
ActiveCell.Offset(14, 1).Value = "FollowU and ops"
ActiveCell.Offset(15, 1).Value = "FollowU and req"
ActiveCell.Offset(16, 1).Value = "Others"
ActiveCell.Offset(18, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_Harmo / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_Room / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_Skyp / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_Detach / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_Wire / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_Addi / count_of_all
ActiveCell.Offset(10, -1).Value = count_of_crash / count_of_all
ActiveCell.Offset(11, -1).Value = count_of_share / count_of_all
ActiveCell.Offset(12, -1).Value = count_of_signa / count_of_all
ActiveCell.Offset(13, -1).Value = count_of_passw / count_of_all
ActiveCell.Offset(14, -1).Value = count_of_follo_and_ops / count_of_all
ActiveCell.Offset(15, -1).Value = count_of_follo_and_req / count_of_all
ActiveCell.Offset(16, -1).Value = count_of_others / count_of_all

End Sub
</code>```

答:
In an entire If/ElseIf statement, each branch can only execute if all preceding branches did not.

The cell circled in blue triggered the Harmo branch and it cannot trigger any other branches.

If you don't want that to happen, make each branch a separate If/End If statement.

On a side note, you should consider explicitly comparing the result of InStr to zero in all cases. It works currently because you are only using Or, but if you decide to make the condition more complex it might stop working.

Title: VBA: InStr "OR" issue

Body:
I am having issue with my InStr "OR" code. This code: If InStr(items, "harmo") Or InStr(items, "pointt") Then count_of_Harmo = count_of_Harmo + 1
is able to execute well (Highlighted in red below) but this one doesn't ElseIf InStr(items, "addi") Or InStr(items, "add-i") Or InStr(items, "plug") Then count_of_Addi = count_of_Addi + 1(Highlighted in blue below). Please don't mind the other results/counts on the image below as i was not able to capture the whole page as it I think it is relevant to the case. Please see the full code below too. Thank you.

Option Compare Text

Public Sub Keywords_Outlook()

Dim row_number As Long
Dim count_of_Harmo As Long
Dim count_of_Room As Long
Dim count_of_Skyp As Long
Dim count_of_Detach As Long
Dim count_of_Wire As Long
Dim count_of_Addi As Long
Dim count_of_crash As Long
Dim count_of_share As Long
Dim count_of_signa As Long
Dim count_of_passw As Long
Dim count_of_follo_and_ops As Long
Dim count_of_follo_and_req As Long
Dim count_of_others As Long
Dim items As Variant
Dim cursht As String 'for the macro to run in any sheet
cursht = ActiveSheet.Name 'for the macro to run in any sheet

row_number = 1
count_of_Harmo = 0
count_of_Room = 0
count_of_Skyp = 0
count_of_Detach = 0
count_of_Wire = 0
count_of_Addi = 0
count_of_crash = 0
count_of_share = 0
count_of_signa = 0
count_of_passw = 0
count_of_follo_and_ops = 0
count_of_follo_and_req = 0
count_of_others = 0
count_of_all = 0

Do

row_number = row_number + 1
items = Sheets(cursht).Range("N" & row_number)

    If InStr(items, "harmo") Or InStr(items, "pointt") Then
        count_of_Harmo = count_of_Harmo + 1
    ElseIf InStr(items, "room") Then
        count_of_Room = count_of_Room + 1
    ElseIf InStr(items, "skyp") Then
        count_of_Skyp = count_of_Skyp + 1
    ElseIf InStr(items, "detach") Then
        count_of_Detach = count_of_Detach + 1
    ElseIf InStr(items, "wire") Then
        count_of_Wire = count_of_Wire + 1
    ElseIf InStr(items, "addi") Or InStr(items, "add-i") Or InStr(items, "plug") Then
        count_of_Addi = count_of_Addi + 1
    ElseIf InStr(items, "crash") Or InStr(items, "car") Then
        count_of_crash = count_of_crash + 1
    ElseIf InStr(items, "share") Then
        count_of_share = count_of_share + 1
    ElseIf InStr(items, "signa") Then
        count_of_signa = count_of_signa + 1
    ElseIf InStr(items, "passw") Then
        count_of_passw = count_of_passw + 1
    ElseIf Trim(items) Like "*followu*" And Trim(items) Like "*ops*" Then
        count_of_follo_and_ops = count_of_follo_and_ops + 1
    ElseIf Trim(items) Like "*followu*" And Trim(items) Like "*req*" Then
        count_of_follo_and_req = count_of_follo_and_req + 1

    ElseIf items <> "" Then
        count_of_others = count_of_others + 1
    End If

Loop Until items = ""

count_of_all = count_of_Harmo + count_of_Room + count_of_Skyp + count_of_Detach + count_of_Wire + count_of_Addi + count_of_crash + count_of_signa + count_of_passw + count_of_follo_and_ops + count_of_follo_and_req + count_of_others

Range("N2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_Harmo
ActiveCell.Offset(5, 0).Value = count_of_Room
ActiveCell.Offset(6, 0).Value = count_of_Skyp
ActiveCell.Offset(7, 0).Value = count_of_Detach
ActiveCell.Offset(8, 0).Value = count_of_Wire
ActiveCell.Offset(9, 0).Value = count_of_Addi
ActiveCell.Offset(10, 0).Value = count_of_crash
ActiveCell.Offset(11, 0).Value = count_of_share
ActiveCell.Offset(12, 0).Value = count_of_signa
ActiveCell.Offset(13, 0).Value = count_of_passw
ActiveCell.Offset(14, 0).Value = count_of_follo_and_ops
ActiveCell.Offset(15, 0).Value = count_of_follo_and_req
ActiveCell.Offset(16, 0).Value = count_of_others
ActiveCell.Offset(18, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Outlook Keywords"
ActiveCell.Offset(4, 1).Value = "Harmo"
ActiveCell.Offset(5, 1).Value = "Room"
ActiveCell.Offset(6, 1).Value = "Skyp"
ActiveCell.Offset(7, 1).Value = "Detach"
ActiveCell.Offset(8, 1).Value = "Wire"
ActiveCell.Offset(9, 1).Value = "Addi or add-i or plug"
ActiveCell.Offset(10, 1).Value = "Crash"
ActiveCell.Offset(11, 1).Value = "Share"
ActiveCell.Offset(12, 1).Value = "Signa"
ActiveCell.Offset(13, 1).Value = "passw"
ActiveCell.Offset(14, 1).Value = "FollowU and ops"
ActiveCell.Offset(15, 1).Value = "FollowU and req"
ActiveCell.Offset(16, 1).Value = "Others"
ActiveCell.Offset(18, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_Harmo / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_Room / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_Skyp / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_Detach / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_Wire / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_Addi / count_of_all
ActiveCell.Offset(10, -1).Value = count_of_crash / count_of_all
ActiveCell.Offset(11, -1).Value = count_of_share / count_of_all
ActiveCell.Offset(12, -1).Value = count_of_signa / count_of_all
ActiveCell.Offset(13, -1).Value = count_of_passw / count_of_all
ActiveCell.Offset(14, -1).Value = count_of_follo_and_ops / count_of_all
ActiveCell.Offset(15, -1).Value = count_of_follo_and_req / count_of_all
ActiveCell.Offset(16, -1).Value = count_of_others / count_of_all

End Sub


问:
C++ - Macro defines directive
At: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

It mentions a directive called "Macro defines". What do we mean when we say "Macro"?

Thanks.

答:
A macro is a code fragment that gets substituted into your program by the preprocessor (before compilation proper begins).  This may be a function-like block, or it may be a constant value.

A warning when using a function-like macro.  Consider the following code:

```<code>#define foo(x) x*x
</code>```

If you call foo(3), it will become (and be compiled as) 3*3 (=9).  If, instead, you call foo(2+3), it will become 2+3*2+3, (=2+6+3=11), which is not what you want.  Also, since the code is substituted in place, foo(bar++) becomes bar++ * bar++, incrementing bar twice.

Macros are powerful tools, but it can be easy to shoot yourself in the foot while trying to do something fancy with them.

Title: C++ - Macro defines directive

Body:
A macro is a code fragment that gets substituted into your program by the preprocessor (before compilation proper begins).  This may be a function-like block, or it may be a constant value.

A warning when using a function-like macro.  Consider the following code:

#define foo(x) x*x

If you call foo(3), it will become (and be compiled as) 3*3 (=9).  If, instead, you call foo(2+3), it will become 2+3*2+3, (=2+6+3=11), which is not what you want.  Also, since the code is substituted in place, foo(bar++) becomes bar++ * bar++, incrementing bar twice.

Macros are powerful tools, but it can be easy to shoot yourself in the foot while trying to do something fancy with them.


问:
"total += i;" does not work for some reason
For some reason the "total += i;" wont work and when i go to return "total" it returns as 0.

```<code>long int sumOfGroup(int k) {
    long int special = (k * k) + (k - 1);
    long int limit =  special - ((k-1) * 2);
    cout << special << " " << limit << endl;
    long int total = 0;
    for(int i = special; i <= limit; i - 2){
        total += i;
    }
    return  total;
}

int main() {
    int k;
    cin >> k;
    long answer = sumOfGroup(k);
    cout << answer << endl;
    return 0;
}
</code>```

if you ran this no matter the input the answer is 0. all my other numbers are correct and I am quite sure it has something to do with the for loop.

答:
try this for your loop:</p>

```<code>for(int i = special; i >= limit; i -= 2){
    total += i;
}
</code>```

Body:
For some reason the "total += i;" wont work and when i go to return "total" it returns as 0.

long int sumOfGroup(int k) {
    long int special = (k * k) + (k - 1);
    long int limit =  special - ((k-1) * 2);
    cout << special << " " << limit << endl;
    long int total = 0;
    for(int i = special; i <= limit; i - 2){
        total += i;
    }
    return  total;
}

int main() {
    int k;
    cin >> k;
    long answer = sumOfGroup(k);
    cout << answer << endl;
    return 0;
}

if you ran this no matter the input the answer is 0. all my other numbers are correct and I am quite sure it has something to do with the for loop.

Body:
try this for your loop:

for(int i = special; i >= limit; i -= 2){
    total += i;
}


问:
how call function in domain Ono2many field odoo 8
message Error:

TypeError: old_api() takes at least 3 arguments (1 given)

code py:

```<code>@api.model
def domain_users(self):
        if self.env.user.login=="bendjeddou.o":
            domain=[('exp_P','>',0)]
        else:
            domain=[]
        return domain
o2m_materiels fields.One2many('gmat.journaleline','rapJor_ids',string='Materiel',domain=domain_users)
</code>```

class py:

```<code>class Journaleline(models.Model):
    _name = 'gmat.journaleline'
    _description    =   'Detail materiel'

   rapJor_ids = fields.Many2one('gmat.rapporjournal',string='num')
   exp_P = fields.Float(string='Panne(H)',default=0)
</code>```

答:
all message error:

```<code>Traceback (most recent call last):

    File "/opt/odoo/openerp/http.py", line 544, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/opt/odoo/openerp/http.py", line 581, in dispatch
    result = self._call_function(**self.params)
  File "/opt/odoo/openerp/http.py", line 317, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/opt/odoo/openerp/service/model.py", line 118, in wrapper
    return f(dbname, *args, **kwargs)
  File "/opt/odoo/openerp/http.py", line 314, in checked_call
    return self.endpoint(*a, **kw)
  File "/opt/odoo/openerp/http.py", line 810, in __call__
    return self.method(*args, **kw)
  File "/opt/odoo/openerp/http.py", line 410, in response_wrap
    response = f(*args, **kw)
  File "/opt/odoo/openerp/addons/web/controllers/main.py", line 944, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/opt/odoo/openerp/addons/web/controllers/main.py", line 936, in _call_kw
    return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
  File "/opt/odoo/openerp/api.py", line 268, in wrapper
    return old_api(self, *args, **kwargs)
  File "/opt/odoo/openerp/models.py", line 3148, in read
    result = BaseModel.read(records, fields, load=load)
  File "/opt/odoo/openerp/api.py", line 266, in wrapper
    return new_api(self, *args, **kwargs)
  File "/opt/odoo/openerp/models.py", line 3183, in read
    self._read_from_database(stored, inherited)
  File "/opt/odoo/openerp/api.py", line 266, in wrapper
    return new_api(self, *args, **kwargs)
  File "/opt/odoo/openerp/models.py", line 3370, in _read_from_database
    res2 = self._columns[f].get(cr, self._model, ids, f, user, context=context, values=result)
  File "/opt/odoo/openerp/osv/fields.py", line 773, in get
    domain = self._domain(obj) if callable(self._domain) else self._domain
  File "/opt/odoo/openerp/api.py", line 268, in wrapper
    return old_api(self, *args, **kwargs)
</code>```

TypeError: old_api() takes at least 3 arguments (1 given)

Body:
message Error:

TypeError: old_api() takes at least 3 arguments (1 given)

code py:

@api.model
def domain_users(self):
        if self.env.user.login=="bendjeddou.o":
            domain=[('exp_P','>',0)]
        else:
            domain=[]
        return domain
o2m_materiels fields.One2many('gmat.journaleline','rapJor_ids',string='Materiel',domain=domain_users)

class py:

class Journaleline(models.Model):
    _name = 'gmat.journaleline'
    _description    =   'Detail materiel'

   rapJor_ids = fields.Many2one('gmat.rapporjournal',string='num')
   exp_P = fields.Float(string='Panne(H)',default=0)

Body:
all message error:

Traceback (most recent call last):

    File "/opt/odoo/openerp/http.py", line 544, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/opt/odoo/openerp/http.py", line 581, in dispatch
    result = self._call_function(**self.params)
  File "/opt/odoo/openerp/http.py", line 317, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/opt/odoo/openerp/service/model.py", line 118, in wrapper
    return f(dbname, *args, **kwargs)
  File "/opt/odoo/openerp/http.py", line 314, in checked_call
    return self.endpoint(*a, **kw)
  File "/opt/odoo/openerp/http.py", line 810, in __call__
    return self.method(*args, **kw)
  File "/opt/odoo/openerp/http.py", line 410, in response_wrap
    response = f(*args, **kw)
  File "/opt/odoo/openerp/addons/web/controllers/main.py", line 944, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/opt/odoo/openerp/addons/web/controllers/main.py", line 936, in _call_kw
    return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
  File "/opt/odoo/openerp/api.py", line 268, in wrapper
    return old_api(self, *args, **kwargs)
  File "/opt/odoo/openerp/models.py", line 3148, in read
    result = BaseModel.read(records, fields, load=load)
  File "/opt/odoo/openerp/api.py", line 266, in wrapper
    return new_api(self, *args, **kwargs)
  File "/opt/odoo/openerp/models.py", line 3183, in read
    self._read_from_database(stored, inherited)
  File "/opt/odoo/openerp/api.py", line 266, in wrapper
    return new_api(self, *args, **kwargs)
  File "/opt/odoo/openerp/models.py", line 3370, in _read_from_database
    res2 = self._columns[f].get(cr, self._model, ids, f, user, context=context, values=result)
  File "/opt/odoo/openerp/osv/fields.py", line 773, in get
    domain = self._domain(obj) if callable(self._domain) else self._domain
  File "/opt/odoo/openerp/api.py", line 268, in wrapper
    return old_api(self, *args, **kwargs)

TypeError: old_api() takes at least 3 arguments (1 given)


问:
Storing Smtp from email friendly display name in Web.Config
I'm storing my mailsettings in the web config like so...

```<code><mailSettings>
    <smtp from="splidge@findremovalcompanies.com">
        <network host="smtp.findremovalcompanies.com" userName="splidge@findremovalcompanies.com" password="password" />
    </smtp>
</mailSettings>
</code>```

Now when I create a new

```<code>var smtp = new SmtpClient();
</code>```

smpt has my credentials and will default the from address to splidge@findremovalcompanies.com which saves me from having to do this every time.

```<code>MailAddress("splidge@findremovalcompanies.com", "Splidge Master")
</code>```

But I cannot figure out how to specify the friendly display name "Splidge Master" in the web.config theres no setting for it?

答:
If you need the exact equivalent, encode the double quotes (") too :

```<code><smtp from=""Splidge Master" <splidge@findremovalcompanies.com>">
</code>```

Body:
I'm storing my mailsettings in the web config like so...

<mailSettings>
    <smtp from="splidge@findremovalcompanies.com">
        <network host="smtp.findremovalcompanies.com" userName="splidge@findremovalcompanies.com" password="password" />
    </smtp>
</mailSettings>

Now when I create a new

var smtp = new SmtpClient();

smpt has my credentials and will default the from address to splidge@findremovalcompanies.com which saves me from having to do this every time.

MailAddress("splidge@findremovalcompanies.com", "Splidge Master")

But I cannot figure out how to specify the friendly display name "Splidge Master" in the web.config theres no setting for it?

Body:
If you need the exact equivalent, encode the double quotes (&quot;) too :

<smtp from="&quot;Splidge Master&quot; &lt;splidge@findremovalcompanies.com&gt;">


问:
Enable cluster mode on AWS ElastiCache Redis cluster
I have an ElastiCache Redis (cluster mode disabled) Cluster and would like to change to an ElastiCache Redis (cluster mode enabled) Cluster. I haven't found a way to do this, but also have not found a statement that it is not possible either. This is complicated by the confusing language around 'cluster' and 'cluster mode'.

This document from Amazon states that:

Currently, Redis (cluster mode enabled) does not support creating a
  cluster with replicas using an available single-node cluster.

This somewhat implies that it can be done from a cluster with multiple nodes.

Similarly, this document about modifying a cluster says:

You can modify a Redis (cluster mode disabled) cluster's settings using the ElastiCache console, the AWS CLI, or the ElastiCache API. Currently, ElastiCache does not support modifying a Redis (cluster mode enabled) replication group except by creating a backup of the current replication group then using that backup to seed a new Redis (cluster mode enabled) replication group.

Again, this implies that you can change a Redis (cluster mode disabled) cluster but doesn't really say one way or another. Though, I get the idea from this statement that I'd need to back up the current Redis (cluster mode disabled) cluster and then use that to seed a new Redis (cluster mode enabled) cluster.

答:
You have to provision a new cluster with "Cluster" mode enabled, what you want is unfortunately not possible.

You data though can be backed up to S3, and used to seed the newly created system.


问:
Symfony 3.4.0 Could not find any fixture services to load
I am using Symfony 3.4.0, I try to load fixtures with:

```<code>php bin/console doctrine:fixtures:load
</code>```

An error occurred while creating the data, what's wrong?

答:
In 4.0.1 I have to implement service configuration to show Symfony my DataFixtures folder:

in config/services.yaml

```<code>services:

    ...

    App\DataFixtures\:
        resource: '%kernel.project_dir%/src/DataFixtures'
        tags: [doctrine.fixture.orm]
</code>```

if my class IMPLEMENTS FixtureInterface and without this config if it is EXTENDS Fixture

Body:
I am using Symfony 3.4.0, I try to load fixtures with:

php bin/console doctrine:fixtures:load

An error occurred while creating the data, what's wrong?

Body:
In 4.0.1 I have to implement service configuration to show Symfony my DataFixtures folder:

in config/services.yaml

services:

    ...

    App\DataFixtures\:
        resource: '%kernel.project_dir%/src/DataFixtures'
        tags: [doctrine.fixture.orm]

if my class IMPLEMENTS FixtureInterface and without this config if it is EXTENDS Fixture

ContentLicense: CC BY-SA 4.0


问:
Best way to import Google Cloud SQL data into BigQuery
I have a database in a Cloud SQL instance. I would like to copy its content into BigQuery in order to perform analysis.
It is not a requirement for me to continuously update the BigQuery dataset. It is OK if the export is done only once.

What is the best way to achieve this?

The 'Create Table' BigQuery UI does not allow me to import from Cloud SQL (only File, Cloud Storage, Drive or BigTable).

答:
Up to now, there is no automated tool to import data into BigQuery from Cloud SQL, so a procedure you can follow consists in:

Export the data from the table you want in your Cloud SQL instance in CSV format, as explained in the documentation.

Import the CSV data into the BigQuery table you want following the procedure also explained in the documentation.

You are done. If your database is large and has many tables, you may want to do the import programatically, using the API.


问:
QQuickWindow subclass, visibilityChanged and closing signals
I'm trying to create own window class and use it in QML. In first steps I'm trying to subclass QQuickWindow in this way:

```<code>class TestWindow : public QQuickWindow {
Q_OBJECT
...
};
</code>```

then in main.cpp file:

```<code>qmlRegisterType<TestWindow>("test.components", 1, 0, "TestWindow");
</code>```

now in QML I can simply use it in such way:

```<code>import test.components 1.0
TestWindow {
    //onClosing: console.log("closing")
    //onVisibilityChanged: console.log(visibility)
}
</code>```

The problem appears when I'll try to uncomment one of these lines. QML engine says that: ""TestWindow.onVisibilityChanged" is not available in test.components 1.0." Similar thing happens in case of "onClosing". I should be inherited from QWindow/QQuickWindow but I tried to create own anyway.

```<code>  //connect(this, QQuickWindow::visibilityChanged, this, TestWindow::visibilityChanged);
</code>```

and declare appropriate Q_PROPERTY with READ/WRITE and NOTIFY section defined as well. I replaced closing signal with "closingEvent" and did something like this:

```<code>//connect(this, SIGNAL(closing(QQuickCloseEvent*)), this, SIGNAL(closingEvent(QQuickCloseEvent*)));
</code>```

which is also strange cuz when I try to use new signals/slots syntax, the compiler complains about incomplete QQuickCloseEvent which isn't described anywhere and seems to be something from Qt internals. So I had to stick with older code version.

After these treatments, The other "Window" (not TestWindow) from import QtQuick.Window 2.2 says that "x" and "y" properties are undefined. The more warnings/errors I'll try to fix, the more other things stops to work properly.

Has anyone had a similar problem?

edit: I find out that it has something to do with Q_REVISION macro used in case of some signals/slots/properties for both QWindow and QQuickWindow. I even tried to use these lines:

```<code>//qmlRegisterType<TestWindow>("test.components", 1, 0, "TestWindow");
//qmlRegisterType<TestWindow, 1>("test.components", 1, 0, "TestWindow");
qmlRegisterType<TestWindow, 2>("test.components", 1, 0, "TestWindow");
</code>```

still without success.

答:
I found a solution.

```<code>  qmlRegisterType<TestWindow>("test.components", 1, 0, "TestWindow");
  qmlRegisterRevision<QWindow, 1>("test.components", 1, 0);
  qmlRegisterRevision<QQuickWindow, 1>("test.components", 1, 0);
</code>```

I had to register revisions of base classes as well. The explanation described here: https://bugreports.qt.io/browse/QTBUG-22688 in comment.

Body:
I'm trying to create own window class and use it in QML. In first steps I'm trying to subclass QQuickWindow in this way:

class TestWindow : public QQuickWindow {
Q_OBJECT
...
};

then in main.cpp file:

qmlRegisterType<TestWindow>("test.components", 1, 0, "TestWindow");

now in QML I can simply use it in such way:

import test.components 1.0
TestWindow {
    //onClosing: console.log("closing")
    //onVisibilityChanged: console.log(visibility)
}

The problem appears when I'll try to uncomment one of these lines. QML engine says that: ""TestWindow.onVisibilityChanged" is not available in test.components 1.0." Similar thing happens in case of "onClosing". I should be inherited from QWindow/QQuickWindow but I tried to create own anyway.

  //connect(this, QQuickWindow::visibilityChanged, this, TestWindow::visibilityChanged);

and declare appropriate Q_PROPERTY with READ/WRITE and NOTIFY section defined as well. I replaced closing signal with "closingEvent" and did something like this:

//connect(this, SIGNAL(closing(QQuickCloseEvent*)), this, SIGNAL(closingEvent(QQuickCloseEvent*)));

which is also strange cuz when I try to use new signals/slots syntax, the compiler complains about incomplete QQuickCloseEvent which isn't described anywhere and seems to be something from Qt internals. So I had to stick with older code version.

After these treatments, The other "Window" (not TestWindow) from import QtQuick.Window 2.2 says that "x" and "y" properties are undefined. The more warnings/errors I'll try to fix, the more other things stops to work properly.

Has anyone had a similar problem?

edit: I find out that it has something to do with Q_REVISION macro used in case of some signals/slots/properties for both QWindow and QQuickWindow. I even tried to use these lines:

//qmlRegisterType<TestWindow>("test.components", 1, 0, "TestWindow");
//qmlRegisterType<TestWindow, 1>("test.components", 1, 0, "TestWindow");
qmlRegisterType<TestWindow, 2>("test.components", 1, 0, "TestWindow");

still without success.

Body:
I found a solution.

  qmlRegisterType<TestWindow>("test.components", 1, 0, "TestWindow");
  qmlRegisterRevision<QWindow, 1>("test.components", 1, 0);
  qmlRegisterRevision<QQuickWindow, 1>("test.components", 1, 0);

I had to register revisions of base classes as well. The explanation described here: https://bugreports.qt.io/browse/QTBUG-22688 in comment.


问:
How to read/write .xpt file with Python?
Am new to Python and looking for a solution to read/write xpt file(SAS data set) using Python.

I got to know its possible using Python from this link. But then the code is not working as expected. Anything missing in this code, whether to include any library or to install any library. Or even any syntax error in this code.

```<code>with open('example.xpt', 'rb') as f:
for row in xport.Reader(f):
    print row
</code>```

Note: Am familiar with PHP scripting.

Please help me with suitable solution.

答:
You need to import the package to use xport

```<code>Import xport
</code>```

And have to install the package by

```<code>sudo pip install xport
</code>```

Body:
Am new to Python and looking for a solution to read/write xpt file(SAS data set) using Python.

I got to know its possible using Python from this link. But then the code is not working as expected. Anything missing in this code, whether to include any library or to install any library. Or even any syntax error in this code.

with open('example.xpt', 'rb') as f:
for row in xport.Reader(f):
    print row

Note: Am familiar with PHP scripting.

Please help me with suitable solution.

Body:
You need to import the package to use xport

Import xport

And have to install the package by

sudo pip install xport


问:
Java servlets - navigate to page
I have the following project structure:

I am trying to navigate to concerts.jsp from index.jsp:

index.jsp

```<code><li class="active"><a href="/ConcertsController">Concerts</a></li>
</code>```

This is my ConcertsController:

```<code>@WebServlet("/ConcertsController")
public class ConcertsController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ConcertsController() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
        request.getRequestDispatcher("/WEB-INF/pages/concerts.jsp").forward(request, response);
    }
        ...
    }
</code>```

When I run the app, and click on the link in index.jsp, localhost:8080/ConcertsController URL opens and I get the

The requested resource is not available

error.

Edit 1: I am using Tomcat v7.0, servlets v3.0 and Java 8.

Edit 2 (possible duplicate): Well, surely I need to be able to do this without using the jstl library.

Edit 3: When localhost:8080/ConcertsController opens, I get the "resource not found" error. But when I manually edit the url to localhost:8080/AppName/ConcertsController, it works.

答:
URL  localhost:8080/ConcertsController means Application name is ConcertsController, port number is 8080 and the application is run locally. But you do not have ConcertsController Application.
so you are getting error

The requested resource is not available

There are 2 solutions

if you are not using JSTL.

Change href="/ConcertsController"> to href="<%${pageContext.request.contextPath}%>/ConcertsController">

If JSTL is used then <c:set var="contextPath" value="${pageContext.request.contextPath}" />
and then
change href="/ConcertsController"> to href="${contextPath}/ConcertsController">

Title: Java servlets - navigate to page

Body:
I have the following project structure:

I am trying to navigate to concerts.jsp from index.jsp:

index.jsp

Concerts

This is my ConcertsController:

@WebServlet("/ConcertsController")
public class ConcertsController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ConcertsController() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
        request.getRequestDispatcher("/WEB-INF/pages/concerts.jsp").forward(request, response);
    }
        ...
    }

When I run the app, and click on the link in index.jsp, localhost:8080/ConcertsController URL opens and I get the

The requested resource is not available

error.

Edit 1: I am using Tomcat v7.0, servlets v3.0 and Java 8.

Edit 2 (possible duplicate): Well, surely I need to be able to do this without using the jstl library.

Edit 3: When localhost:8080/ConcertsController opens, I get the "resource not found" error. But when I manually edit the url to localhost:8080/AppName/ConcertsController, it works.

Body:
URL  localhost:8080/ConcertsController means Application name is ConcertsController, port number is 8080 and the application is run locally. But you do not have ConcertsController Application.
so you are getting error

The requested resource is not available

There are 2 solutions

if you are not using JSTL.

Change <a href="/ConcertsController"> to <a href="<%${pageContext.request.contextPath}%>/ConcertsController">

If JSTL is used then <c:set var="contextPath" value="${pageContext.request.contextPath}" />
and then
change <a href="/ConcertsController"> to <a href="${contextPath}/ConcertsController">


问:
How to get the distinct id using the same column twice in SQL

I have the following issue. I have a user_id column and an attribute_idcolumn and I want to get the users id that has the attribute_id 1 and 4.

In this case, the result would be one single column with the user_id 1 and 35, once they both have the attribute id 1 and 4.

答:
You may use this:</p>

```<code>SELECT user_id
FROM table_name
WHERE attribute_id IN (1, 4)
GROUP BY user_id
HAVING COUNT(DISTINCT attribute_id) = 2;
</code>```

Body:
You may use this:

SELECT user_id
FROM table_name
WHERE attribute_id IN (1, 4)
GROUP BY user_id
HAVING COUNT(DISTINCT attribute_id) = 2;


问:
adal4j authentication with ClientCredential + login/password
I connect to a Azure AD  with Adal4j to let a Native App access MS CRM Web api.

We use this method to get the token:

```<code>AuthenticationContext : public Future<AuthenticationResult> acquireToken(
    final String resource, final String clientId,
    final String username, final String password,
    final AuthenticationCallback callback)
</code>```

Now I wan to use the same code for a web application. So I have registered a Web app in Azure AD with 'Delegate Permissions' and 'Access CRM Online as organization uses' checked.

I first tried with any change and I have received this error :

{"error_description":"AADSTS70002: The request body must contain the following parameter: 'client_secret or client_assertion'.\r\nTrace ID: xxxxxxxxxxxxxxxxxxxx\r\nCorrelation ID: xxxxxxxxxxxxx\r\nTimestamp: 2017-12-01 14:18:03Z","error":"invalid_client"}

Just to test, I have updated ClientAuthenticationPost.toParameters() method to force the client_secret, and it works:

```<code>Map<String, String> toParameters() {

    Map<String, String> params = new HashMap<String, String>();

    params.put("client_id", getClientID().getValue());
    params.put("client_secret", "___my_client_secret___"); // added line

    return params;
}
</code>```

My question is, why there is no such a method 'clientCredential + Login/password' :

```<code>AuthenticationContext : public Future<AuthenticationResult> acquireToken(
    final String resource, final ClientCredential clientCredential, // ClientCredential = client_id + client_secret
    final String username, final String password,
    final AuthenticationCallback callback)
</code>```

Should it be added ? Or the way I authenticate is wrong ?

Best regards.

答:
Here is the helper method I have added AuthenticationContext Class:

```<code>public Future<AuthenticationResult> acquireToken(final String resource,
                                                 final ClientCredential clientCredential, final String username,
                                                 final String password, final AuthenticationCallback callback) {
    if (StringHelper.isBlank(resource)) {
        throw new IllegalArgumentException("resource is null or empty");
    }

    if (clientCredential == null) {
        throw new IllegalArgumentException("client credential is null");
    }

    if (StringHelper.isBlank(username)) {
        throw new IllegalArgumentException("username is null or empty");
    }

    if (StringHelper.isBlank(password)) {
        throw new IllegalArgumentException("password is null or empty");
    }

    final ClientAuthentication clientAuth = new ClientSecretPost(
            new ClientID(clientCredential.getClientId()), new Secret(
            clientCredential.getClientSecret()));

    return this.acquireToken(new AdalAuthorizatonGrant(
                    new ResourceOwnerPasswordCredentialsGrant(username, new Secret(
                            password)), resource), clientAuth, callback);
}
</code>```

It works fine for my registered Web app with delegated permissions.

Why this was missing ? This way of connexion does have a meaning or it's a no-sens ?

Best regards.

Body:
I connect to a Azure AD  with Adal4j to let a Native App access MS CRM Web api.

We use this method to get the token:

AuthenticationContext : public Future<AuthenticationResult> acquireToken(
    final String resource, final String clientId,
    final String username, final String password,
    final AuthenticationCallback callback)

Now I wan to use the same code for a web application. So I have registered a Web app in Azure AD with 'Delegate Permissions' and 'Access CRM Online as organization uses' checked.

I first tried with any change and I have received this error :

{"error_description":"AADSTS70002: The request body must contain the following parameter: 'client_secret or client_assertion'.\r\nTrace ID: xxxxxxxxxxxxxxxxxxxx\r\nCorrelation ID: xxxxxxxxxxxxx\r\nTimestamp: 2017-12-01 14:18:03Z","error":"invalid_client"}

Just to test, I have updated ClientAuthenticationPost.toParameters() method to force the client_secret, and it works:

Map<String, String> toParameters() {

    Map<String, String> params = new HashMap<String, String>();

    params.put("client_id", getClientID().getValue());
    params.put("client_secret", "___my_client_secret___"); // added line

    return params;
}

My question is, why there is no such a method 'clientCredential + Login/password' :

AuthenticationContext : public Future<AuthenticationResult> acquireToken(
    final String resource, final ClientCredential clientCredential, // ClientCredential = client_id + client_secret
    final String username, final String password,
    final AuthenticationCallback callback)

Should it be added ? Or the way I authenticate is wrong ?

Best regards.

Body:
Here is the helper method I have added AuthenticationContext Class:

public Future<AuthenticationResult> acquireToken(final String resource,
                                                 final ClientCredential clientCredential, final String username,
                                                 final String password, final AuthenticationCallback callback) {
    if (StringHelper.isBlank(resource)) {
        throw new IllegalArgumentException("resource is null or empty");
    }

    if (clientCredential == null) {
        throw new IllegalArgumentException("client credential is null");
    }

    if (StringHelper.isBlank(username)) {
        throw new IllegalArgumentException("username is null or empty");
    }

    if (StringHelper.isBlank(password)) {
        throw new IllegalArgumentException("password is null or empty");
    }

    final ClientAuthentication clientAuth = new ClientSecretPost(
            new ClientID(clientCredential.getClientId()), new Secret(
            clientCredential.getClientSecret()));

    return this.acquireToken(new AdalAuthorizatonGrant(
                    new ResourceOwnerPasswordCredentialsGrant(username, new Secret(
                            password)), resource), clientAuth, callback);
}

It works fine for my registered Web app with delegated permissions.

Why this was missing ? This way of connexion does have a meaning or it's a no-sens ?

Best regards.


问:
Why need to assign constructor back to my custom error type in JavaScript
I am learning "Error Handling in JavaScript" and read articles on site point. In the articles, it shows the way to make custom error type:

```<code>function DivisionByZeroError(message) {
  this.name = "DivisionByZeroError";
  this.message = (message || "");
}

DivisionByZeroError.prototype = new Error();
DivisionByZeroError.prototype.constructor = DivisionByZeroError;
</code>```

However, I can not understand why the function constructor has to assign to itself again. That is,

```<code>DivisionByZeroError.prototype.constructor = DivisionByZeroError;
</code>```

I think this is because DivisionByZeroError.prototype assigned to new Error() so the prototype was changed.

But I am not sure why even after commenting out that line. The code still works fine.

Demo code is put on jsfiddle

Reference:

Exceptional Exception Handling in JavaScript

A Guide to Proper Error Handling in JavaScript

答:
The reason behind this, is that if you run the following code:

```<code>console.log(new Error().constructor)
</code>```

it outputs:

```<code>"ƒ Error() { [native code] }"
</code>```

Now, by standard, if you create a class, then the following should be true:

```<code>console.log(new MyClassName().constructor === MyClassName)
</code>```

for example, the following is true:

```<code>(new Error().constructor) === Error; // true
</code>```

A use for this could be like so:

```<code>function isArray(maybeArray) {
  return maybeArray.constructor === Array;
}
isArray([]); // true
isArray(new Array(10)); // true
isArray(false); // false

// or say this function
function makeAnotherOfObjectWithoutParameters(object) {
    return new object.constructor();
}
(makeAnotherOfObjectWithoutParameters([])); // empty array
</code>```

So now say you want to see if an object is a DivisionByZeroError. You have your function like so:

```<code>function DivisionByZeroError(message) {
  this.name = "DivisionByZeroError";
  this.message = (message || "");
}

DivisionByZeroError.prototype = new Error();
</code>```

now, you should expect the following to be true:

```<code>console.log(new DivisionByZeroError('my message').constructor === DivisionByZeroError);
</code>```

but you would be surprised that it is false, so now you have to explicitly set the constructor like so:

```<code>DivisionByZeroError.prototype.constructor = DivisionByZeroError
</code>```

and now the above code will work!

Hope this helped someone... I learnt something too!

Body:
I am learning "Error Handling in JavaScript" and read articles on site point. In the articles, it shows the way to make custom error type:

function DivisionByZeroError(message) {
  this.name = "DivisionByZeroError";
  this.message = (message || "");
}

DivisionByZeroError.prototype = new Error();
DivisionByZeroError.prototype.constructor = DivisionByZeroError;

However, I can not understand why the function constructor has to assign to itself again. That is,

DivisionByZeroError.prototype.constructor = DivisionByZeroError;

I think this is because DivisionByZeroError.prototype assigned to new Error() so the prototype was changed.

But I am not sure why even after commenting out that line. The code still works fine.

Demo code is put on jsfiddle

Reference:

Exceptional Exception Handling in JavaScript

A Guide to Proper Error Handling in JavaScript

Body:
The reason behind this, is that if you run the following code:

console.log(new Error().constructor)

it outputs:

"ƒ Error() { [native code] }"

Now, by standard, if you create a class, then the following should be true:

console.log(new MyClassName().constructor === MyClassName)

for example, the following is true:

(new Error().constructor) === Error; // true

A use for this could be like so:

function isArray(maybeArray) {
  return maybeArray.constructor === Array;
}
isArray([]); // true
isArray(new Array(10)); // true
isArray(false); // false

// or say this function
function makeAnotherOfObjectWithoutParameters(object) {
    return new object.constructor();
}
(makeAnotherOfObjectWithoutParameters([])); // empty array

So now say you want to see if an object is a DivisionByZeroError. You have your function like so:

function DivisionByZeroError(message) {
  this.name = "DivisionByZeroError";
  this.message = (message || "");
}

DivisionByZeroError.prototype = new Error();

now, you should expect the following to be true:

console.log(new DivisionByZeroError('my message').constructor === DivisionByZeroError);

but you would be surprised that it is false, so now you have to explicitly set the constructor like so:

DivisionByZeroError.prototype.constructor = DivisionByZeroError

and now the above code will work!

Hope this helped someone... I learnt something too!


问:
Sorting rectangular contours opencv

  i have a picture of words , each word is bounded by a rectangular contour. i need the rectangular contour vector to be sorted so i can do some operation on it.

Here is the picture of words(with contours).
image with contours

i have tried to sort it and my compare function is

```<code>bool my_compare(Rect2d rect1, Rect2d rect2)
{  if(((rect1.tl().y) <= rect2.tl().y) &&(rect1.tl().y < rect2.br().y))
     return (rect1.tl().x < rect2.tl().x);
  return (rect1.tl().y < rect2.tl().y);
}
</code>```

also i tried this

```<code> if((rect1.tl().y == rect2.tl().y))
   return (rect1.tl().x < rect2.tl().x);
   return (rect1.tl().y < rect2.tl().y);
</code>```

the result is not sorted properly (it doesnt start from very top left or it starts but it skips a contour in the same line ).

答:
The reason is probably because rectangles in the same row has different height. Let's say a rectangle is followed by a taller rectangle in the same row, the taller rectangle is going to be sorted earlier than the left one.

```<code>+--------------> x
|          ****
| ****     *  *
| *  *     *  *
| ****     ****
| rect1    rect2
v
y
</code>```

Using your first compare function, rect1.tl().y <= rect2.tl().y is false and rect1.tl().y < rect2.br().y) is true, thus return (rect1.tl().y < rect2.tl().y) which will put the right rectangle smaller than the left one

One suggestion to overcome this is if the rectangles top left corner difference in y is within a threshold, consider them to be on the same row and compare by x instead.

```<code>bool my_compare(Rect2d rect1, Rect2d rect2)
{
    if (fabs(rect1.tl().y - rect2.tl().y) < threshold)
        return (rect1.tl().x < rect2.tl().x);
    return (rect1.tl().y < rect2.tl().y);
}
</code>```

fabs is the floating point absolute function under <cmath>. One way to calculate threshold is by using average height of the rectangle.

```<code>threshold = ((rect1.br().y - rect1.tl().y) + (rect2.br().y - rect2.tl().y)) / 2 * K;
</code>```

K is a constant which you can experiment to see which perform best, it should be between 0 and 1.

Title: Sorting rectangular contours opencv

Body:
  i have a picture of words , each word is bounded by a rectangular contour. i need the rectangular contour vector to be sorted so i can do some operation on it.

Here is the picture of words(with contours).
image with contours

i have tried to sort it and my compare function is

bool my_compare(Rect2d rect1, Rect2d rect2)
{  if(((rect1.tl().y) <= rect2.tl().y) &&(rect1.tl().y < rect2.br().y))
     return (rect1.tl().x < rect2.tl().x);
  return (rect1.tl().y < rect2.tl().y);
}

also i tried this

 if((rect1.tl().y == rect2.tl().y))
   return (rect1.tl().x < rect2.tl().x);
   return (rect1.tl().y < rect2.tl().y);

the result is not sorted properly (it doesnt start from very top left or it starts but it skips a contour in the same line ).

Body:
The reason is probably because rectangles in the same row has different height. Let's say a rectangle is followed by a taller rectangle in the same row, the taller rectangle is going to be sorted earlier than the left one.

+--------------> x
|          ****
| ****     *  *
| *  *     *  *
| ****     ****
| rect1    rect2
v
y

Using your first compare function, rect1.tl().y <= rect2.tl().y is false and rect1.tl().y < rect2.br().y) is true, thus return (rect1.tl().y < rect2.tl().y) which will put the right rectangle smaller than the left one

One suggestion to overcome this is if the rectangles top left corner difference in y is within a threshold, consider them to be on the same row and compare by x instead.

bool my_compare(Rect2d rect1, Rect2d rect2)
{
    if (fabs(rect1.tl().y - rect2.tl().y) < threshold)
        return (rect1.tl().x < rect2.tl().x);
    return (rect1.tl().y < rect2.tl().y);
}

fabs is the floating point absolute function under <cmath>. One way to calculate threshold is by using average height of the rectangle.

threshold = ((rect1.br().y - rect1.tl().y) + (rect2.br().y - rect2.tl().y)) / 2 * K;

K is a constant which you can experiment to see which perform best, it should be between 0 and 1.


问:
want to call controller method from class and get controller context without making request to controller?
I want to call a controller method from a class and get the controller context without making requests to the controller. What are possible ways of doing that?

I can call method by creating an object of a controller class but I am unable to get controller's context.

```<code>var controllerObj = new HomeController()
controllerObj.methodA();
</code>```

and in methodA request context is not available.

答:
Get the instance of a Controller in a class using DependencyResolver.

```<code>public class Example
{
    public static void CallActionMethod()
    {
        var controller = DependencyResolver.Current.GetService<AboutController>();
        controller.ControllerContext = new ControllerContext(System.Web.HttpContext.Current
        .Request.RequestContext, controller);
        controller.Index();
    }
}
</code>```

Reference

Body:
I want to call a controller method from a class and get the controller context without making requests to the controller. What are possible ways of doing that?

I can call method by creating an object of a controller class but I am unable to get controller's context.

var controllerObj = new HomeController()
controllerObj.methodA();

and in methodA request context is not available.

Body:
Get the instance of a Controller in a class using DependencyResolver.

public class Example
{
    public static void CallActionMethod()
    {
        var controller = DependencyResolver.Current.GetService<AboutController>();
        controller.ControllerContext = new ControllerContext(System.Web.HttpContext.Current
        .Request.RequestContext, controller);
        controller.Index();
    }
}

Reference


问:
`LOAD_FAST` in dis module
In 32.12. dis — Disassembler for Python bytecode — Python 3.6.3 documentation, there's an example saying:

Example: Given the function myfunc():

```<code>def myfunc(alist):
    return len(alist)
</code>```

the following command can be used to display the disassembly of myfunc():

```<code>>>> dis.dis(myfunc)
  2           0 LOAD_GLOBAL              0 (len)
              2 LOAD_FAST                0 (alist)
              4 CALL_FUNCTION            1
              6 RETURN_VALUE
</code>```

I can understand LOAD_GLOBAL CALL_FUNCTION and RETURN_VALUE

What's the meaning of LOAD_FAST

答:
According to the Python dis docs:

LOAD_FAST(var_num)

Pushes a reference to the local co_varnames[var_num] onto the stack.

So, in your case, the LOAD_FAST instruction loads alist to be able to pass it to the global len function:

```<code>return        len          (alist)

RETURN_VALUE  LOAD_GLOBAL  LOAD_FAST
                < CALL_FUNCTION >
</code>```

Title: `LOAD_FAST` in dis module

Body:
In 32.12. dis — Disassembler for Python bytecode — Python 3.6.3 documentation, there's an example saying:

Example: Given the function myfunc():

def myfunc(alist):
    return len(alist)

the following command can be used to display the disassembly of myfunc():

>>> dis.dis(myfunc)
  2           0 LOAD_GLOBAL              0 (len)
              2 LOAD_FAST                0 (alist)
              4 CALL_FUNCTION            1
              6 RETURN_VALUE

I can understand LOAD_GLOBAL CALL_FUNCTION and RETURN_VALUE

What's the meaning of LOAD_FAST

Body:
According to the Python dis docs:

LOAD_FAST(var_num)

Pushes a reference to the local co_varnames[var_num] onto the stack.

So, in your case, the LOAD_FAST instruction loads alist to be able to pass it to the global len function:

return        len          (alist)

RETURN_VALUE  LOAD_GLOBAL  LOAD_FAST
                < CALL_FUNCTION >


答:
"Macro defines" merely indicate how they are specified (with #define directives), while "Macro" is the function or expression that is defined.

There is little difference between them aside from semantics, however.

Title: C++ - Macro defines directive

Body:
At: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

It mentions a directive called "Macro defines". What do we mean when we say "Macro"?

Thanks.