问:
Why isnt my css transition working?
I've looked over this simple code about hundred times, the transform property is working just fine, but its just snapping in place as if the transition property isnt working, what minor detail do I keep glossing over?
Here a jsfiddle with the transform property commented out.
https://jsfiddle.net/t8kbtjdy/30/</p>

```<code>#testItem{
  width: 100px;
  height: 100px;
  background-color: red;
  transform: rotate(45deg);
  transition: transform 1000ms ease-in-out 0ms;
}
</code>```

答:
the problem in your case is that you are loading your element in transformed state on your page so there is nothing to transition to.

In the example below I used hover to change the rotation:

#testItem{
  width: 100px;
  height: 100px;
  background-color: red;
  transition: transform 1000ms ease-in-out 0ms;
}
#testItem:hover{
  transform: rotate(45deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="t2">
  <div id="testItem"></div>
</div></code>```

However, if you want to see your transition on page load instead of :hover you need to use css animation

@keyframes rotateIt {
  0% {
    transform: rotate(0);
  }
  50% {
    transform: rotate(45deg);
  }
  100% {
    transform: rotate(0);
  }
}

#testItem{
  width: 100px;
  height: 100px;
  background-color: red;
  animation: rotateIt 1s infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="t2">
  <div id="testItem"></div>
</div></code>```

Title: Why isnt my css transition working?

Body:
I've looked over this simple code about hundred times, the transform property is working just fine, but its just snapping in place as if the transition property isnt working, what minor detail do I keep glossing over?
Here a jsfiddle with the transform property commented out.
https://jsfiddle.net/t8kbtjdy/30/

#testItem{
  width: 100px;
  height: 100px;
  background-color: red;
  transform: rotate(45deg);
  transition: transform 1000ms ease-in-out 0ms;
}

Body:
the problem in your case is that you are loading your element in transformed state on your page so there is nothing to transition to.

In the example below I used hover to change the rotation:

#testItem{
  width: 100px;
  height: 100px;
  background-color: red;
  transition: transform 1000ms ease-in-out 0ms;
}
#testItem:hover{
  transform: rotate(45deg);
}

<div id="t2">
  <div id="testItem"></div>
</div>

However, if you want to see your transition on page load instead of :hover you need to use css animation

@keyframes rotateIt {
  0% {
    transform: rotate(0);
  }
  50% {
    transform: rotate(45deg);
  }
  100% {
    transform: rotate(0);
  }
}

#testItem{
  width: 100px;
  height: 100px;
  background-color: red;
  animation: rotateIt 1s infinite;
}

<div id="t2">
  <div id="testItem"></div>
</div>


来源: stackexchange

问:
Python - Max and Min sorting
EDIT: testing out the maxxx function with new changes. output still the print statement in 2nd line. (no indentation errors thrown)
I need to sort this list using custom function (I cannot use built in functions).

When I run, it only outputs the second print statement. How can I make it work?

```<code>    nums = [0, 3.14159, 5, 1, 9, 2.71828, -1]
    print(nums)
    def maxxx():
        maxy = nums[0]
        for num in nums:
            if nums[i+1] > maxy:
                print("The maximum number in the list is:", maxy)
                return maxy
        maxxx()
    def minnn():
        miny = nums[1]
        while i in range (nums):
            if nums[i+1] < miny:
                return miny
            print ("The minimm number in the list is:", miny)
        minnn()
</code>```

答:
There's actually a decent number of issues.  Basically, your return was in the wrong spot, meaning it would only check the first element.  I'd recommend just reading through the following and comparing it with your own code.</p>

```<code>nums = [0, 3.14159, 5, 1, 9, 2.71828, -1]
def maxxx():
   maxy = nums[0]
   for num in nums:
      if num > maxy:
         maxy = num
   print("The maximum number in the list is:", maxy)
   return maxy
def minnn():
   miny = nums[0]
   for num in nums:
      if num < miny:
         miny = num
   print ("The minimm number in the list is:", miny)
   return miny

print(nums)
maxxx()
minnn()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python - Max and Min sorting

Body:
EDIT: testing out the maxxx function with new changes. output still the print statement in 2nd line. (no indentation errors thrown)
I need to sort this list using custom function (I cannot use built in functions).

When I run, it only outputs the second print statement. How can I make it work?

    nums = [0, 3.14159, 5, 1, 9, 2.71828, -1]
    print(nums)
    def maxxx():
        maxy = nums[0]
        for num in nums:
            if nums[i+1] > maxy:
                print("The maximum number in the list is:", maxy)
                return maxy
        maxxx()
    def minnn():
        miny = nums[1]
        while i in range (nums):
            if nums[i+1] < miny:
                return miny
            print ("The minimm number in the list is:", miny)
        minnn()

Body:
There's actually a decent number of issues.  Basically, your return was in the wrong spot, meaning it would only check the first element.  I'd recommend just reading through the following and comparing it with your own code.

nums = [0, 3.14159, 5, 1, 9, 2.71828, -1]
def maxxx():
   maxy = nums[0]
   for num in nums:
      if num > maxy:
         maxy = num
   print("The maximum number in the list is:", maxy)
   return maxy
def minnn():
   miny = nums[0]
   for num in nums:
      if num < miny:
         miny = num
   print ("The minimm number in the list is:", miny)
   return miny

print(nums)
maxxx()
minnn()


问:
How to get GCM ID using phonegap-plugin-push
I am trying to get GCM ID with the latest version of phonegap-plugin-push.

I have built many sample code from the internet but none of them are working.

I have followed the steps from phonegaptut.com, and phonegappro.com, and this phonegap-plugin-push example too.

I have followed the instructions carefully but the GCM ID is not there.

These are the steps I have taken:

I create new project on GCM and get the project number

cordova create GCM com.phonegaptut.gcm GCM

cd GCM

cordova platform add android

cordova plugin add phonegap-plugin-push --variable SENDER_ID="MY SENDER ID"

Edit Index.html

```<code><html>
<head>
    <title>PhonegapTut</title>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="jquery.js"></script>
    <style> textarea { width:100%; } </style>
    <script type="text/javascript">
        document.addEventListener("deviceready",onDeviceReady,false);

        function onDeviceReady(){
            console.log("Device Ready");
            var push = PushNotification.init({ "android": {"senderID": "MY SENDER ID"},"ios": {"alert": "true", "badge": "true", "sound": "true"}, "windows": {} } );

            push.on('registration', function(data) {
                console.log(data.registrationId);
                $("#gcm_id").val(data.registrationId);
            });

            push.on('notification', function(data) {
                console.log(data.message);
                alert(data.title+" Message: " +data.message);
                // data.title,
                // data.count,
                // data.sound,
                // data.image,
                // data.additionalData
            });

            push.on('error', function(e) {
                console.log(e.message);
            });
        }

    </script>
</head>
<body>
    <h2>Push Notification Example</h2>
    Your GCM ID : <br/>
    <textarea id="gcm_id" rows="10"></textarea>
</body>
</html>
</code>```

Cordova build android

Cordova run android –device

However, the GCM ID does not appear; can anyone see anything wrong with the code?

答:
Here's my solution

phonegap create my-app --template phonegap-template-push

phonegap platform add android

edit and replace SENDER_ID "XXXXXXX" with your GCM project number in config.xml

Blockquote

```<code><plugin name="phonegap-plugin-push" spec="1.6.0">
<param name="SENDER_ID" value="XXXXXXX" />
</plugin>
</code>```

edit and replace SENDER_ID "XXXXXXX" with your GCM project number in js/index.js file

Blockquote

```<code>var push = PushNotification.init({
android: {
senderID: "XXXXXXX"
},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
});'
</code>```

add a new code to set registration id

console.log('registration event: ' + data.registrationId);
document.getElementById("gcm_id").innerHTML = data.registrationId;

add
 in your index.html to display GCM ID

Blockquote

```<code><div id="gcm_id"> registration id: </div>
</code>```

phonegap build android

phonegap run android --device

and your GCM ID will be displayed inside the DIV

Body:
I am trying to get GCM ID with the latest version of phonegap-plugin-push.

I have built many sample code from the internet but none of them are working.

I have followed the steps from phonegaptut.com, and phonegappro.com, and this phonegap-plugin-push example too.

I have followed the instructions carefully but the GCM ID is not there.

These are the steps I have taken:

I create new project on GCM and get the project number

cordova create GCM com.phonegaptut.gcm GCM

cd GCM

cordova platform add android

cordova plugin add phonegap-plugin-push --variable SENDER_ID="MY SENDER ID"

Edit Index.html

    <title>PhonegapTut</title>

Push Notification Example

    Your GCM ID :

    <textarea id="gcm_id" rows="10"></textarea>

Cordova build android

Cordova run android –device

However, the GCM ID does not appear; can anyone see anything wrong with the code?

Body:
Here's my solution

phonegap create my-app --template phonegap-template-push

phonegap platform add android

edit and replace SENDER_ID "XXXXXXX" with your GCM project number in config.xml

Blockquote

<plugin name="phonegap-plugin-push" spec="1.6.0">
<param name="SENDER_ID" value="XXXXXXX" />
</plugin>

edit and replace SENDER_ID "XXXXXXX" with your GCM project number in js/index.js file

Blockquote

var push = PushNotification.init({
android: {
senderID: "XXXXXXX"
},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
});'

add a new code to set registration id

console.log('registration event: ' + data.registrationId);
document.getElementById("gcm_id").innerHTML = data.registrationId;

add < div > in your index.html to display GCM ID

Blockquote

<div id="gcm_id"> registration id: </div>

phonegap build android

phonegap run android --device

and your GCM ID will be displayed inside the DIV


问:
.htaccess error while forecefully accessing subdomains
I am using the current code for example.com

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]
</code>```

Which makes you add forefully https://www OR https:// if you have already put www.

The problem with this code is that even if i call subdomains like ex.example.com

it adds https://www.ex.example.com

what i want is for subdomain to redirect like this => https://ex.example.com

Please can anyone provide me a valid code ?

答:
To force https for subdomains , put the following right after RewriteEngine on line :

```<code>RewriteCond %{HTTPS}#%{HTTP_HOST} ^off#sub\.example\.com$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]
</code>```

This will redirect http://sub.example.com to https://sub.example.com . You have put this before your other HTTPS Redirect rule otherwise your rule will override this.

Body:
I am using the current code for example.com

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

