问:
Swinject inject self's property into new UIViewController
Let's pretend we have an UITableViewController that on didSelectRowAtSection loads an instance of a class named i.e.: ClassToInject and it wants to inject it through a property injection because our ViewControllerToBePushed has a property of ClassToInject, that subsequently (because it's an UITabBarViewController) on the didSet callback it searches for all its viewControllers property that conforms to ClassToInjectPresentable simple as:

```<code>protocol ClassToInjectPresentable {
  var property: ClassToInject { get set }
}
</code>```

Until now, i would just do something like this:

```<code>func didSelectRowAtIndexPath {
     let classToInject = self.loadClassToInjectFor(indexPath)
     let tabBarViewController = SomeTabBarViewController()
     tabBarViewController.property = classToInject
     self.navigationController.push(tabBarViewController, animated: true)
}
</code>```

And in SomeTabBarViewController ...

```<code>class SomeTabBarViewController: ClassToInjectPresentable {
  var property: ClassToInject? {
  didSet(newValue) {
      self.viewControllers.filter{ $0 is ClassToInjectPresentable }.map{ $0 as! ClassToInjectPresentable }.forEach{ $0.property = newValue }
  }
 }
</code>```

And everything should be get loaded nice and easy (but it's not). I've read about Swinject and this might be solved with it. I have seen lots of examples registering things like:

```<code>container.register(Animal.self) { _ in Cat(name: "Mimi") }
</code>```

But I don't know if I can register some property that is loaded in self:

```<code>container.register(ClassToInjectInjector.self) { _ in
self.loadClassToInjectFor(indexPath) }
// And then
container.register(ClassToInjectPresentable.self) { _ in
SomeTabBarViewController() }
    .initCompleted { r, p in
        let tabBar = p as! SomeTabBarViewController
        tabBar.property = r.resolve(ClassToInjectInjector.self)
        // And lastly?
        self.navigationController.pushViewController(tabBar, animated: true)
    }
}
</code>```

答:
Finally I got the final answer by following the suggestions proposed.

```<code>public class Containers {
    fileprivate init() { }
}

extension Containers {
    static let activityPresentableContainer: Container = {
        let container = Container()
        container.register(ActivityTabBarController.self) { (r: Resolver, arg1: Activity) in
            return ActivityTabBarController(activity: arg1)
        }
        container.register(ActivityPresentable.self) {
           (r: Resolver, arg1: ActivityPresentableTabs, arg2: Activity) in
           switch arg1 {
           case .summary:
               return ActivitySummaryViewController(activity: arg2)
           case .detail:
               return ActivityDetailPageViewController(activity: arg2)
           case .map:
               return ActivityMapViewController(activity: arg2)
           case .charts:
               return ActivityChartsViewController(activity: arg2)
           case .strava:
              return ActivityStravaViewController(activity: arg2)
           }
        }.inObjectScope(.transient)
       return container
    }()
</code>```

With this approach, the named ActivityTabBarController gets instantiated always by the activityPresentableContainer using the following statement:

```<code>let controller = Containers.activityPresentableContainer.resolve(
    ActivityTabBarController.self, argument: activity
)!
</code>```

And then, each of the tabs inside the TabBarController gets instantiated using the required argument Activity and the type of tab itself using a .transient context. It resolves like this:

```<code>let activitySummary = Containers.activityPresentableContainer.resolve(
   ActivityPresentable.self, arguments: ActivityPresentableTabs.summary, activity!
) as! UIViewController
</code>```

This way I can generalize the tabs of the tab bar depending just on the information that they're using. If one of the tabs change in any moment, I can just change the registration, following the ActivityPresentable protocol.

Body:
Let's pretend we have an UITableViewController that on didSelectRowAtSection loads an instance of a class named i.e.: ClassToInject and it wants to inject it through a property injection because our ViewControllerToBePushed has a property of ClassToInject, that subsequently (because it's an UITabBarViewController) on the didSet callback it searches for all its viewControllers property that conforms to ClassToInjectPresentable simple as:

protocol ClassToInjectPresentable {
  var property: ClassToInject { get set }
}

Until now, i would just do something like this:

func didSelectRowAtIndexPath {
     let classToInject = self.loadClassToInjectFor(indexPath)
     let tabBarViewController = SomeTabBarViewController()
     tabBarViewController.property = classToInject
     self.navigationController.push(tabBarViewController, animated: true)
}

And in SomeTabBarViewController ...

