问:
Setting a timer with different values
I currently am using a single timer. This timer is set so every two seconds it will switch to the next case in the case switch. However I now want to be able to set the timer to a different amount of seconds. I would like to have three or four more different values.
I know I can create new timers and then from that get the event handler for each one however I don't want to do that here.
Is there a way that I can set a single timer to different values?
The code I currently have is listed below: </p>

```<code>Clock = new Timer(2000);
           Clock.Elapsed += Clock_Elapsed;
            Clock.Enabled = true;
            Clock.Start();

 private void Clock_Elapsed(object sender, ElapsedEventArgs e)
        {
            switch (CurrentDevice)
            {
                case (Devices.WSS):
                    if (OurWSS.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        OurWSS.UnLoad();
                    }
                    CurrentDevice = Devices.Robot
                    break;
                case (Devices.Robot):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurMachine.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.Machine;
                    break;
                case (Devices.Machine):
                    if (OurMachine.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        //OurComponent.GetCurrentOperation();
                        OurMachine.UnLoad();
                    }
                    CurrentDevice = Devices.RobotOut;
                    break;
                case (Devices.RobotOut):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurWSS.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.WSS;
                    break;
            }
        }
</code>```

答:
You can change timer's interval by using Clock.Interval = 3000. Timer.Interval Property

Also there is no need to call Start() method after Clock.Enabled = true;, if you take a look to Start() implementation, it is just setting Enabled to true.

```<code> /// <devdoc>
 /// <para>Starts the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='true'/>.</para>
 /// </devdoc>
 public void Start() {
     Enabled = true;
 }
</code>```

Source: Timer Start()

Title: Setting a timer with different values

Body:
I currently am using a single timer. This timer is set so every two seconds it will switch to the next case in the case switch. However I now want to be able to set the timer to a different amount of seconds. I would like to have three or four more different values.
I know I can create new timers and then from that get the event handler for each one however I don't want to do that here.
Is there a way that I can set a single timer to different values?
The code I currently have is listed below:

Clock = new Timer(2000);
           Clock.Elapsed += Clock_Elapsed;
            Clock.Enabled = true;
            Clock.Start();

 private void Clock_Elapsed(object sender, ElapsedEventArgs e)
        {
            switch (CurrentDevice)
            {
                case (Devices.WSS):
                    if (OurWSS.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        OurWSS.UnLoad();
                    }
                    CurrentDevice = Devices.Robot
                    break;
                case (Devices.Robot):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurMachine.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.Machine;
                    break;
                case (Devices.Machine):
                    if (OurMachine.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        //OurComponent.GetCurrentOperation();
                        OurMachine.UnLoad();
                    }
                    CurrentDevice = Devices.RobotOut;
                    break;
                case (Devices.RobotOut):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurWSS.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.WSS;
                    break;
            }
        }

Body:
You can change timer's interval by using Clock.Interval = 3000. Timer.Interval Property

Also there is no need to call Start() method after Clock.Enabled = true;, if you take a look to Start() implementation, it is just setting Enabled to true.

 /// <devdoc>
 /// <para>Starts the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='true'/>.</para>
 /// </devdoc>
 public void Start() {
     Enabled = true;
 }

Source: Timer Start()


来源: stackexchange

问:
Available GIS toolkits?
We are considering using ESRI's ArcGIS Engine to write an application with some GIS features. The GIS toolkit features that we are primarily concerned with are:

3D visualization: Blend elevation data with raster or vector data.

Embed GIS functionality within a custom UI / application (QT4 preferred)

Function without an internet connection (local data caching or geodatabase)

Create new features (point, line, polygon) and store them in a geodatabase.

Overlay images over map data and update them frequently.

Good interoperability with C++

Cross-platform: Windows, Mac, and Linux

The initial goals for this project are relatively limited, but will likely be expanded in the future -- doing some image processing that incorporates geospatial data, for example.

In addition to ESRI's ArcGIS Engine, we're also looking at using:

NASA World Wind

GRASS GIS

It appears that Intergraph has a large number of GIS software products, but it's not yet clear whether they sell an equivalent to the ArcGIS Engine toolkit.

Are there other options worth considering? Insights or opinions on the options already mentioned?

答:
In addition to GRASS

Mapnik is a C++ cross-platform mapping toolkit that runs on Windows, Mac, and Linux

Quantum GIS can be customised in Python.

If you'd consider Java, you could use GeoTools or OpenJump

You could check out these lists of open source desktop GIS software: OSGeo and SpatialServer.

ContentLicense: CC BY-SA 2.5

Title: Available GIS toolkits?


问:
Tool for upgrading project to VS2017
There are descriptions on Web how to migrate your projects in VS2015 or earlier to new VS2017 template.

But is there a tool that has already automated that?

答: Yes, there is OpenSource https://github.com/hvanbakel/CsprojToVs2017 that is doing exactly this.</p>

ContentLicense: CC BY-SA 3.0

Title: Tool for upgrading project to VS2017


问:
PrimeFaces GMap Inside div Element Does Not Show Up
I have a GMap inside a div with display:none;.

Inside the div is a PrimeFaces map component.

After clicking on a button, the content of the div element should appear, but only a blank page is showing.

```<code><div class="form-group" id="mapContainer" style="display:none;">
    <p:gmap id="gmap" center="51.30993291552862,9.448113441467285" zoom="15" type="terrain" style="width:100%;height:700px;" widgetVar="gmap" navigationControl="false" />
</div>
</code>```

But outside the div element, the map is built and showing correctly.

How can I solve this problem?

答:
As mentioned in one of comments, google map object is not initialized if mapContainer div is hidden (display: none) during page load...

so you will need to "manually" initialize google map object after you make mapContainer div visible.

Here is fully working code (based on your posted code) that will do what you need:

Add this JavaScript to your page

```<code>    <script>
        function resizeElement(elementId,width,height){
            console.log("Resizing element " + elementId + " W/H="+ width + "/" + height);

            var element = document.getElementById(elementId);

            element.style.width=width+"px";
            element.style.height=height+"px"
        }

        function resizePfGmapInsideWrapperElement(wrapperElementId){
            var wrapperElement=document.getElementById(wrapperElementId);
            var width=wrapperElement.clientWidth-40;
            var height=wrapperElement.clientHeight-60;

            resizeElement("gmap",width,height);
        }

        function resizePfGmapInsideDiv(){
            var gmap = PF('gmap').getMap();
            console.log(gmap);

            resizePfGmapInsideWrapperElement("mapContainer");
        }

        function toggleDivVisibility() {
            var div = document.getElementById("mapContainer");
            if(div.style.display === "block"){
                div.style.display = "none";
            }else{
                div.style.display = "block";
                div.style.width="600px";
                div.style.height="400px";
                initializeGmap();
                resizePfGmapInsideDiv();
            }
        }

        function initializeGmap() {
            var myOptions = {
                zoom: 15,
                center: new google.maps.LatLng(51.30993291552862, 9.448113441467285),
                mapTypeId: google.maps.MapTypeId.TERRAIN
            }
            new google.maps.Map(document.getElementById("gmap"),myOptions);
         }

    </script>
</code>```

and, just  for testing purposes, add a button that will toggle mapContainer div visibility

```<code><p:commandButton value="Show/hide map" onclick="toggleDivVisibility();"/>
</code>```

The crucial JS method is self-explanatory initializeGmap() executed in the moment when you make div visible: it will create "a new map inside of the given HTML container, which is typically a DIV element." as stated in documentation referenced above.

ContentLicense: CC BY-SA 4.0

Body:
I have a GMap inside a div with display:none;.

Inside the div is a PrimeFaces map component.

After clicking on a button, the content of the div element should appear, but only a blank page is showing.

But outside the div element, the map is built and showing correctly.

How can I solve this problem?

Body:
As mentioned in one of comments, google map object is not initialized if mapContainer div is hidden (display: none) during page load...

so you will need to "manually" initialize google map object after you make mapContainer div visible.

Here is fully working code (based on your posted code) that will do what you need:

Add this JavaScript to your page

    <script>
        function resizeElement(elementId,width,height){
            console.log("Resizing element " + elementId + " W/H="+ width + "/" + height);

            var element = document.getElementById(elementId);

            element.style.width=width+"px";
            element.style.height=height+"px"
        }

        function resizePfGmapInsideWrapperElement(wrapperElementId){
            var wrapperElement=document.getElementById(wrapperElementId);
            var width=wrapperElement.clientWidth-40;
            var height=wrapperElement.clientHeight-60;

            resizeElement("gmap",width,height);
        }

        function resizePfGmapInsideDiv(){
            var gmap = PF('gmap').getMap();
            console.log(gmap);

            resizePfGmapInsideWrapperElement("mapContainer");
        }

        function toggleDivVisibility() {
            var div = document.getElementById("mapContainer");
            if(div.style.display === "block"){
                div.style.display = "none";
            }else{
                div.style.display = "block";
                div.style.width="600px";
                div.style.height="400px";
                initializeGmap();
                resizePfGmapInsideDiv();
            }
        }

        function initializeGmap() {
            var myOptions = {
                zoom: 15,
                center: new google.maps.LatLng(51.30993291552862, 9.448113441467285),
                mapTypeId: google.maps.MapTypeId.TERRAIN
            }
            new google.maps.Map(document.getElementById("gmap"),myOptions);
         }

    </script>

