问:
ConfigureAwait(false) performance test
Everywhere I read that I should use ConfigureAwait(false) to avoid deadlocks and for performance reasons. We are using ConfigureAwait in our application. But might remove the ConfigureAwaits as it's causing a different thread's execution context.

The different thread's execution context is causing (sometimes) problems with translations. As the set culture in currentculture and currentUICulture is not accessible on a different execution context.

I have tested it a little bit with the code below. It did not make any performance difference. I understand it's not a good test as with this simple test there are not many threads used.

```<code>static async Task MyMethodAsync()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  for (int i = 0; i < 1000; i++)
  {
     await Task.Delay(10);
     await Task.Delay(10).ConfigureAwait(continueOnCapturedContext: false);
  }
  stopwatch.Stop();
  Console.WriteLine("Await: " + stopwatch.Elapsed.ToString());
}

static async Task MyMethodAsyncNoAwait()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  for (int i = 0; i < 1000; i++)
  {
     await Task.Delay(10);
     await Task.Delay(10);
  }
  stopwatch.Stop();
  Console.WriteLine(stopwatch.Elapsed.ToString());
}
</code>```

How should I test this properly? Is it a really bad idea of removing all ConfigureAwaits?

答: Don't use ConfigureAwait blindly for performance. Use it when writing code (usually library code) where resuming on the same thread/synchronization context doesn't matter. If resuming on the right thread/synchronization context does matter, ConfigureAwait(false) will break your code, and then it doesn't matter how fast it could have been.

Title: ConfigureAwait(false) performance test

Body:
Everywhere I read that I should use ConfigureAwait(false) to avoid deadlocks and for performance reasons. We are using ConfigureAwait in our application. But might remove the ConfigureAwaits as it's causing a different thread's execution context.

The different thread's execution context is causing (sometimes) problems with translations. As the set culture in currentculture and currentUICulture is not accessible on a different execution context.

I have tested it a little bit with the code below. It did not make any performance difference. I understand it's not a good test as with this simple test there are not many threads used.

static async Task MyMethodAsync()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  for (int i = 0; i < 1000; i++)
  {
     await Task.Delay(10);
     await Task.Delay(10).ConfigureAwait(continueOnCapturedContext: false);
  }
  stopwatch.Stop();
  Console.WriteLine("Await: " + stopwatch.Elapsed.ToString());
}

static async Task MyMethodAsyncNoAwait()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  for (int i = 0; i < 1000; i++)
  {
     await Task.Delay(10);
     await Task.Delay(10);
  }
  stopwatch.Stop();
  Console.WriteLine(stopwatch.Elapsed.ToString());
}

How should I test this properly? Is it a really bad idea of removing all ConfigureAwaits?


来源: stackexchange

问:
rails _5.0.1_ new toy_app installs 5.1.1 version
I am pretty new in Ruby in Rails, I was trying to follow https://www.railstutorial.org/book/toy_app and learn a bit. I tried rails _5.0.1_ new toy_app command but all the time I was getting 5.1.1 version and I had some compatibility problems because of that.

答: So as I wrote in comment, the solution for that was to install gem install rails -v 5.0.2 and then start project rails _5.0.2_ new toy_app, still weird cause that installed me 5.0.3 version, but it works fine now, I solved all compatibility issues.

ContentLicense: CC BY-SA 3.0


问:
How to find distance from the latitude and longitude of two locations?
I have a set of latitudes and longitudes of locations.

How to find distance from one location in the set to another?

Is there a formula ?

答:
Following is the module (coded in f90) containing three formulas discussed in the previous answers. You can either put this module at the top of your program
(before PROGRAM MAIN) or compile it separately and include the module directory during compilation. The following module contains three formulas. First two are great-circle distances based on the assumption that earth is spherical.</p>

```<code>module spherical_dists

contains

subroutine great_circle_distance(lon1,lat1,lon2,lat2,dist)
  !https://en.wikipedia.org/wiki/Great-circle_distance
  ! It takes lon, lats of two points on an assumed spherical earth and
  ! calculates the distance between them along the great circle connecting the two points
  implicit none
  real,intent(in)::lon1,lon2,lat1,lat2
  real,intent(out)::dist
  real,parameter::pi=3.141592,mean_earth_radius=6371.0088
  real::lonr1,lonr2,latr1,latr2
  real::delangl,dellon
  lonr1=lon1*(pi/180.);lonr2=lon2*(pi/180.)
  latr1=lat1*(pi/180.);latr2=lat2*(pi/180.)
  dellon=lonr2-lonr1
  delangl=acos(sin(latr1)*sin(latr2)+cos(latr1)*cos(latr2)*cos(dellon))
  dist=delangl*mean_earth_radius
end subroutine

subroutine haversine_formula(lon1,lat1,lon2,lat2,dist)
  ! https://en.wikipedia.org/wiki/Haversine_formula
  ! This is similar above but numerically better conditioned for small distances
  implicit none
  real,intent(in)::lon1,lon2,lat1,lat2
  !lon, lats of two points
  real,intent(out)::dist
  real,parameter::pi=3.141592,mean_earth_radius=6371.0088
  real::lonr1,lonr2,latr1,latr2
  real::delangl,dellon,dellat,a
  ! degrees are converted to radians
  lonr1=lon1*(pi/180.);lonr2=lon2*(pi/180.)
  latr1=lat1*(pi/180.);latr2=lat2*(pi/180.)
  dellon=lonr2-lonr1 ! These dels simplify the haversine formula
  dellat=latr2-latr1
  ! The actual haversine formula
  a=(sin(dellat/2))**2+cos(latr1)*cos(latr2)*(sin(dellon/2))**2
  delangl=2*asin(sqrt(a)) !2*asin(sqrt(a))
  dist=delangl*mean_earth_radius
end subroutine

subroutine vincenty_formula(lon1,lat1,lon2,lat2,dist)
  !https://en.wikipedia.org/wiki/Vincenty%27s_formulae
  !It's a better approximation over previous two, since it considers earth to in oblate spheroid, which better approximates the shape of the earth
  implicit none
  real,intent(in)::lon1,lon2,lat1,lat2
  real,intent(out)::dist
  real,parameter::pi=3.141592,mean_earth_radius=6371.0088
  real::lonr1,lonr2,latr1,latr2
  real::delangl,dellon,nom,denom
  lonr1=lon1*(pi/180.);lonr2=lon2*(pi/180.)
  latr1=lat1*(pi/180.);latr2=lat2*(pi/180.)
  dellon=lonr2-lonr1
  nom=sqrt((cos(latr2)*sin(dellon))**2. + (cos(latr1)*sin(latr2)-sin(latr1)*cos(latr2)*cos(dellon))**2.)
  denom=sin(latr1)*sin(latr2)+cos(latr1)*cos(latr2)*cos(dellon)
  delangl=atan2(nom,denom)
  dist=delangl*mean_earth_radius
end subroutine

end module
</code>```

Body:
Following is the module (coded in f90) containing three formulas discussed in the previous answers. You can either put this module at the top of your program
(before PROGRAM MAIN) or compile it separately and include the module directory during compilation. The following module contains three formulas. First two are great-circle distances based on the assumption that earth is spherical.

module spherical_dists

contains

subroutine great_circle_distance(lon1,lat1,lon2,lat2,dist)
  !https://en.wikipedia.org/wiki/Great-circle_distance
  ! It takes lon, lats of two points on an assumed spherical earth and
  ! calculates the distance between them along the great circle connecting the two points
  implicit none
  real,intent(in)::lon1,lon2,lat1,lat2
  real,intent(out)::dist
  real,parameter::pi=3.141592,mean_earth_radius=6371.0088
  real::lonr1,lonr2,latr1,latr2
  real::delangl,dellon
  lonr1=lon1*(pi/180.);lonr2=lon2*(pi/180.)
  latr1=lat1*(pi/180.);latr2=lat2*(pi/180.)
  dellon=lonr2-lonr1
  delangl=acos(sin(latr1)*sin(latr2)+cos(latr1)*cos(latr2)*cos(dellon))
  dist=delangl*mean_earth_radius
end subroutine

subroutine haversine_formula(lon1,lat1,lon2,lat2,dist)
  ! https://en.wikipedia.org/wiki/Haversine_formula
  ! This is similar above but numerically better conditioned for small distances
  implicit none
  real,intent(in)::lon1,lon2,lat1,lat2
  !lon, lats of two points
  real,intent(out)::dist
  real,parameter::pi=3.141592,mean_earth_radius=6371.0088
  real::lonr1,lonr2,latr1,latr2
  real::delangl,dellon,dellat,a
  ! degrees are converted to radians
  lonr1=lon1*(pi/180.);lonr2=lon2*(pi/180.)
  latr1=lat1*(pi/180.);latr2=lat2*(pi/180.)
  dellon=lonr2-lonr1 ! These dels simplify the haversine formula
  dellat=latr2-latr1
  ! The actual haversine formula
  a=(sin(dellat/2))**2+cos(latr1)*cos(latr2)*(sin(dellon/2))**2
  delangl=2*asin(sqrt(a)) !2*asin(sqrt(a))
  dist=delangl*mean_earth_radius
end subroutine

subroutine vincenty_formula(lon1,lat1,lon2,lat2,dist)
  !https://en.wikipedia.org/wiki/Vincenty%27s_formulae
  !It's a better approximation over previous two, since it considers earth to in oblate spheroid, which better approximates the shape of the earth
  implicit none
  real,intent(in)::lon1,lon2,lat1,lat2
  real,intent(out)::dist
  real,parameter::pi=3.141592,mean_earth_radius=6371.0088
  real::lonr1,lonr2,latr1,latr2
  real::delangl,dellon,nom,denom
  lonr1=lon1*(pi/180.);lonr2=lon2*(pi/180.)
  latr1=lat1*(pi/180.);latr2=lat2*(pi/180.)
  dellon=lonr2-lonr1
  nom=sqrt((cos(latr2)*sin(dellon))**2. + (cos(latr1)*sin(latr2)-sin(latr1)*cos(latr2)*cos(dellon))**2.)
  denom=sin(latr1)*sin(latr2)+cos(latr1)*cos(latr2)*cos(dellon)
  delangl=atan2(nom,denom)
  dist=delangl*mean_earth_radius
end subroutine

end module

ContentLicense: CC BY-SA 4.0


问:
can pimpl idiom's impl class has destructor？
I learn pimpl in effective modern cpp,after do some search,no one has talk about the pimpl idiom's impl class's destructor implement, is it unnecessary?</p>

```<code>//in widget.h
#include <memory>
class Widget{
public:
    Widget();
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
//in widget.cpp
........
struct Widget::Impl{
  std::string name;                // Widget::Impl
  std::vector<double> data;
};

struct Widget::~Impl()   //error!!!,how can we implement it
{
};
</code>```

