问:
CORS issue with UseOpenIdConnectAuthentication
Here Angularjs is front end and Web API is middle tier. we are using AzureAD OpenID connect for Authentication.

I'm facing following issue. because of the my landing page is not loading

Access to XMLHttpRequest at 'https://login.microsoftonline.com/xx-86f1-41af-91ab-xxx/oauth2/authorize?client_id=xxxx1&response_mode=form_post&response_type=code%20id_token&scope=openid%20profile&state=OpenIdConnect.AuthenticationPropertiesxxxxx&noncexxxxx&redirect_uri=https%3A%2F%2Flocalhost%3A44300%2F&x-client-SKU=ID_NET451&x-client-ver=5.2.1.0' (redirected from 'https%3A%2F%2Flocalhost%3A44300%2F/api/Scorecard/GetServiceNameWithManagers?loginUser=xxx@microsoft.com') from origin 'https%3A%2F%2Flocalhost%3A44300%2F' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've done lot of research and applied Access-Control-Allow-Origin =* at Request and response. also applied app.UseCors(Owin.Cors.CorsOptions.AllowAll);
but so far no success.

consider following code, AuthorizationCodeReceived delegate is not invoking very first time even though the user is logged in to microsoft site.

Please be noted, this code is not working very first time. It will work after few button clicks (postbacks) and then after few minutes if we run the application it's throws CORS preflight issue. Please help.

This is my startup.cs

```<code>    public void Configuration(IAppBuilder app)
    {
        app.UseCors(Owin.Cors.CorsOptions.AllowAll);
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies",
            CookieManager = new SystemWebChunkingCookieManager(),
        });

        //// Bearer token authentication middleware.(Ex: request from web clients,ajax calls able to pass authenticated bearer info)
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
          new WindowsAzureActiveDirectoryBearerAuthenticationOptions
          {
              TokenValidationParameters = new TokenValidationParameters
              {
                  ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
                  TokenReplayCache = new TokenReplayCache(new MemoryCacheProvider())
              },
              Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
              Provider = new OAuthBearerAuthenticationProvider
              {
                  OnValidateIdentity = ctx =>
                  {
                      //// Retrieve user roles from the request.
                      var authenticationTicket = ctx.Ticket;
                      if (authenticationTicket.Identity.IsAuthenticated)
                      {
                          ////Use the block when role/user specific authorization needs and to modify the user identity claims based on requirement
                      }

                      return Task.FromResult(0);
                  },
                  OnRequestToken = ctx => { return Task.FromResult(0); }
              }
          });

        //// Non Bearer authentication middleware. (Ex: request secured web api call directly from URL/Web API server scope it self)
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = ClientId,
                ClientSecret = ConfigurationManager.AppSettings["ida:AppKey"],
                Authority = Authority,
                PostLogoutRedirectUri = PostLogoutRedirectUri,
                AuthenticationMode = AuthenticationMode.Active,
                ResponseType = "code id_token",
                CallbackPath = new PathString("/"),

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    SecurityTokenValidated = context =>
                    {
                        if (context.AuthenticationTicket.Identity.IsAuthenticated)
                        {
                            ////Use the block when role/user specific authorization needs and to modify the user identity claims based on requirement
                        }

                        return Task.FromResult(0);
                    },
                    AuthorizationCodeReceived = async context =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(ClientId, Models.ConfigurationData.GraphSecret);
                        string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
                        Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, GraphResource);
                    },
                    RedirectToIdentityProvider = context =>
                    {

                        if (context.ProtocolMessage.RedirectUri == null)
                        {
                            ////To set the reply/redirect Url based on the request host environment.
                            ////Hosting env details we get only through the owin context in startup and this is the delegate to set reply URL in OWincontext before the authentication.
                            string ReplyAddress = context.Request.Scheme + "://" + context.Request.Host + "/";
                            context.ProtocolMessage.RedirectUri = ReplyAddress;
                        }
                        //context.OwinContext.Authentication.User.Identity.IsAuthenticated = true;
                        if (context.OwinContext.Authentication.User.Identity.IsAuthenticated && context.ProtocolMessage.RequestType != IdentityModel.Protocols.OpenIdConnect.OpenIdConnectRequestType.Logout)
                        {
                            ////To avoid infinite loop of redirections in request if user is authenticated and unauthorized.
                            context.HandleResponse();
                            context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        }

                        return Task.FromResult(0);
                    }
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    RoleClaimType = "roles",
                    TokenReplayCache = new TokenReplayCache(new MemoryCacheProvider())
                },
            });
        System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier = System.IdentityModel.Claims.ClaimTypes.NameIdentifier;
    }
</code>```

Access to XMLHttpRequest at 'https://login.microsoftonline.com/xx-86f1-41af-91ab-xxx/oauth2/authorize?client_id=xxxx1&response_mode=form_post&response_type=code%20id_token&scope=openid%20profile&state=OpenIdConnect.AuthenticationPropertiesxxxxx&noncexxxxx&redirect_uri=https%3A%2F%2Flocalhost%3A44300%2F&x-client-SKU=ID_NET451&x-client-ver=5.2.1.0' (redirected from 'https%3A%2F%2Flocalhost%3A44300%2F/api/Scorecard/GetServiceNamxxxManagers?loginUser=xxx@microsoft.com') from origin 'https%3A%2F%2Flocalhost%3A44300%2F' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

答:
I think you misunderstood the error message. It says that your AngularJS application was trying to make a request to https://login.microsoftonline.com/xxx-xx-41af-91ab-xxx/oauth2/authorize and failed, because it was a cross-origin request and the server didn't approve it by returning the Access-Control-Allow-Origin header in a response to preflight request (HTTP method OPTIONS).

So you cannot change it by adding CORS headers to your backend. The authorize is not designed to be called by XMLHttpRequest requests - you are supposed to make a full browser request to that URL. Later, the browser will be redirected to redirect_uri (the request parameter value) along with an auth code or an error.

Body:
Here Angularjs is front end and Web API is middle tier. we are using AzureAD OpenID connect for Authentication.

I'm facing following issue. because of the my landing page is not loading

Access to XMLHttpRequest at 'https://login.microsoftonline.com/xx-86f1-41af-91ab-xxx/oauth2/authorize?client_id=xxxx1&response_mode=form_post&response_type=code%20id_token&scope=openid%20profile&state=OpenIdConnect.AuthenticationPropertiesxxxxx&noncexxxxx&redirect_uri=https%3A%2F%2Flocalhost%3A44300%2F&x-client-SKU=ID_NET451&x-client-ver=5.2.1.0' (redirected from 'https%3A%2F%2Flocalhost%3A44300%2F/api/Scorecard/GetServiceNameWithManagers?loginUser=xxx@microsoft.com') from origin 'https%3A%2F%2Flocalhost%3A44300%2F' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've done lot of research and applied Access-Control-Allow-Origin =* at Request and response. also applied app.UseCors(Owin.Cors.CorsOptions.AllowAll);
but so far no success.

consider following code, AuthorizationCodeReceived delegate is not invoking very first time even though the user is logged in to microsoft site.

Please be noted, this code is not working very first time. It will work after few button clicks (postbacks) and then after few minutes if we run the application it's throws CORS preflight issue. Please help.

This is my startup.cs

    public void Configuration(IAppBuilder app)
    {
        app.UseCors(Owin.Cors.CorsOptions.AllowAll);
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies",
            CookieManager = new SystemWebChunkingCookieManager(),
        });

        //// Bearer token authentication middleware.(Ex: request from web clients,ajax calls able to pass authenticated bearer info)
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
          new WindowsAzureActiveDirectoryBearerAuthenticationOptions
          {
              TokenValidationParameters = new TokenValidationParameters
              {
                  ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
                  TokenReplayCache = new TokenReplayCache(new MemoryCacheProvider())
              },
              Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
              Provider = new OAuthBearerAuthenticationProvider
              {
                  OnValidateIdentity = ctx =>
                  {
                      //// Retrieve user roles from the request.
                      var authenticationTicket = ctx.Ticket;
                      if (authenticationTicket.Identity.IsAuthenticated)
                      {
                          ////Use the block when role/user specific authorization needs and to modify the user identity claims based on requirement
                      }

                      return Task.FromResult(0);
                  },
                  OnRequestToken = ctx => { return Task.FromResult(0); }
              }
          });

        //// Non Bearer authentication middleware. (Ex: request secured web api call directly from URL/Web API server scope it self)
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = ClientId,
                ClientSecret = ConfigurationManager.AppSettings["ida:AppKey"],
                Authority = Authority,
                PostLogoutRedirectUri = PostLogoutRedirectUri,
                AuthenticationMode = AuthenticationMode.Active,
                ResponseType = "code id_token",
                CallbackPath = new PathString("/"),

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    SecurityTokenValidated = context =>
                    {
                        if (context.AuthenticationTicket.Identity.IsAuthenticated)
                        {
                            ////Use the block when role/user specific authorization needs and to modify the user identity claims based on requirement
                        }

                        return Task.FromResult(0);
                    },
                    AuthorizationCodeReceived = async context =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(ClientId, Models.ConfigurationData.GraphSecret);
                        string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
                        Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, GraphResource);
                    },
                    RedirectToIdentityProvider = context =>
                    {

                        if (context.ProtocolMessage.RedirectUri == null)
                        {
                            ////To set the reply/redirect Url based on the request host environment.
                            ////Hosting env details we get only through the owin context in startup and this is the delegate to set reply URL in OWincontext before the authentication.
                            string ReplyAddress = context.Request.Scheme + "://" + context.Request.Host + "/";
                            context.ProtocolMessage.RedirectUri = ReplyAddress;
                        }
                        //context.OwinContext.Authentication.User.Identity.IsAuthenticated = true;
                        if (context.OwinContext.Authentication.User.Identity.IsAuthenticated && context.ProtocolMessage.RequestType != IdentityModel.Protocols.OpenIdConnect.OpenIdConnectRequestType.Logout)
                        {
                            ////To avoid infinite loop of redirections in request if user is authenticated and unauthorized.
                            context.HandleResponse();
                            context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        }

                        return Task.FromResult(0);
                    }
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    RoleClaimType = "roles",
                    TokenReplayCache = new TokenReplayCache(new MemoryCacheProvider())
                },
            });
        System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier = System.IdentityModel.Claims.ClaimTypes.NameIdentifier;
    }