and, just  for testing purposes, add a button that will toggle mapContainer div visibility

<p:commandButton value="Show/hide map" onclick="toggleDivVisibility();"/>

The crucial JS method is self-explanatory initializeGmap() executed in the moment when you make div visible: it will create "a new map inside of the given HTML container, which is typically a DIV element." as stated in documentation referenced above.


问:
Location of images for Xamarin Forms projects
I've a Xamarin Forms project - with the 3 projects for UWP, iOS and Android.
Now I want to use images in my Xamarin Pages. As intended by Xamarin I want to use the same code for all three targets ... e.g.:

```<code><Image Source="Assets/appIcon-256.png"/>
</code>```

This works for iOS and UWP - both have a folder "Assets" where I placed the image. Ok, I've to maintain the image twice, but I've the same XAML code for both project.

But for Android, that doesn't seems to work. The image is not displayed in Android, if I put the png in the Assets folder of the Anroid project.

What can I do to use the same location for all images for all the three projects?

答:
Replace your dashes with underscores. Example, ic_launcher_calendar.png

Try also to remove the digits at the end of the name.

Lastly, you can check out the naming conventions of drawable. http://petrnohejl.github.io/Android-Cheatsheet-For-Graphic-Designers/

Let me know if it works.

Body:
I've a Xamarin Forms project - with the 3 projects for UWP, iOS and Android.
Now I want to use images in my Xamarin Pages. As intended by Xamarin I want to use the same code for all three targets ... e.g.:

<Image Source="Assets/appIcon-256.png"/>

This works for iOS and UWP - both have a folder "Assets" where I placed the image. Ok, I've to maintain the image twice, but I've the same XAML code for both project.

But for Android, that doesn't seems to work. The image is not displayed in Android, if I put the png in the Assets folder of the Anroid project.

What can I do to use the same location for all images for all the three projects?


问:
angularjs $boadcast and $on doesn´t work from angular.injector
I´m trying to call a function into a Controller when received a Push Notification, passing for a $broadcast / factory, but the broadcast doesn´t work when calling by the angular.injector, here a peace of my code:

push.js

```<code>window.onNotification = function(data) {
        angular.injector(['ng', 'myApp']).get("laFactory").PushReceived(data.additionalData); // --> work fine
    };
         window.push = PushNotification.init({
             "android": {
                 "senderID": "123456789",
                 "icon": "system",
                 "forceShow": true
             }
         });

         window.push.on('notification', window.onNotification);
</code>```

laFactory.js

```<code>.factory('laFactory', ['$http', '$rootScope', function ($http, $rootScope) {
    var laFactory = {};

    laFactory.PushReceived = function(data) {
       $rootScope.$broadcast('handleNotify', {}); // --> don´t work when called by angular.injector!!! why not?!
    };

    $rootScope.$broadcast('handleNotify', {}); // this work fine

    return laFactory;
}
</code>```

myController.js

```<code>.controller('NotificacoesController', function($scope, $rootScope, laFactory) {
    var handler = $scope.$on('handleNotify', function () {
            alert('broadcast - on');
    });
</code>```

}

答:
Not sure if it is best, but it works:

```<code>angular.element(document).injector().invoke(["laFactory", function(laF) {
  laF.PushReceived({});
}]);
</code>```

http://plnkr.co/edit/uVHZKxUjRErbxt2dR3lw?p=preview

Body:
I´m trying to call a function into a Controller when received a Push Notification, passing for a $broadcast / factory, but the broadcast doesn´t work when calling by the angular.injector, here a peace of my code:

push.js

window.onNotification = function(data) {
        angular.injector(['ng', 'myApp']).get("laFactory").PushReceived(data.additionalData); // --> work fine
    };
         window.push = PushNotification.init({
             "android": {
                 "senderID": "123456789",
                 "icon": "system",
                 "forceShow": true
             }
         });

         window.push.on('notification', window.onNotification);

laFactory.js

