问:
angularjs filter only required text message
I have following code which prints 1.57 lakh View More Details

```<code><h4> Price: {{Object.price}}</h4>
</code>```

Would like to print only 1.57 lakh instead of printing all extra data.
Can we use filters here to eliminate extra data? if yes, How can we achieve this or are there any methods to achieve this?

答:
You can create a function and use split to get the relevant data and return it.

Demo

angular.module("app",[])
.controller("ctrl",function($scope){
$scope.price = "1.57 lakh View More Details";

$scope.removeText = function(text){
return text.split('lakh')[0]+'lakh';
}
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 {{removeText(price)}}
</div></code>```

Or you can create a custom filter like this also

angular.module("app",[])
.controller("ctrl",function($scope){
$scope.price = "1.57 lakh View More Details";

})
.filter('removeText',function(){
  return function(item){
    return item.split('lakh')[0]+'lakh';
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 {{price | removeText}}
</div></code>```

Body:
I have following code which prints 1.57 lakh View More Details

 Price: {{Object.price}}

Would like to print only 1.57 lakh instead of printing all extra data.
Can we use filters here to eliminate extra data? if yes, How can we achieve this or are there any methods to achieve this?

Body:
You can create a function and use split to get the relevant data and return it.

Demo

angular.module("app",[])
.controller("ctrl",function($scope){
$scope.price = "1.57 lakh View More Details";

$scope.removeText = function(text){
return text.split('lakh')[0]+'lakh';
}
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 {{removeText(price)}}
</div>

Or you can create a custom filter like this also

angular.module("app",[])
.controller("ctrl",function($scope){
$scope.price = "1.57 lakh View More Details";

})
.filter('removeText',function(){
  return function(item){
    return item.split('lakh')[0]+'lakh';
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 {{price | removeText}}
</div>


来源: stackexchange

问:
Get first value of Model's List in jQuery (document).ready using Razor?
How can I get the value of the first item from the model's List? My ViewModel:

```<code>namespace TestWeb
{
  public class NavViewModel
  {
    public NavViewModel()
    {
      NavStepList = new List<NavStep>();
    }

    public List<NavStep> NavStepList { get; set; }
  }
}
</code>```

In my View:

```<code>@using TestWeb
@model NavViewModel

<script>
  $(document).ready(function () {
    var Testvalue = @Model.NavStepList.First();
  });
</script>
</code>```

I want the first value of NavStepList. However an error occurs when I call this function:

TestWeb is undefined

I already test with testing value assign to NavStepList but the error still occurs.

My NavStep Class Property:

```<code>public class NavStep{
        public int NavStepId { get; set; }
        public int SortId { get; set; }
        public string StepName { get; set; }
        public string IdentifierKey { get; set; }
        public bool IsAvailible { get; set; }
}
</code>```

答:
You could convert your server side view model to a javascript variable using the following:

```<code><script>
    $(document).ready(function () {
        var myModel = @Html.Raw(Json.Encode(Model.NavStepList.First()));
    });
</script>
</code>```

and then you could access your model properties in javascript:

```<code>alert(myModel.NavStepId);
alert(myModel.SortId);
alert(myModel.StepName);
...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I get the value of the first item from the model's List? My ViewModel:

namespace TestWeb
{
  public class NavViewModel
  {
    public NavViewModel()
    {
      NavStepList = new List<NavStep>();
    }

    public List<NavStep> NavStepList { get; set; }
  }
}

In my View:

@using TestWeb
@model NavViewModel

I want the first value of NavStepList. However an error occurs when I call this function:

TestWeb is undefined

I already test with testing value assign to NavStepList but the error still occurs.

My NavStep Class Property:

public class NavStep{
        public int NavStepId { get; set; }
        public int SortId { get; set; }
        public string StepName { get; set; }
        public string IdentifierKey { get; set; }
        public bool IsAvailible { get; set; }
}

Body:
You could convert your server side view model to a javascript variable using the following:

<script>
    $(document).ready(function () {
        var myModel = @Html.Raw(Json.Encode(Model.NavStepList.First()));
    });
</script>

and then you could access your model properties in javascript:

alert(myModel.NavStepId);
alert(myModel.SortId);
alert(myModel.StepName);
...


问:
Android Card View ripple effect starts right after a click
I have a simple card view list. When clicking a card, I set a ripple effect:

```<code><android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="170dp"
android:layout_margin="5dp"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
card_view:cardBackgroundColor="@android:color/white"
card_view:cardCornerRadius="5dp"

card_view:cardUseCompatPadding="true">
</code>```

It seems like the ripple effect starts right after I click on a card.
So the ripple effect happens most of the times I just click on the card in order to scroll it. This is an annoying behavior.

Is there a way of "delaying" the ripple effect or making it happen only on a real click and not also on a scroll?

答: Set android:clickable="true" in card view.

Body:
I have a simple card view list. When clicking a card, I set a ripple effect:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="170dp"
android:layout_margin="5dp"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
card_view:cardBackgroundColor="@android:color/white"
card_view:cardCornerRadius="5dp"

card_view:cardUseCompatPadding="true">

It seems like the ripple effect starts right after I click on a card.
So the ripple effect happens most of the times I just click on the card in order to scroll it. This is an annoying behavior.

Is there a way of "delaying" the ripple effect or making it happen only on a real click and not also on a scroll?


问:
how to print null value from javascript array?
I have data from php variable :

```<code>$data['value'] = [null, 24.5, 22.5, null, 30.1];
</code>```

I convert it into javascript using this code :

```<code>var newData = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;
</code>```

I get output like this : , 24.5, 22.5,, 30.1

anyone can tell what's wrong with my code?

UPDATE

PHP variable :

```<code>$data['value'][] = null;
$data['value'][] = 24.5;
$data['value'][] = 22.5;
$data['value'][] = null;
$data['value'][] = 30.1;

$data['value2'][] = 20.5;
$data['value2'][] = 19.5;
$data['value2'][] = 30.1;
$data['value2'][] = null;

    echo json_encode($data, JSON_NUMERIC_CHECK);
</code>```

output : {"value":[null, 24.5, 22.5, null, 30.1],"value2":[20.5,19.5,30.1,null]};

JAVASCRIPT :

```<code>var newData = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;

document.write(newData['value']);
</code>```

output : , 24.5, 22.5,, 30.1

i need javascript output to be like this : null, 24.5, 22.5, null, 30.1

答:
You could use array_walk to go over every item in the array and turn them to string if they are null.

```<code><?php

$data['value'] = [null, 24.5, 22.5, null, 30.1];
function x(&$el) {
    $el = ($el === null) ? 'null' : $el;
}
array_walk($data['value'], 'x');

?>

<script type="text/javascript">
    var newData = <?php echo json_encode($data['value'], JSON_NUMERIC_CHECK); ?>;
    alert(newData);
</script>
</code>```

Body:
I have data from php variable :

$data['value'] = [null, 24.5, 22.5, null, 30.1];

I convert it into javascript using this code :

var newData = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;

I get output like this : , 24.5, 22.5,, 30.1

anyone can tell what's wrong with my code?

UPDATE

PHP variable :

$data['value'][] = null;
$data['value'][] = 24.5;
$data['value'][] = 22.5;
$data['value'][] = null;
$data['value'][] = 30.1;

$data['value2'][] = 20.5;
$data['value2'][] = 19.5;
$data['value2'][] = 30.1;
$data['value2'][] = null;

    echo json_encode($data, JSON_NUMERIC_CHECK);

output : {"value":[null, 24.5, 22.5, null, 30.1],"value2":[20.5,19.5,30.1,null]};

JAVASCRIPT :

var newData = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;

document.write(newData['value']);

output : , 24.5, 22.5,, 30.1

i need javascript output to be like this : null, 24.5, 22.5, null, 30.1

Body:
You could use array_walk to go over every item in the array and turn them to string if they are null.

<?php

$data['value'] = [null, 24.5, 22.5, null, 30.1];
function x(&$el) {
    $el = ($el === null) ? 'null' : $el;
}
array_walk($data['value'], 'x');

?>

<script type="text/javascript">
    var newData = <?php echo json_encode($data['value'], JSON_NUMERIC_CHECK); ?>;
    alert(newData);
</script>


问:
Calling JSON from another activity JAVA
I am trying to call the following method which is supposed to parse a JSON file from another activity. How come Android Studio is showing me a error?

This is the first activity called FirstActivity.java

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);

        ReadJSON classToReadJSON = new ReadJSON();
        classToReadJSON.loadJSONFromAsset();
    }}
</code>```

This is my second class ReadJSON.java:

```<code>public class ReadJSON extends AppCompatActivity{
    public String loadJSONFromAsset() {
            String json = null;
            try {
                InputStream is = getAssets().open("jsonfile.json");
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                json = new String(buffer, "UTF-8");
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
            return json;
        }
}
</code>```

The code to parse the JSON file derives from Faizan's answer.
Reading a json file in Android

Edit: Sorry for not having posted the error log, I am still pretty new to programming.

So this is the error log:

```<code>D/AndroidRuntime: Shutting down VM

                  --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.zeus.jsonstackoverflow, PID: 2805
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.zeus.jsonstackoverflow/com.example.zeus.jsonstackoverflow.FirstActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                      at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
                      at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
                      at android.view.ContextThemeWrapper.getAssets(ContextThemeWrapper.java:116)
                      at com.example.zeus.jsonstackoverflow.ReadJSON.loadJSONFromAsset(ReadJSON.java:16)
                      at com.example.zeus.jsonstackoverflow.FirstActivity.onCreate(FirstActivity.java:14)
                      at android.app.Activity.performCreate(Activity.java:6662)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

I would highly appreciate any help on this matter.

答:
Thank you for your help so far everybody!

I could find out that it has to do with the following line.

```<code>        InputStream is = getAssets().open("jsonfile.json");
</code>```

Why is it not possible to call this line from my first activity?

Title: Calling JSON from another activity JAVA

Body:
I am trying to call the following method which is supposed to parse a JSON file from another activity. How come Android Studio is showing me a error?

This is the first activity called FirstActivity.java

 public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);

        ReadJSON classToReadJSON = new ReadJSON();
        classToReadJSON.loadJSONFromAsset();
    }}

This is my second class ReadJSON.java:

public class ReadJSON extends AppCompatActivity{
    public String loadJSONFromAsset() {
            String json = null;
            try {
                InputStream is = getAssets().open("jsonfile.json");
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                json = new String(buffer, "UTF-8");
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
            return json;
        }
}

The code to parse the JSON file derives from Faizan's answer.
Reading a json file in Android

Edit: Sorry for not having posted the error log, I am still pretty new to programming.

So this is the error log:

D/AndroidRuntime: Shutting down VM

                  --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.zeus.jsonstackoverflow, PID: 2805
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.zeus.jsonstackoverflow/com.example.zeus.jsonstackoverflow.FirstActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                      at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
                      at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
                      at android.view.ContextThemeWrapper.getAssets(ContextThemeWrapper.java:116)
                      at com.example.zeus.jsonstackoverflow.ReadJSON.loadJSONFromAsset(ReadJSON.java:16)
                      at com.example.zeus.jsonstackoverflow.FirstActivity.onCreate(FirstActivity.java:14)
                      at android.app.Activity.performCreate(Activity.java:6662)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

I would highly appreciate any help on this matter.

Body:
Thank you for your help so far everybody!

I could find out that it has to do with the following line.

        InputStream is = getAssets().open("jsonfile.json");

Why is it not possible to call this line from my first activity?


问:
Why might Graphics.RotateTransform() not be applied?
I have the following function:

```<code>static private Image CropRotate(Image wholeImage, Rectangle cropArea)
{
    Bitmap cropped = new Bitmap(cropArea.Width, cropArea.Height);

    using(Graphics g = Graphics.FromImage(cropped))
    {
        g.DrawImage(wholeImage, new Rectangle(0, 0, cropArea.Width, cropArea.Height), cropArea, GraphicsUnit.Pixel);
        g.RotateTransform(180f);
    }
    return cropped as Image;
}
</code>```

It's supposed to crop an image, then rotate the resulting sub-image. In actuality though, it only performs the crop.

Why is RotateTransform() not being applied?

答:
Have you tried putting the RotateTransform() before the DrawImage()?
The example on the msdn page shows the transformation being applied before any drawing is done.

ContentLicense: CC BY-SA 2.5

Body:
I have the following function:

static private Image CropRotate(Image wholeImage, Rectangle cropArea)
{
    Bitmap cropped = new Bitmap(cropArea.Width, cropArea.Height);

    using(Graphics g = Graphics.FromImage(cropped))
    {
        g.DrawImage(wholeImage, new Rectangle(0, 0, cropArea.Width, cropArea.Height), cropArea, GraphicsUnit.Pixel);
        g.RotateTransform(180f);
    }
    return cropped as Image;
}

It's supposed to crop an image, then rotate the resulting sub-image. In actuality though, it only performs the crop.

Why is RotateTransform() not being applied?


问:
What does this Perl statement mean?
I'm trying to parse a Perl script to Python. I have next to no experience with Perl, but still it's going surprisingly smooth. The Perl documentation is vast and impressive. However, from time to time there are some really cryptic syntax I really can't figure out and I'm not in a position of communicating with the author of the script. The following has given me a headache for quite some time now:

```<code>sub someSubroutine
{
    my ($var1, $var2, $var3) = @_;

    # some Perl code

    $var2 =~ s|/|\\|g;

    # and then some more code ..
}
</code>```

I really don't get this one particular and lonely line

```<code>$dst =~ s|/|\\|g;
</code>```

I'm clear that it makes a search/string-match in $var2 with some binary OR operations, but the result is not stored.

I wonder if it has any not so apparent side effects, for instance is it automatically stored in $_?

From what I've read, the default variables are set automatically when one calls a subroutine, initiates a loop or similar, but nothing about when using operators.

I would really appreciate any help or pointers to appropriate documentation.

答:
In the

```<code>$var2 =~ s|/|\\|g;
</code>```

the s/pattern/replacement/ is the substitution operator.

Searches a string for a pattern, and if found, replaces that pattern
  with the replacement text and returns the number of substitutions
  made. Otherwise it returns false (specifically, the empty string).

The | isn't "binary or" - it is a delimiter. In the s you can use any delimiter, especially for easier reading.

from the perlop Regexp Quote-Like Operators

Any non-whitespace delimiter may replace the slashes. Add space after
  the s when using a character allowed in identifiers. If single quotes
  are used, no interpretation is done on the replacement string (the /e
  modifier overrides this, however). Note that Perl treats backticks as
  normal delimiters; the replacement text is not evaluated as a command.
  If the PATTERN is delimited by bracketing quotes, the REPLACEMENT has
  its own pair of quotes, which may or may not be bracketing quotes, for
  example, s(foo)(bar) or s/bar/.

The above replaces every / with \ in the $var2. (The \ is escape character, therefore you need use \\).

```<code>my $v='/a/b/c';
$v =~ s|/|\\|g;
print "$v\n";
# \a\b\c
</code>```

Also,

If no string is specified via the =~ or !~ operator, the $_ variable
  is searched and modified.

$_ = $v;     # assign the $_
s{\\}{/}g;   # substitution on the $_ using bracketed delimiters
print;       # without args prints the $_
# /a/b/c
```

Title: What does this Perl statement mean?

Body:
I'm trying to parse a Perl script to Python. I have next to no experience with Perl, but still it's going surprisingly smooth. The Perl documentation is vast and impressive. However, from time to time there are some really cryptic syntax I really can't figure out and I'm not in a position of communicating with the author of the script. The following has given me a headache for quite some time now:

sub someSubroutine
{
    my ($var1, $var2, $var3) = @_;

    # some Perl code

    $var2 =~ s|/|\\|g;

    # and then some more code ..
}

I really don't get this one particular and lonely line

$dst =~ s|/|\\|g;

I'm clear that it makes a search/string-match in $var2 with some binary OR operations, but the result is not stored.

I wonder if it has any not so apparent side effects, for instance is it automatically stored in $_?

From what I've read, the default variables are set automatically when one calls a subroutine, initiates a loop or similar, but nothing about when using operators.

I would really appreciate any help or pointers to appropriate documentation.

Body:
In the

$var2 =~ s|/|\\|g;

the s/pattern/replacement/ is the substitution operator.

Searches a string for a pattern, and if found, replaces that pattern
  with the replacement text and returns the number of substitutions
  made. Otherwise it returns false (specifically, the empty string).

The | isn't "binary or" - it is a delimiter. In the s you can use any delimiter, especially for easier reading.

from the perlop Regexp Quote-Like Operators

Any non-whitespace delimiter may replace the slashes. Add space after
  the s when using a character allowed in identifiers. If single quotes
  are used, no interpretation is done on the replacement string (the /e
  modifier overrides this, however). Note that Perl treats backticks as
  normal delimiters; the replacement text is not evaluated as a command.
  If the PATTERN is delimited by bracketing quotes, the REPLACEMENT has
  its own pair of quotes, which may or may not be bracketing quotes, for
  example, s(foo)(bar) or s/bar/.

The above replaces every / with \ in the $var2. (The \ is escape character, therefore you need use \\).

my $v='/a/b/c';
$v =~ s|/|\\|g;
print "$v\n";
# \a\b\c

Also,

If no string is specified via the =~ or !~ operator, the $_ variable
  is searched and modified.

$_ = $v;     # assign the $_
s{\\}{/}g;   # substitution on the $_ using bracketed delimiters
print;       # without args prints the $_
# /a/b/c


问:
How to make two apps Yii1 and Yii2 use the same session?
I want to make a dashboard panel web in my existing website. The existing app is using Yii1 can be accessible via, let's say, www.example.com. I want to make www.example.com/dashboard using new app using Yii2. I already made the apache configuration.

But what's missing is the session. Users that logged in through Yii1 app will not be recognized in the dashboard.

How to make Yii1 and Yii2 use the same session data, i.e. user that logged in at Yii1 will be recognized in Yii2 vice versa?

UPDATE

The architecture is standard multiple web servers behind a load balancer.
The two app can be hosted in the same server instance (the config will be in the apache). Or they can be in different (the load balancer will handle the directory too).
But both will use the same memcache server for session storage. The apps also will use the same database, although the ActiveRecord implementation will obviously be in different code. As long as I can get the user ID of the current logged user, it should be okay.

答:
It is possible to share session between two applications (Yii1 and Yii2). Here is how to do it if you are using CDbHttpSession in Yii1 and yii\web\DbSession in Yii2 (I didn't test it with other types of session storage, but it should work same):

In Yii2 configuration for yii\web\DbSession for you application you should setup session name to be PHPSESSID so it can match one used by Yii1.

Since in Yii1 CWebUser use prefix for storing logged user id and other things from user state, you should set this to be empty string (or what ever you can share between both application. Yii2 doesn't use prefix, so empty string works good too) ''. You can do it by extending CWebUser and add something like this inside public function init():

public function init() {
    $this->setStateKeyPrefix('');
    parent::init();
}

This is all what you need to be able to share session between two application.


问:
Same Remote Validation for 2 different properties in a model
I have 2 properties contractor1 and contractor2 in a model, how can I use a single remote validation for both of them

```<code>[Display(Name ="Contractor 1:")]
[Remote("ValidateContractor", "Contracts")]
public string Cntrctr1 {get; set;}

[Display(Name = "Contractor 2:")]
[Remote("ValidateContractor", "Contracts")]`enter code here`
public string Cntrctr2 {get; set;}
</code>```

Remote Validation function in the Controller

```<code>public JsonResult ValidateContractor1(string Cntrctr)
{
    var valid = Validations.ValidateContractor(Cntrctr);
    if (!valid)
    {return Json("Enter correct contractor", JsonRequestBehavior.AllowGet);}
    else{return Json(true, JsonRequestBehavior.AllowGet);}
}
public static bool ValidateContractor(string CntrctrNM)
{
    bool valid;
    using (var entities = new CAATS_Entities())
    {
        var result = (from t in entities.PS_VENDOR_V
                      where (t.VNDR_1_NM).Equals(CntrctrNM)
                      select t).FirstOrDefault();
        if (result != null)
        {
            valid = true;
        }
        else
        {
            valid = false;
        }
    }
    return valid;

}
</code>```

This doesn't work. Can you please help me with this?

答:
Adding onto Rhumborls answer if you find his method not to work it might be because you're using forms; if this is the case you need to use the Form attribute instead of the QueryString as so.</p>

```<code>public JsonResult ValidateContractor()
{
    // gets the name of the property being validated, e.g. "Cntrctr1"
    string fieldName = Request.Form.Keys[0];

    // gets the value to validate
    string Cntrctr = Request.Form[fieldName];

    // carry on as before
    var valid = Validations.ValidateContractor(Cntrctr);
    if (!valid)
    {return Json("Enter correct contractor", JsonRequestBehavior.AllowGet);}
    else{return Json(true, JsonRequestBehavior.AllowGet);}
}
</code>```

Body:
I have 2 properties contractor1 and contractor2 in a model, how can I use a single remote validation for both of them

[Display(Name ="Contractor 1:")]
[Remote("ValidateContractor", "Contracts")]
public string Cntrctr1 {get; set;}

[Display(Name = "Contractor 2:")]
[Remote("ValidateContractor", "Contracts")]`enter code here`
public string Cntrctr2 {get; set;}

Remote Validation function in the Controller

public JsonResult ValidateContractor1(string Cntrctr)
{
    var valid = Validations.ValidateContractor(Cntrctr);
    if (!valid)
    {return Json("Enter correct contractor", JsonRequestBehavior.AllowGet);}
    else{return Json(true, JsonRequestBehavior.AllowGet);}
}
public static bool ValidateContractor(string CntrctrNM)
{
    bool valid;
    using (var entities = new CAATS_Entities())
    {
        var result = (from t in entities.PS_VENDOR_V
                      where (t.VNDR_1_NM).Equals(CntrctrNM)
                      select t).FirstOrDefault();
        if (result != null)
        {
            valid = true;
        }
        else
        {
            valid = false;
        }
    }
    return valid;

}

This doesn't work. Can you please help me with this?

Body:
Adding onto Rhumborls answer if you find his method not to work it might be because you're using forms; if this is the case you need to use the Form attribute instead of the QueryString as so.

public JsonResult ValidateContractor()
{
    // gets the name of the property being validated, e.g. "Cntrctr1"
    string fieldName = Request.Form.Keys[0];

    // gets the value to validate
    string Cntrctr = Request.Form[fieldName];

    // carry on as before
    var valid = Validations.ValidateContractor(Cntrctr);
    if (!valid)
    {return Json("Enter correct contractor", JsonRequestBehavior.AllowGet);}
    else{return Json(true, JsonRequestBehavior.AllowGet);}
}


问:
From phone number is not valid SMS capable inbound phone number
I am trying to use my Auth0 custom UI in android to login with phone number using AuthenticationAPIClient. I get this error when I call authAPIClient.passwordlessWithSMS:

The From phone number +441792720641 is not a valid, SMS-capable inbound phone number or short code for your account. (Code: 21606)

Looks like this is a Twilio error, I have checked in twilio console this UK number has voice and sms enabled, and I got this number as part of trial.

How can I get past this error?

答:
Twilio developer evangelist here.

UK landline numbers, such as the one you have, cannot receive messages from international numbers. If you want to use a UK number, then I recommend getting a UK mobile number. They can send and receive SMS internationally, but cannot make voice calls (which shouldn't be a problem if you are using it for SMS login).

If this is a trial, then the number can also only send to numbers that you have verified in your account.

Does that help at all?


问:
C# .Net Core dependency injection, inject multiple parameters to constructor
I have AuthenticationStrategy class which I'm going to inject in controller constructor.

I have two IAuthenticationProviders: InternalAuthenticationProvider and ExternalAuthenticationProvider.

In AuthenticationStrategy constructor I want to inject all providers.

Sample code:

```<code>public class AuthenticationStrategy
{
    private readonly Dictionary<string, IAuthenticationProvider> _authenticationProviders;

    public AuthenticationStrategy(IAuthenticationProvider[] authenticationProviders)
    {
        if (authenticationProviders == null)
        {
            throw new ArgumentNullException("AuthenticationProviders");
        }

        _authenticationProviders = authenticationProviders
            .ToDictionary(x => nameof(x), x => x);
    }
}
</code>```

How can I inject multiple providers using depency injection?
Sample code:

```<code>services.AddScoped<IAuthenticationProvider, InternalAuthenticationProvider>();
services.AddScoped<IAuthenticationProvider, ExternalAuthenticationProvider>();
services.AddScoped<AuthenticationStrategy>();
</code>```

Any ideas?

答:
If you're sticking with the OOTB dependency injection setup i.e. not using a third party container then one option would be to be explicit in your constructor args like this:

```<code>public class AuthenticationStrategy
{
    public AuthenticationStrategy(
        IInternalAuthenticationProvider internal,
        IExternalAuthenticationProvider external)
    {
        ...
    }
}
</code>```

IInternalAuthenticationProvider and IExternalAuthenticationProvider interfaces are nothing more than marker interfaces like so:

```<code>public interface IInternalAuthenticationProvider : IAuthenticationProvider { }
public interface IExternalAuthenticationProvider : IAuthenticationProvider { }
</code>```

So your DI setup will now look like this:

```<code>services.AddScoped<IInternalAuthenticationProvider , InternalAuthenticationProvider>();
services.AddScoped<IExternalAuthenticationProvider , ExternalAuthenticationProvider>();
services.AddScoped<AuthenticationStrategy>();
</code>```

Body:
I have AuthenticationStrategy class which I'm going to inject in controller constructor.

I have two IAuthenticationProviders: InternalAuthenticationProvider and ExternalAuthenticationProvider.

In AuthenticationStrategy constructor I want to inject all providers.

Sample code:

public class AuthenticationStrategy
{
    private readonly Dictionary<string, IAuthenticationProvider> _authenticationProviders;

    public AuthenticationStrategy(IAuthenticationProvider[] authenticationProviders)
    {
        if (authenticationProviders == null)
        {
            throw new ArgumentNullException("AuthenticationProviders");
        }

        _authenticationProviders = authenticationProviders
            .ToDictionary(x => nameof(x), x => x);
    }
}

How can I inject multiple providers using depency injection?
Sample code:

services.AddScoped<IAuthenticationProvider, InternalAuthenticationProvider>();
services.AddScoped<IAuthenticationProvider, ExternalAuthenticationProvider>();
services.AddScoped<AuthenticationStrategy>();

Any ideas?

Body:
If you're sticking with the OOTB dependency injection setup i.e. not using a third party container then one option would be to be explicit in your constructor args like this:

public class AuthenticationStrategy
{
    public AuthenticationStrategy(
        IInternalAuthenticationProvider internal,
        IExternalAuthenticationProvider external)
    {
        ...
    }
}

IInternalAuthenticationProvider and IExternalAuthenticationProvider interfaces are nothing more than marker interfaces like so:

public interface IInternalAuthenticationProvider : IAuthenticationProvider { }
public interface IExternalAuthenticationProvider : IAuthenticationProvider { }

So your DI setup will now look like this:

services.AddScoped<IInternalAuthenticationProvider , InternalAuthenticationProvider>();
services.AddScoped<IExternalAuthenticationProvider , ExternalAuthenticationProvider>();
services.AddScoped<AuthenticationStrategy>();


问:
Is it possible to change the size of the text in an HTML input tag?
I have a client who wants bigger text in an <input> box.  I would prefer to not have to make custom graphic button for this as it's on a really resource-constrained embedded system.

答:
Yep, it is possible and also simple to do!

HTML:

```<code><input type="text" class="example_input" name="example_input" />
</code>```

And the CSS:

```<code>.example_input{
font: Arial, Helvetica, sans-serif 20px bold;
border: 1px black solid; //optional
}
</code>```

Hope it helped!

EDIT: Example on jsFiddle

Body:
Yep, it is possible and also simple to do!

HTML:

<input type="text" class="example_input" name="example_input" />

And the CSS:

.example_input{
font: Arial, Helvetica, sans-serif 20px bold;
border: 1px black solid; //optional
}

Hope it helped!

EDIT: Example on jsFiddle


问:
Rails - document.ready not working in specific JavaScript file
A piece of JavaScript I wrote (which lives in app/assets/javascripts/tenant_content.js) wasn't working so I boiled it down to the following in order to test it:

```<code>$(document).ready(function() {
  console.log("Test");
});
</code>```

When I refresh the page nothing is logged to the console.

If I remove the console.log from within the document.ready then it prints just fine. The strange thing is it also works if I move it to one of my other JavaScript files. It seems to be the combination of being in this particular file and being within the document.ready function that causes it not to work. Any ideas why?

Note: I'm not using Turbolinks.

Thanks

答:
There was an error in a different JavaScript file that was stopping the rest of the JavaScript from running. The reason it was specific to one file was because it was the only file that came after the error file in the tree:

```<code>javascripts
  counter.js
  notices.js
  stripe.js                << this is where the error occurred...
  tenant_content.js        << ...so the JS in this file wasn't running
</code>```

I hadn't realised that anything after the error wouldn't run.

Body:
A piece of JavaScript I wrote (which lives in app/assets/javascripts/tenant_content.js) wasn't working so I boiled it down to the following in order to test it:

$(document).ready(function() {
  console.log("Test");
});

When I refresh the page nothing is logged to the console.

If I remove the console.log from within the document.ready then it prints just fine. The strange thing is it also works if I move it to one of my other JavaScript files. It seems to be the combination of being in this particular file and being within the document.ready function that causes it not to work. Any ideas why?

Note: I'm not using Turbolinks.

Thanks

Body:
There was an error in a different JavaScript file that was stopping the rest of the JavaScript from running. The reason it was specific to one file was because it was the only file that came after the error file in the tree:

javascripts
  counter.js
  notices.js
  stripe.js                << this is where the error occurred...
  tenant_content.js        << ...so the JS in this file wasn't running

I hadn't realised that anything after the error wouldn't run.


问:
Importing Excel File Through php and i always get an error of undefined offset
Here is my exact code and im always getting an error of Undefined offset in my array

```<code><?php
require_once('../../../Backend/Listings_Database/Listings_Connection.php');

$Response = array();

if($_FILES["file"]["size"] > 0) {
    $filename=$_FILES["file"]["tmp_name"];

    $file = fopen($filename, "r");
    while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
        (name,brand,cat_id,
         store_size,location_floor_unit,phone,traffic_of_mall,
         time_of_traffic,city)
        values('$emapData[0]','$emapData[1]','$emapData[2]',
               '$emapData[3]','$emapData[4]','$emapData[5]',
               '$emapData[6]','$emapData[7]','$emapData[8]')";

        //we are using mysql_query function. it returns a resource on true else False on error

        $result = mysqli_query($sql,$Listings_Database);

        if(! $result ) {
            $Response[] = "Fail";
        } else {
            $Response[] = "Success";
        }
    }
    fclose($file);

    $Response[] = "Success";

    mysqli_close($Listings_Database);
} else {
    $Response[] = "Fail";
}

var_dump($Response);

print json_encode($Response);

?>
</code>```

Here is my exact code and im always getting an error of Undefined offset in my array

答:
Which line shows this "getting an error of Undefined offset" error.
Also take this approach:

```<code> $name = !empty($emapData[0]) ? $emapData[0] : '';
 $brand = !empty($emapData[1]) ? $emapData[1] : '';
</code>```

and so on...
 And then use in your query:

insert into <tableName>
(name,brand,cat_id,store_size,location_floor_unit,phone,traffic_of_mall,time_of_traffic,city) values('$name','$brand',......)";

Body:
Here is my exact code and im always getting an error of Undefined offset in my array

<?php
require_once('../../../Backend/Listings_Database/Listings_Connection.php');

$Response = array();

if($_FILES["file"]["size"] > 0) {
    $filename=$_FILES["file"]["tmp_name"];

    $file = fopen($filename, "r");
    while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
        (name,brand,cat_id,
         store_size,location_floor_unit,phone,traffic_of_mall,
         time_of_traffic,city)
        values('$emapData[0]','$emapData[1]','$emapData[2]',
               '$emapData[3]','$emapData[4]','$emapData[5]',
               '$emapData[6]','$emapData[7]','$emapData[8]')";

        //we are using mysql_query function. it returns a resource on true else False on error

        $result = mysqli_query($sql,$Listings_Database);

        if(! $result ) {
            $Response[] = "Fail";
        } else {
            $Response[] = "Success";
        }
    }
    fclose($file);

    $Response[] = "Success";

    mysqli_close($Listings_Database);
} else {
    $Response[] = "Fail";
}

var_dump($Response);

print json_encode($Response);

?>

Here is my exact code and im always getting an error of Undefined offset in my array

Body:
Which line shows this "getting an error of Undefined offset" error.
Also take this approach:

 $name = !empty($emapData[0]) ? $emapData[0] : '';
 $brand = !empty($emapData[1]) ? $emapData[1] : '';

and so on...
 And then use in your query:

insert into <tableName>
(name,brand,cat_id,store_size,location_floor_unit,phone,traffic_of_mall,time_of_traffic,city) values('$name','$brand',......)";


问:
how to add a MVC View in template URI of typescript component?
I am developing an application in MVC core and angularjs2(with typescript).
I added a  new component (View is placed in Views\Home\Default.cshml ) but it is not working.

please see my tried code below:

```<code>import { Component, OnInit } from '@angular/core';
import { IndexService } from './index.service';

@Component({
    templateUrl: '/Home/Default',
    //styleUrls: ['app/default/index.component.css'],
    providers: [IndexService]
})
export class IndexComponent implements OnInit {
    pageTitle: string = 'Sign Up';
    imageWidth: number = 50;
    imageMargin: number = 2;
    showImage: boolean = false;
    listFilter: string;
    errorMessage: string;

    constructor(private _indexService: IndexService) {

    }
    toggleImage(): void {
        this.showImage = !this.showImage;
    }

    ngOnInit(): void {
        //this._companyService.getCompanies()
        //    .subscribe(companies => this.companies = companies,
        //                   error => this.errorMessage = <any>error);
    }
    onRatingClicked(message: string): void {
        this.pageTitle = 'Sign Up: ' + message;
    }

    onSignUpClicked(indexService: IndexService): void {
        //this._companyService.saveCompanySignUp(company).subscribe(
        //    (data) => {
        //        this.company = data;
        //        console.log("Item " + this.company.Id + " has been added.");
        //        //this.router.navigate([""]);
        //    },
        //    (error) => console.log(error)
        //);
    }

}
  public IActionResult Default()
        {
            return View();
        }
</code>```

When i try to run the application, I am facing exception in browser's console.

```<code>Please specify a ShareThis Publisher Key
For help, contact support@sharethis.com
util.js:211 Google Maps API warning: SensorNotRequired https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required
aB.j @ util.js:211
http://localhost:5000/Home/Default Failed to load resource: the server responded with a status of 500 (Internal Server Error)
zone.js:388 Unhandled Promise rejection: Failed to load /Home/Default ; Zone: <root> ; Task: Promise.then ; Value: Failed to load /Home/Default undefined
consoleError @ zone.js:388
zone.js:390 Error: Uncaught (in promise): Failed to load /Home/Default
    at resolvePromise (zone.js:468)
    at resolvePromise (zone.js:453)
    at zone.js:502
    at ZoneDelegate.invokeTask (zone.js:265)
    at Zone.runTask (zone.js:154)
    at drainMicroTaskQueue (zone.js:401)
    at XMLHttpRequest.ZoneTask.invoke (zone.js:339)
</code>```

答:
Use   moduleId: module.id in component decorator  </p>

```<code>@Component({
    moduleId: module.id,
    templateUrl: '/Home/Default',
    //styleUrls: ['app/default/index.component.css'],
    providers: [IndexService]
})
</code>```

Body:
I am developing an application in MVC core and angularjs2(with typescript).
I added a  new component (View is placed in Views\Home\Default.cshml ) but it is not working.

please see my tried code below:

import { Component, OnInit } from '@angular/core';
import { IndexService } from './index.service';

@Component({
    templateUrl: '/Home/Default',
    //styleUrls: ['app/default/index.component.css'],
    providers: [IndexService]
})
export class IndexComponent implements OnInit {
    pageTitle: string = 'Sign Up';
    imageWidth: number = 50;
    imageMargin: number = 2;
    showImage: boolean = false;
    listFilter: string;
    errorMessage: string;

    constructor(private _indexService: IndexService) {

    }
    toggleImage(): void {
        this.showImage = !this.showImage;
    }

    ngOnInit(): void {
        //this._companyService.getCompanies()
        //    .subscribe(companies => this.companies = companies,
        //                   error => this.errorMessage = <any>error);
    }
    onRatingClicked(message: string): void {
        this.pageTitle = 'Sign Up: ' + message;
    }

    onSignUpClicked(indexService: IndexService): void {
        //this._companyService.saveCompanySignUp(company).subscribe(
        //    (data) => {
        //        this.company = data;
        //        console.log("Item " + this.company.Id + " has been added.");
        //        //this.router.navigate([""]);
        //    },
        //    (error) => console.log(error)
        //);
    }

}
  public IActionResult Default()
        {
            return View();
        }

When i try to run the application, I am facing exception in browser's console.

Please specify a ShareThis Publisher Key
For help, contact support@sharethis.com
util.js:211 Google Maps API warning: SensorNotRequired https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required
aB.j @ util.js:211
http://localhost:5000/Home/Default Failed to load resource: the server responded with a status of 500 (Internal Server Error)
zone.js:388 Unhandled Promise rejection: Failed to load /Home/Default ; Zone: <root> ; Task: Promise.then ; Value: Failed to load /Home/Default undefined
consoleError @ zone.js:388
zone.js:390 Error: Uncaught (in promise): Failed to load /Home/Default
    at resolvePromise (zone.js:468)
    at resolvePromise (zone.js:453)
    at zone.js:502
    at ZoneDelegate.invokeTask (zone.js:265)
    at Zone.runTask (zone.js:154)
    at drainMicroTaskQueue (zone.js:401)
    at XMLHttpRequest.ZoneTask.invoke (zone.js:339)

Body:
Use   moduleId: module.id in component decorator

@Component({
    moduleId: module.id,
    templateUrl: '/Home/Default',
    //styleUrls: ['app/default/index.component.css'],
    providers: [IndexService]
})


问:
Troubles with encoding, pattern matching and noisy texts in R
We are experiencing problems with encoding, pattern matching using texts automatically downloaded from the web.

We need some help to understand where the problem lies and how to fix it.
Personally, I must confess that after having read so many posts on the topic, I am completely confused :-)

Our texts sometimes include:
1)  disturbing Unicode (I have read this already (Automatically escape unicode characters ), but I am not sure in which way it can help with regular expressions)

2)  weird quotes (such as ticks and double ticks than we do not manage to identify automatically (this page is useful https://www.cl.cam.ac.uk/~mgk25/ucs/quotes.html, but how shall we apply this codes within our code?)

I have already applied the suggestions given in this post: How to change the locale of R in RStudio?

To make a long story short, I will provide an example (out of many) that shows the kind of problems we are experiencing.

Read the code below (inelegant, but easy to read): the goal is to search the pattern “CURRENT URL http://[\S]*” in the input file “_ansiktstics_corpus.txt” and save the matches onto  an output file.

I provide a snippet of an input file at the bottom.

Language used in our texts is Swedish. I am working on Windows 10.

----- start code

```<code>library(stringr)
rm(list=ls(all=TRUE)) # clear memory

setwd("yourPath”)

seeds_eCare01 <- dir(pattern = "_ansiktstics_corpus.txt") # we have a file list, but for the sake of this example I specify only a file that I attach to allow the reproducibility of the experiment

cat(file="yourPath/urls.csv", append =FALSE)

urlPattern<-"CURRENT URL http://[\\S]*" # all the lines containing the following pattern (we are interested in extracting the URLs)

for (f in seeds_eCare01) {

  tempData = scan( f, what="character", encoding = "UTF-8", sep="",quote = NULL)
  urlList<-grep("urlPattern", tempData, value = TRUE, perl = TRUE)
# we tried also with “gsub”, we get the same error

cat(urlList,file="yourPath/urls.csv", sep="\n",append = TRUE)
}
</code>```

----- end code

The console output is the following:

---start console output

```<code>Read 13354 items
Warning messages:
1: In grep("urlPattern", tempData, value = TRUE, perl = TRUE) :
  input string 18 is invalid UTF-8
2: In grep("urlPattern", tempData, value = TRUE, perl = TRUE) :
  input string 19 is invalid UTF-8
3: In grep("urlPattern", tempData, value = TRUE, perl = TRUE) :
  input string 4590 is invalid UTF-8
4: In grep("urlPattern", tempData, value = TRUE, perl = TRUE) :
  input string 4591 is invalid UTF-8
5: In grep("urlPattern", tempData, value = TRUE, perl = TRUE) :
  input string 4593 is invalid UTF-8
</code>```

---edn console output

No pattern was found in the file, although “CURRENT URL” is there.

My default locale is:

```<code>> Sys.getlocale()
[1] "LC_COLLATE=Swedish_Sweden.1252;LC_CTYPE=Swedish_Sweden.1252;LC_MONETARY=Swedish_Sweden.1252;LC_NUMERIC=C;LC_TIME=Swedish_Sweden.1252"
</code>```

Now, let’s get to the problem:

The file that I want to read and search is uploaded using encoding=UTF-8

```<code>scan( f, what="character", encoding = "UTF-8", sep="",quote = NULL)
</code>```

but when I run the following checks (to check whether the tempData is UTF-8) I get FALSE

```<code>all(stri_enc_isutf8(tempData))
[1] FALSE
> stri_enc_mark(tempData)
   [1] "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "UTF-8" "ASCII" "UTF-8" "ASCII" "ASCII" "UTF-8" "UTF-8"
  [18] "UTF-8" "UTF-8" "ASCII" "ASCII" "ASCII" "ASCII" "UTF-8" "UTF-8" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII"
</code>```

I also tried with “readlines” and a connection (as suggested by Gries 2017 )but I experienced similar problems:

```<code>(tempData<-readLines(con<-file(f, encoding="UTF-8"), warn=FALSE)); close(con)
</code>```

when I run the following I get a TRUE, but the grep fails exactly as with “scan”

```<code>all(stri_enc_isutf8(tempData))
[1] TRUE
</code>```

However, when I run the following (to check the encoding), I get a mixture of     ascii and uft-8

```<code>stri_enc_mark(tempData)
  [1] "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "UTF-8" "UTF-8" "UTF-8" "ASCII" "ASCII" "UTF-8" "UTF-8" "UTF-8" "UTF-8" "UTF-8" "UTF-8"
</code>```

Questions
1)  Pattern matching does not work: Why?
2)  The encoding is not consistently UTF-8 although we force it: why?
3)  How can we get rid or convert disturbing characters ?
Any suggestions, hints or insights are greatly appreciated.

Thanks in advance

Cheers, Marina

```<code>input file: “_ansiktstics_corpus.txt"
<>
<header>
<usergroup>lay/specialized</usergroup>
<annotator's comments>[...]</annotator's comments>
</header>
</>CURRENT URL http://www.aftonbladet.se/halsa/article11873667.ab
”Men det är inte som på film”
 Miriam Jaakola, 30, var 26 år när hon fick sin diagnos. Foto: tomas bergman
Hon varken svär eller säger fula ord — men hon drabbas ofta av tics och har svårt att tygla sina
impulser.
Miriam Jaakola, 30, har Tourettes syndrom.
”Jag har haft tics så länge jag kan minnas. När jag var barn hade jag mycket ansiktstics. Jag blinkade, gapade och gjorde grimaser. Jag brukade kalla det för mina ovanor och tänkte egentligen inte så mycket på det. Det var så mycket annat i mitt liv som var rörigt. Jag har en ganska mild form av Tourettes syndrom, så mina tics är inte så tydliga. Det är både på gott och på ont. Folk som inte vet om det märker oftast inte att jag har tourette. Själv förstod jag det inte heller förrän jag var 26 år och fick min diagnos.
Svär inte
Den vanligaste fördomen är att alla som har Tourettes syndrom svär eller säger fula ord. Men ticsen kan se väldigt olika ut. De ändrar sig också över tid. Det är bara en tredjedel av alla med tourette som säger fula ord under någon period i sitt liv. Jag har aldrig gjort det.
Tourette är en sorts känsla – som ett tryck eller en frustration – som byggs upp inom en och till slut bryter ut i tics. Ungefär som när man nyser eller känner att en nysning är på väg. Jag kan hålla tillbaka mina tics om jag är ute bland folk, men då blir de oftast
värre efteråt.Det fi nns en stark energi i tourette. I dag när jag vet hur jag ska hantera det, kan jag vända den energin till något
positivt, till exempel i mitt jobb. Men tourette kan också ställa till problem. Jag har svårt att koncentrera mig och kontrollera impulser. När jag var yngre kunde jag få blixtsnabba utbrott. Jag minns fortfarande första gången jag reflekterade över det. Jag var runt tio år och stod och pillade med något. Plötsligt kastade jag iväg alla grejer. Hade jag haft en allvarligare form av tourette hade jag säkert skrikit eller fått en spasmurladdning. Jag minns att jag tänkte: Undrar om alla har det så här, eller om det bara är jag?
Skoltiden jobbig
Skoltiden var jättejobbig.
</code>```

答:
Here "readlines" is ok, not sure what happens with encoding, but I get NO errors or warnings :-)</p>

```<code>library(stringr)
rm(list=ls(all=TRUE)) # clear memory
setwd("path")

seeds_eCare01 <- dir(pattern = "_ansiktstics_corpus.txt")# see snippet above

cat("seed;NumOfWebDoc;CumulativeSum",file="outputFile",  sep="\n", append =FALSE)

urlPattern<-"<\\/>CURRENT URL"

totURLs<-0

for (f in seeds_eCare01) {

  (tempData<-readLines(con<-file(f, encoding="UTF-8"), warn=FALSE)); close(con)

  urlList<-grep(urlPattern, tempData, value = TRUE, perl = TRUE) #

  countURLsPerSeed<-length(urlList)
  totURLs<-totURLs + countURLsPerSeed
  out1<-c(f, countURLsPerSeed,totURLs)
  out2<-paste(out1,collapse=";")

  cat(out2,file="outputFile", sep="\n",append = TRUE)
}
</code>```

Body:
We are experiencing problems with encoding, pattern matching using texts automatically downloaded from the web.

We need some help to understand where the problem lies and how to fix it.
Personally, I must confess that after having read so many posts on the topic, I am completely confused :-)

Our texts sometimes include:
1)  disturbing Unicode (I have read this already (Automatically escape unicode characters ), but I am not sure in which way it can help with regular expressions)

2)  weird quotes (such as ticks and double ticks than we do not manage to identify automatically (this page is useful https://www.cl.cam.ac.uk/~mgk25/ucs/quotes.html, but how shall we apply this codes within our code?)

I have already applied the suggestions given in this post: How to change the locale of R in RStudio?

To make a long story short, I will provide an example (out of many) that shows the kind of problems we are experiencing.

Read the code below (inelegant, but easy to read): the goal is to search the pattern “CURRENT URL http://[\S]*” in the input file “_ansiktstics_corpus.txt” and save the matches onto  an output file.

I provide a snippet of an input file at the bottom.

Language used in our texts is Swedish. I am working on Windows 10.

----- start code

library(stringr)
rm(list=ls(all=TRUE)) # clear memory

setwd("yourPath”)

seeds_eCare01 <- dir(pattern = "_ansiktstics_corpus.txt") # we have a file list, but for the sake of this example I specify only a file that I attach to allow the reproducibility of the experiment

cat(file="yourPath/urls.csv", append =FALSE)

urlPattern<-"CURRENT URL http://[\\S]*" # all the lines containing the following pattern (we are interested in extracting the URLs)

for (f in seeds_eCare01) {

  tempData = scan( f, what="character", encoding = "UTF-8", sep="",quote = NULL)
  urlList<-grep("urlPattern", tempData, value = TRUE, perl = TRUE)
# we tried also with “gsub”, we get the same error

cat(urlList,file="yourPath/urls.csv", sep="\n",append = TRUE)
}

----- end code

The console output is the following:

---start console output

Read 13354 items
Warning messages:
1: In grep("urlPattern", tempData, value = TRUE, perl = TRUE) :
  input string 18 is invalid UTF-8
2: In grep("urlPattern", tempData, value = TRUE, perl = TRUE) :
  input string 19 is invalid UTF-8
3: In grep("urlPattern", tempData, value = TRUE, perl = TRUE) :
  input string 4590 is invalid UTF-8
4: In grep("urlPattern", tempData, value = TRUE, perl = TRUE) :
  input string 4591 is invalid UTF-8
5: In grep("urlPattern", tempData, value = TRUE, perl = TRUE) :
  input string 4593 is invalid UTF-8

---edn console output

No pattern was found in the file, although “CURRENT URL” is there.

My default locale is:

> Sys.getlocale()
[1] "LC_COLLATE=Swedish_Sweden.1252;LC_CTYPE=Swedish_Sweden.1252;LC_MONETARY=Swedish_Sweden.1252;LC_NUMERIC=C;LC_TIME=Swedish_Sweden.1252"

Now, let’s get to the problem:

The file that I want to read and search is uploaded using encoding=UTF-8

scan( f, what="character", encoding = "UTF-8", sep="",quote = NULL)

but when I run the following checks (to check whether the tempData is UTF-8) I get FALSE

all(stri_enc_isutf8(tempData))
[1] FALSE
> stri_enc_mark(tempData)
   [1] "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "UTF-8" "ASCII" "UTF-8" "ASCII" "ASCII" "UTF-8" "UTF-8"
  [18] "UTF-8" "UTF-8" "ASCII" "ASCII" "ASCII" "ASCII" "UTF-8" "UTF-8" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII"

I also tried with “readlines” and a connection (as suggested by Gries 2017 )but I experienced similar problems:

(tempData<-readLines(con<-file(f, encoding="UTF-8"), warn=FALSE)); close(con)

when I run the following I get a TRUE, but the grep fails exactly as with “scan”

all(stri_enc_isutf8(tempData))
[1] TRUE

However, when I run the following (to check the encoding), I get a mixture of     ascii and uft-8

stri_enc_mark(tempData)
  [1] "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "ASCII" "UTF-8" "UTF-8" "UTF-8" "ASCII" "ASCII" "UTF-8" "UTF-8" "UTF-8" "UTF-8" "UTF-8" "UTF-8"

Questions
1)  Pattern matching does not work: Why?
2)  The encoding is not consistently UTF-8 although we force it: why?
3)  How can we get rid or convert disturbing characters ?
Any suggestions, hints or insights are greatly appreciated.

Thanks in advance

Cheers, Marina

input file: “_ansiktstics_corpus.txt"
<>

<usergroup>lay/specialized</usergroup>
<annotator's comments>[...]</annotator's comments>

</>CURRENT URL http://www.aftonbladet.se/halsa/article11873667.ab
”Men det är inte som på film”
 Miriam Jaakola, 30, var 26 år när hon fick sin diagnos. Foto: tomas bergman
Hon varken svär eller säger fula ord — men hon drabbas ofta av tics och har svårt att tygla sina
impulser.
Miriam Jaakola, 30, har Tourettes syndrom.
”Jag har haft tics så länge jag kan minnas. När jag var barn hade jag mycket ansiktstics. Jag blinkade, gapade och gjorde grimaser. Jag brukade kalla det för mina ovanor och tänkte egentligen inte så mycket på det. Det var så mycket annat i mitt liv som var rörigt. Jag har en ganska mild form av Tourettes syndrom, så mina tics är inte så tydliga. Det är både på gott och på ont. Folk som inte vet om det märker oftast inte att jag har tourette. Själv förstod jag det inte heller förrän jag var 26 år och fick min diagnos.
Svär inte
Den vanligaste fördomen är att alla som har Tourettes syndrom svär eller säger fula ord. Men ticsen kan se väldigt olika ut. De ändrar sig också över tid. Det är bara en tredjedel av alla med tourette som säger fula ord under någon period i sitt liv. Jag har aldrig gjort det.
Tourette är en sorts känsla – som ett tryck eller en frustration – som byggs upp inom en och till slut bryter ut i tics. Ungefär som när man nyser eller känner att en nysning är på väg. Jag kan hålla tillbaka mina tics om jag är ute bland folk, men då blir de oftast
värre efteråt.Det fi nns en stark energi i tourette. I dag när jag vet hur jag ska hantera det, kan jag vända den energin till något
positivt, till exempel i mitt jobb. Men tourette kan också ställa till problem. Jag har svårt att koncentrera mig och kontrollera impulser. När jag var yngre kunde jag få blixtsnabba utbrott. Jag minns fortfarande första gången jag reflekterade över det. Jag var runt tio år och stod och pillade med något. Plötsligt kastade jag iväg alla grejer. Hade jag haft en allvarligare form av tourette hade jag säkert skrikit eller fått en spasmurladdning. Jag minns att jag tänkte: Undrar om alla har det så här, eller om det bara är jag?
Skoltiden jobbig
Skoltiden var jättejobbig.

Body:
Here "readlines" is ok, not sure what happens with encoding, but I get NO errors or warnings :-)

