问:
How to pass extra data to activity from homescreen shortcut?
I have an Non-Launcher activity with a context menu. The menu contains an option to add the activity to android home screen as a shortcut.

I am using the below code to create the shortcut.

```<code>private void ShortcutIcon(){

    Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    Intent addIntent = new Intent();
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Test");
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));

    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(addIntent);
}
</code>```

Necessary permissions and intent filters are correctly set. When I run this code, the shortcut is created successfully. On shortcut click, the activity opens as expected.

However, my activity shows some dynamic data. for that I need to pass one small string variable to the activity.

I have tried to use this code before setAction (just like you would pass extra data to a normal intent for launching an activity)

```<code>addIntent.putExtra("key_primarykey", value_i_want_to_pass);
</code>```

However, when user clicks on the shortcut, inside the activity, the value_i_want_to_pass comes as Null.

Some applications like Whatsapp allows to do exactly the same. you can save a shortcut of a chat. also some dialer apps allow to add a contact as a shortcut so that when you tap on the shortcut, a voice call is initiated automatically.

I want to know how can I pass some data from my shortcut to my activity.

答:
You are sending your data to addIntent which will be caught by Launcher's Broadcast Receiver.

Just change following line

```<code>addIntent.putExtra("key_primarykey", value_i_want_to_pass);
</code>```

to

```<code>shortcutIntent.putExtra("key_primarykey", value_i_want_to_pass);
</code>```

and write it along with your shorcutIntent code before setting shortcutIntent to addIntent.

So that the Action Intent you are setting for the shortcut will return you the correct value.
So the modified code will be as follows.

```<code>private void ShortcutIcon(){

    Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    shortcutIntent.putExtra("key_primarykey", value_i_want_to_pass);

    Intent addIntent = new Intent();
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Test");
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));

    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(addIntent);
}
</code>```

Body:
I have an Non-Launcher activity with a context menu. The menu contains an option to add the activity to android home screen as a shortcut.

I am using the below code to create the shortcut.

private void ShortcutIcon(){

    Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    Intent addIntent = new Intent();
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Test");
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));

    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(addIntent);
}

Necessary permissions and intent filters are correctly set. When I run this code, the shortcut is created successfully. On shortcut click, the activity opens as expected.

However, my activity shows some dynamic data. for that I need to pass one small string variable to the activity.

I have tried to use this code before setAction (just like you would pass extra data to a normal intent for launching an activity)

addIntent.putExtra("key_primarykey", value_i_want_to_pass);

However, when user clicks on the shortcut, inside the activity, the value_i_want_to_pass comes as Null.

Some applications like Whatsapp allows to do exactly the same. you can save a shortcut of a chat. also some dialer apps allow to add a contact as a shortcut so that when you tap on the shortcut, a voice call is initiated automatically.

I want to know how can I pass some data from my shortcut to my activity.

Body:
You are sending your data to addIntent which will be caught by Launcher's Broadcast Receiver.

Just change following line

addIntent.putExtra("key_primarykey", value_i_want_to_pass);

to

shortcutIntent.putExtra("key_primarykey", value_i_want_to_pass);

and write it along with your shorcutIntent code before setting shortcutIntent to addIntent.

So that the Action Intent you are setting for the shortcut will return you the correct value.
So the modified code will be as follows.

private void ShortcutIcon(){

    Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    shortcutIntent.putExtra("key_primarykey", value_i_want_to_pass);

    Intent addIntent = new Intent();
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Test");
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));

    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(addIntent);
}


来源: stackexchange

问:
Why Can't i update a variable of class from another class in android(Java)?
I want to update this num variable from different classes through this Methods .
but it show '0' when i display it

```<code>public class ResultNum extends AppCompatActivity{

private  int num;

public int ResultNum1(){

   return num;
}

public void yesMethod(int i){

    num = i+num;

}
</code>```

Here is Another class

```<code> yes.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.yesMethod(2);

        }
    });
</code>```

and also I've some other classes as well which passes different numbers

here's code for displaying number

```<code> TextView t = (TextView) findViewById(R.id.text_number);
   int x = result.ResultNum1();
    t.setText(""+x);
</code>```

i also tried

```<code> TextView t = (TextView) findViewById(R.id.text_number);
    t.setText(""+result.ResultNum1());
</code>```

so What exactly i need to do now?

答: As already stated, you should either declare int num as static or make sure that all your methods across application use the same instance of ResultNum class.

ContentLicense: CC BY-SA 3.0

Body:
I want to update this num variable from different classes through this Methods .
but it show '0' when i display it

public class ResultNum extends AppCompatActivity{

private  int num;

public int ResultNum1(){

   return num;
}

public void yesMethod(int i){

    num = i+num;

}

Here is Another class

 yes.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.yesMethod(2);

        }
    });

and also I've some other classes as well which passes different numbers

here's code for displaying number

 TextView t = (TextView) findViewById(R.id.text_number);
   int x = result.ResultNum1();
    t.setText(""+x);

i also tried

 TextView t = (TextView) findViewById(R.id.text_number);
    t.setText(""+result.ResultNum1());

so What exactly i need to do now?


问:
REST API resource structure where there are multiple "owners"
I am struggling to see how to structure a REST API where multiple owners may use the same resource. For example if there are users and organizations and each of them has something like images or locations. An Image and a location is a database field, which is the same for both users and organizations... I can see two basic ways to go about it

Separate endpoints:

```<code>POST /users/:userID/documents
GET /users/:userID/documents/:id
POST /org/:orgID/documents
GET /org/:orgID/documents/:id
</code>```

pros of separate endpoints: The logic is clean and everything is very obvious

cons of separate endpoints: There is a LOT of code copying between the endpoints.

Shared endpoints:

```<code>POST /documents
GET /documents/:id
</code>```

pros of separate endpoints: There are fewer overall endpoints, less code copying.