.factory('laFactory', ['$http', '$rootScope', function ($http, $rootScope) {
    var laFactory = {};

    laFactory.PushReceived = function(data) {
       $rootScope.$broadcast('handleNotify', {}); // --> don´t work when called by angular.injector!!! why not?!
    };

    $rootScope.$broadcast('handleNotify', {}); // this work fine

    return laFactory;
}

myController.js

.controller('NotificacoesController', function($scope, $rootScope, laFactory) {
    var handler = $scope.$on('handleNotify', function () {
            alert('broadcast - on');
    });

}

Body:
Not sure if it is best, but it works:

angular.element(document).injector().invoke(["laFactory", function(laF) {
  laF.PushReceived({});
}]);

http://plnkr.co/edit/uVHZKxUjRErbxt2dR3lw?p=preview


问:
omitEmptyStrings cannot be worked properly
I'm stuck in the middle.

I'm creating wrapper class for
com.google.common.base.Splitter.

But the method omitEmptyStrings doesn't work properly.

Please, give your awesome guidances to me.

Here is [the caller]

```<code>public class Hoge {
 public static void main(String[] args) {
     Iterable<String> hoge =
         Splitter.on(",")
               .omitEmptyStrings()
               .split("　foo　,,11,bar1　,　quux");

 }
}
</code>```

This is the result:
[　foo　]

[11]

[bar1　]

[　quux]

Below is my Wrapper class.

```<code>public final class Splitter extends Object {

 private static final Splitter splitter = new Splitter();

 private static com.google.common.base.Splitter guavaSplitter;

 private static Object separatorChars = null;

 private static boolean omitEmptyStringsFlg = false;

 private static CharMatcher trimmer = null;

 /**
  * Default Construction
  * This constructor is private to deny access
  *
  */
 private Splitter() {
 }
  /**
   * setting guava Splitter to this class guavaSplitter
   *
   * @param separatorMatcher
   * @return Splitter
   */
  public static Splitter on(final String separator) {

 if (StringUtils.isEmpty(separator)) {
  Splitter.guavaSplitter = null;
 } else {
  Splitter.guavaSplitter
      = com.google.common.base.Splitter.on(separator);

  Splitter.separatorChars = separator;
 }

 return Splitter.splitter;

  }

 /**
  * setting guava Splitter to this class guavaSplitter
  *
  * @return Splitter
  */

 public Splitter omitEmptyStrings() {

  if (null != Splitter.guavaSplitter) {

   if (Splitter.separatorChars instanceof String) {
    if (null != Splitter.trimmer) {
     Splitter.guavaSplitter
         = com.google.common.base.Splitter.on(
       (String)Splitter.separatorChars)
       .omitEmptyStrings()
       .trimResults(Splitter.trimmer);

    } else {
     Splitter.guavaSplitter
         = com.google.common.base.Splitter.on(
       (String)Splitter.separatorChars).omitEmptyStrings();

    }

   }

  }
  Splitter.omitEmptyStringsFlg = true;
     return Splitter.splitter;
 }

  /**
   * Splits the {@link CharSequence} passed in parameter.
   *
   * @param sequence the sequence of characters to split
   * @return an iteration over the segments split from the parameter.
   */
  public Iterable<String> split(final CharSequence sequence) {
 Iterable<String> retList = new List();

    if (null != sequence && null != Splitter.guavaSplitter) {
     retList = Splitter.guavaSplitter.split(sequence);

    }

    return retList;
  }

}

/**
 *
 * Returns an iterator over a set of elements of type String.
 *
 */
class List implements Iterable<String> {

 private java.util.List<String> splittedList
  = new java.util.ArrayList<String>();

 @Override
 public Iterator<String> iterator() {
  return this.splittedList.iterator();
 }
}
</code>```

答: It seems like you wanted trimResults in addition to omitEmptyStrings, didn't you?</p>

Body:
I'm stuck in the middle.

I'm creating wrapper class for
com.google.common.base.Splitter.

But the method omitEmptyStrings doesn't work properly.

Please, give your awesome guidances to me.

Here is [the caller]

public class Hoge {
 public static void main(String[] args) {
     Iterable<String> hoge =
         Splitter.on(",")
               .omitEmptyStrings()
               .split("　foo　,,11,bar1　,　quux");

 }
}

This is the result:
[　foo　]

[11]

[bar1　]

[　quux]

Below is my Wrapper class.

public final class Splitter extends Object {

 private static final Splitter splitter = new Splitter();

 private static com.google.common.base.Splitter guavaSplitter;

 private static Object separatorChars = null;

 private static boolean omitEmptyStringsFlg = false;

 private static CharMatcher trimmer = null;

 /**
  * Default Construction
  * This constructor is private to deny access
  *
  */
 private Splitter() {
 }
  /**
   * setting guava Splitter to this class guavaSplitter
   *
   * @param separatorMatcher
   * @return Splitter
   */
  public static Splitter on(final String separator) {

 if (StringUtils.isEmpty(separator)) {
  Splitter.guavaSplitter = null;
 } else {
  Splitter.guavaSplitter
      = com.google.common.base.Splitter.on(separator);

  Splitter.separatorChars = separator;
 }

 return Splitter.splitter;

  }

 /**
  * setting guava Splitter to this class guavaSplitter
  *
  * @return Splitter
  */

 public Splitter omitEmptyStrings() {

  if (null != Splitter.guavaSplitter) {

   if (Splitter.separatorChars instanceof String) {
    if (null != Splitter.trimmer) {
     Splitter.guavaSplitter
         = com.google.common.base.Splitter.on(
       (String)Splitter.separatorChars)
       .omitEmptyStrings()
       .trimResults(Splitter.trimmer);

    } else {
     Splitter.guavaSplitter
         = com.google.common.base.Splitter.on(
       (String)Splitter.separatorChars).omitEmptyStrings();

    }

   }

  }
  Splitter.omitEmptyStringsFlg = true;
     return Splitter.splitter;
 }

  /**
   * Splits the {@link CharSequence} passed in parameter.
   *
   * @param sequence the sequence of characters to split
   * @return an iteration over the segments split from the parameter.
   */
  public Iterable<String> split(final CharSequence sequence) {
 Iterable<String> retList = new List();

    if (null != sequence && null != Splitter.guavaSplitter) {
     retList = Splitter.guavaSplitter.split(sequence);

    }

    return retList;
  }

}

/**
 *
 * Returns an iterator over a set of elements of type String.
 *
 */
class List implements Iterable<String> {

 private java.util.List<String> splittedList
  = new java.util.ArrayList<String>();

 @Override
 public Iterator<String> iterator() {
  return this.splittedList.iterator();
 }
}


问:
Stream of optional fields return values
I have a few Optional fields with String and Long values:

```<code>Optional<Long> id;
Optional<String> name;
Optional<String> lastname;
Optional<Long> number;
....
</code>```

I would like to return List with contains all of the values. If e.g optional "name" is no present, should be stored empty String. Result of method should be List with values e.q: "1", "John", "", "5".

I made stream:

```<code>Stream fields = Stream.of(id, name, lastname, number);
</code>```

But I have no idea what next.

Regards.

答:
You can use the map method of the stream to manipulate the content of your stream, something like the below code:

```<code>fields.map(field -> field.orElse("").toString());
</code>```

The optional also has a map method that can be used when manipulating the stream:

```<code>fields.map(field -> field.map(x -> x.toString()).orElse(""));
</code>```

Title: Stream of optional fields return values

Body:
I have a few Optional fields with String and Long values:

Optional<Long> id;
Optional<String> name;
Optional<String> lastname;
Optional<Long> number;
....

I would like to return List with contains all of the values. If e.g optional "name" is no present, should be stored empty String. Result of method should be List with values e.q: "1", "John", "", "5".

I made stream:

Stream fields = Stream.of(id, name, lastname, number);

But I have no idea what next.

Regards.

Body:
You can use the map method of the stream to manipulate the content of your stream, something like the below code:

fields.map(field -> field.orElse("").toString());

The optional also has a map method that can be used when manipulating the stream:

fields.map(field -> field.map(x -> x.toString()).orElse(""));


问:
Best Kentico Way to Host Multiple 404 pages in the Content Tree
I'm looking for the best (or a very good) "Kentico way" to accomplish having multiple 404 Not Found pages inside the content tree, each for a different area of the content tree.

For example, given the following hypothetical content tree structure with blog items and partner profiles,

```<code>% Root Master
|__ Home
|__ Blog ._ Blog Item A
         |_ Blog Item B
         |_ Blog Item C
         |_ 404 Page for Blogs
|__ Policy
|__ Partners ._ Partner Profile A
             |_ Partner Profile B
             |_ Partner Profile C
             |_ 404 Page for Partners
|_ Site 404 Page
</code>```

I'm looking for the following behaviour:

if the user visits a Blog Item D which does not exist, I want to 404 Page for Blogs to be displayed.

likewise if the user visits a Partner Profile D which does not exist,I want the 404 Page for Partners to show.

If any other page is Not found in the site then the Site 404 Page should be shown, as per normal, through Kentico setting for this.

I'm hesitant to dip down into only using ASP.NET configuration for this because I want to maintain the solution inside Kentico and without recycling the website's application pool when adding new 404 pages.

My immediate thought is to create a custom web part that I can drop onto the Site's global 404 Page Template (the default place for every 404).  This web part would use the Error Path (ala querystring value aspxerrorpath=) to  see the path that was not found and then check to see if it contains the word "blogs" or "partners" and redirect the browser to the appropriate sub-404-page respectively. Or, is there an even simpler approach -- maybe using page aliases and/or macros -- while keeping the solution inside Kentico?

I'm using Kentico 9 & 10.

答:
I think it is a bit unnatural for web site to have multiple 404. I think what you describing  is the Kentico way. On this one common 404 page you can drop multiple static HTML web parts and make them enable based on ErrorPath, if none of ErrorPath are matched you have a generic static HTML web part to handle common case.
P.S. Technically you can have specific web.config per folder in IIS and try to play around with that, but Kentico Tree is purely virtual, so what you describing is pretty much the Kentico way.</p>

Body:
I'm looking for the best (or a very good) "Kentico way" to accomplish having multiple 404 Not Found pages inside the content tree, each for a different area of the content tree.

For example, given the following hypothetical content tree structure with blog items and partner profiles,

% Root Master
|__ Home
|__ Blog ._ Blog Item A
         |_ Blog Item B
         |_ Blog Item C
         |_ 404 Page for Blogs
|__ Policy
|__ Partners ._ Partner Profile A
             |_ Partner Profile B
             |_ Partner Profile C
             |_ 404 Page for Partners
|_ Site 404 Page

I'm looking for the following behaviour:

if the user visits a Blog Item D which does not exist, I want to 404 Page for Blogs to be displayed.

likewise if the user visits a Partner Profile D which does not exist,I want the 404 Page for Partners to show.

If any other page is Not found in the site then the Site 404 Page should be shown, as per normal, through Kentico setting for this.

I'm hesitant to dip down into only using ASP.NET configuration for this because I want to maintain the solution inside Kentico and without recycling the website's application pool when adding new 404 pages.

My immediate thought is to create a custom web part that I can drop onto the Site's global 404 Page Template (the default place for every 404).  This web part would use the Error Path (ala querystring value aspxerrorpath=) to  see the path that was not found and then check to see if it contains the word "blogs" or "partners" and redirect the browser to the appropriate sub-404-page respectively. Or, is there an even simpler approach -- maybe using page aliases and/or macros -- while keeping the solution inside Kentico?

I'm using Kentico 9 & 10.


问:
Unable to extract a data from Table using inner join on same table
Trying to extract the data from table called TB_Emloyee. There are 4 columns in table with C_ID, Name, Department, Count.

My table has following data

http://sqlfiddle.com/#!9/e74be

I would like to have following output.

```<code>C_ID   NAme    Department  Count
200    Max     IH          2
100    David   PR          1
101    Lex     PR          1
102    Alex    IT          2
103    Slava   IH          1
104    Tunja   PR          2
</code>```

Until now I have tried the following, but I am not able to get the whole data.

http://sqlfiddle.com/#!9/e74be/2/0

I am not an expert with inner query so help me with situation.

Thanks.

答:
Just add Name and department fields like this:

```<code>SELECT
    C_ID, Name, department,
    max(Count) AS max_count
FROM
  Tb_Employee
GROUP BY
  C_ID, Name, department;
</code>```

Provided that Name and department have the same values for the same C_ID.

If you are designing the database schema, you should normalize the tables better.

Body:
Trying to extract the data from table called TB_Emloyee. There are 4 columns in table with C_ID, Name, Department, Count.

My table has following data

http://sqlfiddle.com/#!9/e74be

I would like to have following output.

C_ID   NAme    Department  Count
200    Max     IH          2
100    David   PR          1
101    Lex     PR          1
102    Alex    IT          2
103    Slava   IH          1
104    Tunja   PR          2

Until now I have tried the following, but I am not able to get the whole data.

http://sqlfiddle.com/#!9/e74be/2/0

I am not an expert with inner query so help me with situation.

Thanks.

Body:
Just add Name and department fields like this:

SELECT
    C_ID, Name, department,
    max(Count) AS max_count
FROM
  Tb_Employee
GROUP BY
  C_ID, Name, department;

Provided that Name and department have the same values for the same C_ID.

If you are designing the database schema, you should normalize the tables better.


问:
Synchronous call retrofit 2 and return recyclerview in Alert Dialog
I am having a question as to how can I make a call using retrofit2 to return in my Alertdialog a Recyclerview list?

I tried to use the call retrofit2 with the progress bar, but a returned null pointer exception is still returned.

```<code>public class CtePresenter {

    private ProgressDialog dialog;
    private ServiceOSB service;
    private String authToken;

    public CtePresenter(Context context) {
        this.dialog = new ProgressDialog(context);
        this.dialog.setIndeterminate(true);
        this.service = ServiceOSB.getInstance(Prefs.getAmbiente(context));
        this.authToken = Prefs.getAuthToken(context);
    }

    public void listaCliente(final RequestListener<RetListaCliente> listener) {
        dialog.setMessage("Carregando...");
        dialog.show();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);

        try {
            service.getCteService().listaCliente(authToken).enqueue(new RequestCallback<RetListaCliente>(listener, dialog));
        } catch (Exception e) {
            Log.d(Util.TAG_LOG, e.getMessage());
            listener.onError(e.getMessage());
        }
    }

    searchRemetente.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            final List<RetListaCliente.Cliente> lstCliente = new ArrayList<>();
            CtePresenter ctePresenter = new CtePresenter(getActivity());
            ctePresenter.listaCliente(new RequestListener<RetListaCliente>() {
                @Override
                public void onSuccess(RetListaCliente response) {
                    for (RetListaCliente.Cliente c : response.getClientes()) {
                        lstCliente.add(c);
                    }
                }

                @Override
                public void onError(String error) {

                }

                @Override
                public void onUnauthoried(String error) {

                }
            });
            searchRemetenteDestinatario(v, lstCliente);
        }
    });
}
</code>```

答:
Not clear if you need a synchronous event since it will work if you are using the callbacks correctly.

onSuccess is not guaranteed to run in any order
before  searchRemetenteDestinatario uses that list

You need to move it inside the listener callback method if you want data to be in the list

```<code>@Override
public void onSuccess(RetListaCliente response) {
    lstCliente.clear();
    for (RetListaCliente.Cliente c : response.getClientes()) {
        lstCliente.add(c);
    }
    // searchRemetenteDestinatario
}
</code>```

The nullpointerexception does not appear to be related to a progress dialog, so you'll have to clarify that

Body:
I am having a question as to how can I make a call using retrofit2 to return in my Alertdialog a Recyclerview list?

I tried to use the call retrofit2 with the progress bar, but a returned null pointer exception is still returned.

public class CtePresenter {

    private ProgressDialog dialog;
    private ServiceOSB service;
    private String authToken;

    public CtePresenter(Context context) {
        this.dialog = new ProgressDialog(context);
        this.dialog.setIndeterminate(true);
        this.service = ServiceOSB.getInstance(Prefs.getAmbiente(context));
        this.authToken = Prefs.getAuthToken(context);
    }

    public void listaCliente(final RequestListener<RetListaCliente> listener) {
        dialog.setMessage("Carregando...");
        dialog.show();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);

        try {
            service.getCteService().listaCliente(authToken).enqueue(new RequestCallback<RetListaCliente>(listener, dialog));
        } catch (Exception e) {
            Log.d(Util.TAG_LOG, e.getMessage());
            listener.onError(e.getMessage());
        }
    }

    searchRemetente.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            final List<RetListaCliente.Cliente> lstCliente = new ArrayList<>();
            CtePresenter ctePresenter = new CtePresenter(getActivity());
            ctePresenter.listaCliente(new RequestListener<RetListaCliente>() {
                @Override
                public void onSuccess(RetListaCliente response) {
                    for (RetListaCliente.Cliente c : response.getClientes()) {
                        lstCliente.add(c);
                    }
                }

                @Override
                public void onError(String error) {

                }

                @Override
                public void onUnauthoried(String error) {

                }
            });
            searchRemetenteDestinatario(v, lstCliente);
        }
    });
}