class SomeTabBarViewController: ClassToInjectPresentable {
  var property: ClassToInject? {
  didSet(newValue) {
      self.viewControllers.filter{ $0 is ClassToInjectPresentable }.map{ $0 as! ClassToInjectPresentable }.forEach{ $0.property = newValue }
  }
 }

And everything should be get loaded nice and easy (but it's not). I've read about Swinject and this might be solved with it. I have seen lots of examples registering things like:

container.register(Animal.self) { _ in Cat(name: "Mimi") }

But I don't know if I can register some property that is loaded in self:

container.register(ClassToInjectInjector.self) { _ in
self.loadClassToInjectFor(indexPath) }
// And then
container.register(ClassToInjectPresentable.self) { _ in
SomeTabBarViewController() }
    .initCompleted { r, p in
        let tabBar = p as! SomeTabBarViewController
        tabBar.property = r.resolve(ClassToInjectInjector.self)
        // And lastly?
        self.navigationController.pushViewController(tabBar, animated: true)
    }
}

Body:
Finally I got the final answer by following the suggestions proposed.

public class Containers {
    fileprivate init() { }
}

extension Containers {
    static let activityPresentableContainer: Container = {
        let container = Container()
        container.register(ActivityTabBarController.self) { (r: Resolver, arg1: Activity) in
            return ActivityTabBarController(activity: arg1)
        }
        container.register(ActivityPresentable.self) {
           (r: Resolver, arg1: ActivityPresentableTabs, arg2: Activity) in
           switch arg1 {
           case .summary:
               return ActivitySummaryViewController(activity: arg2)
           case .detail:
               return ActivityDetailPageViewController(activity: arg2)
           case .map:
               return ActivityMapViewController(activity: arg2)
           case .charts:
               return ActivityChartsViewController(activity: arg2)
           case .strava:
              return ActivityStravaViewController(activity: arg2)
           }
        }.inObjectScope(.transient)
       return container
    }()

With this approach, the named ActivityTabBarController gets instantiated always by the activityPresentableContainer using the following statement:

let controller = Containers.activityPresentableContainer.resolve(
    ActivityTabBarController.self, argument: activity
)!

And then, each of the tabs inside the TabBarController gets instantiated using the required argument Activity and the type of tab itself using a .transient context. It resolves like this:

let activitySummary = Containers.activityPresentableContainer.resolve(
   ActivityPresentable.self, arguments: ActivityPresentableTabs.summary, activity!
) as! UIViewController

This way I can generalize the tabs of the tab bar depending just on the information that they're using. If one of the tabs change in any moment, I can just change the registration, following the ActivityPresentable protocol.


来源: stackexchange

问:
Dynamic Class creation and access class properties c#
I want to create a class dynamically and add properties to that class dynamically
and after that I want to create a object of that class and Generic list of that class and access it something like this :

答:
If you simply want the data in an undefined format, you could use Dictionary

Ex:

Dictionary < string, object > param = new Dictionary< string, object>();

param.Add("msg", "hello");

param.Add("number", 1234);

Later could be accessible as:

param["msg"] as string

param["number"] as int

ContentLicense: CC BY-SA 3.0


问:
Sharing a gorilla/mux router across packages
I'm having some issues with implementing a slight MVC design with gorilla/mux.

The layout of the modules is as follows:

```<code>main.go
-- controllers
---- base.controller.go
---- example.controller.go
-- models
---- base.model.go
---- example.controller.go
</code>```

All the files in controllers is in the controllers package, same with models and then the main.go is the main package.

Currently I'm just trying to get the Base Controller to be able to be shared with the main package which is working, although it's throwing some errors when trying to implement routes. The build is not throwing any errors, but the routes are not available. If I implement the Walk function in the Gorilla/Mux documentation to print out all the registered routes for the mux.Router then it gives me this error:

&{%!!(MISSING)s(*mux.Router=&{  [0xc4200901b0] map[] true
  false false false}) %!!(MISSING)s(http.HandlerFunc=0xc8df0)
  [%!!(MISSING)s(*mux.routeRegexp=&{/ false false true false
  0xc420095360 / [] []})] %!!(MISSING)s(*mux.routeRegexpGroup=&{
  0xc420016240 []}) %!!(MISSING)s(bool=true) %!!(MISSING)s(bool=false)
  %!!(MISSING)s(bool=false)  %!!(MISSING)s(bool=false)
  %!!(MISSING)s(mux.BuildVarsFunc=)}

The reasoning for the global var V1Router *mux.Router is firstly to access it in the main package and also to create subrouters in the other controllers.

I am fairly new to Go, but I'm trying my best to learn the best practices! Any help would be greatly appreciated!

Example code below:

base.controllers.go

```<code>package controllers

import (
        "fmt"
        "bytes"
        "net/http"
        "github.com/gorilla/mux"
)

var V1Router *mux.Router

func init () {
    V1Router = mux.NewRouter()
    V1Router.StrictSlash(true)
    V1Router.HandleFunc("/", BaseHandler)
}

// Base route to access the API Documentation.
func BaseHandler (w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, Gophers!")
}
</code>```

main.go

```<code>package main

import (
    "net/http"
    "log"
    "github.com/projectrepo/project/models"
    "github.com/projectrepo/project/controllers"
    "github.com/gorilla/mux"
)

func main () {
    http.Handle("/v1", controllers.V1Router)
    if err := http.ListenAndServe(":8000", nil); err != nil {
        log.Fatal("Serving error.")
    }
}
</code>```

In response to the comments, I tried this solution with the same result:

```<code>package main

import (
    "net/http"
    "log"
    "github.com/projectrepo/project/models"
    "github.com/projectrepo/project/controllers"
    "github.com/gorilla/mux"
)

func main () {
    r := mux.NewRouter()
    r.Handle("/v1", controllers.V1Router)
    if err := http.ListenAndServe(":8000", r); err != nil {
        log.Fatal("Serving error.")
    }
}
</code>```

答:
Gorilla mux.Router is supposed to be used to create mapping between a set of predefined rules (e.g. host, path, protocol, scheme, etc...) and it's handler (http.Handler or http.HandlerFunc). Gorilla mux can be used to replace standard server mux. If you combine gorilla/mux with built in http server mux as your original question, i.e.

```<code>func main () {
    http.Handle("/v1", controllers.V1Router)
    if err := http.ListenAndServe(":8000", nil); err != nil {
        log.Fatal("Serving error.")
    }
}
</code>```

what actually happen when a client access /v1 is controllers.V1Router will be called with request path /v1 passed to V1Router1. In the controllers.V1Router, you defined that / will be handled by BaseHandler. However, since incoming request path is /v1, it won't match to your routing table. If you want to define sub routing, you can do as follows (this is what I mean in first comment):

```<code>func main () {
    r := mux.NewRouter()
    v1 := r.PathPrefix("/v1").Subrouter()
    controllers.RegisterHandlers(v1)

    if err := http.ListenAndServe(":8000", r); err != nil {
        log.Fatal("Serving error.")
    }
}
</code>```

Then in the controllers (base.controllers.go) define

```<code>//Register handlers and it's sub router
func RegisterHandlers(r *mux.Router) {
    //base handler, i.e. /v1
    r.StrictSlash(true)
    r.HandleFunc("/", BaseHandler)

    //example sub-router, i.e. /v1/example
    ex := r.PathPrefix("/example").Subrouter()
    ex.HandleFunc("/", ExampleHandler)

    //other handlers...
}
</code>```

Body:
I'm having some issues with implementing a slight MVC design with gorilla/mux.

The layout of the modules is as follows:

main.go
-- controllers
---- base.controller.go
---- example.controller.go
-- models
---- base.model.go
---- example.controller.go

All the files in controllers is in the controllers package, same with models and then the main.go is the main package.

Currently I'm just trying to get the Base Controller to be able to be shared with the main package which is working, although it's throwing some errors when trying to implement routes. The build is not throwing any errors, but the routes are not available. If I implement the Walk function in the Gorilla/Mux documentation to print out all the registered routes for the mux.Router then it gives me this error:

&{%!!(MISSING)s(*mux.Router=&{  [0xc4200901b0] map[] true
  false false false}) %!!(MISSING)s(http.HandlerFunc=0xc8df0)
  [%!!(MISSING)s(*mux.routeRegexp=&{/ false false true false
  0xc420095360 / [] []})] %!!(MISSING)s(*mux.routeRegexpGroup=&{
  0xc420016240 []}) %!!(MISSING)s(bool=true) %!!(MISSING)s(bool=false)
  %!!(MISSING)s(bool=false)  %!!(MISSING)s(bool=false)
  %!!(MISSING)s(mux.BuildVarsFunc=)}

The reasoning for the global var V1Router *mux.Router is firstly to access it in the main package and also to create subrouters in the other controllers.

I am fairly new to Go, but I'm trying my best to learn the best practices! Any help would be greatly appreciated!

Example code below:

base.controllers.go

package controllers

import (
        "fmt"
        "bytes"
        "net/http"
        "github.com/gorilla/mux"
)

var V1Router *mux.Router

func init () {
    V1Router = mux.NewRouter()
    V1Router.StrictSlash(true)
    V1Router.HandleFunc("/", BaseHandler)
}

// Base route to access the API Documentation.
func BaseHandler (w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, Gophers!")
}

main.go

package main

import (
    "net/http"
    "log"
    "github.com/projectrepo/project/models"
    "github.com/projectrepo/project/controllers"
    "github.com/gorilla/mux"
)

func main () {
    http.Handle("/v1", controllers.V1Router)
    if err := http.ListenAndServe(":8000", nil); err != nil {
        log.Fatal("Serving error.")
    }
}

In response to the comments, I tried this solution with the same result:

package main

import (
    "net/http"
    "log"
    "github.com/projectrepo/project/models"
    "github.com/projectrepo/project/controllers"
    "github.com/gorilla/mux"
)

func main () {
    r := mux.NewRouter()
    r.Handle("/v1", controllers.V1Router)
    if err := http.ListenAndServe(":8000", r); err != nil {
        log.Fatal("Serving error.")
    }
}

Body:
Gorilla mux.Router is supposed to be used to create mapping between a set of predefined rules (e.g. host, path, protocol, scheme, etc...) and it's handler (http.Handler or http.HandlerFunc). Gorilla mux can be used to replace standard server mux. If you combine gorilla/mux with built in http server mux as your original question, i.e.

func main () {
    http.Handle("/v1", controllers.V1Router)
    if err := http.ListenAndServe(":8000", nil); err != nil {
        log.Fatal("Serving error.")
    }
}

what actually happen when a client access /v1 is controllers.V1Router will be called with request path /v1 passed to V1Router1. In the controllers.V1Router, you defined that / will be handled by BaseHandler. However, since incoming request path is /v1, it won't match to your routing table. If you want to define sub routing, you can do as follows (this is what I mean in first comment):

func main () {
    r := mux.NewRouter()
    v1 := r.PathPrefix("/v1").Subrouter()
    controllers.RegisterHandlers(v1)

    if err := http.ListenAndServe(":8000", r); err != nil {
        log.Fatal("Serving error.")
    }
}

Then in the controllers (base.controllers.go) define

//Register handlers and it's sub router
func RegisterHandlers(r *mux.Router) {
    //base handler, i.e. /v1
    r.StrictSlash(true)
    r.HandleFunc("/", BaseHandler)

    //example sub-router, i.e. /v1/example
    ex := r.PathPrefix("/example").Subrouter()
    ex.HandleFunc("/", ExampleHandler)

    //other handlers...
}


问:
Laravel clicking on link adds to url
Okay I have a small problem.

When user clicks on a link it goes to website/create/business which is fine however if nothing is done but the link is clicked again, it goes to website/create/business/create/business for whatever reason.

```<code><li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
        {{ Auth::user()->name }} <span class="caret"></span>
    </a>
    <ul class="dropdown-menu" role="menu">
        <li>
            <a href="profile/{{Auth::user()->id}}">Profile</a>
            <a href="create/business/">Add Business</a>
            <a href="{{ url('/logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                Logout
            </a>
            <form id="logout-form" <a href="{{ url('home') }}" action="{{ url('/logout') }}" method="POST" style="display: none;">
                {{ csrf_field() }}
            </form>
        </li>
    </ul>
</li>
</code>```

Routes:

```<code>Route::get('profile/{user_id}', 'ProfileController@checkid');
Route::post('update', 'ProfileController@updateProfile');
Route::get('create/business', 'BusinessController@addBusiness');
Route::post('create', 'BusinessController@createBusiness');
</code>```

ProfileController:

```<code>public function checkid($user_id) {
    if (Auth::check())
    {
        $user_id = Auth::id();
        return view('profile', [
            'id' => $user_id
        ]);
    }
}
function updateProfile(Request $request) {
    $user = $request->user();
    $twitter = $request->input('twitter');
    $facebook = $request->input('facebook');
    $instagram = $request->input('instagram');
    $telephone = $request->input('telephone');
    $user->twitter_personal = $twitter;
    $user->facebook_personal = $facebook;
    $user->instagram_personal = $instagram;
    $user->telephone = $telephone;
    $result = $user->save();
    if($result) {
        $message = 'success';
    }else{
        $message = 'error';
    }
   return redirect()->back()->withInput()->with('message', $message);
}
</code>```

BusinessController:

```<code>function addBusiness() {
    return view('addBusiness');
}

function createBusiness(Request $request) {
    $name = $request->input('name');
    $type = $request->input('type');
    $email = $request->input('email');
    $user_id = Auth::id();
    $business = new Business();
    $business->name = $name;
    $business->type = $type;
    $business->email = $email;
    $business->user_id = $user_id;
    $business->save();
    $address1 = $request->input('address1');
    $address2 = $request->input('address2');
    $town = $request->input('town');
    $city = $request->input('city');
    $postcode = $request->input('postcode');
    $telephone = $request->input('telephone');
    $address = new Address();
    $address->firstline_address = $address1;
    $address->secondline_address = $address2;
    $address->town = $town;
    $address->city = $city;
    $address->postcode = $postcode;
    $address->telephone = $telephone;
    $address->save();
    $result = $business->save();
    $result2 = $address->save();

    $business_id = $business->id;
    $address_id = $address->id;
    DB::table('business_address')->insert(array('business_id' =>  $business_id, 'address_id' => $address_id));
    DB::table('user_business')->insert(array('user_id' => $user_id, 'business_id' => $business_id));

    if($result && $result2) {
        $message = 'success';
    }else{
        $message = 'error';
    }
    return redirect()->back()->withInput()->with('message', $message);
}
</code>```

答:
Try to use the route() function. For this example: Add Business. When your route changes it is automatically changed throughout the application.

You can name your routes like this:

```<code>Route::get('create/bussiness', [
    'as' => 'my_route_name',
    'uses' => 'BusinessController@createBusiness'
]);
</code>```

Title: Laravel clicking on link adds to url

Body:
Okay I have a small problem.

When user clicks on a link it goes to website/create/business which is fine however if nothing is done but the link is clicked again, it goes to website/create/business/create/business for whatever reason.

        {{ Auth::user()->name }}

            id}}">Profile
            Add Business

                Logout

            <form id="logout-form"
                {{ csrf_field() }}
            </form>

Routes:

Route::get('profile/{user_id}', 'ProfileController@checkid');
Route::post('update', 'ProfileController@updateProfile');
Route::get('create/business', 'BusinessController@addBusiness');
Route::post('create', 'BusinessController@createBusiness');

ProfileController:

public function checkid($user_id) {
    if (Auth::check())
    {
        $user_id = Auth::id();
        return view('profile', [
            'id' => $user_id
        ]);
    }
}
function updateProfile(Request $request) {
    $user = $request->user();
    $twitter = $request->input('twitter');
    $facebook = $request->input('facebook');
    $instagram = $request->input('instagram');
    $telephone = $request->input('telephone');
    $user->twitter_personal = $twitter;
    $user->facebook_personal = $facebook;
    $user->instagram_personal = $instagram;
    $user->telephone = $telephone;
    $result = $user->save();
    if($result) {
        $message = 'success';
    }else{
        $message = 'error';
    }
   return redirect()->back()->withInput()->with('message', $message);
}

BusinessController:

function addBusiness() {
    return view('addBusiness');
}

