问:
How to read and separate segments of a txt file?
I have a txt file, that has headers and then 3 columns of values (i.e)

Description=null

area = 100

1,2,3

1,2,4

2,1,5 ...

... 1,2,1//(these are the values that I need in one list)

Then another segment

Description=null

area = 10

1,2,3

1,2,4

2,1,5 ...

... 1,2,1//(these are the values that I need in one list).

In fact I just need one list per "Table" of values, the values always are in 3 columns but, there are n segments, any idea?
Thanks!

```<code>List<double> VMM40xyz = new List<double>();
            foreach (var item in VMM40blocklines)
            {
                if (item.Contains(','))
                {
                    VMM40xyz.AddRange(item.Split(',').Select(double.Parse).ToList());
                }
            }
</code>```

I tried this, but it just work with the values in just one big list.

答:
It looks like you want your data to end up in a format like this:

```<code>public class SetOfData //Feel free to name these parts better.
{
    public string Description = "";
    public string Area = "";
    public List<double> Data = new List<double>();
}
</code>```

...stored somewhere in...

```<code>List<SetOfData> finalData = new List<SetOfData>();
</code>```

So, here's how I'd read that in:

```<code>public static List<SetOfData> ReadCustomFile(string Filename)
{
  if (!File.Exists(Filename))
  {
    throw new FileNotFoundException($"{Filename} does not exist.");
  }

  List<SetOfData> returnData = new List<SetOfData>();
  SetOfData currentDataSet = null;
  using (FileStream fs = new FileStream(Filename, FileMode.Open))
  {
    using (StreamReader reader = new StreamReader(fs))
    {
      while (!reader.EndOfStream)
      {
        string line = reader.ReadLine();
        //This will start a new object on every 'Description' line.
        if (line.Contains("Description="))
        {
          //Save off the old data set if there is one.
          if (currentDataSet != null)
            returnData.Add(currentDataSet);

          currentDataSet = new SetOfData();
          //Now, to make sure there is something after "Description=" and to set the Description if there is.
          //Your example data used "null" here, which this will take literally to be a string containing the letters "null". You can check the contents of parts[1] inside the if block to change this.
          string[] parts = line.Split('=');
          if (parts.Length > 1)
            currentDataSet.Description = parts[1].Trim();
        }
        else if (line.Contains("area = "))
        {
          //Just in case your file didn't start with a "Description" line for some reason.
          if (currentDataSet == null)
            currentDataSet = new SetOfData();

          //And then we do some string splitting like we did for Description.
          string[] parts = line.Split('=');
          if (parts.Length > 1)
            currentDataSet.Area = parts[1].Trim();
        }
        else
        {
          //Just in case your file didn't start with a "Description" line for some reason.
          if (currentDataSet == null)
            currentDataSet = new SetOfData();

          string[] parts = line.Split(',');
          foreach (string part in parts)
          {
            if (double.TryParse(part, out double number))
            {
              currentDataSet.Data.Add(number);
            }
          }
        }
      }
      //Make sure to add the last set.
      returnData.Add(currentDataSet);
    }
  }

  return returnData;
}
</code>```

Body:
I have a txt file, that has headers and then 3 columns of values (i.e)

Description=null

area = 100

1,2,3

1,2,4

2,1,5 ...

... 1,2,1//(these are the values that I need in one list)

Then another segment

Description=null

area = 10

1,2,3

1,2,4

2,1,5 ...

... 1,2,1//(these are the values that I need in one list).

In fact I just need one list per "Table" of values, the values always are in 3 columns but, there are n segments, any idea?
Thanks!

List<double> VMM40xyz = new List<double>();
            foreach (var item in VMM40blocklines)
            {
                if (item.Contains(','))
                {
                    VMM40xyz.AddRange(item.Split(',').Select(double.Parse).ToList());
                }
            }

I tried this, but it just work with the values in just one big list.

Body:
It looks like you want your data to end up in a format like this:

public class SetOfData //Feel free to name these parts better.
{
    public string Description = "";
    public string Area = "";
    public List<double> Data = new List<double>();
}

...stored somewhere in...

List<SetOfData> finalData = new List<SetOfData>();

So, here's how I'd read that in:

public static List<SetOfData> ReadCustomFile(string Filename)
{
  if (!File.Exists(Filename))
  {
    throw new FileNotFoundException($"{Filename} does not exist.");
  }

  List<SetOfData> returnData = new List<SetOfData>();
  SetOfData currentDataSet = null;
  using (FileStream fs = new FileStream(Filename, FileMode.Open))
  {
    using (StreamReader reader = new StreamReader(fs))
    {
      while (!reader.EndOfStream)
      {
        string line = reader.ReadLine();
        //This will start a new object on every 'Description' line.
        if (line.Contains("Description="))
        {
          //Save off the old data set if there is one.
          if (currentDataSet != null)
            returnData.Add(currentDataSet);

          currentDataSet = new SetOfData();
          //Now, to make sure there is something after "Description=" and to set the Description if there is.
          //Your example data used "null" here, which this will take literally to be a string containing the letters "null". You can check the contents of parts[1] inside the if block to change this.
          string[] parts = line.Split('=');
          if (parts.Length > 1)
            currentDataSet.Description = parts[1].Trim();
        }
        else if (line.Contains("area = "))
        {
          //Just in case your file didn't start with a "Description" line for some reason.
          if (currentDataSet == null)
            currentDataSet = new SetOfData();

          //And then we do some string splitting like we did for Description.
          string[] parts = line.Split('=');
          if (parts.Length > 1)
            currentDataSet.Area = parts[1].Trim();
        }
        else
        {
          //Just in case your file didn't start with a "Description" line for some reason.
          if (currentDataSet == null)
            currentDataSet = new SetOfData();

          string[] parts = line.Split(',');
          foreach (string part in parts)
          {
            if (double.TryParse(part, out double number))
            {
              currentDataSet.Data.Add(number);
            }
          }
        }
      }
      //Make sure to add the last set.
      returnData.Add(currentDataSet);
    }
  }

  return returnData;
}


来源: stackexchange

问:
How to make a radio button unchecked by clicking it?
Unlike check boxes, it is impossible for the user to deselect radio buttons once they are clicked.  Is there any way so that they can be toggled programmatically using Javascript?  This would be preferably without using jQuery.</p>

答:
Let's suppose you have a button where on clicking it, you can make all your radio button selection to false. You can write the below code inside the onclick handler.

Below code take radio buttons based on class name and for each element it will mark it to false.

var elements=document.getElementsByClassName('Button');