Body:
Not clear if you need a synchronous event since it will work if you are using the callbacks correctly.

onSuccess is not guaranteed to run in any order
before  searchRemetenteDestinatario uses that list

You need to move it inside the listener callback method if you want data to be in the list

@Override
public void onSuccess(RetListaCliente response) {
    lstCliente.clear();
    for (RetListaCliente.Cliente c : response.getClientes()) {
        lstCliente.add(c);
    }
    // searchRemetenteDestinatario
}

The nullpointerexception does not appear to be related to a progress dialog, so you'll have to clarify that


问:
ionic Native + geofance + iOS ERROR : "Location always permissions not granted"
please help me out from this error.

ionic Native + geofance + iOS

I am dealing with geofence with ionic native, with Android Geofence working fine, but iOS give me error error : "Location always permissions not granted".

=========================================

this.geofence.initialize().then(data => {

```<code>      console.log('Geofence Plugin Ready');
         let fence = {
            id              : '69ca1b88-6fbe-4e80-a4d4-ff4d3748acdb', //any unique ID
            latitude        : 21.08328129405459, //
            longitude       : 72.88010023534298, //
            radius          : 30,
            transitionType  : 3,
            notification    : { //notification settings
                                id              :  11212,//
                                title           : 'Insta Place',
                                text            : 'You are Near the Location.',
                                icon            : 'file://icon.png',
                                openAppOnClick  : true
                            }
          }
          // alert(JSON.stringify(fence));

          this.geofence.addOrUpdate(fence).then(
             (data) => console.log('Geofence added'),
             (err) => alert('Geofence failed to add Please Turn On your device location and try again.'+ err)
           );
        },err => {
           alert('Geofence Plugin Not Ready' + JSON.stringify(err));
        })
</code>```

============================

thanks.

答:
for me the solution is the following privacy put in your .plist file.

NSLocationAlwaysAndWhenInUseUsageDescription
    This app requires constant access to your location in order to track your position, even when the screen is off or the app is in the background.

thanks.

Body:
please help me out from this error.

ionic Native + geofance + iOS

I am dealing with geofence with ionic native, with Android Geofence working fine, but iOS give me error error : "Location always permissions not granted".

=========================================

this.geofence.initialize().then(data => {

      console.log('Geofence Plugin Ready');
         let fence = {
            id              : '69ca1b88-6fbe-4e80-a4d4-ff4d3748acdb', //any unique ID
            latitude        : 21.08328129405459, //
            longitude       : 72.88010023534298, //
            radius          : 30,
            transitionType  : 3,
            notification    : { //notification settings
                                id              :  11212,//
                                title           : 'Insta Place',
                                text            : 'You are Near the Location.',
                                icon            : 'file://icon.png',
                                openAppOnClick  : true
                            }
          }
          // alert(JSON.stringify(fence));

          this.geofence.addOrUpdate(fence).then(
             (data) => console.log('Geofence added'),
             (err) => alert('Geofence failed to add Please Turn On your device location and try again.'+ err)
           );
        },err => {
           alert('Geofence Plugin Not Ready' + JSON.stringify(err));
        })

============================

thanks.


问:
How do I validate that a certificate was created by a particular certification authority?
I have a Windows certification authority that I am using to issue client authentication certificates via .net / c#. I have been able to successfully get it to issue certificates programmatically by calling the certification authority's API through COM. I issue a new certificate when I set up a client.

At runtime, these clients attach the certificates to requests to my server. How can I verify programmatically that an X509Certificate2 was signed by the root certificate of my certificate authority (and reject certificates signed by any other source)?

答:
You can also use the built in method Verify() for X509Certificate2.

```<code>X509Certificate2 certificateToValidate = GetCertificateToValidate();
bool valid = certificateToValidate.Verify()
</code>```

https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.verify.aspx

Body:
You can also use the built in method Verify() for X509Certificate2.

X509Certificate2 certificateToValidate = GetCertificateToValidate();
bool valid = certificateToValidate.Verify()

https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.verify.aspx


问:
How to pass url value in django to views
My url.py is as below,

```<code>from myapp import views
urlpatterns = [
   url(r'^myapp/get_requests/$', views.get_requests),
]
</code>```

Now my views.py is as below,

```<code>@api_view(['GET'])
def get_request(request):
   #How can I get request ID (base url here)?
   return HttpResponse('test')
</code>```

In the above if I do request in my browser with url as below it reaches my get_request method,

```<code>http://localhost:8080/myapp/get_requests/
</code>```

But the same gives error 404 when I try with some ID in the end as below,

```<code>http://localhost:8080/myapp/get_requests/40
</code>```

Now How can I get this ID number 40 in my views.py method?

答:
Change your urls.py to

```<code>from myapp import views
urlpatterns = [
       url(r'^myapp/get_requests/(?P<id>[0-9]+)$', views.get_requests),
]
</code>```

Now get the id parameter in your views like this

```<code>@api_view(['GET'])
def get_request(request,id):
    print id
    return HttpResponse('test')
</code>```

For more information check out django docs

Body:
My url.py is as below,

from myapp import views
urlpatterns = [
   url(r'^myapp/get_requests/$', views.get_requests),
]

Now my views.py is as below,

@api_view(['GET'])
def get_request(request):
   #How can I get request ID (base url here)?
   return HttpResponse('test')

In the above if I do request in my browser with url as below it reaches my get_request method,

http://localhost:8080/myapp/get_requests/

But the same gives error 404 when I try with some ID in the end as below,

http://localhost:8080/myapp/get_requests/40

Now How can I get this ID number 40 in my views.py method?

Body:
Change your urls.py to

from myapp import views
urlpatterns = [
       url(r'^myapp/get_requests/(?P<id>[0-9]+)$', views.get_requests),
]

Now get the id parameter in your views like this

@api_view(['GET'])
def get_request(request,id):
    print id
    return HttpResponse('test')

For more information check out django docs


问:
Origins of the most popular file serving pattern in web
Most modern file upload/sharing services, apart from having lots of ads and constantly offering you to buy a subscription, also share the same design pattern: when you are ready to download a file they typically write something like "Your download should start automatically in 5 seconds. Click here to download manually."

What rationale stands behind this behavior? Where did it come from? Why don't they just send a redirect or open a temporary link in another window (via target="_blank")? TIA

答: I'd say it's because it's become what people expect. Often a direct link to a file will leave the user with a blank window while their file downloads (depending on the browser, I haven't checked but I'm pretty sure this behaviour was common with browsers 5 years ago), so avoiding this is good. I'd wager that most internet users would be confused if they clicked a download link and were presented with a blank page (and a dialog somewhere, possible hidden, downloading the file). Since this has become commonplace, it's now what users expect, so doing it another way would make it more confusing for most users, even if it does make more sense!</p>


问:
Location of drools-spring.xsd on git hub (or reliable source)
My project depends on drools 5.6.0.Final version. As part of that I'm trying to find a uri that I can rely for the drools-spring.xsd file. I'm trying to locate a reliable URI for that file I can reference, so that eclipses doesn't show issues, and so that spring can also intercept the requests and replace with the files in the jar as it sees fit.

I can drill into drools-spring-5.6.0.Final.jar in eclipse and see the xsd files in org.drools.container.spring. I also can see the xsd file here: http://grepcode.com/file_/repository.jboss.org/nexus/content/repositories/releases/org.drools/drools-spring/5.6.0.Final/org/drools/container/spring/drools-spring.xsd/?v=source

Going to drools.org and following their link to github and follow the rename of their group shown in the README file to https://github.com/kiegroup. I've searched this group for the xsd file(s) but have had no luck. e.g. https://github.com/kiegroup/droolsjbpm-integration/find/5.6.0.Final and https://github.com/kiegroup/drools/find/5.6.0.Final

This makes me think that the xsd files
are generated? Can someone confirm this and if so, is there a reliable URI that I can reference for this?

答:
The drools-spring.xsd file location on drools website will give you a 404 error. You can have below two approaches which i could find while searching on the net.

One : Host the file on your local machine

Two : Place the .xsd file in the same directory as the location of the xml file referencing it.

Please refer to the below information . This will give a better understanding of the two methods mentioned above.


问:
Connection between programs over the network
I want to dive into the whole diversity of tools which provide connection between programs over the network.

To clarify the question, I divide it on subquestions:

Why some groups of programs (or specific tools/frameworks/approaches with programming languages where this frameworks can be used) were popular in each period of time? (I expect description of problems which were solved, description of tools, why those tools are considered as best solution to those problems at that time, why some tools lost popularity)

What is the entire history of software communication over the network? (tools/approaches popularity precisely to decades)

What are the modern solutions to this problem?

I can distinguish only two significant approaches.

RPC, RMI and their implementations (I saw this, but it is about concrete problem and specific tools to solve this problem, I want to see the place of this problem in the whole picture of interconnection programs over the network. I heard about implementations: ONC RPC, XML-RPC, CORBA, DCOM, gRPC, but which are active now? which are reasonable to use? which are preferable and why? I want answers not to be opinion based, so I accept answers like "technology A better than technology B for problem X because ..." only if there is reliable research/statistics or facts). I heard that RPC and RMI were popular 10 years ago. Are they still?

Web services: REST, SOAP.

Am I miss something? Maybe there are some technologies which solve problem completely new way? Maybe there are technologies which can be treated as replacement to RPC(RMI) and Web Services? Can we replace RPC(RMI) by REST for any task? Can we replace RPC(RMI) by REST only for modern tasks? Should I separate technologies not as RPC and Web Services, but in some other manner?

答:
To your question „Am I missing something“: yes.

Very popular communication patterns are the so-called Event-Driven or Message-Driven protocols. This type of protocols are often used in distributed systems such web applications, microservices and IoT-Environments. The communication is complete asynchronously and allows building scalable and loosely coupled systems.

There are many different frameworks and methods for Event-Driven systems like WebSockets, WebHooks, Pub-Sub and Messaging-Librarys like AcitveMQ, OpenMQ, RabbitMQ, ZeroMQ and MQTT.

Hope this info helps for your research.


问:
Add UIView to ContentView in a TableViewCell using constraints
I am trying to add cells to UITableView using Constraints. Do you know how. The following just gives:

And says: Height is ambiguous for UIView

Do you know how to add a UIView to ContextView using constraints - note the fixed height in the constraints.

```<code>import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintHeight = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.height,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: nil,
                                                  attribute: NSLayoutAttribute.height,
                                                  multiplier: 1, constant: 50) // << Note fixed height

        view.translatesAutoresizingMaskIntoConstraints = false

        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintHeight])

        return cell!
    }

}
</code>```

Tried to change constraints to include bottom of the contentView:

```<code>import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintBottom = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: view,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  multiplier: 1, constant: 0)

        view.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintBottom])

        return cell!
    }

}
</code>```

答:
Your fourth constraint is applying a fixed height to the contentView. What you want instead is to pin the bottom edges of the contentView and your custom view (like you did with leading/top/trailing) and apply the constant height constraint to view, not contentView. contentView simply adapts to its subviews, you don't tell it its height directly.

Additionally, in your viewDidLoad, you'll want to set your tableView.rowHeight = UITableViewAutomaticDimension, since you're calculating the height via constraints.

Also, you will run into problems because this code is in cellForRow. This function is called every time a new cell comes onscreen, which means as you scroll, you're going to reuse the same views and have duplicate extra views added. I recommend you subclass UITableViewCell and put this code in its init.

Body:
I am trying to add cells to UITableView using Constraints. Do you know how. The following just gives:

And says: Height is ambiguous for UIView

Do you know how to add a UIView to ContextView using constraints - note the fixed height in the constraints.

import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintHeight = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.height,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: nil,
                                                  attribute: NSLayoutAttribute.height,
                                                  multiplier: 1, constant: 50) // << Note fixed height

        view.translatesAutoresizingMaskIntoConstraints = false

        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintHeight])

        return cell!
    }

}