function createBusiness(Request $request) {
    $name = $request->input('name');
    $type = $request->input('type');
    $email = $request->input('email');
    $user_id = Auth::id();
    $business = new Business();
    $business->name = $name;
    $business->type = $type;
    $business->email = $email;
    $business->user_id = $user_id;
    $business->save();
    $address1 = $request->input('address1');
    $address2 = $request->input('address2');
    $town = $request->input('town');
    $city = $request->input('city');
    $postcode = $request->input('postcode');
    $telephone = $request->input('telephone');
    $address = new Address();
    $address->firstline_address = $address1;
    $address->secondline_address = $address2;
    $address->town = $town;
    $address->city = $city;
    $address->postcode = $postcode;
    $address->telephone = $telephone;
    $address->save();
    $result = $business->save();
    $result2 = $address->save();

    $business_id = $business->id;
    $address_id = $address->id;
    DB::table('business_address')->insert(array('business_id' =>  $business_id, 'address_id' => $address_id));
    DB::table('user_business')->insert(array('user_id' => $user_id, 'business_id' => $business_id));

    if($result && $result2) {
        $message = 'success';
    }else{
        $message = 'error';
    }
    return redirect()->back()->withInput()->with('message', $message);
}

Body:
Try to use the route() function. For this example: <a href="{{ route('my_route_name') }}">Add Business</a>. When your route changes it is automatically changed throughout the application.

You can name your routes like this:

Route::get('create/bussiness', [
    'as' => 'my_route_name',
    'uses' => 'BusinessController@createBusiness'
]);


问:
hive query taking infinitely long for execution
The below hive query is taking an infinitely long time for its execution (more than 3 days). Not sure whether any optimisations in the query would help. </p>

<p>Any suggestions are appreciated !! </p>

```<code>    select count(distinct(a.custname)) from (
    (select custname, pages, variable
    from table1
    where date_time between "2017-01-01" and "2017-01-31"
    and (pages in ('Summary', 'Details')
    or variable in ('Complete', 'Receive'))) a
    left join
    (select custname, pages, variable
    from table1
    where date_time between "2017-01-01 00:00:00" and "2017-01-31 00:00:00"
    and (pages not in ('Summary', 'Details')
    and variable not in ('Complete', 'Receive'))) b
    on a.custname = b.custname)
    where b.pages is null
</code>```

答:
```<code>select  count(*)

from   (select      custname

        from        table1

        where       date_time between date '2017-01-01' and date '2017-01-31'

        group by    custname

        having      count
                    (
                        case
                            when    pages     in ('Summary' ,'Details')
                                or  variable  in ('Complete','Receive')
                            then    1
                        end
                    ) > 0

                and count
                    (
                        case
                            when    pages    not in ('Summary'  ,'Details')
                                and variable not in ('Complete' ,'Receive')
                            then    1
                        end
                    ) = 0
        ) t
</code>```

Body:
The below hive query is taking an infinitely long time for its execution (more than 3 days). Not sure whether any optimisations in the query would help.

Any suggestions are appreciated !!

    select count(distinct(a.custname)) from (
    (select custname, pages, variable
    from table1
    where date_time between "2017-01-01" and "2017-01-31"
    and (pages in ('Summary', 'Details')
    or variable in ('Complete', 'Receive'))) a
    left join
    (select custname, pages, variable
    from table1
    where date_time between "2017-01-01 00:00:00" and "2017-01-31 00:00:00"
    and (pages not in ('Summary', 'Details')
    and variable not in ('Complete', 'Receive'))) b
    on a.custname = b.custname)
    where b.pages is null


问:
Android GPS location too much disk space
I'm developing an app with Xamarin.Forms, my app works on Local Network (VPN).

Here is my Dependency Service in .Droid project;

```<code>using System;
using Android.Content;
using myApp.Droid;
using Android.Locations;
using myApp.DS;

[assembly: Xamarin.Forms.Dependency(typeof(DS_Location))]
namespace myApp.Droid
{
    public class DS_Location : Java.Lang.Object, DS_Loc, ILocationListener
    {
        LocationManager _locationManager;
        string _locationProvider;

        public void OnProviderDisabled(string provider) { }
        public void OnProviderEnabled(string provider) { }
        public void OnStatusChanged(string provider, Availability status, Android.OS.Bundle extras) { }

        public void OnLocationChanged(Location location)
        {
            if (location != null)
            {
                App.lblLat = location.Latitude.ToString();
                App.lblLat = location.Longitude.ToString();
            };
        }

        public void ObtainMyLocation()
        {
            _locationManager = (LocationManager)Xamarin.Forms.Forms.Context.GetSystemService(Context.LocationService);
            _locationProvider = LocationManager.GpsProvider;
            _locationManager.RemoveUpdates(this);
            _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
        }
    }
}
</code>```

Everything is OK, the code works fine.
But when the App runs for 5-6 days the free space on the phone is decreasing.
Now disk usage is 4,96 GB. And I can't delete the file because I can't show the data folder of device. (Not rooted)
I release the project and install the APK and show the free space it's decreasing 2 KB in every 2-3 seconds.
When I disable ObtainMyLocation function and install the APK nothing decreasing, and everything is OK.

Our devices are Samsung Galaxy Grand Prime Android 5.1

答: Solved this problem by updating Android 5.1 Security Update. This bug solved by installing this 500MB update.</p>

Body:
I'm developing an app with Xamarin.Forms, my app works on Local Network (VPN).

Here is my Dependency Service in .Droid project;

using System;
using Android.Content;
using myApp.Droid;
using Android.Locations;
using myApp.DS;

[assembly: Xamarin.Forms.Dependency(typeof(DS_Location))]
namespace myApp.Droid
{
    public class DS_Location : Java.Lang.Object, DS_Loc, ILocationListener
    {
        LocationManager _locationManager;
        string _locationProvider;

        public void OnProviderDisabled(string provider) { }
        public void OnProviderEnabled(string provider) { }
        public void OnStatusChanged(string provider, Availability status, Android.OS.Bundle extras) { }

        public void OnLocationChanged(Location location)
        {
            if (location != null)
            {
                App.lblLat = location.Latitude.ToString();
                App.lblLat = location.Longitude.ToString();
            };
        }

        public void ObtainMyLocation()
        {
            _locationManager = (LocationManager)Xamarin.Forms.Forms.Context.GetSystemService(Context.LocationService);
            _locationProvider = LocationManager.GpsProvider;
            _locationManager.RemoveUpdates(this);
            _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
        }
    }
}

Everything is OK, the code works fine.
But when the App runs for 5-6 days the free space on the phone is decreasing.
Now disk usage is 4,96 GB. And I can't delete the file because I can't show the data folder of device. (Not rooted)
I release the project and install the APK and show the free space it's decreasing 2 KB in every 2-3 seconds.
When I disable ObtainMyLocation function and install the APK nothing decreasing, and everything is OK.

Our devices are Samsung Galaxy Grand Prime Android 5.1


问:
CRM 2011 Removing Activity Party from the Email CC List
How can I remove Activity Party from an Email CC field in CRM 2011 via a Plugin?

I have done so far, but I am stuck beyond this. My problem is that the Email Router is duplicating contacts with the same email address in the CC field. We have suggested that de-duplicating the contacts is the best solution, however that solution has not been accepted. So, for now, we need to be able remove activity parties from the email CC field and replace it with an unresolved email address.

Any thoughts?

```<code>Email email = crmService.Retrieve(Email.EntityLogicalName, emailId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true)).ToEntity<Email>(); //Do not use ColumnSet(true)
List<ActivityParty> ccPartyList = email.Cc.ToList<ActivityParty>();
List<string> ccEmailAddresses = new List<string>();

foreach (ActivityParty ap in ccPartyList)
{
    ccEmailAddresses.Add(ap.AddressUsed);
}

List<string> dedupedCCEmailAddresses = ccEmailAddresses.Distinct().ToList();
List<string> emailAddressToBeRemoved = new List<string>();

//Check for each unique email addresses, how many records are there
foreach (string emailAddress in dedupedCCEmailAddresses)
{
    int count = ccPartyList.Count(ap => ap.AddressUsed.Equals(emailAddress, StringComparison.InvariantCultureIgnoreCase));
    if (count > 1) //Same email address; Multiple Records
    {
       emailAddressToBeRemoved.Add(emailAddress);
    }
}

//Remove ALL Activity Party from the List
foreach (string emailAddress in emailAddressToBeRemoved)
{
    ccPartyList.RemoveAll(ap => ap.AddressUsed.Equals(emailAddress, StringComparison.InvariantCultureIgnoreCase));
    ActivityParty unResolvedEmailAddress = new ActivityParty();
    unResolvedEmailAddress.AddressUsed = emailAddress;
    ccPartyList.Add(unResolvedEmailAddress);
}

Email emailToUpdate = new Email();
emailToUpdate.Id = emailId;
emailToUpdate.Cc = ccPartyList;
crmService.Update(emailToUpdate);
</code>```

I have now updated it with the following code, wherein I remove all CC parties.

```<code>if (localContext == null)
{
    throw new ArgumentNullException("localContext");
}

IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
tracingService = localContext.TracingService;

Email emailFromTarget = (context.InputParameters.Contains("Target")
                        && context.InputParameters["Target"] is Entity)
                        ?
((Entity)context.InputParameters["Target"]).ToEntity<Email>() : null;

Entity email = service.Retrieve(Email.EntityLogicalName, emailFromTarget.Id, new ColumnSet("cc"));

EntityCollection cc = email.GetAttributeValue<EntityCollection>("cc");
if (cc != null)
{
    cc.Entities.ToList().ForEach(party =>
    {
        cc.Entities.Remove(party);
    });
}

email["cc"] = cc;
service.Update(email);
</code>```

Even, then the CC field continues to hold on to the data post creation.

I am doing it in the Post Create Plugin. Is that way is it not removing them? Do I have to do it as a Workflow / CWA?

答:
What's wrong with the code you've suggested?</p>

```<code>// Get your cc field
var cc = email.GetAttributeValue<EntityCollection>("cc");

// Iterate through the collection. If there's a partyId, it's a party list, so remove it
cc.Entities.ToList().ForEach(entity =>
{
    var partyId = entity.GetAttributeValue<EntityReference>("partyid");
    if (partyId != null)
        cc.Entities.Remove(entity);
}

// Update your email
email["cc"] = cc;
service.Update(email);
</code>```

Body:
How can I remove Activity Party from an Email CC field in CRM 2011 via a Plugin?

I have done so far, but I am stuck beyond this. My problem is that the Email Router is duplicating contacts with the same email address in the CC field. We have suggested that de-duplicating the contacts is the best solution, however that solution has not been accepted. So, for now, we need to be able remove activity parties from the email CC field and replace it with an unresolved email address.