cons of separate endpoints: The logic gets messy, IDK the best way to go about sending the orgID or userID with the request (without in effect creating a new endpoint within the /documents resource. I could use a query string, but that just feels wrong... (IDK if it is wrong)

Any advice?

答:
It all depends on the use case scenarios for your API.

There's nothing wrong with separate endpoints, if the flow would generally be to request users/organizations and their respective documents. It also doesn't have to mean code duplication - you can simply have some sort of common DocumentRepository in the backend, consumed in multiple places.

However, if the requirements are to simply search/display documents, a query string might be your best bet:

```<code>GET /documents?userId={userId}&organizationId={organizationId}
</code>```

Body:
I am struggling to see how to structure a REST API where multiple owners may use the same resource. For example if there are users and organizations and each of them has something like images or locations. An Image and a location is a database field, which is the same for both users and organizations... I can see two basic ways to go about it

Separate endpoints:

POST /users/:userID/documents
GET /users/:userID/documents/:id
POST /org/:orgID/documents
GET /org/:orgID/documents/:id

pros of separate endpoints: The logic is clean and everything is very obvious

cons of separate endpoints: There is a LOT of code copying between the endpoints.

Shared endpoints:

POST /documents
GET /documents/:id

pros of separate endpoints: There are fewer overall endpoints, less code copying.

cons of separate endpoints: The logic gets messy, IDK the best way to go about sending the orgID or userID with the request (without in effect creating a new endpoint within the /documents resource. I could use a query string, but that just feels wrong... (IDK if it is wrong)

Any advice?

Body:
It all depends on the use case scenarios for your API.

There's nothing wrong with separate endpoints, if the flow would generally be to request users/organizations and their respective documents. It also doesn't have to mean code duplication - you can simply have some sort of common DocumentRepository in the backend, consumed in multiple places.

However, if the requirements are to simply search/display documents, a query string might be your best bet:

GET /documents?userId={userId}&organizationId={organizationId}


问:
In Java, why have a code block with no keywords, just curly brackets
I'm re-factoring some inherited code, but was stumped by the design decision and can't figure out the proper terms to google this. My predecessor would use blocks like this one:

```<code>public class ChildClass extends ParentClass {
    {
        inheritedVar = "someVal";
    }

    public ChildClass(){ /* constructor exists */ }
    // rest of code
}
</code>```

What is the point of declaring a block of code with no keyword? It doesn't behave like a static block, I don't believe. Is it an alternative to setting in the constructor? Would this have some effect if a factory was being used (which in this case it's not)? I found a related thread here on this happening in C but the reasoning (scope & variable declaration) didn't seem relevant to Java.

Any thoughts or ideas on the "why" of this would be appreciated. It's easy enough to re-factor this, I'm just curious at this point.

答:
It's called an initializer block.

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

```<code>    {
        // whatever code is needed for initialization goes here
    }
</code>```

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

ContentLicense: CC BY-SA 2.5

Body:
I'm re-factoring some inherited code, but was stumped by the design decision and can't figure out the proper terms to google this. My predecessor would use blocks like this one:

public class ChildClass extends ParentClass {
    {
        inheritedVar = "someVal";
    }

    public ChildClass(){ /* constructor exists */ }
    // rest of code
}

What is the point of declaring a block of code with no keyword? It doesn't behave like a static block, I don't believe. Is it an alternative to setting in the constructor? Would this have some effect if a factory was being used (which in this case it's not)? I found a related thread here on this happening in C but the reasoning (scope & variable declaration) didn't seem relevant to Java.

Any thoughts or ideas on the "why" of this would be appreciated. It's easy enough to re-factor this, I'm just curious at this point.

Body:
It's called an initializer block.

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

    {
        // whatever code is needed for initialization goes here
    }

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.


问:
Java Math.sin Math.cos Math.tan Giving answer in Radian
I was trying to use the Math library in Java where Math.sin(90) gives me result 0.8939966636005579 I search on StackOverflow about this and came to know that the value is) in radian so I used below code to convert it to a degree.

```<code>Double deg;
deg = Math.toDegrees(value);
</code>```

The value of sin(90) in degree is 1 but the above code returns 51.222235723088794 what should I do to get an accurate result?

Result should be like for sin(90) :: 1

答: Try double result = Math.sin(Math.toRadians(90))

Body:
I was trying to use the Math library in Java where Math.sin(90) gives me result 0.8939966636005579 I search on StackOverflow about this and came to know that the value is) in radian so I used below code to convert it to a degree.

Double deg;
deg = Math.toDegrees(value);

The value of sin(90) in degree is 1 but the above code returns 51.222235723088794 what should I do to get an accurate result?

Result should be like for sin(90) :: 1


问:
How to sort regardless of case with Comparator?
I am using the Comparator interface to sort objects in ascending order using following code fragment:

```<code>final List<LinkModelSpi> documentLinks = this.documentLinksModelSpi.getDocumentLinks();

//Add This method for Sorting Document Link View Same Order. Now The application display same links order
// in catalogue administration edit drug window
if (Checks.checkNotNullAndNonEmpty(documentLinks)) {
  if (this.documentLinksModelSpi.getDocumentLinks().iterator().next() instanceof DocumentLinkModelSpi) {
    Collections.sort(documentLinks, (Comparator<? super LinkModelSpi>) new Comparator<DocumentLinkModelImpl>() {
      @Override
      public int compare(DocumentLinkModelImpl o1, DocumentLinkModelImpl o2) {
        return o1.getResource().compareTo(o2.getResource());
      }
    });
  } else {
    Collections.sort(documentLinks, (Comparator<? super LinkModelSpi>) new Comparator<LinkModelImpl>() {
      @Override
      public int compare(LinkModelImpl o1, LinkModelImpl o2) {
        return o1.getResource().compareTo(o2.getResource());
      }
    });
  }
}

//Collections.reverse(documentLinks);
for (final LinkModelSpi documentLinkModelSpi : documentLinks) {
  //noinspection unchecked
  ((DtoPresentationModelSpi<?, MDTO>) documentLinkModelSpi).addPropertyChangeListener(this);
}
</code>```

The final result is this:

But I want to sort list like this:

Where the links are sorted regardless of case. How can I do this?

答:
The generic solution is to use java.text.Collator, which is a specialised Comparator that not only handles uppercase/lowercase, but can also deal with diacritic signs (such as ä and ë) and knows about locale differences (e.g. most Western languages put the ë with the e, but Finland puts it after the z).

```<code>import java.text.Collator;
import java.util.*;

public class Example {
    public static void main(String[] args) {
        Collator en_US = Collator.getInstance(Locale.US);
        Collator fi_FI = Collator.getInstance(new Locale("fi", "FI"));

        // Optional configuration; read the Javadoc for more information
//        en_US.setStrength(Collator.PRIMARY);
//        en_US.setDecomposition(Collator.FULL_DECOMPOSITION);

        List l = new ArrayList(Arrays.asList("Azz", "ämm", "aaa"));
        Collections.sort(l, en_US);
        System.out.printf("en_US: %s\n", l);
        Collections.sort(l, fi_FI);
        System.out.printf("fi_FI: %s\n", l);
    }
}

// Output:
// en_US: [aaa, ämm, Azz]
// fi_FI: [aaa, Azz, ämm]
</code>```

Body:
I am using the Comparator interface to sort objects in ascending order using following code fragment:

final List<LinkModelSpi> documentLinks = this.documentLinksModelSpi.getDocumentLinks();

//Add This method for Sorting Document Link View Same Order. Now The application display same links order
// in catalogue administration edit drug window
if (Checks.checkNotNullAndNonEmpty(documentLinks)) {
  if (this.documentLinksModelSpi.getDocumentLinks().iterator().next() instanceof DocumentLinkModelSpi) {
    Collections.sort(documentLinks, (Comparator<? super LinkModelSpi>) new Comparator<DocumentLinkModelImpl>() {
      @Override
      public int compare(DocumentLinkModelImpl o1, DocumentLinkModelImpl o2) {
        return o1.getResource().compareTo(o2.getResource());
      }
    });
  } else {
    Collections.sort(documentLinks, (Comparator<? super LinkModelSpi>) new Comparator<LinkModelImpl>() {
      @Override
      public int compare(LinkModelImpl o1, LinkModelImpl o2) {
        return o1.getResource().compareTo(o2.getResource());
      }
    });
  }
}

//Collections.reverse(documentLinks);
for (final LinkModelSpi documentLinkModelSpi : documentLinks) {
  //noinspection unchecked
  ((DtoPresentationModelSpi<?, MDTO>) documentLinkModelSpi).addPropertyChangeListener(this);
}

The final result is this:

But I want to sort list like this:

Where the links are sorted regardless of case. How can I do this?

Body:
The generic solution is to use java.text.Collator, which is a specialised Comparator that not only handles uppercase/lowercase, but can also deal with diacritic signs (such as ä and ë) and knows about locale differences (e.g. most Western languages put the ë with the e, but Finland puts it after the z).

import java.text.Collator;
import java.util.*;

public class Example {
    public static void main(String[] args) {
        Collator en_US = Collator.getInstance(Locale.US);
        Collator fi_FI = Collator.getInstance(new Locale("fi", "FI"));

        // Optional configuration; read the Javadoc for more information
//        en_US.setStrength(Collator.PRIMARY);
//        en_US.setDecomposition(Collator.FULL_DECOMPOSITION);

        List l = new ArrayList(Arrays.asList("Azz", "ämm", "aaa"));
        Collections.sort(l, en_US);
        System.out.printf("en_US: %s\n", l);
        Collections.sort(l, fi_FI);
        System.out.printf("fi_FI: %s\n", l);
    }
}

// Output:
// en_US: [aaa, ämm, Azz]
// fi_FI: [aaa, Azz, ämm]


问:
TypeError: 'undefined' is not a function (evaluating '$(document)')

I'm using a WordPress site.

I'm including this script in the header.

When the script loads, I get this error:

TypeError: 'undefined' is not a function (evaluating '$(document)')

I have no idea what is causing it or what it even means.

In firebug, I get this:

$ is not a function

答:
You can pass $ in function()

```<code>jQuery(document).ready(function($){

// jQuery code is in here

});
</code>```

or you can replace $(document); with this jQuery(document);

or you can use jQuery.noConflict()

```<code>var jq=jQuery.noConflict();
jq(document).ready(function(){
  jq('selector').show();
});
</code>```

Body:
You can pass $ in function()

jQuery(document).ready(function($){

// jQuery code is in here

});

or you can replace $(document); with this jQuery(document);

or you can use jQuery.noConflict()

var jq=jQuery.noConflict();
jq(document).ready(function(){
  jq('selector').show();
});


问:
get next immediate same date using php

i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed

if i select 12 then output will be 2017-06-12 cause this date future date

final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month

i have tired but not working this

```<code>$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));
</code>```

or

```<code>$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));
</code>```

thanks in your advance

答:
Try this code :</p>

```<code><?php
$selected_date = '2017-06-05';
$current = date('Y-m-d');
//echo $current;
if($selected_date < $current)
{
    $newDate = date('Y-m-d',strtotime($selected_date."+1 month"));
    echo $newDate; // gives 2017-07-05
}else if($selected_date > $current)
{
    $newDate = $current;
    echo $newDate; // gives 2017-06-07
}
?>
</code>```

Title: get next immediate same date using php

Body:
i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed

if i select 12 then output will be 2017-06-12 cause this date future date

final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month

i have tired but not working this

$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));

or

$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));

thanks in your advance

Body:
Try this code :

<?php
$selected_date = '2017-06-05';
$current = date('Y-m-d');
//echo $current;
if($selected_date < $current)
{
    $newDate = date('Y-m-d',strtotime($selected_date."+1 month"));
    echo $newDate; // gives 2017-07-05
}else if($selected_date > $current)
{
    $newDate = $current;
    echo $newDate; // gives 2017-06-07
}
?>


问:
ActionScript 3: Adding multiple instances of the same object to the stage and removing each separately
I have a piece of code adding three insances of the same MovieClip to the stage. I also added MouseEvent.CLICK listener. Once any of the MovieClips gets clicked, I want it to be removed from the stage. My problem is, whenever any of the elements gets clicked, only the last one gets removed and when I click again on a different instance, I'm getting:

ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

I added these three MovieClips to an array, but I don't know how I can properly identify which instance got clicked and remove only the said instance.

This is the excerpt of code I have:

var myMC: SomeMC;
var myArray: Array = [];

function Loaded(e: Event): void {

 for (var i: int = 0; i < 3; i++) {

 myMC = new SomeMC();

 myMC.addEventListener(MouseEvent.CLICK, Clicked);

 myMC.y = 50;
 myMC.x = 50 * i;

 addChild(myMC);

 myArray.push(myMC);

 }
}

function  imageClicked(e: MouseEvent){

  // Only the last instance gets removed.

 e.currentTarget.parent.removeChild(myMC);

  }```

I'd be grateful for any help.

答:
In Loaded function you create 3 instances of the object, but by doing:

myMC = new SomeMC();

you overwrite reference. In first iteration myMC is 1st one, in 2nd 2nd one, etc...

Then in imageClicked you're trying to remove it. 1st time it's working because it's referencing the last object, but after you removed it from stage it won't work anymore.

How about changing e.currentTarget.parent.removeChild(myMC); to e.currentTarget.parent.removeChild(e.currentTarget); ? That should remove clicked one.

Body:
I have a piece of code adding three insances of the same MovieClip to the stage. I also added MouseEvent.CLICK listener. Once any of the MovieClips gets clicked, I want it to be removed from the stage. My problem is, whenever any of the elements gets clicked, only the last one gets removed and when I click again on a different instance, I'm getting:

ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

I added these three MovieClips to an array, but I don't know how I can properly identify which instance got clicked and remove only the said instance.

This is the excerpt of code I have:

var myMC: SomeMC;
var myArray: Array = [];

function Loaded(e: Event): void {

 for (var i: int = 0; i < 3; i++) {

 myMC = new SomeMC();

 myMC.addEventListener(MouseEvent.CLICK, Clicked);

 myMC.y = 50;
 myMC.x = 50 * i;

 addChild(myMC);

 myArray.push(myMC);

 }
}

function  imageClicked(e: MouseEvent){

  // Only the last instance gets removed.

 e.currentTarget.parent.removeChild(myMC);

  }

I'd be grateful for any help.


问:
using roles provider in mvc2 application
i  have function named  comments with attributes [Authorize(Roles="Admin,Users")].
I have edit button for comments. On the Edit function we have attribute [Authorize(Roles="Admin")]. When User tries to access i want to throw a custom error page.I am not using forms authentication just roles provider. How can i redirect to custom error page. </p>

答:
Write a custom attribute

eg

```<code>public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        private string[] UnAuthorizedRoles = new string[] { "USER" };

        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            bool authorized = true;
            foreach (string role in UnAuthorizedRoles)
            {
                if (httpContext.User.IsInRole(role))
                {
                    authorized = false;
                }
            }
            return authorized;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
           // send to custom error page
        }
    }