library(stringr)
rm(list=ls(all=TRUE)) # clear memory
setwd("path")

seeds_eCare01 <- dir(pattern = "_ansiktstics_corpus.txt")# see snippet above

cat("seed;NumOfWebDoc;CumulativeSum",file="outputFile",  sep="\n", append =FALSE)

urlPattern<-"<\\/>CURRENT URL"

totURLs<-0

for (f in seeds_eCare01) {

  (tempData<-readLines(con<-file(f, encoding="UTF-8"), warn=FALSE)); close(con)

  urlList<-grep(urlPattern, tempData, value = TRUE, perl = TRUE) #

  countURLsPerSeed<-length(urlList)
  totURLs<-totURLs + countURLsPerSeed
  out1<-c(f, countURLsPerSeed,totURLs)
  out2<-paste(out1,collapse=";")

  cat(out2,file="outputFile", sep="\n",append = TRUE)
}


问:
Select tag not including options after the first time
Relatively new to php, I want to fetch a column named make for which i am using a loop and mysqli_fetch_row to fetch each row from the column and then i am inserting the data into a select tag. The problem I am facing is that it inserts the data into the options tag the first time, and after that it just echos it out of the list.
Here is the code for it,

```<code>$SQLstring = "select make from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("<p>Unable to query the $TableName table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
//$row= mysqli_fetch_all($queryResult);
$i=0;
echo"<label for='make'>Please select a make:</label>
<select>
    <option name='make' value='All'>All</option>";
    while($row= mysqli_fetch_row($queryResult)){
    echo"<option value='$row[$i]'>$row[$i]</option>
</select>";
    }
</code>```

