问:
C# MVC Query String Encoding and Decoding
I want to encode and decode the url parameters.

calling function in javascript

```<code>var url = '/Demo/Demo?id=58';
$(location).attr('href', url)
</code>```

Current url parameter

www.example.com/Demo/Demo?id=58

code in Demo controller

```<code>public ActionResult Demo(int id)
{
   return view();
}
</code>```

i want the above url to be changed like the bolow line

www.example.com/Demo/Demo?id=Sff5f8ddg

So that the id value will be confidential. what is the best way to encode and decode.

Note: we calling method by anchor tag, ajax and jquery. Encoding and Decoding other than Base64

Is there any cryptography method other than Base64 enoding and decoding like encrypt in javascript and decrypt in C# method

答:
So that the id value will be confidential. what is the best way to encode and decode.

It won't. At least in the way you are trying to make it. As soon as you encode the [internal] id it becomes the public id for that entry. It does not matter for user which id to use: 58 or Sff5f8ddg, as it would refer to the same entry in the system. If you are using unsalted algorithms it would prevent only not so sophisticated users to discover other entries in your system.

As I understand the problem you are trying to solve is - how to make other entries undiscoverable by having an id for some entry(ies). Eg, if user has an url for entry 58, they should not be able to find entries 57 and 59.

The solution is: use GUIDs as ID for your entries.

Also, you need to make sure that you've implemented proper access control for your entries.

Body:
I want to encode and decode the url parameters.

calling function in javascript

var url = '/Demo/Demo?id=58';
$(location).attr('href', url)

Current url parameter

www.example.com/Demo/Demo?id=58

code in Demo controller

public ActionResult Demo(int id)
{
   return view();
}

i want the above url to be changed like the bolow line

www.example.com/Demo/Demo?id=Sff5f8ddg

So that the id value will be confidential. what is the best way to encode and decode.

Note: we calling method by anchor tag, ajax and jquery. Encoding and Decoding other than Base64

Is there any cryptography method other than Base64 enoding and decoding like encrypt in javascript and decrypt in C# method


来源: stackexchange

问:
How do I send a value through AD-B2C using openid-Connect
I am currently developing an application using AD-B2C as my identity provider. This is integrated into the solution using their guidelines at AD B2C graph, which uses openid-connect (to the best of my understanding at least).

I need to use a form of email activation (outside of their register policy) and as such I need to be able to pass a value from the URL in the email, through the sign-up process at B2C and back to the redirection URL.

I read somewhere that a parameter called "state" can be used for this:

State: A value included in the request that will also be returned in the token response. It can be a string of any content that you want. A randomly generated unique value is typically used for preventing cross-site request forgery attacks. The state is also used to encode information about the user's state in the app before the authentication request occurred, such as the page they were on or the policy being executed.

I have tried to append a value to the redirection that happens when transferring the user to the B2C, but I don't know how.

```<code>if (!Request.IsAuthenticated)
        { // go to login page
            HttpContext.GetOwinContext().Authentication.Challenge(
                  new AuthenticationProperties() { RedirectUri = "/" }, Startup.SignUpSignInPolicyId);
        }
</code>```

The policy is stored in the startup.auth.cs file...

```<code>// B2C policy identifiers
    public static string SignUpPolicyId = ConfigurationManager.AppSettings["ida:SignUpPolicyId"];
    public static string SignInPolicyId = ConfigurationManager.AppSettings["ida:SignInPolicyId"];
    public static string SignUpSignInPolicyId = ConfigurationManager.AppSettings["ida:SignUpSignInPolicyId"];
    public static string ProfilePolicyId = ConfigurationManager.AppSettings["ida:UserProfilePolicyId"];
    public static string PasswordResetPolicyId = ConfigurationManager.AppSettings["ida:PasswordResetPolicyId"];
</code>```

....and is run during the ConfigureAuth method:

```<code>public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            CookieHttpOnly = true,
            ExpireTimeSpan = TimeSpan.FromHours(1),
        });

        // Configure OpenID Connect middleware for each policy
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpPolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ProfilePolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpSignInPolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(PasswordResetPolicyId));
    }
</code>```

which calls:

```<code>private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
    {
        return new OpenIdConnectAuthenticationOptions
        {
            // For each policy, give OWIN the policy-specific metadata address, and
            // set the authentication type to the id of the policy
            MetadataAddress = String.Format(aadInstance, tenant, policy),
            AuthenticationType = policy,

            // These are standard OpenID Connect parameters, with values pulled from web.config
            ClientId = clientId,
            RedirectUri = redirectUri,
            PostLogoutRedirectUri = redirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = AuthenticationFailed,
            },
            Scope = "openid",
            ResponseType = "id_token",
            //// This piece is optional - it is used for displaying the user's name in the navigation bar.
            //TokenValidationParameters = new TokenValidationParameters
            //{
            //    NameClaimType = "name",
            //},
        };

    }
</code>```

How do I pass a value like: (simplified example:)

```<code>if (!Request.IsAuthenticated)
        { // go to login page
            HttpContext.GetOwinContext().Authentication.Challenge(
                  new AuthenticationProperties() { RedirectUri = "/" }, Startup.SignUpSignInPolicyId, new { state = "value=uniquetoken&token=secrets" });
        }
</code>```

When these methods and policies are set on runtime ?
Furthermore if I am heading in a completely wrong direction, where do I go from here?

Any help is appreciated :)

Best Regards

答:
To pass a value when we use the OpenIdConnect protocol, we can add the value to the state as you mentioned.

We can pass this value before it redirect it to the identity data provider(Azure AD) using RedirectToIdentityProvider. After that we can extract the custom values we added using the MessageReceived when a protocol message is first received.

Here is the code sample for your reference:

```<code>new OpenIdConnectAuthenticationOptions
{
    // For each policy, give OWIN the policy-specific metadata address, and
    // set the authentication type to the id of the policy
    MetadataAddress = String.Format(aadInstance, tenant, policy),
    AuthenticationType = policy,

    // These are standard OpenID Connect parameters, with values pulled from web.config
    ClientId = clientId,
    RedirectUri = redirectUri,
    PostLogoutRedirectUri = redirectUri,
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        AuthenticationFailed = AuthenticationFailed,
        RedirectToIdentityProvider= OnRedirectToIdentityProvider,
        MessageReceived= OnMessageReceived
    },
    Scope = "openid",
    ResponseType = "id_token",

    // This piece is optional - it is used for displaying the user's name in the navigation bar.
    TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name",
    },
};

private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    var stateQueryString = notification.ProtocolMessage.State.Split('=');
    var protectedState = stateQueryString[1];
    var state = notification.Options.StateDataFormat.Unprotect(protectedState);
    state.Dictionary.Add("mycustomparameter", "myvalue");
    notification.ProtocolMessage.State = stateQueryString[0] + "=" + notification.Options.StateDataFormat.Protect(state);
    return Task.FromResult(0);
}

private Task OnMessageReceived(MessageReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    string mycustomparameter;
    var protectedState = notification.ProtocolMessage.State.Split('=')[1];
    var state = notification.Options.StateDataFormat.Unprotect(protectedState);
    state.Dictionary.TryGetValue("mycustomparameter", out mycustomparameter);
    return Task.FromResult(0);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently developing an application using AD-B2C as my identity provider. This is integrated into the solution using their guidelines at AD B2C graph, which uses openid-connect (to the best of my understanding at least).

I need to use a form of email activation (outside of their register policy) and as such I need to be able to pass a value from the URL in the email, through the sign-up process at B2C and back to the redirection URL.

I read somewhere that a parameter called "state" can be used for this:

State: A value included in the request that will also be returned in the token response. It can be a string of any content that you want. A randomly generated unique value is typically used for preventing cross-site request forgery attacks. The state is also used to encode information about the user's state in the app before the authentication request occurred, such as the page they were on or the policy being executed.

I have tried to append a value to the redirection that happens when transferring the user to the B2C, but I don't know how.

if (!Request.IsAuthenticated)
        { // go to login page
            HttpContext.GetOwinContext().Authentication.Challenge(
                  new AuthenticationProperties() { RedirectUri = "/" }, Startup.SignUpSignInPolicyId);
        }

The policy is stored in the startup.auth.cs file...

// B2C policy identifiers
    public static string SignUpPolicyId = ConfigurationManager.AppSettings["ida:SignUpPolicyId"];
    public static string SignInPolicyId = ConfigurationManager.AppSettings["ida:SignInPolicyId"];
    public static string SignUpSignInPolicyId = ConfigurationManager.AppSettings["ida:SignUpSignInPolicyId"];
    public static string ProfilePolicyId = ConfigurationManager.AppSettings["ida:UserProfilePolicyId"];
    public static string PasswordResetPolicyId = ConfigurationManager.AppSettings["ida:PasswordResetPolicyId"];

....and is run during the ConfigureAuth method:

public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            CookieHttpOnly = true,
            ExpireTimeSpan = TimeSpan.FromHours(1),
        });

        // Configure OpenID Connect middleware for each policy
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpPolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ProfilePolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpSignInPolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(PasswordResetPolicyId));
    }

which calls:

private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
    {
        return new OpenIdConnectAuthenticationOptions
        {
            // For each policy, give OWIN the policy-specific metadata address, and
            // set the authentication type to the id of the policy
            MetadataAddress = String.Format(aadInstance, tenant, policy),
            AuthenticationType = policy,

            // These are standard OpenID Connect parameters, with values pulled from web.config
            ClientId = clientId,
            RedirectUri = redirectUri,
            PostLogoutRedirectUri = redirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = AuthenticationFailed,
            },
            Scope = "openid",
            ResponseType = "id_token",
            //// This piece is optional - it is used for displaying the user's name in the navigation bar.
            //TokenValidationParameters = new TokenValidationParameters
            //{
            //    NameClaimType = "name",
            //},
        };

    }

How do I pass a value like: (simplified example:)

if (!Request.IsAuthenticated)
        { // go to login page
            HttpContext.GetOwinContext().Authentication.Challenge(
                  new AuthenticationProperties() { RedirectUri = "/" }, Startup.SignUpSignInPolicyId, new { state = "value=uniquetoken&token=secrets" });
        }

When these methods and policies are set on runtime ?
Furthermore if I am heading in a completely wrong direction, where do I go from here?

Any help is appreciated :)

Best Regards

Body:
To pass a value when we use the OpenIdConnect protocol, we can add the value to the state as you mentioned.

We can pass this value before it redirect it to the identity data provider(Azure AD) using RedirectToIdentityProvider. After that we can extract the custom values we added using the MessageReceived when a protocol message is first received.

Here is the code sample for your reference:

new OpenIdConnectAuthenticationOptions
{
    // For each policy, give OWIN the policy-specific metadata address, and
    // set the authentication type to the id of the policy
    MetadataAddress = String.Format(aadInstance, tenant, policy),
    AuthenticationType = policy,

    // These are standard OpenID Connect parameters, with values pulled from web.config
    ClientId = clientId,
    RedirectUri = redirectUri,
    PostLogoutRedirectUri = redirectUri,
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        AuthenticationFailed = AuthenticationFailed,
        RedirectToIdentityProvider= OnRedirectToIdentityProvider,
        MessageReceived= OnMessageReceived
    },
    Scope = "openid",
    ResponseType = "id_token",

    // This piece is optional - it is used for displaying the user's name in the navigation bar.
    TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name",
    },
};

private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    var stateQueryString = notification.ProtocolMessage.State.Split('=');
    var protectedState = stateQueryString[1];
    var state = notification.Options.StateDataFormat.Unprotect(protectedState);
    state.Dictionary.Add("mycustomparameter", "myvalue");
    notification.ProtocolMessage.State = stateQueryString[0] + "=" + notification.Options.StateDataFormat.Protect(state);
    return Task.FromResult(0);
}

private Task OnMessageReceived(MessageReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    string mycustomparameter;
    var protectedState = notification.ProtocolMessage.State.Split('=')[1];
    var state = notification.Options.StateDataFormat.Unprotect(protectedState);
    state.Dictionary.TryGetValue("mycustomparameter", out mycustomparameter);
    return Task.FromResult(0);
}


问:
Using UnityEventTools.RemovePersistentListener
I am creating an editor script that creates UI buttons and add listeners with arguments. I have completed that. Now, I want to remove the listeners with code.

The unity documentation for this isn't much help.

Code:

```<code>GameObject my_UIPanel;

