问:
Redirect in javascript: IF GET parameter key allow to stay on the page; otherwise redirect to another page
How is the best way to write this code? We want to let people who know how to add the ?Redirect=No to append the url stay on the page and view it otherwise the person will get redirected to the new site or to a "we-have-moved" page. An example would help me very much in knowing how to detect the GET url use case. I am a noobie javascript coder so your help is much appreciated!

Option #1

USE CASE 1: oldsite.mysite.com : redirects to new site Use case

USE CASE 2: oldsite.mysite.com?Redirect=No : does not redirect and the page loads normally

Option #2 (A more user friendly approach)

Use case 1: oldsite.mysite.com : site redirects immediately to new
site

Use case 2: oldsite.mysite.com?Redirect=No : does not redirect and the
page loads normally

Use case 3: oldsite.mysite.com/AnyOtherPage : redirects to a “we’ve
moved page” and then after “x” seconds redirects to the new site.

Use case 4: oldsite.mysite.com/AnyOtherPage?Redirect=No : does not
redirect and the page loads normally

```<code><script>

// Check if the GET url parameter of "redirect=NO" is appended to the url
and redirect if there is no parameter defined.

$(function() {

  if (  ... //url equals oldsite.mysite.com ...  )

      //GET redirect=NO so do nothing and stay here

      window.location.href = "https://newsite.mysite.com";

     }

   else if ( ... //url equals oldsite.mysite.com/anyOtherPage ...  )

     //GET redirect=NO so do nothing and stay here

     window.location.href = "https://oldsite.mysite.com/we-have-moved";

  }

 });

</script>
</code>```

OR would it look more like this?

```<code><script>

switch(expression) {

    case n:
         //GET url contains parameter "Redirect=NO"
         break;

    case n:
         if (//url contains a child page name) {

          window.location.href = "https://newsite.mysite.com/we-have-moved";

             }

         break;

   default:
         window.location.href = "https://newsite.mysite.com";

 }

</script>
</code>```

答:
Uncomment in actual code.

var sleep =(ms)=> new Promise((res, rej)=>{
         setTimeout( res, ms );
});
var redirect = async (pathname, ms) => {
    if(ms){
       await sleep(ms);
       console.log('waiting for' + ms + '...');
    }else{
      console.log('immediate');
    }

    console.log('http://newUrl.com' + pathname);//location.href = 'http://newUrl.com' + pathname
}

var main = (url, ms) => {
  var u =new URL(url);
  var sp = Array.from(u.searchParams.entries());
  sp.some((arr,i)=>arr[0] === 'Redirect' && arr[1]=== 'No')? '': u.pathname === '/' ? redirect(''+u.search,0) : redirect(u.pathname+u.search, ms);
}

main('http://oldsite.mysite.com?Redirect=No', 5000);
main('http://oldsite.mysite.com/AnyOtherPage?Redirect=No', 5000);

console.log('redirection cases');
main('http://oldsite.mysite.com/AnyOtherPage', 5000);
main('http://oldsite.mysite.com', 5000);```

Body:
How is the best way to write this code? We want to let people who know how to add the ?Redirect=No to append the url stay on the page and view it otherwise the person will get redirected to the new site or to a "we-have-moved" page. An example would help me very much in knowing how to detect the GET url use case. I am a noobie javascript coder so your help is much appreciated!

Option #1

USE CASE 1: oldsite.mysite.com : redirects to new site Use case

USE CASE 2: oldsite.mysite.com?Redirect=No : does not redirect and the page loads normally

Option #2 (A more user friendly approach)

Use case 1: oldsite.mysite.com : site redirects immediately to new
site

Use case 2: oldsite.mysite.com?Redirect=No : does not redirect and the
page loads normally

Use case 3: oldsite.mysite.com/AnyOtherPage : redirects to a “we’ve
moved page” and then after “x” seconds redirects to the new site.

Use case 4: oldsite.mysite.com/AnyOtherPage?Redirect=No : does not
redirect and the page loads normally

OR would it look more like this?


来源: stackexchange

问:
How can I avoid showing extensions on one Filter option in OpenFileDialog?
In addition to a list of supported file formats, I want to have a catch-all of "All Supported Files". I want the extensions to be displayed for the individual formats, but not for the catch-all. I thought this would do it:

```<code>    const string OpenFileFilters = "AAA Files (*.aaa)|*.aaa|" +
                           "BBB Files (*.bbb)|*.bbb|" +
                           "CCC Files (*.ccc)|*.ccc|" +
                           "DDD Files (*.ddd)|*.ddd|" +
                           "EEE Files (*.eee)|*.eee|" +
                           "FFF Files (*.fff)|*.fff|" +
                           "GGG Files (*.ggg)|*.ggg|" +
                           "HHH Files (*.hhh)|*.hhh|" +
                           "III Files (*.iii)|*.iii|" +
                           "All Supported Files |*.aaa;*.bbb;*.ccc;*.ddd;*.eee;*.fff;*.ggg;*.hhh;*.iii";

    var dialog = new OpenFileDialog
    {
        InitialDirectory = FileUtilites.ValidateInitialDirectory(initialDirectory),
        Filter = OpenFileFilters,
        FilterIndex = Settings.Default.OpenFileFilter,
        Multiselect = true
    };

    var result = dialog.ShowDialog();
</code>```

But it gives me this:

Is there some way to specify the Filter string so that it will not include the long list of extensions on that last option?

答:
I ended up using

```<code>const string OpenFileFilters = "AAA Files (*.aaa)|*.aaa|" +
                       "BBB Files (*.bbb)|*.bbb|" +
                       "CCC Files (*.ccc)|*.ccc|" +
                       "DDD Files (*.ddd)|*.ddd|" +
                       "EEE Files (*.eee)|*.eee|" +
                       "FFF Files (*.fff)|*.fff|" +
                       "GGG Files (*.ggg)|*.ggg|" +
                       "HHH Files (*.hhh)|*.hhh|" +
                       "III Files (*.iii)|*.iii|" +
                       "All Supported Files (*.*)|*.aaa;*.bbb;*.ccc;*.ddd;*.eee;*.fff;*.ggg;*.hhh;*.iii";
</code>```

It shows (*.*) in the combo box, which is a lie, but it's a white lie.

ContentLicense: CC BY-SA 3.0

Body:
In addition to a list of supported file formats, I want to have a catch-all of "All Supported Files". I want the extensions to be displayed for the individual formats, but not for the catch-all. I thought this would do it:

    const string OpenFileFilters = "AAA Files (*.aaa)|*.aaa|" +
                           "BBB Files (*.bbb)|*.bbb|" +
                           "CCC Files (*.ccc)|*.ccc|" +
                           "DDD Files (*.ddd)|*.ddd|" +
                           "EEE Files (*.eee)|*.eee|" +
                           "FFF Files (*.fff)|*.fff|" +
                           "GGG Files (*.ggg)|*.ggg|" +
                           "HHH Files (*.hhh)|*.hhh|" +
                           "III Files (*.iii)|*.iii|" +
                           "All Supported Files |*.aaa;*.bbb;*.ccc;*.ddd;*.eee;*.fff;*.ggg;*.hhh;*.iii";

    var dialog = new OpenFileDialog
    {
        InitialDirectory = FileUtilites.ValidateInitialDirectory(initialDirectory),
        Filter = OpenFileFilters,
        FilterIndex = Settings.Default.OpenFileFilter,
        Multiselect = true
    };

    var result = dialog.ShowDialog();

But it gives me this:

Is there some way to specify the Filter string so that it will not include the long list of extensions on that last option?

Body:
I ended up using

const string OpenFileFilters = "AAA Files (*.aaa)|*.aaa|" +
                       "BBB Files (*.bbb)|*.bbb|" +
                       "CCC Files (*.ccc)|*.ccc|" +
                       "DDD Files (*.ddd)|*.ddd|" +
                       "EEE Files (*.eee)|*.eee|" +
                       "FFF Files (*.fff)|*.fff|" +
                       "GGG Files (*.ggg)|*.ggg|" +
                       "HHH Files (*.hhh)|*.hhh|" +
                       "III Files (*.iii)|*.iii|" +
                       "All Supported Files (*.*)|*.aaa;*.bbb;*.ccc;*.ddd;*.eee;*.fff;*.ggg;*.hhh;*.iii";

It shows (*.*) in the combo box, which is a lie, but it's a white lie.


问:
Use PowerShell to generate a list of files and directories
I'm writing a PowerShell script to make several directories and copy a bunch of files together to "compile" some technical documentation.  I'd like to generate a manifest of the files and directories as part of the readme file, and I'd like PowerShell to do this, since I'm already working in PowerShell to do the "compiling".

I've done some searching already, and it seems that I need to use the cmdlet "Get-ChildItem", but it's giving me too much data, and I'm not clear on how to format and prune out what I don't want to get my desired results.

I would like an output similar to this:

```<code>Directory
     file
     file
     file
Directory
     file
     file
     file
     Subdirectory
          file
          file
          file
</code>```

or maybe something like this:

```<code>+---FinGen
|   \---doc
+---testVBFilter
|   \---html
\---winzip
</code>```

In other words, some kind of basic visual ASCII representation of the tree structure with the directory and file names and nothing else.  I have seen programs that do this, but I am not sure if PowerShell can do this.

Can PowerShell do this?  If so, would Get-ChildItem be the right cmdlet?

答:
The best and clear way for me is:</p>

```<code>PS P:\> Start-Transcript -path C:\structure.txt -Append
PS P:\> tree c:\test /F
PS P:\> Stop-Transcript
</code>```

Body:
I'm writing a PowerShell script to make several directories and copy a bunch of files together to "compile" some technical documentation.  I'd like to generate a manifest of the files and directories as part of the readme file, and I'd like PowerShell to do this, since I'm already working in PowerShell to do the "compiling".

I've done some searching already, and it seems that I need to use the cmdlet "Get-ChildItem", but it's giving me too much data, and I'm not clear on how to format and prune out what I don't want to get my desired results.

I would like an output similar to this:

Directory
     file
     file
     file
Directory
     file
     file
     file
     Subdirectory
          file
          file
          file

or maybe something like this:

+---FinGen
|   \---doc
+---testVBFilter
|   \---html
\---winzip

In other words, some kind of basic visual ASCII representation of the tree structure with the directory and file names and nothing else.  I have seen programs that do this, but I am not sure if PowerShell can do this.

Can PowerShell do this?  If so, would Get-ChildItem be the right cmdlet?

Body:
The best and clear way for me is:

PS P:\> Start-Transcript -path C:\structure.txt -Append
PS P:\> tree c:\test /F
PS P:\> Stop-Transcript


问:
Azure search: Multiple custom attributes of the same type found
we are facing with a very strange problem with azure search which only happens on our live environment.

This is the code

```<code>var  aaa= new SearchServiceClient("name", new SearchCredentials("XXX"));
</code>```

Literally one line of code, directly under Controller, the page breaks with following message:

```<code>[AmbiguousMatchException: Multiple custom attributes of the same type found.]
   System.Attribute.GetCustomAttribute(Assembly element, Type attributeType, Boolean inherit) +119
   Microsoft.Rest.ServiceClient`1.get_FrameworkVersion() +103
   Microsoft.Rest.ServiceClient`1.get_DefaultUserAgentInfoList() +120
   Microsoft.Rest.ServiceClient`1.SetUserAgent(String productName, String version) +50
   TMDApi.Controllers.HomeController.Fucker() in C:\PROJECTS\txfmd\TMDApi\Controllers\HomeController.cs:66
   lambda_method(Closure , ControllerBase , Object[] ) +87
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +209
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +40
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +71
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +43
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +72
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +385
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +43
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +30
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +43
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +39
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +656
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +143
</code>```