</code>```

Body:
Write a custom attribute

eg

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        private string[] UnAuthorizedRoles = new string[] { "USER" };

        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            bool authorized = true;
            foreach (string role in UnAuthorizedRoles)
            {
                if (httpContext.User.IsInRole(role))
                {
                    authorized = false;
                }
            }
            return authorized;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
           // send to custom error page
        }
    }


问:
Nginx Docker 400 Bad Request
I am currently trying to host nexus as a private registry for docker images within my organisation . My nginx configuration are as below .

```<code>user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    server {

            listen 6666;   ### Docker Hosted Repo HTTPS port
            server_name box.company.net;  ### Nexus Server
            keepalive_timeout 60;

            ssl on;
            ssl_certificate /etc/ssl/certs/nexus.crt;
            ssl_certificate_key /etc/ssl/certs/nexus.key;
            ssl_ciphers HIGH:!kEDH:!ADH:!MD5:@STRENGTH;
            ssl_session_cache shared:TLSSSL:16m;
            ssl_session_timeout 10m;
            ssl_prefer_server_ciphers on;

            client_max_body_size 0;
            chunked_transfer_encoding on;

            location /v2/ {

                    if ($http_user_agent ~ "^(docker\/1\.(3|4|5(?!\.[0-9]-dev))|Go ).*$" ) {
                    return 404;
                    }
                    error_log               /var/log/nginx/error.log debug;
                    access_log              /var/log/nginx/docker.log;
                    proxy_set_header        Host $http_host;
                    proxy_set_header        X-Real-IP $remote_addr;
                    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_set_header        X-Forwarded-Proto "https";
                    proxy_pass             http://box.company.net:4444/;
                    proxy_read_timeout      900;
        }

            location / {

                    error_log               /var/log/nginx/error.log debug;
                    access_log              /var/log/nginx/docker.log;
                    proxy_set_header        Host $http_host;
                    proxy_set_header        X-Real-IP $remote_addr;
                    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_set_header        X-Forwarded-Proto "https";
                    proxy_pass              http://box.company.net:4444/;
                    proxy_read_timeout      90;
        }
    }
</code>```

Have configured an hosted docker repo within nexus(running on port 4444) with https port 6666.

Currently we are able to login to docker registry .

[test@server ~]$ docker login -u admin -p admin123
  box.company.net:6666 Login Succeeded

But when we try to push tagged images to the nexus hosted docker registry it throws back 400 Bad Request error .

[test@server ~]$ docker push box.company.net:6666/alpine
  The push refers to a repository [box.company.net:6666/alpine]
  3fb66f713c9f: Preparing error parsing HTTP 400 response body: invalid
  character '<' looking for beginning of value: "\n\n\n\n  400 - Nexus Repository
  Manager\n  \n\n\n  \n
  (new
  Image).src=\"https://box.company.net:6666/favicon.ico?3.2.1-01\"</script>\n
  \n  https://box.company.net:6666/favicon-32x32.png?3.2.1-01\"
  sizes=\"32x32\">\n  https://box.company.net:6666/safari-pinned-tab.svg?3.2.1-01\" color=\"#5bbad5\">\n  https://box.company.net:6666/favicon-16x16.png?3.2.1-01\"
  sizes=\"16x16\">\n  https://box.company.net:6666/favicon.ico?3.2.1-01\">\n
  https://box.company.net:6666/mstile-144x144.png?3.2.1-01\">\n  \n\n  https://box.company.net:6666/static/css/nexus-content.css?3.2.1-01\"/>\n\n\n\n  https://box.company.net:6666\">\n    \n      https://box.company.net:6666/static/images/nexus.png?3.2.1-01\"/>\n
  \n    \n      \n        Nexus Repository Manager\n      \n
  \n        OSS 3.2.1-01\n      \n    \n
  \n\n\n\n  \n    https://box.company.net:6666/static/rapture/resources/icons/x32/exclamation.png?3.2.1-01\"/>\n
  Error 400\n    Bad Request\n  \n  \n    \n

  HTTP method POST is not supported by this URL\n    \n

  \n\n\n\n\n"

Am I missing some important nginx configuration? Or are my requests getting malformed.

答:
You're missing the namespace when pushing your image.

Take a look into the documentation (https://books.sonatype.com/nexus-book/3.0/reference/docker.html#_accessing_repositories):

```<code>docker <command> <nexus-hostname>:<repository-port>/<namespace>/<image>:<tag>
</code>```

You could try it with

```<code>docker push server.int.org.com:6666/alpine/alpine
</code>```

ContentLicense: CC BY-SA 4.0

Title: Nginx Docker 400 Bad Request

Body:
I am currently trying to host nexus as a private registry for docker images within my organisation . My nginx configuration are as below .

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    server {

            listen 6666;   ### Docker Hosted Repo HTTPS port
            server_name box.company.net;  ### Nexus Server
            keepalive_timeout 60;

            ssl on;
            ssl_certificate /etc/ssl/certs/nexus.crt;
            ssl_certificate_key /etc/ssl/certs/nexus.key;
            ssl_ciphers HIGH:!kEDH:!ADH:!MD5:@STRENGTH;
            ssl_session_cache shared:TLSSSL:16m;
            ssl_session_timeout 10m;
            ssl_prefer_server_ciphers on;

            client_max_body_size 0;
            chunked_transfer_encoding on;

            location /v2/ {

                    if ($http_user_agent ~ "^(docker\/1\.(3|4|5(?!\.[0-9]-dev))|Go ).*$" ) {
                    return 404;
                    }
                    error_log               /var/log/nginx/error.log debug;
                    access_log              /var/log/nginx/docker.log;
                    proxy_set_header        Host $http_host;
                    proxy_set_header        X-Real-IP $remote_addr;
                    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_set_header        X-Forwarded-Proto "https";
                    proxy_pass             http://box.company.net:4444/;
                    proxy_read_timeout      900;
        }

            location / {

                    error_log               /var/log/nginx/error.log debug;
                    access_log              /var/log/nginx/docker.log;
                    proxy_set_header        Host $http_host;
                    proxy_set_header        X-Real-IP $remote_addr;
                    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_set_header        X-Forwarded-Proto "https";
                    proxy_pass              http://box.company.net:4444/;
                    proxy_read_timeout      90;
        }
    }

Have configured an hosted docker repo within nexus(running on port 4444) with https port 6666.

Currently we are able to login to docker registry .

[test@server ~]$ docker login -u admin -p admin123
  box.company.net:6666 Login Succeeded

But when we try to push tagged images to the nexus hosted docker registry it throws back 400 Bad Request error .

[test@server ~]$ docker push box.company.net:6666/alpine
  The push refers to a repository [box.company.net:6666/alpine]
  3fb66f713c9f: Preparing error parsing HTTP 400 response body: invalid
  character '<' looking for beginning of value: "\n\n\n\n  400 - Nexus Repository
  Manager\n  \n\n\n  \n
  (new
  Image).src=\"https://box.company.net:6666/favicon.ico?3.2.1-01\"</script>\n
  \n  https://box.company.net:6666/favicon-32x32.png?3.2.1-01\"
  sizes=\"32x32\">\n  https://box.company.net:6666/safari-pinned-tab.svg?3.2.1-01\" color=\"#5bbad5\">\n  https://box.company.net:6666/favicon-16x16.png?3.2.1-01\"
  sizes=\"16x16\">\n  https://box.company.net:6666/favicon.ico?3.2.1-01\">\n
  https://box.company.net:6666/mstile-144x144.png?3.2.1-01\">\n  \n\n  https://box.company.net:6666/static/css/nexus-content.css?3.2.1-01\"/>\n\n\n\n  https://box.company.net:6666\">\n    \n      https://box.company.net:6666/static/images/nexus.png?3.2.1-01\"/>\n
  \n    \n      \n        Nexus Repository Manager\n      \n
  \n        OSS 3.2.1-01\n      \n    \n
  \n\n\n\n  \n    https://box.company.net:6666/static/rapture/resources/icons/x32/exclamation.png?3.2.1-01\"/>\n
  Error 400\n    Bad Request\n  \n  \n    \n

  HTTP method POST is not supported by this URL\n    \n

  \n\n\n\n\n"

Am I missing some important nginx configuration? Or are my requests getting malformed.

Body:
You're missing the namespace when pushing your image.

Take a look into the documentation (https://books.sonatype.com/nexus-book/3.0/reference/docker.html#_accessing_repositories):

docker <command> <nexus-hostname>:<repository-port>/<namespace>/<image>:<tag>

You could try it with

docker push server.int.org.com:6666/alpine/alpine


问:
AutoHotKey Copy Paste between windows
I'm trying to copy and paste between a Excell file and firefox browser the username and password, but when it switches back to the excel file, it's not copying the password, and pastes the username in the password field.

^z::

{

```<code>Send, {CTRLDOWN}c{CTRLUP}{RIGHT}{ALTDOWN}{TAB}{ALTUP}
sleep, 300
Send, {CTRLDOWN}v{CTRLUP}{TAB}{ALTDOWN}{TAB}{ALTUP}
sleep, 500
Send, {CTRLDOWN}c{CTRLUP}
sleep, 500
Send, {ALTDOWN}{TAB}{ALTUP}
Sleep, 300
Send, {CTRLDOWN}v{CTRLUP}{TAB}{SPACE}
</code>```

}

return

答:
You may try it:</p>

```<code>#c::
Send, {CTRLDOWN}c{CTRLUP}{ALTDOWN}{TAB}{ALTUP}
sleep, 300
Send, {CTRLDOWN}v{CTRLUP}{ENTER}{ALTDOWN}{TAB}{ALTUP}
return
</code>```

Title: AutoHotKey Copy Paste between windows

Body:
I'm trying to copy and paste between a Excell file and firefox browser the username and password, but when it switches back to the excel file, it's not copying the password, and pastes the username in the password field.

^z::

{

Send, {CTRLDOWN}c{CTRLUP}{RIGHT}{ALTDOWN}{TAB}{ALTUP}
sleep, 300
Send, {CTRLDOWN}v{CTRLUP}{TAB}{ALTDOWN}{TAB}{ALTUP}
sleep, 500
Send, {CTRLDOWN}c{CTRLUP}
sleep, 500
Send, {ALTDOWN}{TAB}{ALTUP}
Sleep, 300
Send, {CTRLDOWN}v{CTRLUP}{TAB}{SPACE}

}

return

Body:
You may try it:

#c::
Send, {CTRLDOWN}c{CTRLUP}{ALTDOWN}{TAB}{ALTUP}
sleep, 300
Send, {CTRLDOWN}v{CTRLUP}{ENTER}{ALTDOWN}{TAB}{ALTUP}
return


问:
php check username + need variable case insensitive to register in database
I have a file register.php for my site.

```<code>$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
while ($row = $result->fetch_object()) {
    if(empty($row->username)) {
        echo "different username. IS OK !!";
    } else {
        echo "<font color='red'>*</font>".$username."<font color='red'> : this username already exist in DB!!</font><br />";
    }
}
</code>```

Here I compare the ($username from form) with ($row->username from DB)
$row->username exist only if $username is already register. So, if this exist, will go on ELSE part.
If $row->username doesn't exist (is empty) , because SELECT from sql will find no attribute, my code must go on IF part and display this message "different username. IS OK !!"

Why IF part doesn't work? I know sql will return 0, or NULL or "" or something like this. If I put a username which is not already registered, the code don't show the specific message. Because in this part I want to change the message with the code which permit to register new username.

empty($row->username) is not really empty if SQL can't find something to return?

Another problem is : I have a registered username "Test". MySQL is not case-sensitive, but in php, I can register another username "test". The code in php will run as a new register, but in MySQL nothing will happening because "username is unique" there. So, in "check username" from above, I need to check 2 insensitive variables ($username and $row->username). Because if in DB I have Test, and I want to register new user "test", this code will let me to do it. I want to show a error message if this happening.

答:
i think you should covert your database and php variable into same case then compare it for checking.

```<code>$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT LCASE(username) AS username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', strtolower($username)); // used strtolower();
$stmt->execute();
</code>```

Try this code, hope this helps...

Body:
I have a file register.php for my site.

$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
while ($row = $result->fetch_object()) {
    if(empty($row->username)) {
        echo "different username. IS OK !!";
    } else {
        echo "*".$username." : this username already exist in DB!!
";
    }
}

Here I compare the ($username from form) with ($row->username from DB)
$row->username exist only if $username is already register. So, if this exist, will go on ELSE part.
If $row->username doesn't exist (is empty) , because SELECT from sql will find no attribute, my code must go on IF part and display this message "different username. IS OK !!"

Why IF part doesn't work? I know sql will return 0, or NULL or "" or something like this. If I put a username which is not already registered, the code don't show the specific message. Because in this part I want to change the message with the code which permit to register new username.

empty($row->username) is not really empty if SQL can't find something to return?

Another problem is : I have a registered username "Test". MySQL is not case-sensitive, but in php, I can register another username "test". The code in php will run as a new register, but in MySQL nothing will happening because "username is unique" there. So, in "check username" from above, I need to check 2 insensitive variables ($username and $row->username). Because if in DB I have Test, and I want to register new user "test", this code will let me to do it. I want to show a error message if this happening.

Body:
i think you should covert your database and php variable into same case then compare it for checking.

$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT LCASE(username) AS username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', strtolower($username)); // used strtolower();
$stmt->execute();

Try this code, hope this helps...


答:
All you need is to verify if no rows are returned.

```<code>$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$count = $stmt->num_rows;
if ($count == 0) {
    // Username not in table
} else {
    // Username already exists
]
</code>```

To be sure that all your usernames are lowercase, simply convert it to lowercase before inserting it.

```<code>$username = strtolower($username);
</code>```

Title: php check username + need variable case insensitive to register in database

Body:
All you need is to verify if no rows are returned.

$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$count = $stmt->num_rows;
if ($count == 0) {
    // Username not in table
} else {
    // Username already exists
]

To be sure that all your usernames are lowercase, simply convert it to lowercase before inserting it.

$username = strtolower($username);


问:
Regex for finding valid filename
I want to check whether a string is a file name (name DOT ext) or not.

Name of file cannot contain / ? * : ; { } \

Could you please suggest me the regex expression to use in preg_match()?

答:
Below the regex using for checking Unix filename in a Golang program :</p>

```<code>    reg := regexp.MustCompile("^/[[:print:]]+(/[[:print:]]+)*$")
</code>```

Title: Regex for finding valid filename

Body:
Below the regex using for checking Unix filename in a Golang program :

    reg := regexp.MustCompile("^/[[:print:]]+(/[[:print:]]+)*$")


问:
The name "X" does not exist in the namespace "using:Y"
After reading every article here and trying every suggested action I'm out of things to try:

I have a namespace issue in Visual Studio 2015 - in a XAML file in UWP.
The concrete error message is:

"The name "FieldManagementViewModel" does not exist in the namespace
  "using:StudyConfigurationClient.ViewModels"".

This is my XAML:

This is the structure to show, that the folder and file actually exists, folder structure equals namespaces in this project:

I've looked all references and namespaces through, I've repaired Visual Studio 2015, I've cleaned and rebuilt several times and changed platform for the build back and forth - I'm out of options.

答:
Just add this solution to this probelm:
- Close and re-open Visual Studio</p>


答:
From what you described in the points at beginning of the question, you could achieve it this way:

```<code>$selectedDate = new DateTime('2016-06-05 00:00:00');
$now = new DateTime('now');
$now->setTime(0, 0, 0);