Tried to change constraints to include bottom of the contentView:

import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintBottom = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: view,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  multiplier: 1, constant: 0)

        view.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintBottom])

        return cell!
    }

}


问:
Page breaks for images in Python fpdf
I want to insert some lengthy images (each image can extend to 2 pages) using python fpdf. But the images don't continue to next page once a page break is triggered. How can I print the rest of the images into the next page starting from a given set_y value (header included)?</p>

答:
If your pdf-dataset is a data string you can start searching for the "\r" and/or (multiple) '\n' character(s) using the below code:

```<code>chrs = ['\r', '\n', '\n\n']

for item in chars:
     pdf-data.replace(item)
</code>```

In case its formatted strings in a list:

```<code>list = pdaf-data

for list-item in list:
    for list-item in chars:
         pdf-data.replace(item)
</code>```

In case you read directly from a file use "open file, etc" and readline().

Title: Page breaks for images in Python fpdf

Body:
If your pdf-dataset is a data string you can start searching for the "\r" and/or (multiple) '\n' character(s) using the below code:

chrs = ['\r', '\n', '\n\n']

for item in chars:
     pdf-data.replace(item)

In case its formatted strings in a list:

list = pdaf-data

for list-item in list:
    for list-item in chars:
         pdf-data.replace(item)