Array.prototype.forEach.call(elements, function(element) {
  element.checked = false;
});
```

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
If condition on Spinner drop-down list
I made a drop-down list using spinner but now I want and a specific message to display when a certain value is selected along with an EditText when a certain keyword is entered. I attempted using if condition but it didn't work. The scenario is like this: When the user input their age over 18 and selects "Yes" from the drop-down hire, a certain message will appear, both conditions must be satisfied

```<code> public void stan(View hiring){
        ArrayAdapter<CharSequence> hire=ArrayAdapter.createFromResource(this,R.array.decide, android.R.layout.simple_spinner_item);
        hire.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(hire);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String decide =spinner.getSelectedItem().toString()
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        int age= Integer.parseInt(aged.getText().toString());
        if(age>18 && spinner.equals("Yes")){
            Toast.makeText(this,"Ok, go eat cabbage sauce",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(this,"no",Toast.LENGTH_LONG).show();
        }
</code>```

答:
Use spinner.getSelectedItem().toString()

Finally, Your condition will be

```<code>if(age>18 && spinner.getSelectedItem().toString().equals("Yes")){
             Toast.makeText(YourActivityName.this,"Ok, go eat cabbage sauce",Toast.LENGTH_LONG).show();
            }else{
             Toast.makeText(YourActivityName.this,"no",Toast.LENGTH_LONG).show();
            }
</code>```

Title: If condition on Spinner drop-down list

Body:
I made a drop-down list using spinner but now I want and a specific message to display when a certain value is selected along with an EditText when a certain keyword is entered. I attempted using if condition but it didn't work. The scenario is like this: When the user input their age over 18 and selects "Yes" from the drop-down hire, a certain message will appear, both conditions must be satisfied

 public void stan(View hiring){
        ArrayAdapter<CharSequence> hire=ArrayAdapter.createFromResource(this,R.array.decide, android.R.layout.simple_spinner_item);
        hire.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(hire);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String decide =spinner.getSelectedItem().toString()
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        int age= Integer.parseInt(aged.getText().toString());
        if(age>18 && spinner.equals("Yes")){
            Toast.makeText(this,"Ok, go eat cabbage sauce",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(this,"no",Toast.LENGTH_LONG).show();
        }

Body:
Use spinner.getSelectedItem().toString()

Finally, Your condition will be

if(age>18 && spinner.getSelectedItem().toString().equals("Yes")){
             Toast.makeText(YourActivityName.this,"Ok, go eat cabbage sauce",Toast.LENGTH_LONG).show();
            }else{
             Toast.makeText(YourActivityName.this,"no",Toast.LENGTH_LONG).show();
            }


问:
How to run all tests with python manage.py test command in django
I am working on a django project in which I have multiple apps. Every app has a tests directory which has test for whole project. My directory structure is as follow.

```<code>Project
      App_1
           tests
               __init__.py
               tests_views.py
      App_2
           tests
               __init__.py
               tests_views.py
      settings.py
      manage.py
</code>```

I can run tests like this

python manage.py test App_1.tests

which run all tests in App_1/tests/test_views.py. But I have to do this for all app in my project. I want a single command which run all tests inside all apps in my project. I tried by running

python manage.py test

but I got following error

```<code>Traceback (most recent call last):
  File "manage.py", line 9, in <module>
    execute_from_command_line(sys.argv)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
    super(Command, self).run_from_argv(argv)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
    super(Command, self).execute(*args, **options)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
    failures = test_runner.run_tests(test_labels)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/test/runner.py", line 209, in run_tests
    suite = self.build_suite(test_labels, extra_tests)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/test/runner.py", line 150, in build_suite
    tests = self.test_loader.discover(start_dir=label, **kwargs)
  File "/usr/lib/python2.7/unittest/loader.py", line 204, in discover
    tests = list(self._find_tests(start_dir, pattern))
  File "/usr/lib/python2.7/unittest/loader.py", line 285, in _find_tests
    for test in self._find_tests(full_path, pattern):
  File "/usr/lib/python2.7/unittest/loader.py", line 265, in _find_tests
    raise ImportError(msg % (mod_name, module_dir, expected_dir))
ImportError: 'tests' module incorrectly imported from '/vagrant/code/project/App_1/tests'. Expected '/vagrant/code/project/App_1'. Is this module globally installed?
</code>```

Can any one tells me how I can all tests in my app with a single command?

答:
I had a similar problem. My file structure looked like this

```<code>project/
    apps/
        app_1/
            test/
                __init__.py
                test_views.py

        app_2/
             test/
                __init__.py
                test_models.py
    manage.py

</code>```

And for me helps to set folder (not an app from installed apps).
All tests runs by command python ./manage.py test apps/ attention to the trailing slash

tests for app_1 runs by command python ./manage.py test app_1

Body:
I am working on a django project in which I have multiple apps. Every app has a tests directory which has test for whole project. My directory structure is as follow.

Project
      App_1
           tests
               __init__.py
               tests_views.py
      App_2
           tests
               __init__.py
               tests_views.py
      settings.py
      manage.py

I can run tests like this

python manage.py test App_1.tests

which run all tests in App_1/tests/test_views.py. But I have to do this for all app in my project. I want a single command which run all tests inside all apps in my project. I tried by running

python manage.py test

but I got following error

Traceback (most recent call last):
  File "manage.py", line 9, in <module>
    execute_from_command_line(sys.argv)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
    super(Command, self).run_from_argv(argv)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
    super(Command, self).execute(*args, **options)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
    failures = test_runner.run_tests(test_labels)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/test/runner.py", line 209, in run_tests
    suite = self.build_suite(test_labels, extra_tests)
  File "/srv/www/project/shared/env/local/lib/python2.7/site-packages/django/test/runner.py", line 150, in build_suite
    tests = self.test_loader.discover(start_dir=label, **kwargs)
  File "/usr/lib/python2.7/unittest/loader.py", line 204, in discover
    tests = list(self._find_tests(start_dir, pattern))
  File "/usr/lib/python2.7/unittest/loader.py", line 285, in _find_tests
    for test in self._find_tests(full_path, pattern):
  File "/usr/lib/python2.7/unittest/loader.py", line 265, in _find_tests
    raise ImportError(msg % (mod_name, module_dir, expected_dir))
ImportError: 'tests' module incorrectly imported from '/vagrant/code/project/App_1/tests'. Expected '/vagrant/code/project/App_1'. Is this module globally installed?

Can any one tells me how I can all tests in my app with a single command?

Body:
I had a similar problem. My file structure looked like this

project/
    apps/
        app_1/
            test/
                __init__.py
                test_views.py

        app_2/
             test/
                __init__.py
                test_models.py
    manage.py

And for me helps to set folder (not an app from installed apps).
All tests runs by command python ./manage.py test apps/ attention to the trailing slash

tests for app_1 runs by command python ./manage.py test app_1


问:
Why the output is a string array even after assigning the variable as number in typescript?
Code:

```<code>function fun(example:string|number|string[])
{
    if(typeof example == "string")
    {
        console.log("Example is String " + example);
    }
    else if(typeof example == "number")
    {
        console.log("Example is Number " + example);
    }
    else{
        console.log("Example is String Array " + example);
    }
}
var example:number; //Here i have assigned the var as a number
fun(example);
</code>```

Output:

```<code>Example is String Array undefined
</code>```

I have given the var type as a "number", but why the output screen shows "String array"?

答: Even though you just declared a number variable but you haven't assigned that variable a number, as we know very well we don't have any default value of the number in typescript It would be undefined and the property that you have defined for the variable is not the property of that variable It will be the property of the value that will be assigned to that veriable. </p>

Body:
Code:

function fun(example:string|number|string[])
{
    if(typeof example == "string")
    {
        console.log("Example is String " + example);
    }
    else if(typeof example == "number")
    {
        console.log("Example is Number " + example);
    }
    else{
        console.log("Example is String Array " + example);
    }
}
var example:number; //Here i have assigned the var as a number
fun(example);

Output:

Example is String Array undefined

I have given the var type as a "number", but why the output screen shows "String array"?


问:
pandas dataframe rolling apply function using multiple columns
I am trying to apply a function to a rolling window. I need to reference multiple columns from the dataframe to compute the output for the function.
Below is some sample code of what I am trying to do.

```<code>import pandas as pd
import statsmodels.formula.api as smf

d = pd.DataFrame({
    'Col1': range(0,10),
    'Col2': range(10,20),
    'Col3': range(20,30)
    })

func = lambda x: smf.ols('Col1 ~ Col2', data=x).fit().params[1]

d['Out'] = d.rolling(3).apply(func)
</code>```

Thank you

答:
Currently implementation of rolling working with each column separately, so not possible sum 2 different columns.

You can test it by:

```<code>def func(x):
    print (x)
    return x.sum()

d.rolling(3).apply(func)
</code>```

Body:
I am trying to apply a function to a rolling window. I need to reference multiple columns from the dataframe to compute the output for the function.
Below is some sample code of what I am trying to do.

import pandas as pd
import statsmodels.formula.api as smf

d = pd.DataFrame({
    'Col1': range(0,10),
    'Col2': range(10,20),
    'Col3': range(20,30)
    })

func = lambda x: smf.ols('Col1 ~ Col2', data=x).fit().params[1]

d['Out'] = d.rolling(3).apply(func)

Thank you

Body:
Currently implementation of rolling working with each column separately, so not possible sum 2 different columns.

You can test it by:

def func(x):
    print (x)
    return x.sum()

d.rolling(3).apply(func)


问:
Rxjs create an observable that emits when a function is called
I'm likely missing something simple but can't quite puzzle this out from the docs. I'd simply like to have a function that when called will emit a value on an rxjs observable.

Psuedocode:

```<code>const myFunction = () => true //or whatever value
const myObservable = ... emit true whenever myFunction is called

...use myFunction somewhere where it being called is a useful event so
observers of myObservable can process it
</code>```

What's the standard pattern to emit a value when a function is called with rxjs?

答:
You need to use Subject.

const subject = new Subject(); // a subject to notify
const myObservable = subject.asObservable();

const myFunction = () => {
  subject.next(true);
};

myObservable.subscribe(console.log);

myFunction();
myFunction();
myFunction();

```

Body:
I'm likely missing something simple but can't quite puzzle this out from the docs. I'd simply like to have a function that when called will emit a value on an rxjs observable.

Psuedocode:

const myFunction = () => true //or whatever value
const myObservable = ... emit true whenever myFunction is called

...use myFunction somewhere where it being called is a useful event so
observers of myObservable can process it

What's the standard pattern to emit a value when a function is called with rxjs?


问:
Make an attended transfer with SIP.js
Good morning, I need to make attended transfers with SIP.js. Anyone succeded in this task?
I can only make blind transfers right now, i found an article that reports that in version 0.7.x there is support for attended transfer trough replace command.

https://www.onsip.com/blog/sipjs-070-adds-fixes-and-support-for-attended-transfer-recommended-upgrade

答:
I solved this for audio this manner</p>

```<code>    sessionOne.hold();//already exists previously

    var uri = phone + '@' + sip_server;
    var options = {
       media: {
           constraints: {
               audio: true,
               video: false
           },
           render: {
               remote: document.getElementById('audio-output')
           },
           stream: mediaStream
       },
       extraHeaders: [...],
       inviteWithoutSdp: true,
       rel100: SIP.C.supported.SUPPORTED,
       activeAfterTransfer: false //die when the transfer is completed
   };

   sessionTwo = userAgent.invite(uri, options);
   //if yo want handle the transfer at the application level, then implements the handler events as on('refer', function(request) {}) for the session object
   ...
   sessionOne.refer(sessionTwo);//session two already must is accepted (sip server)
</code>```

Title: Make an attended transfer with SIP.js

Body:
I solved this for audio this manner

    sessionOne.hold();//already exists previously

    var uri = phone + '@' + sip_server;
    var options = {
       media: {
           constraints: {
               audio: true,
               video: false
           },
           render: {
               remote: document.getElementById('audio-output')
           },
           stream: mediaStream
       },
       extraHeaders: [...],
       inviteWithoutSdp: true,
       rel100: SIP.C.supported.SUPPORTED,
       activeAfterTransfer: false //die when the transfer is completed
   };

   sessionTwo = userAgent.invite(uri, options);
   //if yo want handle the transfer at the application level, then implements the handler events as on('refer', function(request) {}) for the session object
   ...
   sessionOne.refer(sessionTwo);//session two already must is accepted (sip server)


问:
Exclude a user role from LoginView/RoleGroup
Is there a way to exclude a Role using the LoginView RoleGroup control combination. My problem is that a user is in both customer and trialUser roles. I want to display a menu option only for customer roles, not for trial user. If I say the following, it will display the option for both trial and customer role users since the trial user is also a customer. I want the "Link" to appear only for customers so basically I have to say include "customer" but exclude "trial".</p>

```<code> <asp:LoginView ID="LoginView4" runat="server">
                        <RoleGroups>
                            <asp:RoleGroup Roles="Customer">
                                <ContentTemplate>
                                    <li>Link</li>
                                </ContentTemplate>
                            </asp:RoleGroup>
                        </RoleGroups>
                    </asp:LoginView>
</code>```

答:
ok, it turned out to be simple. It seems like the role group will match the first role it finds and then skip the rest. So, this did the trick.</p>

```<code><asp:LoginView ID="LoginView4" runat="server">
                        <RoleGroups>
                            <asp:RoleGroup Roles="Trial">
                                <ContentTemplate>
                                </ContentTemplate>
                            </asp:RoleGroup>
                            <asp:RoleGroup Roles="Customer">
                                <ContentTemplate>
                                    <li>Link</li>
                                </ContentTemplate>
                            </asp:RoleGroup>
                        </RoleGroups>
                    </asp:LoginView>
</code>```

Body:
Is there a way to exclude a Role using the LoginView RoleGroup control combination. My problem is that a user is in both customer and trialUser roles. I want to display a menu option only for customer roles, not for trial user. If I say the following, it will display the option for both trial and customer role users since the trial user is also a customer. I want the "Link" to appear only for customers so basically I have to say include "customer" but exclude "trial".

 <asp:LoginView ID="LoginView4" runat="server">
                        <RoleGroups>
                            <asp:RoleGroup Roles="Customer">
                                <ContentTemplate>

Link

                                </ContentTemplate>
                            </asp:RoleGroup>
                        </RoleGroups>
                    </asp:LoginView>

Body:
ok, it turned out to be simple. It seems like the role group will match the first role it finds and then skip the rest. So, this did the trick.

<asp:LoginView ID="LoginView4" runat="server">
                        <RoleGroups>
                            <asp:RoleGroup Roles="Trial">
                                <ContentTemplate>
                                </ContentTemplate>
                            </asp:RoleGroup>
                            <asp:RoleGroup Roles="Customer">
                                <ContentTemplate>
                                    <li>Link</li>
                                </ContentTemplate>
                            </asp:RoleGroup>
                        </RoleGroups>
                    </asp:LoginView>


问:
Reading string and integer from file into struct - C
I hope this question isn't too similar to another that's posted. I am still learning how to read other peoples code at this point let alone write my own. I am confused as to how to read both a string and int from a line in a file and store it in a struct called People.
I have been looking at fgets, fscanf and even fread but I can't figure out what to use and where to use it.
I am getting this data from a file with a max of 10 entries that looks like this:

```<code>Joshua 50
Dwayne 90
Jennifer 45
Goldilocks 85
</code>```

Here is my code:

```<code>typedef struct
{
    char *name[20];
    int change_amount;
    int fifties;
    int twenties;
    int tens;
    int fives;
}People;

int get_file()
{
    const int MAXPEOPLE = 10;
    People persons[MAXPEOPLE];
    int i = 0;
    FILE *fpointer;
    char line[12];
    fopen("file.txt", "r");
    if (fpointer == NULL)
    {
        perror("Error opening file");
        return (0);
    }
    while (fgets(line, 8, fpointer) != NULL)
    {
        //Max number of letters for name under assumption is 8
        char name[8];
        int amount = 0;
        scanf(line, "%s %d", name, amount);
        printf("%s", name);
        memset(line, 0, 8);
        for (int i = 0; i < MAXPEOPLE; ++i)
        {
            return(0);
        }
    }
}
</code>```

Any help is appreciated. Go easy on me :)

答:
I think the main issue with getting the scanning right is that you read into line with fgets()(wise move) and then try to scan from there.

```<code>scanf(line, "%s %d", name, amount);
</code>```

but use the wrong function to do so. Use sscanf().

https://en.cppreference.com/w/c/io/fscanf

For completeness let me add the contribution from comments by Martin James and Jonathan Leffler:

You only live twice, but you can only return once: your loop is pointless

I.e. once any iteration of your for loop has a return, and all of them have, your while loop is finished.

You call fopen() but don't assign (or check) the returned value. You then test the still uninitialized fpointer. Not a recipe for happiness!

I.e. this

```<code>fopen("file.txt", "r");
if (fpointer == NULL)
</code>```

should be

```<code>fpointer = fopen("file.txt", "r");
if (fpointer == NULL)
</code>```

Body:
I hope this question isn't too similar to another that's posted. I am still learning how to read other peoples code at this point let alone write my own. I am confused as to how to read both a string and int from a line in a file and store it in a struct called People.
I have been looking at fgets, fscanf and even fread but I can't figure out what to use and where to use it.
I am getting this data from a file with a max of 10 entries that looks like this:

Joshua 50
Dwayne 90
Jennifer 45
Goldilocks 85

Here is my code:

typedef struct
{
    char *name[20];
    int change_amount;
    int fifties;
    int twenties;
    int tens;
    int fives;
}People;

int get_file()
{
    const int MAXPEOPLE = 10;
    People persons[MAXPEOPLE];
    int i = 0;
    FILE *fpointer;
    char line[12];
    fopen("file.txt", "r");
    if (fpointer == NULL)
    {
        perror("Error opening file");
        return (0);
    }
    while (fgets(line, 8, fpointer) != NULL)
    {
        //Max number of letters for name under assumption is 8
        char name[8];
        int amount = 0;
        scanf(line, "%s %d", name, amount);
        printf("%s", name);
        memset(line, 0, 8);
        for (int i = 0; i < MAXPEOPLE; ++i)
        {
            return(0);
        }
    }
}

Any help is appreciated. Go easy on me :)