if ($selectedDate < $now) { // Selected date is in past

    // Set month and year to current
    $selectedDate->setDate(
        date('Y'),
        date('m'),
        $selectedDate->format('d')
    );

    // Add 1 month
    $selectedDate->add(new DateInterval('P1M'));
}

// If selected date is current or in future we do nothing

echo $selectedDate->format('Y-m-d');
</code>```

For input 2017-06-05 it will return 2017-07-05 as expected, and for current or future date will return the date that was selected. Works also for any past date like 2016-04-05

Title: get next immediate same date using php

Body:
From what you described in the points at beginning of the question, you could achieve it this way:

$selectedDate = new DateTime('2016-06-05 00:00:00');
$now = new DateTime('now');
$now->setTime(0, 0, 0);

if ($selectedDate < $now) { // Selected date is in past

    // Set month and year to current
    $selectedDate->setDate(
        date('Y'),
        date('m'),
        $selectedDate->format('d')
    );

    // Add 1 month
    $selectedDate->add(new DateInterval('P1M'));
}

// If selected date is current or in future we do nothing

echo $selectedDate->format('Y-m-d');

For input 2017-06-05 it will return 2017-07-05 as expected, and for current or future date will return the date that was selected. Works also for any past date like 2016-04-05


问:
Test if a vector contains a given element
How to check if a vector contains a given value?</p>

答:
I will group the options based on output. Assume the following vector for all the examples.

```<code>v <- c('z', 'a','b','a','e')
</code>```

For checking presence:

%in%

```<code>> 'a' %in% v
[1] TRUE
</code>```

any()

```<code>> any('a'==v)
[1] TRUE
</code>```

is.element()

```<code>> is.element('a', v)
[1] TRUE
</code>```

For finding first occurance:

match()

```<code>> match('a', v)
[1] 2
</code>```

For finding all occurances as vector of indices:

which()

```<code>> which('a' == v)
[1] 2 4
</code>```

For finding all occurances as logical vector:

==

```<code>> 'a' == v
[1] FALSE  TRUE FALSE  TRUE FALSE
</code>```

Edit:
Removing grep() and grepl() from the list for reason mentioned in comments

Body:
I will group the options based on output. Assume the following vector for all the examples.

v <- c('z', 'a','b','a','e')

For checking presence:

%in%

> 'a' %in% v
[1] TRUE

any()

> any('a'==v)
[1] TRUE

is.element()

> is.element('a', v)
[1] TRUE

For finding first occurance:

match()

> match('a', v)
[1] 2

For finding all occurances as vector of indices:

which()

> which('a' == v)
[1] 2 4

For finding all occurances as logical vector:

==

> 'a' == v
[1] FALSE  TRUE FALSE  TRUE FALSE

Edit:
Removing grep() and grepl() from the list for reason mentioned in comments


问:
Jenkins2 Pipeline: deploy on tomcat
I'm a newbie on Jenkins Pipelines. I wrote this small Groovy script from pulling from git and compiling.

```<code>node('master') {
  def workspace = pwd()

  stage 'Git pull'
  git branch: 'develop',
  credentialsId: 'Cred_xxxx',
  url: 'https://xxxx/yyyy.git'

  stage 'Builing'
  def mvnHome = tool name: 'Maven3', type: 'hudson.tasks.Maven$MavenInstallation'
  sh "cd ${workspace}/tlt/; ${mvnHome}/bin/mvn install -Pdevelopment"
  sh "cd ${workspace}"
}
</code>```

Now I would like to deploy on Tomcat7 the file tlt/target/tlt.war.
The previous approach was to fill the "Deploy war/ear to container" plugin.
Now, I have no idea how to do this with Groovy.

Thanks

Riccardo

答:
Just you need to put the user, like this:

```<code>sshagent(['CREDENTIALS_ID']) {
    sh 'scp tlt/target/tlt.war root@some-remote-host:/LOCATION/TOMCAT/webapps/'
}
</code>```

Without user the task block in this step

Title: Jenkins2 Pipeline: deploy on tomcat

Body:
I'm a newbie on Jenkins Pipelines. I wrote this small Groovy script from pulling from git and compiling.

node('master') {
  def workspace = pwd()

  stage 'Git pull'
  git branch: 'develop',
  credentialsId: 'Cred_xxxx',
  url: 'https://xxxx/yyyy.git'

  stage 'Builing'
  def mvnHome = tool name: 'Maven3', type: 'hudson.tasks.Maven$MavenInstallation'
  sh "cd ${workspace}/tlt/; ${mvnHome}/bin/mvn install -Pdevelopment"
  sh "cd ${workspace}"
}

Now I would like to deploy on Tomcat7 the file tlt/target/tlt.war.
The previous approach was to fill the "Deploy war/ear to container" plugin.
Now, I have no idea how to do this with Groovy.

Thanks

Riccardo

Body:
Just you need to put the user, like this:

sshagent(['CREDENTIALS_ID']) {
    sh 'scp tlt/target/tlt.war root@some-remote-host:/LOCATION/TOMCAT/webapps/'
}

Without user the task block in this step


问:
Angular 4 Radio form controll not working properly
I have a radio button

```<code><div class="radio" *ngFor="let item of shipping?.availableOptions">
     <input type="radio" name="shipping"  value="{{item.id}}" [checked]="orderCheckoutRequest?.order?.shippingOptionId===item.id" formControlName="shipping">
                                            {{item.name}} <strong>( {{item.shippingCost.amount}} {{item.shippingCost.currency | lowercase}} )</strong>