We are using Azure.Search v4.0.0.0

答: This looks like a known compatibility issue with an older version of Application Insights. See this GitHub issue for details on how to resolve it.</p>

Body:
we are facing with a very strange problem with azure search which only happens on our live environment.

This is the code

var  aaa= new SearchServiceClient("name", new SearchCredentials("XXX"));

Literally one line of code, directly under Controller, the page breaks with following message:

[AmbiguousMatchException: Multiple custom attributes of the same type found.]
   System.Attribute.GetCustomAttribute(Assembly element, Type attributeType, Boolean inherit) +119
   Microsoft.Rest.ServiceClient`1.get_FrameworkVersion() +103
   Microsoft.Rest.ServiceClient`1.get_DefaultUserAgentInfoList() +120
   Microsoft.Rest.ServiceClient`1.SetUserAgent(String productName, String version) +50
   TMDApi.Controllers.HomeController.Fucker() in C:\PROJECTS\txfmd\TMDApi\Controllers\HomeController.cs:66
   lambda_method(Closure , ControllerBase , Object[] ) +87
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +209
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +40
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +71
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +43
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +72
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +385
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +43
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +30
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +43
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +39
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +656
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +143

We are using Azure.Search v4.0.0.0


问:
Knowledge Graph (Demo) UI using sigma.js?
Are there any beginner-friendly tutorials to display graphs in the way Knowledge graph has been done?

I have the data is JSON format presented from a graphdb

For eg:

答:
The closest I have found so far is Gelphi. Which also can be integrated with unity to produce a 3d Graph like this one https://www.youtube.com/watch?v=h_arRCf73Kg.

Then there is https://cayley.io/

https://n0where.net/opengraphiti-data-visualization-engine/

There is also https://www.maana.io/knowledge-platform/platform-capabilities/#maana-knowledge-graph . However, i have not tried to use/download their platform.

https://en.wikipedia.org/wiki/Force-directed_graph_drawing

Finally, I am working myself on learning unity to build a simple GUI which a user can identify nodes and edges and entities easily and move them around. So instead of just reading from a data base, also write to it through a UI.


问:
Is there something similar to Android's dimens.xml in iOS?
I recently found out that I should be placing all my sizing/dimensions in dimens.xml for Android applications that I want to support multiple screen resolutions.

Is there something similar that I should do in iOS to support multiple screen resolutions? I code all my views in the back end (no storyboards) and when I want to position a view (padding, margins, etc.) I simply add hard-coded numbers to the X and Y properties of the view's frame. Same thing for Width, Height, Font size, etc. I imagine my iOS apps that I coded like this will look awkward on different screen resolutions like this?

By the way, I'm using Xamarin (Xamarin.Android and Xamarin.iOS). But I would understand answers using native code.

答:
you can create an empty swift file, and use struct instead of dimens.xml for Android</p>

```<code>struct Padding {
    static let left = 10
    static let right = 10
    static let top = 10
    static let bottom = 10
}
</code>```

Body:
you can create an empty swift file, and use struct instead of dimens.xml for Android

struct Padding {
    static let left = 10
    static let right = 10
    static let top = 10
    static let bottom = 10
}


问:
How to add a database retrieved value custom claim to JWT Token using ServiceStack
In AppHost.Configure I have the following code:

```<code>Plugins.Add(new AuthFeature(() => new AuthUserSession(),
    new IAuthProvider[] {
        new JwtAuthProvider
        {
            HashAlgorithm = "HS256",
            RequireSecureConnection = requireSecureConnection,
            AuthKeyBase64 = _configuration["AuthSettings:JwtAuthKeyBase64"],//Settings.Value.JwtAuthKeyBase64,
            ExpireTokensIn        = TimeSpan.FromHours(_configuration["AuthSettings:ExpireTokensIn"].ToDouble()),  // JWT Token Expiry
            ExpireRefreshTokensIn = TimeSpan.FromHours(_configuration["AuthSettings:ExpireRefreshTokensIn"].ToDouble()), // Refresh Token Expiry,
            CreatePayloadFilter = (payload,session) => {
                    payload["ZipCode"] = "value_from_database_for_user";
            }
        },
        new CustomCredentialsAuthProvider(), //HTML Form post of User/Pass
    }));
</code>```

The above code is standard ServiceStack JwtAuthProvider code.

You can see in the above code that the implementation for the anonymous function bound to CreatePayloadFilter would like to retrieve a value from the database, the user's ZipCode is the value and add that as a custom claim to the token.

For many obvious reasons, implementing the retrieval of the user's ZipCode in the AppHost is not easy, elegant or system/architecturally sound. Also it is not even possible, as I will not have the UserId, AppHost is just startup configuration code ran when the service starts.

You can also see in the above code that I have implemented a CustomCredentialsAuthProvider, I can load session data for the logged in user in CustomCredentialsAuthProvider and ServiceStack will map the session values to hydrate the appropriate JWT claims but I cannot add a custom claim via the ServiceStack session object, here is the implementation of CustomCredentialsAuthProvider:

```<code>public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
    public override bool TryAuthenticate(IServiceBase authService,
        string userName, string password)
    {
        return true;
        //throw new NotImplementedException();
    }

    public override IHttpResult OnAuthenticated(IServiceBase authService,
        IAuthSession session, IAuthTokens tokens,
        Dictionary<string, string> authInfo)
    {
        //Fill IAuthSession with data you want to retrieve in the app eg:
        session.FirstName = "some_firstname_from_db";
        session.LastName = "some_lastname_from_db";
        session.Roles = new List<string> {"role1", "role2"};
        session.Permissions = new List<string> { "permission1", "permission2" };
        session.Email = "test@test.com";
        session.AuthProvider = "credentials";

        //...

        //Call base method to Save Session and fire Auth/Session callbacks:
        return base.OnAuthenticated(authService, session, tokens, authInfo);

        //Alternatively avoid built-in behavior and explicitly save session with
        //authService.SaveSession(session, SessionExpiry);
        //return null;
    }
}
</code>```

How can I add a custom claim to the ServiceStack framework created JWT, the value of that claim coming from the database and this implementation of this code not be function binding in AppHost.cs where I do not even have the UserId to retrieve the value anyways?

答:
I wanted to provide my final code for this even though @mythz provided the answer:

The CustomerUserSession:

```<code>[DataContract]
public class CustomUserSession: AuthUserSession
{
    [DataMember]
    public string ZipCode { get; set; }
}
</code>```

The CustomCredentialsAuthProvider because I have a legacy db with all account info:

```<code>public override bool TryAuthenticate(IServiceBase authService,
        string userName, string password)
    {
        return true;
    }

    public override IHttpResult OnAuthenticated(IServiceBase authService,
        IAuthSession session, IAuthTokens tokens,
        Dictionary<string, string> authInfo)
    {
        var customUserSession = (CustomUserSession) session;
        //Fill IAuthSession with data you want to retrieve in the app eg:
        customUserSession.FirstName = "some_firstname_from_db";
        customUserSession.LastName = "some_lastname_from_db";
        customUserSession.Roles = new List<string> {"role1", "role2"};
        customUserSession.Permissions = new List<string> { "permission1", "permission2" };
        customUserSession.Email = "test@test.com";
        customUserSession.AuthProvider = "credentials";
        customUserSession.CreatedAt = DateTime.UtcNow;
        customUserSession.ZipCode = "92123";

        //Call base method to Save Session and fire Auth/Session callbacks:
        return base.OnAuthenticated(authService, session, tokens, authInfo);
    }
</code>```

And my AppHost adding of the ServiceStack AuthFeature:

```<code>Plugins.Add(new AuthFeature(() => new CustomUserSession(),
    new IAuthProvider[] {
        new JwtAuthProvider
        {
            HashAlgorithm = "HS256",
            RequireSecureConnection = requireSecureConnection,
            AuthKeyBase64 = _configuration["AuthSettings:JwtAuthKeyBase64"],//Settings.Value.JwtAuthKeyBase64,
            ExpireTokensIn        = TimeSpan.FromHours(_configuration["AuthSettings:ExpireTokensIn"].ToDouble()),  // JWT Token Expiry
            ExpireRefreshTokensIn = TimeSpan.FromHours(_configuration["AuthSettings:ExpireRefreshTokensIn"].ToDouble()), // Refresh Token Expiry,
            CreatePayloadFilter = (payload,session) => {
                    payload["zipCode"] = ((CustomUserSession)session).ZipCode;
            },
            PopulateSessionFilter = (session, token, req) => {
                ((CustomUserSession) session).ZipCode = token["zipCode"];
            }
        },
        new CustomCredentialsAuthProvider() //HTML Form post of User/Pass
    }));