Which makes you add forefully https://www OR https:// if you have already put www.

The problem with this code is that even if i call subdomains like ex.example.com

it adds https://www.ex.example.com

what i want is for subdomain to redirect like this => https://ex.example.com

Please can anyone provide me a valid code ?

Body:
To force https for subdomains , put the following right after RewriteEngine on line :

RewriteCond %{HTTPS}#%{HTTP_HOST} ^off#sub\.example\.com$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

This will redirect http://sub.example.com to https://sub.example.com . You have put this before your other HTTPS Redirect rule otherwise your rule will override this.


问:
While Loop Variable Initialization and Variable Types(C)
I'm relatively new to coding and am currently studying C. I had some trouble regarding a textbook exercise and some help would be much appreciated.

The exercise's main objective is to calculate the total salary that an employee should receive by inputting the hours of work done and the hourly rate. The rate is 100% up to 40 hours, but after 40 hours it goes up to 150%. Here's the code that I wrote:

```<code>#include <stdio.h>

int main (void) {
    int employee, hour, ratenormal, totalrate, counter, rate;
    int salary;

    hour = 1;

    while (hour != -1) {
        printf("Enter # of hours worked (-1 to end): ");
        scanf_s("%d", &hour);
        if (hour == -1) break;

        printf("Enter hourly rate of the work ($00.00): $");
        scanf_s("%d", &rate);

        if (hour <= 40) {
            salary = hour * rate;
        }
        else if (hour > 40) {
            salary = salary + ((hour - 40) * (rate * 1.5));
        }

        printf("Salary is $%d\n\n", salary);
    }

    return 0;
}
</code>```

I had a couple of questions:

1) If I declare the variable "salary" as a float, then the result only prints 0. Why is that?

2) The loop works fine, but only for the first iteration. The problem is that I need to initialize the variable salary again, otherwise it keeps storing some of the value that has been previously used. How could I do this?

Thank you for all the help!

答:
If you are using salary as float then you have to print</p>

```<code>printf("Salary is $%f\n\n", salary);
salary=0.0;
</code>```

Body:
I'm relatively new to coding and am currently studying C. I had some trouble regarding a textbook exercise and some help would be much appreciated.

The exercise's main objective is to calculate the total salary that an employee should receive by inputting the hours of work done and the hourly rate. The rate is 100% up to 40 hours, but after 40 hours it goes up to 150%. Here's the code that I wrote:

#include <stdio.h>

int main (void) {
    int employee, hour, ratenormal, totalrate, counter, rate;
    int salary;

    hour = 1;

    while (hour != -1) {
        printf("Enter # of hours worked (-1 to end): ");
        scanf_s("%d", &hour);
        if (hour == -1) break;

        printf("Enter hourly rate of the work ($00.00): $");
        scanf_s("%d", &rate);

        if (hour <= 40) {
            salary = hour * rate;
        }
        else if (hour > 40) {
            salary = salary + ((hour - 40) * (rate * 1.5));
        }

        printf("Salary is $%d\n\n", salary);
    }

    return 0;
}

I had a couple of questions:

1) If I declare the variable "salary" as a float, then the result only prints 0. Why is that?

2) The loop works fine, but only for the first iteration. The problem is that I need to initialize the variable salary again, otherwise it keeps storing some of the value that has been previously used. How could I do this?

Thank you for all the help!

Body:
If you are using salary as float then you have to print

printf("Salary is $%f\n\n", salary);
salary=0.0;


问:
Exporting the entire database for elastic search in csv
Any ideas on how to export the entire database in elastic search in csv? I just need one index to be exported.

I tried the following python plugin but elastic search as a service provider is complaining on root certificates:

https://github.com/taraslayshchuk/es2csv/blob/master/README.rst

es2csv -i leads -a user:password -u https://host.us-east-1.aws.found.io:9243 -q '' -o database.csv

but I get: elasticsearch.exceptions.ImproperlyConfigured: Root certificates are missing for certificate validation. Either pass them in using the ca_certs parameter or install certifi to use it automatically.

help? I'm using Elasticsearch.co as a service for my elastic search

答: The latest update of es2csv has a SSL patch, which should resolve your problem. </p>


问:
How to press back button on Whatsapp programmatically in Android?
I have made a Social Sharing Application for sharing images on different platforms Gmail,FB, Twitter, Whatsapp.

I am using Intent for whatsapp sharing . But i need Whatsapp to close after Sharing .

I am using a timer , on timer lapse i want to trigger the back button press so i can go back to Parent Activity.

Code :

```<code>      public  void sendWhatsapp() {
        final Dialog dialog1 = new Dialog(this);

        Log.d("LVMH", " opening MAIL dialog ");
        dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog1.setContentView(R.layout.whatsapp_layout);
        dialog1.getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        dialog1.setCanceledOnTouchOutside(true);
        dialog1.setCancelable(true);

        dialog1.setOnCancelListener(
                new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {

                        dialog1.dismiss();
                        Log.d("LVMH", " cancelled MAIL dialog ");

                    }
                }
        );

        //calling mail send button inside popup
        final Button whatsapp = (Button)dialog1.findViewById(R.id.buttonSend1);
        editTextEmail1 = (EditText) dialog1.findViewById(R.id.editTextMail1);
        editTextName1 = (EditText) dialog1.findViewById(R.id.editTextName1);

        final Button closeButton = (Button) dialog1.findViewById(R.id.btClose);

        closeButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Log.d("LVMH", "close button clicked ");

                //closeButton.setVisibility(GONE);
                dialog1.dismiss();
                sharingScreen();

            }
        });

        whatsapp.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                dialog1.dismiss();

                Log.d("LVMH", "mail button clicked ");

                final String email = editTextEmail1.getText().toString().trim();
                final String subject = editTextName1.getText().toString().trim();
                Log.d("lvmh","whatsapp number:"+email);
                Log.d("lvmh","whatsapp name:"+subject);
                addContact(subject,"+91"+email);

                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_TEXT,"hey , "+subject + "\nHere is your image from #IPL #RCB" );
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imagePath));
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                shareIntent.setType("image/*");
                shareIntent.setPackage("com.whatsapp");
                startActivity(shareIntent);

              Toast.makeText(getApplicationContext(), "Wait for Few seconds before your contact apperars in List , Your contact will be removed automatically.",
                        Toast.LENGTH_LONG).show();

                int FinishTime = 13;
                int countDownInterval = 1000;
                CountDownTimer   counterTimer = new CountDownTimer(FinishTime * 1000, countDownInterval) {
                    public void onFinish() {
                        //finish your activity here

                        deleteContact(getApplicationContext(),email,subject);
                        Log.d("LVMH", "Whats app finished");
                      //  this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
                      //  this.onBackPressed();
                        //finish();
                    }

                    public void onTick(long millisUntilFinished) {
                        //called every 1 sec coz countDownInterval = 1000 (1 sec)
                        Log.d("LVMH", "Ticks");
                    }
                };
                counterTimer.start();

// we will delete the numbers
                //

            }
        });
        dialog1.show();// opening mail dialog

    }
</code>```

Update : I am calling this fucntion from Oncreate (MainActivity ) on a event .

I have commented the different codes i have tried . Nothing worked .

Let me know any inputs ?

Thanks
NJ

答:
I am using Intent for whatsapp sharing . But i need Whatsapp to close after Sharing .

You can't control how other apps behave. You should wait until user press exit from whatsapp

Body:
I have made a Social Sharing Application for sharing images on different platforms Gmail,FB, Twitter, Whatsapp.

I am using Intent for whatsapp sharing . But i need Whatsapp to close after Sharing .

I am using a timer , on timer lapse i want to trigger the back button press so i can go back to Parent Activity.

Code :

      public  void sendWhatsapp() {
        final Dialog dialog1 = new Dialog(this);

        Log.d("LVMH", " opening MAIL dialog ");
        dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog1.setContentView(R.layout.whatsapp_layout);
        dialog1.getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        dialog1.setCanceledOnTouchOutside(true);
        dialog1.setCancelable(true);

        dialog1.setOnCancelListener(
                new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {

                        dialog1.dismiss();
                        Log.d("LVMH", " cancelled MAIL dialog ");

                    }
                }
        );

        //calling mail send button inside popup
        final Button whatsapp = (Button)dialog1.findViewById(R.id.buttonSend1);
        editTextEmail1 = (EditText) dialog1.findViewById(R.id.editTextMail1);
        editTextName1 = (EditText) dialog1.findViewById(R.id.editTextName1);

        final Button closeButton = (Button) dialog1.findViewById(R.id.btClose);

        closeButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Log.d("LVMH", "close button clicked ");

                //closeButton.setVisibility(GONE);
                dialog1.dismiss();
                sharingScreen();

            }
        });

        whatsapp.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                dialog1.dismiss();

                Log.d("LVMH", "mail button clicked ");

                final String email = editTextEmail1.getText().toString().trim();
                final String subject = editTextName1.getText().toString().trim();
                Log.d("lvmh","whatsapp number:"+email);
                Log.d("lvmh","whatsapp name:"+subject);
                addContact(subject,"+91"+email);

                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_TEXT,"hey , "+subject + "\nHere is your image from #IPL #RCB" );
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imagePath));
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                shareIntent.setType("image/*");
                shareIntent.setPackage("com.whatsapp");
                startActivity(shareIntent);

              Toast.makeText(getApplicationContext(), "Wait for Few seconds before your contact apperars in List , Your contact will be removed automatically.",
                        Toast.LENGTH_LONG).show();

                int FinishTime = 13;
                int countDownInterval = 1000;
                CountDownTimer   counterTimer = new CountDownTimer(FinishTime * 1000, countDownInterval) {
                    public void onFinish() {
                        //finish your activity here

                        deleteContact(getApplicationContext(),email,subject);
                        Log.d("LVMH", "Whats app finished");
                      //  this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
                      //  this.onBackPressed();
                        //finish();
                    }

                    public void onTick(long millisUntilFinished) {
                        //called every 1 sec coz countDownInterval = 1000 (1 sec)
                        Log.d("LVMH", "Ticks");
                    }
                };
                counterTimer.start();

// we will delete the numbers
                //

            }
        });
        dialog1.show();// opening mail dialog

    }

Update : I am calling this fucntion from Oncreate (MainActivity ) on a event .

I have commented the different codes i have tried . Nothing worked .