</div>
</code>```

If i preselect this radio using [checked]="orderCheckoutRequest?.order?.shippingOptionId===item.id" radio button is indeed preselected, but angular form does not recognize it and form is invalid (because shipping option is required)

If i go another route and do something like this in my component:

```<code>const shippingControl = this.checkoutForm.get("shipping");
const selectedShippingOptionId = option['shippingOptionId'];
shippingControl.patchValue(selectedShippingOptionId);
</code>```

Then for angular form this is valid, because control has a value, but i have 2 problems :

When i render the view in browser button is not selected at all

I trigger another http request because in ngOnInit() i have subscribed to shippingControl like this :

shippingControl.valueChanges.skip(1).subscribe(data => {
this.cartService.updateShippingForOrder();
})

I have tried fixing this problem with skip(1) but this is not honored at all for some reason.
Thanks

答:
Push one flag , say "radioSelected" to shipping?.availableOptions array.
By default set its value to false.
Once orderCheckoutRequest?.order?.shippingOptionId===item.id
   satisfies, then update the corresponding "radioSelected" value to true.

Change the html template [checked] with

```<code><input type="radio" name="shipping"  value="{{item.id}}" [checked]="item.radioSelected" formControlName="shipping">
</code>```

Body:
I have a radio button

     <input type="radio" name="shipping"  value="{{item.id}}" [checked]="orderCheckoutRequest?.order?.shippingOptionId===item.id" formControlName="shipping">
                                            {{item.name}} ( {{item.shippingCost.amount}} {{item.shippingCost.currency | lowercase}} )

If i preselect this radio using [checked]="orderCheckoutRequest?.order?.shippingOptionId===item.id" radio button is indeed preselected, but angular form does not recognize it and form is invalid (because shipping option is required)

If i go another route and do something like this in my component:

const shippingControl = this.checkoutForm.get("shipping");
const selectedShippingOptionId = option['shippingOptionId'];
shippingControl.patchValue(selectedShippingOptionId);

Then for angular form this is valid, because control has a value, but i have 2 problems :

When i render the view in browser button is not selected at all

I trigger another http request because in ngOnInit() i have subscribed to shippingControl like this :

shippingControl.valueChanges.skip(1).subscribe(data => {
this.cartService.updateShippingForOrder();
})

I have tried fixing this problem with skip(1) but this is not honored at all for some reason.
Thanks

Body:
Push one flag , say "radioSelected" to shipping?.availableOptions array.
By default set its value to false.
Once orderCheckoutRequest?.order?.shippingOptionId===item.id
   satisfies, then update the corresponding "radioSelected" value to true.

Change the html template [checked] with

<input type="radio" name="shipping"  value="{{item.id}}" [checked]="item.radioSelected" formControlName="shipping">


问:
get title of items selected using TAB button, on a web page
I have a web application with no images in it. It is for visually impaired people. It is navigated using TAB button. How can I get the title/text of the selected web page like button,menu,etc. By selected I mean using TAB button, not mouse click. Using Javascript or any other language. </p>

答:
Use .focusin() method of jQuery library. Try to navigate on the form inputs from the snippet below using TAB button.

$(document).focusin(function(e) {
  console.log(e.target.name);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
  <input type="text" name="input1"/>
  <input type="text" name="input2"/>
  <input type="text" name="input3"/>
</form></code>```

I used name property of the event target in my example, but you could get any property value. For example

```<code>$(document).focusin(function(e) {
  console.log($(e.target).attr("type"));
});
</code>```

It is possible to get id and another info by same way.

Body:
Use .focusin() method of jQuery library. Try to navigate on the form inputs from the snippet below using TAB button.