Any thoughts?

Email email = crmService.Retrieve(Email.EntityLogicalName, emailId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true)).ToEntity<Email>(); //Do not use ColumnSet(true)
List<ActivityParty> ccPartyList = email.Cc.ToList<ActivityParty>();
List<string> ccEmailAddresses = new List<string>();

foreach (ActivityParty ap in ccPartyList)
{
    ccEmailAddresses.Add(ap.AddressUsed);
}

List<string> dedupedCCEmailAddresses = ccEmailAddresses.Distinct().ToList();
List<string> emailAddressToBeRemoved = new List<string>();

//Check for each unique email addresses, how many records are there
foreach (string emailAddress in dedupedCCEmailAddresses)
{
    int count = ccPartyList.Count(ap => ap.AddressUsed.Equals(emailAddress, StringComparison.InvariantCultureIgnoreCase));
    if (count > 1) //Same email address; Multiple Records
    {
       emailAddressToBeRemoved.Add(emailAddress);
    }
}

//Remove ALL Activity Party from the List
foreach (string emailAddress in emailAddressToBeRemoved)
{
    ccPartyList.RemoveAll(ap => ap.AddressUsed.Equals(emailAddress, StringComparison.InvariantCultureIgnoreCase));
    ActivityParty unResolvedEmailAddress = new ActivityParty();
    unResolvedEmailAddress.AddressUsed = emailAddress;
    ccPartyList.Add(unResolvedEmailAddress);
}

Email emailToUpdate = new Email();
emailToUpdate.Id = emailId;
emailToUpdate.Cc = ccPartyList;
crmService.Update(emailToUpdate);

I have now updated it with the following code, wherein I remove all CC parties.

if (localContext == null)
{
    throw new ArgumentNullException("localContext");
}

IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
tracingService = localContext.TracingService;

Email emailFromTarget = (context.InputParameters.Contains("Target")
                        && context.InputParameters["Target"] is Entity)
                        ?
((Entity)context.InputParameters["Target"]).ToEntity<Email>() : null;

Entity email = service.Retrieve(Email.EntityLogicalName, emailFromTarget.Id, new ColumnSet("cc"));

EntityCollection cc = email.GetAttributeValue<EntityCollection>("cc");
if (cc != null)
{
    cc.Entities.ToList().ForEach(party =>
    {
        cc.Entities.Remove(party);
    });
}

email["cc"] = cc;
service.Update(email);

Even, then the CC field continues to hold on to the data post creation.

I am doing it in the Post Create Plugin. Is that way is it not removing them? Do I have to do it as a Workflow / CWA?

Body:
What's wrong with the code you've suggested?

// Get your cc field
var cc = email.GetAttributeValue<EntityCollection>("cc");

// Iterate through the collection. If there's a partyId, it's a party list, so remove it
cc.Entities.ToList().ForEach(entity =>
{
    var partyId = entity.GetAttributeValue<EntityReference>("partyid");
    if (partyId != null)
        cc.Entities.Remove(entity);
}

// Update your email
email["cc"] = cc;
service.Update(email);


问:
How to use initializer-list loops for modifying elements?
I can easily simulate a for .. in loop using initializer lists for read access

```<code>std::list<int> foo, bar, baz;

int main()
{
  foo.push_back(3);
  foo.push_back(2);
  bar.push_back(1);
  for (auto &x : {foo, bar, baz}) {
    // x.push_back(42);
    std::cout << x.size() << std::endl;
  }
  return 0;
}
</code>```

This prints:

```<code>2
1
0
</code>```

What should I do so that I can modify the actual objects, just as in the commented line:

```<code>// x.push_back(42);
</code>```

答:
A pointer-based trick that we know from C might be applied as follows

```<code>  for (auto x : { &foo, &bar, &baz }) {
    x->push_back(42);
    std::cout << x->size() << std::endl;
  }
</code>```

However, this assumes that you actually want to work with the original objects, as opposed to their copies. (The code you posted originally actually works with copies.)

Body:
I can easily simulate a for .. in loop using initializer lists for read access

std::list<int> foo, bar, baz;

int main()
{
  foo.push_back(3);
  foo.push_back(2);
  bar.push_back(1);
  for (auto &x : {foo, bar, baz}) {
    // x.push_back(42);
    std::cout << x.size() << std::endl;
  }
  return 0;
}

This prints:

2
1
0

What should I do so that I can modify the actual objects, just as in the commented line:

// x.push_back(42);

Body:
A pointer-based trick that we know from C might be applied as follows

  for (auto x : { &foo, &bar, &baz }) {
    x->push_back(42);
    std::cout << x->size() << std::endl;
  }

However, this assumes that you actually want to work with the original objects, as opposed to their copies. (The code you posted originally actually works with copies.)


问:
Canvas collision
I programmed canvas collision into my html game. I have checked numerous times but I cant find a problem with the code.</p>

```<code>// Handle left and right collisions with the canvas
if (player.x <= canvas.x) {
    // Left edige
    player.xdir = 1;
    player.x = canvas.x;
} else if (player.x + player.width >= canvas.x + canvas.width) {
    // Right edge
    player.xdir = -1;
    player.x = canvas.x + canvas.width - player.width;
}

// Handle top and bottom collisions with the canvas
if (player.y <= canvas.y) {
    // Top edge
    player.ydir = 1;
    player.y = canvas.y;
} else if (player.y + player.height >= canvas.y + canvas.height) {
    // Bottom edge
    player.ydir = -1;
    player.y = canvas.y + canvas.height - player.height;
}
</code>```

答:
I think the canvas.x thing is misunderstood. Everything in canvas is always absolute relative to the canvas' point of origin:

//Polyfill for "requestAnimationFrame"
window.requestAnimationFrame = window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  window.msRequestAnimationFrame ||
  function(callback) {
    setTimeout(callback, 1000 / 60);
  };
//The player object
var player = {
  x: 50,
  y: 150,
  xdir: 1,
  ydir: 1,
  width: 10,
  height: 10
};
//The canvas (creation and appending)
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.height = 200;
canvas.width = canvas.height;
//Rendering context
var ctx = canvas.getContext("2d");

function simulate() {
  //Move player
  if (player.xdir === 1) {
    player.x += 1;
  } else {
    player.x -= 1;
  }
  if (player.ydir === 1) {
    player.y += 1;
  } else {
    player.y -= 1;
  }
  // Handle left and right collisions with the canvas
  if (player.x <= player.width * 0.5) {
    // Left edige
    player.xdir = 1;
  } else if (player.x + player.width >= canvas.width + player.width * 0.5) {
    // Right edge
    player.xdir = -1;
  }
  // Handle top and bottom collisions with the canvas
  if (player.y <= player.height * 0.5) {
    // Top edge
    player.ydir = 1;
  } else if (player.y + player.height >= canvas.height + player.height * 0.5) {
    // Bottom edge
    player.ydir = -1;
  }
  requestAnimationFrame(simulate);
  //Draw the player (just for fun)
  ctx.fillStyle = "rgba(235,235,255,0.1)";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "red";
  ctx.fillRect(player.x - 0.5 * player.width, player.y - 0.5 * player.height, player.width, player.height);
}
//Start simulation
simulate();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  background-color: rgba(235, 235, 255, 0.1);
}</code>```

Title: Canvas collision

Body:
I programmed canvas collision into my html game. I have checked numerous times but I cant find a problem with the code.

// Handle left and right collisions with the canvas
if (player.x <= canvas.x) {
    // Left edige
    player.xdir = 1;
    player.x = canvas.x;
} else if (player.x + player.width >= canvas.x + canvas.width) {
    // Right edge
    player.xdir = -1;
    player.x = canvas.x + canvas.width - player.width;
}

// Handle top and bottom collisions with the canvas
if (player.y <= canvas.y) {
    // Top edge
    player.ydir = 1;
    player.y = canvas.y;
} else if (player.y + player.height >= canvas.y + canvas.height) {
    // Bottom edge
    player.ydir = -1;
    player.y = canvas.y + canvas.height - player.height;
}

Body:
I think the canvas.x thing is misunderstood. Everything in canvas is always absolute relative to the canvas' point of origin:

//Polyfill for "requestAnimationFrame"
window.requestAnimationFrame = window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  window.msRequestAnimationFrame ||
  function(callback) {
    setTimeout(callback, 1000 / 60);
  };
//The player object
var player = {
  x: 50,
  y: 150,
  xdir: 1,
  ydir: 1,
  width: 10,
  height: 10
};
//The canvas (creation and appending)
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.height = 200;
canvas.width = canvas.height;
//Rendering context
var ctx = canvas.getContext("2d");

function simulate() {
  //Move player
  if (player.xdir === 1) {
    player.x += 1;
  } else {
    player.x -= 1;
  }
  if (player.ydir === 1) {
    player.y += 1;
  } else {
    player.y -= 1;
  }
  // Handle left and right collisions with the canvas
  if (player.x <= player.width * 0.5) {
    // Left edige
    player.xdir = 1;
  } else if (player.x + player.width >= canvas.width + player.width * 0.5) {
    // Right edge
    player.xdir = -1;
  }
  // Handle top and bottom collisions with the canvas
  if (player.y <= player.height * 0.5) {
    // Top edge
    player.ydir = 1;
  } else if (player.y + player.height >= canvas.height + player.height * 0.5) {
    // Bottom edge
    player.ydir = -1;
  }
  requestAnimationFrame(simulate);
  //Draw the player (just for fun)
  ctx.fillStyle = "rgba(235,235,255,0.1)";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "red";
  ctx.fillRect(player.x - 0.5 * player.width, player.y - 0.5 * player.height, player.width, player.height);
}
//Start simulation
simulate();

canvas {
  background-color: rgba(235, 235, 255, 0.1);
}


问:
Not able to click dropdown
I am a new learner in selenium and try to click on a dropdown to populate list but it keeps on giving me runtime exception:

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException:
    Element is not currently visible and so may not be interacted with )

Please help. Below is my code that I am executing.

```<code>    WebDriver dr=new FirefoxDriver();
    dr.get("https://jqueryui.com/selectmenu/");
    dr.manage().window().maximize();
    dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    dr.switchTo().frame(dr.findElement(By.className("demo-frame")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("speed-       menu"))).click();
</code>```

答:
Try This

```<code>WebDriver driver = new FirefoxDriver();
driver.get("https://jqueryui.com/selectmenu/");
WebElement DynamicElement = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.presenceOfElementLocated(By.id("DynamicElement")));
</code>```

OR

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("yourid")));
</code>```