Body:
I think the main issue with getting the scanning right is that you read into line with fgets()(wise move) and then try to scan from there.

scanf(line, "%s %d", name, amount);

but use the wrong function to do so. Use sscanf().

https://en.cppreference.com/w/c/io/fscanf

For completeness let me add the contribution from comments by Martin James and Jonathan Leffler:

You only live twice, but you can only return once: your loop is pointless

I.e. once any iteration of your for loop has a return, and all of them have, your while loop is finished.

You call fopen() but don't assign (or check) the returned value. You then test the still uninitialized fpointer. Not a recipe for happiness!

I.e. this

fopen("file.txt", "r");
if (fpointer == NULL)

should be

fpointer = fopen("file.txt", "r");
if (fpointer == NULL)


问:
How to cythonize a python script for Android using Chaquopy?
My target is to cythonize/obfuscate a python script using Cython for Android platform.

What I have tried till now is:
I have a setup.py

```<code>from setuptools import setup
from Cython.Build import cythonize
import os
print(os.getcwd())
os.chdir('/sdcard/Download')
print(os.getcwd())

setup(
    ext_modules=cythonize('test1.py')
)
</code>```

Here I am changing the dir to /sdcard/Download/ since the python script I want to obfuscate is in that dir.

Case 1:

Inside MainActivity.java am calling the setup.py like:

```<code>Python py = Python.getInstance();
PyObject os= py.getModule("setup");
</code>```

This way it throws an error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.styleapp, PID: 2422
    com.chaquo.python.PyException: SystemExit: usage:  [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
       or:  --help [cmd1 cmd2 ...]
       or:  --help-commands
       or:  cmd --help

    error: no commands supplied
        at <python>.distutils.core.setup(core.py:136)
        at <python>.setuptools.setup(__init__.py:161)
        at <python>.setup.<module>(setup.py:8)
        at <python>.importlib._bootstrap._call_with_frames_removed(<frozen importlib._bootstrap>:219)
        at <python>.importlib._bootstrap_external.exec_module(<frozen importlib._bootstrap_external>:783)
        at <python>.java.android.importer.exec_module(importer.py:503)
        at <python>.java.android.importer.exec_module(importer.py:546)
        at <python>.importlib._bootstrap._load_unlocked(<frozen importlib._bootstrap>:671)
        at <python>.importlib._bootstrap._find_and_load_unlocked(<frozen importlib._bootstrap>:975)
        at <python>.importlib._bootstrap._find_and_load(<frozen importlib._bootstrap>:991)
        at <python>.importlib._bootstrap._gcd_import(<frozen importlib._bootstrap>:1014)
        at <python>.importlib.import_module(__init__.py:127)
        at <python>.chaquopy_java.Java_com_chaquo_python_Python_getModule(chaquopy_java.pyx:152)
        at com.chaquo.python.Python.getModule(Native Method)
        at com.example.styleapp.MainActivity.runthemodel(MainActivity.java:127)
        at com.example.styleapp.MainActivity.access$000(MainActivity.java:47)
        at com.example.styleapp.MainActivity$2.onMenuItemClick(MainActivity.java:103)
        at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:154)
        at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
        at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:981)
        at androidx.appcompat.widget.ActionMenuView.invokeItem(ActionMenuView.java:625)
        at androidx.appcompat.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)
        at android.view.View.performClick(View.java:7140)
        at android.view.View.performClickInternal(View.java:7117)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27355)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7410)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