// Destroy panel and buttons that were created previously.

my_UIPanel = GameObject.Find ("Panel_RoomButtons");
Button[] myBtns = my_UIPanel.GetComponentsInChildren<Button> ();
foreach (Button myBtn in myBtns)
{
    // This is the thing giving me a headache. Rest everything works fine.
    UnityEventTools.RemovePersistentListener(myBtn.onClick, myUIManager.DEV_myFunction);
}
if (my_UIPanel != null)
    DestroyImmediate (my_UIPanel);

// Create new panel and buttons.

my_UIPanel = Instantiate(Pnl_RoomBtnsPrefab) as GameObject;

foreach (GameObject emptyLocation in teleLocations)
{
    GameObject myBtnGO = Instantiate (teleBtnPrefab) as GameObject;
    myBtnGO.name = emptyLocation.name + "Btn";
    myBtnGO.transform.SetParent (my_UIPanel.transform, false);
    GameObject currentGO = emptyLocation;
    Button myBtn = myBtnGO.GetComponent <Button> ();
    UnityEventTools.AddObjectPersistentListener(myBtn.onClick, myUIManager.DEV_myFunction, currentGO);
}
</code>```

If you can help me solve this, I'd be grateful for your help.

Thanks!

EDIT: These are the errors I'm getting

Assets/Scripts/RIGScripts/Editor/WorkspaceSetupEditor.cs(247,65): error CS1502: The best overloaded method match for `UnityEditor.Events.UnityEventTools.RemovePersistentListener(UnityEngine.Events.UnityEventBase, int)' has some invalid arguments

Assets/Scripts/RIGScripts/Editor/WorkspaceSetupEditor.cs(247,65): error CS1503: Argument #2' cannot convertmethod group' expression to type `int'

in this line:

```<code>UnityEventTools.RemovePersistentListener(myBtn.onClick, myUIManager.DEV_myFunction);
</code>```

答:
I was having the same problem.

Try this:

```<code>UnityEventTools.RemovePersistentListener<TYPE_OF_PARAMETER>(myBtn.onClick, myUIManager.DEV_myFunction);
</code>```

This was the solution in my case :)

Body:
I am creating an editor script that creates UI buttons and add listeners with arguments. I have completed that. Now, I want to remove the listeners with code.

The unity documentation for this isn't much help.

Code:

GameObject my_UIPanel;

// Destroy panel and buttons that were created previously.

my_UIPanel = GameObject.Find ("Panel_RoomButtons");
Button[] myBtns = my_UIPanel.GetComponentsInChildren<Button> ();
foreach (Button myBtn in myBtns)
{
    // This is the thing giving me a headache. Rest everything works fine.
    UnityEventTools.RemovePersistentListener(myBtn.onClick, myUIManager.DEV_myFunction);
}
if (my_UIPanel != null)
    DestroyImmediate (my_UIPanel);

// Create new panel and buttons.

my_UIPanel = Instantiate(Pnl_RoomBtnsPrefab) as GameObject;

foreach (GameObject emptyLocation in teleLocations)
{
    GameObject myBtnGO = Instantiate (teleBtnPrefab) as GameObject;
    myBtnGO.name = emptyLocation.name + "Btn";
    myBtnGO.transform.SetParent (my_UIPanel.transform, false);
    GameObject currentGO = emptyLocation;
    Button myBtn = myBtnGO.GetComponent <Button> ();
    UnityEventTools.AddObjectPersistentListener(myBtn.onClick, myUIManager.DEV_myFunction, currentGO);
}

If you can help me solve this, I'd be grateful for your help.

Thanks!

EDIT: These are the errors I'm getting

Assets/Scripts/RIGScripts/Editor/WorkspaceSetupEditor.cs(247,65): error CS1502: The best overloaded method match for `UnityEditor.Events.UnityEventTools.RemovePersistentListener(UnityEngine.Events.UnityEventBase, int)' has some invalid arguments

Assets/Scripts/RIGScripts/Editor/WorkspaceSetupEditor.cs(247,65): error CS1503: Argument #2' cannot convertmethod group' expression to type `int'

in this line:

UnityEventTools.RemovePersistentListener(myBtn.onClick, myUIManager.DEV_myFunction);

Body:
I was having the same problem.

Try this:

UnityEventTools.RemovePersistentListener<TYPE_OF_PARAMETER>(myBtn.onClick, myUIManager.DEV_myFunction);

This was the solution in my case :)


问:
Changing an image on hover but only if hovered for a set period of time (jQuery)
I'm trying to change an image, but ony if hovered for a set period of time. I've tried using delay(), which kinda works, but the problem is that the hover animation is still triggered, after the mouse has been moved off the element.

Here's my code

```<code>$('.pack-list li').hover(function() {

  $(this).find('.pack-icon img').delay(1000).animate({
    width: 0,
    height: 0
  }, 100, function() {
    // Animation complete.
    $(this).attr('src','images/download-icon.png');

    $(this).animate({
      width: 30 + "px",
      height: 36 + "px"
    }, 100, function() {
      // Animation complete.
    });
  });

}, function() {
  $(this).find('.pack-icon img').attr('src','images/pack-icon.png');
});
</code>```

答:
1: Define a variable for a timer.

2: Define a time.

3: Clear timeout on leave.

```<code>var timer;
var delai = 500; // milliseconds

$('.pack-list li').hover(in, out);

function in(){    // Set timeout on enter

  timer = setTimout(function(){
    $(this).find('.pack-icon img').delay(1000).animate({
        width: 0,
        height: 0
      }, 100,

      // animate callback
      function() {
        // Animation complete.
        $(this).attr('src','images/download-icon.png');

        $(this).animate({
          width: 30 + "px",
          height: 36 + "px"
        }, 100, function() {
          // Animation complete.
        });
      });
  },delai);
}

function out() {    // Clear timout on leave
  $(this).find('.pack-icon img').attr('src','images/pack-icon.png');
  clearTimeout(timer);
}
</code>```

Body:
I'm trying to change an image, but ony if hovered for a set period of time. I've tried using delay(), which kinda works, but the problem is that the hover animation is still triggered, after the mouse has been moved off the element.

Here's my code

$('.pack-list li').hover(function() {

  $(this).find('.pack-icon img').delay(1000).animate({
    width: 0,
    height: 0
  }, 100, function() {
    // Animation complete.
    $(this).attr('src','images/download-icon.png');

    $(this).animate({
      width: 30 + "px",
      height: 36 + "px"
    }, 100, function() {
      // Animation complete.
    });
  });

}, function() {
  $(this).find('.pack-icon img').attr('src','images/pack-icon.png');
});

Body:
1: Define a variable for a timer.

2: Define a time.

3: Clear timeout on leave.

var timer;
var delai = 500; // milliseconds

$('.pack-list li').hover(in, out);

function in(){    // Set timeout on enter

  timer = setTimout(function(){
    $(this).find('.pack-icon img').delay(1000).animate({
        width: 0,
        height: 0
      }, 100,

      // animate callback
      function() {
        // Animation complete.
        $(this).attr('src','images/download-icon.png');

        $(this).animate({
          width: 30 + "px",
          height: 36 + "px"
        }, 100, function() {
          // Animation complete.
        });
      });
  },delai);
}

function out() {    // Clear timout on leave
  $(this).find('.pack-icon img').attr('src','images/pack-icon.png');
  clearTimeout(timer);
}


问:
ORA-03113: end-of-file on communication channel after ~ 2 hours and 10 mins
I have a sql script with a procedure. I run it using
sqlplus -s @script.sql logfile.log myparam1 myparam2

But after ~ 2 hour and 10 mins, my script ends with

```<code>ERROR:
ORA-03114: not connected to ORACLE

DECLARE
*
ERROR at line 1:
ORA-03113: end-of-file on communication channel
Process ID: 12345
Session ID: 33 Serial number: 54321
</code>```

I have following tcp settings

```<code>-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_time (which is two hours)
7200
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_intvl
75
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_probes
9
</code>```

When the script was running, I checked that TCP connection was established at my end , but on the database side (database server machine) there was no such connection.

My theory is that somehow database server is dropping the connection. And when my system sends first keepalive probe after 2 hours (7200 seconds), it finds that connection is no more active and closes the connection and script returns.

I am unable to understand why would a database system drop a connection?
Are there any settings at database end to increase verbosity? Or could this be related to some firewall settings? Also, in 2 hours and 10 mins, we can guess that 2 hours portion is coming from tcp_keepalive_time, what would be 10 mins portion. Any database side retries?