What to d0 here?

答:
Try this:

```<code><select>
<option name='make' value='All'>All</option>";
while($row= mysqli_fetch_row($queryResult)){
  echo "<option value='$row[$i]'>$row[$i]</option>";
}
</select>
</code>```

Since you are "relatively new to php", here is a good read about why you shouldn't mix php and html code or in other words, why you should separate application logic from presentation http://thisinterestsme.com/mixing-php-html/

Hope this helps!

Body:
Relatively new to php, I want to fetch a column named make for which i am using a loop and mysqli_fetch_row to fetch each row from the column and then i am inserting the data into a select tag. The problem I am facing is that it inserts the data into the options tag the first time, and after that it just echos it out of the list.
Here is the code for it,

$SQLstring = "select make from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("
Unable to query the $TableName table.
"."
Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "
";
//$row= mysqli_fetch_all($queryResult);
$i=0;
echo"Please select a make:
<select>
    <option name='make' value='All'>All</option>";
    while($row= mysqli_fetch_row($queryResult)){
    echo"<option value='$row[$i]'>$row[$i]</option>
</select>";
    }

What to d0 here?

Body:
Try this:

<select>
<option name='make' value='All'>All</option>";
while($row= mysqli_fetch_row($queryResult)){
  echo "<option value='$row[$i]'>$row[$i]</option>";
}
</select>