</code>```

Body:
In AppHost.Configure I have the following code:

Plugins.Add(new AuthFeature(() => new AuthUserSession(),
    new IAuthProvider[] {
        new JwtAuthProvider
        {
            HashAlgorithm = "HS256",
            RequireSecureConnection = requireSecureConnection,
            AuthKeyBase64 = _configuration["AuthSettings:JwtAuthKeyBase64"],//Settings.Value.JwtAuthKeyBase64,
            ExpireTokensIn        = TimeSpan.FromHours(_configuration["AuthSettings:ExpireTokensIn"].ToDouble()),  // JWT Token Expiry
            ExpireRefreshTokensIn = TimeSpan.FromHours(_configuration["AuthSettings:ExpireRefreshTokensIn"].ToDouble()), // Refresh Token Expiry,
            CreatePayloadFilter = (payload,session) => {
                    payload["ZipCode"] = "value_from_database_for_user";
            }
        },
        new CustomCredentialsAuthProvider(), //HTML Form post of User/Pass
    }));

The above code is standard ServiceStack JwtAuthProvider code.

You can see in the above code that the implementation for the anonymous function bound to CreatePayloadFilter would like to retrieve a value from the database, the user's ZipCode is the value and add that as a custom claim to the token.

For many obvious reasons, implementing the retrieval of the user's ZipCode in the AppHost is not easy, elegant or system/architecturally sound. Also it is not even possible, as I will not have the UserId, AppHost is just startup configuration code ran when the service starts.

You can also see in the above code that I have implemented a CustomCredentialsAuthProvider, I can load session data for the logged in user in CustomCredentialsAuthProvider and ServiceStack will map the session values to hydrate the appropriate JWT claims but I cannot add a custom claim via the ServiceStack session object, here is the implementation of CustomCredentialsAuthProvider:

public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
    public override bool TryAuthenticate(IServiceBase authService,
        string userName, string password)
    {
        return true;
        //throw new NotImplementedException();
    }

    public override IHttpResult OnAuthenticated(IServiceBase authService,
        IAuthSession session, IAuthTokens tokens,
        Dictionary<string, string> authInfo)
    {
        //Fill IAuthSession with data you want to retrieve in the app eg:
        session.FirstName = "some_firstname_from_db";
        session.LastName = "some_lastname_from_db";
        session.Roles = new List<string> {"role1", "role2"};
        session.Permissions = new List<string> { "permission1", "permission2" };
        session.Email = "test@test.com";
        session.AuthProvider = "credentials";

        //...

        //Call base method to Save Session and fire Auth/Session callbacks:
        return base.OnAuthenticated(authService, session, tokens, authInfo);

        //Alternatively avoid built-in behavior and explicitly save session with
        //authService.SaveSession(session, SessionExpiry);
        //return null;
    }
}

How can I add a custom claim to the ServiceStack framework created JWT, the value of that claim coming from the database and this implementation of this code not be function binding in AppHost.cs where I do not even have the UserId to retrieve the value anyways?

Body:
I wanted to provide my final code for this even though @mythz provided the answer:

The CustomerUserSession:

[DataContract]
public class CustomUserSession: AuthUserSession
{
    [DataMember]
    public string ZipCode { get; set; }
}

The CustomCredentialsAuthProvider because I have a legacy db with all account info:

public override bool TryAuthenticate(IServiceBase authService,
        string userName, string password)
    {
        return true;
    }

    public override IHttpResult OnAuthenticated(IServiceBase authService,
        IAuthSession session, IAuthTokens tokens,
        Dictionary<string, string> authInfo)
    {
        var customUserSession = (CustomUserSession) session;
        //Fill IAuthSession with data you want to retrieve in the app eg:
        customUserSession.FirstName = "some_firstname_from_db";
        customUserSession.LastName = "some_lastname_from_db";
        customUserSession.Roles = new List<string> {"role1", "role2"};
        customUserSession.Permissions = new List<string> { "permission1", "permission2" };
        customUserSession.Email = "test@test.com";
        customUserSession.AuthProvider = "credentials";
        customUserSession.CreatedAt = DateTime.UtcNow;
        customUserSession.ZipCode = "92123";

        //Call base method to Save Session and fire Auth/Session callbacks:
        return base.OnAuthenticated(authService, session, tokens, authInfo);
    }

And my AppHost adding of the ServiceStack AuthFeature:

Plugins.Add(new AuthFeature(() => new CustomUserSession(),
    new IAuthProvider[] {
        new JwtAuthProvider
        {
            HashAlgorithm = "HS256",
            RequireSecureConnection = requireSecureConnection,
            AuthKeyBase64 = _configuration["AuthSettings:JwtAuthKeyBase64"],//Settings.Value.JwtAuthKeyBase64,
            ExpireTokensIn        = TimeSpan.FromHours(_configuration["AuthSettings:ExpireTokensIn"].ToDouble()),  // JWT Token Expiry
            ExpireRefreshTokensIn = TimeSpan.FromHours(_configuration["AuthSettings:ExpireRefreshTokensIn"].ToDouble()), // Refresh Token Expiry,
            CreatePayloadFilter = (payload,session) => {
                    payload["zipCode"] = ((CustomUserSession)session).ZipCode;
            },
            PopulateSessionFilter = (session, token, req) => {
                ((CustomUserSession) session).ZipCode = token["zipCode"];
            }
        },
        new CustomCredentialsAuthProvider() //HTML Form post of User/Pass
    }));


问:
Where to put reusable methods for access by controllers in rails
I have several methods I call from my controllers that feel like they should be pulled out and put into a reusable class, outside of the controller. Where do people usually put this stuff? I know I can put them into my ApplicationController, but that doesn't seem to be a great solution if I think I can use these methods later in other applications.

Also, I have a bunch of utility methods in my controllers that likely won't be used in other controllers, or in the future at all, but I feel like they just bloat my controller a bit. Do people usually move these out someplace for cleanliness or just end up with a huge controller?

I'm coming from Java and Actionscript where I'd just create new util classes for this stuff.

答:
Related to Sahil kalra's above answer from 2014:

Rails now has an app/controllers/concerns directory where you can put modules full of helper methods and easily include or extend them in your controllers.  I just copied and pasted all of my logic-intensive methods out of my application_controller and they worked right out of the box.

(You should, of course, still make sure everything works correctly before putting anything into production.)

ContentLicense: CC BY-SA 2.5


问:
Firebase Node.js- onAuthStateChanged() : How to redirect to different page?
As the onAuthStateChanged() function in Firebase does not accept any res/req parameters, nor does window.location work on Node.js (because it is server-side code), how do I redirect to another page after auth state changes?

For reference what I had was:

```<code>firebase.auth().onAuthStateChanged(firebaseUser=>{
    if(user){
         window.location = "/profile";
    }
});
</code>```

答:
I believe you're using the client side Firebase SDK. If you're developing inside of Node you'll have to use the Admin SDK. I believe it gives you more control over authentication.

https://firebase.google.com/docs/auth/admin/

What you're trying to do would work well on the client but doing it on the server would require a completely different approach. One might be using a Cloud Function to have the user logout. You could handle the session manually and redirect as needed.

However, The code you're writing now is better suited to doing this over on the client.

Body:
As the onAuthStateChanged() function in Firebase does not accept any res/req parameters, nor does window.location work on Node.js (because it is server-side code), how do I redirect to another page after auth state changes?

For reference what I had was:

firebase.auth().onAuthStateChanged(firebaseUser=>{
    if(user){
         window.location = "/profile";
    }
});


问:
TFS database project for both Azure SQL database and on premises with multiple filegroups
I am working on a project to replicate an application that currently runs on premises to an Azure SQL Database.  For the foreseeable future, the application will have to run both on site and on Azure.  The project is stored in TFS, and multiple filegroups are specified.  Development is ongoing.  Is there a way I can maintain this as one project in source control, given that Azure SQL databases only have a primary filegroup?  I feel like I can't be the first person in this situation, but I haven't found a decent solution yet.

I'm fine with the Azure database only running on primary, but that is not an option for the local database.  This is not for a single deployment, I would like to continue to deploy changes both locally and to Azure from source control.  I may be asking for too much here, I just really really want to avoid dual maintenance, when there are a number of teams involved.

Thank you!

答:
There is no way to use multiple filegroups in Azure SQL Database. If you want to move your database to the cloud and keep the ability to use multiple filegroups, please consider setting an Azure VM with SQL Server on it. Another option would be to change your application so that it does not use SQL filegroups.

As for the replication, please consider SQL Server replication or Azure Data Sync. Azure Data Sync requires an Azure SQL database. It is slower than SQL Server replication but it can handle conflicts.


问:
My Android device does not appear in the list of adb devices
I have a HP Slate 21 that is connected to my Windows box using a USB cable.

USB debugging is enabled on the device.

After adding the proper %SingleAdbInterface% and %CompositeAdbInterface% entries to the android_winusb.inf file, I now see "Android ADB Interface" in my Device Manager.
However, running adb devices at the command-line does not show the device.

I have another HP slate 7 that shows up just fine under adb devices.

The only difference I see from Device Manager is that the one that works is named "Android Composite ADB Interface" and the other one is named "Android ADB Interface."

There is yet another subtle difference. In the winusb.inf file, for Slate 7 I have two %CompositeAdbInterface% entries defined but for Slate 21, there is just one %CompositeAdbInterface% entry defined.

How can I see my device by running the command adb devices?

答:
After trying all the solutions and still not finding a solution, I deduced the problem to the USB cable(s).

Since it was working sometimes for me (ie at work) and not other times (ie at home), I decided to try out different cables and different Android phones I had. And sure enough, some of the cables did not work (adb can't see phone) with any of the phones, but they still charged the phone and Android recognized that it was plugged in.

The good cables obviously charged the phones and were immediately recognized by adb. It was a pretty clear difference.

I couldn't tell the cables apart physically from outside, but all were free USB cables I've gathered over the years.

ContentLicense: CC BY-SA 4.0


问:
Recommended Fonts for Programming?
What fonts do you use for programming, and for what language/IDE?  I use Consolas for all my Visual Studio work, any other recommendations?</p>

答: I like Fixedsys in Visual Studio.  It's a classic.  No anti-aliasing blur.

Title: Recommended Fonts for Programming?

LastEditorDisplayName: Peter Hilton


问:
.Net 3.5, most secure way to pass string between processes
I'd like to be able to pass a SecureString (a cached passphrase) to a child process in C# (.Net 3.5), but I don't know what the most secure way is to do it. If I were to convert the SecureString back to a regular string and pass it as a command-line argument, for example, then I think the value may be prone to disk paging--which would make the plaintext touch the filesystem and ruin the point of using SecureString.

Can the IntPtr for the SecureString be passed instead? Could I use a named pipe without increasing the risk?

答:
In general you should define your threat model before worrying about more exotic attacks. In this case: are you worried that somebody shuts down the computer and does a forensic analysis of the harddrive? Application memory can also be swapped out, so the simple fact that one process has it in memory, makes it potentially possible for it to end in the swap file. What about hibernation? During hibernation the entire content of the memory is written to the harddisk (including the SecureString - and presumably the encryption key!). What if the attacker has access to the system while it's running and can search through the memory of applications?

In general client side security is very tricky and unless you have dedicated hardware (like a TPM chip) it is almost impossible to get right. Two solutions would be:

If you only need to test for equality between two strings (ie: is this string the same as the one I had earlier), store only a (salted) hash value of it.

Make the user re-enter the information when it is needed a second time (not very convenient, but security and convenience are opposed to each other)

OwnerDisplayName: Chris Wenham

LastEditorDisplayName: Mark Biek

OwnerDisplayName: Cd-MaN


问:
Fastest way to generate combinations of rows
We have a table of plans and each plan has many services. We would like a fast way of finding the combinations of plans that do not contain duplicate services but as a combinations contain certain services.

e.g. table of plans

```<code>id | service_1 | service_2 | ...
---------------------------------
1  |   true    |  true     | ...
2  |   true    |  false    | ...
3  |   false   |  true     | ...
</code>```

e.g. valid combinations containing service_1 and service_2

UPDATE

If there were 2 services and I required both of them we would combine up to 2 rows (or plans) as they could contain at minimum 1 service in each.

```<code>id | service_1 | service_2 | id | service_1 | service_2 |
---------------------------------------------------------
1  |   true    |  true     |NULL|    NULL   |    NULL   |
2  |   true    |  false    | 3  |    false  |    true   |
</code>```

UPDATE

It currently works by self left joining itself with aggressive pruning or rows. The query is dynamically generated based on the number of services. It creates the permutations of valid join conditions making it not practical to post.

Currently the cost is in the order of number of plans ^ number of services.

I'm mostly interested in other ways of solving this not necessarily improvements to the current way.

答:
As I mentioned in comments, the rule by which one determines a "duplicate" is unclear. However, from the sounds of it, you are simply doing a bitwise AND.

```<code>With RawData As
    (
    Select 1 As id, 1 As service_1, 1 As service_2
    Union All Select 2, 1, 0
    Union All Select 3, 0, 1
    )
    , BinData As
    (
    Select A.id, A.service_1, A.service_2
        , A.service_1 * 2 + A.service_2 As Bin
    From RawData As A
    )