Access to XMLHttpRequest at 'https://login.microsoftonline.com/xx-86f1-41af-91ab-xxx/oauth2/authorize?client_id=xxxx1&response_mode=form_post&response_type=code%20id_token&scope=openid%20profile&state=OpenIdConnect.AuthenticationPropertiesxxxxx&noncexxxxx&redirect_uri=https%3A%2F%2Flocalhost%3A44300%2F&x-client-SKU=ID_NET451&x-client-ver=5.2.1.0' (redirected from 'https%3A%2F%2Flocalhost%3A44300%2F/api/Scorecard/GetServiceNamxxxManagers?loginUser=xxx@microsoft.com') from origin 'https%3A%2F%2Flocalhost%3A44300%2F' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.


来源: stackexchange

问:
FParsec: how to omit `many` parser failures from error messages
Consider this parser that converts digit strings to ints:

```<code>let toInt (s:string) =
    match Int32.TryParse(s) with
    | (true, n) -> preturn n
    | _         -> fail "Number must be below 2147483648"

let naturalNum = many1Chars digit >>= toInt <?> "natural number"
</code>```

When I run it on non-numeric strings like "abc" it shows the correct error message:

Error in Ln: 1 Col: 1
abc
^
Expecting: natural number
```

<p>But when I give it a numeric string exceeding the <code>int</code> range it gives the following counter-productive message:</p>

<pre class="lang-none prettyprint-override"><code>Error in Ln: 1 Col: 17
9999999999999999
                ^
Note: The error occurred at the end of the input stream.
Expecting: decimal digit
Other error messages:
  Number must be below 2147483648
</code>```

The primary message "Expecting: decimal digit" makes no sense, because we have to many digits already.

Is there a way to get rid of it and only show "Number must be below 2147483648"?

Full example:

```<code>open System
open FParsec

[<EntryPoint>]
let main argv =
    let toInt (s:string) =
        match Int32.TryParse(s) with
        | (true, n) -> preturn n
        | _         -> fail "Number must be below 2147483648"

    let naturalNum = many1Chars digit >>= toInt <?> "natural number"

    match run naturalNum "9999999999999999" with
    | Failure (msg, _, _) -> printfn "%s" msg
    | Success (a, _, _)   -> printfn "%A" a

    0
</code>```

答:
I think the root of the problem here is that this is a non-syntactic concern, which doesn't fit well with the model of a lookahead parser. If you could express "too many digits" in a syntactic way, it would make sense for the parser too, but as it is it will instead go back and try to consume more input. I think the cleanest solution therefore would be to do the int conversion in a separate pass after the parsing.

That said, FParsec seems flexible enough that you should still be able to hack it together. This does what you ask I think:

```<code>let naturalNum: Parser<int, _> =
    fun stream ->
        let reply = many1Chars digit stream
        match reply.Status with
            | Ok ->
                match Int32.TryParse(reply.Result) with
                | (true, n) -> Reply(n)
                | _         -> Reply(Error, messageError "Number must be below 2147483648")
            | _ ->
                Reply(Error, reply.Error)
</code>```

Or if you want the "natural number" error message instead of "decimal digit", replace the last line with:

```<code>Reply(Error, messageError "Expecting: natural number")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Consider this parser that converts digit strings to ints:

let toInt (s:string) =
    match Int32.TryParse(s) with
    | (true, n) -> preturn n
    | _         -> fail "Number must be below 2147483648"

let naturalNum = many1Chars digit >>= toInt <?> "natural number"

When I run it on non-numeric strings like "abc" it shows the correct error message:

Error in Ln: 1 Col: 1
abc
^
Expecting: natural number

But when I give it a numeric string exceeding the int range it gives the following counter-productive message:

Error in Ln: 1 Col: 17
9999999999999999
                ^
Note: The error occurred at the end of the input stream.
Expecting: decimal digit
Other error messages:
  Number must be below 2147483648

The primary message "Expecting: decimal digit" makes no sense, because we have to many digits already.

Is there a way to get rid of it and only show "Number must be below 2147483648"?

Full example:

open System
open FParsec

[<EntryPoint>]
let main argv =
    let toInt (s:string) =
        match Int32.TryParse(s) with
        | (true, n) -> preturn n
        | _         -> fail "Number must be below 2147483648"

    let naturalNum = many1Chars digit >>= toInt <?> "natural number"

    match run naturalNum "9999999999999999" with
    | Failure (msg, _, _) -> printfn "%s" msg
    | Success (a, _, _)   -> printfn "%A" a

    0

Body:
I think the root of the problem here is that this is a non-syntactic concern, which doesn't fit well with the model of a lookahead parser. If you could express "too many digits" in a syntactic way, it would make sense for the parser too, but as it is it will instead go back and try to consume more input. I think the cleanest solution therefore would be to do the int conversion in a separate pass after the parsing.

That said, FParsec seems flexible enough that you should still be able to hack it together. This does what you ask I think:

let naturalNum: Parser<int, _> =
    fun stream ->
        let reply = many1Chars digit stream
        match reply.Status with
            | Ok ->
                match Int32.TryParse(reply.Result) with
                | (true, n) -> Reply(n)
                | _         -> Reply(Error, messageError "Number must be below 2147483648")
            | _ ->
                Reply(Error, reply.Error)

Or if you want the "natural number" error message instead of "decimal digit", replace the last line with:

Reply(Error, messageError "Expecting: natural number")


问:
Xamarin Forms Collection view ItemsSource Binding not updating the UI
Xamarin.Forms 4.0 collection view ItemsSource binding is not working as expected if I set the binding in code behind. The items are displayed based on the initial value of the source collection but, the UI is not updating when the source collection is updated. Same is working if I set the binding in xaml.

Code behind:

```<code>    public MainPage()
    {
        this.InitializeComponent();
        this.BindingContext = this.mainViewModel = new MainViewModel();

        CollectionView courseCollectionView = new CollectionView
        {
            ItemSizingStrategy = ItemSizingStrategy.MeasureFirstItem,
            ItemTemplate = new DataTemplate(typeof(ItemView))
        };

     courseCollectionView.SetBinding(CollectionView.ItemsSourceProperty,
     new Binding() { Source = this.mainViewModel.CountryNames, Mode =
     BindingMode.TwoWay });

     courseCollectionView.ItemsLayout = new GridItemsLayout(4,
      ItemsLayoutOrientation.Vertical);

        this.CoursesStack.Children.Clear();
        this.CoursesStack.Children.Add(courseCollectionView);

    }
</code>```

View Model Property which is using for ItemsSource Binding:

```<code>   ObservableCollection<Country> countryNames;

    public ObservableCollection<Country> CountryNames
    {
        get => this.countryNames;
        set
        {
            this.countryNames = value;
            RaisePropertyChanged("CountryNames");
        }
    }