</code>```

I understand this is because am not passing any arguments like I should:

```<code>python setup.py build_ext -b /sdcard/Download/ -t .
</code>```

Case 2:

If i use this:

```<code>PyObject os= py.getModule("setup.py build_ext -b /sdcard/Download/ -t .");
</code>```

I get the same error.

I need help to understand how to pass on these args?

I tried to replicate:

```<code>import os
os.system('python3 setup.py build_ext -b "/sdcard/Download/" -t .')
</code>```

as

```<code>PyObject os = py.getModule("os");
os.callAttr("system","python3 setup.py build_ext -b /sdcard/Download/ -t .");
</code>```

But that is not even calling the setup.py script.

答: The reason I was not able to compile a Cython module on an actual Android device, because most devices don't come with a compiler. I guess we can compile py files into pyc since they are not machine dependant.</p>

Body:
My target is to cythonize/obfuscate a python script using Cython for Android platform.

What I have tried till now is:
I have a setup.py

from setuptools import setup
from Cython.Build import cythonize
import os
print(os.getcwd())
os.chdir('/sdcard/Download')
print(os.getcwd())

setup(
    ext_modules=cythonize('test1.py')
)

Here I am changing the dir to /sdcard/Download/ since the python script I want to obfuscate is in that dir.

Case 1:

Inside MainActivity.java am calling the setup.py like:

Python py = Python.getInstance();
PyObject os= py.getModule("setup");

This way it throws an error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.styleapp, PID: 2422
    com.chaquo.python.PyException: SystemExit: usage:  [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
       or:  --help [cmd1 cmd2 ...]
       or:  --help-commands
       or:  cmd --help

    error: no commands supplied
        at <python>.distutils.core.setup(core.py:136)
        at <python>.setuptools.setup(__init__.py:161)
        at <python>.setup.<module>(setup.py:8)
        at <python>.importlib._bootstrap._call_with_frames_removed(<frozen importlib._bootstrap>:219)
        at <python>.importlib._bootstrap_external.exec_module(<frozen importlib._bootstrap_external>:783)
        at <python>.java.android.importer.exec_module(importer.py:503)
        at <python>.java.android.importer.exec_module(importer.py:546)
        at <python>.importlib._bootstrap._load_unlocked(<frozen importlib._bootstrap>:671)
        at <python>.importlib._bootstrap._find_and_load_unlocked(<frozen importlib._bootstrap>:975)
        at <python>.importlib._bootstrap._find_and_load(<frozen importlib._bootstrap>:991)
        at <python>.importlib._bootstrap._gcd_import(<frozen importlib._bootstrap>:1014)
        at <python>.importlib.import_module(__init__.py:127)
        at <python>.chaquopy_java.Java_com_chaquo_python_Python_getModule(chaquopy_java.pyx:152)
        at com.chaquo.python.Python.getModule(Native Method)
        at com.example.styleapp.MainActivity.runthemodel(MainActivity.java:127)
        at com.example.styleapp.MainActivity.access$000(MainActivity.java:47)
        at com.example.styleapp.MainActivity$2.onMenuItemClick(MainActivity.java:103)
        at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:154)
        at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
        at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:981)
        at androidx.appcompat.widget.ActionMenuView.invokeItem(ActionMenuView.java:625)
        at androidx.appcompat.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)
        at android.view.View.performClick(View.java:7140)
        at android.view.View.performClickInternal(View.java:7117)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27355)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7410)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)

I understand this is because am not passing any arguments like I should:

python setup.py build_ext -b /sdcard/Download/ -t .

Case 2:

If i use this:

PyObject os= py.getModule("setup.py build_ext -b /sdcard/Download/ -t .");

I get the same error.

I need help to understand how to pass on these args?

I tried to replicate:

import os
os.system('python3 setup.py build_ext -b "/sdcard/Download/" -t .')

as

PyObject os = py.getModule("os");
os.callAttr("system","python3 setup.py build_ext -b /sdcard/Download/ -t .");

But that is not even calling the setup.py script.


问:
"kubectl get pods -A" command not working
I installed Kubernetes in virtual BOX  previously it was working properly but not it is showing The connection to the server 192.168.42.141:6443 was refused - did you specify the right host or port?, Please help.

答:
The connection to the server 192.168.42.141:6443 was refused - did you specify the right host or port?

According to issue there might be kube-apiserver not running state. To check the apiserver status run following command

```<code>$ docker ps
# If above is not sowing apiserver container, then it is stopped, To see the stopped container run
$ docker ps -a
</code>```

P.S: From the comment there is also a version mismatch. To update kubectl follow this

Body:
The connection to the server 192.168.42.141:6443 was refused - did you specify the right host or port?

According to issue there might be kube-apiserver not running state. To check the apiserver status run following command

$ docker ps
# If above is not sowing apiserver container, then it is stopped, To see the stopped container run
$ docker ps -a

P.S: From the comment there is also a version mismatch. To update kubectl follow this


问:
Unable to add an array index
I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

```<code>// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };
</code>```

i want to get something like

```<code>f0: 1,
f1: 5,
f2: 9
</code>```

答:
My approach would be a little different from other answers.
I would prefer using Object.entries as this is more clear and explicit.

const sf = {}
const arr = [1,2,3,4,5,6]
for (let [key, value] of Object.entries(arr)) {
  sf[`f${key}`] = value
}
console.log(sf);```

Title: Unable to add an array index

Body:
I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };

i want to get something like

f0: 1,
f1: 5,
f2: 9


问:
how to draw thousand of circles at once openCv faster - (Maybe use GPU)
I need to draw thousands of dots on a given area of an image (frame of a video).

Using a loop is the easiest way to do this.

```<code>    while i < num:
        x = random.randint(min_x, max_x)
        y = random.randint(min_y, max_y)
        //this if is to check the the random points are within the original shape
        if cv2.pointPolygonTest(contour, (int(x), int(y)), False)==1:
            cv2.circle(img, (int(x), int(y)), 2, color, -1)
            i = i+1;
</code>```

this process takes a long time to complete.

how can I achieve this more efficiently?

答:
Maybe it's possible to speed it up using several tricks:

Try to get rid of the loop and vectorize your operations.
You can vectorize the (x, y) point generation by passing size to random.randint. If after filtering they don't amount to num, you can generate another set.

Instead of pointPolygonTest, maybe you can try matplotlib.path.Path.contains_points that operates on a vector of points rather than a single point.

For the circle, once you filter all your circle centers, create an all zeros image to draw your circles, then mark centers in this image (again, vectorize). If you want color circles you'll have to set the pixel value to appropriate gray level for each channel. Then dilate using a circular structuring element having the required radius. For small radii, these circles should be fine. Or, you can try Gaussian blur as well, because, if you convolve a Gaussian with an impulse, it'll give you a Gaussian, and a symmetric Gaussian will resemble a circle in the image. You can also use filter2D to do this if your circles have the same size. If the dilation result isn't good, you can create your own kernel resembling the circle you want, then convolve it with centers image.

Copy all non-zero pixels from this circles image to your img using the circles image as a mask.

A simple example for creating circles:

```<code>import numpy as np
import cv2 as cv

# create random centers for circles
img = np.random.randint(low=0, high=1000, size=(256, 256))
img = np.uint8(img < 1) * 255
# use Gaussian bluer to create cricles
img1 = cv.GaussianBlur(img, (9, 9), 3)*20
# use morphological dilation bluer to create cricles
se = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
img2 = cv.dilate(img, se)
</code>```

Centers:

Circles using dilation:

Circles using Gaussian blur:

Body:
I need to draw thousands of dots on a given area of an image (frame of a video).

Using a loop is the easiest way to do this.

    while i < num:
        x = random.randint(min_x, max_x)
        y = random.randint(min_y, max_y)
        //this if is to check the the random points are within the original shape
        if cv2.pointPolygonTest(contour, (int(x), int(y)), False)==1:
            cv2.circle(img, (int(x), int(y)), 2, color, -1)
            i = i+1;

this process takes a long time to complete.

how can I achieve this more efficiently?

Body:
Maybe it's possible to speed it up using several tricks:

Try to get rid of the loop and vectorize your operations.
You can vectorize the (x, y) point generation by passing size to random.randint. If after filtering they don't amount to num, you can generate another set.

Instead of pointPolygonTest, maybe you can try matplotlib.path.Path.contains_points that operates on a vector of points rather than a single point.

For the circle, once you filter all your circle centers, create an all zeros image to draw your circles, then mark centers in this image (again, vectorize). If you want color circles you'll have to set the pixel value to appropriate gray level for each channel. Then dilate using a circular structuring element having the required radius. For small radii, these circles should be fine. Or, you can try Gaussian blur as well, because, if you convolve a Gaussian with an impulse, it'll give you a Gaussian, and a symmetric Gaussian will resemble a circle in the image. You can also use filter2D to do this if your circles have the same size. If the dilation result isn't good, you can create your own kernel resembling the circle you want, then convolve it with centers image.

Copy all non-zero pixels from this circles image to your img using the circles image as a mask.

A simple example for creating circles:

import numpy as np
import cv2 as cv

# create random centers for circles
img = np.random.randint(low=0, high=1000, size=(256, 256))
img = np.uint8(img < 1) * 255
# use Gaussian bluer to create cricles
img1 = cv.GaussianBlur(img, (9, 9), 3)*20
# use morphological dilation bluer to create cricles
se = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
img2 = cv.dilate(img, se)

Centers:

Circles using dilation:

Circles using Gaussian blur:


答:
Try this</p>

```<code>public void stan(View hiring){
        ArrayAdapter<CharSequence> hire=ArrayAdapter.createFromResource(this,R.array.decide, android.R.layout.simple_spinner_item);
        hire.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(hire);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String decide =spinner.getSelectedItem().toString();
                int age= Integer.parseInt(aged.getText().toString());
                if(age>18 && decide.equals("Yes")){
                Toast.makeText(this,"Ok, go eat cabbage sauce",Toast.LENGTH_LONG).show();
                }else{
                Toast.makeText(this,"no",Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
</code>```

Title: If condition on Spinner drop-down list