Select *
From BinData As F1
    Left Join BinData As F2
        On F2.id <> F1.id
            And F1.Bin & F2.Bin = 0
Order By F1.id
</code>```

However, you will note in this solution that I get a row for id=3. For the same reason that id=3 is a "duplicate" for id=2, the reverse is also true.

If this is not correct, we need far more clarity and some better sample data that illustrates the edge cases of what is and is not a "duplicate".

Update

Given what cyberwiki has stated in comments, if what is being sought for each plan is another plan which when combined provide all services exactly once, then what is being sought is a binary one's compliment that will produce all 1's. We can do that by finding all plans which when XOR'd to the current plan produce all ones:

```<code>With RawData As
    (
    Select 1 As id, 1 As service_1, 1 As service_2
    Union All Select 2, 1, 0
    Union All Select 3, 0, 1
    )
    , BinData As
    (
    Select A.id, A.service_1, A.service_2
        , A.service_1 * 2 + A.service_2 As Bin
    From RawData As A
    )
Select *, F1.Bin ^ F2.Bin
From BinData As F1
    Left Join BinData As F2
        On F2.id <> F1.id
            And F1.Bin ^ F2.Bin = 3
Order By F1.id
</code>```

Again, note that id=3 will show in the result because just as id=3 is perfect match for id=2, the reverse is also true.

Body:
We have a table of plans and each plan has many services. We would like a fast way of finding the combinations of plans that do not contain duplicate services but as a combinations contain certain services.

e.g. table of plans

id | service_1 | service_2 | ...
---------------------------------
1  |   true    |  true     | ...
2  |   true    |  false    | ...
3  |   false   |  true     | ...

e.g. valid combinations containing service_1 and service_2

UPDATE

If there were 2 services and I required both of them we would combine up to 2 rows (or plans) as they could contain at minimum 1 service in each.

id | service_1 | service_2 | id | service_1 | service_2 |
---------------------------------------------------------
1  |   true    |  true     |NULL|    NULL   |    NULL   |
2  |   true    |  false    | 3  |    false  |    true   |

UPDATE

It currently works by self left joining itself with aggressive pruning or rows. The query is dynamically generated based on the number of services. It creates the permutations of valid join conditions making it not practical to post.

Currently the cost is in the order of number of plans ^ number of services.

I'm mostly interested in other ways of solving this not necessarily improvements to the current way.

Body:
As I mentioned in comments, the rule by which one determines a "duplicate" is unclear. However, from the sounds of it, you are simply doing a bitwise AND.

With RawData As
    (
    Select 1 As id, 1 As service_1, 1 As service_2
    Union All Select 2, 1, 0
    Union All Select 3, 0, 1
    )
    , BinData As
    (
    Select A.id, A.service_1, A.service_2
        , A.service_1 * 2 + A.service_2 As Bin
    From RawData As A
    )
Select *
From BinData As F1
    Left Join BinData As F2
        On F2.id <> F1.id
            And F1.Bin & F2.Bin = 0
Order By F1.id

However, you will note in this solution that I get a row for id=3. For the same reason that id=3 is a "duplicate" for id=2, the reverse is also true.

If this is not correct, we need far more clarity and some better sample data that illustrates the edge cases of what is and is not a "duplicate".

Update

Given what cyberwiki has stated in comments, if what is being sought for each plan is another plan which when combined provide all services exactly once, then what is being sought is a binary one's compliment that will produce all 1's. We can do that by finding all plans which when XOR'd to the current plan produce all ones:

With RawData As
    (
    Select 1 As id, 1 As service_1, 1 As service_2
    Union All Select 2, 1, 0
    Union All Select 3, 0, 1
    )
    , BinData As
    (
    Select A.id, A.service_1, A.service_2
        , A.service_1 * 2 + A.service_2 As Bin
    From RawData As A
    )
Select *, F1.Bin ^ F2.Bin
From BinData As F1
    Left Join BinData As F2
        On F2.id <> F1.id
            And F1.Bin ^ F2.Bin = 3
Order By F1.id

Again, note that id=3 will show in the result because just as id=3 is perfect match for id=2, the reverse is also true.


问:
Regex: Get everything after the first occurrence of a space after a word
I need to get all the characters after the first space after a string.
E.g. I need to get {'s':'2'} from a string that is of format:

```<code>a=1 session=<value> {'s'='2'}
</code>```

The value will be of random length without space and there will be space before {'s'='2'}. So {'s'='2'} will always occur after the string 'session=' and the first space after that and there will be variable number of key value pairs like a=1 before session.

E.g.

```<code>From: a=1 b=2 session=sdasdsadsa {'foo':'2'}         # I need to get {'foo':'2'}
From: a=1 b=2  c=3 session=s2312dssdaa {'bar':'3'}   # I need to get {'bar':'3'}
</code>```

答:
This regexp should work /^\S*\s+(\S+) /

It is probably a better way of writing it. As this does quite many operations.

Body:
I need to get all the characters after the first space after a string.
E.g. I need to get {'s':'2'} from a string that is of format:

a=1 session=<value> {'s'='2'}

The value will be of random length without space and there will be space before {'s'='2'}. So {'s'='2'} will always occur after the string 'session=' and the first space after that and there will be variable number of key value pairs like a=1 before session.

E.g.

From: a=1 b=2 session=sdasdsadsa {'foo':'2'}         # I need to get {'foo':'2'}
From: a=1 b=2  c=3 session=s2312dssdaa {'bar':'3'}   # I need to get {'bar':'3'}


问:
Retrieving Stock Quotes using Eclipse - Error: The value of the local variable is not used
I'm trying out a java application to retrieve stock quotes using Yahoo API.
http://greatwebguy.com/programming/java/stock-quote-and-chart-from-yahoo-in-java/

No amendments to the sample code above. I've just added a main class.

```<code>public class Main {

    public static void main (String[] args) {

        StockBean stock = StockTickerDAO.getInstance().getStockPrice("GOOG");
    }
}
</code>```

I'm unable to execute the main class due to:
The value of the local variable stock is not used.

Can anyone spot what I'm missing?
Thank you in advance!

答: Yahoo discontinued it's stock quote service after it was acquired by Verizon. Intrinio is the alternative right now. There is a sample java program in GitHub at https://github.com/pmkent/intrinio-java-sample</p>

Body:
I'm trying out a java application to retrieve stock quotes using Yahoo API.
http://greatwebguy.com/programming/java/stock-quote-and-chart-from-yahoo-in-java/

No amendments to the sample code above. I've just added a main class.

public class Main {

    public static void main (String[] args) {

        StockBean stock = StockTickerDAO.getInstance().getStockPrice("GOOG");
    }
}

I'm unable to execute the main class due to:
The value of the local variable stock is not used.

Can anyone spot what I'm missing?
Thank you in advance!


问:
ScriptEngine JavaScript Doesn't Support Contains?
I've got some code like the following.

```<code>ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.eval("[1, 2, 3].contains(1)");
</code>```

But that throws the following error

```<code>javax.script.ScriptException: TypeError: [1, 2, 3].contains is not a function in <eval> at line number 1
</code>```

I can do indexOf(1) instead and that seems to work, but is there a reason why I don't have access to contains with this parser?

答:
You are looking for Array.prototype.includes.

Your code would be:

```<code>engine.eval("[1, 2, 3].includes(1)");
</code>```

Body:
I've got some code like the following.

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.eval("[1, 2, 3].contains(1)");

But that throws the following error

javax.script.ScriptException: TypeError: [1, 2, 3].contains is not a function in <eval> at line number 1

I can do indexOf(1) instead and that seems to work, but is there a reason why I don't have access to contains with this parser?

Body:
You are looking for Array.prototype.includes.

Your code would be:

engine.eval("[1, 2, 3].includes(1)");


问:
Angular2 - Component based architecture
Custom property is used for data binding across components.

```<code>          <section id="main">
              <app-home [dict]="dict">Hello there!</app-home>
          </section>
</code>```

here, dict is a custom property, where app-home is selector of one component used in other component.

The idea of components in Angular2 is to be highly cohesive and loosely coupled.

Why angular2 allow data binding across components?

答:
Passing data from parent to child with input binding is main
approach for component interaction.In summary this is required by development.</p>

Title: Angular2 - Component based architecture

Body:
Custom property is used for data binding across components.

              <app-home [dict]="dict">Hello there!</app-home>

here, dict is a custom property, where app-home is selector of one component used in other component.

The idea of components in Angular2 is to be highly cohesive and loosely coupled.

Why angular2 allow data binding across components?


问:
CSS: Background image larger than entire page
EDIT: Not a duplicate of the linked question as I am stating that I attempted the accepted solutions in the other question and that they are not solving my problem

I'm trying to give a containing section a background image but the image is about 15% larger than the screen. I've attempted making the background-size 100%, cover, and contain but it is consistently larger than the page. I looked through the size of each element in the DOM and they're all the same size none are larger so I am stumped as to what is causing the larger background image. Here's my code:
html

```<code><section className="Intro">
    <img />
    <h1>...</h1>
    <h2>...</h2>
    <h3>...</h3>
    <p>...</p>