</code>```

Expected: View should be updated as per the changes made to the ObsevableCollection (add/delete items from collection) which is bound to the ItemsSource Property.

Actual: View is not updated with changes to the ObservableCollection.

答:
I believe your binding is wrong. Try:
courseCollectionView.SetBinding(CollectionView.ItemsSourceProperty, nameof(mainViewModel.CountryNames));

You need to specify the Path (mainViewModel.CountryNames) and not the Source

Body:
Xamarin.Forms 4.0 collection view ItemsSource binding is not working as expected if I set the binding in code behind. The items are displayed based on the initial value of the source collection but, the UI is not updating when the source collection is updated. Same is working if I set the binding in xaml.

Code behind:

    public MainPage()
    {
        this.InitializeComponent();
        this.BindingContext = this.mainViewModel = new MainViewModel();

        CollectionView courseCollectionView = new CollectionView
        {
            ItemSizingStrategy = ItemSizingStrategy.MeasureFirstItem,
            ItemTemplate = new DataTemplate(typeof(ItemView))
        };

     courseCollectionView.SetBinding(CollectionView.ItemsSourceProperty,
     new Binding() { Source = this.mainViewModel.CountryNames, Mode =
     BindingMode.TwoWay });

     courseCollectionView.ItemsLayout = new GridItemsLayout(4,
      ItemsLayoutOrientation.Vertical);

        this.CoursesStack.Children.Clear();
        this.CoursesStack.Children.Add(courseCollectionView);

    }

View Model Property which is using for ItemsSource Binding:

   ObservableCollection<Country> countryNames;

    public ObservableCollection<Country> CountryNames
    {
        get => this.countryNames;
        set
        {
            this.countryNames = value;
            RaisePropertyChanged("CountryNames");
        }
    }

Expected: View should be updated as per the changes made to the ObsevableCollection (add/delete items from collection) which is bound to the ItemsSource Property.

Actual: View is not updated with changes to the ObservableCollection.


问:
Can I get "&&" or "-and" to work in PowerShell?
Note: This question originally asked in 2009, when powershell did not have support for the && operator.
In 2019, per Jay's answer, microsoft added support for && and || in Powershell 7.
https://stackoverflow.com/a/564092/234

Original Question

&& is notoriously hard to search for on Google Search, but the best I've found is this article which says to use -and.

Unfortunately it doesn't give any more information, and I can't find out what I'm supposed to do with -and (again, a notoriously hard thing to search for).

The context I'm trying to use it in is "execute cmd1, and if successful, execute cmd2", basically this:

```<code>csc /t:exe /out:a.exe SomeFile.cs && a.exe
</code>```

If you just want to run multiple commands on a single line and you don't care if the first one fails or not, you can use ; For most of my purposes this is fine.

For example: kill -n myapp; ./myapp.exe.

答:
It depends on the context, but here's an example of "-and" in action:

```<code>get-childitem | where-object { $_.Name.StartsWith("f") -and $_.Length -gt 10kb }
</code>```

So that's getting all the files bigger than 10kb in a directory whose filename starts with "f".

OwnerDisplayName: Orion Edwards

Body:
Note: This question originally asked in 2009, when powershell did not have support for the && operator.
In 2019, per Jay's answer, microsoft added support for && and || in Powershell 7.
https://stackoverflow.com/a/564092/234

Original Question

&& is notoriously hard to search for on Google Search, but the best I've found is this article which says to use -and.

Unfortunately it doesn't give any more information, and I can't find out what I'm supposed to do with -and (again, a notoriously hard thing to search for).

The context I'm trying to use it in is "execute cmd1, and if successful, execute cmd2", basically this:

csc /t:exe /out:a.exe SomeFile.cs && a.exe

If you just want to run multiple commands on a single line and you don't care if the first one fails or not, you can use ; For most of my purposes this is fine.

For example: kill -n myapp; ./myapp.exe.

LastEditorDisplayName: Orion Edwards

Body:
It depends on the context, but here's an example of "-and" in action:

get-childitem | where-object { $_.Name.StartsWith("f") -and $_.Length -gt 10kb }

So that's getting all the files bigger than 10kb in a directory whose filename starts with "f".

OwnerDisplayName: Matt Hamilton

ContentLicense: CC BY-SA 2.5


问:
Killing EXCEL.exe Process from C# in a Windows Service
I have a windows service that opens up an Excel spreadsheet via  the Microsoft.Office.Interop.Excel.Application object.

```<code>Application xlApp = new Application();
Workbook workbook = xlApp.Workbooks.Open(fileName, 2, false);
...
...
workbook.Close();
xlApp.Quit();
</code>```

I would like to kill the EXCEL.exe process that is left running after it is done working with the workbook.

I've tried the following with no success...

```<code>// This returns a processId of 0
IntPtr processId;
GetWindowThreadProcessId(new IntPtr(xlApp.Hwnd), out processId);
Process p = Process.GetProcessById(processId.ToInt32());
p.Kill();
</code>```

Anyone have any ideas as to how I can do this via a Windows Service?

答:
Properly closing the open Excel workbook and quitting the app is extremely difficult.  If I can find the links I'll post them, but essentially you must clean up all references to any COM object that you create.  This includes everything from ODBCConnections (data connections), Worksheets, Workbooks, and the Excel application.  A combination I got to work involved garbage collection and the System.Runtime.InteropServices.Marshal object:

```<code>// Garbage collecting
GC.Collect();
GC.WaitForPendingFinalizers();
// Clean up references to all COM objects
// As per above, you're just using a Workbook and Excel Application instance, so release them:
workbook.Close(false, Missing.Value, Missing.Value);
xlApp.Quit();
Marshal.FinalReleaseComObject(workbook);
Marshal.FinalReleaseComObject(xlApp);
</code>```

Like you mentioned, looping through and killing each Excel process is usually not a good idea, since if you're running this as a Windows app you may close Excel on your user, or in a service also close an instance of Excel that is running via some other program.

Edit: See this question for more info.

ContentLicense: CC BY-SA 3.0

Body:
I have a windows service that opens up an Excel spreadsheet via  the Microsoft.Office.Interop.Excel.Application object.

Application xlApp = new Application();
Workbook workbook = xlApp.Workbooks.Open(fileName, 2, false);
...
...
workbook.Close();
xlApp.Quit();

I would like to kill the EXCEL.exe process that is left running after it is done working with the workbook.

I've tried the following with no success...

// This returns a processId of 0
IntPtr processId;
GetWindowThreadProcessId(new IntPtr(xlApp.Hwnd), out processId);
Process p = Process.GetProcessById(processId.ToInt32());
p.Kill();

Anyone have any ideas as to how I can do this via a Windows Service?

Body:
Properly closing the open Excel workbook and quitting the app is extremely difficult.  If I can find the links I'll post them, but essentially you must clean up all references to any COM object that you create.  This includes everything from ODBCConnections (data connections), Worksheets, Workbooks, and the Excel application.  A combination I got to work involved garbage collection and the System.Runtime.InteropServices.Marshal object:

// Garbage collecting
GC.Collect();
GC.WaitForPendingFinalizers();
// Clean up references to all COM objects
// As per above, you're just using a Workbook and Excel Application instance, so release them:
workbook.Close(false, Missing.Value, Missing.Value);
xlApp.Quit();
Marshal.FinalReleaseComObject(workbook);
Marshal.FinalReleaseComObject(xlApp);

Like you mentioned, looping through and killing each Excel process is usually not a good idea, since if you're running this as a Windows app you may close Excel on your user, or in a service also close an instance of Excel that is running via some other program.

Edit: See this question for more info.


问:
Ajax call returning users error: length of the string exceeds the value set on the maxJsonLength property
I am making use of an ajax call to my controller that returns an array of around 10k users back to my view, which is used for pinning users. However, I am getting this error.

I have read up on a lot of posts and have see the following, and tried it, but still getting the same issue:

Tried adding the below into my web.config:

```<code><system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength = "2147483647"></jsonSerialization>
      </webServices>
    </scripting>
</system.web.extensions>
</code>```

I have also added this to my actionresult:

```<code>var objJSS = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

return Json(objJSS.Serialize(pinnedUsers), JsonRequestBehavior.AllowGet);
</code>```

Below is my entire actionresult:

```<code>public ActionResult GetPinnedUsers()
        {
            clsComments clsComments = new clsComments();
            PinnedUsersViewModel[] pinnedUsers;

            pinnedUsers = clsComments.GetPinnedUsers();

            //var jsonResult = Json(pinnedUsers, JsonRequestBehavior.AllowGet);
            //jsonResult.MaxJsonLength = int.MaxValue;

            var objJSS = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

            return Json(objJSS.Serialize(pinnedUsers), JsonRequestBehavior.AllowGet);
        }
</code>```

Below is my Ajax call:

```<code>$.ajax({
        type: 'get',
        traditional: true,
        url: '@Url.Action("GetPinnedUsers", "ILearn")',
        success: function (usersArray) {
                                    success(usersArray)
                                 },
                                error: error
                            });
</code>```

Am I doing something incorrect or missing something ? Or is there another way of getting all the users passed to my view ?

Thanks for any assistance.

答:
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue; //Or any size you want to use, basically int maxValue is 2GB, you shouldn't need this big json string to deserialize, else you are doing it wrong.
myObject obj = serializer.Deserialize<myObject>(yourJsonString);

you can try this when you try to deserialise the JSON string.

Body:
I am making use of an ajax call to my controller that returns an array of around 10k users back to my view, which is used for pinning users. However, I am getting this error.

I have read up on a lot of posts and have see the following, and tried it, but still getting the same issue:

Tried adding the below into my web.config:

<system.web.extensions>

</system.web.extensions>

I have also added this to my actionresult:

var objJSS = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

return Json(objJSS.Serialize(pinnedUsers), JsonRequestBehavior.AllowGet);

Below is my entire actionresult:

public ActionResult GetPinnedUsers()
        {
            clsComments clsComments = new clsComments();
            PinnedUsersViewModel[] pinnedUsers;

            pinnedUsers = clsComments.GetPinnedUsers();

            //var jsonResult = Json(pinnedUsers, JsonRequestBehavior.AllowGet);
            //jsonResult.MaxJsonLength = int.MaxValue;

            var objJSS = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

            return Json(objJSS.Serialize(pinnedUsers), JsonRequestBehavior.AllowGet);
        }

Below is my Ajax call:

$.ajax({
        type: 'get',
        traditional: true,
        url: '@Url.Action("GetPinnedUsers", "ILearn")',
        success: function (usersArray) {
                                    success(usersArray)
                                 },
                                error: error
                            });

Am I doing something incorrect or missing something ? Or is there another way of getting all the users passed to my view ?

Thanks for any assistance.


问:
Weird fade transition that is not wanted with fullpage.js and midnight.js
I have a wordpress site I'm creating using fullpage.js and using the midnight.js with jquery. When I scroll down the logo changes color but it is delayed. for the life of me I cannot figure out where the delay is coming from. Here is the testing site. https://trailheadnc.org</p>

答:
I don't know how midnight.js works, but I know how fullPage.js does :)

Probably the easiest fix you'll be able to find is using the fullPage.js option scrollBar:true.

That should make the site act as any other site, firing the scroll event.

Dealing with css3 transformations might be the cause of midnight.js not working properly. Browsers still have it difficult to achieve certain things and might require the transformations to end to apply the changes.

If you really do not want to show the scroll bar by using scrollBar:true, then you can try using css3:false. This way fullPage.js will change the top property of the site and you might not encounter the same issues you have when dealing with 3d transformations.


问:
Laravel JSON Where Clauses with number in key
I have table with json column "options".
Exemple:

```<code> {"language":"en" }
</code>```

When i doing query, it's OK:

```<code>DB::table('users')->where('options->language', 'en')->get();
</code>```

But if i have number key:

```<code>{"221":"en" }
</code>```

I get empty array:

```<code>DB::table('users')->where('options->221', 'en')->get();
</code>```

How i can get true query?
Laravel 5.2

答:
Try to use whereJsonContains method. In your case:

DB::table('users')->whereJsonContaints('options', ['221' => 'en'])->get();
```

Body:
I have table with json column "options".
Exemple:

 {"language":"en" }

When i doing query, it's OK:

DB::table('users')->where('options->language', 'en')->get();

But if i have number key:

{"221":"en" }

I get empty array:

DB::table('users')->where('options->221', 'en')->get();

How i can get true query?
Laravel 5.2


问:
Invoke delegate on main thread - No UI
I've been reading all sorts of questions that are similar to what I'm trying to do, but different enough that they do not seem to apply.  What I have is a C# project to create a CLR stored procedure.  I'm in the process of improving performance on the CLR Stored Procedure by multi-threading it.  (It has a set of nested loops, and on the inner-most loop I'm calling Parallel.ForEach to run them all on their own threads.)  Well, sometimes the processing that's done needs to execute a query against the database.  This is done using the context connection that launched the stored procedure in the first place.  And here's my problem.  SQL Server will not let you access the context connection from a child thread.  If you're going to access the context connection, you must be executing on the main thread.