Body:
I made a drop-down list using spinner but now I want and a specific message to display when a certain value is selected along with an EditText when a certain keyword is entered. I attempted using if condition but it didn't work. The scenario is like this: When the user input their age over 18 and selects "Yes" from the drop-down hire, a certain message will appear, both conditions must be satisfied

 public void stan(View hiring){
        ArrayAdapter<CharSequence> hire=ArrayAdapter.createFromResource(this,R.array.decide, android.R.layout.simple_spinner_item);
        hire.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(hire);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String decide =spinner.getSelectedItem().toString()
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        int age= Integer.parseInt(aged.getText().toString());
        if(age>18 && spinner.equals("Yes")){
            Toast.makeText(this,"Ok, go eat cabbage sauce",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(this,"no",Toast.LENGTH_LONG).show();
        }

Body:
Try this

public void stan(View hiring){
        ArrayAdapter<CharSequence> hire=ArrayAdapter.createFromResource(this,R.array.decide, android.R.layout.simple_spinner_item);
        hire.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(hire);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String decide =spinner.getSelectedItem().toString();
                int age= Integer.parseInt(aged.getText().toString());
                if(age>18 && decide.equals("Yes")){
                Toast.makeText(this,"Ok, go eat cabbage sauce",Toast.LENGTH_LONG).show();
                }else{
                Toast.makeText(this,"no",Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });


问:
React/Redux question about dispatching an action to add an item to an array
I am building a flashcard app and I would like to store the id of seen cards in an array so my GET_RANDOM_CARD action does not select the same card twice.

Inside my componentDidMount method, I dispatch the addSeenCard action like so:

```<code>addSeenCard(this.props.randomCard)
</code>```

Here is my portable action creator function for addSeenCard:

```<code>export function addSeenCard(randomCard) {

 return {
    type: 'ADD_SEEN_CARD',
    randomCard: randomCard
  }
}
</code>```

Here is my reducer function:

```<code> case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [state.seenCard, action.randomCard.id]
    }
</code>```

However, the Redux tool instead of showing an array with an id value shows an array with a nested empty array and a value of null.  I am learning Redux and I am blocked as to where I am going wrong in my code.

Redux state Raw

答:
From the above code of reducer, it came to know that "seenCard" will be an array of ids and you have assigned array as the first element of seenCard going forward.

So use a Spread operator to destructure the array of elements.

```<code>case 'ADD_SEEN_CARD':
  return {
    ...state,
    seenCard: [
      ...state.seenCard,
       action.randomCard.id
     ]
  }
</code>```

Note the 3 dots added on the 5th line of code.

Also, make sure id is always passed to action creator.

I hope this is helpful!

Body:
I am building a flashcard app and I would like to store the id of seen cards in an array so my GET_RANDOM_CARD action does not select the same card twice.

Inside my componentDidMount method, I dispatch the addSeenCard action like so:

addSeenCard(this.props.randomCard)

Here is my portable action creator function for addSeenCard:

export function addSeenCard(randomCard) {

 return {
    type: 'ADD_SEEN_CARD',
    randomCard: randomCard
  }
}

Here is my reducer function:

 case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [state.seenCard, action.randomCard.id]
    }

However, the Redux tool instead of showing an array with an id value shows an array with a nested empty array and a value of null.  I am learning Redux and I am blocked as to where I am going wrong in my code.

Redux state Raw

Body:
From the above code of reducer, it came to know that "seenCard" will be an array of ids and you have assigned array as the first element of seenCard going forward.

So use a Spread operator to destructure the array of elements.

case 'ADD_SEEN_CARD':
  return {
    ...state,
    seenCard: [
      ...state.seenCard,
       action.randomCard.id
     ]
  }

Note the 3 dots added on the 5th line of code.

Also, make sure id is always passed to action creator.

I hope this is helpful!


问:
Build only projects which are changed in a solution -Azure CI pipeline - YAML
I have multiple projects under a solution,

```<code>ProjectA.csproj
projectB.csproj
projectC.csproj
</code>```

I have created a YAML CI build pipeline for this solution with trigger from Master Branch

"trigger: - Master"

Whenever a check-in happens to Master for any of the project above, it triggers the CI pipeline and create artifacts for all the above individual projects.

Question - can I only build projects which have changes using the same single YAML file for the solution?

答:
Question - can I only build projects which have changes using the same
  single YAML file for the solution?

Yes, you can. Assuming you have multiple jobs/steps for different projects, you can use Conditions to determine when it should run/skip some specific steps. You can check this example:

```<code>trigger:
- master

pool:
  vmImage: 'windows-latest'

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $files=$(git diff HEAD HEAD~ --name-only)
      $temp=$files -split ' '
      $count=$temp.Length
      For ($i=0; $i -lt $temp.Length; $i++)
      {
        $name=$temp[$i]
        echo "this is $name file"
        if ($name -like "ProjectA/*")
          {
            Write-Host "##vso[task.setvariable variable=RunProjectA]True"
          }
        if ($name -like "ProjectB/*")
          {
            Write-Host "##vso[task.setvariable variable=RunProjectB]True"
          }
        if ($name -like "ProjectC/*")
          {
            Write-Host "##vso[task.setvariable variable=RunProjectC]True"
          }
      }

- script: echo "Run this step when ProjectA folder is changed."
  displayName: 'Run A'
  condition: eq(variables['RunProjectA'], 'True')

- script: echo "Run this step when ProjectB folder is changed."
  displayName: 'Run B'
  condition: eq(variables['RunProjectB'], 'True')

- script: echo "Run this step when ProjectC folder is changed."
  displayName: 'Run C'
  condition: eq(variables['RunProjectC'], 'True')
</code>```

Then if we only have changes in ProjectA folder, only those steps/tasks with condition: eq(variables['RunProjectA'], 'True') will run. You should have three separate build tasks in your pipeline for ProjectA, ProjectB and ProjectC, and give them your custom condition, then you can only build projects which have changes... (Hint from Jayendran in this issue!)

Hope it works.

Body:
I have multiple projects under a solution,

ProjectA.csproj
projectB.csproj
projectC.csproj

I have created a YAML CI build pipeline for this solution with trigger from Master Branch

"trigger: - Master"

Whenever a check-in happens to Master for any of the project above, it triggers the CI pipeline and create artifacts for all the above individual projects.

Question - can I only build projects which have changes using the same single YAML file for the solution?

Body:
Question - can I only build projects which have changes using the same
  single YAML file for the solution?

Yes, you can. Assuming you have multiple jobs/steps for different projects, you can use Conditions to determine when it should run/skip some specific steps. You can check this example:

trigger:
- master

pool:
  vmImage: 'windows-latest'

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $files=$(git diff HEAD HEAD~ --name-only)
      $temp=$files -split ' '
      $count=$temp.Length
      For ($i=0; $i -lt $temp.Length; $i++)
      {
        $name=$temp[$i]
        echo "this is $name file"
        if ($name -like "ProjectA/*")
          {
            Write-Host "##vso[task.setvariable variable=RunProjectA]True"
          }
        if ($name -like "ProjectB/*")
          {
            Write-Host "##vso[task.setvariable variable=RunProjectB]True"
          }
        if ($name -like "ProjectC/*")
          {
            Write-Host "##vso[task.setvariable variable=RunProjectC]True"
          }
      }

- script: echo "Run this step when ProjectA folder is changed."
  displayName: 'Run A'
  condition: eq(variables['RunProjectA'], 'True')

- script: echo "Run this step when ProjectB folder is changed."
  displayName: 'Run B'
  condition: eq(variables['RunProjectB'], 'True')

- script: echo "Run this step when ProjectC folder is changed."
  displayName: 'Run C'
  condition: eq(variables['RunProjectC'], 'True')

Then if we only have changes in ProjectA folder, only those steps/tasks with condition: eq(variables['RunProjectA'], 'True') will run. You should have three separate build tasks in your pipeline for ProjectA, ProjectB and ProjectC, and give them your custom condition, then you can only build projects which have changes... (Hint from Jayendran in this issue!)

Hope it works.


问:
hibernate cascade - update child to null
I have a one to many relationship between event and session. I'd like cascade to update event fk in session to null when i delete the corresponding event. Any clue how to do this?
Thanks and advance.</p>

答:
Hibernate or JPA unfortunately don't have a Cascade type 'SET to NULL' but you should be able to do it with @PreRemove

on the one side (Owner):

```<code>@OneToMany(mappedBy="whatever")
public List<SomeEntity> getSomeEntity(){
    return someEntity;
}

@PreRemove
public void onDelete(){
    for(SomeEntity se : getSomeEntity()){
        se.setOwner(null);
     }
}
</code>```

Hope that helps.

ContentLicense: CC BY-SA 2.5

Body:
Hibernate or JPA unfortunately don't have a Cascade type 'SET to NULL' but you should be able to do it with @PreRemove

on the one side (Owner):

@OneToMany(mappedBy="whatever")
public List<SomeEntity> getSomeEntity(){
    return someEntity;
}

@PreRemove
public void onDelete(){
    for(SomeEntity se : getSomeEntity()){
        se.setOwner(null);
     }
}

Hope that helps.


问:
Signin Page showing no Storage provider for custom AuthService Karma
I'm finding it hard to debug why my ionic page is complaining that the AuthService does not have a Storage Provider. I tried creating a new AuthService in the TestBed but no dice. Could you also explain why this is an issue so I can learn from it? I can't find anything about Injecting a service which is injecting the storage module.

Failed: StaticInjectorError(DynamicTestModule)[AuthService -> Storage]:
    StaticInjectorError(Platform: core)[AuthService -> Storage]:
      NullInjectorError: No provider for Storage!

import {
  async,
  ComponentFixture,
  TestBed,
  fakeAsync,
  tick,
} from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { RouterTestingModule } from '@angular/router/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import {
  HttpClientTestingModule,
  HttpTestingController,
} from '@angular/common/http/testing';
import { SignInPage } from './sign-in.page';
import { User } from 'src/app/classes/user';
import { AuthService } from '../../services/auth-service/auth.service';
import { UsersDataPublic } from '../../services/users-service/users-data-public';
import { UserProfileService } from '../../services/user-profile/user-profile.service';
import { UserProfileDatabase } from '../../services/user-profile/user-profile-db.service';
import { AppConstants } from '../../constants/app.constants';
import { Storage } from '@ionic/Storage';
import { NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA, inject } from '@angular/core';

const storageIonicMock: any = {
  get: () => new Promise<any>((resolve, reject) => resolve('As2342fAfgsdr')),
  set: () => new Promise<any>((resolve, reject) => resolve('As2342fAfgsdr'))
};

describe('SignInPage', () => {
  let component: SignInPage;
  let httpTestingController: HttpTestingController;
  let fixture: ComponentFixture<SignInPage>;
  let httpClient: HttpClient;
  let service: UsersDataPublic;
  let userProfileservice: UserProfileService;
  let authService: AuthService;
  let auth;
  let userProfileDatabase: UserProfileDatabase;
  let constants: AppConstants;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [SignInPage],
      providers: [
        UsersDataPublic,
        UserProfileService,
        UserProfileDatabase,
        AppConstants,
        AuthService,
        {
          provide: Storage,
          useValue: storageIonicMock
        }
      ],
      imports: [
        IonicModule.forRoot(),
        ReactiveFormsModule,
        FormsModule,
        RouterTestingModule,
        FormsModule,
        HttpClientTestingModule,
      ],
      schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA],
    }).compileComponents();

    fixture = TestBed.createComponent(SignInPage);
    constants = TestBed.get(AppConstants);
    service = TestBed.get(UsersDataPublic);
    userProfileservice = TestBed.get(UserProfileService);
    authService = TestBed.get(new AuthService(storageIonicMock, httpClient, constants));
    userProfileDatabase = TestBed.get(UserProfileDatabase);
    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('form invalid when empty', () => {
    expect(component.signinForm.valid).toBeFalsy();
  });

  it('should run ngOnInit 1 time', fakeAsync(() => {
    fixture.detectChanges();
    spyOn(component, 'ngOnInit').and.callThrough();
    component.ngOnInit();
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(component.ngOnInit).toHaveBeenCalledTimes(1);
  }));

  it('should have a title of Sign In', () => {
    const title: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#home-title'
    );
    expect(title.textContent).toEqual('Sign In');
  });

  it('should run signIn 1 time', fakeAsync(() => {
    fixture.detectChanges();
    spyOn(component, 'signIn').and.callThrough();
    component.signIn();
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(component.signIn).toHaveBeenCalledTimes(1);
  }));

  it('should set the user object to the values set by signIn', fakeAsync(() => {
    const user = {
      ppsn: '13322277P',
      day: '1',
      month: '1',
      year: '1970',
      password: 'Testing123!',
    };

    let ppsn: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#ppsn'
    );
    let day: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#day'
    );
    let month: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#month'
    );
    let year: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#year'
    );
    let password: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#password'
    );

    ppsn.value = '13322277P';
    day.value = '1';
    month.value = '1';
    year.value = '1970';
    password.value = 'Testing123!';

    fixture.detectChanges();
    spyOn(component, 'signIn').and.callThrough();
    component.signIn();
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(component.signIn).toHaveBeenCalledTimes(1);
    expect(component.userDetails).toEqual(user);
  }));

  it('should not match the user object to the values set by signIn', fakeAsync(() => {
    const user = {
      ppsn: '13322277P',
      day: '1',
      month: '2',
      year: '1970',
      password: 'Testing123!',
    };

    let ppsn: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#ppsn'
    );
    let day: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#day'
    );
    let month: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#month'
    );
    let year: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#year'
    );
    let password: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#password'
    );

    ppsn.value = '13322277P';
    day.value = '1';
    month.value = '1';
    year.value = '1970';
    password.value = 'Testing123!';

    fixture.detectChanges();
    spyOn(component, 'signIn').and.callThrough();
    component.signIn();
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(component.signIn).toHaveBeenCalledTimes(1);
    expect(component.userDetails).not.toEqual(user);
  }));
});