EDIT: DBA and I looked at the issue, I see the TCP connection as ESTABLISHED at my end and he didn't see any connection coming from my side.

答:
end-of-file on communication channel is rarely a DB side problem.
If you suspect DB side problem, then monitor the session activity via gv$session.  You will be able to find out right away if the session is "hung" or long-running on a particular statement.  It is not uncommon to loose a connection to the DB, especially if the network is not real stable.</p>

Body:
I have a sql script with a procedure. I run it using
sqlplus -s @script.sql logfile.log myparam1 myparam2

But after ~ 2 hour and 10 mins, my script ends with

ERROR:
ORA-03114: not connected to ORACLE

DECLARE
*
ERROR at line 1:
ORA-03113: end-of-file on communication channel
Process ID: 12345
Session ID: 33 Serial number: 54321

I have following tcp settings

-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_time (which is two hours)
7200
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_intvl
75
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_probes
9

When the script was running, I checked that TCP connection was established at my end , but on the database side (database server machine) there was no such connection.

My theory is that somehow database server is dropping the connection. And when my system sends first keepalive probe after 2 hours (7200 seconds), it finds that connection is no more active and closes the connection and script returns.

I am unable to understand why would a database system drop a connection?
Are there any settings at database end to increase verbosity? Or could this be related to some firewall settings? Also, in 2 hours and 10 mins, we can guess that 2 hours portion is coming from tcp_keepalive_time, what would be 10 mins portion. Any database side retries?

EDIT: DBA and I looked at the issue, I see the TCP connection as ESTABLISHED at my end and he didn't see any connection coming from my side.


问:
How to create a method that takes any object and returns a name:value pair for all properties?
For example I have a simple class like

```<code>public class Person{
    public int Age {get;set;}
    public string Name {get;set;}
}
</code>```

I need to make a method that takes any class and spits out values of properties set in the  object as a string in format "Age:35;Name:John Doe;"

I am looking for a method signature on the lines of

```<code>public string SpitNameValuePairs<T>()
</code>```

or something like it. How can this be done efficiently if using reflection?

答:
That have protection from crashes when property have an indexer defined and also it output only instance properties (no static).</p>

```<code>    private static string SplitNameValuePairs<T>(T value)
    {
        StringBuilder sb = new StringBuilder();

        foreach (PropertyInfo property in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
        {
            if (property.GetIndexParameters().Length == 0)
                sb.AppendFormat("{0}:{1};", property.Name, property.GetValue(value, null));
        }
        return sb.ToString();
    }
</code>```

OwnerDisplayName: Perpetualcoder

ContentLicense: CC BY-SA 2.5

Body:
For example I have a simple class like

public class Person{
    public int Age {get;set;}
    public string Name {get;set;}
}

I need to make a method that takes any class and spits out values of properties set in the  object as a string in format "Age:35;Name:John Doe;"

I am looking for a method signature on the lines of

public string SpitNameValuePairs<T>()

or something like it. How can this be done efficiently if using reflection?

LastEditorDisplayName: Perpetualcoder