In case you read directly from a file use "open file, etc" and readline().


问:
Select2 adds an empty span that I can't remove
I have a multiple select defined in this way:

```<code><select class="form-control" name="citiesNotValid">
</code>```

If I initialize it as select2 it duplicates the select elements, one working and filled with my preselected option, and the other empty and not working.
This is the inizialization of the select2:

```<code>    $(s).select2({
    language: "it",
    placeholder: {
        id: '-1', // the value of the option
        text: 'All'
    },
    width: '100%',
    //multiple: true,
    allowClear: true,
    ajax: {
        delay: 500,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: o,
        dataType: "json",
        cache: 1,
        data: function (params) {
            var query = JSON.stringify({
                country_code: country,
                search: params.term
            })

            return query;
        },
        processResults: function (t) {
            return {
                results: $.map(JSON.parse(t.d), function (obj) {
                    if (obj.city_name == "-") {
                        return { id: "-1", text: "Tutte" };
                    }
                    return { id: obj.city_name, text: obj.city_name };

                })
            };
        },
        error: function (t, o, i) {
            var n = "Si è verificato un errore. Controlla di aver passato correttamente tutti i parametri.";
            //if (t.statusText != null && t.statusText != "")
            // n = t.statusText;
            "toastr" == a && toastr ? toastr.error(n) : "notific8" == a && $.notific8 ? ($.notific8("zindex", 11500), $.notific8(n, {
                theme: "ruby",
                life: 3e3
            })) : console.log(n)
        }
    },
    minimumInputLength: 2,
});
</code>```

}

When I run the code in this way, it  creates a second  element, I can see it in my Chrome console, but if I try to delete it in my jQuery code I can't find it, like it doesn't exist.

Another thing that I noted is that if I add to my select the select2 class, it creates only one select, but Ajax isn't triggered.

答: Are you using an empty option as first element of you html select? If so, try removing it.

Body:
I have a multiple select defined in this way:

<select class="form-control" name="citiesNotValid">

If I initialize it as select2 it duplicates the select elements, one working and filled with my preselected option, and the other empty and not working.
This is the inizialization of the select2:

    $(s).select2({
    language: "it",
    placeholder: {
        id: '-1', // the value of the option
        text: 'All'
    },
    width: '100%',
    //multiple: true,
    allowClear: true,
    ajax: {
        delay: 500,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: o,
        dataType: "json",
        cache: 1,
        data: function (params) {
            var query = JSON.stringify({
                country_code: country,
                search: params.term
            })

            return query;
        },
        processResults: function (t) {
            return {
                results: $.map(JSON.parse(t.d), function (obj) {
                    if (obj.city_name == "-") {
                        return { id: "-1", text: "Tutte" };
                    }
                    return { id: obj.city_name, text: obj.city_name };

                })
            };
        },
        error: function (t, o, i) {
            var n = "Si è verificato un errore. Controlla di aver passato correttamente tutti i parametri.";
            //if (t.statusText != null && t.statusText != "")
            // n = t.statusText;
            "toastr" == a && toastr ? toastr.error(n) : "notific8" == a && $.notific8 ? ($.notific8("zindex", 11500), $.notific8(n, {
                theme: "ruby",
                life: 3e3
            })) : console.log(n)
        }
    },
    minimumInputLength: 2,
});

}

When I run the code in this way, it  creates a second  element, I can see it in my Chrome console, but if I try to delete it in my jQuery code I can't find it, like it doesn't exist.

Another thing that I noted is that if I add to my select the select2 class, it creates only one select, but Ajax isn't triggered.


问:
Octlet, quad word or what?
I am translating some documentation on libraw1394 to Russian. The documentation on libraw1394 says:

The basic data structures defined in
  the standard and used in this document
  are the quadlet (32 bit quantity) and
  the octlet (64 bit quantity)...

There is no such unit like "octlet" in Russian. I used to use "quad word" (russian "chetvertnoye slovo") for 64 bit quantity. Would it be correct to substitute "octlet" by "quad word"?

What are the alternative terms for "octlet"?

答:
octlet == 8-byte   [8-байт ?]

I wouldn't use "WORD" because a word can vary. It could be 1 byte, 2 bytes, 4 bytes...  a Byte is always 8 bits.

Title: Octlet, quad word or what?


问:
Error Home page is opened without login using mvc?
When i run my project it goes to login page working fine

```<code>public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
            );
        }
    }
</code>```

When i entered username and password is login properly

```<code>//[Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        public ActionResult Index()
        {
            return View();
        }

#region Login
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Login login)
        {
            if (ModelState.IsValid)
            {
                bool success = WebSecurity.Login(login.UserName, login.Password, false);
                var UserID = GetUserID_By_UserName(login.UserName);

                if (success == true)
                {
                    Session["Name"] = login.UserName;
                    Session["UserID"] = UserID;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("Error", "Please enter valid Username and Password");
                    return View(login);
                }

            }
            return View(login);
        }
        #endregion

}
</code>```

once i logout and clear the session and When i entered URL bar localhost:51426/Home/index to the home page that home page opened directly without login.So home page should n't open without login process.

答:
Change the Index method so that Anonymous user can not able to access the page by adding Authorize attribute.</p>

```<code>// GET: /Account/
[Authorize]
public ActionResult Index()
{
   return View();
}
</code>```

Body:
When i run my project it goes to login page working fine

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
            );
        }
    }

When i entered username and password is login properly

//[Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        public ActionResult Index()
        {
            return View();
        }

#region Login
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Login login)
        {
            if (ModelState.IsValid)
            {
                bool success = WebSecurity.Login(login.UserName, login.Password, false);
                var UserID = GetUserID_By_UserName(login.UserName);

                if (success == true)
                {
                    Session["Name"] = login.UserName;
                    Session["UserID"] = UserID;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("Error", "Please enter valid Username and Password");
                    return View(login);
                }

            }
            return View(login);
        }
        #endregion

}

once i logout and clear the session and When i entered URL bar localhost:51426/Home/index to the home page that home page opened directly without login.So home page should n't open without login process.

Body:
Change the Index method so that Anonymous user can not able to access the page by adding Authorize attribute.

// GET: /Account/
[Authorize]
public ActionResult Index()
{
   return View();
}


问:
WebSocket Server (Java) cannot read but send to C# (Unity) Client
For a project in university we should build a multiplayer game. Cause I have quiet a lot experience in Unity I want to use it as Game Engine. We have to use WebSockets for communication and json as protocoll to carry the data.

So far so good. C# don´t have a default websocket implementation, so I use a library called websocket-sharp for that (https://github.com/sta/websocket-sharp).

My Code on client (Unity) side is as followed:

```<code>    public class EchoTest : MonoBehaviour {

    public GameObject master;
    public string serveradress = "ws://";

    private WebSocket w = null;

    // Use this for initialization
    IEnumerator Start () {
        w = new WebSocket(new Uri(serveradress));
        yield return StartCoroutine(w.Connect());

        w.SendString ("Hello World from client");
        //w.SendString("Hi there");
        int i=0;
        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                master.GetComponent<Networker> ().onNetworkMessage (reply);
                //Debug.Log ("Received: "+reply);
                //w.SendString("Hi there"+reply);
            }
            if (w.error != null)
            {
                Debug.LogError ("Error: "+w.error);
                break;
            }
            w.SendString("helloworld");
            yield return 0;
        }
        w.Close();
    }

    public void sendString(string message){
        sendRaw(Encoding.UTF8.GetBytes (message));
    }

    public void sendRaw(byte[] send){
        w.Send (send);
    }
}
</code>```