$(document).focusin(function(e) {
  console.log(e.target.name);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
  <input type="text" name="input1"/>
  <input type="text" name="input2"/>
  <input type="text" name="input3"/>
</form>

I used name property of the event target in my example, but you could get any property value. For example

$(document).focusin(function(e) {
  console.log($(e.target).attr("type"));
});

It is possible to get id and another info by same way.


问:
I'm getting problem when setting the height of label dynamically
I'm setting the tableView cells height dynamically according to labels height and labels height according to text. It is working fine when I had given text with spaces (ex: This is Question for stackoverflow). But when I'm entering text of length two lines without spaces(ex ThisisQuestionforstackoverflow) . It is taking two lines and the text is starting from second line and cutting at the end.It taking first line full space and second line like(ThisisQuestionfor.....).

I'm using methods

+(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width:(UILineBreakMode)lineBreakMode

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

In cellForRowAtIndexPath

```<code>float productNameHeight = [DetailsViewController calculateHeightOfTextFromWidth:warObj1.productName :valueFont : valueWidth :UILineBreakModeWordWrap];
UILabel *productNameValue = [[UILabel alloc] initWithFrame:CGRectMake(xCoordinateStartLocatioForValue,yCoordinateStartLocation,valueWidth,productNameHeight)];
</code>```

Can u plz help me quickly.Thanks in advance

答: If there are no spaces in you text, be sure to use UILineBreakModeCharacterWrap or UILineBreakModeClip when both calculating the size of the UILabel and for the lineBreakMode property of the UILabel itself.

Body:
I'm setting the tableView cells height dynamically according to labels height and labels height according to text. It is working fine when I had given text with spaces (ex: This is Question for stackoverflow). But when I'm entering text of length two lines without spaces(ex ThisisQuestionforstackoverflow) . It is taking two lines and the text is starting from second line and cutting at the end.It taking first line full space and second line like(ThisisQuestionfor.....).

I'm using methods

+(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width:(UILineBreakMode)lineBreakMode

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

In cellForRowAtIndexPath

float productNameHeight = [DetailsViewController calculateHeightOfTextFromWidth:warObj1.productName :valueFont : valueWidth :UILineBreakModeWordWrap];
UILabel *productNameValue = [[UILabel alloc] initWithFrame:CGRectMake(xCoordinateStartLocatioForValue,yCoordinateStartLocation,valueWidth,productNameHeight)];

Can u plz help me quickly.Thanks in advance


问:
vertically align two different classes next to each other with css
How can I align two div's with different classes together above another?

If I have the following code:

```<code><div class="div1">
</div>
<div class="div2">
</div>
<div class="div3">
</div>
</code>```

how can I align div1 and div3 next to each other? and above the div1? Is it possible only with html and css?
thanks in advance

答:
Wrap them with a flexbox container, and change the order of the elements:

.container {
  display: flex;
  flex-wrap: wrap;
}

.container > div {
  line-height: 40px;
  text-align: center;
}

.div1 {
  order: 1;
  width: 50%;
  background: red;
}

.div2 {
  order: 3;
  width: 100%;
  background: blue;
}

.div3 {
  order: 2;
  width: 50%;
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="div1">
  1
  </div>
  <div class="div2">
  2
  </div>
  <div class="div3">
  3
  </div>
</div></code>```

Body:
How can I align two div's with different classes together above another?

If I have the following code:

how can I align div1 and div3 next to each other? and above the div1? Is it possible only with html and css?
thanks in advance

Body:
Wrap them with a flexbox container, and change the order of the elements:

.container {
  display: flex;
  flex-wrap: wrap;
}

.container > div {
  line-height: 40px;
  text-align: center;
}

.div1 {
  order: 1;
  width: 50%;
  background: red;
}

.div2 {
  order: 3;
  width: 100%;
  background: blue;
}

.div3 {
  order: 2;
  width: 50%;
  background: yellow;
}

<div class="container">
  <div class="div1">
  1
  </div>
  <div class="div2">
  2
  </div>
  <div class="div3">
  3
  </div>
</div>


问:
Is it possible to iterate an mpl::vector at run time without instantiating the types in the vector?
Generally, I would use boost::mpl::for_each<>() to traverse a boost::mpl::vector, but this requires a functor with a template function declared like the following:

template<typename T> void operator()(T&){T::staticCall();}

My problem with this is that I don't want the object T to be instantiated by for_each<>. I don't need the T parameter in the operator() at all. Is there a way to accomplish this, or an alternative to for_each<> that doesn't pass an object of type T to the template function?

Optimally, I would like the operator() definition to look like this:

template<typename T> void operator()(){T::staticCall();}

And of course, I don't want T to be instantiated at all prior to the call. Any other tips/suggestions are also welcome.

答:
I liked (up-voted) the solution with pointer and own defined *_for_each function. Here is an alternative using type wrapper for T if the goal is to avoid object creation till it is needed. </p>

```<code>template<typename T>
struct Wrapper
{
  typedef T type;
};

struct Functor
{
  template<typename T> void operator()(T t)
  {
    T::type obj(1);
    T::type::static_fuc();
  }
};

struct T1
{
  T1(int a) : m_a(a) { }
  int m_a;
  static inline void static_fuc() { }
};
struct T2
{
  T2(int a) : m_a(a) { }
  int m_a;
  static inline void static_fuc() { }
};

void fun()
{
  namespace mpl=boost::mpl;
  typedef mpl::vector<Wrapper<T1>,Wrapper<T2> > t_vec;
  mpl::for_each<t_vec>(Functor());
}
</code>```

Body:
I liked (up-voted) the solution with pointer and own defined *_for_each function. Here is an alternative using type wrapper for T if the goal is to avoid object creation till it is needed.

template<typename T>
struct Wrapper
{
  typedef T type;
};

struct Functor
{
  template<typename T> void operator()(T t)
  {
    T::type obj(1);
    T::type::static_fuc();
  }
};

struct T1
{
  T1(int a) : m_a(a) { }
  int m_a;
  static inline void static_fuc() { }
};
struct T2
{
  T2(int a) : m_a(a) { }
  int m_a;
  static inline void static_fuc() { }
};

void fun()
{
  namespace mpl=boost::mpl;
  typedef mpl::vector<Wrapper<T1>,Wrapper<T2> > t_vec;
  mpl::for_each<t_vec>(Functor());
}


问:
Time and Date getHour(), getDay() etc... still work on Android 2.3 and 3.0?
these methods are deprecated... but... still work on android 2.3 or 3.0 ?

i'm sure they work on 2.1, cause i tested it on my android phone, but works also in 2.3 or 3.0 ?

答: To add a little, in the Java world, @Deprecated is here to indicate methods you should not use. They still work, for compatibility reasons, but you are advised not to used them. Moreover, as fornwall said, these are old Java 1.1 methods, not Android-specific ones.


问:
ASyncTask load GridView thumbnails loads latest file twice, then slowly loads from the top of the list
I'm using an ASyncTask to load my thumbnails in a GridView layout that I have, but when I refresh the data, the thumbnails load in an odd order. It always loads the last element first, but it renders it with the first elements thumbnail, then re-renders it with the proper thumbnail (the last elements), then it properly loads every other thumbnail from first to second-last. It also reloads the images many times and is fairly slow at loading them (16mp images however)

Here's my GridView adapter (with the ASyncTask).

```<code>public class ReceiptListAdapter extends ArrayAdapter {

    public ReceiptListAdapter(Context context, ArrayList<Receipt> receipts){
        super(context, 0, receipts);
//        getItem(1);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder holder;

        // Lookup view for data population
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.receipt_list_element, parent, false);
            holder = new ViewHolder();
            // Populate the data into the template view using the data object
            holder.title = (TextView) convertView.findViewById(R.id.TitleView);
            holder.date = (TextView) convertView.findViewById(R.id.DateView);
            holder.image = (ImageView) convertView.findViewById(R.id.containerImage);
            holder.spn = (ProgressBar) convertView.findViewById(R.id.spinner);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Receipt receipt = (Receipt) getItem(position);
        holder.imagePath = receipt.getFilepath();
        final int tWidth = receipt.getWidth();

        // manipulate data here...
        holder.spn.setVisibility(View.VISIBLE);
        holder.image.setVisibility(View.GONE);
        holder.title.setText(receipt.getDesc());

        new AsyncTask<ViewHolder, Void, Bitmap>() {

            private ViewHolder h;

            @Override
            protected Bitmap doInBackground(ViewHolder... t) {
                h = t[0];
                Bitmap thumb = ExifUtil.rotateBitmap(h.imagePath, ThumbnailUtils.extractThumbnail(
                        BitmapFactory.decodeFile(h.imagePath),
                        tWidth,
                        tWidth));
                return thumb;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);

                    h.spn.setVisibility(View.GONE);
                    h.image.setVisibility(View.VISIBLE);
                    h.image.setImageBitmap(result);

            }
        }.execute(holder);

        // Return the completed view to render on screen
        return convertView;
    }

    static class ViewHolder {
        private TextView title;
        private TextView date;
        private ImageView image;
        private String imagePath;
        private ProgressBar spn;
    }

}
</code>```

答:
Instead of directly solving this issue, I would propose two things:
1. Use RecyclerView and RecyclerView.Adapter instead of what you have now. 2. Use an image loading library like Picasso or Glide instead of loading it in an AsyncTask. You have many things to consider when loading things asynchronously yourself, and a library already takes care of many possible errors.

See how to implement a ViewHolder pattern with RecyclerView here: https://guides.codepath.com/android/using-the-recyclerview

Body:
I'm using an ASyncTask to load my thumbnails in a GridView layout that I have, but when I refresh the data, the thumbnails load in an odd order. It always loads the last element first, but it renders it with the first elements thumbnail, then re-renders it with the proper thumbnail (the last elements), then it properly loads every other thumbnail from first to second-last. It also reloads the images many times and is fairly slow at loading them (16mp images however)

Here's my GridView adapter (with the ASyncTask).

public class ReceiptListAdapter extends ArrayAdapter {

    public ReceiptListAdapter(Context context, ArrayList<Receipt> receipts){
        super(context, 0, receipts);
//        getItem(1);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder holder;

        // Lookup view for data population
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.receipt_list_element, parent, false);
            holder = new ViewHolder();
            // Populate the data into the template view using the data object
            holder.title = (TextView) convertView.findViewById(R.id.TitleView);
            holder.date = (TextView) convertView.findViewById(R.id.DateView);
            holder.image = (ImageView) convertView.findViewById(R.id.containerImage);
            holder.spn = (ProgressBar) convertView.findViewById(R.id.spinner);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Receipt receipt = (Receipt) getItem(position);
        holder.imagePath = receipt.getFilepath();
        final int tWidth = receipt.getWidth();

        // manipulate data here...
        holder.spn.setVisibility(View.VISIBLE);
        holder.image.setVisibility(View.GONE);
        holder.title.setText(receipt.getDesc());

        new AsyncTask<ViewHolder, Void, Bitmap>() {

            private ViewHolder h;

            @Override
            protected Bitmap doInBackground(ViewHolder... t) {
                h = t[0];
                Bitmap thumb = ExifUtil.rotateBitmap(h.imagePath, ThumbnailUtils.extractThumbnail(
                        BitmapFactory.decodeFile(h.imagePath),
                        tWidth,
                        tWidth));
                return thumb;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);

                    h.spn.setVisibility(View.GONE);
                    h.image.setVisibility(View.VISIBLE);
                    h.image.setImageBitmap(result);

            }
        }.execute(holder);

        // Return the completed view to render on screen
        return convertView;
    }

    static class ViewHolder {
        private TextView title;
        private TextView date;
        private ImageView image;
        private String imagePath;
        private ProgressBar spn;
    }

}


问:
NSString append WhiteSpace for every 4 Character
I have a string like @"1234123412341234", i need to append space between every 4 chars like.

```<code>@"1234 1234 1234 1234"
</code>```

i.e, I need a NSString like Visa Card Type. I have tried like this but i didn't get my result.

```<code>-(void)resetCardNumberAsVisa:(NSString*)aNumber
{
  NSMutableString *s = [aNumber mutableCopy];

  for(int p=0; p<[s length]; p++)
  {
    if(p%4==0)
    {
        [s insertString:@" " atIndex:p];
    }
  }
  NSLog(@"%@",s);
}
</code>```

答:
swift3 based on Droppy</p>

```<code>func codeFormat(_ code: String) -> String {
    let newStr = NSMutableString()
    for i in 0..<code.characters.count {
        if (i > 0 && i % 4 == 0){
            newStr.append(" ")
        }
            var c = (code as NSString).character(at: i)
            newStr.append(NSString(characters: &c, length: 1) as String)
    }
    return newStr as String
}
</code>```

Body:
I have a string like @"1234123412341234", i need to append space between every 4 chars like.

@"1234 1234 1234 1234"

i.e, I need a NSString like Visa Card Type. I have tried like this but i didn't get my result.

-(void)resetCardNumberAsVisa:(NSString*)aNumber
{
  NSMutableString *s = [aNumber mutableCopy];

  for(int p=0; p<[s length]; p++)
  {
    if(p%4==0)
    {
        [s insertString:@" " atIndex:p];
    }
  }
  NSLog(@"%@",s);
}

Body:
swift3 based on Droppy

func codeFormat(_ code: String) -> String {
    let newStr = NSMutableString()
    for i in 0..<code.characters.count {
        if (i > 0 && i % 4 == 0){
            newStr.append(" ")
        }
            var c = (code as NSString).character(at: i)
            newStr.append(NSString(characters: &c, length: 1) as String)
    }
    return newStr as String
}


问:
bind dynamic menu from database to a layout page and show it for all the pages of asp net core
I have a layout page in asp net core application.And I want to bind dynamic menu from database to it which is shown on all the pages of the project having various controllers and models as well. Here is my code for layout page:-

```<code> @Html.Partial("_Menu", Model)
</code>```

here is my partial view page named _Menu:-

```<code>@if (ViewBag.Industries != null)
{
    @foreach (var items in ViewBag.Industries)
    {
        <li class="level0 parent drop-menu">
            <a href="index.html"><span>@items.IndustryName</span></a>
            <ul class="level1">
                @foreach (var subitems in items.MasterProductCategory)
                {
                    <li class="level1 first parent"><a href="404error.html"><span>@subitems.CategoryName</span></a></li>
                }
            </ul>
        </li>
    }
}
</code>```

and here is my controller for fetching the menu items in home controller:-

```<code>public ActionResult _Menu()
        {
            ViewBag.Industries = _context.MasterIndustry.Include(u => u.MasterProductCategory).ToList();
            return PartialView("_Menu", ViewBag.Industries);
        }
</code>```

The Issue is that While debugging the solution it is moving from layout page to the partial page but it is not invoking the menu controller.and giving result that viewBag.Industry is empty.where i have to write menu controller so that for every page and every controller it invokes menu controller to get the desired result. Or if there is any better way to solve this. Please let me know.

答: Partial Views dont using self controllers. Use View Component and then invoke to your layout

Body:
I have a layout page in asp net core application.And I want to bind dynamic menu from database to it which is shown on all the pages of the project having various controllers and models as well. Here is my code for layout page:-

 @Html.Partial("_Menu", Model)

here is my partial view page named _Menu:-

@if (ViewBag.Industries != null)
{
    @foreach (var items in ViewBag.Industries)
    {

            @items.IndustryName

                @foreach (var subitems in items.MasterProductCategory)
                {

@subitems.CategoryName

                }

    }
}

and here is my controller for fetching the menu items in home controller:-

public ActionResult _Menu()
        {
            ViewBag.Industries = _context.MasterIndustry.Include(u => u.MasterProductCategory).ToList();
            return PartialView("_Menu", ViewBag.Industries);
        }

The Issue is that While debugging the solution it is moving from layout page to the partial page but it is not invoking the menu controller.and giving result that viewBag.Industry is empty.where i have to write menu controller so that for every page and every controller it invokes menu controller to get the desired result. Or if there is any better way to solve this. Please let me know.


问:
Using Jquery/Ajax to display a result of codeigniter function in view
I'm currently working on a project by using codeigniter. Where I have a view page called dashboard.php. In dashboard, my task is to display a graph. From dashbord.php I'm calling the controller function which is stat(). I have created the graph using Morris.js and which is located in stat.php.

controller function stat()

```<code>  public function stat()
  {
    $this->load->view('template/admin_header', $data);
    $this->load->view('merchant/stat', $data);
    $this->load->view('template/footer', $data);
  }
</code>```

view page stat.php

```<code><script>
$(function() {
     Morris.Area({
        element: 'morris-area-chart-scan-payment',
        data: [
        {
            period: 'Mon',
            spoint: 2666,
            mpayment: null,
        },
        {
            period: 'Tue',
            spoint: 2778,
            mpayment: 1350,
        },
        {
            period: 'Wed',
            spoint: 4912,
            mpayment: 1969,
        }
      ],

      xkey: 'period',
     ykeys: ['spoint', 'mpayment'],
     labels: ['Scan Point', 'Payment'],
     parseTime: false,
     pointSize: 2,
     hideHover: 'auto',
     resize: true
     });
  });
 </script>

 <div id="morris-area-chart-scan-payment"></div>
</code>```

dashboard.php the view page

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

I have created a div tag in the view page dashboard.php. How can I display the graph in stat.php in dashboard.php using JQuery/Ajax ?

答:
where is your callback URL ?

you must set a callback url where you want to sent the data and receive the value .

Body:
I'm currently working on a project by using codeigniter. Where I have a view page called dashboard.php. In dashboard, my task is to display a graph. From dashbord.php I'm calling the controller function which is stat(). I have created the graph using Morris.js and which is located in stat.php.

controller function stat()

  public function stat()
  {
    $this->load->view('template/admin_header', $data);
    $this->load->view('merchant/stat', $data);
    $this->load->view('template/footer', $data);
  }

view page stat.php

dashboard.php the view page

I have created a div tag in the view page dashboard.php. How can I display the graph in stat.php in dashboard.php using JQuery/Ajax ?


问:
Using javax.ws.rs.core.Response.readEntity to extract a list of strings from a JSON object
If my response is like:

```<code>{
  "values": [ "1", "2" ]
}
</code>```

How should I use readEntity to populate a List<String> with the values: 1, 2?

答:
You can read the entity as a Map<String, List<String>>:

Map<String, List<String>> map =
    response.readEntity(new GenericType<Map<String, List<String>>>() { });
List<String> values = map.get("values");
```

<p>Or define your own POJO:</p>

<pre class="lang-java prettyprint-override"><code>public class MyBean {

    private List<String> values;

    // Getters and setters
}
</code>```

List<String> values = response.readEntity(MyBean.class).getValues();
```

You obviously must have a JSON provider such as Jackson registered.

Body:
If my response is like:

{
  "values": [ "1", "2" ]
}

How should I use readEntity to populate a List<String> with the values: 1, 2?

Body:
You can read the entity as a Map<String, List<String>>:

Map<String, List<String>> map =
    response.readEntity(new GenericType<Map<String, List<String>>>() { });
List<String> values = map.get("values");

Or define your own POJO:

public class MyBean {

    private List<String> values;

    // Getters and setters
}

List<String> values = response.readEntity(MyBean.class).getValues();

You obviously must have a JSON provider such as Jackson registered.


问:
Is there a jquery micro-architecture similar to cairngorm for Flex?
Is there a jquery micro-architecture similar to cairngorm for Flex? That helps development a lot. It makes it more disciplined, and layers out the code.

Is there a good starting point that I have to look up, before starting coding in jquery. I would like the code to be extensible and maintainable.

答:
Recently, I stumbled upon backbone.js - http://documentcloud.github.com/backbone/

Though not as full fledged as cairngorm, it is different, and interesting.


问:
Deploy Flask app on AWS EC2
I'm trying to deploy a simple Flask app on EC2.
Everything works fine, but when I try to access to my site I get a 404 error that says:

The requested URL /flaskapp.py/flaskapp.wsgi/ was not found on this server.

flaskapp.py code:

```<code>from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "hello"

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=80)
</code>```

flaskapp.wsgi:

```<code>import sys
sys.path.insert(0, '/var/www/html/flaskapp')

from flaskapp import app as application
</code>```

And finally the file 000-default.conf

```<code> <VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName myServerHostname
    DocumentRoot /var/www/
    WSGIDaemonProcess flaskapp threads=5
    WSGIScriptAlias / /var/www/html/flaskapp/flaskapp.wsgi

<Directory flaskapp>
    WSGIProcessGroup flaskapp
    WSGIApplicationGroup %{GLOBAL}
    Order deny,allow
    Allow from all
</Directory>

    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
        # This directive allows us to have apache2's default start page
                # in /apache2-default/, but still have / go to the right place
                #RedirectMatch ^/$ /apache2-default/
    </Directory>

    ErrorLog /var/log/apache2/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog /var/log/apache2/access.log combined
    ServerSignature On

</VirtualHost>
</code>```

Is this code wrong?
What can I do to fix it?
Thanks to everyone!

答:
Simplest way to run a basic Flask app om EC2 :

1) application = app = Flask(--name--underscore as usual)
....
....
application.run()

2) save the file as "application.py"

3) Zip the project with requirement.txt and upload the zip file through AWS EB concole.