Title: Not able to click dropdown

Body:
I am a new learner in selenium and try to click on a dropdown to populate list but it keeps on giving me runtime exception:

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException:
    Element is not currently visible and so may not be interacted with )

Please help. Below is my code that I am executing.

    WebDriver dr=new FirefoxDriver();
    dr.get("https://jqueryui.com/selectmenu/");
    dr.manage().window().maximize();
    dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    dr.switchTo().frame(dr.findElement(By.className("demo-frame")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("speed-       menu"))).click();

Body:
Try This

WebDriver driver = new FirefoxDriver();
driver.get("https://jqueryui.com/selectmenu/");
WebElement DynamicElement = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.presenceOfElementLocated(By.id("DynamicElement")));

OR

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("yourid")));


问:
Including Delphi Type Libraries in repository (SVN)?
What is the best way to save a Delphi Type Library in SVN.

The file changes every time you compile the Application

The file is not saved in a readable form of  AscII

It is very difficult to work out what changes have been made from one version to the next

This is a  major problem when more than one person is changing the file

QUESTIONS:

1) Should one save an exported ‘IDL’ file in the version control ?

2) Can one covert an ‘IDL ’ into a Delphi type library If so how ?

3) What are the best practices when working with a Delphi type library ?

4) How easy is it get rid of the type library in Delphi2009 datasnap project?

p.s. I am using BDS2006

答: Prior to Delphi 2009, I would not check in the TLB file but manually put the TLB (and  *_TLB.PAS file for reference) into a zip file then force that into version control.  When ever I made actual changes to the TLB, I would update the zip file and check it in.  The local TLB was always made read/write and ignored by the version control system.  This scheme saved me several times when the TLB file would mysteriously no longer compile, I could just close my project, unzip from the zip file, reload the project and continue working.</p>

OwnerDisplayName: Charles Faiga

LastEditorDisplayName: Charles Faiga

OwnerDisplayName: skamradt

ContentLicense: CC BY-SA 2.5


问:
To check string in jquery.validate
for password validation i am using equalTo:"#password" Whether it is possible to check some sting by giving as equalTo:"string to check" in jquery.validate

答:
equalTo only takes a selector here, but you can make a custom method for the check you want:

```<code>jQuery.validator.addMethod("equals", function(value, element, param) {
  return this.optional(element) || value === param;
}, jQuery.format("You must enter {0}"));
</code>```

Then you can use the a rule with the same name:

```<code>equals:"string to check"
</code>```

You can test it here.

Title: To check string in jquery.validate

Body:
equalTo only takes a selector here, but you can make a custom method for the check you want:

jQuery.validator.addMethod("equals", function(value, element, param) {
  return this.optional(element) || value === param;
}, jQuery.format("You must enter {0}"));

Then you can use the a rule with the same name:

equals:"string to check"

You can test it here.


问:
log ship wizard in SQL 2012 Std not showing compression option
I cannot find the compression option in the log shipping setting page. the version of the SQL is Microsoft SQL 2012 Std.

答: Confirmed from Microsoft , SQL 2012 Standard do not support Log Shipping Compression. only Enterprise Version comes with this feature</p>


问:
How to get current location and network IP in codeigniter?
When Staff login we need to retrieve the current location automatically and insert it.It's an online punch In/Out system.So just to make sure that In/Out is not misused by punching In/Out in from other places. Using the http://ipinfo.io/ as Gaurang Joshi mentioned below i get the internet IP and latitude and logitudes.So do i need to use any google map library to get the specific location?How to implement it?Any Help.

答:
```<code>public function index(){

    $ip = $_SERVER['REMOTE_ADDR'];
    //$location = file_get_contents('http://freegeoip.net/json/'.$_SERVER['REMOTE_ADDR']);
    $location = file_get_contents('http://ip-api.com/json/'.$ip);
    //you can also use ipinfo.io or any other ip location provider API
    //print_r($location);exit;
    $data_loc = json_decode($location);
    $marker = array();
    $data = array(
                'view_file'=>'index',
                'current_menu'=>'index',
                'site_title' =>'site title',
                'logo'      => 'logo',
                'title'=>'Family Owned Pest Control',
            );
    $Lat = '';
    $Lon = '';
    if(isset($_GET['searchsubmit']))
    {
        $Address = $this->input->get('addr_loc');
        $jobtitle = $this->input->get('jobtitle');

        $request_url = "//maps.googleapis.com/maps/api/geocode/xml?address=".$Address."&sensor=true";
        $xml = simplexml_load_file($request_url) or die("url not loading");

        $status = $xml->status;

        if ($status=="OK") {
            $Lat = $xml->result->geometry->location->lat;
            $Lon = $xml->result->geometry->location->lng;
        }
    }

    if(empty($Lat) AND empty($Lon))
    {
        $config['center'] = 'auto';
        $marker['position'] = $data_loc->lat.",". $data_loc->lon ;
        $Lat = $data_loc->lat;
        $Lon = $data_loc->lon;
    }
    else{
        $config['center'] ='auto';
        $marker['position'] = $Lat.",". $Lon ;
    }

    $config['zoom'] = '11';
    $config['places'] = TRUE;
    $config['placesAutocompleteInputID'] = 'myPlaceTextBox';
    $config['placesAutocompleteBoundsMap'] = TRUE; // set results biased towards the maps viewport
    $this->googlemaps->initialize($config);
    $marker['infowindow_content'] =  $data_loc->city.'<br>'.$data_loc->regionName.'<br>'.$data_loc->country;
    $marker['icon'] = '//chart.apis.google.com/chart?chst=d_map_pin_letter&chld=A|9999FF|000000';
    $this->googlemaps->add_marker($marker);
    $Lat1 = $Lat+0.05;
    $Lon1 = $Lon+0.05;
    $marker = array();
    $marker['position'] = $Lat1.",". $Lon1;
    $marker['draggable'] = TRUE;
    $marker['animation'] = 'DROP';
    $marker['infowindow_content'] =  'dskjfhdsjhfsd' ;
    $marker['icon'] = '//chart.apis.google.com/chart?chst=d_map_pin_letter&chld=B|9999FF|000000';
    $this->googlemaps->add_marker($marker);
    $Lat2 = $Lat1+0.05;
    $Lon2 = $Lon1+0.05;
    $marker = array();
    $marker['position'] = $Lat2.",". $Lon2;
    $marker['draggable'] = TRUE;
    $marker['animation'] = 'DROP';
    $marker['infowindow_content'] =  'dskjfhdsjdsfsdfhfsd' ;
    $marker['icon'] = '//chart.apis.google.com/chart?chst=d_map_pin_letter&chld=C|9999FF|000000';
    $this->googlemaps->add_marker($marker);

    $data['content']='content/peta';

    $data['map'] = $this->googlemaps->create_map();

    $this->template->load_index_template($data);
}
</code>```

ContentLicense: CC BY-SA 4.0


问:
spring Batch flow job Vs spring composed task
I want to execute my apps using spring-complex-task and I have already build complex spring-batch Flow Jobs which executes perfectly fine.

could you please explain what is difference between spring Batch flow job Vs spring composed task? and which is best among them?

答:
In general, there's not one that's "better". It's going to be dependent on your use case and requirements.

Spring Batch is a nice framework to run batch processing applications.

Spring Cloud Task is a wrapper that allows you to run short lived microservices using Spring Cloud along with Spring Boot. Once you setup a test with @EnableTask it will then launch your *Runner. The framework also comes with Spring Batch integration points and ComposedTaskRunner helps facilitate that integration.

I'd start with the Spring Cloud Task batch documentation and then come back to ask more specific questions.


问:
How can I use onoffline and ononline events in Chrome and other modern browsers?
I see that ononline and onoffline events are only available on Firefox and IE, but not for the other browsers (Chrome, Opera, Safari). How could I set the events in Chrome and other modern browsers?

答: Use navigator.onLine for all browser support as it is mentioned in link you provided. To whomever said that question is about checking if user is online - that's php's or what ever you prefer to use part not JS's.</p>


问:
R function to subtract the difference between consecutive values in vector from subsequent values in vector
I have a numerical vector that contains a time series of weight data. What I need to do is remove weight change artifacts by identifying unrealistic differences between consecutive weights and subtracting that change from all subsequent values in the series.

For example, in the series: c(5,4,6,8,8,9,8,12,10,100,101,101), I would identify the delta weight between items 9 and 10 (100 - 10 = 90) as an artifact, and I would correct it by subtracting 90 from the subsequent values, yielding c(5,4,6,8,8,9,8,12,10,10,11,11).

In principal, my code would look something like:

```<code>cancel_artifacts <- function(weights, delta_max) {
    for (i in 0:length(weights)) {
        if (weights[i] - weights[i-1] > abs(delta_max)) {
            weights[i:length(weights)] <- weights[i:length(weights)] - (weights[i] - weights[i-1])
        }
    }
</code>```

Obviously my syntax is a disaster. Can anyone help me set this up?

答:
You can do this in a vectorized manner:</p>

```<code>remove_artifacts <- function(weights, delta_max) {
  # calculate deltas, and set first delta to zero
  dw <- c(0, diff(x))
  # create vector of zeros and abs(observations) > delta_max
  # dw * (logical vector) results in either:
  # dw * 0 (if FALSE)
  # dw * 1 (if TRUE)
  dm <- dw * (abs(dw) > delta_max)
  # subtract the cumulative sum of observations > delta_max
  return(weights - cumsum(dm))
}
x <- c(5, 4, 6, 8, 8, 9, 8, 12, 10, 100, 101, 101)
remove_artifacts(x, 50)
# [1]  5  4  6  8  8  9  8 12 10 10 11 11
</code>```

Body:
I have a numerical vector that contains a time series of weight data. What I need to do is remove weight change artifacts by identifying unrealistic differences between consecutive weights and subtracting that change from all subsequent values in the series.

For example, in the series: c(5,4,6,8,8,9,8,12,10,100,101,101), I would identify the delta weight between items 9 and 10 (100 - 10 = 90) as an artifact, and I would correct it by subtracting 90 from the subsequent values, yielding c(5,4,6,8,8,9,8,12,10,10,11,11).

In principal, my code would look something like:

cancel_artifacts <- function(weights, delta_max) {
    for (i in 0:length(weights)) {
        if (weights[i] - weights[i-1] > abs(delta_max)) {
            weights[i:length(weights)] <- weights[i:length(weights)] - (weights[i] - weights[i-1])
        }
    }

Obviously my syntax is a disaster. Can anyone help me set this up?

Body:
You can do this in a vectorized manner:

remove_artifacts <- function(weights, delta_max) {
  # calculate deltas, and set first delta to zero
  dw <- c(0, diff(x))
  # create vector of zeros and abs(observations) > delta_max
  # dw * (logical vector) results in either:
  # dw * 0 (if FALSE)
  # dw * 1 (if TRUE)
  dm <- dw * (abs(dw) > delta_max)
  # subtract the cumulative sum of observations > delta_max
  return(weights - cumsum(dm))
}
x <- c(5, 4, 6, 8, 8, 9, 8, 12, 10, 100, 101, 101)
remove_artifacts(x, 50)
# [1]  5  4  6  8  8  9  8 12 10 10 11 11


问:
How do i get the most updated api by android?
I would like to use the "new" findViewById that returns T extends View and not just View , what do i need to update to receive that ?

this is the updated Doc :

https://developer.android.com/reference/android/view/View.html

the new method  is already there .

答:
That is only available on Android O and higher. Presently, there are zero production devices that run Android O.

Sometime later in 2017, Android O will ship. Let's presume that it is API Level 26. At that time, if you set compileSdkVersion to 26, you can compile code that references that version of findViewById(). However, that code will only run on API Level 26+ devices, which means that you need to set your minSdkVersion to 26 or avoid executing that code on older devices.

If you want to experiment with this today, you can set your compileSdkVersion to android-O. However, the resulting app will only run on devices or emulators with the O Developer Preview on it.


问:
Round date long value
In my Java project I used date in long and for example it is 12136219 and by creating Date object as below:

```<code>long time = 12136219;
Date date = new Date(time);
</code>```

and it represent date as Thu Jan 01 04:22:16 CET 1970. How can I round date (in long representation) to minutes ?

For example I want achieve Thu Jan 01 04:22:00 CET 1970 if the seconds are <30 and Thu Jan 01 04:23:00 CET 1970 if the seconds are >=30 but I want round this long time = 12136219 representation. Any idea?

答:
Don’t reinvent the wheel. Use java.time.Instant for representing an instant in time:

```<code>    Instant i = Instant.ofEpochMilli(time);
    i = i.plusSeconds(30).truncatedTo(ChronoUnit.MINUTES);
</code>```

Instant doesn’t offer rounding, only truncation. However, adding 30 seconds and then truncating gives you what you want. If you need your milliseconds back, it’s easy:

```<code>    time = i.toEpochMilli();
    System.out.println(time);
</code>```

With the number from your question this prints

```<code>12120000
</code>```

(This is equal to an instant of 1970-01-01T03:22:00Z, or 1970-01-01T04:22+01:00[Europe/Paris] in CET, or the expected rounding down of your 04:22:16 CET.)

PS I am quite convinced that a library like Time4J will offer rounding so you don’t need the trick of adding and truncating. Unfortunately I don’t have the experience to give you the details.

Title: Round date long value

Body:
In my Java project I used date in long and for example it is 12136219 and by creating Date object as below:

long time = 12136219;
Date date = new Date(time);

and it represent date as Thu Jan 01 04:22:16 CET 1970. How can I round date (in long representation) to minutes ?

For example I want achieve Thu Jan 01 04:22:00 CET 1970 if the seconds are <30 and Thu Jan 01 04:23:00 CET 1970 if the seconds are >=30 but I want round this long time = 12136219 representation. Any idea?

Body:
Don’t reinvent the wheel. Use java.time.Instant for representing an instant in time:

    Instant i = Instant.ofEpochMilli(time);
    i = i.plusSeconds(30).truncatedTo(ChronoUnit.MINUTES);

Instant doesn’t offer rounding, only truncation. However, adding 30 seconds and then truncating gives you what you want. If you need your milliseconds back, it’s easy:

    time = i.toEpochMilli();
    System.out.println(time);

With the number from your question this prints

12120000

(This is equal to an instant of 1970-01-01T03:22:00Z, or 1970-01-01T04:22+01:00[Europe/Paris] in CET, or the expected rounding down of your 04:22:16 CET.)

PS I am quite convinced that a library like Time4J will offer rounding so you don’t need the trick of adding and truncating. Unfortunately I don’t have the experience to give you the details.


问:
Accessing Swagger Documentation with JHipster
I have generated an app server only through jhipster using only.

```<code>yo jhipster --skip-client
</code>```

It had generated all the necessary api calls I needed however upon accessing

```<code>http://localhost:8080/swagger-ui/index.html
</code>```

I ended on a 404. I was under the impression that swagger is included however it cant seem to be accessed, although the swagger api endpoints is available.

答:
You can't since you are only generating the rest apis. if you want to see the api-docs follow the instructions mentioned here

Once you have succesfully cloned the said repository

open dist/index.html and simply paste the source there

http://localhost:8080/v2/api-docs

it should look like something like this

Body:
I have generated an app server only through jhipster using only.

yo jhipster --skip-client

It had generated all the necessary api calls I needed however upon accessing

http://localhost:8080/swagger-ui/index.html

I ended on a 404. I was under the impression that swagger is included however it cant seem to be accessed, although the swagger api endpoints is available.


问:
How can I write a piece of Java an code that checks if any character of a string is convertible to an integer between 0 and 9?
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

```<code>String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}
</code>```

where IntegerFormat Exception is something like

```<code>public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}
</code>```

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

```<code>at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)
</code>```

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

答:
try this</p>

```<code>String regex = "^-?[0-9]+$";
if (s.matches(regex) {
    // it's a number
} else {
   // not a number
}
</code>```

Body:
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}

where IntegerFormat Exception is something like

public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

Body:
try this

String regex = "^-?[0-9]+$";
if (s.matches(regex) {
    // it's a number
} else {
   // not a number
}


问:
Combine 2 TextBoxFor bound to one property MVC
I need to save the Contact Number in a registration form wherein i'm having 2 TextBox, one for Country Code and another for Number. Now i need to combine both and bind into a single property which i have in my class. How can i do that?

View:

```<code> <div class="form-group">
      @Html.LabelFor(m => m.Phone, "Contact Number:")
      @Html.TextBoxFor(m => m.xxxx,new { @class = "form-control", @id = "txtContactCode", required="required", type ="number" })-
      @Html.TextBoxFor(m => m.Phone,new { @class = "form-control", @id = "txtContactNumber", required="required", type ="number" })
 </div>
</code>```

Property,

```<code> public string Phone { get; set; }
</code>```

Now what should i bind the property in the code of the phone number field to concatenate as one? Is there any way or i should declare another property named Code and then proceed?

答:
In general, you should not try to split/join things. You're just introducing a potential point of failure into your application. If you only care about storing a single combined Phone, then let the user enter their phone number directly in a field for Phone. If you care about ensuring that every phone number has a country code, you can use a phone number validation library like this port of Google's libphonenumber library, to parse the user entered phone numbers and standardize how they're stored in the database.

The problem with trying to combine two fields into one is that you then have to split that one field back into two. Especially with something like a country code that can be variable length, that's going to be really difficult to do reliably. However, if you insist on going down this path, I'd recommend using a view model like:

```<code>public string Phone
{
    get { return String.Format("{0} {1}", CountryCode, Number); }
    set
    {
        CountryCode = null;
        Number = null;

        if (value != null)
        {
            var parts = value.Split(new[] { ' ' }, 2);
            if (parts.Length == 2)
            {
                CountryCode = parts[0];
                Number = parts[1];
            }
        }
    }
}

public string CountryCode { get; set; }
public string Number { get; set; }
</code>```

Then, you would bind to CountryCode and Number, respectively, in your view. The Phone custom getter and setter will take care of translating back and forth between combined and constituent parts.

Body:
I need to save the Contact Number in a registration form wherein i'm having 2 TextBox, one for Country Code and another for Number. Now i need to combine both and bind into a single property which i have in my class. How can i do that?

View:

      @Html.LabelFor(m => m.Phone, "Contact Number:")
      @Html.TextBoxFor(m => m.xxxx,new { @class = "form-control", @id = "txtContactCode", required="required", type ="number" })-
      @Html.TextBoxFor(m => m.Phone,new { @class = "form-control", @id = "txtContactNumber", required="required", type ="number" })

Property,

 public string Phone { get; set; }

Now what should i bind the property in the code of the phone number field to concatenate as one? Is there any way or i should declare another property named Code and then proceed?

Body:
In general, you should not try to split/join things. You're just introducing a potential point of failure into your application. If you only care about storing a single combined Phone, then let the user enter their phone number directly in a field for Phone. If you care about ensuring that every phone number has a country code, you can use a phone number validation library like this port of Google's libphonenumber library, to parse the user entered phone numbers and standardize how they're stored in the database.

The problem with trying to combine two fields into one is that you then have to split that one field back into two. Especially with something like a country code that can be variable length, that's going to be really difficult to do reliably. However, if you insist on going down this path, I'd recommend using a view model like:

public string Phone
{
    get { return String.Format("{0} {1}", CountryCode, Number); }
    set
    {
        CountryCode = null;
        Number = null;

        if (value != null)
        {
            var parts = value.Split(new[] { ' ' }, 2);
            if (parts.Length == 2)
            {
                CountryCode = parts[0];
                Number = parts[1];
            }
        }
    }
}

public string CountryCode { get; set; }
public string Number { get; set; }

Then, you would bind to CountryCode and Number, respectively, in your view. The Phone custom getter and setter will take care of translating back and forth between combined and constituent parts.


问:
How to terminate the function when it takes too many time in Scala?
Recently, I am learning the Scala language. Today I come out a question, that is,
how to terminate a function when it takes too many time.

For example:

```<code>object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, World")
    // How to terminate the sum() function
    // when the time that it takes greater than 2 second?
    val t0 = System.nanoTime : Double
    val total: BigInt = sum(1000000000)
    val t1 = System.nanoTime : Double
    println("Elapsed time " + (t1 - t0) / 1000000.0 + " msecs")

    println(total)

  }

  //Given that sum() is written by others and I cannot change it.
  def sum(k: Int): BigInt = {
    var total: BigInt = 0
    for (i <- 1 to k) {
      total += i
    }
    total
  }
}
</code>```

The above scala code takes about 70s.

答:
Threads are not strictly required for this if you have a tight loop and just want to exit if the condition is not met before a certain timeout:</p>

```<code>def sum(k: Int, timeoutMillis: Long): BigInt = {
  val timeoutMillis = System.currentTimeMillis + timeoutMillis
  var total: BigInt = 0
  for (i <- 1 to k) {
    total += i
    if (timeoutMillis < System.currentTimeMillis)
      throw new RuntimeException("Timed out")
  }
  total
}
</code>```

Body:
Recently, I am learning the Scala language. Today I come out a question, that is,
how to terminate a function when it takes too many time.

For example:

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, World")
    // How to terminate the sum() function
    // when the time that it takes greater than 2 second?
    val t0 = System.nanoTime : Double
    val total: BigInt = sum(1000000000)
    val t1 = System.nanoTime : Double
    println("Elapsed time " + (t1 - t0) / 1000000.0 + " msecs")

    println(total)

  }

  //Given that sum() is written by others and I cannot change it.
  def sum(k: Int): BigInt = {
    var total: BigInt = 0
    for (i <- 1 to k) {
      total += i
    }
    total
  }
}