Body:
That have protection from crashes when property have an indexer defined and also it output only instance properties (no static).

    private static string SplitNameValuePairs<T>(T value)
    {
        StringBuilder sb = new StringBuilder();

        foreach (PropertyInfo property in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
        {
            if (property.GetIndexParameters().Length == 0)
                sb.AppendFormat("{0}:{1};", property.Name, property.GetValue(value, null));
        }
        return sb.ToString();
    }

OwnerDisplayName: Dmitriy Matveev


问:
Improve switch statement in PHP or suggest an alternative workaround
I am trying to improve the below switch statement. What's happening here is that the code is called multiple times based on an x amount of tokens found, so the below code runs once per token.

If the $post->ID is not found then a notification is sent to that token and the id gets added in the database.

This works however at some point it's stopping after around 40% of tokens checked presumably because the ID is found? Since I am on wordpress, I used the update_option to store the id in a table but perhaps an alternative approach can be used?

```<code>$os = $this->os;
switch ($os) {

    case "iOS":
        $iOS_pastPushSavedID = get_option( 'iOS_pastPushSavedID',  $default = false);
        if($post->ID != $iOS_pastPushSavedID) {
            update_option( 'iOS_pastPushSavedID', $post->ID, no);
            $sendPush = true;
            //$title = ($os . '_New Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Android":
        $android_pastPushSavedID = get_option( 'android_pastPushSavedID',  $default = false);
        if($post->ID != $android_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $android_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'android_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $android_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Fire OS":
        $fireos_pastPushSavedID = get_option( 'fireos_pastPushSavedID',  $default = false);
        if($post->ID != $fireos_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $fireos_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'fireos_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $fireos_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Safari":
        $safari_pastPushSavedID = get_option( 'safari_pastPushSavedID',  $default = false);
        if($post->ID != $safari_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $safari_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'safari_pastPushSavedID', $post->ID, no);
            $sendPush = true;

        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $safari_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Chrome":
        $chrome_pastPushSavedID = get_option( 'chrome_pastPushSavedID',  $default = false);
        if($post->ID != $chrome_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $chrome_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'chrome_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $chrome_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Firefox":
        $firefox_pastPushSavedID = get_option( 'firefox_pastPushSavedID',  $default = false);
        if($post->ID != $firefox_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $firefox_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'firefox_pastPushSavedID', $post->ID, no);
            $sendPush = true;

        } else {
        //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $firefox_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    default:
        $sendPush = false;
}
</code>```

答:
Unless I am misunderstanding your process, this is a very DRY / concise way to do it without the verbose switch/case block:

```<code>$os_opts=[
    'iOS'=>'iOS',
    'Android'=>'android',
    'Fire OS'=>'fireos',
    'Safari'=>'safari',
    'Chrome'=>'chrome',
    'Firefox'=>'firefox'
];

$os=$this->os;
$sendPush=false;
if(isset($os_opts[$os])){                           // deny empty and invalid options
    $os_opt="{$os_opts[$os]}_pastPushSavedID";     // build string for next two functions
    if($post->ID!=get_option($os_opt,$default=false)){
        update_option($os_opt,$post->ID,no);
        $sendPush = true;
    }
}
</code>```

The $os_opts array has keys that match $os, and values that work with get_option() & update_option().  This will largely reduce code length, and make future modifications very easy to do.

Since the get_option() result is only used once, it doesn't make sense to declare it as a variable; just use it in the if condition.

The first parameter of get_option() and update_option() always end with the same substring.  I makes sense to prepend the $os_opts[$os] value to it and declare it as a variable.  The variable declaration is not necessary but my personal rule is; if you are going to use data more than once use a variable, if only once don't declare it.

Body:
I am trying to improve the below switch statement. What's happening here is that the code is called multiple times based on an x amount of tokens found, so the below code runs once per token.

If the $post->ID is not found then a notification is sent to that token and the id gets added in the database.

This works however at some point it's stopping after around 40% of tokens checked presumably because the ID is found? Since I am on wordpress, I used the update_option to store the id in a table but perhaps an alternative approach can be used?

$os = $this->os;
switch ($os) {

    case "iOS":
        $iOS_pastPushSavedID = get_option( 'iOS_pastPushSavedID',  $default = false);
        if($post->ID != $iOS_pastPushSavedID) {
            update_option( 'iOS_pastPushSavedID', $post->ID, no);
            $sendPush = true;
            //$title = ($os . '_New Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Android":
        $android_pastPushSavedID = get_option( 'android_pastPushSavedID',  $default = false);
        if($post->ID != $android_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $android_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'android_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $android_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Fire OS":
        $fireos_pastPushSavedID = get_option( 'fireos_pastPushSavedID',  $default = false);
        if($post->ID != $fireos_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $fireos_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'fireos_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $fireos_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Safari":
        $safari_pastPushSavedID = get_option( 'safari_pastPushSavedID',  $default = false);
        if($post->ID != $safari_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $safari_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'safari_pastPushSavedID', $post->ID, no);
            $sendPush = true;

        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $safari_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Chrome":
        $chrome_pastPushSavedID = get_option( 'chrome_pastPushSavedID',  $default = false);
        if($post->ID != $chrome_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $chrome_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'chrome_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $chrome_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Firefox":
        $firefox_pastPushSavedID = get_option( 'firefox_pastPushSavedID',  $default = false);
        if($post->ID != $firefox_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $firefox_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'firefox_pastPushSavedID', $post->ID, no);
            $sendPush = true;

        } else {
        //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $firefox_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    default:
        $sendPush = false;
}

Body:
Unless I am misunderstanding your process, this is a very DRY / concise way to do it without the verbose switch/case block:

$os_opts=[
    'iOS'=>'iOS',
    'Android'=>'android',
    'Fire OS'=>'fireos',
    'Safari'=>'safari',
    'Chrome'=>'chrome',
    'Firefox'=>'firefox'
];

$os=$this->os;
$sendPush=false;
if(isset($os_opts[$os])){                           // deny empty and invalid options
    $os_opt="{$os_opts[$os]}_pastPushSavedID";     // build string for next two functions
    if($post->ID!=get_option($os_opt,$default=false)){
        update_option($os_opt,$post->ID,no);
        $sendPush = true;
    }
}

The $os_opts array has keys that match $os, and values that work with get_option() & update_option().  This will largely reduce code length, and make future modifications very easy to do.

Since the get_option() result is only used once, it doesn't make sense to declare it as a variable; just use it in the if condition.

The first parameter of get_option() and update_option() always end with the same substring.  I makes sense to prepend the $os_opts[$os] value to it and declare it as a variable.  The variable declaration is not necessary but my personal rule is; if you are going to use data more than once use a variable, if only once don't declare it.


问:
did you forget to inherit a required module?
I know there is already a lot of topic about this issue (did you forget to inherit a required module?) but my problem is a little bit special.
    Let me explain it:
    I have an existing package that contains my models classes(the name of the package is model). All my models were located into that package. But I made a change in my application and now part of the models that I am using in my application is now pulled from another application named "MyAppModel". I have added the dependency to this MyAppModel application in my pom.xml file. I have no compilation error (mvn compile is successful) but when I do maven install: I have the following error:
    [ERROR] Line 130: No source code is available for type com.data.service.models.Product; did you forget to inherit a required module?
    [INFO]          [ERROR] Line 588: No source code is available for type com.data.service.models.Order; did you forget to inherit a required module?

```<code>These 2 models:com.data.service.models.Order.java and com.data.service.models.Product.java are from the MyAppModel application but I am not authorized to add them manually to the existing model package of my application.
It seems like it can not find those 2 models Product and Order.

Here is the content of my gwt.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<module>
  <inherits name='com.google.gwt.user.User'/>
  <source path='model'/>
</module>
The source path is only pointing to he existing model package. My question is: how can I do to modify this gwt.xml file to take into account both models packages(the model package of the existing application and also the model package of the external application "MyAppModel")
</code>```

I need to keep my existing source path='model' and should add an access to my external models in my MyAppModel application

```<code>Thank you very much for your help
</code>```

答: In case of GWT, sometimes we see this error if we refer server side classes in client side code.</p>

Body:
I know there is already a lot of topic about this issue (did you forget to inherit a required module?) but my problem is a little bit special.
    Let me explain it:
    I have an existing package that contains my models classes(the name of the package is model). All my models were located into that package. But I made a change in my application and now part of the models that I am using in my application is now pulled from another application named "MyAppModel". I have added the dependency to this MyAppModel application in my pom.xml file. I have no compilation error (mvn compile is successful) but when I do maven install: I have the following error:
    [ERROR] Line 130: No source code is available for type com.data.service.models.Product; did you forget to inherit a required module?
    [INFO]          [ERROR] Line 588: No source code is available for type com.data.service.models.Order; did you forget to inherit a required module?

These 2 models:com.data.service.models.Order.java and com.data.service.models.Product.java are from the MyAppModel application but I am not authorized to add them manually to the existing model package of my application.
It seems like it can not find those 2 models Product and Order.

Here is the content of my gwt.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<module>
  <inherits name='com.google.gwt.user.User'/>
  <source path='model'/>
</module>
The source path is only pointing to he existing model package. My question is: how can I do to modify this gwt.xml file to take into account both models packages(the model package of the existing application and also the model package of the external application "MyAppModel")

I need to keep my existing source path='model' and should add an access to my external models in my MyAppModel application

Thank you very much for your help


问:
Angular 2 router error
I created Angular 2 router module but it doen't work at the moment and I get an error when I want to open link /city 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
Error: Cannot activate an already activated outlet'

But I can open this link manually

Here is the code of:
Router module

```<code>import { NgModule }from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {WeatherListComponent} from "../weather-list/weather-list.component";
import {AddedCityComponent} from "../added-city/added-city.component";
import {AppComponent} from "../app.component";

const routes: Routes = [
    { path: '', redirectTo: '/weather-list', pathMatch: 'full'},
    { path: 'city', component: AddedCityComponent },
    { path: 'weather-list',  component: WeatherListComponent }

];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}
</code>```

2) Appmodule

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdButtonModule, MdCheckboxModule, MdCardModule, MdInputModule} from '@angular/material';

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { AppComponent } from './app.component';
import { WeatherListComponent } from './weather-list/weather-list.component';

import { WeatherService } from './service/weather.service';
import { WeatherSearchComponent } from './weather-search/weather-search.component';
import { CloudsComponent } from './clouds/clouds.component';
import { SunComponent } from './sun/sun.component';
import { RainComponent } from './rain/rain.component';
import { AddedCityComponent } from './added-city/added-city.component';

import { AppRoutingModule } from './service/app.routing';

@NgModule({
  declarations: [
    AppComponent,
    WeatherListComponent,
    AddedCityComponent,
    WeatherSearchComponent,
    CloudsComponent,
    SunComponent,
    RainComponent

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    MdButtonModule,
    MdCardModule,
    MdInputModule,
    NgbModule.forRoot(),
    AppRoutingModule

  ],
  providers: [
    WeatherService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

3) AppComponentHTML

```<code><div class="page-wrapper" [ngClass]="{
                                    'sun-background': weatherDesc == 'Clear',
                                    'rain-background': weatherDesc == 'Rain',
                                    'clouds-background': weatherDesc == 'Clouds'
                                      }">
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-12">
        <header>
          <div class="header-wrapper">
            <h3 class=" text-left">Weather App</h3>
            <a routerLink="/city" routerLinkActive="active">cities</a>
            <a routerLink="/weather-list" routerLinkActive="active">weather</a>
            <app-weather-search></app-weather-search>
          </div>
        </header>
      </div>
    </div>
  </div>
  <!--<app-weather-list (notify)="background($event)"></app-weather-list>-->
  <!--<app-weather-list></app-weather-list>-->
  <router-outlet></router-outlet>

</div>
</code>```

答:
i see that you don't have router-outlet in your App component. Try to copy this code in your app.component.html :

```<code><router-outlet></router-outlet>
</code>```

then try to enter to open links.

Title: Angular 2 router error

Body:
I created Angular 2 router module but it doen't work at the moment and I get an error when I want to open link /city 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
Error: Cannot activate an already activated outlet'

But I can open this link manually

Here is the code of:
Router module

import { NgModule }from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {WeatherListComponent} from "../weather-list/weather-list.component";
import {AddedCityComponent} from "../added-city/added-city.component";
import {AppComponent} from "../app.component";

const routes: Routes = [
    { path: '', redirectTo: '/weather-list', pathMatch: 'full'},
    { path: 'city', component: AddedCityComponent },
    { path: 'weather-list',  component: WeatherListComponent }

];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}

2) Appmodule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdButtonModule, MdCheckboxModule, MdCardModule, MdInputModule} from '@angular/material';

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { AppComponent } from './app.component';
import { WeatherListComponent } from './weather-list/weather-list.component';

import { WeatherService } from './service/weather.service';
import { WeatherSearchComponent } from './weather-search/weather-search.component';
import { CloudsComponent } from './clouds/clouds.component';
import { SunComponent } from './sun/sun.component';
import { RainComponent } from './rain/rain.component';
import { AddedCityComponent } from './added-city/added-city.component';

import { AppRoutingModule } from './service/app.routing';

@NgModule({
  declarations: [
    AppComponent,
    WeatherListComponent,
    AddedCityComponent,
    WeatherSearchComponent,
    CloudsComponent,
    SunComponent,
    RainComponent

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    MdButtonModule,
    MdCardModule,
    MdInputModule,
    NgbModule.forRoot(),
    AppRoutingModule

  ],
  providers: [
    WeatherService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

3) AppComponentHTML

Weather App

            cities
            weather
            <app-weather-search></app-weather-search>

  <router-outlet></router-outlet>

Body:
i see that you don't have router-outlet in your App component. Try to copy this code in your app.component.html :

<router-outlet></router-outlet>

then try to enter to open links.


问:
Cannot integrate Alamofire on Jenkins
I'm trying to perform CI on a Swift project that has Alamofire integrated into it (as a pod). However, I'm getting the following errors when built on the Jenkins server:

```<code>The following build commands failed:
CompileSwift normal arm64 /Users/tsd007/.jenkins/jobs/HelloWorldIOS/workspace/Pods/Alamofire/Source/Alamofire.swift
CompileSwift normal arm64 /Users/tsd007/.jenkins/jobs/HelloWorldIOS/workspace/Pods/Alamofire/Source/Download.swift
CompileSwift normal arm64 /Users/tsd007/.jenkins/jobs/HelloWorldIOS/workspace/Pods/Alamofire/Source/Error.swift
CompileSwift normal arm64 /Users/tsd007/.jenkins/jobs/HelloWorldIOS/workspace/Pods/Alamofire/Source/Manager.swift
CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler
</code>```

However when I built it locally in the IDE (XCode), everything is fine. Anybody got this issue before? Any help would be appreciated.

答:
This seems to be a well-documented issue. One very close example has been closed due to the issue seemingly being fixed as of Xcode (6.2).

It appears this newer version of Xcode (or any version thereafter) should allow your code to be built from the command line and/or from Jenkins because of differences in what Xcode produces.

Title: Cannot integrate Alamofire on Jenkins

Body:
I'm trying to perform CI on a Swift project that has Alamofire integrated into it (as a pod). However, I'm getting the following errors when built on the Jenkins server:

The following build commands failed:
CompileSwift normal arm64 /Users/tsd007/.jenkins/jobs/HelloWorldIOS/workspace/Pods/Alamofire/Source/Alamofire.swift
CompileSwift normal arm64 /Users/tsd007/.jenkins/jobs/HelloWorldIOS/workspace/Pods/Alamofire/Source/Download.swift
CompileSwift normal arm64 /Users/tsd007/.jenkins/jobs/HelloWorldIOS/workspace/Pods/Alamofire/Source/Error.swift
CompileSwift normal arm64 /Users/tsd007/.jenkins/jobs/HelloWorldIOS/workspace/Pods/Alamofire/Source/Manager.swift
CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler

However when I built it locally in the IDE (XCode), everything is fine. Anybody got this issue before? Any help would be appreciated.


问:
Andorid Studio: ExecutionException : (integer) -1 is less than minimum integer 0
I updated to Android Studio 3 Canary build 2, which bumped up my build tools like so:

```<code>classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
</code>```

Now when I try to build I get this issue:

```<code>Error:.../values.xml:3490 (integer) -1 is less than minimum integer 0
Error:java.util.concurrent.ExecutionException:
com.android.builder.internal.aapt.AaptException: AAPT2 link failed:
Error:com.android.builder.internal.aapt.AaptException: AAPT2 link failed:
Error:Execution failed for task ':app:processStagingResources'.
Failed to execute aapt
</code>```

So I took a look at line 3490 of the file referenced above and got this:

```<code><item name="android:numColumns">auto_fit</item>
</code>```

Because it references I GridView style, I went to the docs and found that AUTO_FIT has a value of -1

I'm not sure why I'm getting this issue but I've tried cleaning/building, restarting and I still get that issue. Any idea what to try?

答:
You can disable AAPT2 by putting this in your gradle.properties file:

```<code>android.enableAapt2=false
</code>```

Body:
I updated to Android Studio 3 Canary build 2, which bumped up my build tools like so:

classpath 'com.android.tools.build:gradle:3.0.0-alpha2'

Now when I try to build I get this issue:

Error:.../values.xml:3490 (integer) -1 is less than minimum integer 0
Error:java.util.concurrent.ExecutionException:
com.android.builder.internal.aapt.AaptException: AAPT2 link failed:
Error:com.android.builder.internal.aapt.AaptException: AAPT2 link failed:
Error:Execution failed for task ':app:processStagingResources'.
Failed to execute aapt

So I took a look at line 3490 of the file referenced above and got this:

<item name="android:numColumns">auto_fit</item>

Because it references I GridView style, I went to the docs and found that AUTO_FIT has a value of -1

I'm not sure why I'm getting this issue but I've tried cleaning/building, restarting and I still get that issue. Any idea what to try?

Body:
You can disable AAPT2 by putting this in your gradle.properties file:

android.enableAapt2=false


问:
Beautiful Soup: Parsing between commas in unicode list into Pandas Dataframe
I scraping a list of names and dates. I can get the data into a unicode LIST,
then im pretty much having trouble with everything else.

A sample output of my soup object:

```<code>LAST,FIRST,ID,DEBUT
Aardsma,David,aardd001,04/06/2004
Aaron,Hank,aaroh101,04/13/1954
Aaron,Tommie,aarot101,04/10/1962
</code>```

First I want to strip the first line: 'LAST,FIRST,ID,DEBUT',but pop(0) doesnt work on a unicode list.

Next I want to parse the names, etc into 4 columns and put it into a pandas dataframe.

Here is my latest code that needs a lot of work:

```<code>import urllib2
import csv
import pandas as pd
from bs4 import BeautifulSoup

Cols=['Last','First','ID','Debut']
sock= urllib2.urlopen('http://www.retrosheet.org/retroID.htm')
link=sock.read()
soup = BeautifulSoup(link,'lxml')

list=soup.find_all('pre')
for td in list:
    IDList=td.get_text()

df=pd.DataFrame(IDList,columns=Cols) # giving error so far
print(df)
#IDList=IDList.split(",")
</code>```

答:
Your data is already csv formatted so all you need to do is dump into a StringIO and have pandas read it.

I don't have python3 around to verify and StringIO has changed between python 2 and python 3-- so playing the StringIO piece by memory a bit.  But off the top of my head I believe this would work in either.

```<code>import urllib2
import csv
import pandas as pd
from bs4 import BeautifulSoup
try:
    from StringIO import StringIO
except:
    from io import StringIO

Cols=['Last','First','ID','Debut']
sock= urllib2.urlopen('http://www.retrosheet.org/retroID.htm')
link=sock.read()
soup = BeautifulSoup(link,'lxml')

csv_data = StringIO(soup.find('pre').text)
df = pd.read_csv(csv_data)
print(df)
</code>```

Body:
I scraping a list of names and dates. I can get the data into a unicode LIST,
then im pretty much having trouble with everything else.

A sample output of my soup object:

LAST,FIRST,ID,DEBUT
Aardsma,David,aardd001,04/06/2004
Aaron,Hank,aaroh101,04/13/1954
Aaron,Tommie,aarot101,04/10/1962

First I want to strip the first line: 'LAST,FIRST,ID,DEBUT',but pop(0) doesnt work on a unicode list.

Next I want to parse the names, etc into 4 columns and put it into a pandas dataframe.

Here is my latest code that needs a lot of work:

import urllib2
import csv
import pandas as pd
from bs4 import BeautifulSoup

Cols=['Last','First','ID','Debut']
sock= urllib2.urlopen('http://www.retrosheet.org/retroID.htm')
link=sock.read()
soup = BeautifulSoup(link,'lxml')

list=soup.find_all('pre')
for td in list:
    IDList=td.get_text()

df=pd.DataFrame(IDList,columns=Cols) # giving error so far
print(df)
#IDList=IDList.split(",")

Body:
Your data is already csv formatted so all you need to do is dump into a StringIO and have pandas read it.

I don't have python3 around to verify and StringIO has changed between python 2 and python 3-- so playing the StringIO piece by memory a bit.  But off the top of my head I believe this would work in either.

import urllib2
import csv
import pandas as pd
from bs4 import BeautifulSoup
try:
    from StringIO import StringIO
except:
    from io import StringIO

Cols=['Last','First','ID','Debut']
sock= urllib2.urlopen('http://www.retrosheet.org/retroID.htm')
link=sock.read()
soup = BeautifulSoup(link,'lxml')

csv_data = StringIO(soup.find('pre').text)
df = pd.read_csv(csv_data)
print(df)


问:
How can i write SQL update query with where clause in Entity Framework in C#
I know that for update a model in EF i must get model then change it then dbContext.SaveChanges()
but sometimes in my Asp.net mvc project , i want update a field in my table and i don't know it 's id  and must be get it with where clause.
but i don't want connect twice to database , because in ADO.net i can write:

```<code>UPDATE MyTable SET Field3 = "NewValue" WHERE Active = 1
</code>```

and now i want write a linq to sql for EF that work like that.
Is exist any way for that?
thanks

答:
You can't.
EF is ORM, that means, you need to work with separate objects (update them one by one).

Look at EntityFramework.Extended library for that:

```<code>//update all tasks with status of 1 to status of 2
context.Tasks
    .Where(t => t.StatusId == 1)
    .Update(t => new Task { StatusId = 2 });
</code>```

For EF Core: EntityFramework-Plus

Body:
I know that for update a model in EF i must get model then change it then dbContext.SaveChanges()
but sometimes in my Asp.net mvc project , i want update a field in my table and i don't know it 's id  and must be get it with where clause.
but i don't want connect twice to database , because in ADO.net i can write:

UPDATE MyTable SET Field3 = "NewValue" WHERE Active = 1

and now i want write a linq to sql for EF that work like that.
Is exist any way for that?
thanks

Body:
You can't.
EF is ORM, that means, you need to work with separate objects (update them one by one).

Look at EntityFramework.Extended library for that:

//update all tasks with status of 1 to status of 2
context.Tasks
    .Where(t => t.StatusId == 1)
    .Update(t => new Task { StatusId = 2 });

For EF Core: EntityFramework-Plus

ContentLicense: CC BY-SA 4.0


问:
When the dereference operator (*) is overloaded, is the usage of *this affected?
For example,

```<code>class Person{
        string name;
    public:
        T& operator*(){
            return name;
        }
        bool operator==(const Person &rhs){
            return this->name == rhs.name;
        }
        bool operator!=(const Person &rhs){
            return !(*this == rhs); // Will *this be the string name or the Person?
        }
}
</code>```

If *this ends up dereferencing this to a string instead of a Person, is there a workaround that maintains the usage of * as a dereference operator outside the class?

It would be quite a hindrance if I couldn't overload * without giving up usage of *this.

答:
If *this ends up dereferencing this to a string instead of a Person, is there a workaround that maintains the usage of * as a dereference operator outside the class?

No. *this will be Person& or Person const& depending on the function. The overload applies to Person objects, not pointers to Person objects. this is a pointer to a Person object.

If you use:

```<code> Person p;
 auto v = *p;
</code>```

Then, the operator* overload is called.

To call the operator* overload using this, you'll have to use this->operator*() or **this.

Body:
For example,

class Person{
        string name;
    public:
        T& operator*(){
            return name;
        }
        bool operator==(const Person &rhs){
            return this->name == rhs.name;
        }
        bool operator!=(const Person &rhs){
            return !(*this == rhs); // Will *this be the string name or the Person?
        }
}

If *this ends up dereferencing this to a string instead of a Person, is there a workaround that maintains the usage of * as a dereference operator outside the class?

It would be quite a hindrance if I couldn't overload * without giving up usage of *this.

Body:
If *this ends up dereferencing this to a string instead of a Person, is there a workaround that maintains the usage of * as a dereference operator outside the class?

No. *this will be Person& or Person const& depending on the function. The overload applies to Person objects, not pointers to Person objects. this is a pointer to a Person object.

If you use:

 Person p;
 auto v = *p;

Then, the operator* overload is called.

To call the operator* overload using this, you'll have to use this->operator*() or **this.


问:
Azure IOT ExportDevicesAsync internal server error
Same problem as here. I'm following the simple sample to export the IOT device list to blob storage but hitting an internal server error on ExportDevicesAsync.
I'm using North Europe, but I don't think changing servers is really a valid fix.

All I'm getting back is:

```<code>An exception of type 'Microsoft.Azure.Devices.Common.Exceptions.ServerErrorException' occurred in mscorlib.dll but was not handled in user code

Additional information: {"Message":"ErrorCode:ServerError;InternalServerError","ExceptionMessage":"Tracking ID:c51dad0227604f21b9af3e8acbd77f4c-G:5-TimeStamp:06/03/2017 19:56:10"}
</code>```

Sample Code (connection strings and keys masked)

```<code>internal async Task GetAllDevices()
{

    var ConnectionString =
        "HostName=xxxx.azure-devices.net;SharedAccessKeyName=xxxxowner;SharedAccessKey=xxxxLr3xxxxXKKILLxxxxx";
   registryManager = RegistryManager.CreateFromConnectionString(ConnectionString);

    var key = "https://xxxxotblob1.blob.core.windows.newt/?sv=2016-05-31&ss=bfqt&srt=sco&sp=rwdlxxxxup&se=2017-06-04T04:42:14Z&st=2017-06-03T20:42:14Z&spr=https&sig=kxxxxxxxxxxxxxxx%3D";

    JobProperties exportJob = await registryManager.ExportDevicesAsync(key,"device.txt", false);

    while (true)
    {
        exportJob = await registryManager.GetJobAsync(exportJob.JobId);
        if (exportJob.Status == JobStatus.Completed ||
            exportJob.Status == JobStatus.Failed ||
            exportJob.Status == JobStatus.Cancelled)
        {
            break;
        }

        await Task.Delay(TimeSpan.FromSeconds(5));
    }

}
</code>```

Am I doing something wrong here? Is there a way to catch the real exception I'm missing?

答:
You may have wrong format of the exportBlobContainerUri. The right one looks like this:

```<code>https://[StorageAccountName].blob.core.windows.net/[ContainerName]?sv=2016-05-31&sr=c&sig=mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxw%3D&se=2017-06-06T02%3A07%3A22Z&sp=rwd
</code>```

You can follow these steps to get the container SAS URI:

```<code>//1# Get your container:

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");

//2# Format the Uri:

static string GetContainerSasUri(CloudBlobContainer container)
{
  var sasConstraints = new SharedAccessBlobPolicy();
  sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24);
  sasConstraints.Permissions =
    SharedAccessBlobPermissions.Write |
    SharedAccessBlobPermissions.Read |
    SharedAccessBlobPermissions.Delete;

  string sasContainerToken = container.GetSharedAccessSignature(sasConstraints);

  return container.Uri + sasContainerToken;
}
</code>```

For more information you can reference Create a container and Get the container SAS URI.

Body:
Same problem as here. I'm following the simple sample to export the IOT device list to blob storage but hitting an internal server error on ExportDevicesAsync.
I'm using North Europe, but I don't think changing servers is really a valid fix.

All I'm getting back is:

An exception of type 'Microsoft.Azure.Devices.Common.Exceptions.ServerErrorException' occurred in mscorlib.dll but was not handled in user code

Additional information: {"Message":"ErrorCode:ServerError;InternalServerError","ExceptionMessage":"Tracking ID:c51dad0227604f21b9af3e8acbd77f4c-G:5-TimeStamp:06/03/2017 19:56:10"}

Sample Code (connection strings and keys masked)

internal async Task GetAllDevices()
{

    var ConnectionString =
        "HostName=xxxx.azure-devices.net;SharedAccessKeyName=xxxxowner;SharedAccessKey=xxxxLr3xxxxXKKILLxxxxx";
   registryManager = RegistryManager.CreateFromConnectionString(ConnectionString);

    var key = "https://xxxxotblob1.blob.core.windows.newt/?sv=2016-05-31&ss=bfqt&srt=sco&sp=rwdlxxxxup&se=2017-06-04T04:42:14Z&st=2017-06-03T20:42:14Z&spr=https&sig=kxxxxxxxxxxxxxxx%3D";

    JobProperties exportJob = await registryManager.ExportDevicesAsync(key,"device.txt", false);

    while (true)
    {
        exportJob = await registryManager.GetJobAsync(exportJob.JobId);
        if (exportJob.Status == JobStatus.Completed ||
            exportJob.Status == JobStatus.Failed ||
            exportJob.Status == JobStatus.Cancelled)
        {
            break;
        }

        await Task.Delay(TimeSpan.FromSeconds(5));
    }

}

Am I doing something wrong here? Is there a way to catch the real exception I'm missing?

Body:
You may have wrong format of the exportBlobContainerUri. The right one looks like this:

https://[StorageAccountName].blob.core.windows.net/[ContainerName]?sv=2016-05-31&sr=c&sig=mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxw%3D&se=2017-06-06T02%3A07%3A22Z&sp=rwd

You can follow these steps to get the container SAS URI:

//1# Get your container:

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");

//2# Format the Uri:

static string GetContainerSasUri(CloudBlobContainer container)
{
  var sasConstraints = new SharedAccessBlobPolicy();
  sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24);
  sasConstraints.Permissions =
    SharedAccessBlobPermissions.Write |
    SharedAccessBlobPermissions.Read |
    SharedAccessBlobPermissions.Delete;

  string sasContainerToken = container.GetSharedAccessSignature(sasConstraints);

  return container.Uri + sasContainerToken;
}

For more information you can reference Create a container and Get the container SAS URI.


问:
link_to helper doesn't work for me
the controller file drummer.rb

and I use both old controller/action way and new resource way, either work
the view file index.html.erb:

```<code><ul>
<% @drummer_list.each do |d| %>
  <li>
    <%= link_to :controller => 'drummers',:action => 'show', :id => '@drummer'  do %>
      <%=  d.first_name + ' ' + d.last_name %>
    <% end %>
  </li>
<% end %>
</ul>
</code>```

the resource way:

```<code><ul>
<% @drummer_list.each do |d| %>
  <li>
    <%= link_to drummers_path(@drummer)  do %>
      <%=  d.first_name + ' ' + d.last_name %>
    <% end %>
  </li>
<% end %>
</ul>
</code>```

when I click each link, in the browser url bar give me this

```<code>http://localhost:3000/drummers/@drummer
</code>```

it should give me

```<code>http://localhost:3000/drummers/1
</code>```

I think the problem is about the @drummer, I'm not sure about the it.

答: I think maybe you wanted to use "d" instead of "@drummer" as that's your loop variable of the drummer instance?</p>

Title: link_to helper doesn't work for me

Body:
the controller file drummer.rb

and I use both old controller/action way and new resource way, either work
the view file index.html.erb:

<% @drummer_list.each do |d| %>

    <%= link_to :controller => 'drummers',:action => 'show', :id => '@drummer'  do %>
      <%=  d.first_name + ' ' + d.last_name %>
    <% end %>

<% end %>

the resource way:

<% @drummer_list.each do |d| %>

    <%= link_to drummers_path(@drummer)  do %>
      <%=  d.first_name + ' ' + d.last_name %>
    <% end %>

<% end %>

when I click each link, in the browser url bar give me this

http://localhost:3000/drummers/@drummer

it should give me

http://localhost:3000/drummers/1

I think the problem is about the @drummer, I'm not sure about the it.


问:
POST JSON data in Python
```<code>def post():
    url = "someurl.com"
    with open(jsonfile) as myfile:
        for line in myfile:
            post_fields = line
            print(post_fields)
            request = Request(url, urlencode(post_fields).encode())
            json = urlopen(request).read().decode()
            print(json)

post()
</code>```

I am trying to post my JSON data to a website using the code above. However, I met up with an error. The error is

not a valid non-string sequence or mapping object

Below is my JSON data.

```<code>[{"ContentUrl": "https://twitter.com/realDonaldTrump/status/871331574649901056", "Text": "Do you notice we are not having a gun debate right now? That's because they used knives and a truck!", "PublishDate": "4:43 AM - 4 Jun 2017", "Title": "", "SourceUrl": "https://twitter.com/@realDonaldTrump", "SocialNetwork": "Twitter", "Source": "", "Author": "Donald J. Trump", "Like_count": "147,875 likes", "Replies_count": "57,397 replies", "Retweets_count": "45,500 retweets", "Schema": "SOCIAL_MEDIA"}]
</code>```

Any help or suggestions for me?

答:
Here are my comments:

You need to precise what is the payload part that you want to post to the url.

You need to decode the json objects from each line by using json.loads

According to your answer to my question the json file contains the following.

[{"ContentUrl": "https://twitter.com/realDonaldTrump/status/871331574649901056", "Text": "Do you notice we are not having a gun debate right now? That's because they used knives and a truck!", "PublishDate": "4:43 AM - 4 Jun 2017", "Title": "", "SourceUrl": "https://twitter.com/@realDonaldTrump", "SocialNetwork": "Twitter", "Source": "", "Author": "Donald J. Trump", "Like_count": "147,875 likes", "Replies_count": "57,397 replies", "Retweets_count": "45,500 retweets", "Schema": "SOCIAL_MEDIA"}]

Then, which part of the dictionary is the payload that you want to use in the post request ?

Here is the fixed code. But you still need to precise the right url and payload you want to use.

```<code>from urllib import urlencode
from urllib import urlopen
from requests import Request
import json
import requests

def post(jsonfile):
    with open(jsonfile) as myfile:
        for line in myfile:
            # Decoding JSON object
            json_data = json.loads(line)
            # Here you need to iterate over the json_data as it is an array
            for el in json_data:
                url = el["ContentUrl"]
                el.pop("ContentUrl")
                # Here I use the rest of the fields in el as payload
                # But I don't think that you are using the right data
                # You still need to find out which payload you want to send in the post request
                response = requests.post(url, data = el)
                print(response.status_code, response.reason)

jsonfile='testfile.json'
post(jsonfile)
</code>```

Title: POST JSON data in Python

Body:
def post():
    url = "someurl.com"
    with open(jsonfile) as myfile:
        for line in myfile:
            post_fields = line
            print(post_fields)
            request = Request(url, urlencode(post_fields).encode())
            json = urlopen(request).read().decode()
            print(json)

post()

I am trying to post my JSON data to a website using the code above. However, I met up with an error. The error is

not a valid non-string sequence or mapping object

Below is my JSON data.

[{"ContentUrl": "https://twitter.com/realDonaldTrump/status/871331574649901056", "Text": "Do you notice we are not having a gun debate right now? That's because they used knives and a truck!", "PublishDate": "4:43 AM - 4 Jun 2017", "Title": "", "SourceUrl": "https://twitter.com/@realDonaldTrump", "SocialNetwork": "Twitter", "Source": "", "Author": "Donald J. Trump", "Like_count": "147,875 likes", "Replies_count": "57,397 replies", "Retweets_count": "45,500 retweets", "Schema": "SOCIAL_MEDIA"}]

Any help or suggestions for me?

Body:
Here are my comments:

You need to precise what is the payload part that you want to post to the url.

You need to decode the json objects from each line by using json.loads

According to your answer to my question the json file contains the following.

[{"ContentUrl": "https://twitter.com/realDonaldTrump/status/871331574649901056", "Text": "Do you notice we are not having a gun debate right now? That's because they used knives and a truck!", "PublishDate": "4:43 AM - 4 Jun 2017", "Title": "", "SourceUrl": "https://twitter.com/@realDonaldTrump", "SocialNetwork": "Twitter", "Source": "", "Author": "Donald J. Trump", "Like_count": "147,875 likes", "Replies_count": "57,397 replies", "Retweets_count": "45,500 retweets", "Schema": "SOCIAL_MEDIA"}]

Then, which part of the dictionary is the payload that you want to use in the post request ?

Here is the fixed code. But you still need to precise the right url and payload you want to use.

from urllib import urlencode
from urllib import urlopen
from requests import Request
import json
import requests

def post(jsonfile):
    with open(jsonfile) as myfile:
        for line in myfile:
            # Decoding JSON object
            json_data = json.loads(line)
            # Here you need to iterate over the json_data as it is an array
            for el in json_data:
                url = el["ContentUrl"]
                el.pop("ContentUrl")
                # Here I use the rest of the fields in el as payload
                # But I don't think that you are using the right data
                # You still need to find out which payload you want to send in the post request
                response = requests.post(url, data = el)
                print(response.status_code, response.reason)

jsonfile='testfile.json'
post(jsonfile)


问:
django - url with automatic slash adding
I'm using django admin on my website. When I enter url without slash after admin (http://example.com/admin) I receive 404 error. I thought that django automatically added slash on the end of url. Of course when I enter url ended with slash it works fine. What I am doing wrong, or which settings I have to change. Thanks for any ideas.</p>

答:
Try setting APPEND_SLASH = True in settings.py.

On second thoughts, I think the default setting is True.

https://docs.djangoproject.com/en/dev/ref/settings/#append-slash


问:
docker build error in Dockerfile
When I try to run 'docker build .' or 'docker build - < Dockerfile', errors appeared as below:

```<code>[root@VM_60_90_centos dtask-ctrip-train-domestic]# docker build .
Sending build context to Docker daemon 38.98 MB
Step 1 : FROM ubuntu:14.04  ---> 132b7427a3b4
Step 2 : MAINTAINER Ke Peng<ke.peng@jingli365.com>  ---> Using cache  --->
         db9529465f77
Step 3: WORKDIR /opt/app  ---> Using cache  ---> 3122f40a8e56
Step 4 :COPY . ./  ---> 4d67a5fbf128 Removing intermediate container
c2d83602f613
Step 5 : RUN npm  install  ---> Running in 67680232cbdf

/bin/sh: 1: npm: not found The command '/bin/sh -c npm  install'
returned a non-zero code: 127
</code>```

and my Dockerfile like this:

```<code>FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json
</code>```

Can anyone have similar experience and give me an solution. Very appreciated!

答:
Try this:</p>

```<code>FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
RUN sudo apt-get update && \
    sudo apt-get install -y nodejs npm

WORKDIR /opt/app

COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json
</code>```

Title: docker build error in Dockerfile

Body:
When I try to run 'docker build .' or 'docker build - < Dockerfile', errors appeared as below:

[root@VM_60_90_centos dtask-ctrip-train-domestic]# docker build .
Sending build context to Docker daemon 38.98 MB
Step 1 : FROM ubuntu:14.04  ---> 132b7427a3b4
Step 2 : MAINTAINER Ke Peng<ke.peng@jingli365.com>  ---> Using cache  --->
         db9529465f77
Step 3: WORKDIR /opt/app  ---> Using cache  ---> 3122f40a8e56
Step 4 :COPY . ./  ---> 4d67a5fbf128 Removing intermediate container
c2d83602f613
Step 5 : RUN npm  install  ---> Running in 67680232cbdf

/bin/sh: 1: npm: not found The command '/bin/sh -c npm  install'
returned a non-zero code: 127

and my Dockerfile like this:

FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json

Can anyone have similar experience and give me an solution. Very appreciated!

Body:
Try this:

FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
RUN sudo apt-get update && \
    sudo apt-get install -y nodejs npm

WORKDIR /opt/app

COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json


问:
SQL Query - Oracle GL Transaction Detail
I am a novice SQL coder, and need some assistance with the SQL query I'm building for the GL Transaction Detail from Oracle.

I have been able to write my query, and I am successfully able to put the data how I like it. There's something I'd like to add to the query, which I believe requires a sub query, but I'm not sure how to write it.

```<code>SELECT CLIENT,
RESPONSIBILITY,
SERVICE_LINE,
STOB,
PROJECT,
JE_LINES_NET_ACT_AMOUNT AS "ACTUAL_AMOUNT",
EFFECTIVE_DATE,
PERIOD_NAME,
VENDOR_NAME,
DISTRIBUTION_SUPPLIER_NAME,
CASE WHEN JE_LINE_DESCRIPTION='Journal Import Created' THEN
     AP_DISTRIBUTION_DESCRIPTION ELSE
     JE_LINE_DESCRIPTION END AS DESCRIPTION,
CASE WHEN JE_HEADER_NAME LIKE '%Purchase%' THEN
     INVOICE_NUMBER ELSE
     JE_HEADER_NAME END AS DOCUMENT_NUMBER
FROM GL_Detail
WHERE RESPONSIBILITY BETWEEN '17500' AND '17511'
     AND EFFECTIVE_DATE BETWEEN '2016/04/01' AND '2017/03/31'
     AND JE_LINES_NET_ACT_AMOUNT <> 0
</code>```

Above is an example of the code I'm using for my query. Currently I have it pulling data for a range of responsibility centers (or cost centers). For reporting purposes, we have these responsibility centers roll up to different levels for location and department. Most users, want to pull the data by these rolled up responsibility numbers; however our GL transaction detail table does not have these columns.

What I want to be able to do: I want to be able to define a range of responsibility centers and assign them with their rolled up responsibility number that I can define. When I set the parameter after the WHERE, I want to be able to set the rolled up responsibility number as a parameter.

Would a nested case function solve this after select do this? Or is there another function I need to use?

Any help would be greatly appreciated.

答: you did not state the data types of your columns, but I see a potential problem with implicit type conversion.  To avoid that, use bind variables that match the type of the column being subset.</p>

Body:
I am a novice SQL coder, and need some assistance with the SQL query I'm building for the GL Transaction Detail from Oracle.

I have been able to write my query, and I am successfully able to put the data how I like it. There's something I'd like to add to the query, which I believe requires a sub query, but I'm not sure how to write it.

SELECT CLIENT,
RESPONSIBILITY,
SERVICE_LINE,
STOB,
PROJECT,
JE_LINES_NET_ACT_AMOUNT AS "ACTUAL_AMOUNT",
EFFECTIVE_DATE,
PERIOD_NAME,
VENDOR_NAME,
DISTRIBUTION_SUPPLIER_NAME,
CASE WHEN JE_LINE_DESCRIPTION='Journal Import Created' THEN
     AP_DISTRIBUTION_DESCRIPTION ELSE
     JE_LINE_DESCRIPTION END AS DESCRIPTION,
CASE WHEN JE_HEADER_NAME LIKE '%Purchase%' THEN
     INVOICE_NUMBER ELSE
     JE_HEADER_NAME END AS DOCUMENT_NUMBER
FROM GL_Detail
WHERE RESPONSIBILITY BETWEEN '17500' AND '17511'
     AND EFFECTIVE_DATE BETWEEN '2016/04/01' AND '2017/03/31'
     AND JE_LINES_NET_ACT_AMOUNT <> 0

Above is an example of the code I'm using for my query. Currently I have it pulling data for a range of responsibility centers (or cost centers). For reporting purposes, we have these responsibility centers roll up to different levels for location and department. Most users, want to pull the data by these rolled up responsibility numbers; however our GL transaction detail table does not have these columns.

What I want to be able to do: I want to be able to define a range of responsibility centers and assign them with their rolled up responsibility number that I can define. When I set the parameter after the WHERE, I want to be able to set the rolled up responsibility number as a parameter.

Would a nested case function solve this after select do this? Or is there another function I need to use?

Any help would be greatly appreciated.


问:
how to validate Radio button in GWT
I have two radio buttons and text field and i want to have validator that one radio checked, the text field must not be null.

Here is the code:

```<code>radio1 = new Radio();
radio1.setBoxLabel("yes");
radio1.setId("active");
radio1.setValue(false);

radio2 = new Radio();
radio2.setBoxLabel("no");
radio2.setId("deactive");
radio2.setValue(true);

final RadioGroup defaultRadioGroup = new RadioGroup();
defaultRadioGroup.setFieldLabel("activeا");
defaultRadioGroup.add(radio1);
defaultRadioGroup.add(radio2);
simpleForm.add(defaultRadioGroup, formData);

labelField = new TextField<String>();
labelField.setEmptyText("please insert value");
labelField.setReadOnly(true);
</code>```

答:
You should write a new Validator for the textbox and then call textbox.validate()

Other option is to check if your textbox class supports any utility method like "allowEmpty(boolean)"

Title: how to validate Radio button in GWT

Body:
I have two radio buttons and text field and i want to have validator that one radio checked, the text field must not be null.

Here is the code:

radio1 = new Radio();
radio1.setBoxLabel("yes");
radio1.setId("active");
radio1.setValue(false);

radio2 = new Radio();
radio2.setBoxLabel("no");
radio2.setId("deactive");
radio2.setValue(true);

final RadioGroup defaultRadioGroup = new RadioGroup();
defaultRadioGroup.setFieldLabel("activeا");
defaultRadioGroup.add(radio1);
defaultRadioGroup.add(radio2);
simpleForm.add(defaultRadioGroup, formData);

labelField = new TextField<String>();
labelField.setEmptyText("please insert value");
labelField.setReadOnly(true);


问:
string split using regex PHP
My string is "30OKOKOKOKOKOKOKOK30OKOKOKOKOKOKOKOKOKOKOKOKOKOK120"
i want to split it in digits and 'OK' string, my expected output is

```<code>array(0=>30,1=>OK,2=>OK,......,n=>120)
</code>```

currently i am using this

```<code>preg_match_all('!\d+!', $str, $matches);
</code>```

but it only returns me digits i.e. 30,30,120
please help me to get above expected output

答:
What you want is…

```<code>preg_match_all('(\d+|OK)', $string, $matches);
</code>```

\d+ - One or more digits

| - or

OK - Capital O followed by capital K

Title: string split using regex PHP

Body:
My string is "30OKOKOKOKOKOKOKOK30OKOKOKOKOKOKOKOKOKOKOKOKOKOK120"
i want to split it in digits and 'OK' string, my expected output is

array(0=>30,1=>OK,2=>OK,......,n=>120)

currently i am using this

preg_match_all('!\d+!', $str, $matches);

but it only returns me digits i.e. 30,30,120
please help me to get above expected output

Body:
What you want is…

preg_match_all('(\d+|OK)', $string, $matches);

\d+ - One or more digits

| - or

OK - Capital O followed by capital K


问:
handle ngui's button event programmatically in unity
I'm transferring from Unity's UI to NGUI.

Formerly, I could add listeners to button with following scripts:

```<code>button.GetComponentInChildren<Button>().onClick.AddListener(() =>
{
    //codes that could be triggered by click the button.
});
</code>```

But when changing to NGUI, I can't make it work by:

```<code>EventDelegate.Set(go.GetComponent<UIButton>().onClick, OnButtonClickActive);

private void OnButtonClickActive()
{
   Debug.Log("active button clicked");
}
</code>```

答:
Finally, I made this work by adding a custom event to OnClick with the following script (using UIEventListener):

```<code>UIEventListener.Get(go).onClick += OnButtonClickActive;
</code>```

And the event handler is defined as follows:

```<code>private void OnButtonClickActive(GameObject go)
    {
        int level;
        int.TryParse(go.GetComponentInChildren<UILabel>().text, out level);
        Debug.Log(level + "active button clicked");
        ApplicationModel.CurrentLevel = ApplicationModel.Levels[level - 1];
        SceneManager.LoadScene("PlayScene");
    }
</code>```

Note that, it might be a little bit silly to pass the parameter (level info) with the UILable component in the gameobject. If there is other more elegant way, please let me know.

Body:
I'm transferring from Unity's UI to NGUI.

Formerly, I could add listeners to button with following scripts:

button.GetComponentInChildren<Button>().onClick.AddListener(() =>
{
    //codes that could be triggered by click the button.
});

But when changing to NGUI, I can't make it work by:

EventDelegate.Set(go.GetComponent<UIButton>().onClick, OnButtonClickActive);

private void OnButtonClickActive()
{
   Debug.Log("active button clicked");
}

Body:
Finally, I made this work by adding a custom event to OnClick with the following script (using UIEventListener):

UIEventListener.Get(go).onClick += OnButtonClickActive;

And the event handler is defined as follows:

private void OnButtonClickActive(GameObject go)
    {
        int level;
        int.TryParse(go.GetComponentInChildren<UILabel>().text, out level);
        Debug.Log(level + "active button clicked");
        ApplicationModel.CurrentLevel = ApplicationModel.Levels[level - 1];
        SceneManager.LoadScene("PlayScene");
    }

Note that, it might be a little bit silly to pass the parameter (level info) with the UILable component in the gameobject. If there is other more elegant way, please let me know.


问:
I am creating an email spammer, for an outstanding cause
In Cuba, web access is extremely censored, so I created a tool that allows more than 50,000 people to browse the Internet through email. Cubans send me an email with an URL in the subject line, and I email them back with the response. Read more at https://apretaste.com.

It was working like a charm, till the communist government of Cuba started blocking my emails. My solution was rotation.

I started with Amazon SES, and I was changing the domain each time it was blocked, but Amazon adds a header to all emails, and once they blocked the header no email from SES was able to reach Cuba any more. The same happened with Mailgun and others, they all add headers.

Currently I am creating Gmail accounts and sending via SMTP, but Google blocks me for no reason and only allows to send 100 emails a day per account. Also I can only create few emails using the same IP address/phone, so I was forced to use anonymous proxies and fake Chinese phones. Now I am fighting a war on two fronts.

An email can be blocked by three parameters: IP address, domain, and email address.

It will be terrific if I can set up my own Postfix server at a VPS that auto-rotates the IP address. Even better if I can simulate "gmail.com", to avoid purchasing a new domain every day.

All the intents to create what I call "the ultimate sender" just either reach the spam folder or add unwanted headers making it too easy to block. I feel exhausted. I hit a knowledge barrier here.

I know I am crossing to the dark side, but this is for a very good cause. Thousands count on this service as their only source of unbiased news, social network and to feel part of the 21st century.

Can you please help me implementing "the ultimate sender", or pointing to another solution that I may be missing?

答:
The simplest solution is perhaps to set up a local SMTP server on your own computer. You don't even need a server per se.

https://sourceforge.net/projects/winsmtpserver/

There are many other such applications. They are usually used to test SMTP functions during local development, but there is nothing against actually sending spam through them.


问:
How to send "back to normal" notifications in Jenkins Declarative Pipeline?
I'm trying to convert an existing Jenkins Pipeline to the new Declarative Pipeline and I was wondering how to handle correctly mail notifications ?

I'm currently using this code:

```<code>node {
   try {

      ...

      currentBuild.result = 'SUCCESS'
   } catch (any) {
       currentBuild.result = 'FAILURE'
       throw any
   } finally {
       step([$class: 'Mailer',
           notifyEveryUnstableBuild: true,
           recipients: "baptiste.wicht@gmail.com",
           sendToIndividuals: true])
   }
}
</code>```

It works well, but I don't see how to use the new declarative syntax for this. I think something could be done by using post() and the different notifications, but I don't know exactly how. I've tried this:

```<code>post {
    always {
        step([$class: 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients: "baptiste.wicht@gmail.com",
            sendToIndividuals: true])
    }
}
</code>```

But the problem is that it does not send any "Back to normal" mail.

How can I used the Mailer plugin in a Jenkins declarative pipeline in order to send "Back to normal" mails ?

Should use again a try/catch around all declarative syntax ?

答:
you can check the previous build like an all-star:</p>

```<code>pipeline {
  agent { label 'docker' }
  stages {
    stage ('build') {
      steps {
        sh 'ls'
      }
    }
  }
  post {
    always {
      script {
        if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
          if (currentBuild.previousBuild != null && currentBuild.previousBuild.result != 'SUCCESS') {
            echo 'send your back to normal email here, maybe something like this, your mileage may vary'
            emailext (
              subject: "Back to normal: ${currentBuild.fullDisplayName}",
              body: "Project is back to <blink>normal</blink>",
              mimeType: 'text/html',
              recipientProviders: [[$class: 'RequesterRecipientProvider'], [$class: 'DevelopersRecipientProvider']]
            )
          }
        }
      }
    }
  }
}
</code>```

Body:
I'm trying to convert an existing Jenkins Pipeline to the new Declarative Pipeline and I was wondering how to handle correctly mail notifications ?

I'm currently using this code:

node {
   try {

      ...

      currentBuild.result = 'SUCCESS'
   } catch (any) {
       currentBuild.result = 'FAILURE'
       throw any
   } finally {
       step([$class: 'Mailer',
           notifyEveryUnstableBuild: true,
           recipients: "baptiste.wicht@gmail.com",
           sendToIndividuals: true])
   }
}

It works well, but I don't see how to use the new declarative syntax for this. I think something could be done by using post() and the different notifications, but I don't know exactly how. I've tried this:

post {
    always {
        step([$class: 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients: "baptiste.wicht@gmail.com",
            sendToIndividuals: true])
    }
}

But the problem is that it does not send any "Back to normal" mail.

How can I used the Mailer plugin in a Jenkins declarative pipeline in order to send "Back to normal" mails ?

Should use again a try/catch around all declarative syntax ?

Body:
you can check the previous build like an all-star:

pipeline {
  agent { label 'docker' }
  stages {
    stage ('build') {
      steps {
        sh 'ls'
      }
    }
  }
  post {
    always {
      script {
        if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
          if (currentBuild.previousBuild != null && currentBuild.previousBuild.result != 'SUCCESS') {
            echo 'send your back to normal email here, maybe something like this, your mileage may vary'
            emailext (
              subject: "Back to normal: ${currentBuild.fullDisplayName}",
              body: "Project is back to <blink>normal</blink>",
              mimeType: 'text/html',
              recipientProviders: [[$class: 'RequesterRecipientProvider'], [$class: 'DevelopersRecipientProvider']]
            )
          }
        }
      }
    }
  }
}


答:
Try changing the base image to one containing node, such as:

```<code>FROM node:6
MAINTAINER Ke Peng <ke.peng@jingli365.com>
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json
</code>```

Note: changed the first line only.

Title: docker build error in Dockerfile

Body:
Try changing the base image to one containing node, such as:

FROM node:6
MAINTAINER Ke Peng <ke.peng@jingli365.com>
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json

Note: changed the first line only.


问:
Run AJAX in order
I need to run 2 AJAX in order. The first AJAX will only be called once when the page is loaded. The second AJAX will be called after the first AJAX was called or when user clicked some buttons on the page.

I have written the following, but the first AJAX will be called each time when the second AJAX is called.

```<code>var GetFirstAJAX = function() {
  var deferred = $.Deferred();
  $.ajax({
    ...
  success: deferred.resolve();
  error: deferred.reject();
    ...
  });
  return deferred.promise();
};

//Second AJAX
$.when(GetFirstAJAX()).then(function()
{
  $.ajax({
    ...
  });
});
</code>```

答:
You can just run the second ajax in the done method that can be chained on the first ajax like so:

// first ajax
$.ajax({
  // .. ajax details
}).done(function(res){
  // res is the result of the first ajax
  // do something with it (e.g console.log) or call second ajax call
  $.ajax({
    // .. second ajax details
  }).done(function(res2) {
    // .. the rest of logic
  })
})```

Title: Run AJAX in order

Body:
I need to run 2 AJAX in order. The first AJAX will only be called once when the page is loaded. The second AJAX will be called after the first AJAX was called or when user clicked some buttons on the page.

I have written the following, but the first AJAX will be called each time when the second AJAX is called.

var GetFirstAJAX = function() {
  var deferred = $.Deferred();
  $.ajax({
    ...
  success: deferred.resolve();
  error: deferred.reject();
    ...
  });
  return deferred.promise();
};

//Second AJAX
$.when(GetFirstAJAX()).then(function()
{
  $.ajax({
    ...
  });
});


问:
Control axis size matplotlib pyplot
I can't find a way to control the alignment of points in matplotlib.pyplot in order to more properly center samples within a window. Below is an example where I am plotting two averaged samples with stdev and instead of being uniformly spaced within the window, they are pushed off onto the edges of the plot.

Is there a way to better control this alignment? My code is below for reference.

```<code>plt.clf()
plt.errorbar(np.arange(len(rmean)),rmean,yerr=rstddev, linestyle="None", fmt='o')
plt.xlabel('Probes', fontsize=1)
plt.ylabel('VAF')
plt.title('Average VAF Along Probed Regions')
plt.tight_layout()
plt.xticks(np.arange(len(rmean)),labels,rotation='90')
plt.tight_layout()
plt.show()
</code>```

答:
I guess you've already know this from Matplotlib Examples. Essentially, the x-axis position of your data is defined by "x", which is np.arange(len(rmean)). Therefore, the final visual position is related to the range of x-axis, the xlim. Then one potential solution is to set xlim by plt.xlim([-1, len(rmean)]). I don't have your rmean or rstddev. But testing by some fake data, I got this:

Hopefully, this is what you want.

Title: Control axis size matplotlib pyplot

Body:
I can't find a way to control the alignment of points in matplotlib.pyplot in order to more properly center samples within a window. Below is an example where I am plotting two averaged samples with stdev and instead of being uniformly spaced within the window, they are pushed off onto the edges of the plot.

Is there a way to better control this alignment? My code is below for reference.

plt.clf()
plt.errorbar(np.arange(len(rmean)),rmean,yerr=rstddev, linestyle="None", fmt='o')
plt.xlabel('Probes', fontsize=1)
plt.ylabel('VAF')
plt.title('Average VAF Along Probed Regions')
plt.tight_layout()
plt.xticks(np.arange(len(rmean)),labels,rotation='90')
plt.tight_layout()
plt.show()