Since this is not a WinForms project, I can't make use of BeginInvoke.  (And I know there's a similar command for WPF applications.)  And I've seen several posts discussing the use of SynchronizationContext to do this.  But my main thread does not have a SynchronizationContext to reference.  (I think that's created by the first control placed on the thread?)  I need to figure out how to marshal execution back onto the main thread just enough to access the context connection.  I'm still somewhat new to working with multi-threaded applications.  So I apologize if my terminology usage was poor or imprecise.

Thanks.

Edit:

So, based on the comments and answer, so far, I tried making some changes, but I'm afraid that either they're not working or I'm just not getting something.  So I thought I'd post some simplified code as an example of what I'm currently doing.  (Remember that this example does not work because the query execution is taking place on the child threads and only the main thread can make use of the context connection.)

```<code>public class MyDatabaseProject
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static int MyClrStoredProcedure(...)
    {
        ProcessingEngine engine = new ProcessingEngine();
        engine.SomeQueryEvent += this.HandleSomeQueryEvent;

        ...  // Gather up some data to process.

        DataTable results = engine.Compute(...);

        ...  // Save the computed results DataTable.
    }

    private static void HandleSomeQueryEvent(object Sender, MyEventArgs e)
    {
        SqlConnection contextConn = new SqlConnection("context connection=true");
        contextConn.Open();

        foreach (string query in e.QueriesToExecute)
        {
            // Use the contextConnection to execute the query and store the results in MyEventArgs.
        }
        contextConn.Close();
    }
}

public class ProcessingEngine
{
    public DataTable Compute(...)
    {
        ... // Do stuff

        foreach(var timingIndicator in SomeCollection)
        {
            ... // Do stuff

            Parallel.ForEach(FormulasToProcessNow, new ParallelOptions { MaxDegreeOfParallelism = this.ConcurrencyLevel }, r =>
            {
                ... // Do stuff, including raising "SomeQueryEvent"

                ... // Do stuff with the results of the queries.
            });
        }
    }
}
</code>```

So what's confusing me is how to incorporate your suggestions (such as the ConcurrentQueue and AutoResetEvent) in a way that will work.  Hopefully this code is helpful.  Thanks, again.

答:
Is there a reason why you need to use the Context Connection? Are you using any Session-specific functionality, such as being part of an existing transaction, or reading from existing temp tables, or using CONTEXT_INFO / SESSION_CONTEXT?

Is there a reason why you just don't use a regular / external connection?

(those questions were answered with the following quoted statements)

We want this to run with the user's security, connection settings, etc. Besides, if I attempt to open a connection from within the code, SQL Server raises an exception. So, to be honest, I haven't given that much thought. Opening another connection wasn't allowed, and we wanted to use the context connection, anyway. So that's what we did.

Running with the User's security is easy enough:

If the User is a SQL Server Login, pass those credentials along in the ConnectionString. This might be more difficult if there are a lot of Users that could be executing this code, though you could have the User pass in their credentials as input parameters to the SQLCLR stored procedure and build the Connection String from those.

If the User is a Windows Login, implement Impersonation. You can get the Windows Security Principal (or whatever) from SqlContext. Then do:

```<code>using(impersonationContext = principal.Impersonate())
{
  connection.Open();

  ...

  impersonationContext.Undo();
}
</code>```

That's not exact, but it's close.

Not sure why you would get an exception when opening a regular connection, unless something was off with the connection string. It would help to have the exact (and complete) error message, though it sounds like you have gotten passed this problem at this point.

Okay, so we actually ended up going with this. For these queries, we do not require the context connection. So we were able to get away with opening up new connections, instead of figuring out how to switch threads effectively.

Excellent! Glad to hear that it worked out after all 😺 . Since the Context Connection was not required, it seems like it would have taken more time / effort to figure out the thread-switching than it would have been worth. And, the code would like have been quite a bit more complicated (i.e. harder to maintain) than what you ended up with.

I suspect that if we had architected this from the beginning to run these queries on the main thread that it wouldn't have been such an issue. But this seems to get the job done.

True, it might have been less complicated had you planned that part out from the beginning. However, that would have introduced a point-of-contention on that singular connection, which would decrease performance (even if only slightly). Even with the Context Connection being faster to open/close than a regular connection, depending on how long it takes to get results back from the queries, the various threads could potentially be waiting around far longer than the few extra milliseconds eaten up by establishing regular connections. That, plus the increased complexity of the code, might well be worth it if you require session-specific functionality (i.e. working within an active transaction, working with local temporary objects, using CONTEXT_INFO and/or SESSION_CONTEXT, etc), but otherwise probably not.

For more info on working with SQLCLR in general, please visit: SQLCLR Info

Title: Invoke delegate on main thread - No UI

Body:
I've been reading all sorts of questions that are similar to what I'm trying to do, but different enough that they do not seem to apply.  What I have is a C# project to create a CLR stored procedure.  I'm in the process of improving performance on the CLR Stored Procedure by multi-threading it.  (It has a set of nested loops, and on the inner-most loop I'm calling Parallel.ForEach to run them all on their own threads.)  Well, sometimes the processing that's done needs to execute a query against the database.  This is done using the context connection that launched the stored procedure in the first place.  And here's my problem.  SQL Server will not let you access the context connection from a child thread.  If you're going to access the context connection, you must be executing on the main thread.

Since this is not a WinForms project, I can't make use of BeginInvoke.  (And I know there's a similar command for WPF applications.)  And I've seen several posts discussing the use of SynchronizationContext to do this.  But my main thread does not have a SynchronizationContext to reference.  (I think that's created by the first control placed on the thread?)  I need to figure out how to marshal execution back onto the main thread just enough to access the context connection.  I'm still somewhat new to working with multi-threaded applications.  So I apologize if my terminology usage was poor or imprecise.

Thanks.

Edit:

So, based on the comments and answer, so far, I tried making some changes, but I'm afraid that either they're not working or I'm just not getting something.  So I thought I'd post some simplified code as an example of what I'm currently doing.  (Remember that this example does not work because the query execution is taking place on the child threads and only the main thread can make use of the context connection.)

public class MyDatabaseProject
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static int MyClrStoredProcedure(...)
    {
        ProcessingEngine engine = new ProcessingEngine();
        engine.SomeQueryEvent += this.HandleSomeQueryEvent;

        ...  // Gather up some data to process.

        DataTable results = engine.Compute(...);

        ...  // Save the computed results DataTable.
    }

    private static void HandleSomeQueryEvent(object Sender, MyEventArgs e)
    {
        SqlConnection contextConn = new SqlConnection("context connection=true");
        contextConn.Open();

        foreach (string query in e.QueriesToExecute)
        {
            // Use the contextConnection to execute the query and store the results in MyEventArgs.
        }
        contextConn.Close();
    }
}

public class ProcessingEngine
{
    public DataTable Compute(...)
    {
        ... // Do stuff

        foreach(var timingIndicator in SomeCollection)
        {
            ... // Do stuff

            Parallel.ForEach(FormulasToProcessNow, new ParallelOptions { MaxDegreeOfParallelism = this.ConcurrencyLevel }, r =>
            {
                ... // Do stuff, including raising "SomeQueryEvent"

                ... // Do stuff with the results of the queries.
            });
        }
    }
}

So what's confusing me is how to incorporate your suggestions (such as the ConcurrentQueue and AutoResetEvent) in a way that will work.  Hopefully this code is helpful.  Thanks, again.

Body:
Is there a reason why you need to use the Context Connection? Are you using any Session-specific functionality, such as being part of an existing transaction, or reading from existing temp tables, or using CONTEXT_INFO / SESSION_CONTEXT?

Is there a reason why you just don't use a regular / external connection?

(those questions were answered with the following quoted statements)

We want this to run with the user's security, connection settings, etc. Besides, if I attempt to open a connection from within the code, SQL Server raises an exception. So, to be honest, I haven't given that much thought. Opening another connection wasn't allowed, and we wanted to use the context connection, anyway. So that's what we did.

Running with the User's security is easy enough:

If the User is a SQL Server Login, pass those credentials along in the ConnectionString. This might be more difficult if there are a lot of Users that could be executing this code, though you could have the User pass in their credentials as input parameters to the SQLCLR stored procedure and build the Connection String from those.

If the User is a Windows Login, implement Impersonation. You can get the Windows Security Principal (or whatever) from SqlContext. Then do:

using(impersonationContext = principal.Impersonate())
{
  connection.Open();

  ...

  impersonationContext.Undo();
}

That's not exact, but it's close.

Not sure why you would get an exception when opening a regular connection, unless something was off with the connection string. It would help to have the exact (and complete) error message, though it sounds like you have gotten passed this problem at this point.

Okay, so we actually ended up going with this. For these queries, we do not require the context connection. So we were able to get away with opening up new connections, instead of figuring out how to switch threads effectively.

Excellent! Glad to hear that it worked out after all 😺 . Since the Context Connection was not required, it seems like it would have taken more time / effort to figure out the thread-switching than it would have been worth. And, the code would like have been quite a bit more complicated (i.e. harder to maintain) than what you ended up with.

I suspect that if we had architected this from the beginning to run these queries on the main thread that it wouldn't have been such an issue. But this seems to get the job done.

True, it might have been less complicated had you planned that part out from the beginning. However, that would have introduced a point-of-contention on that singular connection, which would decrease performance (even if only slightly). Even with the Context Connection being faster to open/close than a regular connection, depending on how long it takes to get results back from the queries, the various threads could potentially be waiting around far longer than the few extra milliseconds eaten up by establishing regular connections. That, plus the increased complexity of the code, might well be worth it if you require session-specific functionality (i.e. working within an active transaction, working with local temporary objects, using CONTEXT_INFO and/or SESSION_CONTEXT, etc), but otherwise probably not.

For more info on working with SQLCLR in general, please visit: SQLCLR Info