I tried my implementation with an online service that hosts an echo server (http://demos.kaazing.com/echo/) , everything works fine.

I wrote a basic echo server in Java and checked the server with a browser plugin (https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo) and the echo server website from above. Both working like a charm.

Code from Java Server (running in Tomcat 9):

```<code>@ServerEndpoint(value = "/echo")
public class WSEchoS {

    private static final Logger LOGGER =
            Logger.getLogger(WSEchoS.class.getName());

    @OnOpen
    public void onOpen(Session session) {
        LOGGER.log(Level.INFO, "New connection with client: {0}",
                session.getId());
        try {
            session.getBasicRemote().sendText("Hello new Client x");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        LOGGER.log(Level.INFO, "New message from Client [{0}]: {1}",
                new Object[]{session.getId(), message});
        try {
            session.getBasicRemote().sendText("This is from the server " + message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Server received [" + message + "]";
    }

    @OnClose
    public void onClose(Session session) {
        LOGGER.log(Level.INFO, "Close connection for client: {0}",
                session.getId());
    }

    @OnError
    public void onError(Throwable exception, Session session) {
        LOGGER.log(Level.INFO, "Error for client: {0}", session.getId());
    }
}
</code>```

Nooooowwwww the problem:

The Unity client cannot send data to the server!
He can connect properly and can read messages from the Server, but he cannot send him (trigger onmesssage). I searched the whole day without success.

The client is working great with online services, the server as well, but both of them together don´t work. Can anyone explain that? I would love you for that <3

Greetings Pascal

答:
A day later I found the problem.

Websockets have the ability to handle string, byte[] and some more formats.

I sended my data like this:

```<code>public void SendString(string str)
{
    Send (Encoding.UTF8.GetBytes (str));
}
</code>```

And used the underlying Send(byte[]) method. So when I change the @OnMessage method in Java to

```<code>@OnMessage
public void processUpload(byte[] bytes, boolean last, Session session) {
</code>```

everything works fine, and also the other way around I can send a string and my server is also getting my messages :)

Maybe for some people it´s usefull to know

Greetings Pascal

Body:
For a project in university we should build a multiplayer game. Cause I have quiet a lot experience in Unity I want to use it as Game Engine. We have to use WebSockets for communication and json as protocoll to carry the data.

So far so good. C# don´t have a default websocket implementation, so I use a library called websocket-sharp for that (https://github.com/sta/websocket-sharp).

My Code on client (Unity) side is as followed:

    public class EchoTest : MonoBehaviour {

    public GameObject master;
    public string serveradress = "ws://";

    private WebSocket w = null;

    // Use this for initialization
    IEnumerator Start () {
        w = new WebSocket(new Uri(serveradress));
        yield return StartCoroutine(w.Connect());

        w.SendString ("Hello World from client");
        //w.SendString("Hi there");
        int i=0;
        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                master.GetComponent<Networker> ().onNetworkMessage (reply);
                //Debug.Log ("Received: "+reply);
                //w.SendString("Hi there"+reply);
            }
            if (w.error != null)
            {
                Debug.LogError ("Error: "+w.error);
                break;
            }
            w.SendString("helloworld");
            yield return 0;
        }
        w.Close();
    }

    public void sendString(string message){
        sendRaw(Encoding.UTF8.GetBytes (message));
    }

    public void sendRaw(byte[] send){
        w.Send (send);
    }
}