The above scala code takes about 70s.

Body:
Threads are not strictly required for this if you have a tight loop and just want to exit if the condition is not met before a certain timeout:

def sum(k: Int, timeoutMillis: Long): BigInt = {
  val timeoutMillis = System.currentTimeMillis + timeoutMillis
  var total: BigInt = 0
  for (i <- 1 to k) {
    total += i
    if (timeoutMillis < System.currentTimeMillis)
      throw new RuntimeException("Timed out")
  }
  total
}


问:
Convert an array to Observable Object to normal array of object in Angular 4
I found lot of references to convert array of object to observable array of object, but not reverse from observable array of object to normal array of object?

This code return :

```<code>myObjects: myObjects[] = this.myService.getMyObjects();
</code>```

TS2322:Type 'Observable< myObjects[]>' is not assignable to type 'myObjects[]'.
  Property 'length' is missing in type 'Observable< myObjects[]>'.

How can I convert / cast ?

Thanks

答:
You have to subscribe to it and store the value in a variable.

WARNING

This is an asynchronous call, meaning that your data will be empty until you loaded everything.

```<code>myObjects: myObjects[] = [];

ngOnInit(){
    this.myService.getMyObjects().subscribe( objects => {
        this.myObjects = objects;
    });
}
</code>```

As it seems to be an http call, once the http call has finished, your data will be in the myObjects variable.

Body:
I found lot of references to convert array of object to observable array of object, but not reverse from observable array of object to normal array of object?

This code return :

myObjects: myObjects[] = this.myService.getMyObjects();

TS2322:Type 'Observable< myObjects[]>' is not assignable to type 'myObjects[]'.
  Property 'length' is missing in type 'Observable< myObjects[]>'.

How can I convert / cast ?

Thanks

Body:
You have to subscribe to it and store the value in a variable.

WARNING

This is an asynchronous call, meaning that your data will be empty until you loaded everything.

myObjects: myObjects[] = [];

ngOnInit(){
    this.myService.getMyObjects().subscribe( objects => {
        this.myObjects = objects;
    });
}

As it seems to be an http call, once the http call has finished, your data will be in the myObjects variable.


问:
Join SQL tables, but with additional info from joined table
Here is a basic illustration of the issue

I have two tables I want to join.
One table contains information about a product sale. (product_sales)
The other contains keys for the names of locations. (states_keys)

Both contain the same column 'state_key'.
The states_keys table has an additional column called 'state_names'.

I would like to join the table so that I can view the accurate state name that coordinates to each product sale.

So, I want to join where each table's state_key are = but display the additional column state_names from table states_keys.

答:
Try with something like this:</p>

```<code>Select prod.*, state.state_names
from product_sales prod
inner join states_keys state on state.state_key = prod.state_key
</code>```

Body:
Try with something like this:

Select prod.*, state.state_names
from product_sales prod
inner join states_keys state on state.state_key = prod.state_key


问:
Float object is not subscriptable with enumerate but works with range and if-else
I'm trying to understand why I can't use enumerate like I want to when trying to compare a str value to float in order to execute code in an if-else block.  For example, here is what works:

```<code>testa = [23.12, 34.15, 25.12, 34.23]

if testa[0] == 'word':
    print('It's is a string')
else:
    print('Not a string')
</code>```

This successfully prints "Not a string".  This next code block also works:

```<code>for i in range(len(testa)):
    if testa[i] == 'word':
        print('Its a string')
    else:
        print('Not a string')
</code>```

The above two code blocks work as expected.  Now, I want to use enumerate:

```<code>for i, number in enumerate(testa, start=0):
    if number[i] == 'word':
        print("Its a string")
    else:
        print("Not a string")
TypeError: 'float' object is not subscriptable
</code>```

It's important that I'm able to keep up with specific indices so I thought I could just feed it i for the index counter and let enumerate take care of incrementing it on its own, but something else is happening here that I'm not seeing.

答: With enumerate the number you get for value is already testa[i]. It is the element of the matrix, a float, so you can't index it. Change it to if number == 'word'

Body:
I'm trying to understand why I can't use enumerate like I want to when trying to compare a str value to float in order to execute code in an if-else block.  For example, here is what works:

testa = [23.12, 34.15, 25.12, 34.23]

if testa[0] == 'word':
    print('It's is a string')
else:
    print('Not a string')

This successfully prints "Not a string".  This next code block also works:

for i in range(len(testa)):
    if testa[i] == 'word':
        print('Its a string')
    else:
        print('Not a string')

The above two code blocks work as expected.  Now, I want to use enumerate:

for i, number in enumerate(testa, start=0):
    if number[i] == 'word':
        print("Its a string")
    else:
        print("Not a string")
TypeError: 'float' object is not subscriptable

It's important that I'm able to keep up with specific indices so I thought I could just feed it i for the index counter and let enumerate take care of incrementing it on its own, but something else is happening here that I'm not seeing.


问:
SQL returning aggregated results from one table as a column in a query
Say I have the following setup

```<code>---Posts---
|id
|Title
-----------

---Comments---
|id
|postid
|comment
-----------
</code>```

Some Mock Data

```<code>Posts
ID        Title
1         Hello World
2         Good Bye
3         Pepsi

Comments
ID      postid      comment
 1        1         comment 1
 2        2         comment 2
 3        2         comment 3
</code>```

I want to return back the Title from the Posts table and all the comments related to it via the id in the comments Table.

Something like.

```<code>Title           Comment
Hello World     comment1
Good Bye        comment2
                comment3
Pepsi           null
</code>```

Is this possible just using SQL?

答:
Probably you are looking for this:
GROUP_CONCAT</p>

Body:
Say I have the following setup

---Posts---
|id
|Title
-----------

---Comments---
|id
|postid
|comment
-----------

Some Mock Data

Posts
ID        Title
1         Hello World
2         Good Bye
3         Pepsi

Comments
ID      postid      comment
 1        1         comment 1
 2        2         comment 2
 3        2         comment 3

I want to return back the Title from the Posts table and all the comments related to it via the id in the comments Table.

Something like.

Title           Comment
Hello World     comment1
Good Bye        comment2
                comment3
Pepsi           null

Is this possible just using SQL?


问:
Android OnTouchListener
I want to implement OnTouchListener in my app. What I want:

when I touch the screen , I need to show or hide some action: here when I touch ImageView , show the LinearLayout which handle actions

My Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_af"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">

<ImageView
    android:id="@+id/ivaf"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:layout_centerInParent="true" />

<LinearLayout
    android:id="@+id/llaffbtn"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#000000"
        android:src="@drawable/ic_file_download_white_24dp" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#000000"
        android:src="@drawable/ic_share_white_24dp" />

</LinearLayout>
</code>```

and what i tried in my java class:

```<code>    img = (ImageView) findViewById(R.id.ivaf);
    rl = (RelativeLayout) findViewById(R.id.rl_af);
    affBtn = (LinearLayout) findViewById(R.id.llaffbtn);
    rl.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                affBtn.setVisibility(View.VISIBLE);
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                affBtn.setVisibility(View.INVISIBLE);
            }

            return false;
        }
    });