It will run.

Title: Deploy Flask app on AWS EC2

Body:
I'm trying to deploy a simple Flask app on EC2.
Everything works fine, but when I try to access to my site I get a 404 error that says:

The requested URL /flaskapp.py/flaskapp.wsgi/ was not found on this server.

flaskapp.py code:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "hello"

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=80)

flaskapp.wsgi:

import sys
sys.path.insert(0, '/var/www/html/flaskapp')

from flaskapp import app as application

And finally the file 000-default.conf

 <VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName myServerHostname
    DocumentRoot /var/www/
    WSGIDaemonProcess flaskapp threads=5
    WSGIScriptAlias / /var/www/html/flaskapp/flaskapp.wsgi

<Directory flaskapp>
    WSGIProcessGroup flaskapp
    WSGIApplicationGroup %{GLOBAL}
    Order deny,allow
    Allow from all
</Directory>

    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
        # This directive allows us to have apache2's default start page
                # in /apache2-default/, but still have / go to the right place
                #RedirectMatch ^/$ /apache2-default/
    </Directory>

    ErrorLog /var/log/apache2/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog /var/log/apache2/access.log combined
    ServerSignature On

</VirtualHost>

Is this code wrong?
What can I do to fix it?
Thanks to everyone!


问:
VBA coed mandatory fields based off of specific data
I have created a form using Excel in column A11 I have a dropdown box with three options.  If one of these options are selected the entire row is required.  I have searched everywhere and cant find the right code. I am new to using VBA

```<code>Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

     Dim rsave As Range
     Dim cell As Range

     Set rsave = Sheet1.Range("B11)]")

     For Each cell In rsave

          If cell.Value <> "" And cell.Offset(0, 1).Value = "" Then

          Dim missdata
          missdata = MsgBox("Missing Data - Enter the Date for WorkBook to Save", vbOKOnly, "Missing Data")
          Cancel = True
          cell.Offset(0, 1).Select

      Exit For

      End If

      Next cell

 End Sub
</code>```

答:
This should do it. Set "SheetToCheck" to the sheet you wish to Check.
It will stop looping as soon as it has found a missing value and the MsgBox will give the 1st Range where it found a missing value.</p>

```<code>Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim ws As Worksheet
    Dim lastrow As Integer
    Dim CellToCheck As Range
    Dim exitLoops As Boolean
    Set ws = Worksheets("SheetToCheck")

    lastrow = ws.UsedRange.Rows.Count
    exitLoops = False

    With ws
        'Loop over rows:
        For i = 2 To lastrow
            If exitLoops = True Then Exit For

            If .Range("A" & i).value <> "" And .Range("A" & i).value <> "SELECT ONE" Then

                'Loop over cells in row:
                For Each CellToCheck In .Range("B" & i & ":K" & i)
                    If exitLoops = True Then Exit For
                    If CellToCheck.value = "" Then
                        Cancel = True
                        MsgBox "Missing Data in cell " & CellToCheck.Address
                        exitLoops = True
                    End If
                Next CellToCheck
            End If
        Next i
    End With
End Sub
</code>```

Body:
I have created a form using Excel in column A11 I have a dropdown box with three options.  If one of these options are selected the entire row is required.  I have searched everywhere and cant find the right code. I am new to using VBA

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

     Dim rsave As Range
     Dim cell As Range

     Set rsave = Sheet1.Range("B11)]")

     For Each cell In rsave

          If cell.Value <> "" And cell.Offset(0, 1).Value = "" Then

          Dim missdata
          missdata = MsgBox("Missing Data - Enter the Date for WorkBook to Save", vbOKOnly, "Missing Data")
          Cancel = True
          cell.Offset(0, 1).Select

      Exit For

      End If

      Next cell

 End Sub

Body:
This should do it. Set "SheetToCheck" to the sheet you wish to Check.
It will stop looping as soon as it has found a missing value and the MsgBox will give the 1st Range where it found a missing value.

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim ws As Worksheet
    Dim lastrow As Integer
    Dim CellToCheck As Range
    Dim exitLoops As Boolean
    Set ws = Worksheets("SheetToCheck")

    lastrow = ws.UsedRange.Rows.Count
    exitLoops = False

    With ws
        'Loop over rows:
        For i = 2 To lastrow
            If exitLoops = True Then Exit For

            If .Range("A" & i).value <> "" And .Range("A" & i).value <> "SELECT ONE" Then

                'Loop over cells in row:
                For Each CellToCheck In .Range("B" & i & ":K" & i)
                    If exitLoops = True Then Exit For
                    If CellToCheck.value = "" Then
                        Cancel = True
                        MsgBox "Missing Data in cell " & CellToCheck.Address
                        exitLoops = True
                    End If
                Next CellToCheck
            End If
        Next i
    End With