问:
How to create a clean four-column, left-aligned, layout using justify-content: space-between
I am trying to create a display blog post component with Flexbox that primarily uses justify-content: space-between. In a 4-column layout, it looks great when there are 4 posts to fill the row. The issue is when there are not 4 posts, but 2 or 3. At this point, the posts get spread out and it just looks sloppy. I want to use flexbox without any JavaScript, and I want to be able to have the layout be fully responsive. So at other breakpoints the column layout will drop to 3, 2, or even 1.

One of the things that I found that works great is adding an :after pseudo element to the wrapper with a set width that will fill in the empty space. The problem with that is it is not dynamic enough and will not work properly if I have a different number of post then the one I planned for.

For example: If I have 2 posts, each at 25% width, and then a pseudo element at 50% width, everything looks great. Once I have 3 posts it is not so great because the 50% pseudo element now needs to be 25%. Finally, if there is 4 I wouldn't need a pseudo element at all.

I am trying to work with using some of the SASS selectors, but for some reason when I try to target the parent with my :after element, it targets something else way up the DOM tree.

.content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .entry:nth-child( 2 ):last-of-type {
        :after & {
            content: "";
            flex-grow: 0;
            width: 50%;
        }
    }
    .entry:nth-child( 3 ):last-of-type {
        :after & {
            content: "";
            flex-grow: 0;
            width: 50%;
        }
    }
}
```

At this point I expected the :after element to target the parent class "content" but it doesn't. I also didn't think about how I would adjust it to be more dynamic and be able to handle multiple rows. I guess I could just do the math and make it something like .entry:nth-child( 3n+4 ):last-of-type {}, but I haven't even gotten there yet.

答:
CSS-Grid would seem to be a better fit than flexbox here.

.content {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 1em;
  margin-bottom: 1em;
}

.red .entry {
  background: red;
}

.blue .entry {
  background: blue;
}

.green .entry {
  background: green;
}

.entry {
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content red">
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
</div>

<div class="content blue">
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
</div>

<div class="content green">
  <div class="entry"></div>
  <div class="entry"></div>
</div></code>```

Body:
I am trying to create a display blog post component with Flexbox that primarily uses justify-content: space-between. In a 4-column layout, it looks great when there are 4 posts to fill the row. The issue is when there are not 4 posts, but 2 or 3. At this point, the posts get spread out and it just looks sloppy. I want to use flexbox without any JavaScript, and I want to be able to have the layout be fully responsive. So at other breakpoints the column layout will drop to 3, 2, or even 1.

One of the things that I found that works great is adding an :after pseudo element to the wrapper with a set width that will fill in the empty space. The problem with that is it is not dynamic enough and will not work properly if I have a different number of post then the one I planned for.

For example: If I have 2 posts, each at 25% width, and then a pseudo element at 50% width, everything looks great. Once I have 3 posts it is not so great because the 50% pseudo element now needs to be 25%. Finally, if there is 4 I wouldn't need a pseudo element at all.

I am trying to work with using some of the SASS selectors, but for some reason when I try to target the parent with my :after element, it targets something else way up the DOM tree.

.content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .entry:nth-child( 2 ):last-of-type {
        :after & {
            content: "";
            flex-grow: 0;
            width: 50%;
        }
    }
    .entry:nth-child( 3 ):last-of-type {
        :after & {
            content: "";
            flex-grow: 0;
            width: 50%;
        }
    }
}

At this point I expected the :after element to target the parent class "content" but it doesn't. I also didn't think about how I would adjust it to be more dynamic and be able to handle multiple rows. I guess I could just do the math and make it something like .entry:nth-child( 3n+4 ):last-of-type {}, but I haven't even gotten there yet.

Body:
CSS-Grid would seem to be a better fit than flexbox here.

.content {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 1em;
  margin-bottom: 1em;
}

.red .entry {
  background: red;
}

.blue .entry {
  background: blue;
}

.green .entry {
  background: green;
}

.entry {
  height: 50px;
}

<div class="content red">
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
</div>

<div class="content blue">
  <div class="entry"></div>
  <div class="entry"></div>
  <div class="entry"></div>
</div>

<div class="content green">
  <div class="entry"></div>
  <div class="entry"></div>
</div>


问:
SimpleDateFormat parsing date string incorrectly
I'm trying to parse a String into a Date and then format that Date into a different String format for outputting.

My date formatting code is as follows:

```<code>SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("d/M/yyyy h:m:s a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));
</code>```

The result of sysObj.getString("document_date") is 1/31/2013 12:00:01 AM. And when I check the value of formattedDocumentDate I get 01/07/2015.

Any help is much appreciated.

答:
Another example like this

```<code>SimpleDateFormat sdfInput = new SimpleDateFormat("yyyyMMdd");
System.out.println("date is:"+new java.sql.Date( sdfInput.parse("20164129").getTime() ));
</code>```

Output is: 2019-05-29

I expect to throw parse exception  but not (41)is not a valid month value.
on the other hand if I gave 20170229, system can recognize the February of 2017 doesn't have a lap year and return 2017-03-01 interesting.

Body:
I'm trying to parse a String into a Date and then format that Date into a different String format for outputting.

My date formatting code is as follows:

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("d/M/yyyy h:m:s a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));

The result of sysObj.getString("document_date") is 1/31/2013 12:00:01 AM. And when I check the value of formattedDocumentDate I get 01/07/2015.

Any help is much appreciated.

Body:
Another example like this

SimpleDateFormat sdfInput = new SimpleDateFormat("yyyyMMdd");
System.out.println("date is:"+new java.sql.Date( sdfInput.parse("20164129").getTime() ));

Output is: 2019-05-29

I expect to throw parse exception  but not (41)is not a valid month value.
on the other hand if I gave 20170229, system can recognize the February of 2017 doesn't have a lap year and return 2017-03-01 interesting.


问:
Implementing a OnClick kind of functionality and formatting wrt Rails Partial-Views
I am trying to implement a functionality similar to the onclick method
of Javascript, using Rails Helpers.

I have implemented a auto complete feature for more than one field in
Rails 2.0.2 and Ruby 1.8.7. This configuration is run on Ubuntu 10.04
and yes , I know.. you might feel why Rails 2.x when we have Rails 3.x ,
it is so because of project specific purposes. I don't have much of a
choice on that ..:) .

I am able to successfully retrieve a group specific profile pic, a group
title and a the total number of members belonging to a group based on
the given "title" as the basic search query that a user inputs in the
text field where auto complete functionality is being performed. Getting
the auto complete functionality to work for the scenario above was a
challenge in itself.

In case you aren't able to get a better understanding of what I have
implemented wrt autocomplete, kindly refer to
Implementing auto complete for more than one field in Rails
.

You can also get a better understanding of what I have implemented by referring to http://imagepaste.nullnetwork.net/viewimage.php?id=2048  ,
http://imagepaste.nullnetwork.net/viewimage.php?id=2050
and http://imagepaste.nullnetwork.net/viewimage.php?id=2049 .

Please note the name of group specific profile pic is same as that of
the group title with the exception that the pic would also have .jpg
appended to it.

I am making use of a customized auto complete method, an auto complete
plugin and also making use of Rails partials. The cusotmized auto
complete method is allowing me to modify the basic functionality to suit
my requirement.

Coming to my question, Now say if a user enters "I" in the text field as
per the auto complete feature that I have implemented, the results(for
more than one matches found(i.e. if more than one group exists which
start with an "I") on a specific search query) populated on the User
Interface would have all the following :-

Group Specific Profile Pic(s) starting
with name same as title, in this case
"I%".jpg

Group title name.

Total number of members belonging to
a group

Say I have India and Independence as my group names I would obtain the
following results displayed in my auto complete text field.

```<code>India.jpg(image will be displayed)     India(Group title name displayed)               3(dummy value here)
</code>```

and similarly

```<code>Independence.jpg                     Independence
4
</code>```

All this would come in one text field. Please note the comments in
parentheses are not part of the results returned via auto complete.

In case you are not able to get the picture in your mind of how the UI
would look, Kindly register in www.diasp.org and search for any random
user using its search feature , once your account is created.

Please observe that the spacing between image, title name and total
number of group members is too much. I will be referring back to this in
the comments that follow.

The code for the partial that renders all this is:-

```<code><ul>
  <% for inv_group in @investor_group2 %>
  <%=image_tag "investor_groups/#{inv_group.title}.jpg" , :width =>
</code>```

'40', :height => '22', :align => 'left' %>
<%=h inv_group.title
%>(<%=h inv_group.activated_members.size %>)

      <%end%>

Now if a user hovers his/her mouse over say India and then clicks on it,
the text field is populated with **India(3)** .

What I need is to implement is a on click in Rails which will
select only Group title. I tried to implement the group title and
group size with separate
 tags , I was then able to mouseover and
select only the title and get it populated for the text field.

The problem with this approach is it completely spoils the formatting
and the spacings/gaps between the image, the title and the group size.
This requires formatting in order to obtain a better look and feel of
the UI.

If I can figure out how to reduce the formatting space between each of
the three title.jpg,title and group size. This option could be
considered to be an alternative fix but might not be the best fix.

I am not too sure how can I go about the same(the suggested fix) as I am
a newbie wrt many things in RoR. I am not too sure on what commands of
RoR I can make use of which would help me simplify/solve my task. Can
you please help me on this.

I would be also grateful for any suggestions on a more efficient fix to
this scenario.

I later on, in a way was able to figure out that by using javascript's
onclick event, I could solve my problem. I am not too sure about the
equivalent syntax for the same using Rails Helpers.I referred to
http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-javascript_tag
, to get a hang of how the javascript_tag can be used for my purpose,
but if this is the way out,  I am really clueless on how to modify the
basic syntax to suit my requirements. Kindly help me with the same if
feasible.

Thank you..

答:
The Script.aculo.us Ajax.Autocompleter has a simple feature for just this sort of thing. Any element that you want to exclude from the auto-populated results just needs to be wrapped in a span.informal tag. So your results would look like this:

```<code><li>
    <span class="informal">[img tag]</span>
    India
    <span class="informal">whatever else</span>
</li>
</code>```

When this result is clicked in the autocompleter's hint list, only the word India will be entered in the text field.

Body:
I am trying to implement a functionality similar to the onclick method
of Javascript, using Rails Helpers.