</section>
</code>```

css

```<code>.Intro {
  background-image: url('../mobile-bg.jpg');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  color: white;
  height: 100vh;
}
</code>```

答:
Your code was correct. But some browsers hasn't supported for some css rules. Then we have to use their css rules. Try with this one. It will work</p>

```<code>.Intro {
  background-image: url('../mobile-bg.jpg');
  background-repeat: no-repeat;
  background-position: center center;
 -webkit-background-size: cover;
 -moz-background-size: cover;
 -o-background-size: cover;
  background-size: cover;
  color: white;
  height: 100vh;
}
</code>```

Body:
EDIT: Not a duplicate of the linked question as I am stating that I attempted the accepted solutions in the other question and that they are not solving my problem

I'm trying to give a containing section a background image but the image is about 15% larger than the screen. I've attempted making the background-size 100%, cover, and contain but it is consistently larger than the page. I looked through the size of each element in the DOM and they're all the same size none are larger so I am stumped as to what is causing the larger background image. Here's my code:
html

...

...

...

...

css

.Intro {
  background-image: url('../mobile-bg.jpg');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  color: white;
  height: 100vh;
}

Body:
Your code was correct. But some browsers hasn't supported for some css rules. Then we have to use their css rules. Try with this one. It will work

.Intro {
  background-image: url('../mobile-bg.jpg');
  background-repeat: no-repeat;
  background-position: center center;
 -webkit-background-size: cover;
 -moz-background-size: cover;
 -o-background-size: cover;
  background-size: cover;
  color: white;
  height: 100vh;
}


问:
Android: HTML encoder
I have html text that I want to show in webview.

As specification, data must be URI-escaped.
So I tried to use URLEncoder.encode() function, but that will not help me, as it converts blank space with plus sign.

So is there any encoding function available?

答:
As @Seb said, I created my own function that worked for me:

```<code>public String encodeHTML(String s)
{
    s = s.replaceAll("#", "%23");
    s = s.replaceAll("%", "%25");
    return s;
}
</code>```

Any improvement in this approach will be appreciated.

Title: Android: HTML encoder

Body:
As @Seb said, I created my own function that worked for me:

public String encodeHTML(String s)
{
    s = s.replaceAll("#", "%23");
    s = s.replaceAll("%", "%25");
    return s;
}

Any improvement in this approach will be appreciated.


问:
I am using Tinkerpop 3 and Gremlin. Can someone tell how I can commit the graph that I create using TinkerGraph.open()?
I am using Tinkerpop3 and Gremlin console (by running gremlin.bat). After I create a graph, add nodes, edges to it, if for some reason the console has to be closed I cannot retrieve the graph I created previously. Could someone please tell how I can save the graph I create ?
example- graph = TinkerGraph.open()
// commands to add nodes and edges
// Committing this graph to the db

答: There is no commit() for TinkerGraph as it's not transactional, but you can save your graph in several different formats. Check out Gremlin I/O docs to learn about the supported formats and get some examples on how to save / load graphs.


问:
change text-font size of whole page content
is there a way in javascript/css that i can change text size of all the labels, headings, paragraphs etc on a single click and without explicitly getting element's id and then changing its font size.

what i am doing right now is that i get element's id through javascript and change its font size explicitly. To get a clear picture of what i am doing check this link or check the following code

```<code><script type="text/javascript">
function changemysize(myvalue) {
    var div = document.getElementById("mymain");
    div.style.fontSize = myvalue + "px";
}
</script>
</code>```

HTML code

Choose a text size:
A
A
A

Only this text gets affected

```

答:
You can change the font of a element and its children recursively to "force" it all to change:

```<code>function changeFont(element){
    element.setAttribute("style",element.getAttribute("style")+";font-family: Courier New");
    for(var i=0; i < element.children.length; i++){
        changeFont(element.children[i]);
    }
}
changeFont(document.getElementsByTagName("body")[0]);
</code>```

Alternatively you can use the style atribute of the element as object:

```<code>function changeFont(element){
    element.style.fontFamily="Courier New";
    for(var i=0; i < element.children.length; i++){
        changeFont(element.children[i]);
    }
}
changeFont(document.getElementsByTagName("body")[0]);
</code>```

Body:
is there a way in javascript/css that i can change text size of all the labels, headings, paragraphs etc on a single click and without explicitly getting element's id and then changing its font size.

what i am doing right now is that i get element's id through javascript and change its font size explicitly. To get a clear picture of what i am doing check this link or check the following code

HTML code

Choose a text size:
A
A
A

Only this text gets affected

Body:
You can change the font of a element and its children recursively to "force" it all to change:

function changeFont(element){
    element.setAttribute("style",element.getAttribute("style")+";font-family: Courier New");
    for(var i=0; i < element.children.length; i++){
        changeFont(element.children[i]);
    }
}
changeFont(document.getElementsByTagName("body")[0]);

Alternatively you can use the style atribute of the element as object:

function changeFont(element){
    element.style.fontFamily="Courier New";
    for(var i=0; i < element.children.length; i++){
        changeFont(element.children[i]);
    }
}
changeFont(document.getElementsByTagName("body")[0]);


答:
I know this is really old, but it inspired me to do this natively one-line for multi key objects:

```<code>var arrayOfObjectsToCombine = [ { foo: 'bar', dog: 'cat' }, { baz: 'boom' } ];
arrayOfObjectsToCombine.reduce(function(done, obj) { Object.keys(obj).map( function(K) { done[K] = obj[K] } ); return done; }, {})
</code>```

result:
{ foo: 'bar', dog: 'cat', baz: 'boom' }

Title: Convert array of objects to just one object

Body:
I'm trying to turn this:

[ { '231634908': 137875 },
  { '388252786': 150004 },
  { '333624027': 144107 },
  { '382758108': 149729 },
  { '384113458': 149803 },
  { '384844004': 149848 },
  { '405877005': 150481 },
  { '405877005': 150481 } ]

Into this:

{
    '231634908': 137875,
    '388252786': 150004,
    '333624027': 144107,
    '382758108': 149729,
    '384113458': 149803,
    '384844004': 149848,
    '405877005': 150481,
    '405877005': 150481
}

Using underscore.

I tried

_.object(list);

_.object(_.keys(list), _.values(list));

_.object(_.keys(list[0]), _.values(list[0]));

Body:
I know this is really old, but it inspired me to do this natively one-line for multi key objects:

var arrayOfObjectsToCombine = [ { foo: 'bar', dog: 'cat' }, { baz: 'boom' } ];
arrayOfObjectsToCombine.reduce(function(done, obj) { Object.keys(obj).map( function(K) { done[K] = obj[K] } ); return done; }, {})

result:
{ foo: 'bar', dog: 'cat', baz: 'boom' }


问:
Automatically Create a .cs file from a class in Visual Studio 2010
I often code in such way that I put several classes in one cs file to get my code going and then at some point, I want to move every class to a seperate .cs file within my C# project but I have to do this manually by creating a file for every class and cut and paste the class to the new file and then resolve the required namespace one by one for each file. No Fun!

Is there a way to just click right on the class and make visual studio to automatically move the class to a new file under the project tree? I mean, would you please provide such Macro/Snippet(or whatever it is called :) ) and instructions on how to add it to Visual Studio 2010?

答:
Visual Studio 2017 now has Code Refactoring that includes Moving a class into its own file.

For example you can either right click on the class "Foo" and select "Quick Actions and Refactorings" (or the shortcut Ctrl +)

Then select "Move type into foo.cs"


问:
Button to insert in to sql : event handler is not in the Namespace or there is an error in the script
i'm building this program using javafx and sqllite
i have button in fxml with fx:id button1
and onAction: WriteToSql

```<code>package valgykla;

import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.event.ActionEvent;

/**
 * FXML Controller class
 *
 * @author Lukas
 */
public class MeniuController implements Initializable {
    @FXML
    private Button button1;

    @FXML
  public static void WriteToSql(ActionEvent sql){
        Connection con = null;
        PreparedStatement prSt = null;
        try {
            Class.forName("org.sqlite.JDBC");
            con = DriverManager.
                getConnection("jdbc:sqlite:database.db");
            String query = "insert into Meniu(name,code) values(?,?)";
            prSt = con.prepareStatement(query);
           prSt.setString(1, "jack");
           prSt.setString(12, "02545");
            int count = prSt.executeUpdate();
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block

        }
        // TODO Auto-generated catch block
         finally{
            try{
                if(prSt != null) prSt.close();
                if(con != null) con.close();
            } catch(Exception ex){}

        }
  }

    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

}
</code>```

sadly I get error

```<code>Caused by: javafx.fxml.LoadException: Error resolving onAction='#WriteToSql', either the event handler is not in the Namespace or there is an error in the script.
file:/C:/Users/Lukas/Desktop/lukasX/Valgykla/dist/run1382723305/Valgykla.jar!/valgykla/Meniu.fxml:29
</code>```

答:
emmmm,when I first try it on eclipse i use onAction="#youfuctionname",then cause a error.I check it all,nothing wrong.then i delete the symbol #,it works well.But after a while,when I try to run another program,it gets error,and I don't know why,I search it online and see u put # in your onAction name,finally I put # back to my onAction name ,weirdly it works.
my ide always happen so many strangely problems........not only eclipes </p>

Body:
i'm building this program using javafx and sqllite
i have button in fxml with fx:id button1
and onAction: WriteToSql

package valgykla;

import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.event.ActionEvent;

/**
 * FXML Controller class
 *
 * @author Lukas
 */
public class MeniuController implements Initializable {
    @FXML
    private Button button1;

    @FXML
  public static void WriteToSql(ActionEvent sql){
        Connection con = null;
        PreparedStatement prSt = null;
        try {
            Class.forName("org.sqlite.JDBC");
            con = DriverManager.
                getConnection("jdbc:sqlite:database.db");
            String query = "insert into Meniu(name,code) values(?,?)";
            prSt = con.prepareStatement(query);
           prSt.setString(1, "jack");
           prSt.setString(12, "02545");
            int count = prSt.executeUpdate();
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block

        }
        // TODO Auto-generated catch block
         finally{
            try{
                if(prSt != null) prSt.close();
                if(con != null) con.close();
            } catch(Exception ex){}

        }
  }

    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

}

sadly I get error