```

<h3>AuthService which Injects the Storage</h3>

<pre class="lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError, Observable, BehaviorSubject } from 'rxjs';
import { AppConstants } from '../../constants/app.constants';
import { Storage } from '@ionic/storage';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  authenticationState = new BehaviorSubject(false);
  authDetails = {authenticated: false, type: null, myAccountPortalAuthenticated: false };

  constructor(private storage: Storage, private httpClient: HttpClient, private constants: AppConstants) { }

  handleError(error: HttpErrorResponse) {
    let errorMessage = 'Unknown error!';
    if (error.error instanceof ErrorEvent) {
      errorMessage = `Error: ${error.error.message}`;
    } else {
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    return throwError(errorMessage);
  }

  login(url): Observable<any> {
    return this.httpClient.post(url, {})
    .pipe(
      catchError((err: HttpErrorResponse) => {
        return throwError(err);
      })
    );
  }

  devLogin(url): Observable<any> {
    return this.httpClient.get(this.constants.LOCAL_REST_API_SERVER + '/users')
    .pipe(
      catchError((err: HttpErrorResponse) => {
        return throwError(err);
      })
    );
  }

  logout(url): Observable<any> {
    return this.httpClient.post(url, {})
    .pipe(
      catchError((err: HttpErrorResponse) => {
        return throwError(err);
      })
    );
  }

  getAuthenticationDetails() {
    return this.storage.get('auth');
  }

  getAuthenticationState(): Observable<boolean> {
    return this.authenticationState.asObservable();
  }

  setIsAuthenticated(value, loginType) {
    this.authDetails.authenticated = value;
    this.authDetails.type = loginType;
    this.storage.set('auth', this.authDetails);
    this.authenticationState.next(value);
  }

}

</code>```

Module for SignIn

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { IonicModule } from '@ionic/angular';
import { UserProfileDatabase } from '../../services/user-profile/user-profile-db.service';
import { UserProfileService } from '../../services/user-profile/user-profile.service';
import { AuthService } from '../../services/auth-service/auth.service';
import { SignInPageRoutingModule } from './sign-in-routing.module';
import { SignInPage } from './sign-in.page';
import { ReactiveFormsModule } from '@angular/forms';
import { Storage, IonicStorageModule } from '@ionic/Storage';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    SignInPageRoutingModule,
    ReactiveFormsModule,
    IonicStorageModule.forRoot()
  ],
  declarations: [SignInPage],
  providers: [UserProfileDatabase, UserProfileService, AuthService]
})
export class SignInPageModule {}

```

答:
Change your script to  :- </p>

```<code>import {
async,
ComponentFixture,
TestBed,
fakeAsync,
tick,
} from "@angular/core/testing";
import { IonicModule } from "@ionic/angular";
import { RouterTestingModule } from "@angular/router/testing";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { HttpClient } from "@angular/common/http";
import {
HttpClientTestingModule,
HttpTestingController,
} from "@angular/common/http/testing";
import { SignInPage } from "./sign-in.page";
import { User } from "src/app/classes/user";
import { AuthService } from "../../services/auth-service/auth.service";
import { UsersDataPublic } from "../../services/users-service/users-data-public";
import { UserProfileService } from "../../services/user-profile/user-profile.service";
import { UserProfileDatabase } from "../../services/user-profile/user-profile-db.service";
import { AppConstants } from "../../constants/app.constants";
import {
NO_ERRORS_SCHEMA,
CUSTOM_ELEMENTS_SCHEMA,
inject,
} from "@angular/core";

class MockAuthService {
constructor() {}
handleError(error) {}
login(url) {}
devLogin(url) {}
logout(url) {}
getAuthenticationDetails() {}
getAuthenticationState() {}
setIsAuthenticated() {}
}

describe("SignInPage", () => {
let component: SignInPage;
let httpTestingController: HttpTestingController;
let fixture: ComponentFixture<SignInPage>;
let httpClient: HttpClient;
let service: UsersDataPublic;
let userProfileservice: UserProfileService;
let authService: AuthService;
let auth;
let userProfileDatabase: UserProfileDatabase;
let constants: AppConstants;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SignInPage],
providers: [
UsersDataPublic,
UserProfileService,
UserProfileDatabase,
AppConstants,
{ provide: AuthService, useClass: MockAuthService },
],
imports: [
IonicModule.forRoot(),
ReactiveFormsModule,
FormsModule,
RouterTestingModule,
FormsModule,
HttpClientTestingModule,
],
schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();

fixture = TestBed.createComponent(SignInPage);
constants = TestBed.get(AppConstants);
service = TestBed.get(UsersDataPublic);
userProfileservice = TestBed.get(UserProfileService);
userProfileDatabase = TestBed.get(UserProfileDatabase);
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
authService = TestBed.get(AuthService);
component = fixture.componentInstance;
fixture.detectChanges();
}));

it("should create", () => {
expect(component).toBeTruthy();
});

it("form invalid when empty", () => {
expect(component.signinForm.valid).toBeFalsy();
});

it("should run ngOnInit 1 time", fakeAsync(() => {
fixture.detectChanges();
spyOn(component, "ngOnInit").and.callThrough();
component.ngOnInit();
tick(); // simulates the passage of time until all pending asynchronous activities finish
fixture.detectChanges();
expect(component.ngOnInit).toHaveBeenCalledTimes(1);
}));

it("should have a title of Sign In", () => {
const title: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#home-title"
);
expect(title.textContent).toEqual("Sign In");
});

it("should run signIn 1 time", fakeAsync(() => {
fixture.detectChanges();
spyOn(component, "signIn").and.callThrough();
component.signIn();
tick(); // simulates the passage of time until all pending asynchronous activities finish
fixture.detectChanges();
expect(component.signIn).toHaveBeenCalledTimes(1);
}));

it("should set the user object to the values set by signIn", fakeAsync(() => {
const user = {
ppsn: "13322277P",
day: "1",
month: "1",
year: "1970",
password: "Testing123!",
};

let ppsn: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#ppsn"
);
let day: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#day"
);
let month: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#month"
);
let year: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#year"
);
let password: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#password"
);

ppsn.value = "13322277P";
day.value = "1";
month.value = "1";
year.value = "1970";
password.value = "Testing123!";