I have implemented a auto complete feature for more than one field in
Rails 2.0.2 and Ruby 1.8.7. This configuration is run on Ubuntu 10.04
and yes , I know.. you might feel why Rails 2.x when we have Rails 3.x ,
it is so because of project specific purposes. I don't have much of a
choice on that ..:) .

I am able to successfully retrieve a group specific profile pic, a group
title and a the total number of members belonging to a group based on
the given "title" as the basic search query that a user inputs in the
text field where auto complete functionality is being performed. Getting
the auto complete functionality to work for the scenario above was a
challenge in itself.

In case you aren't able to get a better understanding of what I have
implemented wrt autocomplete, kindly refer to
Implementing auto complete for more than one field in Rails
.

You can also get a better understanding of what I have implemented by referring to http://imagepaste.nullnetwork.net/viewimage.php?id=2048  ,
http://imagepaste.nullnetwork.net/viewimage.php?id=2050
and http://imagepaste.nullnetwork.net/viewimage.php?id=2049 .

Please note the name of group specific profile pic is same as that of
the group title with the exception that the pic would also have .jpg
appended to it.

I am making use of a customized auto complete method, an auto complete
plugin and also making use of Rails partials. The cusotmized auto
complete method is allowing me to modify the basic functionality to suit
my requirement.

Coming to my question, Now say if a user enters "I" in the text field as
per the auto complete feature that I have implemented, the results(for
more than one matches found(i.e. if more than one group exists which
start with an "I") on a specific search query) populated on the User
Interface would have all the following :-

Group Specific Profile Pic(s) starting
with name same as title, in this case
"I%".jpg

Group title name.

Total number of members belonging to
a group

Say I have India and Independence as my group names I would obtain the
following results displayed in my auto complete text field.

India.jpg(image will be displayed)     India(Group title name displayed)               3(dummy value here)

and similarly

Independence.jpg                     Independence
4

All this would come in one text field. Please note the comments in
parentheses are not part of the results returned via auto complete.

In case you are not able to get the picture in your mind of how the UI
would look, Kindly register in www.diasp.org and search for any random
user using its search feature , once your account is created.

Please observe that the spacing between image, title name and total
number of group members is too much. I will be referring back to this in
the comments that follow.

The code for the partial that renders all this is:-

  <% for inv_group in @investor_group2 %>
  <%=image_tag "investor_groups/#{inv_group.title}.jpg" , :width =>

'40', :height => '22', :align => 'left' %>
<%=h inv_group.title
%>(<%=h inv_group.activated_members.size %>)

      <%end%>

Now if a user hovers his/her mouse over say India and then clicks on it,
the text field is populated with **India(3)** .

What I need is to implement is a on click in Rails which will
select only Group title. I tried to implement the group title and
group size with separate
 tags , I was then able to mouseover and
select only the title and get it populated for the text field.

The problem with this approach is it completely spoils the formatting
and the spacings/gaps between the image, the title and the group size.
This requires formatting in order to obtain a better look and feel of
the UI.

If I can figure out how to reduce the formatting space between each of
the three title.jpg,title and group size. This option could be
considered to be an alternative fix but might not be the best fix.

I am not too sure how can I go about the same(the suggested fix) as I am
a newbie wrt many things in RoR. I am not too sure on what commands of
RoR I can make use of which would help me simplify/solve my task. Can
you please help me on this.

I would be also grateful for any suggestions on a more efficient fix to
this scenario.

I later on, in a way was able to figure out that by using javascript's
onclick event, I could solve my problem. I am not too sure about the
equivalent syntax for the same using Rails Helpers.I referred to
http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-javascript_tag
, to get a hang of how the javascript_tag can be used for my purpose,
but if this is the way out,  I am really clueless on how to modify the
basic syntax to suit my requirements. Kindly help me with the same if
feasible.

Thank you..

Body:
The Script.aculo.us Ajax.Autocompleter has a simple feature for just this sort of thing. Any element that you want to exclude from the auto-populated results just needs to be wrapped in a span.informal tag. So your results would look like this:

<li>
    <span class="informal">[img tag]</span>
    India
    <span class="informal">whatever else</span>
</li>

When this result is clicked in the autocompleter's hint list, only the word India will be entered in the text field.


问:
Combining rows by ID
I have a large dataset and I would like to combine rows that have the same ID into one row, without losing any information.

To start with, here is my long data:

```<code> # A random data frame
    df1  <- read.table(text="question ID  ARG  AUT ITA
                              A     90   NA  all   never
                              A     90   NA  all   NA
                              A1    91   12  NA    NA
                              A2    92   14  two   41
                              A3    93   17  NA    44
                              AA    90   20  NA    NA
                              B2    91   NA  NA    NA
                              B3    92   NA  four  NA
                              B4    93   NA  10    yes", header=TRUE, stringsAsFactors=FALSE)
</code>```

This is what I would like to achieve:

```<code># A random data frame
    df1  <- read.table(text="question ID  ARG  AUT ITA
                              A     90   20  all   never
                              A1    91   12  13    61
                              A2    92   14  two   41
                              A3    93   17  10    yes ", header=TRUE, stringsAsFactors=FALSE)
</code>```

Please note that my actual dataset is in the wide format and includes more variables / columns than in the example above.

I was thinking about the aggregate() function, but I don't know how to implement it, because I have character values to be "aggregated". I would be very grateful for any suggestion how to tackle this issue!

答:
An option would be</p>

```<code>library(dplyr)
df1 %>%
   group_by(ID) %>%
   summarise_all(list(~ .[!is.na(.)][1]))
</code>```

Title: Combining rows by ID

Body:
I have a large dataset and I would like to combine rows that have the same ID into one row, without losing any information.