Caused by: javafx.fxml.LoadException: Error resolving onAction='#WriteToSql', either the event handler is not in the Namespace or there is an error in the script.
file:/C:/Users/Lukas/Desktop/lukasX/Valgykla/dist/run1382723305/Valgykla.jar!/valgykla/Meniu.fxml:29


问:
iOS 11 iPhone X simulator UITabBar icons and titles being rendered on top covering eachother
Anyone having issue with the iPhone X simulator around the UITabBar component?

Mine seem to be rendering the icons and title on top of each other, I'm not sure if I'm missing anything, I also ran it in the iPhone 8 simulator, and one actual devices where it looks fine just as shown on the story board.

iPhone X:

iPhone 8

答:
I have scratched my head over this problem. It seems to be associated with how the tabBar is initialized and added to view hierarchy. I also tried above solutions like calling invalidateIntrinsicContentSize, setting the frame, and also bottomInsets inside a UITabBar subclass. They seem to work however temporarily and they break of some other scenario or regress the tab bar by causing some ambiguous layout issue. When I was debugging the issue I tried assigning the height constraints to the UITabBar and centerYAnchor, however neither fixed the problem. I realized in view debugger that the tabBar height was correct before and after the problem reproduced, which led me to think that the problem was in the subviews. I used the below code to successfully fix this problem without regressing any other scenario.

```<code>- (void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if (DEVICE_IS_IPHONEX())
    {
        [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            for (UIView *view in self.tabBar.subviews)
            {
                if ([NSStringFromClass(view.class) containsString:@"UITabBarButton"])
                {
                    if (@available (iOS 11, *))
                    {
                        [view.bottomAnchor constraintEqualToAnchor:view.superview.safeAreaLayoutGuide.bottomAnchor].active = YES;
                    }
                }
            }
        } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            [self.tabBar layoutSubviews];
        }];
    }
}
</code>```

Assumptions: I am doing this only for iPhone X, since it doesn't seem to reproduce on any other device at the moment.
Is based on the assumption that Apple doesn't change the name of the UITabBarButton class in future iOS releases.
We're doing this on UITabBarButton only when means if apple adds more internal subviews in to UITabBar we might need to modify the code to adjust for that.

Please lemme know if this works, will be open to suggestions and improvements!

It should be simple to create a swift equivalent for this.

Body:
I have scratched my head over this problem. It seems to be associated with how the tabBar is initialized and added to view hierarchy. I also tried above solutions like calling invalidateIntrinsicContentSize, setting the frame, and also bottomInsets inside a UITabBar subclass. They seem to work however temporarily and they break of some other scenario or regress the tab bar by causing some ambiguous layout issue. When I was debugging the issue I tried assigning the height constraints to the UITabBar and centerYAnchor, however neither fixed the problem. I realized in view debugger that the tabBar height was correct before and after the problem reproduced, which led me to think that the problem was in the subviews. I used the below code to successfully fix this problem without regressing any other scenario.

- (void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if (DEVICE_IS_IPHONEX())
    {
        [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            for (UIView *view in self.tabBar.subviews)
            {
                if ([NSStringFromClass(view.class) containsString:@"UITabBarButton"])
                {
                    if (@available (iOS 11, *))
                    {
                        [view.bottomAnchor constraintEqualToAnchor:view.superview.safeAreaLayoutGuide.bottomAnchor].active = YES;
                    }
                }
            }
        } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            [self.tabBar layoutSubviews];
        }];
    }
}

Assumptions: I am doing this only for iPhone X, since it doesn't seem to reproduce on any other device at the moment.
Is based on the assumption that Apple doesn't change the name of the UITabBarButton class in future iOS releases.
We're doing this on UITabBarButton only when means if apple adds more internal subviews in to UITabBar we might need to modify the code to adjust for that.

Please lemme know if this works, will be open to suggestions and improvements!

It should be simple to create a swift equivalent for this.


问:
keyboard shortcut customizing in visual studio 2013
Basically I want to Add a short cut key to write my Sign and Current Data + time on the Comment code to see in future when and by whom the code was changed ! I searched on net and i found the option for open the KeyBinding.json file either to Open from Tools > Modify keyboard short cuts or File > Preference > KeyBoard Short cut ..
But I am not having either of the Option available in my menu or submenu . </p>

答:
There is an extension for Visual Studio that enables the use of macros in the Visual Studio IDE

Macros for Visual Studio

It has certain  handy features like following

Record and playback active document operations and Visual Studio IDE
commands

Playback multiple times

Manage and persist macros with a Macro Explorer

Assign keyboard bindings to any macro

Macros recorded as JavaScript files that call VS DTE APIs

Macro editing in Visual Studio with DTE IntelliSense

Stop playback

Sample macros

However from Menu>Tools>Macros>Macro Explorer you can record your custom macros and also between lots of predefined macros you can find Insert Date & Time or Insert Date macro as per your requirement.

Hope it helps. Happy Coding!


问:
Returning an array of string and populate UILabel - Swift 3
There are two requests being made. The first request returns an array of int. The objects in the array of int are unique. Meaning, it has a string value associated with an int. To get the value for the key, I have to make a second request. The second URL request has the value for the array of int from the first URL.
(Second URL Request) I am trying to make a URL request using swift 3. Following is the code:

```<code>func fetchMovieGenres(_ forGenreIds: [Int], callback: @escaping (String) -> Void) {
    let params = [ API: APIKey ]
    var request = URLRequest(url: urlBuilder.tmdbURLBuilder(params as [String: Any], withPathExtension: MovieGenreList))
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = urlBuilder.session.dataTask(with: request) {(data, response, error) in
        do {
            if let data = data, let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any], let results = json["genre"] as? [[String:Any]] {
                callback(Genre.genreFromResults(results)) // Cannot convert value of type '[Genre]' to expected argument type 'String'
            }
        } catch {
            print("Error parsing JSON: \(error)")
        }
    }
    task.resume()
}
</code>```

In the viewDidLoad() I am doing this:
genreLabel.text = "\(fetchMovieGenres(result?.genreIds)!)"

What is happening is, I am trying to return an array of string from remote URL and populate that in UILabel. But for some reason, I am not being able to achieve that.

答:
First of all, you need to supply a callback for the eventual string. Assuming that Genre.genreFromResults(results) is your desired string for the label...

Change your method to:

private func fetchMovieGenres(_ forGenreIds: [Int], callback: (String) -> Void) {

Change:

self.genre = Genre.genreFromResults(results)
    print(json)

to:

callback(Genre.genreFromResults(results))

And change your method call to:

fetchMovieGenres(ids) { string in
    genreLabel.text = string
}

Body:
There are two requests being made. The first request returns an array of int. The objects in the array of int are unique. Meaning, it has a string value associated with an int. To get the value for the key, I have to make a second request. The second URL request has the value for the array of int from the first URL.
(Second URL Request) I am trying to make a URL request using swift 3. Following is the code:

func fetchMovieGenres(_ forGenreIds: [Int], callback: @escaping (String) -> Void) {
    let params = [ API: APIKey ]
    var request = URLRequest(url: urlBuilder.tmdbURLBuilder(params as [String: Any], withPathExtension: MovieGenreList))
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = urlBuilder.session.dataTask(with: request) {(data, response, error) in
        do {
            if let data = data, let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any], let results = json["genre"] as? [[String:Any]] {
                callback(Genre.genreFromResults(results)) // Cannot convert value of type '[Genre]' to expected argument type 'String'
            }
        } catch {
            print("Error parsing JSON: \(error)")
        }
    }
    task.resume()
}

In the viewDidLoad() I am doing this:
genreLabel.text = "\(fetchMovieGenres(result?.genreIds)!)"

What is happening is, I am trying to return an array of string from remote URL and populate that in UILabel. But for some reason, I am not being able to achieve that.


问:
Appending ng-repeat into HTML element dynamically
I trying to append ng-repeat into my HTML div on load.
It recognizes  the ng-repeat, however the index value isn't displaying as it should

HTML

```<code><div id="myInnerCarousel"></div>
</code>```

controller:

```<code>var myCarousel = document.getElementById('myInnerCarousel');
var newItem = document.createElement("div");
newItem.setAttribute("class","item");

var newData = document.createElement("div");
newData.setAttribute("class", "col-xs-6 col-sm-6 col-md-3 col-lg-3");
newData.setAttribute("ng-repeat", "mat in " + arr);

//Create individual values seperately
var newMaterialName = document.createElement("h4");
var nameNode = document.createTextNode("{{mat.Name}}");
newMaterialName.appendChild(nameNode);
//Append everything together

newData.appendChild(newMaterialName);
newItem.appendChild(newData);
myCarousel.appendChild(newItem);
</code>```

However the result is this:

https://gyazo.com/00b76c6b910d4c6701059d404783f720

It got the right idea of displaying my array, however angular isn't displaying h4 right.

EDIT: imtrying to achieve this in my html:

```<code><div ng-controller="myController">
<div class="item">
    <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3" ng-repeat="mat in array1">
        <h4>{{mat.Name}}</h4>
    </div>
</div>
<div class="item">
    <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3" ng-repeat="mat in array2">
        <h4>{{mat.Name}}</h4>
    </div>
</div>
</code>```

答:
Dynamically added component should be compiled using angular. you can use $compile function of angular. Below is working code.

Jsfiddle

```<code>function TodoCtrl($scope, $compile) {
    $scope.arr = [{Name: "Dynamically Added cowermponent"}];
    var myCarousel = document.getElementById('myInnerCarousel');
    var newItem = document.createElement("div");
    newItem.setAttribute("class","item");

    var newData = document.createElement("div");
    newData.setAttribute("class", "col-xs-6 col-sm-6 col-md-3 col-lg-3");
    newData.setAttribute("ng-repeat", "mat in arr");

    //Create individual values seperately
    var newMaterialName = document.createElement("h4");
    var nameNode = document.createTextNode("{{mat.Name}}");
    newMaterialName.appendChild(nameNode);
    //Append everything together

    newData.appendChild(newMaterialName);
    newItem.appendChild(newData);
    myCarousel.appendChild(newItem);
    $compile(newItem)($scope);
}
</code>```

Body:
I trying to append ng-repeat into my HTML div on load.
It recognizes  the ng-repeat, however the index value isn't displaying as it should

HTML

controller:

var myCarousel = document.getElementById('myInnerCarousel');
var newItem = document.createElement("div");
newItem.setAttribute("class","item");

var newData = document.createElement("div");
newData.setAttribute("class", "col-xs-6 col-sm-6 col-md-3 col-lg-3");
newData.setAttribute("ng-repeat", "mat in " + arr);