答:
thanks for democode post by @Retired Ninja,it helps a lot,the point is,we need a declaration of ~Impl in the cpp file:</p>

```<code>Widget::Widget():pImpl(std::make_unique<Impl>())
{
}

 struct Widget::Impl {
     std::string name;
     std::vector<double> data;
     ~Impl();// need this !!
 };

 Widget::Impl::~Impl(){
 };

 Widget::~Widget() {
 }
</code>```

Body:
I learn pimpl in effective modern cpp,after do some search,no one has talk about the pimpl idiom's impl class's destructor implement, is it unnecessary?

//in widget.h
#include <memory>
class Widget{
public:
    Widget();
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
//in widget.cpp
........
struct Widget::Impl{
  std::string name;                // Widget::Impl
  std::vector<double> data;
};

struct Widget::~Impl()   //error!!!,how can we implement it
{
};

Body:
thanks for democode post by @Retired Ninja,it helps a lot,the point is,we need a declaration of ~Impl in the cpp file:

Widget::Widget():pImpl(std::make_unique<Impl>())
{
}

 struct Widget::Impl {
     std::string name;
     std::vector<double> data;
     ~Impl();// need this !!
 };

 Widget::Impl::~Impl(){
 };

 Widget::~Widget() {
 }


问:
Show Tutorial View on first time only
I'm trying to create an tutorial screen that displays only during the first opening of an app. i know i should use user defaults but how and where ? in method viewDidLoad or on app delegate class ? </p>

答:
@Maddy has given correct answer but let me just clarify one thing why we will not use viewDidLoad?
Why we are using didFinishLaunch

in short:

viewDidLoad

System has already decided which View to load when application launches .By default it's the "Main" storyboard's initial view controller

didFinishLaunch

System has done all tasks to show your app but has not decided which view to load. Thats why you can control here to show your tutorial screen first. :)

Title: Show Tutorial View on first time only


问:
How can I make my icon
s show up next to each other, rather than underneath each other?
I have this

```<code><a href="#"><div class="iconFriends"></div></a>
<a href="#"><div class="iconFavorite"></div></a>
<a href="#"><div class="iconPM"></div></a>
<a href="#"><div class="iconShield"></div></a>
</code>```

and the css for the icons class looks all similiar to this:

```<code>.iconFriends{
background: url(../images/icons/friends_16x16.png) no-repeat;
width: 16px;
height: 16px;
border: none;
}
</code>```

Now the results is that there is like a
 when I do this. But if i remove the div and make a normal  It shows fine. How can i fix this?

答:
Option 1: replace the
 with a

Option 2: set the
 to display: inline;. Its default display property value is block, which is why each one is on its own line.

```<code>.iconFriends {
    display: inline;
    ...
</code>```

ContentLicense: CC BY-SA 2.5

Title: How can I make my icon <div>s show up next to each other, rather than underneath each other?

Body:
I have this

and the css for the icons class looks all similiar to this:

.iconFriends{
background: url(../images/icons/friends_16x16.png) no-repeat;
width: 16px;
height: 16px;
border: none;
}

Now the results is that there is like a
 when I do this. But if i remove the div and make a normal  It shows fine. How can i fix this?

Body:
Option 1: replace the <div> with a <span>

Option 2: set the <div> to display: inline;. Its default display property value is block, which is why each one is on its own line.