Since you are "relatively new to php", here is a good read about why you shouldn't mix php and html code or in other words, why you should separate application logic from presentation http://thisinterestsme.com/mixing-php-html/

Hope this helps!


问:
Calendar picker with Selenium and Python
I want to click a day of the calendar(doesn't matter what day) if it's available

There are days that are availables and other that they aren't.

The calendar is made with table tag, each td tag, if it isn't available ,  has a class notSelectableDay.

I have to reload the page till the program found a available day which has the class selectableDay.

The program structure its in this other question i made if else loop on Python. Checking a class name with Selenium

Could this work:

```<code>if driver.find_elements_by_class_name("selectableDay"):

    driver.find_element_by_class_name("selectableDay").click()
</code>```

I`ve made another question more clearly explainded :

I got a calender picker. How to select the available day with Selenium and Python?

答:
Here is the piece of code where you can pick required date from the calendar. Just you need to pass date which you want to be selected from the calendar.

```<code>from selenium import webdriver

def datepicker(date):
    driverInstance = webdriver.Chrome()
    driverInstance.get("http://www.seleniumframework.com/Practiceform/")
    driverInstance.maximize_window()
    driverInstance.find_element_by_id("vfb-8").click()
    elements = driverInstance.find_elements_by_xpath(".//*[@id='ui-datepicker-div']/table/tbody/tr/td/a")
    for dates in elements:
        if(dates.is_enabled() and dates.is_displayed() and str(dates.get_attribute("innerText")) == date):
            dates.click()
</code>```

if you want to select date 10 from calendar the pass string "10" to the function

example: datepicker("10")

Let me know if you have any issue.

Body:
I want to click a day of the calendar(doesn't matter what day) if it's available

There are days that are availables and other that they aren't.

The calendar is made with table tag, each td tag, if it isn't available ,  has a class notSelectableDay.

I have to reload the page till the program found a available day which has the class selectableDay.

The program structure its in this other question i made if else loop on Python. Checking a class name with Selenium

Could this work:

if driver.find_elements_by_class_name("selectableDay"):

    driver.find_element_by_class_name("selectableDay").click()

I`ve made another question more clearly explainded :

I got a calender picker. How to select the available day with Selenium and Python?

Body:
Here is the piece of code where you can pick required date from the calendar. Just you need to pass date which you want to be selected from the calendar.

from selenium import webdriver

def datepicker(date):
    driverInstance = webdriver.Chrome()
    driverInstance.get("http://www.seleniumframework.com/Practiceform/")
    driverInstance.maximize_window()
    driverInstance.find_element_by_id("vfb-8").click()
    elements = driverInstance.find_elements_by_xpath(".//*[@id='ui-datepicker-div']/table/tbody/tr/td/a")
    for dates in elements:
        if(dates.is_enabled() and dates.is_displayed() and str(dates.get_attribute("innerText")) == date):
            dates.click()

if you want to select date 10 from calendar the pass string "10" to the function

example: datepicker("10")

Let me know if you have any issue.


问:
How to identify an anonymous function
I have a class that creates a List<Action<int>> and holds on to them until a later time. This class can add and remove delegates from this list. This works well as long as people don't get too fancy. To combat anonymous function (which can't be removed) I check against the target of the delegate being null. If its null I throw an exception. The problem comes in when there is an anonymous delegate that contains a function. This has a target, but is just as unremovable. The simplified code below illustrates my issues