</code>```

答:
Try returning "True" after ACTION_DOWN. Android will then listen to ACTION_UP events and call it when it happens. I had a similar issue in an earlier project of mine.</p>

```<code>rl.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            affBtn.setVisibility(View.VISIBLE);
            return true;
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            affBtn.setVisibility(View.INVISIBLE);
        }

        return false;
    }
});
</code>```

Title: Android OnTouchListener

Body:
I want to implement OnTouchListener in my app. What I want:

when I touch the screen , I need to show or hide some action: here when I touch ImageView , show the LinearLayout which handle actions

My Layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_af"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">

<ImageView
    android:id="@+id/ivaf"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:layout_centerInParent="true" />

<LinearLayout
    android:id="@+id/llaffbtn"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#000000"
        android:src="@drawable/ic_file_download_white_24dp" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#000000"
        android:src="@drawable/ic_share_white_24dp" />

</LinearLayout>

and what i tried in my java class:

    img = (ImageView) findViewById(R.id.ivaf);
    rl = (RelativeLayout) findViewById(R.id.rl_af);
    affBtn = (LinearLayout) findViewById(R.id.llaffbtn);
    rl.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                affBtn.setVisibility(View.VISIBLE);
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                affBtn.setVisibility(View.INVISIBLE);
            }

            return false;
        }
    });

Body:
Try returning "True" after ACTION_DOWN. Android will then listen to ACTION_UP events and call it when it happens. I had a similar issue in an earlier project of mine.

rl.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            affBtn.setVisibility(View.VISIBLE);
            return true;
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            affBtn.setVisibility(View.INVISIBLE);
        }

        return false;
    }
});


问:
How to test Unicode "non-chars" (lsep, rsep etc.)?
Is there an application or a utility for generating non-characters, such as U-2028 and U-2029 (line separators)?</p>

答:
If you are with Windows, you don't need external tools: press alt, and + sign, and the hex code.

If you need \u2028, you press Alt and +, and 2028, the sign appears.

It depends on the code page you are using. Please refer to

https://en.wikipedia.org/wiki/Alt_code

and

https://en.wikipedia.org/wiki/Code_page

In my case, with my code page, I have ý when typing alt code 2028.


问:
To check string in jquery.validate
for password validation i am using equalTo:"#password" Whether it is possible to check some sting by giving as equalTo:"string to check" in jquery.validate

答:
Override the equalTo: with below function</p>

```<code>equalTo: function(element) {
                        if( (
                                $("#password").val() == "Your String Value Here"
                            ) {
return true;
}else{
return false;
}
</code>```

Title: To check string in jquery.validate

Body:
Override the equalTo: with below function

equalTo: function(element) {
                        if( (
                                $("#password").val() == "Your String Value Here"
                            ) {
return true;
}else{
return false;
}


问:
ES6 Classes ability to perform polymorphism
I am trying to emulate polymorphism through ES6 Classes, in order to be able to better understand this theory.

Concept is clear (designing objects to share behaviors and to be able to override shared behaviors with specific ones) but I am afraid my code above is not a valid polymorphism example.

Due to my lack of experience, I appreciate if you answer these questions in a comprehensive way:

The fact that both Classes have an equally named method, and that instances made from each Class get access correctly to their respective methods, makes this a polymorphic example?

In case this does not emulate polimorphism, what changes should be
done in the code for it?

I've tried removing the Employee.prototype = new Person(); line, and it still works. This is why I am afraid I'm not getting this concept.

class Person {
  constructor (name, age) {
    this._name = name;
    this._age = age;
  }
}

Person.prototype.showInfo = function(){
  return "Im " + this._name + ", aged " + this._age;
};

class Employee {
  constructor (name, age, sex) {
    this._name = name;
    this._age = age;
    this._sex = sex;
  }
}

Employee.prototype = new Person();

Employee.prototype.showInfo = function(){
  return "Im " + this._sex + ", named " + this._name + ", aged " + this._age;
};

var myPerson = new Person('Jon', 20);
var myEmployee = new Employee('Doe', 10, 'men');

document.write(myPerson.showInfo() + "

");   // Im Jon, aged 20
document.write(myEmployee.showInfo() + "

"); // Im men, named Doe, aged 10```

答:
You are mixing ES5 and ES6. Also, you simply created two classes. Employee does not really inherit from Person. The code you want should look like this:

class Person {
    constructor(name, age) {
        this._name = name;
        this._age = age;
    }

    showInfo() {
        return `I'm ${this._name}, aged ${this._age}.`;
    }
}

class Employee extends Person {
    constructor(name, age, sex) {
        super(name, age);
        this._sex = sex;
    }

    showInfo() {
        return `I'm a ${this._sex} named ${this._name}, aged ${this._age}.`;
    }
}

const alice = new Person("Alice", 20);
const bob = new Employee("Bob", 25, "male");

console.log(alice.showInfo());
console.log(bob.showInfo());```

So, here's a quick recap of what's changed.

First off, no need to assign a prototype anymore. Instead, you extend the parent class to create a child class. You can call the parent constructor using the super() call in the child constructor - this will set the properties that are handled by the parent ctor. Note that we don't set name or age in the child ctor anymore! This is why your example still worked after removing the line setting the child prototype: you set the properties manually anyway.

Methods are defined inside the class; no need to use the prototype. You override the method in the child class by just declaring it there.

Should you need any additional clarification, please ask in the comment.

Body:
You are mixing ES5 and ES6. Also, you simply created two classes. Employee does not really inherit from Person. The code you want should look like this:

class Person {
    constructor(name, age) {
        this._name = name;
        this._age = age;
    }

    showInfo() {
        return `I'm ${this._name}, aged ${this._age}.`;
    }
}

class Employee extends Person {
    constructor(name, age, sex) {
        super(name, age);
        this._sex = sex;
    }

    showInfo() {
        return `I'm a ${this._sex} named ${this._name}, aged ${this._age}.`;
    }
}

const alice = new Person("Alice", 20);
const bob = new Employee("Bob", 25, "male");

console.log(alice.showInfo());
console.log(bob.showInfo());

So, here's a quick recap of what's changed.

First off, no need to assign a prototype anymore. Instead, you extend the parent class to create a child class. You can call the parent constructor using the super() call in the child constructor - this will set the properties that are handled by the parent ctor. Note that we don't set name or age in the child ctor anymore! This is why your example still worked after removing the line setting the child prototype: you set the properties manually anyway.

Methods are defined inside the class; no need to use the prototype. You override the method in the child class by just declaring it there.

Should you need any additional clarification, please ask in the comment.


问:
react - redux - router setup issues
Can anyone help me figure out how to get this setup working.

```<code>import 'babel-polyfill';
    import React from 'react';
    import ReactDOM from "react-dom";
    import {Provider} from 'react-redux';
    import {createStore, applyMiddleware} from 'redux';
    import thunk from 'redux-thunk';
    import promise from 'redux-promise';
    import createLogger from 'redux-logger';
    import allReducers from './reducers';
    import App from './components/App';
    import createHistory from 'history/createBrowserHistory'
    import { Route } from 'react-router-dom'
    import { ConnectedRouter, routerMiddleware, push } from 'react-router-redux'

    const logger = createLogger();

    // Create a history of your choosing (we're using a browser history in this case)
    const history = createHistory()

    // Build the middleware for intercepting and dispatching navigation actions
    const middleware = routerMiddleware(history)

    // Add the reducer to your store on the `router` key
    // Also apply our middleware for navigating
    const store = createStore(
    allReducers,
    applyMiddleware(middleware, thunk, promise, logger)
    )

    ReactDOM.render(
        <Provider store={store}>
            <ConnectedRouter history={history}>
            <div>
                <Route exact path="/" component={App}/>
            </div>
            </ConnectedRouter>
        </Provider>,
        document.getElementById('root')
    );
</code>```

I seem to be getting an error called. Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

答: Thanks for all the feedback the answer was ConnectedRouter was undefined. I have now fixed this importing correctly.</p>

Title: react - redux - router setup issues

Body:
Can anyone help me figure out how to get this setup working.

import 'babel-polyfill';
    import React from 'react';
    import ReactDOM from "react-dom";
    import {Provider} from 'react-redux';
    import {createStore, applyMiddleware} from 'redux';
    import thunk from 'redux-thunk';
    import promise from 'redux-promise';
    import createLogger from 'redux-logger';
    import allReducers from './reducers';
    import App from './components/App';
    import createHistory from 'history/createBrowserHistory'
    import { Route } from 'react-router-dom'
    import { ConnectedRouter, routerMiddleware, push } from 'react-router-redux'

    const logger = createLogger();

    // Create a history of your choosing (we're using a browser history in this case)
    const history = createHistory()

    // Build the middleware for intercepting and dispatching navigation actions
    const middleware = routerMiddleware(history)

    // Add the reducer to your store on the `router` key
    // Also apply our middleware for navigating
    const store = createStore(
    allReducers,
    applyMiddleware(middleware, thunk, promise, logger)
    )

    ReactDOM.render(
        <Provider store={store}>
            <ConnectedRouter history={history}>

                <Route exact path="/" component={App}/>

            </ConnectedRouter>
        </Provider>,
        document.getElementById('root')
    );

I seem to be getting an error called. Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.


问:
Yet another ERROR ITMS-90161: "Invalid Provisioning Profile"
Over the past couple of days I've worked my way through all the prior posts on here that I could find that seemed to be related (many of them appear to be horrifically out of date and less than useful now), as well as the Apple Troubleshooting and Maintaining Your Signing Identities and Certificate guides (not to mention the usual Internet searches).

The app in question was deploying fine until the latest XCode update, but now fails to upload (build is successful obviously, and there have been code changes as well):

```<code>ERROR ITMS-90161: "Invalid Provisioning Profile. The provisioning profile included in the bundle *content removed* is invalid. [Missing code-signing certificate]. A Distribution Provisioning profile should be used when submitting apps to the App Store. For more information, visit the iOS Developer Portal."
</code>```

It's not the first time I've mysteriously had a failure like this, but in prior cases simply revoking the certs, removing the profile, then rebuilding would take care of it.  Not so in this case.

The provisioning profile is confirmed to be the correct type, and the code signing certificate sure looks like it's in there...  Certificate gets a nice green checkmark too.  Any new suggestions not covered in the usual places?

答:
It turns out that there's nothing wrong with the certificate itself, but it's the upload process which needs to be done different.

In the past I had been deploying the distribution outputs from Cordova CLI via the Application Loader.  The App store no longer accepts my builds when done that way.

With the current version of XCode, I need to use the GUI now and set the build target to "Generic iOS Device" and then do an "Archive" operation.  The archive will upload the app through a different loader, which the App store will accept.

Body:
Over the past couple of days I've worked my way through all the prior posts on here that I could find that seemed to be related (many of them appear to be horrifically out of date and less than useful now), as well as the Apple Troubleshooting and Maintaining Your Signing Identities and Certificate guides (not to mention the usual Internet searches).

The app in question was deploying fine until the latest XCode update, but now fails to upload (build is successful obviously, and there have been code changes as well):

ERROR ITMS-90161: "Invalid Provisioning Profile. The provisioning profile included in the bundle *content removed* is invalid. [Missing code-signing certificate]. A Distribution Provisioning profile should be used when submitting apps to the App Store. For more information, visit the iOS Developer Portal."

It's not the first time I've mysteriously had a failure like this, but in prior cases simply revoking the certs, removing the profile, then rebuilding would take care of it.  Not so in this case.

The provisioning profile is confirmed to be the correct type, and the code signing certificate sure looks like it's in there...  Certificate gets a nice green checkmark too.  Any new suggestions not covered in the usual places?


答:
Use number instead of number[i].

Remember, you're already iterating over testa.

Title: Float object is not subscriptable with enumerate but works with range and if-else


问:
Laravel mix doesn't see img elements in vue components
Laravel Mix moves images that used in scss from resources folder to public folder, but doesn't moves images from src attribute of img tags that I use in my vuejs components...  </p>

```<code><img src="images/logo.png" >
</code>```

<p>What I have to do? </p>

答:
Change your code to

Edit

The image tag should be , considering the relative path from resouces/assets/js/components/Example.vue to resources/assets/img/logo.jpg.

Body:
Laravel Mix moves images that used in scss from resources folder to public folder, but doesn't moves images from src attribute of img tags that I use in my vuejs components...

What I have to do?

Body:
Change your code to
<img src="./images/logo.png" >

Edit

The image tag should be , considering the relative path from resouces/assets/js/components/Example.vue to resources/assets/img/logo.jpg.


问:
Convert character 'A' to 'B' if I add 1
Suppose you have one character/string, "A".

What do you write to convert it to 'B' if add 1 to 'A'. If I add '2' it should be converted to 'C' and so on...

Title: Convert character 'A' to 'B' if I add 1

Body:
You could roundtrip via .ord

'a'.ord # => 97
'a'.ord + 2 # => 99
('a'.ord + 2).chr # => "c"
('A'.ord + 5).chr # => "F"