fixture.detectChanges();
spyOn(component, "signIn").and.callThrough();
component.signIn();
tick(); // simulates the passage of time until all pending asynchronous activities finish
fixture.detectChanges();
expect(component.signIn).toHaveBeenCalledTimes(1);
expect(component.userDetails).toEqual(user);
}));

it("should not match the user object to the values set by signIn", fakeAsync(() => {
const user = {
ppsn: "13322277P",
day: "1",
month: "2",
year: "1970",
password: "Testing123!",
};

let ppsn: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#ppsn"
);
let day: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#day"
);
let month: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#month"
);
let year: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#year"
);
let password: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#password"
);

ppsn.value = "13322277P";
day.value = "1";
month.value = "1";
year.value = "1970";
password.value = "Testing123!";

fixture.detectChanges();
spyOn(component, "signIn").and.callThrough();
component.signIn();
tick(); // simulates the passage of time until all pending asynchronous activities finish
fixture.detectChanges();
expect(component.signIn).toHaveBeenCalledTimes(1);
expect(component.userDetails).not.toEqual(user);
}));
});
</code>```

Body:
I'm finding it hard to debug why my ionic page is complaining that the AuthService does not have a Storage Provider. I tried creating a new AuthService in the TestBed but no dice. Could you also explain why this is an issue so I can learn from it? I can't find anything about Injecting a service which is injecting the storage module.

Failed: StaticInjectorError(DynamicTestModule)[AuthService -> Storage]:
    StaticInjectorError(Platform: core)[AuthService -> Storage]:
      NullInjectorError: No provider for Storage!

import {
  async,
  ComponentFixture,
  TestBed,
  fakeAsync,
  tick,
} from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { RouterTestingModule } from '@angular/router/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import {
  HttpClientTestingModule,
  HttpTestingController,
} from '@angular/common/http/testing';
import { SignInPage } from './sign-in.page';
import { User } from 'src/app/classes/user';
import { AuthService } from '../../services/auth-service/auth.service';
import { UsersDataPublic } from '../../services/users-service/users-data-public';
import { UserProfileService } from '../../services/user-profile/user-profile.service';
import { UserProfileDatabase } from '../../services/user-profile/user-profile-db.service';
import { AppConstants } from '../../constants/app.constants';
import { Storage } from '@ionic/Storage';
import { NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA, inject } from '@angular/core';

const storageIonicMock: any = {
  get: () => new Promise<any>((resolve, reject) => resolve('As2342fAfgsdr')),
  set: () => new Promise<any>((resolve, reject) => resolve('As2342fAfgsdr'))
};

describe('SignInPage', () => {
  let component: SignInPage;
  let httpTestingController: HttpTestingController;
  let fixture: ComponentFixture<SignInPage>;
  let httpClient: HttpClient;
  let service: UsersDataPublic;
  let userProfileservice: UserProfileService;
  let authService: AuthService;
  let auth;
  let userProfileDatabase: UserProfileDatabase;
  let constants: AppConstants;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [SignInPage],
      providers: [
        UsersDataPublic,
        UserProfileService,
        UserProfileDatabase,
        AppConstants,
        AuthService,
        {
          provide: Storage,
          useValue: storageIonicMock
        }
      ],
      imports: [
        IonicModule.forRoot(),
        ReactiveFormsModule,
        FormsModule,
        RouterTestingModule,
        FormsModule,
        HttpClientTestingModule,
      ],
      schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA],
    }).compileComponents();

    fixture = TestBed.createComponent(SignInPage);
    constants = TestBed.get(AppConstants);
    service = TestBed.get(UsersDataPublic);
    userProfileservice = TestBed.get(UserProfileService);
    authService = TestBed.get(new AuthService(storageIonicMock, httpClient, constants));
    userProfileDatabase = TestBed.get(UserProfileDatabase);
    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('form invalid when empty', () => {
    expect(component.signinForm.valid).toBeFalsy();
  });

  it('should run ngOnInit 1 time', fakeAsync(() => {
    fixture.detectChanges();
    spyOn(component, 'ngOnInit').and.callThrough();
    component.ngOnInit();
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(component.ngOnInit).toHaveBeenCalledTimes(1);
  }));

  it('should have a title of Sign In', () => {
    const title: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#home-title'
    );
    expect(title.textContent).toEqual('Sign In');
  });

  it('should run signIn 1 time', fakeAsync(() => {
    fixture.detectChanges();
    spyOn(component, 'signIn').and.callThrough();
    component.signIn();
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(component.signIn).toHaveBeenCalledTimes(1);
  }));

  it('should set the user object to the values set by signIn', fakeAsync(() => {
    const user = {
      ppsn: '13322277P',
      day: '1',
      month: '1',
      year: '1970',
      password: 'Testing123!',
    };

    let ppsn: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#ppsn'
    );
    let day: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#day'
    );
    let month: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#month'
    );
    let year: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#year'
    );
    let password: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#password'
    );

    ppsn.value = '13322277P';
    day.value = '1';
    month.value = '1';
    year.value = '1970';
    password.value = 'Testing123!';

    fixture.detectChanges();
    spyOn(component, 'signIn').and.callThrough();
    component.signIn();
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(component.signIn).toHaveBeenCalledTimes(1);
    expect(component.userDetails).toEqual(user);
  }));

  it('should not match the user object to the values set by signIn', fakeAsync(() => {
    const user = {
      ppsn: '13322277P',
      day: '1',
      month: '2',
      year: '1970',
      password: 'Testing123!',
    };

    let ppsn: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#ppsn'
    );
    let day: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#day'
    );
    let month: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#month'
    );
    let year: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#year'
    );
    let password: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
      '#password'
    );

    ppsn.value = '13322277P';
    day.value = '1';
    month.value = '1';
    year.value = '1970';
    password.value = 'Testing123!';

    fixture.detectChanges();
    spyOn(component, 'signIn').and.callThrough();
    component.signIn();
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(component.signIn).toHaveBeenCalledTimes(1);
    expect(component.userDetails).not.toEqual(user);
  }));
});

AuthService which Injects the Storage

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError, Observable, BehaviorSubject } from 'rxjs';
import { AppConstants } from '../../constants/app.constants';
import { Storage } from '@ionic/storage';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  authenticationState = new BehaviorSubject(false);
  authDetails = {authenticated: false, type: null, myAccountPortalAuthenticated: false };

  constructor(private storage: Storage, private httpClient: HttpClient, private constants: AppConstants) { }

  handleError(error: HttpErrorResponse) {
    let errorMessage = 'Unknown error!';
    if (error.error instanceof ErrorEvent) {
      errorMessage = `Error: ${error.error.message}`;
    } else {
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    return throwError(errorMessage);
  }

  login(url): Observable<any> {
    return this.httpClient.post(url, {})
    .pipe(
      catchError((err: HttpErrorResponse) => {
        return throwError(err);
      })
    );
  }

  devLogin(url): Observable<any> {
    return this.httpClient.get(this.constants.LOCAL_REST_API_SERVER + '/users')
    .pipe(
      catchError((err: HttpErrorResponse) => {
        return throwError(err);
      })
    );
  }

  logout(url): Observable<any> {
    return this.httpClient.post(url, {})
    .pipe(
      catchError((err: HttpErrorResponse) => {
        return throwError(err);
      })
    );
  }

  getAuthenticationDetails() {
    return this.storage.get('auth');
  }

  getAuthenticationState(): Observable<boolean> {
    return this.authenticationState.asObservable();
  }

  setIsAuthenticated(value, loginType) {
    this.authDetails.authenticated = value;
    this.authDetails.type = loginType;
    this.storage.set('auth', this.authDetails);
    this.authenticationState.next(value);
  }

}

Module for SignIn

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { IonicModule } from '@ionic/angular';
import { UserProfileDatabase } from '../../services/user-profile/user-profile-db.service';
import { UserProfileService } from '../../services/user-profile/user-profile.service';
import { AuthService } from '../../services/auth-service/auth.service';
import { SignInPageRoutingModule } from './sign-in-routing.module';
import { SignInPage } from './sign-in.page';
import { ReactiveFormsModule } from '@angular/forms';
import { Storage, IonicStorageModule } from '@ionic/Storage';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    SignInPageRoutingModule,
    ReactiveFormsModule,
    IonicStorageModule.forRoot()
  ],
  declarations: [SignInPage],
  providers: [UserProfileDatabase, UserProfileService, AuthService]
})
export class SignInPageModule {}

Body:
Change your script to  :-

import {
async,
ComponentFixture,
TestBed,
fakeAsync,
tick,
} from "@angular/core/testing";
import { IonicModule } from "@ionic/angular";
import { RouterTestingModule } from "@angular/router/testing";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { HttpClient } from "@angular/common/http";
import {
HttpClientTestingModule,
HttpTestingController,
} from "@angular/common/http/testing";
import { SignInPage } from "./sign-in.page";
import { User } from "src/app/classes/user";
import { AuthService } from "../../services/auth-service/auth.service";
import { UsersDataPublic } from "../../services/users-service/users-data-public";
import { UserProfileService } from "../../services/user-profile/user-profile.service";
import { UserProfileDatabase } from "../../services/user-profile/user-profile-db.service";
import { AppConstants } from "../../constants/app.constants";
import {
NO_ERRORS_SCHEMA,
CUSTOM_ELEMENTS_SCHEMA,
inject,
} from "@angular/core";

class MockAuthService {
constructor() {}
handleError(error) {}
login(url) {}
devLogin(url) {}
logout(url) {}
getAuthenticationDetails() {}
getAuthenticationState() {}
setIsAuthenticated() {}
}

describe("SignInPage", () => {
let component: SignInPage;
let httpTestingController: HttpTestingController;
let fixture: ComponentFixture<SignInPage>;
let httpClient: HttpClient;
let service: UsersDataPublic;
let userProfileservice: UserProfileService;
let authService: AuthService;
let auth;
let userProfileDatabase: UserProfileDatabase;
let constants: AppConstants;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SignInPage],
providers: [
UsersDataPublic,
UserProfileService,
UserProfileDatabase,
AppConstants,
{ provide: AuthService, useClass: MockAuthService },
],
imports: [
IonicModule.forRoot(),
ReactiveFormsModule,
FormsModule,
RouterTestingModule,
FormsModule,
HttpClientTestingModule,
],
schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();

fixture = TestBed.createComponent(SignInPage);
constants = TestBed.get(AppConstants);
service = TestBed.get(UsersDataPublic);
userProfileservice = TestBed.get(UserProfileService);
userProfileDatabase = TestBed.get(UserProfileDatabase);
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
authService = TestBed.get(AuthService);
component = fixture.componentInstance;
fixture.detectChanges();
}));

it("should create", () => {
expect(component).toBeTruthy();
});

it("form invalid when empty", () => {
expect(component.signinForm.valid).toBeFalsy();
});

it("should run ngOnInit 1 time", fakeAsync(() => {
fixture.detectChanges();
spyOn(component, "ngOnInit").and.callThrough();
component.ngOnInit();
tick(); // simulates the passage of time until all pending asynchronous activities finish
fixture.detectChanges();
expect(component.ngOnInit).toHaveBeenCalledTimes(1);
}));

it("should have a title of Sign In", () => {
const title: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#home-title"
);
expect(title.textContent).toEqual("Sign In");
});

it("should run signIn 1 time", fakeAsync(() => {
fixture.detectChanges();
spyOn(component, "signIn").and.callThrough();
component.signIn();
tick(); // simulates the passage of time until all pending asynchronous activities finish
fixture.detectChanges();
expect(component.signIn).toHaveBeenCalledTimes(1);
}));

it("should set the user object to the values set by signIn", fakeAsync(() => {
const user = {
ppsn: "13322277P",
day: "1",
month: "1",
year: "1970",
password: "Testing123!",
};

let ppsn: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#ppsn"
);
let day: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#day"
);
let month: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#month"
);
let year: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#year"
);
let password: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#password"
);

ppsn.value = "13322277P";
day.value = "1";
month.value = "1";
year.value = "1970";
password.value = "Testing123!";

fixture.detectChanges();
spyOn(component, "signIn").and.callThrough();
component.signIn();
tick(); // simulates the passage of time until all pending asynchronous activities finish
fixture.detectChanges();
expect(component.signIn).toHaveBeenCalledTimes(1);
expect(component.userDetails).toEqual(user);
}));

it("should not match the user object to the values set by signIn", fakeAsync(() => {
const user = {
ppsn: "13322277P",
day: "1",
month: "2",
year: "1970",
password: "Testing123!",
};

let ppsn: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#ppsn"
);
let day: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#day"
);
let month: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#month"
);
let year: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#year"
);
let password: HTMLInputElement = fixture.debugElement.nativeElement.querySelector(
"#password"
);

ppsn.value = "13322277P";
day.value = "1";
month.value = "1";
year.value = "1970";
password.value = "Testing123!";

fixture.detectChanges();
spyOn(component, "signIn").and.callThrough();
component.signIn();
tick(); // simulates the passage of time until all pending asynchronous activities finish
fixture.detectChanges();
expect(component.signIn).toHaveBeenCalledTimes(1);
expect(component.userDetails).not.toEqual(user);
}));
});


问:
What can cause a kotlin.TypeCastException for an Activity?
In the Google Play console, I look at the error report and see the following:

```<code>kotlin.TypeCastException:
  at com.app.android.ui.SplashFragment.loadAds (SplashFragment.java:111)
  at com.app.android.ui.SplashFragment$requestConsentInfoUpdate$1.onConsentInfoUpdated (SplashFragment.java:68)
  at com.google.ads.consent.ConsentInformation$ConsentInfoUpdateTask.onPostExecute (ConsentInformation.java:277)
  at com.google.ads.consent.ConsentInformation$ConsentInfoUpdateTask.onPostExecute (ConsentInformation.java:188)
  at android.os.AsyncTask.finish (AsyncTask.java:632)
  at android.os.AsyncTask.access$600 (AsyncTask.java:177)
  at android.os.AsyncTask$InternalHandler.handleMessage (AsyncTask.java:645)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:145)
  at android.app.ActivityThread.main (ActivityThread.java:5942)
  at java.lang.reflect.Method.invoke (Method.java)
  at java.lang.reflect.Method.invoke (Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1400)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1195)