.iconFriends {
    display: inline;
    ...


问:
Drag and drop from qx.ui.table.Table (Qooxdoo version 5.x or master)
I am trying to drag from a qx.ui.table.Table widget to some other widget.
I fail to get information about the table row I am trying to drag.

I would like to drag a row (respectively its content) without it being focused or selected, e.g.g just click into the row and immediately start dragging.

Thanks,
Fritz

答:
What I'm doing in this situation is to first set the tables focusCellOnPointerMove property to true.

If you don't want to have the feedback of cells being highlighted on mouse move, you could additionally call table.highlightFocusedRow(false) to supress that.

This way the table is "aware" of the cell/row being currently under the mouse pointer.

Then you're able to detect the current row index in the table's dragstart event handler:

```<code> _onDragStartGetFocusedRow : function(e) {
   var index = this.getFocusedRow();
   if(qx.lang.Type.isNumber(index)) {
     // do something usefull with this information
     // and start dragging
     e.addAction("move);
     e.addType("myType");
   }
 },
</code>```

After finishing drag and drop you could reset the focused row by calling table.resetCellFocus() eg. in the dragend handler.

This does, of course, only work with pointer devices.

Body:
What I'm doing in this situation is to first set the tables focusCellOnPointerMove property to true.

If you don't want to have the feedback of cells being highlighted on mouse move, you could additionally call table.highlightFocusedRow(false) to supress that.

This way the table is "aware" of the cell/row being currently under the mouse pointer.

Then you're able to detect the current row index in the table's dragstart event handler:

 _onDragStartGetFocusedRow : function(e) {
   var index = this.getFocusedRow();
   if(qx.lang.Type.isNumber(index)) {
     // do something usefull with this information
     // and start dragging
     e.addAction("move);
     e.addType("myType");
   }
 },

After finishing drag and drop you could reset the focused row by calling table.resetCellFocus() eg. in the dragend handler.

This does, of course, only work with pointer devices.


问:
Angular: Disable Change Detector for an entire class (service or component)
Is there a way to completely disable Angular's change detector if events that normally cause the change detection to run (setTimeout, setInterval, browser events, ajax calls etc..), are coming from a specific class (service or component)?

Namely, it seemed totally wrong to me when I found out that the setInterval registered in my service causes the global change detection to run every second..

I'm aware I can wrap my code inside the NgZone.runOutsideAngular method's callback, but I'd prefer the solution where the change detector can be disabled for an entire class, as I have other chunks of code within the service that are needlessly running the detection too.

Thanks for your help.

答:
You can change the detection strategy of individual components with the following:

```<code>import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'ws-layout-page',
  templateUrl: './layout-page.component.html',
  styleUrls: ['./layout-page.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LayoutPageComponent {

}
</code>```

I dont know any other method that could archieve some selective turn on/of depending of where is the information coming from

Body:
You can change the detection strategy of individual components with the following:

import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'ws-layout-page',
  templateUrl: './layout-page.component.html',
  styleUrls: ['./layout-page.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LayoutPageComponent {

}

I dont know any other method that could archieve some selective turn on/of depending of where is the information coming from


问:
Deploy shiny app in rocker/shiny docker
Well, I'm new at Docker and I need to implement a Shiny app in a Docker Container.

I have the image from https://hub.docker.com/r/rocker/shiny/, that includes Shiny Server, but I don't know how to deploy my app in the server.

I want to deploy the app in the server, install the required packages for my app into the Docker, save the changes and export the image/container.

As I said, I'm new at Docker and I don't know how it really works.

Any idea?

答:
The link(https://hub.docker.com/r/rocker/shiny/) covers how to deploy the shiny server.
Simplest way would be:
docker run --rm -p 3838:3838 rocker/shiny

If you want to extend shiny server, you can write your own Dockerfile and start with shiny image as base image.(https://docs.docker.com/engine/reference/builder/)

Dockerfile:
FROM rocker/shiny:latest

Title: Deploy shiny app in rocker/shiny docker


问:
Is creating instances of a class inside a static PageMethod thread safe?
I am using jQuery to call PageMethods.  For certain operations, the current user credentials must be validated and for other operations, I need to call other static methods.  Here is some sample code:

Sample #1

```<code>[WebMethod]
public static void PostComment(string comment)
{
    UserAuth auth = new UserAuth();
    if (auth.isAuthenticated)
        {
            //Post comment here...
        }
}
</code>```

Sample #2

```<code>[WebMethod]
public static string GetComment(int commentId)
{

    commentDto comment = //get comment data from the database...
    string friendlyDate = ConvertFriendlyDate(comment.commentDate);

    return friendlyDate + " " + comment.text;
}

public static string ConvertFriendlyDate(DateTime commentDate)
{
    string friendlyDate = //call static utility method to convert date to friendly format

    return friendlyDate;

}
</code>```

Will I be safe using these kinds of operations?

Am I better to drop page methods and just call a separate ASPX page for my AJAX requests?

答:
From http://msdn.microsoft.com/en-us/library/system.web.ui.page.aspx

"Any public static (Shared in Visual Basic) members of this type [Page] are thread safe. Any instance members are not guaranteed to be thread safe."

Therefore as long as your static methods don't touch class-scope objects you should be fine. e.g. this might be bad:

```<code>static UserAuth auth;
[WebMethod]
public static void PostComment(string comment)
{
    auth = new UserAuth();
    if (auth.isAuthenticated)
        {
            //Post comment here...
        }
}
</code>```

Body:
I am using jQuery to call PageMethods.  For certain operations, the current user credentials must be validated and for other operations, I need to call other static methods.  Here is some sample code:

Sample #1

[WebMethod]
public static void PostComment(string comment)
{
    UserAuth auth = new UserAuth();
    if (auth.isAuthenticated)
        {
            //Post comment here...
        }
}

Sample #2

[WebMethod]
public static string GetComment(int commentId)
{

    commentDto comment = //get comment data from the database...
    string friendlyDate = ConvertFriendlyDate(comment.commentDate);

    return friendlyDate + " " + comment.text;
}

public static string ConvertFriendlyDate(DateTime commentDate)
{
    string friendlyDate = //call static utility method to convert date to friendly format

    return friendlyDate;

}

Will I be safe using these kinds of operations?

Am I better to drop page methods and just call a separate ASPX page for my AJAX requests?

Body:
From http://msdn.microsoft.com/en-us/library/system.web.ui.page.aspx

"Any public static (Shared in Visual Basic) members of this type [Page] are thread safe. Any instance members are not guaranteed to be thread safe."

Therefore as long as your static methods don't touch class-scope objects you should be fine. e.g. this might be bad:

static UserAuth auth;
[WebMethod]
public static void PostComment(string comment)
{
    auth = new UserAuth();
    if (auth.isAuthenticated)
        {
            //Post comment here...
        }
}


问:
webpackHtmlPlugin: control the order of injected files
I use HtmlWebpackPlugin for auto generate the index.thml with the output of webpack compile.

for performance reason I split my entries to vendors and project

like that:

```<code>...
entry:{
    vendors:'./vendors.js'
    ,TimerApp:'./src/index.js'

},
output:{
    path: path.join(__dirname,'build'),
    filename:'[name].js'
},
...
</code>```

when I run the project by webpack-dev-server:

set NODE_ENV=development && webpack-dev-server -d --hot --port 4040 --content-base src/"

I get index.html

```<code><head>
...
    <title>Timer Task</title>
    <link href="vendors.css"  rel="stylesheet">
    <link href="TimerApp.css" rel="stylesheet">
</head>
<body >
 ...
<script src="vendors.js"></script>
<script src="TimerApp.js"></script>
</code>```

verdor.js first and TimerApp.js second. and that perfect.

but.. when I use webpack:

webpack --colors --watch --optimize-dedupe

the order is TimerApp.js first and vendors.js second
and that make exception every time project compiled

very annoyed.

so, what is the way to control the order of the output files ??

reference: webpack.js file:

```<code>var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var ngAnnotatePlugin = require('ng-annotate-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var exportRunTimeVariable = new webpack.DefinePlugin({
   MODE: {
    production: process.env.NODE_ENV === 'production'
   }
});

var extractSCSS =  new ExtractTextPlugin("[name].css");

module.exports = {
    watch: true,
    devtool: 'source-map', /*devtool: 'inline-source-map'*/
    context: __dirname, /*for node key*/
    node:{
        __filename:true,
        __dirname:true
    },
    resolve: {
        root:[
            path.resolve('src')
            ,path.resolve('node_modules')
            ,path.resolve('bower_components')
        ]
        //root: __dirname + '/src'
    },
    entry:{
        vendors:'./vendors.js'
        ,TimerApp:'./src/index.js'

    },
    output:{
        path: path.join(__dirname,'build'),
        filename:'[name].js'
    },
    module:{
        loaders:[
            /*
            test: A condition that must be met
            exclude: A condition that must not be met
            include: A condition that must be met
            loader: A string of "!" separated loaders
            loaders: A array of loaders as string
            */
            {test:/\.css$/,
                loader:extractSCSS.extract('style-loader?sourceMap','css-               loader!sass-loader')},

        {test: /\.scss$/,
            loader: extractSCSS.extract('style-loader?sourceMap','css-loader!sass-loader')},

        {test: /\.js$/,
            loader: 'ng-annotate',
            exclude: /node_modules|bower_components/},

        {test: /\.(woff|woff2|ttf|eot|svg)(\?]?.*)?$/,
            loader : 'file-loader?name=res/[name].[ext]?[hash]'
        },
        //{test: /index\.html$/,
        //    loader : 'file-loader?name=[name].[ext]'
        //},

        {test: /\.html$/,
            loader: 'raw'
            ,exclude:[/index.html/]},

        {test: /\.json/,
            loader: 'json'}

    ]
},
plugins: [
    extractSCSS,
    exportRunTimeVariable,
    new ngAnnotatePlugin({
        add: true
            // other ng-annotate options here
        }),
        new HtmlWebpackPlugin({
            title: 'Timer Task'
            //,filename: ''
            ,template: 'src/index.html'
        })
    ]
};
</code>```

答:
```<code>chunksSortMode: function (chunk1, chunk2) {
    var order = ['first', 'second', 'third'];
    var order1 = order.indexOf(chunk1.names[0]);
    var order2 = order.indexOf(chunk2.names[0]);
    return order1 - order2;
}
</code>```

Body:
I use HtmlWebpackPlugin for auto generate the index.thml with the output of webpack compile.

for performance reason I split my entries to vendors and project

like that:

...
entry:{
    vendors:'./vendors.js'
    ,TimerApp:'./src/index.js'

},
output:{
    path: path.join(__dirname,'build'),
    filename:'[name].js'
},
...

when I run the project by webpack-dev-server:

set NODE_ENV=development && webpack-dev-server -d --hot --port 4040 --content-base src/"

I get index.html

...
    <title>Timer Task</title>
    <link href="vendors.css"  rel="stylesheet">
    <link href="TimerApp.css" rel="stylesheet">

 ...

verdor.js first and TimerApp.js second. and that perfect.

but.. when I use webpack:

webpack --colors --watch --optimize-dedupe

the order is TimerApp.js first and vendors.js second
and that make exception every time project compiled

very annoyed.

so, what is the way to control the order of the output files ??

reference: webpack.js file:

var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var ngAnnotatePlugin = require('ng-annotate-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var exportRunTimeVariable = new webpack.DefinePlugin({
   MODE: {
    production: process.env.NODE_ENV === 'production'
   }
});

var extractSCSS =  new ExtractTextPlugin("[name].css");

module.exports = {
    watch: true,
    devtool: 'source-map', /*devtool: 'inline-source-map'*/
    context: __dirname, /*for node key*/
    node:{
        __filename:true,
        __dirname:true
    },
    resolve: {
        root:[
            path.resolve('src')
            ,path.resolve('node_modules')
            ,path.resolve('bower_components')
        ]
        //root: __dirname + '/src'
    },
    entry:{
        vendors:'./vendors.js'
        ,TimerApp:'./src/index.js'

    },
    output:{
        path: path.join(__dirname,'build'),
        filename:'[name].js'
    },
    module:{
        loaders:[
            /*
            test: A condition that must be met
            exclude: A condition that must not be met
            include: A condition that must be met
            loader: A string of "!" separated loaders
            loaders: A array of loaders as string
            */
            {test:/\.css$/,
                loader:extractSCSS.extract('style-loader?sourceMap','css-               loader!sass-loader')},

        {test: /\.scss$/,
            loader: extractSCSS.extract('style-loader?sourceMap','css-loader!sass-loader')},

        {test: /\.js$/,
            loader: 'ng-annotate',
            exclude: /node_modules|bower_components/},

        {test: /\.(woff|woff2|ttf|eot|svg)(\?]?.*)?$/,
            loader : 'file-loader?name=res/[name].[ext]?[hash]'
        },
        //{test: /index\.html$/,
        //    loader : 'file-loader?name=[name].[ext]'
        //},

        {test: /\.html$/,
            loader: 'raw'
            ,exclude:[/index.html/]},

        {test: /\.json/,
            loader: 'json'}

    ]
},
plugins: [
    extractSCSS,
    exportRunTimeVariable,
    new ngAnnotatePlugin({
        add: true
            // other ng-annotate options here
        }),
        new HtmlWebpackPlugin({
            title: 'Timer Task'
            //,filename: ''
            ,template: 'src/index.html'
        })
    ]
};


问:
Kotlin's synthetic properties conflict
I'm new to Kotlin. Among other very interesting things, I've found the Android extensions which, according to the documentation, should let me use activities' views without the need of findViewById.

Actually it works very well by adding just this line in my imports:

```<code>import kotlinx.android.synthetic.main.<layout>.*
</code>```

The problem is when two different layouts contain a widget with the same id (i.e. the same name for the synthetic property),

e.g. two different TextViews with the id txtTitle. Say the first one is on an activity and the second one belongs to the layout used inside of an adapter.

When I try to call a method on the first TextView (the activity's one) I can't see the expected result, as if the call would be done on another view. As confirmation of this, when I call txtTitle.parent, I see the parent and the siblings of the other txtTitle rather than the ones expected.

Am I doing something wrong? The only ways I've found to bypass this issue is to use different names in all my layouts or continue to use findViewById, but it would be a pity to waste this language feature...

答:
You can try below thing for TextView having same id from different layout.

```<code>import kotlinx.android.synthetic.main.activity_main.text_hello as lActivity

import kotlinx.android.synthetic.main.extra_layout.text_hello as lView
</code>```

use lActivity.text = "Some text" for TextView from activity_main and lView.text = "Some text" for TextView from extra_layout.

Title: Kotlin's synthetic properties conflict

Body:
I'm new to Kotlin. Among other very interesting things, I've found the Android extensions which, according to the documentation, should let me use activities' views without the need of findViewById.

Actually it works very well by adding just this line in my imports:

import kotlinx.android.synthetic.main.<layout>.*

The problem is when two different layouts contain a widget with the same id (i.e. the same name for the synthetic property),

e.g. two different TextViews with the id txtTitle. Say the first one is on an activity and the second one belongs to the layout used inside of an adapter.

When I try to call a method on the first TextView (the activity's one) I can't see the expected result, as if the call would be done on another view. As confirmation of this, when I call txtTitle.parent, I see the parent and the siblings of the other txtTitle rather than the ones expected.

Am I doing something wrong? The only ways I've found to bypass this issue is to use different names in all my layouts or continue to use findViewById, but it would be a pity to waste this language feature...

Body:
You can try below thing for TextView having same id from different layout.

import kotlinx.android.synthetic.main.activity_main.text_hello as lActivity

import kotlinx.android.synthetic.main.extra_layout.text_hello as lView

use lActivity.text = "Some text" for TextView from activity_main and lView.text = "Some text" for TextView from extra_layout.


问:
Extracting a list of products bu category using doctrine
I want to extract a list of products by given category, I dont know how to do that! I have found findAll which return all products in database should I use dql?

somthing like:

my controller

```<code>public function ProductByCategory(Request $request, Category $cat)
{
    $product =new Product() ;

    $form = $this->createForm('AppBundle\Form\ProductType',$product);

    $query = $em->createQueryBuilder('p')
  ->where('p->getCategory()->getId()  = :categoryid')   /*I mean where  id
   product =id category  */
  ->setParameter(' categoryid ',$cat->getId())
  ->getQuery();

  $products = $query->getResult();

return $this->render('AppBundle:Category:ListProductByCategory.html.twig', array('products' =>$products));

}
</code>```

my twig will looks like:

```<code><table id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
    <thead>
    <tr>
        <th>Product name</th>

        <th>Product price</th>
        <th>quantity</th>
        <th>color</th>

    </tr>
    </thead>
    <tbody>
    {% for p in products  %}
        <tr>
            <td>{{p.name }}<td>

            <td>{{ p.price }}</td>
            <td>{{ p. quantity }}</td>
            <td>{{ p. color }}</td>
            <td>
                <a href="{{ path('us_product_update', {'id': p.id}) }}"  name="update">Update</a>
                <a href="{{ path('us_ product _delete', {'id': p.id}) }}" name="delete">delete</a>

                 </td>
        </tr>

    {% endfor %}
    </tbody>
</table>
</code>```

Upadte

I am updating my post with the right code I hope that will help sombody

```<code>    $products= $this->getDoctrine()->getManager()->getRepository('AppBundle:Product')->findByCategory($cat->getId());
</code>```

答:
try this to get your products based on category Id</p>

```<code>$products = $this->manager->getRepository('AppBundle:Product')
            ->findOneByCategory($cat->getId());
</code>```

Body:
I want to extract a list of products by given category, I dont know how to do that! I have found findAll which return all products in database should I use dql?

somthing like:

my controller

public function ProductByCategory(Request $request, Category $cat)
{
    $product =new Product() ;

    $form = $this->createForm('AppBundle\Form\ProductType',$product);

    $query = $em->createQueryBuilder('p')
  ->where('p->getCategory()->getId()  = :categoryid')   /*I mean where  id
   product =id category  */
  ->setParameter(' categoryid ',$cat->getId())
  ->getQuery();

  $products = $query->getResult();

return $this->render('AppBundle:Category:ListProductByCategory.html.twig', array('products' =>$products));

}

my twig will looks like:

        Product name

        Product price
        quantity
        color

    {% for p in products  %}

            {{p.name }}

            {{ p.price }}
            {{ p. quantity }}
            {{ p. color }}

                Update
                delete

    {% endfor %}

Upadte

I am updating my post with the right code I hope that will help sombody

    $products= $this->getDoctrine()->getManager()->getRepository('AppBundle:Product')->findByCategory($cat->getId());

Body:
try this to get your products based on category Id

$products = $this->manager->getRepository('AppBundle:Product')
            ->findOneByCategory($cat->getId());


问:
Simple word replacement in output from SQL
I'm running PostgreSQL 9.4.

Is there a replace string function which can take an array of words, or other similar function?

Ex.

```<code>SELECT REPLACE(my_column, ['blue', 'red'], ['ColorBlue', 'ColorRed']);
</code>```

So blue becomes ColorBlue, and red becomes ColorRed?
It's not only such simple replacements, but for the example I'm using this.

答:
One way is create it:

```<code>create or replace function rep_arr(str text, src text[], rep text[])
returns text as $$
begin
    for i in 1..array_length(src, 1) loop
        str := replace(str, src[i], rep[i]);
    end loop;
    return str;
end; $$ language plpgsql
</code>```

Call:

```<code>select rep_arr('bla bla blue bla red bla', '{blue,red}' , '{ColorBlue,ColorRed}');
</code>```

Body:
I'm running PostgreSQL 9.4.

Is there a replace string function which can take an array of words, or other similar function?

Ex.

SELECT REPLACE(my_column, ['blue', 'red'], ['ColorBlue', 'ColorRed']);

So blue becomes ColorBlue, and red becomes ColorRed?
It's not only such simple replacements, but for the example I'm using this.

Body:
One way is create it:

create or replace function rep_arr(str text, src text[], rep text[])
returns text as $$
begin
    for i in 1..array_length(src, 1) loop
        str := replace(str, src[i], rep[i]);
    end loop;
    return str;
end; $$ language plpgsql

Call:

select rep_arr('bla bla blue bla red bla', '{blue,red}' , '{ColorBlue,ColorRed}');


问:
How to correctly render a ar-SA date and time string
So, I've got a DateTime value, and I need to render it out using the ar-SA culture (using the Gregorian Calendar).

The format I'd like to use is dd-MMM-yyyy HH:mm.

I'm using this currently to format it -

```<code>dateTimeValue.ToString("dd-MMM-yyyy HH:mm", culture)
</code>```

In en-GB, I'd see -

06-Jun-2017 16:49

In ar-SA, when I use the same method, I see -

06-يونيو-2017 16:49

Now, from what I can work out, I think it's the RTL string that's causing the problem, since it's always on the right-hand side.

How do I render out this date correctly in RTL?

答:
Right, after a bit of digging, I've managed to get a solution that works.

Even though my question was originally about ar-SA, it does apply to any right-to-left culture.

I ended up using unicode characters to explicitly state what parts of the string were left-to-right and right-to-left.

So, using the constants -

```<code>private const char LeftToRightCharacter = (char)0x200E;
private const char RightToLeftCharacter = (char)0x200F;
</code>```

I can then build up a string of the date as follows -

```<code>if (culture.TextInfo.IsRightToLeft)
{
    return
        LeftToRightCharacter +
        date.ToString("yyyy-", culture) +
        RightToLeftCharacter +
        date.ToString("MMM", culture) +
        LeftToRightCharacter +
        date.ToString("-dd", culture);
}
return date.ToString("dd-MMM-yyyy", culture);
</code>```

...where culture is a CultureInfo (with the DateTimeFormat.Calendar set to new GregorianCalendar()) and date is a DateTime.

So, for the date 06-Jun-2017, in en-GB I get -

06-Jun-2017

and in ar-SA I get -

2017-يونيو-06

Now that I've got that as a string, I can add the time on either side (to the left, if the culture is RTL and on the right if the culture is LTR).

It was useful seeing how Unicode deals with these characters, along with the other characters I could have used instead - http://www.unicode.org/reports/tr9/

Body:
So, I've got a DateTime value, and I need to render it out using the ar-SA culture (using the Gregorian Calendar).

The format I'd like to use is dd-MMM-yyyy HH:mm.

I'm using this currently to format it -

dateTimeValue.ToString("dd-MMM-yyyy HH:mm", culture)

In en-GB, I'd see -

06-Jun-2017 16:49

In ar-SA, when I use the same method, I see -

06-يونيو-2017 16:49

Now, from what I can work out, I think it's the RTL string that's causing the problem, since it's always on the right-hand side.

How do I render out this date correctly in RTL?

Body:
Right, after a bit of digging, I've managed to get a solution that works.

Even though my question was originally about ar-SA, it does apply to any right-to-left culture.

I ended up using unicode characters to explicitly state what parts of the string were left-to-right and right-to-left.

So, using the constants -

private const char LeftToRightCharacter = (char)0x200E;
private const char RightToLeftCharacter = (char)0x200F;

I can then build up a string of the date as follows -

if (culture.TextInfo.IsRightToLeft)
{
    return
        LeftToRightCharacter +
        date.ToString("yyyy-", culture) +
        RightToLeftCharacter +
        date.ToString("MMM", culture) +
        LeftToRightCharacter +
        date.ToString("-dd", culture);
}
return date.ToString("dd-MMM-yyyy", culture);

...where culture is a CultureInfo (with the DateTimeFormat.Calendar set to new GregorianCalendar()) and date is a DateTime.

So, for the date 06-Jun-2017, in en-GB I get -

06-Jun-2017

and in ar-SA I get -

2017-يونيو-06

Now that I've got that as a string, I can add the time on either side (to the left, if the culture is RTL and on the right if the culture is LTR).

It was useful seeing how Unicode deals with these characters, along with the other characters I could have used instead - http://www.unicode.org/reports/tr9/


问:
A suitable PC for Visual Studio 2010 programming
I'm planning on buying a new PC for programming under Visual Studio 2010. My main other usages are:

Programming under Microsoft Visual Studio.

Running VMWare Virtual Machines.

Probably multi-monitor (if my budget lets me buy an extra one)

Here are my questions:

Do I need to purchase a high performance display adapter considering my usage described above? or a medium-range one will suffice? In general, I'd like to know how much a display adapter could affect my usages?

Which CPU could perform better? Core i7, Core 2 Quad, AMD?  I have a limited budget but I really need a good performance and buying a good CPU/MB/RAM is my first priority.

答:
I would consider getting a better-than-average video card because you'll need some horsepower to run multiple monitors, since you'll want to take advantage of the new tab tear-off ability in vs 2010 to display code files in separate windows.

I would definitely recommend a 10,000 RPM Velociraptor hard-drive or a pair of them striped because VS is a bit of a hog on IO resources.

If it was me, I'd go with a 6-core AMD Phenom processor and 6GB of Triple-channel RAM to maximize performance. If you're an Intel fan, go i7.


问:
Sitecore testing licenses
I currently work for a company that uses allot of Sitecore servers and has many dev seats across Europe.

A problem that I have run into is that we desperately need a testing environment for Smoke Testing, Automation Tests and other Manual pre QA deployment.

The internal department that deals with licenses says that kind of environment is classed a a full server and requires the full license fee (which has allot of zeros!!)

Because its an enterprise business we are now in a catch 22 situation. I have heard that spinning up a new VM on the machine I am developing on is allowed on a developers license / and I can reusue my developer license on any machine as long as i am the only person that uses it.

So, if our tester sets up his own test machine that only he uses, its covered by his developer license? That thing will be rebuilt several times a week and never have anybody else connect to it really, maybe other developers. (license overlapping?)

Anybody have any similar issues or solution? I need to provide formal proof if I have any chance of pushing this forward. (I contacted sitecore also but it may take a while for them to come back, Just looking too see if anybody else may help in the mean time)

答:
Sitecore 8+ licensing structure has changed and will allow you to create multiples of Virtual Machines using a single license. This can be leveraged for test systems, load balancing, pre-production or quality assurance uses.

IMHO: The only reason they did this was to probably get onto the
  "cloud" marketing train and realised their 1990's extremely restrictive licensing terms
  needed to be overhauled  as it prevented them selves from using their
  own software in virtual machines.

So prior to Sitecore 8, No. You have to have a full license for each machine and each machine.

Basically extremely restrictive licensing that cost a fortune, as that is the Sitecore business model.

Title: Sitecore testing licenses


问:
How to install jpeglib on Windows 10
I am having 64 bit Windows 10 operating system.  I have downloaded  jpegsr9b library from JPEG website which is used for reading JPEG header file. I have written program in C to read JPEG file as below:

```<code>#include<stdio.h>
#include<jpeglib.h>
#include <stdlib.h>

int main()
{

struct jpeg_decompress_struct cinfo;

 struct jpeg_error_mgr jerr;

int height,width,pixel_size,colorspace,i,j,k,res;

FILE *infile = fopen("e:/Images/im.jpg", "rb");
cinfo.err = jpeg_std_error(&jerr);

jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, infile);
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
width = cinfo.output_width;
height = cinfo.output_height;

printf("\nWidth = %d",width);
printf("\nHeight = %d",height);
}
</code>```

Then compiled as

```<code>gcc demo.c -ljpeg
</code>```

But it gives error

In file included from demo.c:2:0:
  jpeglib.h:25:62: fatal error: jconfig.h: No such file or directory
  compilation terminated.

How to solve the problem?

答:
install the binary from here and then include the include folder from the installation in visual studio.

for more instruction follow this answer.

Title: How to install jpeglib on Windows 10

Body:
I am having 64 bit Windows 10 operating system.  I have downloaded  jpegsr9b library from JPEG website which is used for reading JPEG header file. I have written program in C to read JPEG file as below:

#include<stdio.h>
#include<jpeglib.h>
#include <stdlib.h>

int main()
{

struct jpeg_decompress_struct cinfo;

 struct jpeg_error_mgr jerr;

int height,width,pixel_size,colorspace,i,j,k,res;

FILE *infile = fopen("e:/Images/im.jpg", "rb");
cinfo.err = jpeg_std_error(&jerr);

jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, infile);
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
width = cinfo.output_width;
height = cinfo.output_height;

printf("\nWidth = %d",width);
printf("\nHeight = %d",height);
}

Then compiled as

gcc demo.c -ljpeg

But it gives error

In file included from demo.c:2:0:
  jpeglib.h:25:62: fatal error: jconfig.h: No such file or directory
  compilation terminated.

How to solve the problem?


问:
Mysql change all table names to lower case
I have got 10 tables in mysql all starting with uppercase, I was wondering if can change all of them to lowercase with one query rather than 20?</p>

答:
Check Amy Anuszewski answer</p>

```<code>select concat('rename table ', table_name, ' to ' , lower(table_name) , ';')from information_schema.tables where table_schema = 'your_schema_name';
</code>```

Body:
Check Amy Anuszewski answer

select concat('rename table ', table_name, ' to ' , lower(table_name) , ';')from information_schema.tables where table_schema = 'your_schema_name';


问:
Android studio Action call to run USSD codes
By using an app I want to run a USSD code, but the problem is it doesn't recognize the "#" symbol.
If I want to run "*100#" it recognize the input only as "*100". How to add the "#". and what is the reason to not recognize that?

Here is my code ...

```<code>  checkBalance.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent i = new Intent(Intent.ACTION_CALL);

            i.setData(Uri.parse("tel:"+"*100#"));

            if (ActivityCompat.checkSelfPermission(mobitelPage.this,
                    Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            startActivity(i);

        }
    });
</code>```

答:
Try this code.Use Uri.encode("#"):

```<code>    String encodedHash = Uri.encode("#");
    i.setData(Uri.parse("tel:"+"*100"+encodedHash));

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    startActivity(i);
</code>```

Body:
By using an app I want to run a USSD code, but the problem is it doesn't recognize the "#" symbol.
If I want to run "*100#" it recognize the input only as "*100". How to add the "#". and what is the reason to not recognize that?

Here is my code ...

  checkBalance.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent i = new Intent(Intent.ACTION_CALL);

            i.setData(Uri.parse("tel:"+"*100#"));

            if (ActivityCompat.checkSelfPermission(mobitelPage.this,
                    Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            startActivity(i);

        }
    });

Body:
Try this code.Use Uri.encode("#"):

    String encodedHash = Uri.encode("#");
    i.setData(Uri.parse("tel:"+"*100"+encodedHash));

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    startActivity(i);


问:
Convert javascript code to c code
Is there any way to convert C code to JavaScript and from JavaScript to C? I found V8 juice which can generate JavaScript-side classes from C++, but it's only one way (C++ to JavaScript).

I'm not looking for a software.

答:
This project looks quite promising, even though it is a work in progress.

https://github.com/andrei-markeev/ts2c

You can convert JavaScript to C online here:

https://andrei-markeev.github.io/ts2c/

Title: Convert javascript code to c code


问:
TableLayout with RecyclerView
There is only two layout manager for RecyclerView: LinearLayoutManager and GridLayoutManager. Is there a way to use TableLayout as layout manager with RecyclerView? Any suggestion?

EDIT: I wonder if there is any solution without writing a layout manager from zero. TableLayout behaviour is enough for me, just want to add recycle feature for performance issues on handling large amount fo data.

And creating a table looking listview is not solve my problem I think, because my table is very dynamic, I don't know even column names, customer deciding all details of the table. So cells would be custom, column widths needs to be auto resizing depend on content length. I don't think listview can handle that.

Thanks in advance for helps.

答: Create a custom row with linearlayout and than attach that row to recyclerView Adapter this is only the solution for making a table like Structure in RecyclerView. </p>

Title: TableLayout with RecyclerView


问:
ScrollView inside an PanResponder
I am making my own implementation of a tab navigator with swiping in React-Native. It works fine, but when I have a ScrollView inside one of my tabs it seems to break. Swiping left and right to change tabs works fine, and also scrolling down and up in scrollview. It breaks when I click to drag the scrollView and then move sideways without releasing to swipe. Then the tab  system just resets to the first tab.

I made a hack where I disable swiping from inside a tab when the scrollview is scrolled. This works, but feels like a bad solution because the tab content has to be aware that it is inside a tab.

```<code>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { View, Animated, Dimensions, PanResponder } from 'react-native';
import Immutable from 'immutable';
import Tab1 from './Tab1';
import Tab2 from './Tab2';
import ScrollViewTab from './ScrollViewTab';

@connect(
    state => ({
        tabs: state.tabs
    })
)

export default class Tabs extends Component {
    static propTypes = {
        tabs: PropTypes.instanceOf(Immutable.Map).isRequired,
        dispatch: PropTypes.func.isRequired
    };
    constructor(props) {
        super(props);
        this.justLoaded = true;
        this.state = {
            left: new Animated.Value(0),
            tabs: [{ // Tabs must be in order, despite index.
                name: 'tab1',
                component: <Tab1 setTab={this.setTab} />,
                index: 0
            }, {
                name: 'tab2',
                component: <Tab2 setTab={this.setTab} />,
                index: 1
            }, {
                name: 'scrollViewTab',
                component: <ScrollViewTab setTab={this.setTab} />,
                index: 2
            }]
        };
        this.getIndex = this.getIndex.bind(this);
    }
    componentWillMount() {
        this.panResponder = PanResponder.create({
            onMoveShouldSetResponderCapture: () => true,
            onMoveShouldSetPanResponderCapture: (evt, gestureState) => {
                if (Math.abs(gestureState.dx) > 10) {
                    return true;
                }
                return false;
            },
            onPanResponderGrant: () => {
                this.state.left.setOffset(this.state.left._value);
                this.state.left.setValue(0);
            },
            onPanResponderMove: (e, gestureState) => {
                if (this.isSwipingOverLeftBorder(gestureState) ||
                    this.isSwipingOverRightBorder(gestureState)) return;
                Animated.event([null, {
                    dx: this.state.left
                }])(e, gestureState);
            },
            onPanResponderRelease: (e, gestureState) => {
                this.state.left.flattenOffset();

                if (this.isSwipingOverLeftBorder(gestureState) ||
                    this.isSwipingOverRightBorder(gestureState)) {
                    return;
                }

                Animated.timing(
                    this.state.left,
                    { toValue: this.calcX(gestureState) }
                ).start();
            }
        });
    }
    componentDidMount() {
        this.justLoaded = false;
    }
    getStyle() {
        const oldLeft = this.state.left;
        let left = 0;
        const screenWidth = Dimensions.get('window').width;
        // Set tab carouselle coordinate to match the selected tab.
        this.state.tabs.forEach((tab) => {
            if (tab.name === this.props.tabs.get('tab')) {
                left = -tab.index * screenWidth;
            }
        });

        if (this.justLoaded) {
            Animated.timing(
                this.state.left,
                { toValue: left,
                    duration: 0
                }
            ).start();

            return { transform: [{ translateX: oldLeft }], flexDirection: 'row', height: '100%' };
        }
        Animated.timing(
                this.state.left,
            { toValue: left
            }
            ).start();
        return { transform: [{ translateX: oldLeft }], flexDirection: 'row', height: '100%' };
    }
    getIndex(tabN) {
        let index = 0;

        this.state.tabs.forEach((tab) => {
            if (tab.name === tabN) {
                index = tab.index;
            }
            return tab;
        });

        return index;
    }
    setTab(tab, props) {
        this.navProps = props;
        this.props.dispatch({ type: 'SET_TAB', tab });
    }
    isSwipingOverLeftBorder(gestureState) {
        return (this.props.tabs.get('tab') === this.state.tabs[0].name &&
                gestureState.dx > 0);
    }
    isSwipingOverRightBorder(gestureState) {
        return (this.props.tabs.get('tab') === this.state.tabs[this.state.tabs.length - 1].name &&
                gestureState.dx < 0);
    }
    calcX(gestureState) {
        const screenWidth = Dimensions.get('window').width;
        const activeTab = this.getIndex(this.props.tabs.get('tab'));
        let coord = 0;

        if (gestureState.dx > screenWidth * 0.2) {
            coord = (activeTab * screenWidth) - screenWidth;
        } else if (gestureState.dx < -(screenWidth * 0.2)) {
            coord = (activeTab * screenWidth) + screenWidth;
        } else {
            coord = activeTab * screenWidth;
        }

        this.updateTab(-coord, screenWidth);

        return -coord;
    }
    updateTab(coord, screenWidth) {
        // Update current tab according to location and screenwidth
        this.state.tabs.forEach((tab) => {
            if (coord === -tab.index * screenWidth) {
                this.props.dispatch({ type: 'SET_TAB', tab: tab.name });
            }
        });
    }
    render() {
        return (
          <View
            style={{ flex: 1 }}
          >
            <Animated.View
              style={this.getStyle()}
              {...this.panResponder.panHandlers}
            >
              {this.state.tabs.map(tab => tab.component)}
            </Animated.View>
          </View>
        );
    }
}
</code>```

答:
In your view controller which is using your code block(scrollView,pan gesture) ,

write this function:

```<code>func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
   return true
}
</code>```

Hope it helps.:)

Title: ScrollView inside an PanResponder

Body:
I am making my own implementation of a tab navigator with swiping in React-Native. It works fine, but when I have a ScrollView inside one of my tabs it seems to break. Swiping left and right to change tabs works fine, and also scrolling down and up in scrollview. It breaks when I click to drag the scrollView and then move sideways without releasing to swipe. Then the tab  system just resets to the first tab.

I made a hack where I disable swiping from inside a tab when the scrollview is scrolled. This works, but feels like a bad solution because the tab content has to be aware that it is inside a tab.

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { View, Animated, Dimensions, PanResponder } from 'react-native';
import Immutable from 'immutable';
import Tab1 from './Tab1';
import Tab2 from './Tab2';
import ScrollViewTab from './ScrollViewTab';

@connect(
    state => ({
        tabs: state.tabs
    })
)

export default class Tabs extends Component {
    static propTypes = {
        tabs: PropTypes.instanceOf(Immutable.Map).isRequired,
        dispatch: PropTypes.func.isRequired
    };
    constructor(props) {
        super(props);
        this.justLoaded = true;
        this.state = {
            left: new Animated.Value(0),
            tabs: [{ // Tabs must be in order, despite index.
                name: 'tab1',
                component: <Tab1 setTab={this.setTab} />,
                index: 0
            }, {
                name: 'tab2',
                component: <Tab2 setTab={this.setTab} />,
                index: 1
            }, {
                name: 'scrollViewTab',
                component: <ScrollViewTab setTab={this.setTab} />,
                index: 2
            }]
        };
        this.getIndex = this.getIndex.bind(this);
    }
    componentWillMount() {
        this.panResponder = PanResponder.create({
            onMoveShouldSetResponderCapture: () => true,
            onMoveShouldSetPanResponderCapture: (evt, gestureState) => {
                if (Math.abs(gestureState.dx) > 10) {
                    return true;
                }
                return false;
            },
            onPanResponderGrant: () => {
                this.state.left.setOffset(this.state.left._value);
                this.state.left.setValue(0);
            },
            onPanResponderMove: (e, gestureState) => {
                if (this.isSwipingOverLeftBorder(gestureState) ||
                    this.isSwipingOverRightBorder(gestureState)) return;
                Animated.event([null, {
                    dx: this.state.left
                }])(e, gestureState);
            },
            onPanResponderRelease: (e, gestureState) => {
                this.state.left.flattenOffset();

                if (this.isSwipingOverLeftBorder(gestureState) ||
                    this.isSwipingOverRightBorder(gestureState)) {
                    return;
                }

                Animated.timing(
                    this.state.left,
                    { toValue: this.calcX(gestureState) }
                ).start();
            }
        });
    }
    componentDidMount() {
        this.justLoaded = false;
    }
    getStyle() {
        const oldLeft = this.state.left;
        let left = 0;
        const screenWidth = Dimensions.get('window').width;
        // Set tab carouselle coordinate to match the selected tab.
        this.state.tabs.forEach((tab) => {
            if (tab.name === this.props.tabs.get('tab')) {
                left = -tab.index * screenWidth;
            }
        });

        if (this.justLoaded) {
            Animated.timing(
                this.state.left,
                { toValue: left,
                    duration: 0
                }
            ).start();

            return { transform: [{ translateX: oldLeft }], flexDirection: 'row', height: '100%' };
        }
        Animated.timing(
                this.state.left,
            { toValue: left
            }
            ).start();
        return { transform: [{ translateX: oldLeft }], flexDirection: 'row', height: '100%' };
    }
    getIndex(tabN) {
        let index = 0;

        this.state.tabs.forEach((tab) => {
            if (tab.name === tabN) {
                index = tab.index;
            }
            return tab;
        });

        return index;
    }
    setTab(tab, props) {
        this.navProps = props;
        this.props.dispatch({ type: 'SET_TAB', tab });
    }
    isSwipingOverLeftBorder(gestureState) {
        return (this.props.tabs.get('tab') === this.state.tabs[0].name &&
                gestureState.dx > 0);
    }
    isSwipingOverRightBorder(gestureState) {
        return (this.props.tabs.get('tab') === this.state.tabs[this.state.tabs.length - 1].name &&
                gestureState.dx < 0);
    }
    calcX(gestureState) {
        const screenWidth = Dimensions.get('window').width;
        const activeTab = this.getIndex(this.props.tabs.get('tab'));
        let coord = 0;

        if (gestureState.dx > screenWidth * 0.2) {
            coord = (activeTab * screenWidth) - screenWidth;
        } else if (gestureState.dx < -(screenWidth * 0.2)) {
            coord = (activeTab * screenWidth) + screenWidth;
        } else {
            coord = activeTab * screenWidth;
        }

        this.updateTab(-coord, screenWidth);

        return -coord;
    }
    updateTab(coord, screenWidth) {
        // Update current tab according to location and screenwidth
        this.state.tabs.forEach((tab) => {
            if (coord === -tab.index * screenWidth) {
                this.props.dispatch({ type: 'SET_TAB', tab: tab.name });
            }
        });
    }
    render() {
        return (
          <View
            style={{ flex: 1 }}
          >
            <Animated.View
              style={this.getStyle()}
              {...this.panResponder.panHandlers}
            >
              {this.state.tabs.map(tab => tab.component)}
            </Animated.View>
          </View>
        );
    }
}

Body:
In your view controller which is using your code block(scrollView,pan gesture) ,

write this function:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
   return true
}