End Sub


问:
Twig javascript in included child
I have a question regarding adding javascript to child elements. How do you do that?

I have this setup:

base.html.twig:

```<code>{% block content %}
{% endblock content %}

{% block script %}
{% endblock script %}
</code>```

index.html.twig:

```<code>{% extends base.html.twig %}

{% include intro.html.twig %}

{% block content %}
<html></html>
{% endblock content %}

{% block script %}
<script></script>
{% endblock script %}
</code>```

intro.html.twig:

```<code>{% block script %}
<script></script>
{% endblock script %}
</code>```

I want to add more javascript files into the intro.html.twig file, but it doesn't append it to the script block in index.html.twig.

All help appreciated!

UPDATE
I want to send some parameters with intro.html.twig:

```<code>{% extends 'intro.html.twig' with {
'title': 'title',
'type': 'test',
} %}
</code>```

is this possible using extends, or can I only use with with include?

答:
index.html.twig

```<code>{% extends intro.html.twig %}

{% block content %}
    <html></html>
{% endblock content %}

{% block script %}
    {{ parent() }}
    <script></script>
{% endblock script %}
</code>```

intro.html.twig

```<code>{% extends base.html.twig %}

{% block script %}
    <script></script>
{% endblock script %}
</code>```

Title: Twig javascript in included child

Body:
I have a question regarding adding javascript to child elements. How do you do that?

I have this setup:

base.html.twig:

{% block content %}
{% endblock content %}

{% block script %}
{% endblock script %}

index.html.twig:

{% extends base.html.twig %}

{% include intro.html.twig %}

{% block content %}

{% endblock content %}

{% block script %}

{% endblock script %}

intro.html.twig:

{% block script %}

{% endblock script %}

I want to add more javascript files into the intro.html.twig file, but it doesn't append it to the script block in index.html.twig.

All help appreciated!

UPDATE
I want to send some parameters with intro.html.twig:

{% extends 'intro.html.twig' with {
'title': 'title',
'type': 'test',
} %}

is this possible using extends, or can I only use with with include?

Body:
index.html.twig

{% extends intro.html.twig %}

{% block content %}
    <html></html>
{% endblock content %}

{% block script %}
    {{ parent() }}
    <script></script>
{% endblock script %}

intro.html.twig

{% extends base.html.twig %}

{% block script %}
    <script></script>
{% endblock script %}


问:
Regular expressions to add classes to html tags
I am working on a reactjs project and have basic html coming through via json. I need to go back over the markup and append bootstrap classes to it so its styled properly on the page.

the current function

```<code>  const markupFormatting = (html) => {
    html = html.replace(/<p/g, '<p class="paragraph-margin-bottom-10 text--font-size-14 paragraph--justified"')
    html = html.replace(/<a/g, '<a class="text--font-size-14 hyperlink-primary"')
    return html
  }
</code>```

http://jsfiddle.net/0ht35rpb/64/

Is there a cleaner way of doing this?

答:
You can use it in this way:</p>

```<code>  var html1 = '<p>some test with a <a href="text">link</a></p><p>another paragraph with a <a href="test2">link</a></p>';

  function markupFormatting(html1){
    var e = document.createElement('div');
    e.innerHTML = html1;

    e.querySelectorAll('a').forEach(function(obj,i){obj.setAttribute("class", "abc")});

    return e;
  }

  console.log(markupFormatting(html1))
</code>```

Body:
I am working on a reactjs project and have basic html coming through via json. I need to go back over the markup and append bootstrap classes to it so its styled properly on the page.

the current function

  const markupFormatting = (html) => {
    html = html.replace(/<p/g, '<p class="paragraph-margin-bottom-10 text--font-size-14 paragraph--justified"')
    html = html.replace(/<a/g, '<a class="text--font-size-14 hyperlink-primary"')
    return html
  }

http://jsfiddle.net/0ht35rpb/64/

Is there a cleaner way of doing this?

Body:
You can use it in this way:

  var html1 = '<p>some test with a <a href="text">link</a></p><p>another paragraph with a <a href="test2">link</a></p>';

  function markupFormatting(html1){
    var e = document.createElement('div');
    e.innerHTML = html1;

    e.querySelectorAll('a').forEach(function(obj,i){obj.setAttribute("class", "abc")});

    return e;
  }

  console.log(markupFormatting(html1))


问:
check if function is a generator
I played with generators in Nodejs v0.11.2 and I'm wondering
how I can check that argument to my function is generator function.

I found this way typeof f === 'function' && Object.getPrototypeOf(f) !== Object.getPrototypeOf(Function) but I'm not sure if this is good (and working in future) way.

What is your opinion about this issue?

答:
As @Erik Arvidsson stated, there is no standard-way to check if a function is a generator function. But you can, for sure, just check for the interface, a generator function fulfills:

```<code>function* fibonacci(prevPrev, prev) {

  while (true) {

    let next = prevPrev + prev;

    yield next;

    prevPrev = prev;
    prev = next;
  }
}

// fetch get an instance
let fibonacciGenerator = fibonacci(2, 3)

// check the interface
if (typeof fibonacciGenerator[Symbol.iterator] == 'function' &&
    typeof fibonacciGenerator['next'] == 'function' &&
    typeof fibonacciGenerator['throw'] == 'function') {

  // it's safe to assume the function is a generator function or a shim that behaves like a generator function

  let nextValue = fibonacciGenerator.next().value; // 5
}
</code>```

Thats's it.

Title: check if function is a generator

Body:
As @Erik Arvidsson stated, there is no standard-way to check if a function is a generator function. But you can, for sure, just check for the interface, a generator function fulfills:

function* fibonacci(prevPrev, prev) {

  while (true) {

    let next = prevPrev + prev;

    yield next;

    prevPrev = prev;
    prev = next;
  }
}

// fetch get an instance
let fibonacciGenerator = fibonacci(2, 3)

// check the interface
if (typeof fibonacciGenerator[Symbol.iterator] == 'function' &&
    typeof fibonacciGenerator['next'] == 'function' &&
    typeof fibonacciGenerator['throw'] == 'function') {

  // it's safe to assume the function is a generator function or a shim that behaves like a generator function

  let nextValue = fibonacciGenerator.next().value; // 5
}

Thats's it.


问:
REST - Api design for posting a form data and fetching another resource
I am developing a feature, where a user requests some data by filling a form and posting it. The form contains user details (name, email, mobile etc.) and these details need to be saved in the database as a lead. Once the lead data is saved successfully then only the requested data will have to be retrieved from the database and shown to the user.

I started looking into this problem by dividing it into below two APIs and calling it sequentially

A POST API to create a lead resource.

A GET API to fetch the requested resource on the success of POST.

But then I realized that the solution will affect the speed of data retrieval as I will be doing two separate network request sequentially and I cannot compromise on speed.

How can I solve this problem without compromising on speed? Should I use POST request and return the requested data in its response?

P.S. I cannot call both the APIs in parallel

答: Yes, that's exactly what you should do - the POST request should respond with the newly created resource, that the client can subsequently use.</p>


问:
How do I convert "7-1-2014" to "07-01-2014" in MySQL Workbench?
I have already gone through part of the process to convert my text to a proper date:

7-jan -> 7-1 -> 7-1-2014
(note: dd-mm-yyyy)

However, I am now required to change the 7-1-2014 format to 07-01-2014 in order to change the text to a date.

Is there an easy way to do this?
Am not too experienced but have a basic understanding of queries and functions.

答:
you're looking for something like this : </p>

```<code>select STR_TO_DATE('7-1-2017', '%d-%m-%Y')
</code>```

Body:
you're looking for something like this :

select STR_TO_DATE('7-1-2017', '%d-%m-%Y')


问:
Detect Network Connection in Visual studio Xamarin crash android app
In my first Xamarin android app i stuck with another one problem.
When I try to check connection app is crashed.

```<code>ConnectivityManager cm = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo netInfo = cm.ActiveNetworkInfo;
if (netInfo.IsConnected)
{
  pictureSubText.Text = "Internet OK";
}
else
{
  pictureSubText.Text = "No Internet";
}
</code>```

When it's come to if(netInfo.IsConnected), App crashes and run again.
ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE and INTERNET are checked in manifest.
I'll be appreciated for any help.

--UPDATED--

Seems code I use are available only for API 21+
So another question - is it possible to check internet connection in API less than 21?

答:
Below link useful for you,

Add permissions also

https://forums.xamarin.com/discussion/comment/276931#Comment_276931

Body:
In my first Xamarin android app i stuck with another one problem.
When I try to check connection app is crashed.

ConnectivityManager cm = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo netInfo = cm.ActiveNetworkInfo;
if (netInfo.IsConnected)
{
  pictureSubText.Text = "Internet OK";
}
else
{
  pictureSubText.Text = "No Internet";
}

When it's come to if(netInfo.IsConnected), App crashes and run again.
ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE and INTERNET are checked in manifest.
I'll be appreciated for any help.

--UPDATED--

Seems code I use are available only for API 21+
So another question - is it possible to check internet connection in API less than 21?


问:
How is PDL used in real-world programming?
I've been reading code complete, not far in yet but one of the things it talks about is PDL - a higher level design language, which you write each routine in before coding in the language of choice.

I wondered if anyone actually did this in real life?  Another thing it says is to leave each line of PDL in the code as comments.  Surely that is overly verbose commenting?

I've never used PDL in real life, apart from perhaps something similar called ISWIM for a university class but I've never used it when writing my own code.

Surely if you write every routine/method/whatever in pseudo code first you will end up wasting a lot of time?

答: Writing things in pseudocode is very useful and you end up with the documentation already written ;-). It would decouple your intentions from your implementation, that many times is a optimized hack specific for your language or environment. Maintainers in the future or people refactoring your code or translating to other languages would be very grateful to you when you keep that pseudocode in the documentation. I have never called PDL, also because PDL in Perl means Perl Data Language, a very useful package to work with large datasets as vectors or matrices like in R. </p>

OwnerDisplayName: Adam Taylor