</code>```

Google also provides additional. error information:

I tried to run the application on different versions of Android, but I didn’t get an error

The application consists of one activity (MainActivity) and several fragments.

Method in SplashFragment where the error appears:

```<code>fun loadAds() {
        (activity as MainActivity).forceShowAd(callback = { // <- вот тут возникает исключение
            Log.i(TAG, "load ads");
            (activity as MainActivity).toMain()
        })
    }
</code>```

The called method in MainActivity:

```<code>fun forceShowAd(callback: () -> Unit) {
        Log.i(TAG, "forceShowAd")
        run {
            val mInterstitialAd = InterstitialAd(this)
            mInterstitialAd.apply {
                adUnitId = getString(R.string.admob_inter)
                adListener = object : AdListener() {
                    override fun onAdLoaded() {
                        callback()
                        show()
                    }

                    override fun onAdFailedToLoad(p0: Int) {
                        super.onAdFailedToLoad(p0)
                        var mStartAppAd = StartAppAd(applicationContext)
                        mStartAppAd.loadAd(object : AdEventListener {
                            override fun onReceiveAd(ad: Ad) {
                                mStartAppAd.showAd()
                                callback()
                            }
                            override fun onFailedToReceiveAd(ad: Ad) {
                                callback()
                            }
                        })
                    }
                }
                loadAd(getAdRequest())
            }
        }

    }
</code>```

This is how SplashFragment starts in MainActivity:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                    .replace(R.id.container, SplashFragment.newInstance())
                    .commit()
        }
    }
</code>```

Based on the life cycle of the application, while the fragment is running, activity should also work. But at the same time, as I understand it, at the time the exception was thrown activity == null

What could cause the exception problem? This problem occurs already on 6% of devices

答:
In some cases activity may be null, for example when user quits it. Without much changes in your code you can handle it using ? operator:

```<code>fun loadAds() {
    (activity as? MainActivity)?.forceShowAd(callback = {
        Log.i(TAG, "load ads")
        (activity as? MainActivity)?.toMain()
    })
}
</code>```

Also I would suggest to get rid of AsyncTask (it may cause memory leaks and other errors like in your case) and use Kotlin coroutines.

Body:
In the Google Play console, I look at the error report and see the following:

kotlin.TypeCastException:
  at com.app.android.ui.SplashFragment.loadAds (SplashFragment.java:111)
  at com.app.android.ui.SplashFragment$requestConsentInfoUpdate$1.onConsentInfoUpdated (SplashFragment.java:68)
  at com.google.ads.consent.ConsentInformation$ConsentInfoUpdateTask.onPostExecute (ConsentInformation.java:277)
  at com.google.ads.consent.ConsentInformation$ConsentInfoUpdateTask.onPostExecute (ConsentInformation.java:188)
  at android.os.AsyncTask.finish (AsyncTask.java:632)
  at android.os.AsyncTask.access$600 (AsyncTask.java:177)
  at android.os.AsyncTask$InternalHandler.handleMessage (AsyncTask.java:645)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:145)
  at android.app.ActivityThread.main (ActivityThread.java:5942)
  at java.lang.reflect.Method.invoke (Method.java)
  at java.lang.reflect.Method.invoke (Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1400)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1195)

Google also provides additional. error information:

I tried to run the application on different versions of Android, but I didn’t get an error

The application consists of one activity (MainActivity) and several fragments.

Method in SplashFragment where the error appears:

fun loadAds() {
        (activity as MainActivity).forceShowAd(callback = { // <- вот тут возникает исключение
            Log.i(TAG, "load ads");
            (activity as MainActivity).toMain()
        })
    }

The called method in MainActivity:

fun forceShowAd(callback: () -> Unit) {
        Log.i(TAG, "forceShowAd")
        run {
            val mInterstitialAd = InterstitialAd(this)
            mInterstitialAd.apply {
                adUnitId = getString(R.string.admob_inter)
                adListener = object : AdListener() {
                    override fun onAdLoaded() {
                        callback()
                        show()
                    }

                    override fun onAdFailedToLoad(p0: Int) {
                        super.onAdFailedToLoad(p0)
                        var mStartAppAd = StartAppAd(applicationContext)
                        mStartAppAd.loadAd(object : AdEventListener {
                            override fun onReceiveAd(ad: Ad) {
                                mStartAppAd.showAd()
                                callback()
                            }
                            override fun onFailedToReceiveAd(ad: Ad) {
                                callback()
                            }
                        })
                    }
                }
                loadAd(getAdRequest())
            }
        }

    }

This is how SplashFragment starts in MainActivity:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                    .replace(R.id.container, SplashFragment.newInstance())
                    .commit()
        }
    }

Based on the life cycle of the application, while the fragment is running, activity should also work. But at the same time, as I understand it, at the time the exception was thrown activity == null

What could cause the exception problem? This problem occurs already on 6% of devices

Body:
In some cases activity may be null, for example when user quits it. Without much changes in your code you can handle it using ? operator:

fun loadAds() {
    (activity as? MainActivity)?.forceShowAd(callback = {
        Log.i(TAG, "load ads")
        (activity as? MainActivity)?.toMain()
    })
}

Also I would suggest to get rid of AsyncTask (it may cause memory leaks and other errors like in your case) and use Kotlin coroutines.