```<code> public class MyDelegateContainer
 {
    List<Action<int>> m_Container = new List<Action<int>>();

    public void Add(Action<int> del)
    {
        if (del.Target == null)
        {
            throw new Exception("No static handlers");
        }
        m_Container.Add(del);
    }

    public bool Remove(Action<int> del)
    {
        if (m_Container.Contains(del))
        {
            m_Container.Remove(del);
            return true;
        }

        return false;
    }
}

public class MyFakeActionClass
{
    public void Test(int temp) { }
}

class Program
{
    static void Main(string[] args)
    {
        bool removed = false;
        int counter = 0;
        MyDelegateContainer container = new MyDelegateContainer();
        MyFakeActionClass fake = new MyFakeActionClass();
        //container.Add(p => { }); //Throws, this is what I want to happen
        container.Add(fake.Test); //Works, this is the use case
        removed = container.Remove(fake.Test); //Works, this is the use case
        Debug.Assert(removed);
        container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
        removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
        Debug.Assert(removed);
    }
}
</code>```

I need some way to identify

```<code>   p => { fake.Test(p); counter++; }
</code>```

is an anonymous function so I can throw if someone tries it. Thanks for any help

EDIT: I should note that I could use an Action<int> variable for the anonymous function and everything would work, but the Add and Remove are never in the same scope in practice.