To start with, here is my long data:

 # A random data frame
    df1  <- read.table(text="question ID  ARG  AUT ITA
                              A     90   NA  all   never
                              A     90   NA  all   NA
                              A1    91   12  NA    NA
                              A2    92   14  two   41
                              A3    93   17  NA    44
                              AA    90   20  NA    NA
                              B2    91   NA  NA    NA
                              B3    92   NA  four  NA
                              B4    93   NA  10    yes", header=TRUE, stringsAsFactors=FALSE)

This is what I would like to achieve:

# A random data frame
    df1  <- read.table(text="question ID  ARG  AUT ITA
                              A     90   20  all   never
                              A1    91   12  13    61
                              A2    92   14  two   41
                              A3    93   17  10    yes ", header=TRUE, stringsAsFactors=FALSE)

Please note that my actual dataset is in the wide format and includes more variables / columns than in the example above.

I was thinking about the aggregate() function, but I don't know how to implement it, because I have character values to be "aggregated". I would be very grateful for any suggestion how to tackle this issue!

Body:
An option would be

library(dplyr)
df1 %>%
   group_by(ID) %>%
   summarise_all(list(~ .[!is.na(.)][1]))


问:
tableView with custom cells and delay
I have a tableView with custom cells when I switch to the first time there is a delay, after searching for a problem, I found out that displaying a photo is the reason I was looking for a problem, but nothing helped. I tried to make the transition in Main Queue</p>

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TVCellMenu else { return UITableViewCell()}
        let data = category[indexPath.row]
        cell.title.text = data.name

        //image is reason

        let image = UIImage(named: data.image_name ?? "", in: Bundle.main, compatibleWith: nil)
        cell.ImageView.image = image

        return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyBoard.instantiateViewController(withIdentifier: "menu") as! VCMenu
        vc.isCategory = false
        vc.subCategory = self.category[indexPath.row].subCategory
        vc.position = self.category[indexPath.row].position
        navigationController?.pushViewController(vc, animated: true)

}
</code>```

答:
when loading the image is to slow, you should consider to load it async.

for example:

add a function to TVCellMenu:

```<code>func loadImage(imageName: String) {
    DispatchQueue.main.async {
        let image = UIImage(named: imageName ?? "", in: Bundle.main, compatibleWith: nil)
        self.ImageView.image = image
    }
}
</code>```

then (instead of setting the image directly) just call the function in cellForRowAt:

```<code>    cell.loadImage(imageName: data.image_name ?? "");

    return cell
</code>```

Title: tableView with custom cells and delay

Body:
I have a tableView with custom cells when I switch to the first time there is a delay, after searching for a problem, I found out that displaying a photo is the reason I was looking for a problem, but nothing helped. I tried to make the transition in Main Queue

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

        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TVCellMenu else { return UITableViewCell()}
        let data = category[indexPath.row]
        cell.title.text = data.name

        //image is reason

        let image = UIImage(named: data.image_name ?? "", in: Bundle.main, compatibleWith: nil)
        cell.ImageView.image = image

        return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyBoard.instantiateViewController(withIdentifier: "menu") as! VCMenu
        vc.isCategory = false
        vc.subCategory = self.category[indexPath.row].subCategory
        vc.position = self.category[indexPath.row].position
        navigationController?.pushViewController(vc, animated: true)

}

Body:
when loading the image is to slow, you should consider to load it async.

for example:

add a function to TVCellMenu:

func loadImage(imageName: String) {
    DispatchQueue.main.async {
        let image = UIImage(named: imageName ?? "", in: Bundle.main, compatibleWith: nil)
        self.ImageView.image = image
    }
}

then (instead of setting the image directly) just call the function in cellForRowAt:

    cell.loadImage(imageName: data.image_name ?? "");

    return cell


问:
Is new ms botbuilder directline speech good fit for call center scenario?
MS recently introduced direct speech channel and some samples for web frontend to use it. But i was wondering is it a good fit for use in call center scenario using some SIP or services like twilio phone? If so i would like to see some docs how to use direct line speech api and wire it up to some telephony?
I've already created github issue but it stay wo attention https://github.com/MicrosoftDocs/bot-docs/issues/1162

PS: also i have related problem, i can't find any docs on how to exachange secret to direct line token. Link for original direct line is not working for speech direct line. Thanks

答:
Please find the docs section that has Tutorials and so-on. we have the Direct Line Speech channel with which a few lines of code to the above assistant enables you to stream audio to one endpoint and benefit from STT/Bot/TTS all in one call – audio is streamed back.

The steps to add Speech are here. For CallCenter scenarios to integrate with the telephony system (PBX) of the customer, Speech Bot / VIL could take calls (SIP and RTP) from their PBX. Please find the docs for Voice first virtual assistants.


问:
Kotlin poet filet not getting generated
I tried to create a class with annotation processor and Kotlin Poet. This is my code:

```<code>@AutoService(Processor::class)
class TailProcessor : AbstractProcessor() {

    override fun process(elementTypeSet: MutableSet<out TypeElement>?, roundEnvironment: RoundEnvironment?): Boolean {
        roundEnvironment?.getElementsAnnotatedWith(Tail::class.java)?.forEach {
            if (it.javaClass.kotlin.isData) {
                print("You are doing it right")
                val className = it.simpleName.toString()
                val pack = processingEnv.elementUtils.getPackageOf(it).toString()
                val variables = ElementFilter.fieldsIn(elementTypeSet)
                startClassGeneration(className, pack, variables)
            } else {
                return false
            }
        }
        return false
    }

    override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latest()

    override fun getSupportedAnnotationTypes(): MutableSet<String> = mutableSetOf(Tail::class.java.name)

    private fun startClassGeneration(
        className: String,
        pack: String,
        variables: MutableSet<VariableElement>
    ) {
        val fileName = "Tail$className"
        val stringToBePrinted = generateStringFromIncommingValues(variables)
        val printFunction = FunSpec.builder("print").addCode("print($stringToBePrinted)").build()
        val generatedClass = TypeSpec.objectBuilder(fileName).addFunction(printFunction).build()
        val file = FileSpec.builder(pack, fileName).addType(generatedClass).build()
        val kaptKotlinGeneratedDir = processingEnv.options[KOTLIN_DIRECTORY_NAME]
        file.writeTo(File(kaptKotlinGeneratedDir, "$fileName.kt"))
    }

    private fun generateStringFromIncommingValues(variables: MutableSet<VariableElement>): Any {
        val stringBuilder = StringBuilder()
        variables.forEach {
            if (it.constantValue == null) {
                stringBuilder.append("null\n ")
            } else {
                stringBuilder.append("${it.constantValue}\n")
            }
        }
        return stringBuilder.toString()
    }

    companion object {
        const val KOTLIN_DIRECTORY_NAME = "sxhardha.tail"
    }
}
</code>```

The problem, directory and file not generating.  I tried to rebuild, invalidate cache + restart, clean but none of them works. The build goes successful without any errors but I see no changes. Can you check what is wrong?

答:
I actually found the issue. I wasn't checking right if that class is a data class or not and the condition was never met.

Instead of:

```<code>it.javaClass.kotlin.isData
</code>```

Should have been:

```<code>it.kotlinMetadata as KotlinClassMetadata).data.classProto.isDataClass
</code>```

But it can only be achieved by using this library here.

Title: Kotlin poet filet not getting generated

Body:
I tried to create a class with annotation processor and Kotlin Poet. This is my code:

@AutoService(Processor::class)
class TailProcessor : AbstractProcessor() {

    override fun process(elementTypeSet: MutableSet<out TypeElement>?, roundEnvironment: RoundEnvironment?): Boolean {
        roundEnvironment?.getElementsAnnotatedWith(Tail::class.java)?.forEach {
            if (it.javaClass.kotlin.isData) {
                print("You are doing it right")
                val className = it.simpleName.toString()
                val pack = processingEnv.elementUtils.getPackageOf(it).toString()
                val variables = ElementFilter.fieldsIn(elementTypeSet)
                startClassGeneration(className, pack, variables)
            } else {
                return false
            }
        }
        return false
    }

    override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latest()

    override fun getSupportedAnnotationTypes(): MutableSet<String> = mutableSetOf(Tail::class.java.name)

    private fun startClassGeneration(
        className: String,
        pack: String,
        variables: MutableSet<VariableElement>
    ) {
        val fileName = "Tail$className"
        val stringToBePrinted = generateStringFromIncommingValues(variables)
        val printFunction = FunSpec.builder("print").addCode("print($stringToBePrinted)").build()
        val generatedClass = TypeSpec.objectBuilder(fileName).addFunction(printFunction).build()
        val file = FileSpec.builder(pack, fileName).addType(generatedClass).build()
        val kaptKotlinGeneratedDir = processingEnv.options[KOTLIN_DIRECTORY_NAME]
        file.writeTo(File(kaptKotlinGeneratedDir, "$fileName.kt"))
    }

    private fun generateStringFromIncommingValues(variables: MutableSet<VariableElement>): Any {
        val stringBuilder = StringBuilder()
        variables.forEach {
            if (it.constantValue == null) {
                stringBuilder.append("null\n ")
            } else {
                stringBuilder.append("${it.constantValue}\n")
            }
        }
        return stringBuilder.toString()
    }

    companion object {
        const val KOTLIN_DIRECTORY_NAME = "sxhardha.tail"
    }
}

The problem, directory and file not generating.  I tried to rebuild, invalidate cache + restart, clean but none of them works. The build goes successful without any errors but I see no changes. Can you check what is wrong?

Body:
I actually found the issue. I wasn't checking right if that class is a data class or not and the condition was never met.

Instead of:

it.javaClass.kotlin.isData

Should have been:

it.kotlinMetadata as KotlinClassMetadata).data.classProto.isDataClass

But it can only be achieved by using this library here.


问:
Polygon rendering with pixijs
I'm trying to display more than 6000 Polygons on a mobile device.
Currently, I'm doing this with SVG paths in Android WebView using the d3.js library.
It works but I have to deal with performance issues, my map becomes very laggy when I drag my map or zoom.

My Idea now is to try the same with pixijs. My data comes originally from ESRI Shapefiles. I'm convert these Shapefiles to GeoJSON and then to SVG. My array of vertices looks like this, which I'm trying to pass to the drawPolygon function

0: 994.9867684400124
  1: 22.308409862458518
  2: 1042.2789743912592
  3: 61.07148769269074

But when I try to render these polygon nothing being displayed. This is my code:

```<code>        var renderer = PIXI.autoDetectRenderer(1800, 1800, { backgroundColor: 0x000000, antialias: true });
        document.body.appendChild(renderer.view);

        var stage = new PIXI.Container();
        var graphics = new PIXI.Graphics();

        var totalShapes = feat.features.length;

        for (var i = 1; i <= totalShapes -1; i++) {

            var shape = feat.features[i];
            var geometry = shape.geometry.bbox;

            graphics.beginFill(0xe74c3c);
            graphics.drawPolygon([ geometry]);
            graphics.endFill();
            stage.addChild(graphics);
            renderer.render(stage);

         }
</code>```

Can someone help me or could suggest me a different way?

答:
I have not seen that way of initializing a pixie project.

Usually you add the application to the html document like:

```<code>  var app = new PIXI.Application({
    width: window.innerWidth,
    height: window.innerHeight,
    backgroundColor: 0x2c3e50
});
document.body.appendChild(app.view);
</code>```

If you do this you can add your draw calls to the setup of the application:

```<code>app.loader.load(startup);