Hope it helps.:)


问:
Symfony : Get key value from object doctrine
I have this array of objects with doctrine,
how do i scope out one of the values?

This doesnt seem to work for me : todolist[0]->todo_body

```<code>todolist
(
    [0] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 1
        [todo_body:AppBundle\Entity\Todo:private] => Install Symfony
    )

    [1] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 2
        [todo_body:AppBundle\Entity\Todo:private] => Learn Symfony
    )

    [2] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 3
        [todo_body:AppBundle\Entity\Todo:private] => Create Controller
    )

    [3] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 4
        [todo_body:AppBundle\Entity\Todo:private] => Create first page
    )

)
</code>```

答:
Try this, but first be sure to have in your entity the getter getTodoBody:

```<code>todolist[0]->getTodoBody()
</code>```

If you don't have the getter inside TodoEntity add this:

```<code>public function getTodoBody() {
    return $this->todo_body;
}
</code>```

If you need todo_body inside your html template try this:

```<code>{{ todo.TodoId }}
</code>```

or

```<code>{{ todolist[0].todo_body }}
</code>```

Body:
I have this array of objects with doctrine,
how do i scope out one of the values?

This doesnt seem to work for me : todolist[0]->todo_body

todolist
(
    [0] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 1
        [todo_body:AppBundle\Entity\Todo:private] => Install Symfony
    )

    [1] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 2
        [todo_body:AppBundle\Entity\Todo:private] => Learn Symfony
    )

    [2] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 3
        [todo_body:AppBundle\Entity\Todo:private] => Create Controller
    )

    [3] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 4
        [todo_body:AppBundle\Entity\Todo:private] => Create first page
    )

)