答:
As jonnii suggested in a comment, another way you could implement it is with a dictionary:

```<code>public class MyDelegateContainer
{
    Dictionary<string, Action<int>> m_Container =
        new Dictionary<string, Action<int>>();

    public void Add(string key, Action<int> del)
    {
        m_Container.Add(key, del);
    }

    public bool Remove(string key)
    {
        return m_Container.Remove(key);
    }
}
</code>```

Then you could easily remove a known delegate at some arbitrary point in your code just by knowing what name was used to add it:

```<code>    container.Add("fake.Test", fake.Test);
    removed = container.Remove("fake.Test");
    Debug.Assert(removed);
    container.Add("anon", p => { fake.Test(p); counter++; });
    removed = container.Remove("anon"); // works!
    Debug.Assert(removed);
</code>```

Title: How to identify an anonymous function

Body:
I have a class that creates a List<Action<int>> and holds on to them until a later time. This class can add and remove delegates from this list. This works well as long as people don't get too fancy. To combat anonymous function (which can't be removed) I check against the target of the delegate being null. If its null I throw an exception. The problem comes in when there is an anonymous delegate that contains a function. This has a target, but is just as unremovable. The simplified code below illustrates my issues

 public class MyDelegateContainer
 {
    List<Action<int>> m_Container = new List<Action<int>>();

    public void Add(Action<int> del)
    {
        if (del.Target == null)
        {
            throw new Exception("No static handlers");
        }
        m_Container.Add(del);
    }

    public bool Remove(Action<int> del)
    {
        if (m_Container.Contains(del))
        {
            m_Container.Remove(del);
            return true;
        }

        return false;
    }
}