function startup()
{
    var g = new PIXI.Graphics();
    g.beginFill(0x5d0015);
    g.drawPolygon(
        10, 10, 120, 100, 120, 200, 70, 200
    );
    g.endFill();

    app.stage.addChild(g);
}
</code>```

This will render the polygon once.

Title: Polygon rendering with pixijs

Body:
I'm trying to display more than 6000 Polygons on a mobile device.
Currently, I'm doing this with SVG paths in Android WebView using the d3.js library.
It works but I have to deal with performance issues, my map becomes very laggy when I drag my map or zoom.

My Idea now is to try the same with pixijs. My data comes originally from ESRI Shapefiles. I'm convert these Shapefiles to GeoJSON and then to SVG. My array of vertices looks like this, which I'm trying to pass to the drawPolygon function

0: 994.9867684400124
  1: 22.308409862458518
  2: 1042.2789743912592
  3: 61.07148769269074

But when I try to render these polygon nothing being displayed. This is my code:

        var renderer = PIXI.autoDetectRenderer(1800, 1800, { backgroundColor: 0x000000, antialias: true });
        document.body.appendChild(renderer.view);

        var stage = new PIXI.Container();
        var graphics = new PIXI.Graphics();

        var totalShapes = feat.features.length;

        for (var i = 1; i <= totalShapes -1; i++) {

            var shape = feat.features[i];
            var geometry = shape.geometry.bbox;

            graphics.beginFill(0xe74c3c);
            graphics.drawPolygon([ geometry]);
            graphics.endFill();
            stage.addChild(graphics);
            renderer.render(stage);

         }

Can someone help me or could suggest me a different way?

Body:
I have not seen that way of initializing a pixie project.

Usually you add the application to the html document like:

  var app = new PIXI.Application({
    width: window.innerWidth,
    height: window.innerHeight,
    backgroundColor: 0x2c3e50
});
document.body.appendChild(app.view);

If you do this you can add your draw calls to the setup of the application:

app.loader.load(startup);

function startup()
{
    var g = new PIXI.Graphics();
    g.beginFill(0x5d0015);
    g.drawPolygon(
        10, 10, 120, 100, 120, 200, 70, 200
    );
    g.endFill();

    app.stage.addChild(g);
}

This will render the polygon once.


问:
Tab loading screen - Android
I have 5 Tabs and on 2 of theme there is a content provided from our server. There is about 170 items in ListVie in each of tabs. To download and process data it can take about 1 second (or more - depend on signal strength)...

Let me be more exact... I have 5 tabs (tab1, tab2, tab3, tab4, tab5). First two (tab1 and tab2) receives content from servers. When I click from whatever tab to tab1 or tab2 it takes time to switch and looks like app freezes. Therefore I would like to create a loader... How to do that in tabs?

答: You need to fire off a new thread in Android when loading data from the background. You can use a progress bar notification would also provide user feedback but using multiple threads will allow your UI to remain active and provide a better user experience. There is a good guide in the Android documentation: Painless Threading</p>

Title: Tab loading screen - Android


问:
What is the purpose of std::forward()'s rvalue reference overload?
I'm experimenting with Perfect Forwarding and I found that
std::forward() needs two overloads:

Overload nr. 1:

```<code>template <typename T>
inline T&& forward(typename
std::remove_reference<T>::type& t) noexcept
{
    return static_cast<T&&>(t);
}
</code>```

Overload nr.2:

```<code>template <typename T>
inline T&& forward(typename
std::remove_reference<T>::type&& t) noexcept
{
    static_assert(!std::is_lvalue_reference<T>::value,
              "Can not forward an rvalue as an lvalue.");
    return static_cast<T&&>(t);
}
</code>```

Now a typical scenario for Perfect Forwarding is something like

```<code>template <typename T>
void wrapper(T&& e)
{
    wrapped(forward<T>(e));
}
</code>```

Of course you know that when wrapper() is instantiated, T depends on whether the argument passed to it is an lvalue or an rvalue. If it's an lvalue of type U, T is deduced to U&. If it's an rvalue, T is deduced to U.

In any case - in the scope of wrapper() - e is an lvalue, therefore it always uses the first overload of std::forward().

Now my question:

What is a valid scenario in which the 2nd overload is used (and is needed)?

答:
The design rationale for forward is discussed in great detail in N2951.

This document lays out 6 use cases:

A. Should forward an lvalue as an lvalue. All implementations pass
  this test. But this is not the classic perfect forwarding pattern. The
  purpose of this test is to show that implementation 2 fails in its
  stated goal of preventing all use cases except perfect forwarding.

B. Should forward an rvalue as an rvalue. Like use case A, this is
  an identity transformation and this presents a motivating example
  where the identity transformation is needed.

C. Should not forward an rvalue as an lvalue. This use case
  demonstrates a dangerous situation of accidentally creating a dangling
  reference.

D.  Should forward less cv-qualified expressions to more
  cv-qualified expressions. A motivating use case involving the
  addition of const during the forward.

E. Should forward expressions of derived type to an accessible,
  unambiguous base type. A motivating use case involving forwarding a
  derived type to a base type.

F.  Should not forward arbitrary type conversions. This use case
  demonstrates how arbitrary conversions within a forward lead to
  dangling reference run time errors.

The second overload enables cases B and C.

The paper goes on to provide examples of each use case, which are too lengthy to be repeated here.

Update

I've just run the "solution" of just the first overload through these 6 use cases, and this exercise shows that the second overload also enables use case F:  Should not forward arbitrary type conversions.

Body:
I'm experimenting with Perfect Forwarding and I found that
std::forward() needs two overloads:

Overload nr. 1:

template <typename T>
inline T&& forward(typename
std::remove_reference<T>::type& t) noexcept
{
    return static_cast<T&&>(t);
}

Overload nr.2:

template <typename T>
inline T&& forward(typename
std::remove_reference<T>::type&& t) noexcept
{
    static_assert(!std::is_lvalue_reference<T>::value,
              "Can not forward an rvalue as an lvalue.");
    return static_cast<T&&>(t);
}

Now a typical scenario for Perfect Forwarding is something like

template <typename T>
void wrapper(T&& e)
{
    wrapped(forward<T>(e));
}

Of course you know that when wrapper() is instantiated, T depends on whether the argument passed to it is an lvalue or an rvalue. If it's an lvalue of type U, T is deduced to U&. If it's an rvalue, T is deduced to U.

In any case - in the scope of wrapper() - e is an lvalue, therefore it always uses the first overload of std::forward().

Now my question:

What is a valid scenario in which the 2nd overload is used (and is needed)?


问:
Get the number of instance of a component in angular 2/4/6?
I want to get the number of occurrence of a component. Menas want to know how many times this particular component is rendering?

Actually, I have made a toaster and want to know how many times it's displaying?

My codes are:

main.component.ts:

```<code>      <toster-component [message]="'this is toster message'"   [type]="'danger'" [duration]="'15'"> </toster-component>
      <toster-component [message]="'this is toster message 2'" [type]="'info'
  [duration]="'5'"> </toster-component>
</code>```

toster.component.ts:

```<code>import { Component,Input,OnInit,ContentChildren,ElementRef,QueryList } from '@angular/core';

@Component({
  selector: 'toster-component',
  templateUrl: './toster.component.html',
  styleUrls: ['./toster.component.css'],
});

export class TosterComponent implements OnInit {
  public isShow:any=true;
  public TabItem:any;

  @Input() message:string;  // Will show the message.
  @Input() type:string; // What type will decide the style of this toster.
  @Input() duration:number; // If duration ( In second ) is available the it will show till duration otherwise it will show permanently till manually closed

  @ContentChildren(TosterComponent, {read: ElementRef}) tosterComponents:QueryList<TosterComponent>;

  ngAfterContentInit() {
       console.log("Length: ",this.tosterComponents.toArray().length);
     }

  ngOnInit(){
      this.message=this.message?this.message:'Test Message';
      this.type=this.type?this.type:'info';

      if(this.duration>0){
          setTimeout(()=>{
            this.isShow=false;
          },this.duration*1000);
       }
    }

 }
</code>```

In the above code I am using below code:

```<code>@ContentChildren(TosterComponent, {read: ElementRef}) tosterComponents:QueryList<TosterComponent>;

ngAfterContentInit() {
           console.log("Length: ",this.tosterComponents.toArray().length); // I want to print the instance of this component.
         }
</code>```

to achieve the same, But its showing only 1. But it should be 2 because its using 2 times in main.component.ts.

答:
You can declare a static class variable, and increase its count everytime the constructor() runs.

I have prepared THIS here.

Body:
I want to get the number of occurrence of a component. Menas want to know how many times this particular component is rendering?

Actually, I have made a toaster and want to know how many times it's displaying?

My codes are:

main.component.ts:

      <toster-component [message]="'this is toster message'"   [type]="'danger'" [duration]="'15'"> </toster-component>
      <toster-component [message]="'this is toster message 2'" [type]="'info'
  [duration]="'5'"> </toster-component>

toster.component.ts:

import { Component,Input,OnInit,ContentChildren,ElementRef,QueryList } from '@angular/core';

@Component({
  selector: 'toster-component',
  templateUrl: './toster.component.html',
  styleUrls: ['./toster.component.css'],
});

export class TosterComponent implements OnInit {
  public isShow:any=true;
  public TabItem:any;

  @Input() message:string;  // Will show the message.
  @Input() type:string; // What type will decide the style of this toster.
  @Input() duration:number; // If duration ( In second ) is available the it will show till duration otherwise it will show permanently till manually closed

  @ContentChildren(TosterComponent, {read: ElementRef}) tosterComponents:QueryList<TosterComponent>;

  ngAfterContentInit() {
       console.log("Length: ",this.tosterComponents.toArray().length);
     }

  ngOnInit(){
      this.message=this.message?this.message:'Test Message';
      this.type=this.type?this.type:'info';

      if(this.duration>0){
          setTimeout(()=>{
            this.isShow=false;
          },this.duration*1000);
       }
    }

 }

In the above code I am using below code:

@ContentChildren(TosterComponent, {read: ElementRef}) tosterComponents:QueryList<TosterComponent>;

ngAfterContentInit() {
           console.log("Length: ",this.tosterComponents.toArray().length); // I want to print the instance of this component.
         }

to achieve the same, But its showing only 1. But it should be 2 because its using 2 times in main.component.ts.


问:
PayFort IOS SDK gives crash when initialized
I am trying to implement PayFort in my IOS Mobile application
    I have added PayFort FrameWork and bundle in project. When i Initialize payFort object it gives me following crash

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITextField setFloatingLabelActiveTextColor:]: unrecognized selector sent to instance 0x7f81e3413d40'

I am using following piece of code:

```<code>     func  payforCall(){
        let payFort = PayFortController.init(enviroment: KPayFortEnviromentSandBox)
        payFort?.isShowResponsePage = true;
        payFort?.delegate=self
        let request = NSMutableDictionary.init()
        request.setValue("1000", forKey: "amount")
        request.setValue("AUTHORIZATION", forKey: "command")
        request.setValue("USD", forKey: "currency")
        request.setValue("email@domain.com", forKey: "customer_email")
        request.setValue("en", forKey: "language")
        request.setValue("112233682686", forKey: "merchant_reference")
        request.setValue("token" , forKey: "sdk_token")

        payFort?.callPayFort(withRequest: request, currentViewController: self,
                            success: { (requestDic, responeDic) in
                                print("success")
        },
                            canceled: { (requestDic, responeDic) in
                                print("canceled")
        },
                            faild: { (requestDic, responeDic, message) in
                                print("faild")

        })
    }
</code>```

答:
I had the same issue and I spent couple of hours working on it before realize I typed -objc with small "C" letter

In project build settings -> Other Linker Flags -> Set to -ObjC

Body:
I am trying to implement PayFort in my IOS Mobile application
    I have added PayFort FrameWork and bundle in project. When i Initialize payFort object it gives me following crash

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITextField setFloatingLabelActiveTextColor:]: unrecognized selector sent to instance 0x7f81e3413d40'

I am using following piece of code:

     func  payforCall(){
        let payFort = PayFortController.init(enviroment: KPayFortEnviromentSandBox)
        payFort?.isShowResponsePage = true;
        payFort?.delegate=self
        let request = NSMutableDictionary.init()
        request.setValue("1000", forKey: "amount")
        request.setValue("AUTHORIZATION", forKey: "command")
        request.setValue("USD", forKey: "currency")
        request.setValue("email@domain.com", forKey: "customer_email")
        request.setValue("en", forKey: "language")
        request.setValue("112233682686", forKey: "merchant_reference")
        request.setValue("token" , forKey: "sdk_token")

        payFort?.callPayFort(withRequest: request, currentViewController: self,
                            success: { (requestDic, responeDic) in
                                print("success")
        },
                            canceled: { (requestDic, responeDic) in
                                print("canceled")
        },
                            faild: { (requestDic, responeDic, message) in
                                print("faild")

        })
    }