//Create individual values seperately
var newMaterialName = document.createElement("h4");
var nameNode = document.createTextNode("{{mat.Name}}");
newMaterialName.appendChild(nameNode);
//Append everything together

newData.appendChild(newMaterialName);
newItem.appendChild(newData);
myCarousel.appendChild(newItem);

However the result is this:

https://gyazo.com/00b76c6b910d4c6701059d404783f720

It got the right idea of displaying my array, however angular isn't displaying h4 right.

EDIT: imtrying to achieve this in my html:

{{mat.Name}}

{{mat.Name}}

Body:
Dynamically added component should be compiled using angular. you can use $compile function of angular. Below is working code.

Jsfiddle

function TodoCtrl($scope, $compile) {
    $scope.arr = [{Name: "Dynamically Added cowermponent"}];
    var myCarousel = document.getElementById('myInnerCarousel');
    var newItem = document.createElement("div");
    newItem.setAttribute("class","item");

    var newData = document.createElement("div");
    newData.setAttribute("class", "col-xs-6 col-sm-6 col-md-3 col-lg-3");
    newData.setAttribute("ng-repeat", "mat in arr");

    //Create individual values seperately
    var newMaterialName = document.createElement("h4");
    var nameNode = document.createTextNode("{{mat.Name}}");
    newMaterialName.appendChild(nameNode);
    //Append everything together

    newData.appendChild(newMaterialName);
    newItem.appendChild(newData);
    myCarousel.appendChild(newItem);
    $compile(newItem)($scope);
}


问:
Graphviz: How to get fixed node positions
I am quite new to Graphviz, sorry if my question is too naif.

In dot, I am trying to have several images of graphs, with nodes in a fix position, but with different arcs. However, even a minor modification in the arc configuration, makes a huge difference in the layout. I found some workarounds (by keeping certain hedges as invisible, or by using "back" option). However, I am wondering if there is a more elegant way to avoid situations like this, where the only modification of one arc direction gives a totally different layout.

For example, see this:

```<code>digraph exempleUPFM {
label=mylab;
ratio = 0.5;
spline = line; forcelabels=true;
node [shape = circle;style=filled; color=lightgrey;];
1 [xlabel="10" fontcolor= blue group=g1];
4 [xlabel="-6" fontcolor= red group=g1];
2 [xlabel="4" fontcolor= blue group=g2];
5 [xlabel="-8" fontcolor= red group=g2];
node [shape = circle; style=""]
{rank=same; 1 2}
{rank=same; 4 5}
1 -> 2 [label=" 1"]
1 -> 3 [label=" 8"]
1 -> 4 [label=" 1"]
2 -> 3 [label=" 2"]
3 -> 4 [label=" 1"]
3 -> 5 [label=" 4"]
4 -> 5 [label=" 12"]
5 -> 2 [label=" -7"]
}
</code>```

or this

```<code>digraph exemple2UPFM {
label=mylab;
ratio = 0.5;
spline = line; forcelabels=true;
node [shape = circle;style=filled; color=lightgrey;];
1 [xlabel="10" fontcolor= blue group=g1];
4 [xlabel="-6" fontcolor= red group=g1];
2 [xlabel="4" fontcolor= blue group=g2];
5 [xlabel="-8" fontcolor= red group=g2];
node [shape = circle; style=""];
{rank=same; 1 2}
{rank=same; 4 5}
1 -> 2 [label=" 1"]
1 -> 3 [label=" 8"]
1 -> 4 [label=" 1"]
2 -> 3 [label=" 2"]
3 -> 4 [label=" 1"]
3 -> 5 [label=" 4"]
5 -> 4 [label="-12"]
5 -> 2 [label=" -7"]
}
</code>```

In this specific case, the only difference is the direction of arc between 5 and 4. But the difference in the graph layout is brutal. In the second example, if I keep the arc 4 -> 5 and I add the "back" option, the layout comes back to the original.

Do you have any clue why this, and if there is a way to avoid the position of the nodes to change at any minimum arc modification?

Thank you very much for your help.

答:
graphviz doesn't know how you want the graph to look like. It figures it out following the instructions you give. In the default layout (Top to Bottom) when you say A -> B it puts the first node on top of the second, and in case they are of the same rank, it puts the first to the left of the second. If you look at the "brutally" changed layout, you see the logic.

So if you want to stay with the node arrangement of your first listing, it's a safer bet to say 2 -> 5[ dir = back ] in both cases, and the 4 -> 5[ dir = back ] should come as no surprise. If you keep graphviz' logic in mind, you should be able to get your layouts sorted in most cases. Invisible nodes and edges, or adding weight to edges is the next level.

Just to illustrate it:

```<code>digraph exempleSO
{
    label=mylab;
    ratio = 0.5;
    spline = line;
    forcelabels=true;

    node [shape = circle;style=filled; color=lightgrey;];
    1 [xlabel="10" fontcolor= blue group=g1];
    4 [xlabel="-6" fontcolor= red group=g1];
    2 [xlabel="4" fontcolor= blue group=g2];
    5 [xlabel="-8" fontcolor= red group=g2];

    node [shape = circle; style=""]
    {rank=same; 1 2}
    {rank=same; 4 5}
    1 -> 2 [label=" 1"]
    1 -> 3 [label=" 8"]
    1 -> 4 [label=" 1"]
    2 -> 3 [label=" 2"]
    3 -> 4 [label=" 1"]
    3 -> 5 [label=" 4"]
    4 -> 5 [dir = back, label=" 12 back"]
    2 -> 5 [dir = back, label=" -7 back"]
}
</code>```

yields

Body:
I am quite new to Graphviz, sorry if my question is too naif.

In dot, I am trying to have several images of graphs, with nodes in a fix position, but with different arcs. However, even a minor modification in the arc configuration, makes a huge difference in the layout. I found some workarounds (by keeping certain hedges as invisible, or by using "back" option). However, I am wondering if there is a more elegant way to avoid situations like this, where the only modification of one arc direction gives a totally different layout.

For example, see this:

digraph exempleUPFM {
label=mylab;
ratio = 0.5;
spline = line; forcelabels=true;
node [shape = circle;style=filled; color=lightgrey;];
1 [xlabel="10" fontcolor= blue group=g1];
4 [xlabel="-6" fontcolor= red group=g1];
2 [xlabel="4" fontcolor= blue group=g2];
5 [xlabel="-8" fontcolor= red group=g2];
node [shape = circle; style=""]
{rank=same; 1 2}
{rank=same; 4 5}
1 -> 2 [label=" 1"]
1 -> 3 [label=" 8"]
1 -> 4 [label=" 1"]
2 -> 3 [label=" 2"]
3 -> 4 [label=" 1"]
3 -> 5 [label=" 4"]
4 -> 5 [label=" 12"]
5 -> 2 [label=" -7"]
}

or this

digraph exemple2UPFM {
label=mylab;
ratio = 0.5;
spline = line; forcelabels=true;
node [shape = circle;style=filled; color=lightgrey;];
1 [xlabel="10" fontcolor= blue group=g1];
4 [xlabel="-6" fontcolor= red group=g1];
2 [xlabel="4" fontcolor= blue group=g2];
5 [xlabel="-8" fontcolor= red group=g2];
node [shape = circle; style=""];
{rank=same; 1 2}
{rank=same; 4 5}
1 -> 2 [label=" 1"]
1 -> 3 [label=" 8"]
1 -> 4 [label=" 1"]
2 -> 3 [label=" 2"]
3 -> 4 [label=" 1"]
3 -> 5 [label=" 4"]
5 -> 4 [label="-12"]
5 -> 2 [label=" -7"]
}

In this specific case, the only difference is the direction of arc between 5 and 4. But the difference in the graph layout is brutal. In the second example, if I keep the arc 4 -> 5 and I add the "back" option, the layout comes back to the original.

Do you have any clue why this, and if there is a way to avoid the position of the nodes to change at any minimum arc modification?

Thank you very much for your help.

Body:
graphviz doesn't know how you want the graph to look like. It figures it out following the instructions you give. In the default layout (Top to Bottom) when you say A -> B it puts the first node on top of the second, and in case they are of the same rank, it puts the first to the left of the second. If you look at the "brutally" changed layout, you see the logic.

So if you want to stay with the node arrangement of your first listing, it's a safer bet to say 2 -> 5[ dir = back ] in both cases, and the 4 -> 5[ dir = back ] should come as no surprise. If you keep graphviz' logic in mind, you should be able to get your layouts sorted in most cases. Invisible nodes and edges, or adding weight to edges is the next level.

Just to illustrate it:

digraph exempleSO
{
    label=mylab;
    ratio = 0.5;
    spline = line;
    forcelabels=true;

    node [shape = circle;style=filled; color=lightgrey;];
    1 [xlabel="10" fontcolor= blue group=g1];
    4 [xlabel="-6" fontcolor= red group=g1];
    2 [xlabel="4" fontcolor= blue group=g2];
    5 [xlabel="-8" fontcolor= red group=g2];

    node [shape = circle; style=""]
    {rank=same; 1 2}
    {rank=same; 4 5}
    1 -> 2 [label=" 1"]
    1 -> 3 [label=" 8"]
    1 -> 4 [label=" 1"]
    2 -> 3 [label=" 2"]
    3 -> 4 [label=" 1"]
    3 -> 5 [label=" 4"]
    4 -> 5 [dir = back, label=" 12 back"]
    2 -> 5 [dir = back, label=" -7 back"]
}

yields


问:
Query / Filter Azure Search Edm.Collection by any of multiple strings
I'm trying to filter an azure search edm.collection to return results if any of multiple strings are in the collection.  I can only get it working when querying for one item, which isn't good enough for my use case.  I can't find syntax for querying multiple parameters.

```<code>filter += "FirmTypes / any (x: x eq 'Big 4')";
</code>```

the above works and returns all of the documents where firm type is Big 4.

I've tried multiple ways (some below) to filter for more than one parameter with no success

```<code>//filter += " OR any (x: x eq 'Industry')";
//filter += "FirmTypes / any (x: x eq 'Industry')";
//filter += "FirmTypes / any (x: x eq 'Big 4', 'Industry', 'PLC')"
//filter += "FirmTypes / any (x: x eq 'Big 4' or 'Industry' or 'PLC')"
//filter += "FirmTypes / any (x: x eq 'Big 4') or (x: x eq 'Industry')"
//filter += "FirmTypes / any (x: x eq 'Big 4')|(x: x eq 'Industry')"
</code>```

Can anybody kindly point me in the right direction?  Thank you in advance.

答:
The best way to filter over multiple values is to use the new search.in function:

```<code>FirmTypes/any(x: search.in(x, 'Big 4|Industry', '|'))
</code>```