Let me know any inputs ?

Thanks
NJ


问:
Picking contacts number from the contact list and putting it in an EditText
I have an EditText and a Button, the button has an OnClickListener that opens the contacts list with startActivityForResult(new Intent("android.intent.action.PICK", android.provider.ContactsContract.Contacts.CONTENT_URI), 1).

If the user click on the button, it opens the contact so that they can select one, now I want to import that number to the EditText. Is there a way to do that?

Edit: The both the EditText and the button belong to a Fragment.

答:
If you specifically need a phone number to be picked by the user, you can request for a phone-number-picker, instead of a contact-picker like you're doing.

Try this:

```<code>Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
</code>```

The intent data you'll get in return would be for a specific phone row in the Data table:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((requestCode == 1) && (resultCode == RESULT_OK)) {
        Cursor cursor = null;
        try {
            Uri uri = data.getData();
            cursor = getContentResolver().query(uri, new String[] { CommonDataKinds.Phone.NUMBER }, null, null, null);
            if (cursor != null && cursor.moveToNext()) {
                String phone = cursor.getString(0);
                // Do something with phone
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
If you specifically need a phone number to be picked by the user, you can request for a phone-number-picker, instead of a contact-picker like you're doing.

Try this:

Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);

The intent data you'll get in return would be for a specific phone row in the Data table:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((requestCode == 1) && (resultCode == RESULT_OK)) {
        Cursor cursor = null;
        try {
            Uri uri = data.getData();
            cursor = getContentResolver().query(uri, new String[] { CommonDataKinds.Phone.NUMBER }, null, null, null);
            if (cursor != null && cursor.moveToNext()) {
                String phone = cursor.getString(0);
                // Do something with phone
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


问:
How to permanently add a private key with ssh-add on Ubuntu?
I have a private key protected with a password to access a server via SSH.

I have 2 linux (ubuntu 10.04) machines and the behavior of ssh-add command is different in both of them.

In one machine, once I use "ssh-add .ssh/identity" and entered my password, the key was added permanently, i.e., every time I shutdown the computer and login again, the key is already added.

In the other one, I have to add the key every time I login.

As far as I remember, I did the same thing on both. The only difference is that the key was created on the one that is added permanently.

Does anyone know how to add it permanently to the other machine as well?

答:
This worked for me.  </p>

```<code>ssh-agent /bin/sh
ssh-add /path/to/your/key
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This worked for me.

ssh-agent /bin/sh
ssh-add /path/to/your/key


问:
Image filter kernel to expand 16-235 limited color range
Is it possible to write a 5x5 kernel to process the limited color range into the full range?

This is my sample bitonal kernel, and I don't know what values to use and where to achieve this color expansion:

Grayscale

```<code>{ 0.3,  0.3,  0.3,  0.0,  0.0 }
{ 0.6,  0.6,  0.6,  0.0,  0.0 }
{ 0.1,  0.1,  0.1,  0.0,  0.0 }
{ 0.0,  0.0,  0.0,  1.0,  0.0 }
{ 0.0,  0.0,  0.0,  0.0,  1.0 }
</code>```

I would like RGB color expansion RGB 16-235 => 0-255

However i need the kernel matrix because I am not processing the image but I'm passing the matrix to a windows API function (undocumented: SetMagnificationDesktopColorEffect).

I cannot do a simple subtract/divide/multiply on the pixels. I do not have them.

答: You can basically do it without kernel by substracting 16 from your image and then dividing it by 219. Then you will have normalized to 1 image which you have to multiply by 255 to get 255 intensity range representation.</p>

Body:
Is it possible to write a 5x5 kernel to process the limited color range into the full range?

This is my sample bitonal kernel, and I don't know what values to use and where to achieve this color expansion:

Grayscale

{ 0.3,  0.3,  0.3,  0.0,  0.0 }
{ 0.6,  0.6,  0.6,  0.0,  0.0 }
{ 0.1,  0.1,  0.1,  0.0,  0.0 }
{ 0.0,  0.0,  0.0,  1.0,  0.0 }
{ 0.0,  0.0,  0.0,  0.0,  1.0 }

I would like RGB color expansion RGB 16-235 => 0-255

However i need the kernel matrix because I am not processing the image but I'm passing the matrix to a windows API function (undocumented: SetMagnificationDesktopColorEffect).

I cannot do a simple subtract/divide/multiply on the pixels. I do not have them.


问:
Where in memory the const function parameters are stored in C?
Where in memory are the const function parameters stored in C?

Generally the parameters are stored on the stack, but if the parameter is declared const then where it is stored?

答:
Same as any other parameter (implementation dependent). The const qualifier only means the function won't modify its parameter. It doesn't mean the parameter is a compile time constant expression that can be eliminated.

Also, compilers aren't bound to passing arguments/parameters on the call stack (if such a thing exists for an implementation). They can be passed in registers as well, if the compiler deems it better.


问:
Sending delayed email from devise
Is there a simple way of telling Devise to send all email via
delayed_job? </p>

答:
Alternatively, instead of using the Delayed::Mailer gem, you can quite easily implement and use your own ActionMailer "delivery method", one that...

intercepts mail delivery from ActionMailer

stores the email in a table (optional)

creates a Delayed::Job that references the stored email

delivers the stored email when the delayed job is executed

Do something along the lines of:

```<code># in config/application.rb
ActionMailer::Base.add_delivery_method :queued, Mail::QueuedDelivery

# in config/environment.rb (or one of the config/environments/*.rb files)
config.action_mailer.delivery_method = :queued # ie. Mail::QueuedDelivery

# in lib/mail/queued_delivery.rb
module Mail
  class QueuedDelivery

    def initialize(values = {})
      # (optional)
    end

    def deliver!(mail)
      email = Email.create!(:delivery_handler => mail.delivery_handler.name, :message => mail.to_s)
      Delayed::Job.enqueue Jobs::Email::DeliverEmail.new(email.id)
    end

  end # class QueueDelivery
end # module Mail
</code>```

The Delayed::Job you need to implement would then...

retrieve the stored email from the database -- email = ::Email.find_by_id(email_id)

deliver the email via the mail gem -- Mail::Message.new(email.message).deliver

That's it... hope this help!

ContentLicense: CC BY-SA 2.5

Title: Sending delayed email from devise

Body:
Alternatively, instead of using the Delayed::Mailer gem, you can quite easily implement and use your own ActionMailer "delivery method", one that...

intercepts mail delivery from ActionMailer

stores the email in a table (optional)

creates a Delayed::Job that references the stored email

delivers the stored email when the delayed job is executed

Do something along the lines of:

# in config/application.rb
ActionMailer::Base.add_delivery_method :queued, Mail::QueuedDelivery

# in config/environment.rb (or one of the config/environments/*.rb files)
config.action_mailer.delivery_method = :queued # ie. Mail::QueuedDelivery

# in lib/mail/queued_delivery.rb
module Mail
  class QueuedDelivery

    def initialize(values = {})
      # (optional)
    end

    def deliver!(mail)
      email = Email.create!(:delivery_handler => mail.delivery_handler.name, :message => mail.to_s)
      Delayed::Job.enqueue Jobs::Email::DeliverEmail.new(email.id)
    end

  end # class QueueDelivery
end # module Mail

The Delayed::Job you need to implement would then...

retrieve the stored email from the database -- email = ::Email.find_by_id(email_id)

deliver the email via the mail gem -- Mail::Message.new(email.message).deliver

That's it... hope this help!


问:
ionic2 AlertController, how to return the buttons clicked value from method
I m fairly new in Typescript, I have following code in provider

```<code>...
confirm(message, title=""){
        let confirm = this.alertCtrl.create({
            title: title || "Please confirm",
            message: message,
            buttons: [
                {
                  text: 'Yes',
                  handler: () => {
                    return true;
                  }
                },
                {
                  text: 'No',
                  handler: () => {
                    return false;
                  }
                }
              ]
        });

        confirm.present();
    }
</code>```

UPDATE:

There is a button in a page, which calls a function deleteItems

```<code>deleteItems(){
    this.popup.confirm("Are you sure you want to delete this item");
    if(this.popup.isTrue == true){
          //delete items
     }

}
</code>```

I want the confirm method to return true or false depending upon the button "Yes" or "No" clicked.

Can anybody tell me how to achieve this?

答:
You can do it as shown below.

Note: Creating an UI related things with Provider is treated as Anti-Pattern on Ionic2.Because provider is to handle service related use cases.Keep that in mind too.

Would you like to see the alternative? Please see 2nd Method of my answer here.In other words you can use a base class for handling it.

```<code> isTrue:boolean=null;

    constructor(){}

    confirm(message, title=""){
            let confirm = this.alertCtrl.create({
                title: title || "Please confirm",
                message: message,
                buttons: [
                    {
                      text: 'Yes',
                       handler: data => {
                             this.isTrue=true;
                      }
                    },
                    {
                      text: 'No',
                     handler: data => {
                              this.isTrue=false;
                      }
                    }
                  ]
            });

            confirm.present();
        }
</code>```

Body:
I m fairly new in Typescript, I have following code in provider

...
confirm(message, title=""){
        let confirm = this.alertCtrl.create({
            title: title || "Please confirm",
            message: message,
            buttons: [
                {
                  text: 'Yes',
                  handler: () => {
                    return true;
                  }
                },
                {
                  text: 'No',
                  handler: () => {
                    return false;
                  }
                }
              ]
        });

        confirm.present();
    }

UPDATE:

There is a button in a page, which calls a function deleteItems

deleteItems(){
    this.popup.confirm("Are you sure you want to delete this item");
    if(this.popup.isTrue == true){
          //delete items
     }

}

I want the confirm method to return true or false depending upon the button "Yes" or "No" clicked.

Can anybody tell me how to achieve this?

Body:
You can do it as shown below.

Note: Creating an UI related things with Provider is treated as Anti-Pattern on Ionic2.Because provider is to handle service related use cases.Keep that in mind too.

Would you like to see the alternative? Please see 2nd Method of my answer here.In other words you can use a base class for handling it.

 isTrue:boolean=null;

    constructor(){}

    confirm(message, title=""){
            let confirm = this.alertCtrl.create({
                title: title || "Please confirm",
                message: message,
                buttons: [
                    {
                      text: 'Yes',
                       handler: data => {
                             this.isTrue=true;
                      }
                    },
                    {
                      text: 'No',
                     handler: data => {
                              this.isTrue=false;
                      }
                    }
                  ]
            });

            confirm.present();
        }


问:
How to format a phone number with jQuery
I'm currently displaying phone numbers like 2124771000. However, I need the number to be formatted in a more human-readable form, for example: 212-477-1000. Here's my current HTML:

```<code><p class="phone">2124771000</p>
</code>```

答:
Consider libphonenumber-js (https://github.com/halt-hammerzeit/libphonenumber-js) which is a smaller version of the full and famous libphonenumber.

Quick and dirty example:

```<code>$(".phone-format").keyup(function() {
// Don't reformat backspace/delete so correcting mistakes is easier
if (event.keyCode != 46 && event.keyCode != 8) {
    var val_old = $(this).val();
    var newString = new libphonenumber.asYouType('US').input(val_old);
    $(this).focus().val('').val(newString);
}
});
</code>```

(If you do use a regex to avoid a library download, avoid reformat on backspace/delete will make it easier to correct typos.)

Body:
I'm currently displaying phone numbers like 2124771000. However, I need the number to be formatted in a more human-readable form, for example: 212-477-1000. Here's my current HTML:

2124771000

Body:
Consider libphonenumber-js (https://github.com/halt-hammerzeit/libphonenumber-js) which is a smaller version of the full and famous libphonenumber.

Quick and dirty example:

$(".phone-format").keyup(function() {
// Don't reformat backspace/delete so correcting mistakes is easier
if (event.keyCode != 46 && event.keyCode != 8) {
    var val_old = $(this).val();
    var newString = new libphonenumber.asYouType('US').input(val_old);
    $(this).focus().val('').val(newString);
}
});

(If you do use a regex to avoid a library download, avoid reformat on backspace/delete will make it easier to correct typos.)


问:
generate edit and delete button at run time an handle the click event in datagridview using c# for windows application
Please look for the code, Here need a processed way for the problem mention in the question.  </p>

```<code> private void addBtn_Click(object sender, EventArgs e)
     {

        try
        {

            dataGridView1.Rows.Add(comboBox2.Text, textBox6.Text, textBox7.Text, textBox2.Text,textBox3.Text,textBox4.Text,textBox5.Text);
            if (dataGridView1 != null)
            {

                for (int count = 0; (count <= (dataGridView1.Rows.Count - 2)); count++)
                {

                    dataGridView1.Rows[count].HeaderCell.Value = string.Format((count + 1).ToString(), "0");

                }

            }
</code>```

<p>//how to know which button is pressed i.e edit or delete
//and how to know which rows button is pressed and fetch that row data when
//edit button is pressed into another windows form and when i press update button
//from edit form then data must be change on the same row of datagridview whos
 //edit button is pressed  </p>

```<code> private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

 //this is how i added button

 Editlink.UseColumnTextForButtonValue=true;

        Editlink.HeaderText = "Edit";
        Editlink.DataPropertyName = "lnkColumn";
        Editlink.Text = "Edit";
        dataGridView1.Columns.Add(Editlink);

        Deletelink.UseColumnTextForButtonValue = true;
        Deletelink.HeaderText = "delete";
        Deletelink.DataPropertyName = "lnkColumn";
        Deletelink.Text = "Delete";
        dataGridView1.Columns.Add(Deletelink);
</code>```

答:
It's in the event object argument e: DataGridViewCellEventArgs

You can use e.ColumnIndex and e.RowIndex

Then, to get the row, just do:

```<code>var row = (DataGridRow)dataGridView1.ItemContainerGenerator.ContainerFromIndex(e.RowIndex);
</code>```

Body:
Please look for the code, Here need a processed way for the problem mention in the question.

 private void addBtn_Click(object sender, EventArgs e)
     {

        try
        {

            dataGridView1.Rows.Add(comboBox2.Text, textBox6.Text, textBox7.Text, textBox2.Text,textBox3.Text,textBox4.Text,textBox5.Text);
            if (dataGridView1 != null)
            {

                for (int count = 0; (count <= (dataGridView1.Rows.Count - 2)); count++)
                {

                    dataGridView1.Rows[count].HeaderCell.Value = string.Format((count + 1).ToString(), "0");

                }

            }

//how to know which button is pressed i.e edit or delete
//and how to know which rows button is pressed and fetch that row data when
//edit button is pressed into another windows form and when i press update button
//from edit form then data must be change on the same row of datagridview whos
 //edit button is pressed

 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

 //this is how i added button

 Editlink.UseColumnTextForButtonValue=true;

        Editlink.HeaderText = "Edit";
        Editlink.DataPropertyName = "lnkColumn";
        Editlink.Text = "Edit";
        dataGridView1.Columns.Add(Editlink);

        Deletelink.UseColumnTextForButtonValue = true;
        Deletelink.HeaderText = "delete";
        Deletelink.DataPropertyName = "lnkColumn";
        Deletelink.Text = "Delete";
        dataGridView1.Columns.Add(Deletelink);

Body:
It's in the event object argument e: DataGridViewCellEventArgs

You can use e.ColumnIndex and e.RowIndex

Then, to get the row, just do:

var row = (DataGridRow)dataGridView1.ItemContainerGenerator.ContainerFromIndex(e.RowIndex);


问:
Why can't java find StringEntity class even after importing org.apache.http packages?
I am using a  sample code from Microsoft Cognitive Services. It makes use of StringEntity class to make request to the REST API. The java compiler seems to be unable to find 'symbol' StringEntity? What could be the reason for this and how to resolve this?
Here goes the code -

```<code>import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.*;

public class NEWS_FETCHER
{
    public static void main(String[] args)
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/v5.0/news/search");

            builder.setParameter("q", "microsoft");
            builder.setParameter("count", "10");
            builder.setParameter("offset", "0");
            builder.setParameter("mkt", "en-us");
            builder.setParameter("safeSearch", "Moderate");

            URI uri = builder.build();
            HttpGet request = new HttpGet(uri);
            request.setHeader("Ocp-Apim-Subscription-Key", "<Key goes here>");

            // Request body
            StringEntity reqEntity = new StringEntity("");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null)
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}
</code>```

Most of it is taken from Microsoft API Test Sample.
https://dev.cognitive.microsoft.com/docs/services/56b43f72cf5ff8098cef380a/operations/56b449fbcf5ff81038d15cdf

答:
The class StringEntity is in the package org.apache.http.entity, so you have to add the correct import for that:

```<code>import org.apache.http.entity.StringEntity
</code>```

Body:
I am using a  sample code from Microsoft Cognitive Services. It makes use of StringEntity class to make request to the REST API. The java compiler seems to be unable to find 'symbol' StringEntity? What could be the reason for this and how to resolve this?
Here goes the code -

import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.*;

public class NEWS_FETCHER
{
    public static void main(String[] args)
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/v5.0/news/search");

            builder.setParameter("q", "microsoft");
            builder.setParameter("count", "10");
            builder.setParameter("offset", "0");
            builder.setParameter("mkt", "en-us");
            builder.setParameter("safeSearch", "Moderate");

            URI uri = builder.build();
            HttpGet request = new HttpGet(uri);
            request.setHeader("Ocp-Apim-Subscription-Key", "<Key goes here>");

            // Request body
            StringEntity reqEntity = new StringEntity("");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null)
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Most of it is taken from Microsoft API Test Sample.
https://dev.cognitive.microsoft.com/docs/services/56b43f72cf5ff8098cef380a/operations/56b449fbcf5ff81038d15cdf

Body:
The class StringEntity is in the package org.apache.http.entity, so you have to add the correct import for that:

import org.apache.http.entity.StringEntity


问:
transform text to json
I have a huge list like this:

```
Title / Company

Subtitle

Description (usually long)
(line break)
(line break)
(line break)
(next object like above)
```

If there is no company name, the Title is the Company name and the Title.

I need to transform this to a json-object like this:

```
{
  "id": "title",
  "title": "Title",
  "subtitle": "Subtitle",
  "company": "Company",
  "titleImage": "_title.png",
  "text": "Description",
  "hmtl": "",
  "tags": []
},
```

What's the fastest way to do different transformation tasks like this with javascript/bash-scripts/other tools and how would that look?

答:
That's a 2 step process:

you have to parse your original file (with some regex), store the infos in an object (or a list of objects maybe)

dump your json

```<code># parse your data...

JSON.stringify(parsed_data)
</code>```

You understood it: the hardest part is the parse the original thing.

With so little examples, we can't really help you, and that's not the purpose of StackOverflow anyway. If you have trouble while coding the first step, then ask (don't forget show us what you've done) and plenty of people (including me) will be willing to help you out!

Title: transform text to json

Body:
I have a huge list like this:

Title / Company

Subtitle

Description (usually long)
(line break)
(line break)
(line break)
(next object like above)

If there is no company name, the Title is the Company name and the Title.

I need to transform this to a json-object like this:

{
  "id": "title",
  "title": "Title",
  "subtitle": "Subtitle",
  "company": "Company",
  "titleImage": "_title.png",
  "text": "Description",
  "hmtl": "",
  "tags": []
},

What's the fastest way to do different transformation tasks like this with javascript/bash-scripts/other tools and how would that look?

Body:
That's a 2 step process:

you have to parse your original file (with some regex), store the infos in an object (or a list of objects maybe)

dump your json

# parse your data...

JSON.stringify(parsed_data)

You understood it: the hardest part is the parse the original thing.

With so little examples, we can't really help you, and that's not the purpose of StackOverflow anyway. If you have trouble while coding the first step, then ask (don't forget show us what you've done) and plenty of people (including me) will be willing to help you out!


问:
Protecting a Subdomain with htaccess
I have my own server and do everything on my end as much as possible for a gaming community (in order to keep overhead down).  This includes hosting the website myself with WAMP and Windows 10. Let's say I have a domain. I'm using a REST server for .. stuff. I need to provide access to the REST server via a Web Control Panel that uses a chunk of complicated PHP and Javascript noise to work. The only way to run it is through the server (obviously) which means it needs it's own virtual host to operate (I think. It doesn't work if I just use PHP Include). So I created a subdomain (rest.domain.com) and plugged that into the src for an iframe that I put on a webpage that is password protected. The only problem I'm facing right now is that anyone can go to rest.domain.com and go right around the paltry Wordpress security and mess about with my stuff.

I'm open to either

Blocking direct URL access and including some fancy code so only the iFrame can get to it.

Passwording the SubDomain and just giving my REST users the rest.domain.com url.

Something entirely different that I didn't know existed.

What should I do?

EDIT:1

So, we've gotten to the point where we're using an .htaccess file to restrict the subdomain with a login/password.  I've created the .htaccess file in the directory of the REST files and created an .htpasswd file.

I am now receiving 500ISE errors.
I have gone down through 3 Google Search pages trying to research the issue and have made dozens of edits to my .htaccess file to make it work.  Without the htaccess, the REST server can be accessed without restriction.  The error is in the .htaccess file.  Here is what my .htaccess file looks like upon giving up on this for the evening:

Messing around with this for hours and have gone down 3 Google Pages, opening and researching every single hit (most are on SO) and still stuck on a 500 Internal Server Error.  This is where I'm sitting at right now with my htaccess file and this is where I'm giving up for the night:

```<code>AuthType Basic
AuthName "Locked"
AuthUserFile o:\..\..\..\..\.htpasswd
Require valid-user

SetEnvIf Host rest.domain.com !secure_content

Order Allow,Deny
Allow env secure_content
Deny From All

Satisfy Any
</code>```

EDIT:1.1

So, instead of giving up (because I ain't no quitta!) I've started noticing a trend from a few other sites that using a far less complicated .htaccess than the "instructional" I originally found.  I went ahead and commented out the following lines:

```<code>#SetEnvIf Host rest.radio-takeover.com !secure_content

#Order Allow,Deny
#Allow env secure_content
#Deny From All

#Satisfy Any
</code>```

It now appears to be working as intended.  Thank you, Jenny, for somewhat pointing me down the right path.

答:
If thats not what you asked then here is another option.

Create a .htaccess file in root folder of rest.domain.com and write "deny from all" in it.Hope you will get what you need.

Title: Protecting a Subdomain with htaccess

Body:
I have my own server and do everything on my end as much as possible for a gaming community (in order to keep overhead down).  This includes hosting the website myself with WAMP and Windows 10. Let's say I have a domain. I'm using a REST server for .. stuff. I need to provide access to the REST server via a Web Control Panel that uses a chunk of complicated PHP and Javascript noise to work. The only way to run it is through the server (obviously) which means it needs it's own virtual host to operate (I think. It doesn't work if I just use PHP Include). So I created a subdomain (rest.domain.com) and plugged that into the src for an iframe that I put on a webpage that is password protected. The only problem I'm facing right now is that anyone can go to rest.domain.com and go right around the paltry Wordpress security and mess about with my stuff.

I'm open to either

Blocking direct URL access and including some fancy code so only the iFrame can get to it.

Passwording the SubDomain and just giving my REST users the rest.domain.com url.

Something entirely different that I didn't know existed.

What should I do?

EDIT:1

So, we've gotten to the point where we're using an .htaccess file to restrict the subdomain with a login/password.  I've created the .htaccess file in the directory of the REST files and created an .htpasswd file.

I am now receiving 500ISE errors.
I have gone down through 3 Google Search pages trying to research the issue and have made dozens of edits to my .htaccess file to make it work.  Without the htaccess, the REST server can be accessed without restriction.  The error is in the .htaccess file.  Here is what my .htaccess file looks like upon giving up on this for the evening:

Messing around with this for hours and have gone down 3 Google Pages, opening and researching every single hit (most are on SO) and still stuck on a 500 Internal Server Error.  This is where I'm sitting at right now with my htaccess file and this is where I'm giving up for the night:

AuthType Basic
AuthName "Locked"
AuthUserFile o:\..\..\..\..\.htpasswd
Require valid-user

SetEnvIf Host rest.domain.com !secure_content

Order Allow,Deny
Allow env secure_content
Deny From All

Satisfy Any

EDIT:1.1

So, instead of giving up (because I ain't no quitta!) I've started noticing a trend from a few other sites that using a far less complicated .htaccess than the "instructional" I originally found.  I went ahead and commented out the following lines:

#SetEnvIf Host rest.radio-takeover.com !secure_content

#Order Allow,Deny
#Allow env secure_content
#Deny From All

#Satisfy Any

It now appears to be working as intended.  Thank you, Jenny, for somewhat pointing me down the right path.


问:
State of HTML5 in mobile browsers
What is the state of HTML 5 on the mobile browser ? I'm particularly interested in the offline storage possibilities (localStorage, Database storage with SQLish interface).

Android > 2.0, database storage available (what about 1.6?)

iOS > 3, database storage available

Blackberry Webkit based browser ? database already available? In which version ?

WP7, the browser seems to be a mix of IE7-8. No offline storage available I guess ?

Symbian, It seems that QT (>=4.7) based Symbian application have access to Web Storage via QTWebkit http://doc.trolltech.com/4.7/qtwebkit.html Any idea how is it supported in the builtin browser ?

答: You can find your answer here http://caniuse.com/ under Web Storage, it's the most complete list I have seen so far. I will update this answer if I find something more detailed.</p>

Title: State of HTML5 in mobile browsers


问:
Toggle Value in Angular Material CheckBox
I have a Template Driven Form in which i am putting a checkbox that can toggle its value.

Component

```<code>public toggles = [
    { value: 'toggled', display: 'Toggled' },
    { value: 'untoggled', display: 'UnToggled' },
];

<div>
    <input type="hidden" name="toggle" [(ngModel)]="user.toggle">
    <div>
        <label>
            <input type="checkbox"
                [checked]="user.toggle === toggles[0].value"
                (change)="$event.target.checked? (user.toggle =  toggles[0].value) : (user.toggle = toggles[1].value)">
            {{ toggles[0].display }}
        </label>
    </div>
</div>
</code>```

The following works great, but when i am switching to Angular Material it just fails to works .

The material Template code

```<code><input type="hidden" name="toggle" [(ngModel)]="user.toggle">
<md-checkbox [checked]="user.toggle === toggles[0].value"
               (change)="$event.target.checked?(user.toggle = toggles[0].value): (user.toggle = toggles[1].value)">
    {{toggles[0].display}}</md-checkbox>
</code>```

I am getting the following Error in console, it says cannot read the property of undefined  console,

```<code>TypeError: Cannot read property 'checked' of undefined
        at Object.eval [as handleEvent] (TemplateDrivenComponent.html:64)
</code>```

I know the point where the error is occurring $event.target.checked angular cannot read this checked event on md-checkbox , how to get around this any pointers will be great

thanks

答:
Looking at comments try the following hope this solves the issue i guess you need not use target with event in Material.   </p>

```<code> <input type="hidden" name="toggle" [(ngModel)]="user.toggle">
        <md-checkbox [checked]="user.toggle === toggles[0].value"
                       (change)="$event.checked?(user.toggle = toggles[0].value): (user.toggle = toggles[1].value)">
            {{toggles[0].display}}</md-checkbox>
</code>```

Body:
I have a Template Driven Form in which i am putting a checkbox that can toggle its value.

Component

public toggles = [
    { value: 'toggled', display: 'Toggled' },
    { value: 'untoggled', display: 'UnToggled' },
];

    <input type="hidden" name="toggle" [(ngModel)]="user.toggle">

            <input type="checkbox"
                [checked]="user.toggle === toggles[0].value"
                (change)="$event.target.checked? (user.toggle =  toggles[0].value) : (user.toggle = toggles[1].value)">
            {{ toggles[0].display }}

The following works great, but when i am switching to Angular Material it just fails to works .

The material Template code

<input type="hidden" name="toggle" [(ngModel)]="user.toggle">
<md-checkbox [checked]="user.toggle === toggles[0].value"
               (change)="$event.target.checked?(user.toggle = toggles[0].value): (user.toggle = toggles[1].value)">
    {{toggles[0].display}}</md-checkbox>

I am getting the following Error in console, it says cannot read the property of undefined  console,

TypeError: Cannot read property 'checked' of undefined
        at Object.eval [as handleEvent] (TemplateDrivenComponent.html:64)

I know the point where the error is occurring $event.target.checked angular cannot read this checked event on md-checkbox , how to get around this any pointers will be great

thanks

Body:
Looking at comments try the following hope this solves the issue i guess you need not use target with event in Material.

 <input type="hidden" name="toggle" [(ngModel)]="user.toggle">
        <md-checkbox [checked]="user.toggle === toggles[0].value"
                       (change)="$event.checked?(user.toggle = toggles[0].value): (user.toggle = toggles[1].value)">
            {{toggles[0].display}}</md-checkbox>


问:
When are UITabBarController's views loaded?
I have a UITabBarController with 3 tabs each with their own UIViewController file. In the Tabbar's viewDidLoad() when I iterate through the children views in a loop, each view appears to be there:

```<code>if let childViewControllers = self.viewControllers {
    for viewController in childViewControllers {
       print("Hi")                               // Prints "Hi" 3 times
    }
}
</code>```

However, if I put a print statement inside the individual childrens UIViewController file's viewDidLoad() only the first child's print statement is executed (The first tab of the tabbar).

How is it that the viewDidLoad() of the other children aren't executed yet I'm still able to iterate through all the tabbar's children and do things such as setting their properties?

答: The view of each tab is loaded only when needed, meaning only when you click on the tab to view it. Only the first tab prints your statement because it is the one that you are viewing. Try to click on the other tabs and you'll see the statement being printed as well.</p>

Body:
I have a UITabBarController with 3 tabs each with their own UIViewController file. In the Tabbar's viewDidLoad() when I iterate through the children views in a loop, each view appears to be there:

if let childViewControllers = self.viewControllers {
    for viewController in childViewControllers {
       print("Hi")                               // Prints "Hi" 3 times
    }
}

However, if I put a print statement inside the individual childrens UIViewController file's viewDidLoad() only the first child's print statement is executed (The first tab of the tabbar).

How is it that the viewDidLoad() of the other children aren't executed yet I'm still able to iterate through all the tabbar's children and do things such as setting their properties?


问:
C program gives different answers with a floating rand() call included
I was trying to solve a competitive programming question when I wrote this code:

```<code>#include<stdio.h>
#include <stdlib.h>

int brr[100];
int n,arr[100];
int s[100];

int dyn(int num){
    int i,ans;
    if(brr[num]!=-1){
      return brr[num];}

    for(i=0;i<n;i++){
      if(arr[i]==num){
        ans=1;
        s[num]=arr[i];
        break;}
      else if(arr[i]<num){
        if(i==0){
          ans=1+dyn(num-arr[i]);
          s[num]=arr[i];}
        else {
          if(ans>1+dyn(num-arr[i])){
            ans=1+dyn(num-arr[i]);
            s[num]=arr[i];
          }}}}
  brr[num]=ans;
   return ans ;
}

int main(){
  scanf("%d",&n);
  int i;
  for(i=0;i<n;i++){
    scanf(" %d",&arr[i]);
  }
  int num=0;
  scanf(" %d",&num);
  for(i=0;i<=num;i++){
    brr[i]=-1;}
  brr[0]=0;
  for(i=1;i<=num;i++){
    dyn(i);
    //rand();
  }
  printf("\n%d\n",dyn(num));
  while(num>0){
    printf("\t%d",s[num]);
    num=num-1;
  }
  return 0;
}
</code>```

Line 44 has a commented out rand(). If I execute the code with the rand() commented out, i get the result as

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

for the input 4 6 5 2 1 10

After removing the comment I get

```<code>2
5    6    6    6    6    5    2    2    2    1
</code>```

for the same input.

What's going on?

答:
In the function dyn in the line

```<code>if(ans>1+dyn(num-arr[i])){
</code>```

the value ans may be used uninitialized. This is causing that the behavior of the program is undefined.

Body:
I was trying to solve a competitive programming question when I wrote this code:

#include<stdio.h>
#include <stdlib.h>

int brr[100];
int n,arr[100];
int s[100];

int dyn(int num){
    int i,ans;
    if(brr[num]!=-1){
      return brr[num];}

    for(i=0;i<n;i++){
      if(arr[i]==num){
        ans=1;
        s[num]=arr[i];
        break;}
      else if(arr[i]<num){
        if(i==0){
          ans=1+dyn(num-arr[i]);
          s[num]=arr[i];}
        else {
          if(ans>1+dyn(num-arr[i])){
            ans=1+dyn(num-arr[i]);
            s[num]=arr[i];
          }}}}
  brr[num]=ans;
   return ans ;
}

int main(){
  scanf("%d",&n);
  int i;
  for(i=0;i<n;i++){
    scanf(" %d",&arr[i]);
  }
  int num=0;
  scanf(" %d",&num);
  for(i=0;i<=num;i++){
    brr[i]=-1;}
  brr[0]=0;
  for(i=1;i<=num;i++){
    dyn(i);
    //rand();
  }
  printf("\n%d\n",dyn(num));
  while(num>0){
    printf("\t%d",s[num]);
    num=num-1;
  }
  return 0;
}

Line 44 has a commented out rand(). If I execute the code with the rand() commented out, i get the result as

2
6    6    6    6    6    5    0    0    2    1

for the input 4 6 5 2 1 10

After removing the comment I get

2
5    6    6    6    6    5    2    2    2    1

for the same input.

What's going on?

Body:
In the function dyn in the line

if(ans>1+dyn(num-arr[i])){

the value ans may be used uninitialized. This is causing that the behavior of the program is undefined.


问:
lambda in list comprehension error
I am doing the following:

```<code>ll = [-8, -4, 0, 4, 8]
[lambda x: x**2 for x in ll]
</code>```

and getting following error:

```<code>[<function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>]
</code>```

What could be the problem? I know desired result can be achieved by below code but I want to understand why lambda is not working in list comprehension?

```<code>[x**2 for x in ll]
</code>```

答:
lambda returns a function, it does not evaluate the function, you may want:

```<code>ll = [-8, -4, 0, 4, 8]
[x**2 for x in ll]
</code>```

or

```<code>ll = [-8, -4, 0, 4, 8]
f = lambda x: x**2
[f(x) for x in ll]
</code>```

and it is equal to:

```<code>ll = [-8, -4, 0, 4, 8]
def f(x):
   return x**2
[f(x) for x in ll]
</code>```

Title: lambda in list comprehension error

Body:
I am doing the following:

ll = [-8, -4, 0, 4, 8]
[lambda x: x**2 for x in ll]

and getting following error:

[<function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>]

What could be the problem? I know desired result can be achieved by below code but I want to understand why lambda is not working in list comprehension?

[x**2 for x in ll]

Body:
lambda returns a function, it does not evaluate the function, you may want:

ll = [-8, -4, 0, 4, 8]
[x**2 for x in ll]

or

ll = [-8, -4, 0, 4, 8]
f = lambda x: x**2
[f(x) for x in ll]

and it is equal to:

ll = [-8, -4, 0, 4, 8]
def f(x):
   return x**2
[f(x) for x in ll]


问:
Equivalent to the deprecated <sec:authorize> ifNotGranted attribute
I would like to prevent an image having a link if a user does NOT have a certain role.  e.g.

```<code><sec:authorize ifNotGranted="ROLE_ACCOUNTS" ><img src="someimage.jpg"/></sec:authorize>
<sec:authorize ifAllGranted="ROLE_ACCOUNTS" ><a href="somelink.htm"><img src="someimage.jpg"/></a></sec:authorize>
</code>```

However ifNotGranted and ifAllGranted are now deprecated in favour of the access expression.  I can see that ifAllGranted can be replicated with:

```<code><sec:authorize access="hasRole('ROLE_ACCOUNTS')"><a href="somelink.htm"><img src="someimage.jpg"/></a></sec:authorize>
</code>```

But how can ifNotGranted be replicated using the access method?  Any help would be greatfully appreciated.

答:
In case if you have many files to update, I recommend use the regular express to search and replace

find

```<code><sec:authorize\s+ifAnyGranted="([^"]+)"
</code>```

replace with

```<code><sec:authorize access="hasAnyRole('$1')"
</code>```

and search

```<code><sec:authorize\s+ifNotGranted="([^"]+)"
</code>```

replace with

```<code><sec:authorize access="!hasAnyRole('$1')"
</code>```

Hope this can save you time

Body:
I would like to prevent an image having a link if a user does NOT have a certain role.  e.g.

<sec:authorize ifNotGranted="ROLE_ACCOUNTS" ></sec:authorize>
<sec:authorize ifAllGranted="ROLE_ACCOUNTS" ></sec:authorize>

However ifNotGranted and ifAllGranted are now deprecated in favour of the access expression.  I can see that ifAllGranted can be replicated with:

<sec:authorize access="hasRole('ROLE_ACCOUNTS')"></sec:authorize>

But how can ifNotGranted be replicated using the access method?  Any help would be greatfully appreciated.

Body:
In case if you have many files to update, I recommend use the regular express to search and replace

find

<sec:authorize\s+ifAnyGranted="([^"]+)"

replace with

<sec:authorize access="hasAnyRole('$1')"

and search

<sec:authorize\s+ifNotGranted="([^"]+)"

replace with

<sec:authorize access="!hasAnyRole('$1')"

Hope this can save you time


问:
Why does batch file execution stop before processing the second "call" statement?
I've a fairly rudimentary knowledge of batch files and usually manage to get by but have hit a problem which I can't solve.

The batch files are run on Windows 7 Ultimate and Windows 10 Professional systems and are usually invoked by a Scheduler program, although sometimes I just click the relevant desktop icon. Essentially, the role of the batch files is to download specific files (TV programmes) which are listed in an external text file, in my case, located in my Dropbox account. For each item in the text file (TV.txt) there are two lines, one naming the file, the other listing its ID:

```<code>name1
ID1
name2
ID2
name3
ID3
</code>```

The batch files successively work through the items listed in the text file, one file works on the "IDs", the second on the "names".

The "IDs" file (tv-pid.cmd) consists of the following:

```<code>set $textFile="D:\Dropbox\Get_iPlayer\0-TVdl\tv.txt"
for /f "delims=" %%a in ('type %$textFile%') do get_iplayer --pid %%a
</code>```

The "names" file (tv-nopid.cmd) consists of the following:

```<code>set $textFile="D:\Dropbox\Get_iPlayer\0-TVdl\tv.txt"
for /f "delims=" %%a in ('type %$textFile%') do get_iplayer --get %%a
</code>```

Each batch file works well on its own, the problem is when I try to combine the two into a single batch file.

If I create a "combined" batch file (tv.cmd):

```<code>call tv-pid.cmd
call tv-nopid.cmd
</code>```

the first "call" is executed but the batch operation terminates before calling the second file.

Equally if I create a "combined" batch file (not using "call" commands)

```<code>set $textFile="D:\Dropbox\Get_iPlayer\0-TVdl\tv.txt"
for /f "delims=" %%a in ('type %$textFile%') do get_iplayer --pid %%a
set $textFile="D:\Dropbox\Get_iPlayer\0-TVdl\tv.txt"
for /f "delims=" %%a in ('type %$textFile%') do get_iplayer --get %%a
</code>```

the same happens, the download activity on line 2 is executed after which the batch operation terminates.

Personally I would prefer a solution based on the "call" commands, but I don't mind.

答:
```<code>set $textFile="D:\Dropbox\Get_iPlayer\0-TVdl\tv.txt"
set "idnames="
for /f "delims=" %%a in ('type %$textFile%') do (
 if defined id_names (
  set "id_names="
  call get_iplayer --pid %%a
 ) else (
  set "id_names=Y"
  call get_iplayer --get %%a
 )
</code>```

This may work. I've no idea what get_iplayer is or does.

The idea here is that the line-content alternates, so toggling the variable id_names between set-to-a-value and set-to-no-value (=cleared) allows us to execute get_iplayer with the correct options.

Note that your code would execute get_iplayer with the option pid or get for each line of the input file - which may be causing the problem.

Body:
I've a fairly rudimentary knowledge of batch files and usually manage to get by but have hit a problem which I can't solve.

The batch files are run on Windows 7 Ultimate and Windows 10 Professional systems and are usually invoked by a Scheduler program, although sometimes I just click the relevant desktop icon. Essentially, the role of the batch files is to download specific files (TV programmes) which are listed in an external text file, in my case, located in my Dropbox account. For each item in the text file (TV.txt) there are two lines, one naming the file, the other listing its ID:

name1
ID1
name2
ID2
name3
ID3

The batch files successively work through the items listed in the text file, one file works on the "IDs", the second on the "names".

The "IDs" file (tv-pid.cmd) consists of the following:

set $textFile="D:\Dropbox\Get_iPlayer\0-TVdl\tv.txt"
for /f "delims=" %%a in ('type %$textFile%') do get_iplayer --pid %%a

The "names" file (tv-nopid.cmd) consists of the following:

set $textFile="D:\Dropbox\Get_iPlayer\0-TVdl\tv.txt"
for /f "delims=" %%a in ('type %$textFile%') do get_iplayer --get %%a

Each batch file works well on its own, the problem is when I try to combine the two into a single batch file.

If I create a "combined" batch file (tv.cmd):

call tv-pid.cmd
call tv-nopid.cmd

the first "call" is executed but the batch operation terminates before calling the second file.

Equally if I create a "combined" batch file (not using "call" commands)

set $textFile="D:\Dropbox\Get_iPlayer\0-TVdl\tv.txt"
for /f "delims=" %%a in ('type %$textFile%') do get_iplayer --pid %%a
set $textFile="D:\Dropbox\Get_iPlayer\0-TVdl\tv.txt"
for /f "delims=" %%a in ('type %$textFile%') do get_iplayer --get %%a

the same happens, the download activity on line 2 is executed after which the batch operation terminates.

Personally I would prefer a solution based on the "call" commands, but I don't mind.

Body:
set $textFile="D:\Dropbox\Get_iPlayer\0-TVdl\tv.txt"
set "idnames="
for /f "delims=" %%a in ('type %$textFile%') do (
 if defined id_names (
  set "id_names="
  call get_iplayer --pid %%a
 ) else (
  set "id_names=Y"
  call get_iplayer --get %%a
 )

This may work. I've no idea what get_iplayer is or does.

The idea here is that the line-content alternates, so toggling the variable id_names between set-to-a-value and set-to-no-value (=cleared) allows us to execute get_iplayer with the correct options.

Note that your code would execute get_iplayer with the option pid or get for each line of the input file - which may be causing the problem.


问:
undefined method `find' for File:Class
I'm trying to create a ROR application that allows me to upload excel files. I want to be able to list out the names of all excel files uploaded with a clickable link to each name that will bring me to the show.html.erb page which will show the data of the file.

I'm stuck with this "undefined method `find' for File:Class" error when i try to access the reports/index page, probably because there is not identifier associated with the file, but only with the row of the excel data.

Here is my schema:

```<code>ActiveRecord::Schema.define(version: 20170402043056) do

  create_table "files", force: :cascade do |t|
    t.string   "Name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "reports", force: :cascade do |t|
    t.string "date"
    t.string "order"
    t.string "item"
    t.string "product"
  end

end
</code>```

I have added this to routes.rb:

```<code>resources :reports do
  collection { post :import }
end
</code>```

Reports model:

```<code>`class Report< ActiveRecord::Base

require 'roo'
belongs_to  :file

def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    report = find_by_id(row["id"]) || new
    report.attributes = row.to_hash
    report.save!
  end
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path, packed: false, file_warning: :ignore)
  when ".xls" then Roo::Excel.new(file.path, packed: false, file_warning: :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, packed: false, file_warning: :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end

end
</code>```

reports_controller:

```<code>class ReportsController < ApplicationController

def index
@file = File.all
end

def show
@file = File.find(params[:id])
end

def import
@report = Report.import(params[:file])
@file = File.import(params[:id])
redirect_to reports_path, notice: "report imported."
end

end
</code>```

new.html.erb (page to upload file):

```<code><%= form_tag import_reports_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>
</code>```

index.html.erb (page to list out names of files uploaded):

```<code><h1>List of reports uploaded</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Created at</th>
      <th>Updated at</th>
    </tr>
  </thead>

  <tbody>
    <% @report.each do |report| %>
      <tr>
        <td><%= report.original_filename %></td>
        <td><%= report.created_at %></td>
        <td><%= report.update_at %></td>
      </tr>
    <% end %>
  </tbody>
</table>
</code>```

show.html.erb (page showing the data):

```<code><h1>Report data</h1>

<table>
  <thead>
    <tr>
      <th>Date</th>
      <th>Order</th>
      <th>Item</th>
      <th>Product</th>
      <th></th>
      <th></th>
    </tr>
  </thead>

  <tbody>
    <% @report.each do |report| %>
      <tr>
        <td><%= report.date %></td>
        <td><%= report.order %></td>
        <td><%= report.item %></td>
        <td><%= report.product %></td>
      </tr>
    <% end %>
  </tbody>
</table>
</code>```

答: File is a  bad name for your model. Do not give that name, it's built-in class and shouldn't be used.

Title: undefined method `find' for File:Class

Body:
I'm trying to create a ROR application that allows me to upload excel files. I want to be able to list out the names of all excel files uploaded with a clickable link to each name that will bring me to the show.html.erb page which will show the data of the file.

I'm stuck with this "undefined method `find' for File:Class" error when i try to access the reports/index page, probably because there is not identifier associated with the file, but only with the row of the excel data.

Here is my schema:

ActiveRecord::Schema.define(version: 20170402043056) do

  create_table "files", force: :cascade do |t|
    t.string   "Name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "reports", force: :cascade do |t|
    t.string "date"
    t.string "order"
    t.string "item"
    t.string "product"
  end

end

I have added this to routes.rb:

resources :reports do
  collection { post :import }
end

Reports model:

`class Report< ActiveRecord::Base

require 'roo'
belongs_to  :file

def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    report = find_by_id(row["id"]) || new
    report.attributes = row.to_hash
    report.save!
  end
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path, packed: false, file_warning: :ignore)
  when ".xls" then Roo::Excel.new(file.path, packed: false, file_warning: :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, packed: false, file_warning: :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end

end

reports_controller:

class ReportsController < ApplicationController

def index
@file = File.all
end

def show
@file = File.find(params[:id])
end

def import
@report = Report.import(params[:file])
@file = File.import(params[:id])
redirect_to reports_path, notice: "report imported."
end

end

new.html.erb (page to upload file):

<%= form_tag import_reports_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>

index.html.erb (page to list out names of files uploaded):

List of reports uploaded

      Name
      Created at
      Updated at

    <% @report.each do |report| %>

        <%= report.original_filename %>
        <%= report.created_at %>
        <%= report.update_at %>

    <% end %>

show.html.erb (page showing the data):

Report data

      Date
      Order
      Item
      Product

    <% @report.each do |report| %>

        <%= report.date %>
        <%= report.order %>
        <%= report.item %>
        <%= report.product %>

    <% end %>


问:
Redirect one page to another with parameters via htaccess
I want to redirect from a page to another with parameters with htaccess.

For example:

From: www.websitename.co.uk/mylink.php?u=*username*

To: www.websitename.co.uk/mylink/*username*

I tried this but it's not working.

```<code>RewriteEngine on
RewriteRule www.websitename.co.uk/mylink.php?u=*username* www.websitename.co.uk/mylink/*username* [R=301]
</code>```

Where am I doing wrong?

答:
Rewrite rules use regex like this:

```<code>RewriteEngine on
RewriteRule ^/mylink.php?u=(.*) /mylink/$1 [R=301]
</code>```

Reference: https://httpd.apache.org/docs/current/rewrite/intro.html

Body:
I want to redirect from a page to another with parameters with htaccess.

For example:

From: www.websitename.co.uk/mylink.php?u=*username*

To: www.websitename.co.uk/mylink/*username*

I tried this but it's not working.

RewriteEngine on
RewriteRule www.websitename.co.uk/mylink.php?u=*username* www.websitename.co.uk/mylink/*username* [R=301]

Where am I doing wrong?

Body:
Rewrite rules use regex like this:

RewriteEngine on
RewriteRule ^/mylink.php?u=(.*) /mylink/$1 [R=301]

Reference: https://httpd.apache.org/docs/current/rewrite/intro.html


问:
Angular 2 how to handle asynchronous calls
First time button is clicked in form undefined is return, button has to be clicked twice to return correct result. How do I not process until result is return. When button clicked return correct result not previous one?

Product.componet.html

Product found

Price

Product details

{{ product.price }}

{{product.description}}

No Product found

```

<p>Product.compontent.ts</p>

<pre class="lang-typescript prettyprint-override"><code>onSubmit() {
    if (this.formModel.valid) {
        this.submitted = false;
        this.result = false;

        lens id = this.formModel.controls['id'].value;

        this.productService.getProductOne(id)
            .subscribe(product => this.product = product)

        //Check to see if object undefined
        if (this.product) {
            if (this.product.id != 0)
            {
                this.submitted = true;
            }
            else
            {
                this.result = true;
            }
        }
    }
}
</code>```

product-service.ts

  getProductOne(id: number): Observable<Product> {
      // Parameters obj
      let params: URLSearchParams = new URLSearchParams();
      params.set('id', id.toString());

      //Http request
      return this.http
          .get("api/getProduct", {
              search: params
          })
          .map(response => response.json())
          .catch(handleError);
  }
```

<p>Web api – ProductController.cs   </p>

<pre class="lang-csharp prettyprint-override"><code> [Route("api/getProduct")]
    public Product GetProduct(int id)
    {
        var product = products.FirstOrDefault((p) => p.id == id);

        if (product == null)
        {
            product = new Product();
        }

        return product;
    }
</code>```

答:
Modify your onSubmit() in Product.compontent.ts this way :

```<code>onSubmit() {
        if (this.formModel.valid) {
            this.submitted = false;
            this.result = false;

            lens id = this.formModel.controls['id'].value;

            this.productService.getProductOne(id).subscribe(
                    (product) => {
                     this.product = product;
                        //Check to see if object undefined
                        if (this.product) {
                            if (this.product.id != 0)
                            {
                                this.submitted = true;
                            }
                            else
                            {
                                this.result = true;
                            }
                        }
              });
        }
    }
</code>```

Body:
First time button is clicked in form undefined is return, button has to be clicked twice to return correct result. How do I not process until result is return. When button clicked return correct result not previous one?

Product.componet.html

Product found

Price

Product details

{{ product.price }}

{{product.description}}

No Product found

Product.compontent.ts

onSubmit() {
    if (this.formModel.valid) {
        this.submitted = false;
        this.result = false;

        lens id = this.formModel.controls['id'].value;

        this.productService.getProductOne(id)
            .subscribe(product => this.product = product)

        //Check to see if object undefined
        if (this.product) {
            if (this.product.id != 0)
            {
                this.submitted = true;
            }
            else
            {
                this.result = true;
            }
        }
    }
}

product-service.ts

  getProductOne(id: number): Observable<Product> {
      // Parameters obj
      let params: URLSearchParams = new URLSearchParams();
      params.set('id', id.toString());

      //Http request
      return this.http
          .get("api/getProduct", {
              search: params
          })
          .map(response => response.json())
          .catch(handleError);
  }

Web api – ProductController.cs

 [Route("api/getProduct")]
    public Product GetProduct(int id)
    {
        var product = products.FirstOrDefault((p) => p.id == id);

        if (product == null)
        {
            product = new Product();
        }

        return product;
    }

Body:
Modify your onSubmit() in Product.compontent.ts this way :

onSubmit() {
        if (this.formModel.valid) {
            this.submitted = false;
            this.result = false;

            lens id = this.formModel.controls['id'].value;

            this.productService.getProductOne(id).subscribe(
                    (product) => {
                     this.product = product;
                        //Check to see if object undefined
                        if (this.product) {
                            if (this.product.id != 0)
                            {
                                this.submitted = true;
                            }
                            else
                            {
                                this.result = true;
                            }
                        }
              });
        }
    }


问:
how to fix click button to show popup content and click out element area to close popup jquery
i have problem when trying setup code with Jquery

i want when click the button, the popup content will show, and when i click out area of content popup , the popup was close.

but my code have problems.
help me...

my code here :

```<code><button class="popup_dangky"></button>

<!-- show popup -->
<div id="thim-popup-login" class="has-shortcode">
    content popup
</div>

<script type="text/javascript">
/*  jQuery(document).ready(function(){*/
        jQuery('button.popup_dangky').click(function() {
            jQuery("div.has-shortcode").addClass("active");
        });

        jQuery("html").click(function(e){
                jQuery(".has-shortcode").removeClass("active");
        });
/*  });*/
</script>
</code>```

答:
When you click on button, htmlclick event is also trigger at same time.
below is updated code.

  jQuery(document).ready(function(){
        jQuery('button.popup_dangky').click(function() {
            jQuery("div.has-shortcode").addClass("active");
        });

       /* jQuery("html").click(function(e){
                jQuery(".has-shortcode").removeClass("active");
        });*/

        jQuery(document).mouseup(function (e)
          {
            var container = jQuery(".has-shortcode");

            if (!container.is(e.target) // if the target of the click isn't the container...
              && container.has(e.target).length === 0) // ... nor a descendant of the container
            {
              container.removeClass('active');
            }
 });

  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.has-shortcode{
  display:none
}
.active{
  display:inline !important;
}</code>```

<button class="popup_dangky">click</button>

    content popup

```

Body:
i have problem when trying setup code with Jquery

i want when click the button, the popup content will show, and when i click out area of content popup , the popup was close.

but my code have problems.
help me...

my code here :

<button class="popup_dangky"></button>

    content popup

Body:
When you click on button, htmlclick event is also trigger at same time.
below is updated code.

  jQuery(document).ready(function(){
        jQuery('button.popup_dangky').click(function() {
            jQuery("div.has-shortcode").addClass("active");
        });

       /* jQuery("html").click(function(e){
                jQuery(".has-shortcode").removeClass("active");
        });*/

        jQuery(document).mouseup(function (e)
          {
            var container = jQuery(".has-shortcode");

            if (!container.is(e.target) // if the target of the click isn't the container...
              && container.has(e.target).length === 0) // ... nor a descendant of the container
            {
              container.removeClass('active');
            }
 });

  });

.has-shortcode{
  display:none
}
.active{
  display:inline !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="popup_dangky">click</button>

<!-- show popup -->
<div id="thim-popup-login" class="has-shortcode">
    content popup
</div>


问:
ssh -L forward multiple ports
I'm currently running a bunch of:

```<code>sudo ssh -L PORT:IP:PORT root@IP
</code>```

where IP is the target of a secured machine, and PORT represents the ports I'm forwarding.

This is because I use a lot of applications which I cannot access without this forwarding. After performing this, I can access through localhost:PORT.

The main problem occured now that I actually have 4 of these ports that I have to forward.

My solution is to open 4 shells and constantly search my history backwards to look for exactly which ports need to be forwarded etc, and then run this command - one in each shell (having to fill in passwords etc).

If only I could do something like:

```<code>sudo ssh -L PORT1+PORT2+PORT+3:IP:PORT+PORT2+PORT3 root@IP
</code>```

then that would already really help.

Is there a way to make it easier to do this?

答:
You can use the following bash function (just add it to your ~/.bashrc):

```<code>function pfwd {
  for i in ${@:2}
  do
    echo Forwarding port $i
    ssh -N -L $i:localhost:$i $1 &
  done
}
</code>```

Usage example:

```<code>pfwd hostname {6000..6009}
</code>```

Title: ssh -L forward multiple ports

Body:
I'm currently running a bunch of:

sudo ssh -L PORT:IP:PORT root@IP

where IP is the target of a secured machine, and PORT represents the ports I'm forwarding.

This is because I use a lot of applications which I cannot access without this forwarding. After performing this, I can access through localhost:PORT.

The main problem occured now that I actually have 4 of these ports that I have to forward.

My solution is to open 4 shells and constantly search my history backwards to look for exactly which ports need to be forwarded etc, and then run this command - one in each shell (having to fill in passwords etc).

If only I could do something like:

sudo ssh -L PORT1+PORT2+PORT+3:IP:PORT+PORT2+PORT3 root@IP

then that would already really help.

Is there a way to make it easier to do this?

Body:
You can use the following bash function (just add it to your ~/.bashrc):

function pfwd {
  for i in ${@:2}
  do
    echo Forwarding port $i
    ssh -N -L $i:localhost:$i $1 &
  done
}

Usage example:

pfwd hostname {6000..6009}


问:
How to create a new branch from a tag?
I'd like to create a new master branch from an existing tag. Say I have a tag v1.0. How to create a new branch from this tag?

答:
My branch list (only master now)

My tag list (have three tags)

Switch to new branch feature/codec from opus_codec tag

```<code>git checkout -b feature/codec opus_codec
</code>```

Title: How to create a new branch from a tag?

Body:
My branch list (only master now)

My tag list (have three tags)

Switch to new branch feature/codec from opus_codec tag

git checkout -b feature/codec opus_codec


问:
No route matches [POST] "/account/new"
I'm trying to create a new account. but for some reason I'm getting this error when trying to submit the form No route matches [POST] "/account/new". Here is my form_for:

```<code><%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>
</code>```

ROUTES

```<code>account_index GET    /account(.:format)                                      account#index
                                  POST   /account(.:format)                                      account#create
                      new_account GET    /account/new(.:format)                                  account#new
                     edit_account GET    /account/:id/edit(.:format)                             account#edit
                          account GET    /account/:id(.:format)                                  account#show
                                  PATCH  /account/:id(.:format)                                  account#update
                                  PUT    /account/:id(.:format)                                  account#update
                                  DELETE /account/:id(.:format)                                  account#destroy
</code>```

ROUTES.RB

```<code>resources :account
</code>```

ACCOUNT CONTROLLER:

```<code>class AccountController < ApplicationController
  def new
    @account = Account.new
  end

  def create
    binding.pry
    interactor = CreateAccount.call(
      params: account_params,
      user: current_user
    )

    if interactor.success?
      redirect_to pages_dashboard_path
    else
      render :new
    end
  end

  private

  def account_params
    params.require(:account).permit(:name)
  end
end
</code>```

NEW.HTML.ERB

```<code><div class="plans">
  <h1>New Account Plan</h1>

  <%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>
    <div class="plans__trial">
      <h3>Trial</h3>
      <p>1 Worker</p>
      <p>1 Assignment</p>

      <p class="price">Price: Free</p>

      <label>
        <%= form.submit "Select", name: "trial", class: "button" %>
      </label>
    </div>

    <div class="plans__tier-1">
      <h3>Tier 1</h3>
      <p>Unlimited Workers</p>
      <p>Unlimited Assignments</p>

      <p class="price">Price: $9.00</p>

      <label>
        <input type="radio" required  />
        <a href="" class="button">Select</a>
      </label>
    </div>

    <div class="cc-fields">
      <%= render partial: "shared/cc-fields" %>
    </div>
    <%= form.submit name: "tier_1" %>
  <% end %>
</div>
</code>```

What am I doing wrong. Should it hit the create action? It's not currently.

答:
Change form_for line to just this, rails will automatically handle the routing if you follow Convention Over Configuration.

```<code><%= form_for @account do |form| %>
</code>```

Hope that helps!

Title: No route matches [POST] "/account/new"

Body:
I'm trying to create a new account. but for some reason I'm getting this error when trying to submit the form No route matches [POST] "/account/new". Here is my form_for:

<%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>

ROUTES

account_index GET    /account(.:format)                                      account#index
                                  POST   /account(.:format)                                      account#create
                      new_account GET    /account/new(.:format)                                  account#new
                     edit_account GET    /account/:id/edit(.:format)                             account#edit
                          account GET    /account/:id(.:format)                                  account#show
                                  PATCH  /account/:id(.:format)                                  account#update
                                  PUT    /account/:id(.:format)                                  account#update
                                  DELETE /account/:id(.:format)                                  account#destroy

ROUTES.RB

resources :account

ACCOUNT CONTROLLER:

class AccountController < ApplicationController
  def new
    @account = Account.new
  end

  def create
    binding.pry
    interactor = CreateAccount.call(
      params: account_params,
      user: current_user
    )

    if interactor.success?
      redirect_to pages_dashboard_path
    else
      render :new
    end
  end

  private

  def account_params
    params.require(:account).permit(:name)
  end
end

NEW.HTML.ERB

New Account Plan

  <%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>

Trial

1 Worker

1 Assignment

Price: Free

        <%= form.submit "Select", name: "trial", class: "button" %>

Tier 1

Unlimited Workers

Unlimited Assignments

Price: $9.00

        <input type="radio" required  />
        Select

      <%= render partial: "shared/cc-fields" %>

    <%= form.submit name: "tier_1" %>
  <% end %>

What am I doing wrong. Should it hit the create action? It's not currently.

Body:
Change form_for line to just this, rails will automatically handle the routing if you follow Convention Over Configuration.

<%= form_for @account do |form| %>

Hope that helps!