Body:
Try this, but first be sure to have in your entity the getter getTodoBody:

todolist[0]->getTodoBody()

If you don't have the getter inside TodoEntity add this:

public function getTodoBody() {
    return $this->todo_body;
}

If you need todo_body inside your html template try this:

{{ todo.TodoId }}

or

{{ todolist[0].todo_body }}


问:
Can i compare two Images?
I want to compare two images each other. If that possible then give me code. I was tried that but that was a take more memory and also take huge time to compare.

Here in my device two same image available but that's url are different.So first i was convert that url to image and after that  convert into data  and compare each other.

```<code>ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
             [library assetForURL:imageUrl
                      resultBlock:^(ALAsset *asset) {
                        UIImage *image1=[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];

                          NSData *data1 = UIImageJPEGRepresentation(image1, 0.01);
                          NSData *data2 = UIImageJPEGRepresentation(image2, 0.01);

                            if ([data1 isEqualToData:data2]){
                                NSLog(@"YES");
                            }
                            else{
                                NSLog(@"NO");
                            }

                      }

                     failureBlock:^(NSError *error){
                         NSLog(@"operation was not successfull!");
                     } ];
</code>```

答:
You can compare both images using their NSData..</p>

```<code>- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2
{
    NSData *imgData1 = UIImagePNGRepresentation(image1);
    NSData *imgData2 = UIImagePNGRepresentation(image2);

    return [imgData1 isEqual:imgData2];
}
</code>```