public class MyFakeActionClass
{
    public void Test(int temp) { }
}

class Program
{
    static void Main(string[] args)
    {
        bool removed = false;
        int counter = 0;
        MyDelegateContainer container = new MyDelegateContainer();
        MyFakeActionClass fake = new MyFakeActionClass();
        //container.Add(p => { }); //Throws, this is what I want to happen
        container.Add(fake.Test); //Works, this is the use case
        removed = container.Remove(fake.Test); //Works, this is the use case
        Debug.Assert(removed);
        container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
        removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
        Debug.Assert(removed);
    }
}

I need some way to identify

   p => { fake.Test(p); counter++; }

is an anonymous function so I can throw if someone tries it. Thanks for any help

EDIT: I should note that I could use an Action<int> variable for the anonymous function and everything would work, but the Add and Remove are never in the same scope in practice.

Body:
As jonnii suggested in a comment, another way you could implement it is with a dictionary:

public class MyDelegateContainer
{
    Dictionary<string, Action<int>> m_Container =
        new Dictionary<string, Action<int>>();

    public void Add(string key, Action<int> del)
    {
        m_Container.Add(key, del);
    }

    public bool Remove(string key)
    {
        return m_Container.Remove(key);
    }
}

Then you could easily remove a known delegate at some arbitrary point in your code just by knowing what name was used to add it:

    container.Add("fake.Test", fake.Test);
    removed = container.Remove("fake.Test");
    Debug.Assert(removed);
    container.Add("anon", p => { fake.Test(p); counter++; });
    removed = container.Remove("anon"); // works!
    Debug.Assert(removed);


问:
JavaScript works locally, but not online, and is rounding to whole numbers rather than decimals. [Articulate Storyline]
I created a piece of JavaScript to run within an eLearning module that I built with Articulate Storyline 2 (eLearning rapid development software). The code is meant to work as a calculator, outputting how much it would cost a company to run inductions for new staff.

The user inputs the numbers into the Storyline player/elearning module in their browser. The code retrieves these inputs and stores it in variables. This information is used to do the calculations and the user gets the result on the final screen in the browser.

Oddly, the JavaScript runs without issue locally, but when it is uploaded to our server, the result always comes back as zero. I'm not sure why this is happening.

Also, the numbers are always whole numbers. They never come back as something like £13,553.99. It usually rounds it to the nearest whole number, e.g. £13,554.00.

If anyone could give me some advice, I'd really appreciate it. I've included the code and comments so you can see what I've done. If you need more information, please let me know.

```<code>// Retrieve variables from Storyline file.
var player=GetPlayer();

// Assign Storyline variables to JS variables. Each letter represents a data entry box in the elearning module.
var aa = player.GetVar("a");
var bb = player.GetVar("b");
var cc = player.GetVar("c");
var dd = player.GetVar("d");
var ee = player.GetVar("e");
var ff = player.GetVar("f");
var gg = player.GetVar("g");
var hh = player.GetVar("h");
var ii = player.GetVar("i");
var jj = player.GetVar("j");
var ll = player.GetVar("l");
var qq = player.GetVar("q");

// Convert strings to integers
var aa = parseInt(aa);
var bb = parseInt(bb);
var cc = parseInt(cc);
var dd = parseInt(dd);
var ee = parseInt(ee);
var ff = parseInt(ff);
var gg = parseInt(gg);
var hh = parseInt(hh);
var ii = parseInt(ii);
var jj = parseInt(jj);
var ll = parseInt(ll);
var qq = parseInt(qq);

// Add comma to thousands.
function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

// Use the numbers stored in the variables to do the induction calculations.
// # per month
var mm = aa * 12;

// £ new recruit/hr + £ trainer/hr
var ss = bb + cc;

// Duration mins
var nn = dd / 60;

// (Room booking admin mins + admin records) / 60 * £ admin/hr
var oo = (ee + gg) / 60 * ff;

// Repeating hrs/month
var pp = jj * (bb + cc);

// # of trainers
var rr = (ll * qq) * (cc + cc);

//Results calculations
var tt = (ss * nn) + oo;

var uu = tt + hh + ii;

var vv = uu * mm;

var ww = pp * 12;

// Calculate final result, round to 2 decimal places and convert number to a string. Add comma to define thousands.
var total = vv + ww + rr;
var totalRnd = total.toFixed(2);
var totalStr = totalRnd.toString();
var totalCost = addCommas(totalStr);

// Sends result back to Storyline.
player.SetVar("result",totalCost);
</code>```

UPDATE: I use parseInt() instead of parseFloat(), which explains the whole numbers issue.

答: parseInt parses the input to an integer value. You need to use parseFloat instead. However, it is strange this worked locally for you. I think you had integer values there, so parseInt did not ruin preciseness.

Body:
I created a piece of JavaScript to run within an eLearning module that I built with Articulate Storyline 2 (eLearning rapid development software). The code is meant to work as a calculator, outputting how much it would cost a company to run inductions for new staff.

The user inputs the numbers into the Storyline player/elearning module in their browser. The code retrieves these inputs and stores it in variables. This information is used to do the calculations and the user gets the result on the final screen in the browser.

Oddly, the JavaScript runs without issue locally, but when it is uploaded to our server, the result always comes back as zero. I'm not sure why this is happening.

Also, the numbers are always whole numbers. They never come back as something like £13,553.99. It usually rounds it to the nearest whole number, e.g. £13,554.00.

If anyone could give me some advice, I'd really appreciate it. I've included the code and comments so you can see what I've done. If you need more information, please let me know.

// Retrieve variables from Storyline file.
var player=GetPlayer();

// Assign Storyline variables to JS variables. Each letter represents a data entry box in the elearning module.
var aa = player.GetVar("a");
var bb = player.GetVar("b");
var cc = player.GetVar("c");
var dd = player.GetVar("d");
var ee = player.GetVar("e");
var ff = player.GetVar("f");
var gg = player.GetVar("g");
var hh = player.GetVar("h");
var ii = player.GetVar("i");
var jj = player.GetVar("j");
var ll = player.GetVar("l");
var qq = player.GetVar("q");

// Convert strings to integers
var aa = parseInt(aa);
var bb = parseInt(bb);
var cc = parseInt(cc);
var dd = parseInt(dd);
var ee = parseInt(ee);
var ff = parseInt(ff);
var gg = parseInt(gg);
var hh = parseInt(hh);
var ii = parseInt(ii);
var jj = parseInt(jj);
var ll = parseInt(ll);
var qq = parseInt(qq);

// Add comma to thousands.
function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

// Use the numbers stored in the variables to do the induction calculations.
// # per month
var mm = aa * 12;

// £ new recruit/hr + £ trainer/hr
var ss = bb + cc;

// Duration mins
var nn = dd / 60;

// (Room booking admin mins + admin records) / 60 * £ admin/hr
var oo = (ee + gg) / 60 * ff;

// Repeating hrs/month
var pp = jj * (bb + cc);

// # of trainers
var rr = (ll * qq) * (cc + cc);

//Results calculations
var tt = (ss * nn) + oo;

var uu = tt + hh + ii;

var vv = uu * mm;

var ww = pp * 12;

// Calculate final result, round to 2 decimal places and convert number to a string. Add comma to define thousands.
var total = vv + ww + rr;
var totalRnd = total.toFixed(2);
var totalStr = totalRnd.toString();
var totalCost = addCommas(totalStr);

// Sends result back to Storyline.
player.SetVar("result",totalCost);

UPDATE: I use parseInt() instead of parseFloat(), which explains the whole numbers issue.


问:
OpenGLES 3 iOS object displaying as triangles and not filled
I am trying to display a banana in iOS using OpenGLES. I am pretty sure I have everything set up properly, but when the app starts, the banana isn't being drawn correctly. It shows up like this:

The banana object I am trying to display is from the sample banana.h provided by obj2opengl.

App running on iPhone 5 simulator

Here is the setup:

```<code>    - (void)setupGL {
    [EAGLContext setCurrentContext:self.context];

    [self loadShaders];

    glEnable(GL_BLEND);

    self.effect = [[GLKBaseEffect alloc] init];
    self.effect.light0.enabled = GL_TRUE;
    self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 1.0f);

    glGenVertexArrays(1, &_vertexArray);
    glBindVertexArray(_vertexArray);

    glGenBuffers(1, &_vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(bananaVerts), bananaVerts, GL_STATIC_DRAW);

    glGenBuffers(1, &_textureCoords);
    glBindBuffer(GL_ARRAY_BUFFER, _textureCoords);
    glBufferData(GL_ARRAY_BUFFER, sizeof(bananaTexCoords), bananaTexCoords, GL_STATIC_DRAW);

    //Vertex attribute
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 0,0);
    glEnableVertexAttribArray(GLKVertexAttribPosition);
    // Normal attribute
    /*glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 0,0);
    glEnableVertexAttribArray(GLKVertexAttribNormal);*/
    // TexCoord attribute
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);

    [self loadTexture];

    glBindVertexArray(0);
}
</code>```

And this is the drawing method:

```<code>- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    glClearColor(0.65f, 0.65f, 0.65f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    [self calculateMatrices];

    glUseProgram(_program);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _texture.name);
    glUniform1i(glGetUniformLocation(_program, "texture1"), 0);

    glUniformMatrix4fv(glGetUniformLocation(_program, "viewMatrix"), 1, GL_FALSE, _modelViewMatrix.m);
    glUniformMatrix4fv(glGetUniformLocation(_program, "projectionMatrix"), 1, GL_FALSE, _projectionMatrix.m);

    glBindVertexArray(_vertexArray);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, bananaNumVerts);
}
</code>```

Vertex Shader:

```<code>attribute vec3 position;
attribute vec2 texCoord;

uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;

varying vec2 TexCoord;
varying vec3 vNormal;

void main()
{
    gl_Position = viewMatrix * projectionMatrix * vec4(position, 1.0);
    TexCoord = vec2(texCoord.x, 1.0 - texCoord.y);
}
</code>```

Fragment Shader:

```<code>precision mediump float;

varying vec2 TexCoord;

uniform sampler2D texture1;

void main()
{
    gl_FragColor = texture2D(texture1, TexCoord);
}
</code>```

EDIT:

I fixed the problem by changing the draw command to

```<code>GL_LINES
</code>```

instead of

```<code>GL_TRIANGLES.
</code>```

答:
Your use of glVertexAttribPointer looks wrong.

You need to call glBindBuffer(GL_ARRAY_BUFFER, ...) of the relevant buffer before calling glVertexAttribPointer to reference it. Currently you are referencing the _textureCoords buffer for both position and texture coordinates.

Body:
I am trying to display a banana in iOS using OpenGLES. I am pretty sure I have everything set up properly, but when the app starts, the banana isn't being drawn correctly. It shows up like this:

The banana object I am trying to display is from the sample banana.h provided by obj2opengl.

App running on iPhone 5 simulator

Here is the setup:

    - (void)setupGL {
    [EAGLContext setCurrentContext:self.context];

    [self loadShaders];

    glEnable(GL_BLEND);

    self.effect = [[GLKBaseEffect alloc] init];
    self.effect.light0.enabled = GL_TRUE;
    self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 1.0f);

    glGenVertexArrays(1, &_vertexArray);
    glBindVertexArray(_vertexArray);

    glGenBuffers(1, &_vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(bananaVerts), bananaVerts, GL_STATIC_DRAW);

    glGenBuffers(1, &_textureCoords);
    glBindBuffer(GL_ARRAY_BUFFER, _textureCoords);
    glBufferData(GL_ARRAY_BUFFER, sizeof(bananaTexCoords), bananaTexCoords, GL_STATIC_DRAW);

    //Vertex attribute
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 0,0);
    glEnableVertexAttribArray(GLKVertexAttribPosition);
    // Normal attribute
    /*glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 0,0);
    glEnableVertexAttribArray(GLKVertexAttribNormal);*/
    // TexCoord attribute
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);

    [self loadTexture];

    glBindVertexArray(0);
}

And this is the drawing method:

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    glClearColor(0.65f, 0.65f, 0.65f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    [self calculateMatrices];

    glUseProgram(_program);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _texture.name);
    glUniform1i(glGetUniformLocation(_program, "texture1"), 0);

    glUniformMatrix4fv(glGetUniformLocation(_program, "viewMatrix"), 1, GL_FALSE, _modelViewMatrix.m);
    glUniformMatrix4fv(glGetUniformLocation(_program, "projectionMatrix"), 1, GL_FALSE, _projectionMatrix.m);

    glBindVertexArray(_vertexArray);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, bananaNumVerts);
}

Vertex Shader:

attribute vec3 position;
attribute vec2 texCoord;

uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;

varying vec2 TexCoord;
varying vec3 vNormal;

void main()
{
    gl_Position = viewMatrix * projectionMatrix * vec4(position, 1.0);
    TexCoord = vec2(texCoord.x, 1.0 - texCoord.y);
}

Fragment Shader:

precision mediump float;

varying vec2 TexCoord;

uniform sampler2D texture1;

void main()
{
    gl_FragColor = texture2D(texture1, TexCoord);
}

EDIT:

I fixed the problem by changing the draw command to

GL_LINES

instead of

GL_TRIANGLES.


问:
Trigger an action when user open the location settings in android
Here is the scenario, I am forcing the user to enable location if user turned off the location, I start a periodic service  with job scheduler, which will continuously check if location is enabled,  if location is not enabled the I show a dialog to enable location. I  turned of the job service when user enable the location.

The problem is when user open the location settings from the dialog the periodic job service still show the dialog to go to settings page to turn the location. I don't want to show the dialog to user when user already opened settings page.

Is there any intent which will be fired when user open the location settings ?

答: You can stop a service when setting is open and again start a service when back to application by using activityForResult() </p>


问:
Handling Angular2 - 4 errors with nested form groups in reactive forms
Guys I need some help with Angular 4 reactive forms. I have nested form-groups also works fine except Validation. But my app is crashing when I try to add some handling validation in my html markup.

my component code looks like:

createForm() {
    let options: any = {};

    for (let option of this.annoucementOptions) {
        options[option.title] = new FormControl(false);
    }

    let optionsFormGroup: FormGroup = new FormGroup(options);

    this.annoucementForm = this.fb.group({
        address: this.fb.group({
            country: ['', [Validators.maxLength(50)]],
            state: ['', [Validators.maxLength(50)]],
            city: ['', [Validators.required, Validators.maxLength(50)]],
            street: ['', [Validators.required, Validators.maxLength(50)]],
            apartment: ['', [Validators.required, Validators.maxLength(50)]],
        }),
        description: this.fb.group({
            title: ['', [Validators.required, Validators.maxLength(80)]],
            shortDescription: [''],
            livingPlaces: [''],
            room: [''],
            options: optionsFormGroup
        }),
        priceBlock: this.fb.group({
            price: ['', [Validators.required, Validators.maxLength(80)]],
            type: ['', [Validators.required, Validators.maxLength(80)]],
        }),
    });
}
```

<p>and this is a piece of my template code:</p>

<pre class="lang-html prettyprint-override"><code><form class="form form-lg form-def" *ngIf="annoucementForm" (ngSubmit)="saveDetails(annoucementForm)"  name="annoucementForm" [formGroup]="annoucementForm">
<div class="form-block"  formGroupName="address">
    <h2 class="form-block-heading flag-label primary">Address</h2>

    <ul class="row form-list">
        <li class="col-md-6 col-lg-4 form-list-item">
            <md-input-container class="d-block">
                <input type="text" mdInput placeholder="*Country" formControlName="country">
            </md-input-container>

            <div  class="form-error text-danger"
                  *ngIf="annoucementForm.get('country').touched "
            >
                <p *ngIf="annoucementForm.get('country').hasError('maxlength')">
                    *This field be more than 35 characters long.
                </p>
            </div>
        </li>
   </ul>
</code>```

答:
Use

```<code>annoucementForm.get('address.country')
</code>```

or

```<code>annoucementForm.get(['address', 'country'])
</code>```

instead of

```<code>annoucementForm.get('country')
</code>```

Body:
Guys I need some help with Angular 4 reactive forms. I have nested form-groups also works fine except Validation. But my app is crashing when I try to add some handling validation in my html markup.

my component code looks like:

createForm() {
    let options: any = {};

    for (let option of this.annoucementOptions) {
        options[option.title] = new FormControl(false);
    }

    let optionsFormGroup: FormGroup = new FormGroup(options);

    this.annoucementForm = this.fb.group({
        address: this.fb.group({
            country: ['', [Validators.maxLength(50)]],
            state: ['', [Validators.maxLength(50)]],
            city: ['', [Validators.required, Validators.maxLength(50)]],
            street: ['', [Validators.required, Validators.maxLength(50)]],
            apartment: ['', [Validators.required, Validators.maxLength(50)]],
        }),
        description: this.fb.group({
            title: ['', [Validators.required, Validators.maxLength(80)]],
            shortDescription: [''],
            livingPlaces: [''],
            room: [''],
            options: optionsFormGroup
        }),
        priceBlock: this.fb.group({
            price: ['', [Validators.required, Validators.maxLength(80)]],
            type: ['', [Validators.required, Validators.maxLength(80)]],
        }),
    });
}

and this is a piece of my template code:

<form class="form form-lg form-def" *ngIf="annoucementForm" (ngSubmit)="saveDetails(annoucementForm)"  name="annoucementForm" [formGroup]="annoucementForm">

Address

            <md-input-container class="d-block">
                <input type="text" mdInput placeholder="*Country" formControlName="country">
            </md-input-container>

                    *This field be more than 35 characters long.

Body:
Use

annoucementForm.get('address.country')

or

annoucementForm.get(['address', 'country'])

instead of

annoucementForm.get('country')