I tried my implementation with an online service that hosts an echo server (http://demos.kaazing.com/echo/) , everything works fine.

I wrote a basic echo server in Java and checked the server with a browser plugin (https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo) and the echo server website from above. Both working like a charm.

Code from Java Server (running in Tomcat 9):

@ServerEndpoint(value = "/echo")
public class WSEchoS {

    private static final Logger LOGGER =
            Logger.getLogger(WSEchoS.class.getName());

    @OnOpen
    public void onOpen(Session session) {
        LOGGER.log(Level.INFO, "New connection with client: {0}",
                session.getId());
        try {
            session.getBasicRemote().sendText("Hello new Client x");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        LOGGER.log(Level.INFO, "New message from Client [{0}]: {1}",
                new Object[]{session.getId(), message});
        try {
            session.getBasicRemote().sendText("This is from the server " + message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Server received [" + message + "]";
    }

    @OnClose
    public void onClose(Session session) {
        LOGGER.log(Level.INFO, "Close connection for client: {0}",
                session.getId());
    }

    @OnError
    public void onError(Throwable exception, Session session) {
        LOGGER.log(Level.INFO, "Error for client: {0}", session.getId());
    }
}

Nooooowwwww the problem:

The Unity client cannot send data to the server!
He can connect properly and can read messages from the Server, but he cannot send him (trigger onmesssage). I searched the whole day without success.

The client is working great with online services, the server as well, but both of them together don´t work. Can anyone explain that? I would love you for that <3

Greetings Pascal

Body:
A day later I found the problem.

Websockets have the ability to handle string, byte[] and some more formats.

I sended my data like this:

public void SendString(string str)
{
    Send (Encoding.UTF8.GetBytes (str));
}

And used the underlying Send(byte[]) method. So when I change the @OnMessage method in Java to

@OnMessage
public void processUpload(byte[] bytes, boolean last, Session session) {

everything works fine, and also the other way around I can send a string and my server is also getting my messages :)

Maybe for some people it´s usefull to know

Greetings Pascal


问:
Display view below RecyclerView (without overlaping)
There are a lot of solutions where the last view is bottom aligned, but I need it to be flexible. Imagine a dialog with a list and positive/negative buttons below. If there are only few elements I'd like it to look like this:

And when there are a lot of items this dialog should expand itself to the bottom, like so:

Layout structure inside LinearLayout is:

```<code>title layout
RecyclerView
buttons layout
</code>```

I tried to wrap RecyclerView inside LinearLayout without succes it just overlap my buttons

答:
```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/splash"
android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/card_listing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_add_card"
        android:layout_below="@+id/card_line"
        android:layout_margin="10dp"
        android:dividerHeight="2dp"
        android:visibility="visible" />

    <TextView
        android:id="@+id/error_message"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/card_listing"
        android:layout_toRightOf="@+id/card_listing"
        android:gravity="center"
        android:text="@string/internet_toast"
        android:textColor="@color/white"
        android:textSize="20sp"
        android:visibility="gone" />

    <Button
        android:id="@+id/btn_add"
        style="@style/ButtonStyle"
        android:layout_above="@+id/pay_now"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:text="Button" />
</RelativeLayout>
</code>```

Body:
There are a lot of solutions where the last view is bottom aligned, but I need it to be flexible. Imagine a dialog with a list and positive/negative buttons below. If there are only few elements I'd like it to look like this:

And when there are a lot of items this dialog should expand itself to the bottom, like so:

Layout structure inside LinearLayout is:

title layout
RecyclerView
buttons layout

I tried to wrap RecyclerView inside LinearLayout without succes it just overlap my buttons


问:
Where to put properties file in jDeveloper IDE and how to access it in Java class
I have been using jDeveloper IDE Build JDEVADF_12.1.3.0.0_GENERIC_140521.1008.S. My project consist of SOAP based web services. All looks good. My project is running fine. However there is a requirement from client for properties file.

I tried to create folder at various places and even placed .properties file directly in the package and tried to fetch values from it using below code.

```<code>        /* First try of fetching from properties file*/

        InputStream is = CountryRepositoryDao.class.getClassLoader().getResourceAsStream("bundle.properties");
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("bundle.properties");
        Properties prop = new Properties();
        prop.load(is);
        System.out.println(prop.getProperty("surname"));

        /* Second try of fetching properties file */
        ClassLoader loader = ClassLoader.getSystemClassLoader ();
        InputStream oInputStream = loader.getResourceAsStream ("config.properties");
        Properties m_Properties = new Properties();
        m_Properties.load(oInputStream);
       System.out.println(m_Properties.getProperty("surname"));
</code>```

However I am getting Null pointer exception ! I tried every tricks in the box but no luck.

could you guys please help me.

Thanks,
Kailash

答:
I have resolved the issue. I did following.

```<code>InputStream  adf =
CountryRepositoryDao.class.getClassLoader().
getResourceAsStream("com/ge/fcm/dao/app.properties");

Properties prop = new Properties();
prop.load(adf);
System.out.println(prop.getProperty("surname")); //I am getting the value.
</code>```

There was an issue with the path in the parameter of getResourceAsStream.

Thanks,
Kailash

Body:
I have been using jDeveloper IDE Build JDEVADF_12.1.3.0.0_GENERIC_140521.1008.S. My project consist of SOAP based web services. All looks good. My project is running fine. However there is a requirement from client for properties file.

I tried to create folder at various places and even placed .properties file directly in the package and tried to fetch values from it using below code.

        /* First try of fetching from properties file*/

        InputStream is = CountryRepositoryDao.class.getClassLoader().getResourceAsStream("bundle.properties");
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("bundle.properties");
        Properties prop = new Properties();
        prop.load(is);
        System.out.println(prop.getProperty("surname"));

        /* Second try of fetching properties file */
        ClassLoader loader = ClassLoader.getSystemClassLoader ();
        InputStream oInputStream = loader.getResourceAsStream ("config.properties");
        Properties m_Properties = new Properties();
        m_Properties.load(oInputStream);
       System.out.println(m_Properties.getProperty("surname"));

However I am getting Null pointer exception ! I tried every tricks in the box but no luck.

could you guys please help me.

Thanks,
Kailash

Body:
I have resolved the issue. I did following.

InputStream  adf =
CountryRepositoryDao.class.getClassLoader().
getResourceAsStream("com/ge/fcm/dao/app.properties");

Properties prop = new Properties();
prop.load(adf);
System.out.println(prop.getProperty("surname")); //I am getting the value.

There was an issue with the path in the parameter of getResourceAsStream.

Thanks,
Kailash


问:
How to get two or more json_encode php echos via Ajax?
```<code>   $errMsgUsername="";
    $errMsgPassword="";

    if ($_POST['username']==""){
     $errMsgUsername="Username is null";
    }
    if ($_POST['password']==""){
     $errMsgPassword="Password is null";
    }

    echo json_encode(['errMsgUsername'=>$errMsgUsername,'errMsgPassword',=>$errMsgPassword]); // json response 1

$success = "";
if ($_POST['username']!="" && $_POST['password']!=""){
$success = "Form data available";
json_encode(['success'=>$success]); // json response 2
}
$.ajax({
              url: $url,
              type: $type,
              data :formData,
              cache: false,
              dataType:"json",
              contentType: false,
              processData: false,
              success: function(response){
                //if fields null, the response has to display here.
                $('.div_username').html(response.errMsgUsername);
                $('.div_password').html(response.errMsgPassword);

                //if fields are not null the response has to display here/
                $('.div').html(response.success);

              }
            });
</code>```

The problem is when i submit the form while (the Username and Password are null), the ajax response is displaying in the Div's as expected. But when I submit the form while (Username and Password are not null with data), the ajax response is not displaying in the $('.div').html(response.success);.
When I see check the ajax request under developer tools it shows that the request is successful, and the the response also came back like this {"errMsgUsername":" ","errMsgPassword":" "}{"success":"Form data available"}.

So the problem here is the ajax response has two two json_encode responses. So how to manage this two responses successfully?

答:
Started on this response before Jomy replied you, posting it as i cleaned up your code a bit, might be useful.</p>

```<code><?php

  $errors = array();

  if (empty($_POST['username'])){
   $errors['errMsgUsername']="Username is null";
  }
  if (empty($_POST['password'])){
   $errors['errMsgPassword']="Password is null";
  }

  if( !empty( $errors ) )
    return json_encode( $errors );

  // If failed, which means we succeeded.
  $success = array(
    'success' => 'Form data available'
  );

  return json_encode($success);
</code>```

Body:
   $errMsgUsername="";
    $errMsgPassword="";

    if ($_POST['username']==""){
     $errMsgUsername="Username is null";
    }
    if ($_POST['password']==""){
     $errMsgPassword="Password is null";
    }

    echo json_encode(['errMsgUsername'=>$errMsgUsername,'errMsgPassword',=>$errMsgPassword]); // json response 1

$success = "";
if ($_POST['username']!="" && $_POST['password']!=""){
$success = "Form data available";
json_encode(['success'=>$success]); // json response 2
}
$.ajax({
              url: $url,
              type: $type,
              data :formData,
              cache: false,
              dataType:"json",
              contentType: false,
              processData: false,
              success: function(response){
                //if fields null, the response has to display here.
                $('.div_username').html(response.errMsgUsername);
                $('.div_password').html(response.errMsgPassword);

                //if fields are not null the response has to display here/
                $('.div').html(response.success);

              }
            });

The problem is when i submit the form while (the Username and Password are null), the ajax response is displaying in the Div's as expected. But when I submit the form while (Username and Password are not null with data), the ajax response is not displaying in the $('.div').html(response.success);.
When I see check the ajax request under developer tools it shows that the request is successful, and the the response also came back like this {"errMsgUsername":" ","errMsgPassword":" "}{"success":"Form data available"}.

So the problem here is the ajax response has two two json_encode responses. So how to manage this two responses successfully?

Body:
Started on this response before Jomy replied you, posting it as i cleaned up your code a bit, might be useful.

<?php

  $errors = array();

  if (empty($_POST['username'])){
   $errors['errMsgUsername']="Username is null";
  }
  if (empty($_POST['password'])){
   $errors['errMsgPassword']="Password is null";
  }

  if( !empty( $errors ) )
    return json_encode( $errors );

  // If failed, which means we succeeded.
  $success = array(
    'success' => 'Form data available'
  );

  return json_encode($success);


问:
Validate each element in an array?
I am currently trying to validate a form server side, the way it works is all the data is put into and array, with the form field as the key and and the field data as the value, however I need to check that all the keys have a value associated with other wise I want the submittion to stop and the user having to edit there details and then re-submit, is there a quick check I can run rather that break the array apart and check that or check before it is put in the array with a switch or losts of if statements?</p>

答:
How about something like

```<code><?php
$arrayFilled = true;
foreach($array as $key=>$value) {
    $arrayFilled = trim($value) == '' ? false : $arrayFilled;
    if($arrayFilled === false) { break; }
}
if($arrayFilled === false) {
    echo "missing data";
}
else {
    echo "filled array";
}
</code>```

you may want to check for more than just an empty string but I'll leave that to you

Title: Validate each element in an array?

LastEditorDisplayName: Rob

Body:
How about something like

<?php
$arrayFilled = true;
foreach($array as $key=>$value) {
    $arrayFilled = trim($value) == '' ? false : $arrayFilled;
    if($arrayFilled === false) { break; }
}
if($arrayFilled === false) {
    echo "missing data";
}
else {
    echo "filled array";
}

you may want to check for more than just an empty string but I'll leave that to you

OwnerDisplayName: Anthony


问:
%D field in Apache access logs - first or last byte?
The Apache Httpd manual has a section on custom access log formats.  One of these options is the %D field, which is documented as

The time taken to serve the request, in microseconds.

Can anyone tell me what exactly this is measuring?  Is it time-to-first-byte, or time-to-last-byte, for example, or something more complex than that?

I need this is demonstrate compliance to performance requirements, and I want to know exactly what's being measured here.

答: http://code.google.com/p/mod-log-firstbyte/ seems to imply that %D measures the time to last byte, whereas mod-log-firstbyte measures the time to first byte.</p>


问:
Regex Python extract digits between two strings in a single expression
I want only digits existing between two characters in order to get an integer dollar value, e.g. from string:

"Advance [Extra Value of $1,730,555] in packages 2,3, and 5."

we want to obtain "1730555".

We can use \$(.*)\] to get "1,730,555", but how do we remove the commas in the same expression, while retaining the possibility of arbitrary many commas, ideally getting the number in a single capturing group?

答:
You could use split and join:</p>

```<code>import re

s = "Advance [Extra Value of $1,730,555] in packages 2,3, and 5."

match = re.findall(r'\$([\d,]+)', s)
number = ''.join(match[0].split(','))
print(number)
</code>```

Body:
You could use split and join:

import re

s = "Advance [Extra Value of $1,730,555] in packages 2,3, and 5."

match = re.findall(r'\$([\d,]+)', s)
number = ''.join(match[0].split(','))
print(number)


问:
How do I put two
s side-by-side, with the left
 taking up 100% of the space not taken up by the right
?
I've got a basic issue. Two
s side-by-side, the left
 needs to be able to have a 'flexible' width, as in when the
 on the right isn't displayed, the left
 will then stretch to 100%.

My code currently is as follows, which doesn't fulfil the above requirement.

```<code><html>
        <head>
        <style>
        #container {
                display: block;
        }

        #box-left {
                width: 100%;
                height: 100px;
                background-color: red;
                float: left;
        }

        #box-right {
                width: 15%;
                height: 100px;
                background-color: blue;
                float: right;
        }
        </style>
        </head>
        <div id="container">
                <div id="box-left"></div>
                <div id="box-right"></div>
        </div>
        <body>

        </body>
</code>```

Any pointers would be much appreciated.

答:
```<code>#container {
  display: table;
  table-layout: fixed;
}
#id-right, #id-left {
  display: table-cell;
  float: none;
}
#id-left {
  /* no width */
}
#id-right {
  width: 15%;
}
</code>```

Unfortunately, that doesn't work in IE6, but apart from that it should do the trick.

Title: How do I put two <div>s side-by-side, with the left <div> taking up 100% of the space not taken up by the right <div>?

Body:
I've got a basic issue. Two
s side-by-side, the left
 needs to be able to have a 'flexible' width, as in when the
 on the right isn't displayed, the left
 will then stretch to 100%.

My code currently is as follows, which doesn't fulfil the above requirement.

Any pointers would be much appreciated.

Body:
#container {
  display: table;
  table-layout: fixed;
}
#id-right, #id-left {
  display: table-cell;
  float: none;
}
#id-left {
  /* no width */
}
#id-right {
  width: 15%;
}

Unfortunately, that doesn't work in IE6, but apart from that it should do the trick.