Title: Can i compare two Images?

Body:
I want to compare two images each other. If that possible then give me code. I was tried that but that was a take more memory and also take huge time to compare.

Here in my device two same image available but that's url are different.So first i was convert that url to image and after that  convert into data  and compare each other.

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
             [library assetForURL:imageUrl
                      resultBlock:^(ALAsset *asset) {
                        UIImage *image1=[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];

                          NSData *data1 = UIImageJPEGRepresentation(image1, 0.01);
                          NSData *data2 = UIImageJPEGRepresentation(image2, 0.01);

                            if ([data1 isEqualToData:data2]){
                                NSLog(@"YES");
                            }
                            else{
                                NSLog(@"NO");
                            }

                      }

                     failureBlock:^(NSError *error){
                         NSLog(@"operation was not successfull!");
                     } ];

Body:
You can compare both images using their NSData..

- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2
{
    NSData *imgData1 = UIImagePNGRepresentation(image1);
    NSData *imgData2 = UIImagePNGRepresentation(image2);

    return [imgData1 isEqual:imgData2];
}


问:
proper javascript usage of "this"
Which of the following two ways is better to call the Color property and why? Or does it make a difference?

```<code>lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
</code>```

OR

```<code>lineSymbolizer:{strokeColor: LatLongLines.Color, strokeWidth: 2, strokeOpacity: 0.7},
</code>```

Context CODE:

```<code>var LatLongLines = {
    Graticule: null,
    Color: "#000000",
    Show: function () {
        this.Graticule.activate();
    },
    Hide: function () {
        this.Graticule.deactivate()
    },
    Initialize: function () {
        this.Graticule = new OpenLayers.Control.Graticule({
            numPoints: 2,
            labelled: true,
            lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
            labelSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7}
        });

        map.addControl(this.Graticule);
    }
};
</code>```

答:
In Javascript, this always refers to the item on the left of the dot. In this example you can see the same function scoped to two different this objects.

```<code>myObject = {
    myFunction: function() {
        console.log(this); // in FF or WebKit
    }
};

myObject.myFunction(); // this = myObject

// Now we'll store a reference to our function and call
// it without the dot notation.
myFunc = myObject.myFunction;

myFunc(); // this = window
</code>```

I'd advise using LatLongLines.Color if you are unsure of the context of this to ensure access to the Color property of LatlongLines.

Title: proper javascript usage of "this"

Body:
Which of the following two ways is better to call the Color property and why? Or does it make a difference?

lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},

OR

lineSymbolizer:{strokeColor: LatLongLines.Color, strokeWidth: 2, strokeOpacity: 0.7},

Context CODE:

var LatLongLines = {
    Graticule: null,
    Color: "#000000",
    Show: function () {
        this.Graticule.activate();
    },
    Hide: function () {
        this.Graticule.deactivate()
    },
    Initialize: function () {
        this.Graticule = new OpenLayers.Control.Graticule({
            numPoints: 2,
            labelled: true,
            lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
            labelSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7}
        });

        map.addControl(this.Graticule);
    }
};

Body:
In Javascript, this always refers to the item on the left of the dot. In this example you can see the same function scoped to two different this objects.

myObject = {
    myFunction: function() {
        console.log(this); // in FF or WebKit
    }
};

myObject.myFunction(); // this = myObject

// Now we'll store a reference to our function and call
// it without the dot notation.
myFunc = myObject.myFunction;

myFunc(); // this = window

I'd advise using LatLongLines.Color if you are unsure of the context of this to ensure access to the Color property of LatlongLines.


问:
How to pass variable in command module in ansible
i am using folloing task in YAMl file.

- name: Run deployment of RWI Artifact
  command: "{{ deploy_script }} /home/scripts/lite /application/ a-CL '--Home=/opt/AppServer --appClassLoaderMode=abc'"

but typically , i am getting following error

We could be wrong, but this one looks like it might be an issue with
  missing quotes.  Always quote template expression brackets when they
  start a value. For instance:

with_items:
       - {{ foo }}

Should be written as:

with_items:
        - "{{ foo }}"

i tried all combination but dont know how to put those quotes correctly.

please suggest