For large numbers of values, search.in is significantly faster than using a combination of or and eq, and it can handle a much larger number of values without hitting the hard limits on filter complexity.

Body:
I'm trying to filter an azure search edm.collection to return results if any of multiple strings are in the collection.  I can only get it working when querying for one item, which isn't good enough for my use case.  I can't find syntax for querying multiple parameters.

filter += "FirmTypes / any (x: x eq 'Big 4')";

the above works and returns all of the documents where firm type is Big 4.

I've tried multiple ways (some below) to filter for more than one parameter with no success

//filter += " OR any (x: x eq 'Industry')";
//filter += "FirmTypes / any (x: x eq 'Industry')";
//filter += "FirmTypes / any (x: x eq 'Big 4', 'Industry', 'PLC')"
//filter += "FirmTypes / any (x: x eq 'Big 4' or 'Industry' or 'PLC')"
//filter += "FirmTypes / any (x: x eq 'Big 4') or (x: x eq 'Industry')"
//filter += "FirmTypes / any (x: x eq 'Big 4')|(x: x eq 'Industry')"

Can anybody kindly point me in the right direction?  Thank you in advance.

Body:
The best way to filter over multiple values is to use the new search.in function:

FirmTypes/any(x: search.in(x, 'Big 4|Industry', '|'))

For large numbers of values, search.in is significantly faster than using a combination of or and eq, and it can handle a much larger number of values without hitting the hard limits on filter complexity.


问:
Postgres: create index on attribute of attribute in JSONB column?
I'm working in Postgres 9.6.5. I have the following table:

```<code> id             | integer
 data           | jsonb
</code>```

The data in the data column is nested, in the form:

```<code>{ 'identification': { 'registration_number': 'foo' }}
</code>```

I'd like to index registration_number, so I can query on it. I've tried this (based on this answer):

```<code>CREATE INDEX ON mytable((data->>'identification'->>'registration_number'));
</code>```

But got this:

```<code>ERROR:  operator does not exist: text ->> unknown
LINE 1: CREATE INDEX ON psc((data->>'identification'->>'registration...                                                    ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
</code>```

What am I doing wrong?

答:
You want:

```<code>CREATE INDEX ON mytable((data -> 'identification' ->> 'registration_number'));
</code>```

The -> operator returns the jsonb object under the key, and the ->> operator returns the jsonb object under the key as text. The most notable difference between the two operators is that ->> will "unwrap" string values (i.e. remove double quotes from the TEXT representation).

The error you're seeing is reported because data ->> 'identification' returns text, and the subsequent ->> is not defined for the text type.

Body:
I'm working in Postgres 9.6.5. I have the following table:

 id             | integer
 data           | jsonb

The data in the data column is nested, in the form:

{ 'identification': { 'registration_number': 'foo' }}

I'd like to index registration_number, so I can query on it. I've tried this (based on this answer):

CREATE INDEX ON mytable((data->>'identification'->>'registration_number'));

But got this:

ERROR:  operator does not exist: text ->> unknown
LINE 1: CREATE INDEX ON psc((data->>'identification'->>'registration...                                                    ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

What am I doing wrong?

Body:
You want:

CREATE INDEX ON mytable((data -> 'identification' ->> 'registration_number'));

The -> operator returns the jsonb object under the key, and the ->> operator returns the jsonb object under the key as text. The most notable difference between the two operators is that ->> will "unwrap" string values (i.e. remove double quotes from the TEXT representation).

The error you're seeing is reported because data ->> 'identification' returns text, and the subsequent ->> is not defined for the text type.


问:
how to pass two class instances to a method of the class in python
I made two trees in python with two different instances of the same class. I need to access the method in the class now with both the instances(roots) with which i created two trees.

```<code># To create a tree from scratch
class node:
    """To create nodes each time an instance has been
    created"""
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

def issame(self,root1,root2):
  if root1 or root2:
    print(root1.data,root2.data)
    self.issame(root1.left,root2.left)

"""To insert the data manually"""
##First Tree
root1 = node(10)
root1.left = node(20)
root1.right = node(30)
root1.left.left = node(50)

##Second Tree
root2 = node(20)
root2.left = node(20)
root2.right = node(30)
root2.left.left = node(50)

issame(root1,root2)
</code>```

I read in some post that we can keep the issame function definition outside of the class and use self within. Now at the end if i call the function, it says issame doesn't exist. Issame is used to check if leaf nodes of tree are same and the method is not fully developed as i faced the problem in first step.

答:
Try modify your issame method (outside class):

```<code>def issame(root1,root2):
   if root1 or root2:
   print(root1.data,root2.data)
       issame(root1.left,root2.left)
</code>```

I got the below result:

```<code>Python 3.6.1 (default, Dec 2015, 13:05:11)[GCC 4.8.2] on linux
10 20
20 20
50 50
</code>```

Full code:

```<code># To create a tree from scratch
class node:
    """To create nodes each time an instance has been created"""
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

def issame(roota,rootb):
   if roota or rootb:
      print(roota.data,rootb.data)
      issame(roota.left,rootb.left)

"""To insert the data manually"""
##First Tree
root1 = node(10)
root1.left = node(20)
root1.right = node(30)
root1.left.left = node(50)

##Second Tree
root2 = node(20)
root2.left = node(20)
root2.right = node(30)
root2.left.left = node(50)

issame(root1,root2)
</code>```

Body:
I made two trees in python with two different instances of the same class. I need to access the method in the class now with both the instances(roots) with which i created two trees.

# To create a tree from scratch
class node:
    """To create nodes each time an instance has been
    created"""
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

def issame(self,root1,root2):
  if root1 or root2:
    print(root1.data,root2.data)
    self.issame(root1.left,root2.left)

"""To insert the data manually"""
##First Tree
root1 = node(10)
root1.left = node(20)
root1.right = node(30)
root1.left.left = node(50)

##Second Tree
root2 = node(20)
root2.left = node(20)
root2.right = node(30)
root2.left.left = node(50)

issame(root1,root2)

I read in some post that we can keep the issame function definition outside of the class and use self within. Now at the end if i call the function, it says issame doesn't exist. Issame is used to check if leaf nodes of tree are same and the method is not fully developed as i faced the problem in first step.

Body:
Try modify your issame method (outside class):

def issame(root1,root2):
   if root1 or root2:
   print(root1.data,root2.data)
       issame(root1.left,root2.left)

I got the below result:

Python 3.6.1 (default, Dec 2015, 13:05:11)[GCC 4.8.2] on linux
10 20
20 20
50 50

Full code:

# To create a tree from scratch
class node:
    """To create nodes each time an instance has been created"""
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

def issame(roota,rootb):
   if roota or rootb:
      print(roota.data,rootb.data)
      issame(roota.left,rootb.left)

"""To insert the data manually"""
##First Tree
root1 = node(10)
root1.left = node(20)
root1.right = node(30)
root1.left.left = node(50)

##Second Tree
root2 = node(20)
root2.left = node(20)
root2.right = node(30)
root2.left.left = node(50)

issame(root1,root2)


问:
How can I get all the JS files name
How can I get all JS files name of my application ?

I tested :

```<code>@Inject
private ClientInfrastructure javascriptStack;

void onActivate(){
    mesJavaScripts=javascriptStack.getJavascriptStack();

    for(Asset javascript : mesJavaScripts){
      System.out.println(javascript.toString());
    }
}
</code>```

But I do not have all the JS. Do I use the good service ?

Thanks

答:
This way seems to work, although it relies on some internals that could change and it may slow things down a bit. Depending on your need, you might want to filter that based on a request parameter set in the pages you care about (add RequestGlobals as a parameter and use set/getAttribute).

A better way may be to provide your own DocumentLinker that captures the scripts as they get added.

Add this to your AppModule:

```<code>public void contributeMarkupRenderer(OrderedConfiguration<MarkupRendererFilter> configuration, final Environment environment, final RequestGlobals request) {
  MarkupRendererFilter getScripts = new MarkupRendererFilter() {
    public void renderMarkup(MarkupWriter writer, MarkupRenderer renderer) {
      DocumentLinker dl = environment.peek(DocumentLinker.class);
      renderer.renderMarkup(writer);
      try {
        List<String> scripts = (List<String>)request.getAttribute("scripts");
        if (scripts != null) {
          scripts.clear();
          Field f = dl.getClass().getDeclaredField("scripts");
          f.setAccessible(true);
          scripts.addAll((List<String>)f.get(dl));
        }
      } catch (Exception e) {}
    }
  };
  configuration.add("getScripts", getScripts, "after:DefaultValidationDecorator");
}
</code>```

In your test:

```<code>request.setAttribute("scripts", new ArrayList<String>());
</code>```

execute the page

```<code>assert request.getAttribute("scripts").contains(path_to_script_you_want_to_check);
</code>```

You might have to change either side to strip off the extra path information that Tapestry adds.

Title: How can I get all the JS files name

Body:
How can I get all JS files name of my application ?

I tested :

@Inject
private ClientInfrastructure javascriptStack;

void onActivate(){
    mesJavaScripts=javascriptStack.getJavascriptStack();

    for(Asset javascript : mesJavaScripts){
      System.out.println(javascript.toString());
    }
}

But I do not have all the JS. Do I use the good service ?

Thanks

Body:
This way seems to work, although it relies on some internals that could change and it may slow things down a bit. Depending on your need, you might want to filter that based on a request parameter set in the pages you care about (add RequestGlobals as a parameter and use set/getAttribute).

A better way may be to provide your own DocumentLinker that captures the scripts as they get added.

Add this to your AppModule:

public void contributeMarkupRenderer(OrderedConfiguration<MarkupRendererFilter> configuration, final Environment environment, final RequestGlobals request) {
  MarkupRendererFilter getScripts = new MarkupRendererFilter() {
    public void renderMarkup(MarkupWriter writer, MarkupRenderer renderer) {
      DocumentLinker dl = environment.peek(DocumentLinker.class);
      renderer.renderMarkup(writer);
      try {
        List<String> scripts = (List<String>)request.getAttribute("scripts");
        if (scripts != null) {
          scripts.clear();
          Field f = dl.getClass().getDeclaredField("scripts");
          f.setAccessible(true);
          scripts.addAll((List<String>)f.get(dl));
        }
      } catch (Exception e) {}
    }
  };
  configuration.add("getScripts", getScripts, "after:DefaultValidationDecorator");
}

In your test:

request.setAttribute("scripts", new ArrayList<String>());

execute the page

assert request.getAttribute("scripts").contains(path_to_script_you_want_to_check);

You might have to change either side to strip off the extra path information that Tapestry adds.