答:
In YAML if you start string with quote, it is considered as quoted string, so you must end the string with the same quote.

Try:

```<code>- name: Run deployment of RWI Artifact
  command: "{{ deploy_script }} /home/scripts/lite /application/ a-CL '--Home=/opt/AppServer --appClassLoaderMode=abc'"
</code>```

I assume that deploy_script has no spaces.

Body:
In YAML if you start string with quote, it is considered as quoted string, so you must end the string with the same quote.

Try:

- name: Run deployment of RWI Artifact
  command: "{{ deploy_script }} /home/scripts/lite /application/ a-CL '--Home=/opt/AppServer --appClassLoaderMode=abc'"

I assume that deploy_script has no spaces.


问:
Gradle Build doesnt find Java source code
I am trying to follow the HelloWorld tutorial for Gradle given by Spring but the Build step is not working - when I run Gradle Build I just see the message, NO-SOURCE for the :compileJava step.
I saw on another question that you should add the sourceSets tag into the gradle.build file. I tried this as well and it still doesnt find my Java source files.

I have organised my Java source following the instructions and
placed the code inside directory structure,

=>src-main-java-hello ("HelloWorld.java, Greeter.java").

I am using Java8 and Gradle 3.5

Can anyone help please ? - seems a really basic problem I must be having.

答:
the problem was an embarrassing Gotcha! It had nothing to do with adding the sourceSets configs....my Java files had been saved under Windows using Notepad++ as Text Document files and not Java source files no wonder Gradle was reporting No Source files !! The below screen shot shows the difference.

To avoid this issue when saving your files in Notepad++ you can either wrap the name with quotes or select the Type as a Java Program.

When I changed this and ran gradle.build it all worked fine.


问:
How to deploy Azure service fabric project on to a remote cluster(Azure)
I have Created a cluster in Azure http://******.######.cloudapp.azure.com:19080
but don't know how to deploy my service fabric project on to it.
Link to application manifest
ApplicationManifest.xml</p>

答:
Within Visual Studio, navigate to your Publish Profiles folder under the application and copy/paste the existing cloud.xml file and then rename appropriately. Ensure that you use the correct public facing I.P for your cluster, which will most likely be the load balancer.

The line should look like the following.

```<code><ClusterConnectionParameters ConnectionEndpoint="<YOUR IP>:19000" />
</code>```

Example:

```<code><ClusterConnectionParameters ConnectionEndpoint="151.41.35.35:19000" />
</code>```

However, if the cluster is secured you may need additional information. These options are shown within the commented Cluster Connection Parameters of the cloud.xml file.

Right click on the application, select publish and ensure the new publish profile is selected. Visual studio will attempt to validate the connection. Try to publish and keep an eye on the output window for insight in to the process.

Body:
Within Visual Studio, navigate to your Publish Profiles folder under the application and copy/paste the existing cloud.xml file and then rename appropriately. Ensure that you use the correct public facing I.P for your cluster, which will most likely be the load balancer.

The line should look like the following.

<ClusterConnectionParameters ConnectionEndpoint="<YOUR IP>:19000" />

Example:

<ClusterConnectionParameters ConnectionEndpoint="151.41.35.35:19000" />

However, if the cluster is secured you may need additional information. These options are shown within the commented Cluster Connection Parameters of the cloud.xml file.

Right click on the application, select publish and ensure the new publish profile is selected. Visual studio will attempt to validate the connection. Try to publish and keep an eye on the output window for insight in to the process.


问:
SSMS Copy and Paste Without Header
How do I copy and paste one record from SSMS 2012 without the header (when it comes along without me asking for it)? In SSMS, Tools -> Options -> Query Results -> SQL Server -> Results to Grid -> "Include column headers when copying or saving the results" is unchecked. Sometimes I would like to copy the header, however most of the time I would like to copy and paste one record into Excel and the header comes along uninvited - either when I do ctrl + C or just right click and "Copy". I've tried rebooting my computer to be sure it wasn't some sort of cached functionality but I can't seem to shake the header. Please help!</p>

答:
To maybe save someone else 15 mins of frustration researching this:

I just experienced this problem, which persisted after unchecking Tools -> Options -> Query Results -> SQL Server -> Results to Grid -> "Include column headers when copying or saving the results

I had to restart SSMS for the changes to take effect.

Title: SSMS Copy and Paste Without Header


问:
Iterate through Controls to find errorProviders c# WinForm
Overview of function.

I have this SaveDetails function within a WinForm, which iterates through all of the controls, to determine whether any errorProviders have been flagged in the form during the users input. If the function returns true,
all of my TextBoxes values need to be stored in my private fields, and display a messsagebox and close the form.

// For about 15 textBoxes, Could this be achieved also by looping? As this looks very cumbersome.

title = cmb_Title.Text;
```
<p>If <code>returns false</code> and an <code>errorProvider</code> has been found in the iteration, it needs to display an error message for the user, clear private fields and give the user chance to re-enter details, however not clear textBoxes!!</p>
<p><strong>Issue</strong>:</p>
<p>the loop iterates through everything, all of the controls regardless if it has found an <code>errorProvider</code>. How can I stop this to just flag when just one has been found? This function is also in a <code>clickEvent</code>.</p>
<p><strong>Code</strong></p>
<pre class="lang-cs prettyprint-override"><code>isValid = true;
foreach (Control c in panel1.Controls)
{
    if (errorProvider1.GetError(c).Length > 0)
    {
        isValid = false;
        MessageBox.Show("invalid entry, please revisit the form before proceding");
    }
}
if (isValid)
{
    title = cmb_Title.Text;
    surName = txt_SurName.Text;
    dateOfBirth = dateTimePicker1.Text.ToString();

    MessageBox.Show("Indi Form Saved");
    Hide();
}
</code>```

答:
you can shorten it using only TextBox controls and Linq.

Something like this:

```<code>List<TextBox> textBoxes = panel1.Controls.OfType<TextBox>().ToList();
if (textBoxes.Any(tb => !string.IsNullOrEmpty(errorProvider1.GetError(tb))))
    MessageBox.Show("invalid entry, please revisit the form before proceding");
</code>```

If you don't want to check only TextBox controls but all controls in panel1, you can still use Linq to simplify your code.

```<code>var controlsList = panel1.Controls.Cast<Control>().ToList();
if (controlsList.Any(tb => !string.IsNullOrEmpty(errorProvider1.GetError(tb))))
    MessageBox.Show("invalid entry, please revisit the form before proceding");
</code>```

Body:
Overview of function.

I have this SaveDetails function within a WinForm, which iterates through all of the controls, to determine whether any errorProviders have been flagged in the form during the users input. If the function returns true,
all of my TextBoxes values need to be stored in my private fields, and display a messsagebox and close the form.

// For about 15 textBoxes, Could this be achieved also by looping? As this looks very cumbersome.

title = cmb_Title.Text;

If returns false and an errorProvider has been found in the iteration, it needs to display an error message for the user, clear private fields and give the user chance to re-enter details, however not clear textBoxes!!

Issue:

the loop iterates through everything, all of the controls regardless if it has found an errorProvider. How can I stop this to just flag when just one has been found? This function is also in a clickEvent.

Code

isValid = true;
foreach (Control c in panel1.Controls)
{
    if (errorProvider1.GetError(c).Length > 0)
    {
        isValid = false;
        MessageBox.Show("invalid entry, please revisit the form before proceding");
    }
}
if (isValid)
{
    title = cmb_Title.Text;
    surName = txt_SurName.Text;
    dateOfBirth = dateTimePicker1.Text.ToString();

    MessageBox.Show("Indi Form Saved");
    Hide();
}

Body:
you can shorten it using only TextBox controls and Linq.

Something like this:

List<TextBox> textBoxes = panel1.Controls.OfType<TextBox>().ToList();
if (textBoxes.Any(tb => !string.IsNullOrEmpty(errorProvider1.GetError(tb))))
    MessageBox.Show("invalid entry, please revisit the form before proceding");

If you don't want to check only TextBox controls but all controls in panel1, you can still use Linq to simplify your code.

var controlsList = panel1.Controls.Cast<Control>().ToList();
if (controlsList.Any(tb => !string.IsNullOrEmpty(errorProvider1.GetError(tb))))
    MessageBox.Show("invalid entry, please revisit the form before proceding");


问:
ng-repeat is not showing data.... error(angular.min.js:123 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.6.4/ngRepeat/dupes?
I am using ng-repeat in the option tag to generation multiple options.
but it is not working properly.

//Below is my Angular js code

```<code>      $http.get("assign_leads_1.php?dummydata=2").then(function (response)
        {
            alert(response.data);
            $scope.bdes = response.data;
        });

Below is the html code
<div class="form-group">
                <label>Assign To: </label>
<select ng-model="bde_tuid" class="form-control">
                <option  ng-repeat="bde in bdes" value="{{bde.tuid}}" >
                    {{bde.xyz}}
                </option>
            </select>
</code>```

// Below is the php code for fetching data from database

```<code>    require_once 'dbcon.php';
    $query ="select tuid,username as xyz from tuser where category
 ='employee'";
    $result=  mysqli_query($link, $query);
    $data = array();
    while($row = mysqli_fetch_array($result))
    {
        $data[]=$row;
    }

    print json_encode($data);
    }
</code>```

答:
change this line

```<code><option  ng-repeat="bde in bdes" value="{{bde.tuid}}" >
</code>```

to

```<code><option  ng-repeat="bde in bdes track by $index" value="{{bde.tuid}}" >
</code>```

Body:
I am using ng-repeat in the option tag to generation multiple options.
but it is not working properly.

//Below is my Angular js code

      $http.get("assign_leads_1.php?dummydata=2").then(function (response)
        {
            alert(response.data);
            $scope.bdes = response.data;
        });

Below is the html code

                Assign To:
<select ng-model="bde_tuid" class="form-control">
                <option  ng-repeat="bde in bdes" value="{{bde.tuid}}" >
                    {{bde.xyz}}
                </option>
            </select>

// Below is the php code for fetching data from database

    require_once 'dbcon.php';
    $query ="select tuid,username as xyz from tuser where category
 ='employee'";
    $result=  mysqli_query($link, $query);
    $data = array();
    while($row = mysqli_fetch_array($result))
    {
        $data[]=$row;
    }

    print json_encode($data);
    }

Body:
change this line

<option  ng-repeat="bde in bdes" value="{{bde.tuid}}" >

to

<option  ng-repeat="bde in bdes track by $index" value="{{bde.tuid}}" >


问:
Magento - get the custom attribute value for products in an external PHP script
does anyone know how I can get the custom attribute value for products in an PHP script (that we have in he root of the server which is used to generate XML an feed) ?

The custom attribute is property_type. Others work but not that one. Here is the code:

```<code>foreach ($arrayObj  as $row ) {
//get data
$pro_item = getPropertyItem($row['entity_id'],$pdo);
$images = getImages($row['entity_id'],$pdo);
$term = getTerm($row['entity_id'],$pdo);
$local=getLocation($row['entity_id'],$pdo);
// create tags and data
$item = $xml->createElement('item');
$i_status = $xml->createElement('status',getStatus($row['entity_id'],$pdo));
$i_propertyType = $xml->createElement('propertyType',$row['property_type']);
$i_title = $xml->createElement('title',htmlentities(removeAt($pro_item['title'])));

$i_projectName = $xml->createElement('projectName',getBuilding($local,$pro_item['title']));

$i_description = $xml->createElement('description',htmlentities(removeAt($pro_item['description'])));
</code>```

答:
My be below code will help you..!

```<code>$productId = 'YOUR PRODUCT ID';
$_product= Mage::getSingleton('catalog/product')->load($productId);
echo $_product->getResource()->getAttribute('attribute_code')->getFrontend()->getValue($_product);
</code>```

Please try this one.

Body:
does anyone know how I can get the custom attribute value for products in an PHP script (that we have in he root of the server which is used to generate XML an feed) ?

The custom attribute is property_type. Others work but not that one. Here is the code:

foreach ($arrayObj  as $row ) {
//get data
$pro_item = getPropertyItem($row['entity_id'],$pdo);
$images = getImages($row['entity_id'],$pdo);
$term = getTerm($row['entity_id'],$pdo);
$local=getLocation($row['entity_id'],$pdo);
// create tags and data
$item = $xml->createElement('item');
$i_status = $xml->createElement('status',getStatus($row['entity_id'],$pdo));
$i_propertyType = $xml->createElement('propertyType',$row['property_type']);
$i_title = $xml->createElement('title',htmlentities(removeAt($pro_item['title'])));

$i_projectName = $xml->createElement('projectName',getBuilding($local,$pro_item['title']));

$i_description = $xml->createElement('description',htmlentities(removeAt($pro_item['description'])));

Body:
My be below code will help you..!

$productId = 'YOUR PRODUCT ID';
$_product= Mage::getSingleton('catalog/product')->load($productId);
echo $_product->getResource()->getAttribute('attribute_code')->getFrontend()->getValue($_product);

Please try this one.


问:
How to add JTable in JPanel with null layout?
I want to add JTable into JPanel whose layout is null.  JPanel contains other components. I have to add JTable at proper position.

答:
First, you should seriously consider other Layout managers, for example the BorderLayoutManager (new JPanel(new BorderLayout())) is a good start.

Also when designing your dialog, remember that you can and should nest your layouts: one JPanel inside another JPanel (e.g. a GridLayout inside a BorderLayout). Please note: a 'good' dialog should resize properly, so that if the user resizes your Frame, you want to automatically extend your information objects such as your table, and not show large areas of JPanel background. That's something you cannot achieve with a NullLayout.

But there are probably cases - somewhere in this big world - where a NullLayout is just the thing. So here's an example:

```<code>import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class JTableInNullLayout
{
  public static void main(String[] argv) throws Exception {

      DefaultTableModel model = new DefaultTableModel(
          new String[][] { { "a", "123"} , {"b", "456"} },
          new String[] { "name", "value" } );

      JTable t = new JTable(model);

      JPanel panel = new JPanel(null);

      JScrollPane scroll = new JScrollPane(t);
      scroll.setBounds( 0, 20, 150, 100 ); // x, y, width, height
      panel.add(scroll);

      JFrame frame = new JFrame();
      frame.add(panel);
      frame.setPreferredSize( new Dimension(200,200));
      frame.pack();
      frame.setVisible(true);
  }
}
</code>```

Body:
First, you should seriously consider other Layout managers, for example the BorderLayoutManager (new JPanel(new BorderLayout())) is a good start.

Also when designing your dialog, remember that you can and should nest your layouts: one JPanel inside another JPanel (e.g. a GridLayout inside a BorderLayout). Please note: a 'good' dialog should resize properly, so that if the user resizes your Frame, you want to automatically extend your information objects such as your table, and not show large areas of JPanel background. That's something you cannot achieve with a NullLayout.

But there are probably cases - somewhere in this big world - where a NullLayout is just the thing. So here's an example:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class JTableInNullLayout
{
  public static void main(String[] argv) throws Exception {

      DefaultTableModel model = new DefaultTableModel(
          new String[][] { { "a", "123"} , {"b", "456"} },
          new String[] { "name", "value" } );

      JTable t = new JTable(model);

      JPanel panel = new JPanel(null);

      JScrollPane scroll = new JScrollPane(t);
      scroll.setBounds( 0, 20, 150, 100 ); // x, y, width, height
      panel.add(scroll);

      JFrame frame = new JFrame();
      frame.add(panel);
      frame.setPreferredSize( new Dimension(200,200));
      frame.pack();
      frame.setVisible(true);
  }
}


问:
Hosting multiple site on apache server in windows 2012 server
I am trying to host two sites on apache 2.4 server which is running in windows 2012 server. I have added vhost entries for two sites one running on 80 and other on 8080.

Sample vhost entries:

```<code><VirtualHost *:80>
  DocumentRoot "/www/example1"
  ServerName www.example.com
</VirtualHost>

<VirtualHost *:8080>
  DocumentRoot "/www/example2"
  ServerName www.example2.com
</VirtualHost>
</code>```

With this configuration both the domain points to site running on port 8080. Considering above sample, sites opens same code in directory /www/example1 on both www.example.com and www.example2.com domains.

But if I access site with I.P. like http://198.21.22.1:80 and http://198.21.22.1:8080 the sites work fine but through domains it does not.

We have a load balancer in between which point to the actual server.

Need to know what configurations or setting if any I have missed.

I have added Listen entries for 80 and 8080 in httpd.conf file.

UPDATE

On further analysis I found that, from different systems different version of site opens up. Example, from my system both the domain opens up code running from /www/example1, but from my mobile client it opens up code running from /www/example2 for both domains.

So, I checked from some other system and found that it opens code running from /www/example1 for both domains and again from some other system it opens up code running from /www/example2 for both domains.

We have a load balancer in between which redirects to the http server on which /www/example1 and /www/example2 are present. Currently I do not have access to this load balancer, but can load balancer be cause of this issue?

Thanks,
Uday

答:
I just added virtualhost entries with same port 80 for both sites with different servername. </p>

<p>Issue was with tow systems being present had to make changes on both server in the load balance cluster. </p>

Body:
I am trying to host two sites on apache 2.4 server which is running in windows 2012 server. I have added vhost entries for two sites one running on 80 and other on 8080.

Sample vhost entries:

<VirtualHost *:80>
  DocumentRoot "/www/example1"
  ServerName www.example.com
</VirtualHost>

<VirtualHost *:8080>
  DocumentRoot "/www/example2"
  ServerName www.example2.com
</VirtualHost>

With this configuration both the domain points to site running on port 8080. Considering above sample, sites opens same code in directory /www/example1 on both www.example.com and www.example2.com domains.

But if I access site with I.P. like http://198.21.22.1:80 and http://198.21.22.1:8080 the sites work fine but through domains it does not.

We have a load balancer in between which point to the actual server.

Need to know what configurations or setting if any I have missed.

I have added Listen entries for 80 and 8080 in httpd.conf file.

UPDATE

On further analysis I found that, from different systems different version of site opens up. Example, from my system both the domain opens up code running from /www/example1, but from my mobile client it opens up code running from /www/example2 for both domains.

So, I checked from some other system and found that it opens code running from /www/example1 for both domains and again from some other system it opens up code running from /www/example2 for both domains.

We have a load balancer in between which redirects to the http server on which /www/example1 and /www/example2 are present. Currently I do not have access to this load balancer, but can load balancer be cause of this issue?

Thanks,
Uday

Body:
I just added virtualhost entries with same port 80 for both sites with different servername.

Issue was with tow systems being present had to make changes on both server in the load balance cluster.


问:
Error with create tables in sqlite3 in editor
I am creating table in my database. I am also inserting values into that table. So I am running the .py file in terminal it is not printing the inserted values. Its working in shell but with editor it doesn't ? I am writing this code to create table:

```<code>import sqlite3

conn = sqlite3.connect('raman.db')

c = conn.cursor()

c.execute("CREATE table raman(ATOMIC NUMBER INT, SYMBOL TEXT, ROW INT , COLUMN INT)")

c.execute("INSERT INTO raman VALUES(1,'H',1,'1')");

conn.commit()
</code>```

Now if i want to print those inserted values it doesn't work in editor. but with shell its working. i am writing this to print :

```<code>import sqlite3

conn = sqlite3.connect('raman.db')

c = conn.cursor()

for row in c.execute('SELECT * FROM raman'):

       conn.commit()
</code>```

答:
The python command-line shell prints out the value of everything you enter, but that is just intended for debugging.

To actually print something, use print:

```<code>for row in c.execute('SELECT * FROM raman'):
    print row
</code>```

(And you might want to extract the four values from the row and format them differently.)

Body:
I am creating table in my database. I am also inserting values into that table. So I am running the .py file in terminal it is not printing the inserted values. Its working in shell but with editor it doesn't ? I am writing this code to create table:

import sqlite3

conn = sqlite3.connect('raman.db')

c = conn.cursor()

c.execute("CREATE table raman(ATOMIC NUMBER INT, SYMBOL TEXT, ROW INT , COLUMN INT)")

c.execute("INSERT INTO raman VALUES(1,'H',1,'1')");

conn.commit()

Now if i want to print those inserted values it doesn't work in editor. but with shell its working. i am writing this to print :

import sqlite3

conn = sqlite3.connect('raman.db')

c = conn.cursor()

for row in c.execute('SELECT * FROM raman'):

       conn.commit()

Body:
The python command-line shell prints out the value of everything you enter, but that is just intended for debugging.

To actually print something, use print:

for row in c.execute('SELECT * FROM raman'):
    print row

(And you might want to extract the four values from the row and format them differently.)


问:
CSS vertical Menu - Menu Item Goes to no-hover state on sub-menu hover
when i go to an submenu item on... the Item from the main menu goes to no-hover state.. i want it to stay in hover state if i am on its sub-menu...

take a look at my code here

what i am doing wrong

答:
I haven't tried it out, but it should work, if you define the :hover on the li instead of a (however that won't work in IE6).

So instead of

```<code>a:hover { ... }
</code>```

use

```<code>li:hover a { ... }
</code>```

Body:
I haven't tried it out, but it should work, if you define the :hover on the li instead of a (however that won't work in IE6).

So instead of

a:hover { ... }

use

li:hover a { ... }