问:
Excel VBA to look for the last non-blank cell in a column and convert it to a value
I have a column thats rows are currently filled with this formula:
    =IF(VLOOKUP(H3,B:D,3,0)="NOT_FOUND","",VLOOKUP(H3,B:D,3,0))

That fills rows one by one with the value that it finds. I am hoping that there is a macro that will search the column (I) for the single last non-blank cell and convert the formula answer into a value so I can eventually sum all of the values. I assume it is not a very difficult macro, but I have no experience working with VBA so any help would be appreciated!

Here is a pic of part of the table I am trying to make. Where the 13.8 is I would like for that to be converted to just a value since it is the last non-blank cell in the column. Please let me know if this makes sense or if more info is needed. Thank you!

答:
nofriendsnojo, if overwriting the formula in a cell (in this case VLOOKUP) is all you need, then please see my code below:

```<code>Sub paste_values()
Dim lastRow As Long
Dim cel As Range

'get last non-blank cell in column I
lastRow = Cells(Rows.Count, "I").End(xlUp).Row

'loop that overwrites cell contents with simple values
For Each cel In Range("I1:I" & lastRow)
    cel.Copy
    cel.PasteSpecial xlPasteValues
Next cel

Application.CutCopyMode = False

End Sub
</code>```

This is the basic code, it copies values of the cell and then pastes them to the same cell as values. This ultimately gets rid of any formula and converts the result of the formula into a simple value. It is quite common practice.

Of course, you can then add some references like ThisWorkbook. or ActiveSheet. or whatever scope you need.

I hope this solves your issue or atleast directs you in the right way.

Body:
nofriendsnojo, if overwriting the formula in a cell (in this case VLOOKUP) is all you need, then please see my code below:

Sub paste_values()
Dim lastRow As Long
Dim cel As Range

'get last non-blank cell in column I
lastRow = Cells(Rows.Count, "I").End(xlUp).Row

'loop that overwrites cell contents with simple values
For Each cel In Range("I1:I" & lastRow)
    cel.Copy
    cel.PasteSpecial xlPasteValues
Next cel

Application.CutCopyMode = False

End Sub

This is the basic code, it copies values of the cell and then pastes them to the same cell as values. This ultimately gets rid of any formula and converts the result of the formula into a simple value. It is quite common practice.

Of course, you can then add some references like ThisWorkbook. or ActiveSheet. or whatever scope you need.

I hope this solves your issue or atleast directs you in the right way.


来源: stackexchange

问:
Java write(str.getBytes()) vs writeBytes(str)
When using DataOutputStream to push Strings, I normally do the following:

```<code>DataOutputStream dout;
String str;
dout.write(str.getBytes());
</code>```

I just came across the writeBytes() method of DataOutputStream, and my question is whether the above is equivalent to:

```<code>dout.writeBytes(str);
</code>```

If not, what is difference and when should it be used?

答:
No, it is not equivalent.

The Javadocs for writeBytes say

Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits.

So this will not work well except for ASCII Strings.

You should be doing

```<code>dout.write(str.getBytes(characterSet));
// remember to specify the character set, otherwise it become
// platform-dependent and the result non-portable
</code>```

or

```<code>dout.writeChars(str);
</code>```

or

```<code>dout.writeUTF(str);
</code>```

Note that only the last method also writes the length of the String, so for the others, you probably need to know exactly what you are doing if you intend to later read it back.

The bigger question is why you need to use such a low-level protocol as DataOutputStream directly.

ContentLicense: CC BY-SA 4.0

Body:
When using DataOutputStream to push Strings, I normally do the following:

DataOutputStream dout;
String str;
dout.write(str.getBytes());

I just came across the writeBytes() method of DataOutputStream, and my question is whether the above is equivalent to:

dout.writeBytes(str);

If not, what is difference and when should it be used?

Body:
No, it is not equivalent.

The Javadocs for writeBytes say

Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits.

So this will not work well except for ASCII Strings.

You should be doing

dout.write(str.getBytes(characterSet));
// remember to specify the character set, otherwise it become
// platform-dependent and the result non-portable

or

dout.writeChars(str);

or

dout.writeUTF(str);

Note that only the last method also writes the length of the String, so for the others, you probably need to know exactly what you are doing if you intend to later read it back.

The bigger question is why you need to use such a low-level protocol as DataOutputStream directly.


问:
Why is lazy loading nested relation for each item in collection end up loading same values as last item's relation?
When I lazy load a relation for every item in the collection based on some condition, all items end up having the same relation loaded.
That loaded relation for all items is the last item's relation.

I tried setting custom attribute like

```<code>$single->owner->parent->filenames = Model::where('id', $id);
</code>```

but it doesn't work either. Here is my code

```<code>$index->transform(function($single) use (&$i){

            if($single->content_type === 'type1') {

                $single->owner->parent->load('fileNames');

            } else if($single->content_type === 'type2') {

                //     $single->owner->parent->file_names = Model::where('id', $single->owner->id);

                $single->owner->parent->load(['fileNames' => function($q) use ($single) {
                    $q->where('file_names.id', $single->owner->id);
                }]);

            }

            return $single;
        });
</code>```

In case of 'type2', I want $single->owner->parent->file_names to be having one entry with an id that is given in where clause

But What I get is all items in the collection ends up having the same value of  owner->parent->file_names attribute as the collection's last item's owner->parent->file_names attribute.

答:
Actually I was eager loading 'parent' and it seems eloquent uses same relation object for all items in collection if relation is eager loaded before. Kind of what I understood or guessed.

I solved it by manually setting relation attribute and cloning the 'parent' object for each item in collection. Not very elegant but works for me now.

Please let me know if you have better solution using laravel or eloquent lazy eager loading methods

```<code>$parentIds = $index->whereIn('content_type', ['type1', 'type2'])->load('owner')->pluck('owner.parent_id')->unique()->toArray();

$parents = collect([]);

foreach($parentIds as $singleParentId) {
    $parent = Parent::where('id',$singleParentId)->with('tags', 'category', 'titles')->withCount('allComments')->get()[0];
    $parents->put($singleParentId, $parent);
}

$index->transform(function($single) use ($parents) {
    if($single->content_type === 'type1' || $single->content_type === 'type2') {

        $single->owner->setAttribute('parent', clone $parents->get($single->owner->parent_id));

    }

    return $single;
});

$index->transform(function($single) {

    if($single->content_type === 'type1') {

        $fileNames = FileNames::where('parent_id', $single->owner->parent->id)->orderByRaw('lower(file_name) ASC')->limit(8)->get();

        $single->owner->parent->setAttribute('file_names', $fileNames);

    } else if($single->content_type === 'type2') {

        $fileNames = FileNames::where('parent_id', $single->owner->parent->id)->where('id', $single->owner->id)->get();

        $single->owner->parent->setAttribute('file_names', $fileNames);

    }

    return $single;
});
</code>```

Body:
When I lazy load a relation for every item in the collection based on some condition, all items end up having the same relation loaded.
That loaded relation for all items is the last item's relation.

I tried setting custom attribute like

$single->owner->parent->filenames = Model::where('id', $id);

but it doesn't work either. Here is my code

$index->transform(function($single) use (&$i){

            if($single->content_type === 'type1') {

                $single->owner->parent->load('fileNames');

            } else if($single->content_type === 'type2') {

                //     $single->owner->parent->file_names = Model::where('id', $single->owner->id);

                $single->owner->parent->load(['fileNames' => function($q) use ($single) {
                    $q->where('file_names.id', $single->owner->id);
                }]);

            }

            return $single;
        });

In case of 'type2', I want $single->owner->parent->file_names to be having one entry with an id that is given in where clause

But What I get is all items in the collection ends up having the same value of  owner->parent->file_names attribute as the collection's last item's owner->parent->file_names attribute.

Body:
Actually I was eager loading 'parent' and it seems eloquent uses same relation object for all items in collection if relation is eager loaded before. Kind of what I understood or guessed.

I solved it by manually setting relation attribute and cloning the 'parent' object for each item in collection. Not very elegant but works for me now.

Please let me know if you have better solution using laravel or eloquent lazy eager loading methods

$parentIds = $index->whereIn('content_type', ['type1', 'type2'])->load('owner')->pluck('owner.parent_id')->unique()->toArray();

$parents = collect([]);

foreach($parentIds as $singleParentId) {
    $parent = Parent::where('id',$singleParentId)->with('tags', 'category', 'titles')->withCount('allComments')->get()[0];
    $parents->put($singleParentId, $parent);
}

$index->transform(function($single) use ($parents) {
    if($single->content_type === 'type1' || $single->content_type === 'type2') {

        $single->owner->setAttribute('parent', clone $parents->get($single->owner->parent_id));

    }

    return $single;
});

$index->transform(function($single) {

    if($single->content_type === 'type1') {

        $fileNames = FileNames::where('parent_id', $single->owner->parent->id)->orderByRaw('lower(file_name) ASC')->limit(8)->get();

        $single->owner->parent->setAttribute('file_names', $fileNames);

    } else if($single->content_type === 'type2') {

        $fileNames = FileNames::where('parent_id', $single->owner->parent->id)->where('id', $single->owner->id)->get();

        $single->owner->parent->setAttribute('file_names', $fileNames);

    }

    return $single;
});


问:
iOS like spinner
I need to implement iOS like spinner in Android. I tried extending ListView but was not successful.

The spinner must look like this:

How would I do that?

答:
Android Provides inbuild widget Number Picker for this.

NumberPicker Example

activity_main.xml

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#ffffff"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:text="Select a Language..."
        />
    <NumberPicker
        android:id="@+id/np"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
</code>```

MainActivity.java

```<code>import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
import android.widget.NumberPicker;

public class MainActivity extends Activity {

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

        //Get the widgets reference from XML layout
        final TextView tv = (TextView) findViewById(R.id.tv);
        NumberPicker np = (NumberPicker) findViewById(R.id.np);

        //Set TextView text color
        tv.setTextColor(Color.parseColor("#FF2C834F"));

        //Initializing a new string array with elements
        final String[] values= {"English","Hindi", "Suomi"};

        //Populate NumberPicker values from String array values
        //Set the minimum value of NumberPicker
        np.setMinValue(0); //from array first value
        //Specify the maximum value/number of NumberPicker
        np.setMaxValue(values.length-1); //to array last value

        //Specify the NumberPicker data source as array elements
        np.setDisplayedValues(values);

        //Gets whether the selector wheel wraps when reaching the min/max value.
        np.setWrapSelectorWheel(true);

        //Set a value change listener for NumberPicker
        np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal){
                //Display the newly selected value from picker
                tv.setText("Selected value : " + values[newVal]);
            }
        });
    }
}
</code>```

Title: iOS like spinner

Body:
Android Provides inbuild widget Number Picker for this.

NumberPicker Example

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#ffffff"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:text="Select a Language..."
        />
    <NumberPicker
        android:id="@+id/np"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        />
</RelativeLayout>

MainActivity.java

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
import android.widget.NumberPicker;

public class MainActivity extends Activity {

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

        //Get the widgets reference from XML layout
        final TextView tv = (TextView) findViewById(R.id.tv);
        NumberPicker np = (NumberPicker) findViewById(R.id.np);

        //Set TextView text color
        tv.setTextColor(Color.parseColor("#FF2C834F"));

        //Initializing a new string array with elements
        final String[] values= {"English","Hindi", "Suomi"};

        //Populate NumberPicker values from String array values
        //Set the minimum value of NumberPicker
        np.setMinValue(0); //from array first value
        //Specify the maximum value/number of NumberPicker
        np.setMaxValue(values.length-1); //to array last value

        //Specify the NumberPicker data source as array elements
        np.setDisplayedValues(values);

        //Gets whether the selector wheel wraps when reaching the min/max value.
        np.setWrapSelectorWheel(true);

        //Set a value change listener for NumberPicker
        np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal){
                //Display the newly selected value from picker
                tv.setText("Selected value : " + values[newVal]);
            }
        });
    }
}


问:
How to add values together from a database in windows form application
I'm trying to add all of a students course values together to get the average. The values are saved into a database but when I try add the values together and insert them into a text box it inserts both values into the text box instead of adding the values together.</p>

```<code>            string output = "";
            output += (dr["Course 1"].ToString());
            output += (dr["Course 2"].ToString());
            txtbxaverage.Text = output;

        }
</code>```

答:
The operator "+" with strings is for concatenation, not addition. To keep it simple: "3" + "4" != "7", "3" + "4" = "34".

Now, if you want to calculate the sum of a series of string, what you can do is declare a variable started at 0, and add every string converted to int to that variable. Something like this:

```<code>int result = 0;
result += Convert.ToInt32(dr["Course 1"].ToString());
result += Convert.ToInt32(dr["Course 2"].ToString());
//And so on
</code>```

Also, if dr is an array, instead of having a single line for each value in the array, you can iterate them all with a for or foreach loop:

```<code>for (int i = 0; i < dr.length; i++)
{
    result += Convert.ToInt32(dr[i].ToString());
}
</code>```

And if dr is an array of integer or some other numeric type, you don't need to use ToString function. Do this instead:

```<code>result += dr[i];
</code>```

Body:
I'm trying to add all of a students course values together to get the average. The values are saved into a database but when I try add the values together and insert them into a text box it inserts both values into the text box instead of adding the values together.

            string output = "";
            output += (dr["Course 1"].ToString());
            output += (dr["Course 2"].ToString());
            txtbxaverage.Text = output;

        }

Body:
The operator "+" with strings is for concatenation, not addition. To keep it simple: "3" + "4" != "7", "3" + "4" = "34".

Now, if you want to calculate the sum of a series of string, what you can do is declare a variable started at 0, and add every string converted to int to that variable. Something like this:

int result = 0;
result += Convert.ToInt32(dr["Course 1"].ToString());
result += Convert.ToInt32(dr["Course 2"].ToString());
//And so on

Also, if dr is an array, instead of having a single line for each value in the array, you can iterate them all with a for or foreach loop:

for (int i = 0; i < dr.length; i++)
{
    result += Convert.ToInt32(dr[i].ToString());
}

And if dr is an array of integer or some other numeric type, you don't need to use ToString function. Do this instead:

result += dr[i];


问:
Cannot resolves symbol X, when defining multiple implicit vals
I am testing out some code shown below that basically defines multiple implicit vals taking a string as input and converting it to corresponding types.

The problem I have is that the conversions like toLong, toDouble and toInt become unresolved for some reason.

```<code>class Parse[T](val f: String => T) extends (String => T) {
  def apply(s: String): T = f(s)
}

object Parse {
  def apply[T](f: String => T) = new Parse[T](f)

  implicit val parseLong: Parse[Long] = Parse[Long](s => s.toLong)
  implicit val parseDouble: Parse[Double] = Parse[Double](s => s.toDouble)
  implicit val parseInt: Parse[Int] = Parse[Int](s => s.toInt)
}
</code>```

What is wrong with this code?

答:
The thing is that, since Parse extends String => T, implicits parseLong, parseDouble, parseInt define not only instances of Parse but also implicit conversions String => Long, String => Double, String => Int. And since .toLong, .toDouble, .toInt are extension methods, this creates ambiguities.

You can either remove extends (String => T) or resolve extension methods manually:

```<code>object Parse {
  def apply[T](f: String => T) = new Parse[T](f)

  implicit val parseLong: Parse[Long] = Parse[Long](s => new StringOps(s).toLong)
  implicit val parseDouble: Parse[Double] = Parse[Double](s => new StringOps(s).toDouble)
  implicit val parseInt: Parse[Int] = Parse[Int](s => new StringOps(s).toInt)
}
</code>```

Body:
I am testing out some code shown below that basically defines multiple implicit vals taking a string as input and converting it to corresponding types.

The problem I have is that the conversions like toLong, toDouble and toInt become unresolved for some reason.

class Parse[T](val f: String => T) extends (String => T) {
  def apply(s: String): T = f(s)
}

object Parse {
  def apply[T](f: String => T) = new Parse[T](f)

  implicit val parseLong: Parse[Long] = Parse[Long](s => s.toLong)
  implicit val parseDouble: Parse[Double] = Parse[Double](s => s.toDouble)
  implicit val parseInt: Parse[Int] = Parse[Int](s => s.toInt)
}

What is wrong with this code?

Body:
The thing is that, since Parse extends String => T, implicits parseLong, parseDouble, parseInt define not only instances of Parse but also implicit conversions String => Long, String => Double, String => Int. And since .toLong, .toDouble, .toInt are extension methods, this creates ambiguities.

You can either remove extends (String => T) or resolve extension methods manually:

object Parse {
  def apply[T](f: String => T) = new Parse[T](f)

  implicit val parseLong: Parse[Long] = Parse[Long](s => new StringOps(s).toLong)
  implicit val parseDouble: Parse[Double] = Parse[Double](s => new StringOps(s).toDouble)
  implicit val parseInt: Parse[Int] = Parse[Int](s => new StringOps(s).toInt)
}


问:
Can I have MVC Application Controller classes for AJAX API calls in a APS.NET Core Web Application project?
I created a new .NET Core application project targeting 2.1  By default it uses page routing, so new cshtml files I create follow standard file page routing.

Next I wanted to test making ajax calls from the client to my server. I attempted to add MCV application Controller called TestController and added the following to it:

```<code>public class TestController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost("Test/RunTest")]
        public ActionResult<string> RunTest()
        {
            return "Got it!";
        }
    }
</code>```

Here is my startup.cs file:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc();
        }

</code>```

When I attempt to make a Post via Postman to https://localhost:44313/Test/RunTest , I get a 404 page not found error.
I think it because my razor project is not routing requests to the controllers in my project, but I am not sure.

What should I do to make ajax request to MVC controllers ?

答:
The attribute route template on your Runtest action doesn't have a prefix specified, so you shouldn't prefix the URL with "/Test/". The AJAX post should go to https://localhost:44313/RunTest.

If you want the controller name as part of the route, you can include it in the template:

```<code>[HttpPost("Test/RunTest")]
</code>```

Or you can specify a prefix for all actions in the controller:

```<code>[RoutePrefix("Test")]
public class TestController : Controller
</code>```

Body:
I created a new .NET Core application project targeting 2.1  By default it uses page routing, so new cshtml files I create follow standard file page routing.

Next I wanted to test making ajax calls from the client to my server. I attempted to add MCV application Controller called TestController and added the following to it:

public class TestController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost("Test/RunTest")]
        public ActionResult<string> RunTest()
        {
            return "Got it!";
        }
    }

Here is my startup.cs file:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc();
        }

When I attempt to make a Post via Postman to https://localhost:44313/Test/RunTest , I get a 404 page not found error.
I think it because my razor project is not routing requests to the controllers in my project, but I am not sure.

What should I do to make ajax request to MVC controllers ?

Body:
The attribute route template on your Runtest action doesn't have a prefix specified, so you shouldn't prefix the URL with "/Test/". The AJAX post should go to https://localhost:44313/RunTest.

If you want the controller name as part of the route, you can include it in the template:

[HttpPost("Test/RunTest")]

Or you can specify a prefix for all actions in the controller:

[RoutePrefix("Test")]
public class TestController : Controller


问:
RPM + error during build RPM
please advice why I get the error "Bad file: /root/rpmbuild/SOURCES/test.sh"

I need to create rpm file ,

I only have the spec file under SPECS

and the test.sh script under SOURCES

what’s wrong here?

```<code> [root@linux /usr/src/redhat]# ls

 BUILD  RPMS  SOURCES  SPECS  SRPMS
</code>```

the spec file:

```<code>Summary: An example tool. To show a simple rpm build of the tool.
Name: test.sh
Version: 6.2
Release: 2
Source:/root/test.sh
Group: Development/Debuggers
BuildRoot:/var/tmp/test.sh
%description

Bad file: /root/rpmbuild/SOURCES/test.sh: No such file or directory RPM build     errors:    Bad file: /root/rpmbuild/SOURCES/test.sh: No such file or directory
</code>```

答: The path to sources is never used; all source files must be in %{_sourcedir}, with the same name as the last component of the path.

ContentLicense: CC BY-SA 3.0

Title: RPM + error during build RPM

Body:
please advice why I get the error "Bad file: /root/rpmbuild/SOURCES/test.sh"

I need to create rpm file ,

I only have the spec file under SPECS

and the test.sh script under SOURCES

what’s wrong here?

 [root@linux /usr/src/redhat]# ls

 BUILD  RPMS  SOURCES  SPECS  SRPMS

the spec file:

Summary: An example tool. To show a simple rpm build of the tool.
Name: test.sh
Version: 6.2
Release: 2
Source:/root/test.sh
Group: Development/Debuggers
BuildRoot:/var/tmp/test.sh
%description

Bad file: /root/rpmbuild/SOURCES/test.sh: No such file or directory RPM build     errors:    Bad file: /root/rpmbuild/SOURCES/test.sh: No such file or directory


问:
How to get next 10 days from current date in swift
I have dateformat string like this "2015-03-09".How do i get next 10 days date from current date?any help will be appreciated.thanks in advance</p>

答:
Here is a swift 4/5 version of the answer by @MidhunMP</p>

```<code>var dateStr          = "2015-03-09"
var formatter        = DateFormatter()
formatter.dateFormat = "YYYY-MM-dd"

var calendar = Calendar(identifier: .gregorian)
var dateComponent = DateComponents()

if let currDate = formatter.date(from: dateStr) {
    for i in 1...10 {
        let newDate = calendar.date(byAdding: .day, value: i, to: currDate)
        print(newDate)
    }
}
</code>```

Body:
Here is a swift 4/5 version of the answer by @MidhunMP

var dateStr          = "2015-03-09"
var formatter        = DateFormatter()
formatter.dateFormat = "YYYY-MM-dd"

var calendar = Calendar(identifier: .gregorian)
var dateComponent = DateComponents()

if let currDate = formatter.date(from: dateStr) {
    for i in 1...10 {
        let newDate = calendar.date(byAdding: .day, value: i, to: currDate)
        print(newDate)
    }
}


问:
Angular: ERROR Error: No component factory found
I have created two components in the same ts file as below. Was referring the example code from https://material.angular.io/components/dialog/examples and it uses the same approach.

```<code>import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogModule, MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

@Component({
  selector: 'app-srapi',
  templateUrl: './srapi.component.html',
  styleUrls: ['./srapi.component.scss']
})
export class SrapiComponent {

  constructor(private dialog: MatDialog) { }

  onCreate(): void {
    const dialogRef = this.dialog.open(SrapiTFLFormComponent);
  }
}

@Component({
  selector: 'app-srapi-tfl-form',
  templateUrl: './srapi-tfl-form.html'
})
export class SrapiTFLFormComponent{

  constructor(public dialogRef: MatDialogRef<SrapiTFLFormComponent>) {}
}
</code>```

Also declared and imported both of these in app.module.ts

```<code>import { SrapiComponent, SrapiTFLFormComponent } from './srapi/srapi.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    EdcUserFormComponent,
    SidebarComponent,
    EdcMasterDataComponent,
    SrapiComponent,
    SrapiTFLFormComponent
  ],
  imports: [
    BrowserModule,
.
.
</code>```

but it gives an error when it opens the dialog.

ERROR Error: No component factory found for SrapiTFLFormComponent. Did you add it to @NgModule.entryComponents?
          at noComponentFactoryError (core.js:15705)

答:
As the error says you need to add the component also inside of entryComponents.

```<code>@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    EdcUserFormComponent,
    SidebarComponent,
    EdcMasterDataComponent,
    SrapiComponent,
    SrapiTFLFormComponent
  ],
  imports: [
    BrowserModule,
    ...
  ],
 entryComponents: [SrapiTFLFormComponent]
 ...
</code>```

To clarify what entryComponents are you can take a look here

An entry component is any component that Angular loads imperatively,
  (which means you’re not referencing it in the template), by type. You
  specify an entry component by bootstrapping it in an NgModule, or
  including it in a routing definition.

Body:
I have created two components in the same ts file as below. Was referring the example code from https://material.angular.io/components/dialog/examples and it uses the same approach.

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogModule, MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

@Component({
  selector: 'app-srapi',
  templateUrl: './srapi.component.html',
  styleUrls: ['./srapi.component.scss']
})
export class SrapiComponent {

  constructor(private dialog: MatDialog) { }

  onCreate(): void {
    const dialogRef = this.dialog.open(SrapiTFLFormComponent);
  }
}

@Component({
  selector: 'app-srapi-tfl-form',
  templateUrl: './srapi-tfl-form.html'
})
export class SrapiTFLFormComponent{

  constructor(public dialogRef: MatDialogRef<SrapiTFLFormComponent>) {}
}

Also declared and imported both of these in app.module.ts

import { SrapiComponent, SrapiTFLFormComponent } from './srapi/srapi.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    EdcUserFormComponent,
    SidebarComponent,
    EdcMasterDataComponent,
    SrapiComponent,
    SrapiTFLFormComponent
  ],
  imports: [
    BrowserModule,
.
.

but it gives an error when it opens the dialog.

ERROR Error: No component factory found for SrapiTFLFormComponent. Did you add it to @NgModule.entryComponents?
          at noComponentFactoryError (core.js:15705)

Body:
As the error says you need to add the component also inside of entryComponents.

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    EdcUserFormComponent,
    SidebarComponent,
    EdcMasterDataComponent,
    SrapiComponent,
    SrapiTFLFormComponent
  ],
  imports: [
    BrowserModule,
    ...
  ],
 entryComponents: [SrapiTFLFormComponent]
 ...

To clarify what entryComponents are you can take a look here

An entry component is any component that Angular loads imperatively,
  (which means you’re not referencing it in the template), by type. You
  specify an entry component by bootstrapping it in an NgModule, or
  including it in a routing definition.


问:
Will ClickOnce be ported to .NET Core 3 or .NET 5 as well as WinForms?
Now that Winforms is being ported to .NET Core 3, what technology will be used for deploying those apps?  Will ClickOnce also be ported?

Many of the properties used by ClickOnce are currently stored in the .csproj file, but those project files change significantly between .NET Framework and .NET Core, so presumably this would require changes to Microsoft's ClickOnce code to make it work?

Has there been any official word from Microsoft on this, I can't find anything in the documentation?

答:
Current status

It appears that ClickOnce won't be ported to .NET core 3, but will be ported to .NET 5 as per Matthew Steeples' answer below.

Original answer relating to .NET Core 3

Microsoft's Scott Hunter addressed this in the comments of the .NET Core is the Future of .NET blog post.  He was asked:

What about ClickOnce? Will that be a supported distribution system for
.NET 5 desktop applications?

To which he gave the response:

We are going to recommend MSIX for installation and support for MSIX
will be added for Windows 7 so it should work on all the platforms you
that .NET Core runs on.

More details MSIX can be found in Microsoft's MSIX documentation and in it's GitHub repo.

Other installation frameworks exist too, such as Squirrel.


问:
Argument of type 'number' is not assignable to parameter of type 'number & string'
I want to use Array.prototype.includes method in my ts file like.

```<code>const id = this.selectedItem.id;
ids.includes(id);
</code>```

Where ids is an array of numbers.
I always get a compilation error:
Argument of type 'number' is not assignable to parameter of type 'number & string'

When explicitly transform id to be a number Number(id), then I also see Type number is not assignable to type string.
And when I explicitly transform id to be a string id.toString() then I can see Type string is not assignable to type number.

It is overwhelmig. How includes method can be used in TypeScript? How to use it in my example?

[Edit] Extended example:

```<code>    interface State extends EntityState<IItem> {}

    this.stateSubscription = this.store.select((state: State) => state.items).subscribe(
        val => {
            const selectedId = this.selectedItem ? this.selectedItem.id : null;
            val.ids.includes(selectedId);
    }));
</code>```

val.ids.includes(selectedId as any) also doesn't work.

答:
You have declared ids as number[] & string[]

This means that the parameters you provide to the methods should be of type number[] & string[].

Try declaring it as number[] | string[], which is one of either, instead of both.

Body:
I want to use Array.prototype.includes method in my ts file like.

const id = this.selectedItem.id;
ids.includes(id);

Where ids is an array of numbers.
I always get a compilation error:
Argument of type 'number' is not assignable to parameter of type 'number & string'

When explicitly transform id to be a number Number(id), then I also see Type number is not assignable to type string.
And when I explicitly transform id to be a string id.toString() then I can see Type string is not assignable to type number.

It is overwhelmig. How includes method can be used in TypeScript? How to use it in my example?

[Edit] Extended example:

    interface State extends EntityState<IItem> {}

    this.stateSubscription = this.store.select((state: State) => state.items).subscribe(
        val => {
            const selectedId = this.selectedItem ? this.selectedItem.id : null;
            val.ids.includes(selectedId);
    }));

val.ids.includes(selectedId as any) also doesn't work.


问:
Why does failed source control in CruiseControl.net not fail the build?
I'm using cruisecontrol.net for integration builds along with external source control. The source control (GETMODS) script fails, this is fine and I know why, but the build stays green for some reason when it's expected to fail. CruiseControl shows the exception on the output window below, so why doesn't the build fail?</p>

```<code>ThoughtWorks.CruiseControl.Core.CruiseControlException: Source control operation failed:

at ThoughtWorks.CruiseControl.Core.Sourcecontrol.ProcessSourceControl.Execute
(ProcessInfo processInfo)
at ThoughtWorks.CruiseControl.Core.Sourcecontrol.ProcessSourceControl.GetModifications(ProcessInfo info, DateTime from, DateTime to)
at ThoughtWorks.CruiseControl.Core.Sourcecontrol.ExternalSourceControl.GetMod  ifications(IIntegrationResult from, IIntegrationResult to)
at ThoughtWorks.CruiseControl.Core.Sourcecontrol.QuietPeriod.GetModifications(ISourceControl sourceControl, IIntegrationResult lastBuild, IIntegrationResultthisBuild)
at ThoughtWorks.CruiseControl.Core.IntegrationRunner.GetModifications(IIntegrationResult from, IIntegrationResult to)
at ThoughtWorks.CruiseControl.Core.IntegrationRunner.Integrate(IntegrationRequest request)
at ThoughtWorks.CruiseControl.Core.Project.Integrate(IntegrationRequest request)
at ThoughtWorks.CruiseControl.Core.ProjectIntegrator.Integrate()
at ThoughtWorks.CruiseControl.Core.ProjectIntegrator.Run()
</code>```

答: I believe this is a recent change to ccnet. We are running two versions on separate machines. Version 1.4 breaks the build if it can't get to our svn repository, but version 1.5 will not break the build.  I haven't looked into it yet, but there may be a switch to force 1.5 to break on failure to retrieve code.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm using cruisecontrol.net for integration builds along with external source control. The source control (GETMODS) script fails, this is fine and I know why, but the build stays green for some reason when it's expected to fail. CruiseControl shows the exception on the output window below, so why doesn't the build fail?

ThoughtWorks.CruiseControl.Core.CruiseControlException: Source control operation failed:

at ThoughtWorks.CruiseControl.Core.Sourcecontrol.ProcessSourceControl.Execute
(ProcessInfo processInfo)
at ThoughtWorks.CruiseControl.Core.Sourcecontrol.ProcessSourceControl.GetModifications(ProcessInfo info, DateTime from, DateTime to)
at ThoughtWorks.CruiseControl.Core.Sourcecontrol.ExternalSourceControl.GetMod  ifications(IIntegrationResult from, IIntegrationResult to)
at ThoughtWorks.CruiseControl.Core.Sourcecontrol.QuietPeriod.GetModifications(ISourceControl sourceControl, IIntegrationResult lastBuild, IIntegrationResultthisBuild)
at ThoughtWorks.CruiseControl.Core.IntegrationRunner.GetModifications(IIntegrationResult from, IIntegrationResult to)
at ThoughtWorks.CruiseControl.Core.IntegrationRunner.Integrate(IntegrationRequest request)
at ThoughtWorks.CruiseControl.Core.Project.Integrate(IntegrationRequest request)
at ThoughtWorks.CruiseControl.Core.ProjectIntegrator.Integrate()
at ThoughtWorks.CruiseControl.Core.ProjectIntegrator.Run()


问:
Return statement in for loops within an function in python
I know that my return statement is in wrong place, but can't figure out how to fix it.

Here is my code:

```<code>def show_Number(limit):
   for number in range(limit):
       if number % 2 == 0:
           print(f"{number} even")

       else:
           number % 2 != 0
           print(f"{number} odd")
   return number

</code>```

I expect the output of this function to be:

```<code>0 even
1 odd
2 even
3 odd
4 even
</code>```

but the actual output is:

```<code>0 even
1 odd
2 even
3 odd
4 even
4
</code>```

答: In that case, the return is not necessary, because you already print the results. The last 4 is the return.</p>

Body:
I know that my return statement is in wrong place, but can't figure out how to fix it.

Here is my code:

def show_Number(limit):
   for number in range(limit):
       if number % 2 == 0:
           print(f"{number} even")

       else:
           number % 2 != 0
           print(f"{number} odd")
   return number

I expect the output of this function to be:

0 even
1 odd
2 even
3 odd
4 even

but the actual output is:

0 even
1 odd
2 even
3 odd
4 even
4


问:
Calculate Points from Letters in a Switch Case
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.

```<code>/*
 * To change this license header, choose License Headers in Project      Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package pointsproblem;

/**
 *
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

 public class PointsProblem {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
 public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    //create new object//
    PointsProblem task1 = new PointsProblem();

    File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + input);
        System.exit(0);
    }
    else {
        System.out.println("Successfully opened file: " + input + ".");
    }
    //read all the lines in the file//
   {
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);
            System.out.println("'" + input + "' is worth " + point + " points");

    int point = "";
    switch(point)  {

    case 'a': = "1":
    case 'e': = "1";
    case 'i': = "1";
    case 'l': = "1";
    case 'n': = "1";
    case 'o': = "1";
    case 'r': = "1";
    case 's': = "1";
    case 't': = "1";
    case 'u': = "1";
    case 'g': = "2";
    case 'g': = "2";
    case 'b': = "3";
    case 'm': = "3";
    case 'c': = "3";
    case 'p': = "3";
    case 'f': = "4";
    case 'h': = "4";
    case 'v': = "4";
    case 'w': = "4";
    case 'y': = "4";
    case 'k': = "5";
    case 'j': = "8";
    case 'x': = "8";
    case 'q': = "10";
    case 'z': = "10";

    return score  =  point + "";
        }//end switch

     }//end point calculation loop

    public int getScore() {
        return score;
    }
    //public boolean containsLetter(Character letter) {
        //return points.contains(letter);//

    }
</code>```

I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.

答:
Instead of assigning individually for each 'case' statement, you can also use the fall through feature of the switch block.

```<code>    int calcScore(String str)
    {
        int score = 0;
        for(int i=0; i<str.length(); i++)
        {
        switch(str.charAt(i))  {
            case 'a':
            case 'e':
            case 'i':
            case 'l':
            case 'n':
            case 'o':
            case 'r':
            case 's':
            case 't':
            case 'u': score += 1; break;
            case 'g': score += 2; break;
            case 'b':
            case 'm':
            case 'c':
            case 'p': score += 3; break;
            case 'f':
            case 'h':
            case 'v':
            case 'w':
            case 'y': score += 4; break;
            case 'k': score += 5; break;
            case 'j':
            case 'x': score += 8; break;
            case 'q':
            case 'z': score += 10; break;
            }
    }
        return score;
 }
</code>```

This function can be called for each word.

Body:
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.

/*
 * To change this license header, choose License Headers in Project      Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package pointsproblem;

/**
 *
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

 public class PointsProblem {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
 public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    //create new object//
    PointsProblem task1 = new PointsProblem();

    File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + input);
        System.exit(0);
    }
    else {
        System.out.println("Successfully opened file: " + input + ".");
    }
    //read all the lines in the file//
   {
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);
            System.out.println("'" + input + "' is worth " + point + " points");

    int point = "";
    switch(point)  {

    case 'a': = "1":
    case 'e': = "1";
    case 'i': = "1";
    case 'l': = "1";
    case 'n': = "1";
    case 'o': = "1";
    case 'r': = "1";
    case 's': = "1";
    case 't': = "1";
    case 'u': = "1";
    case 'g': = "2";
    case 'g': = "2";
    case 'b': = "3";
    case 'm': = "3";
    case 'c': = "3";
    case 'p': = "3";
    case 'f': = "4";
    case 'h': = "4";
    case 'v': = "4";
    case 'w': = "4";
    case 'y': = "4";
    case 'k': = "5";
    case 'j': = "8";
    case 'x': = "8";
    case 'q': = "10";
    case 'z': = "10";

    return score  =  point + "";
        }//end switch

     }//end point calculation loop

    public int getScore() {
        return score;
    }
    //public boolean containsLetter(Character letter) {
        //return points.contains(letter);//

    }

I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.

Body:
Instead of assigning individually for each 'case' statement, you can also use the fall through feature of the switch block.

    int calcScore(String str)
    {
        int score = 0;
        for(int i=0; i<str.length(); i++)
        {
        switch(str.charAt(i))  {
            case 'a':
            case 'e':
            case 'i':
            case 'l':
            case 'n':
            case 'o':
            case 'r':
            case 's':
            case 't':
            case 'u': score += 1; break;
            case 'g': score += 2; break;
            case 'b':
            case 'm':
            case 'c':
            case 'p': score += 3; break;
            case 'f':
            case 'h':
            case 'v':
            case 'w':
            case 'y': score += 4; break;
            case 'k': score += 5; break;
            case 'j':
            case 'x': score += 8; break;
            case 'q':
            case 'z': score += 10; break;
            }
    }
        return score;
 }

This function can be called for each word.


问:
When I search in vim and then press “esc” cursor returns to previous position
Something has seemingly happened to my vim install, and I'm not exactly sure what. I'm a long time vim user (although I don't use it as a main editor).

When I search:

```<code>/foo
</code>```

I want to edit the location that it found, so I press ESC (in preparation for getting into insert mode). vim now jumps BACK to where I started from in the file. E.g. if I was on line 0 of a 3000 line file, I search for a particular string, find it at line 1700, and want to edit it - ESC takes me back to line 0.

What's going on? Did I accidentally set some strange mode? Or did I forget a hotkey combination that I should know?

答:
you said

so I press ESC (in preparation for getting into insert mode).

you don't need to press ESC before you can get to insert mode, you need to press enter (known in vim as <CR> for carriage return).

so if you wanted to find foo and start inserting text, type

```<code>/foo<CR>i
</code>```

remember that <CR> is a single pressing of the enter button.

Body:
Something has seemingly happened to my vim install, and I'm not exactly sure what. I'm a long time vim user (although I don't use it as a main editor).

When I search:

/foo

I want to edit the location that it found, so I press ESC (in preparation for getting into insert mode). vim now jumps BACK to where I started from in the file. E.g. if I was on line 0 of a 3000 line file, I search for a particular string, find it at line 1700, and want to edit it - ESC takes me back to line 0.

What's going on? Did I accidentally set some strange mode? Or did I forget a hotkey combination that I should know?

Body:
you said

so I press ESC (in preparation for getting into insert mode).

you don't need to press ESC before you can get to insert mode, you need to press enter (known in vim as <CR> for carriage return).

so if you wanted to find foo and start inserting text, type

/foo<CR>i

remember that <CR> is a single pressing of the enter button.


问:
R:argument is of length zero
I'm getting the error argument is of length zero when I am passing my dataframe and its respective columns to a custom function.

I made a function that checks if the value in one column is equal to value in any other columns, it should return a value in a new column of the dataframe named data$group.

```<code>//Name of Data Frame is 'data'

bucket.function<-function(df2, a, b, c, d, e, f, g, h, i) {

 if(df2$a==df2$b)
        result<- "if"

 else if(df2$a==df2$c)
        result<-"df"

 else if(df2$a==df2$d)
        result<-"bus"

 else if(df2$a==df2$e)
        result<-"car"

    else if(df2$a==df2$f)
        result<-"train"

    else if(df2$a==df2$g)
        result<-"exp"

    else if(df2$a==df2$h)
        result<-"dh"

    else if(df2$a==df2$i)
        result<-"ih"

    else
        result<- "NA"

    return(result)
}

data$group <- bucket.function(data, "latest_txn_date", "if_last_txn_date", "df_last_txn_date", "b_last_txn_date", "car_last_txn_date", "train_last_txn_date", "exp_last_txn_date", "dh_last_txn_date", "ih_last_txn_date")
</code>```

I expect the output to be a column of values in data$group that contains values returned for each value of d$a, here data$latest_txn_date

答:
df2$a is not in your dataframe as you have no a column. You have to access it with df2[[a]] that evaluate the value of a/. It is the same principle for arguments a to i.
Moreover you compare two vectors in your if conditions. I assume you want a different result for each row. Please have a look at the function switch.

Title: R:argument is of length zero

Body:
I'm getting the error argument is of length zero when I am passing my dataframe and its respective columns to a custom function.

I made a function that checks if the value in one column is equal to value in any other columns, it should return a value in a new column of the dataframe named data$group.

//Name of Data Frame is 'data'

bucket.function<-function(df2, a, b, c, d, e, f, g, h, i) {

 if(df2$a==df2$b)
        result<- "if"

 else if(df2$a==df2$c)
        result<-"df"

 else if(df2$a==df2$d)
        result<-"bus"

 else if(df2$a==df2$e)
        result<-"car"

    else if(df2$a==df2$f)
        result<-"train"

    else if(df2$a==df2$g)
        result<-"exp"

    else if(df2$a==df2$h)
        result<-"dh"

    else if(df2$a==df2$i)
        result<-"ih"

    else
        result<- "NA"

    return(result)
}

data$group <- bucket.function(data, "latest_txn_date", "if_last_txn_date", "df_last_txn_date", "b_last_txn_date", "car_last_txn_date", "train_last_txn_date", "exp_last_txn_date", "dh_last_txn_date", "ih_last_txn_date")

I expect the output to be a column of values in data$group that contains values returned for each value of d$a, here data$latest_txn_date


问:
py2exe - generate single executable file
I thought I heard that py2exe was able to do this, but I never figured it out.  Has anyone successfully done this?  Can I see your setup.py file, and what command line options you used?

Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.

答: I'm told bbfreeze will create a single file .EXE, and is newer than py2exe.</p>

OwnerDisplayName: Greg

LastEditorDisplayName: Jerub

OwnerDisplayName: Matt


问:
ASP.Net Core 2.2: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information
I recently started with ASP.Net Core 2.2. I have a situation where I need to use legacy SAP Connector library within my application. After some reading I created my application to target full .Net Framework 4.6.1. I have a test class that references the SAP Connector library.

However, when I run my application, it breaks within Startup.cs right where it calls this line:

```<code>app.UseMvc();
</code>```

Checking the LoaderExceptions property, it shows the error:
Could not load file or assembly 'sapnco, Version=3.0.0.42, Culture=neutral, PublicKeyToken=50436dca5c7f7d23' or one of its dependencies. An attempt was made to load a program with an incorrect format.

My hunch is that although ASP.Net Core supports full .Net Framework, the referenced assembly has to go as far back to particular version of .Net Framework and no less. Although I can't find any concrete info on that.

Please help!

答:
For SAP Connector, I think you need to contact SAP Forum Support to confirm if the SAP Connector .NET Core version is available or will be available.

From the perspective of .Net Core, I am afraid there are no connectors and no plans to develop such connectors.

Body:
I recently started with ASP.Net Core 2.2. I have a situation where I need to use legacy SAP Connector library within my application. After some reading I created my application to target full .Net Framework 4.6.1. I have a test class that references the SAP Connector library.

However, when I run my application, it breaks within Startup.cs right where it calls this line:

app.UseMvc();

Checking the LoaderExceptions property, it shows the error:
Could not load file or assembly 'sapnco, Version=3.0.0.42, Culture=neutral, PublicKeyToken=50436dca5c7f7d23' or one of its dependencies. An attempt was made to load a program with an incorrect format.

My hunch is that although ASP.Net Core supports full .Net Framework, the referenced assembly has to go as far back to particular version of .Net Framework and no less. Although I can't find any concrete info on that.

Please help!


问:
Next greatest number
I'm trying to find the next greatest number from the user input.If the user gives 23 it shows the output as 32.If there is number greater number then it has to print the same given number.But if the user gives 03 it shows 3 but it has to show 30.Because it takes 03 as octal number.How can i change the code to show the correct output as 30?</p>

```<code>public class Main
{
 static void swap(char ar[], int i, int j)
 {
  char temp = ar[i];
  ar[i] = ar[j];
  ar[j] = temp;
 }
 public static void main(String[] args)
 {
   Scanner in = new Scanner(System.in);
   int num = in .nextInt();
   char[] chars = ("" + num).toCharArray();
   int i;
   int n = chars.length;
   for (i = n - 1; i > 0; i--)
   {
    if (chars[i] > chars[i - 1])
     break;
   }
   if (i == 0)
    System.out.println(num);
   else {
    int x = chars[i - 1], min = i;
   for (int j = i + 1; j<n; j++)
   {
    if (chars[j] > x && chars[j]<chars[min])
     min = j;
   }
   swap(chars, i - 1, min);
   Arrays.sort(chars, i, n);
   for (i = 0; i<n; i++)
     System.out.print(chars[i]);
  }
 }
}
</code>```

答:
```<code>package com.demo;

import java.util.Arrays;
import java.util.Scanner;

public class Demo {

    static void swap(char ar[], int i, int j)
    {
     char temp = ar[i];
     ar[i] = ar[j];
     ar[j] = temp;
    }
    public static void main(String[] args)
    {
      Scanner in = new Scanner(System.in);
      //int num = in .nextInt();
      char[] chars=null;
      String numStr=in.next();
      int num= Integer.valueOf(numStr);
      if(numStr.startsWith("0")) {
          chars= ("0" + num).toCharArray();
      }else {
          chars= ("" + num).toCharArray();
      }

      int i;
      int n = chars.length;
      for (i = n - 1; i > 0; i--)
      {
       if (chars[i] > chars[i - 1])
        break;
      }
      if (i == 0)
       System.out.println(num);
      else {
       int x = chars[i - 1], min = i;
      for (int j = i + 1; j<n; j++)
      {
       if (chars[j] > x && chars[j]<chars[min])
        min = j;
      }
      swap(chars, i - 1, min);
      Arrays.sort(chars, i, n);
      for (i = 0; i<n; i++)
        System.out.print(chars[i]);
     }
    }
}
</code>```

Title: Next greatest number

Body:
I'm trying to find the next greatest number from the user input.If the user gives 23 it shows the output as 32.If there is number greater number then it has to print the same given number.But if the user gives 03 it shows 3 but it has to show 30.Because it takes 03 as octal number.How can i change the code to show the correct output as 30?

public class Main
{
 static void swap(char ar[], int i, int j)
 {
  char temp = ar[i];
  ar[i] = ar[j];
  ar[j] = temp;
 }
 public static void main(String[] args)
 {
   Scanner in = new Scanner(System.in);
   int num = in .nextInt();
   char[] chars = ("" + num).toCharArray();
   int i;
   int n = chars.length;
   for (i = n - 1; i > 0; i--)
   {
    if (chars[i] > chars[i - 1])
     break;
   }
   if (i == 0)
    System.out.println(num);
   else {
    int x = chars[i - 1], min = i;
   for (int j = i + 1; j<n; j++)
   {
    if (chars[j] > x && chars[j]<chars[min])
     min = j;
   }
   swap(chars, i - 1, min);
   Arrays.sort(chars, i, n);
   for (i = 0; i<n; i++)
     System.out.print(chars[i]);
  }
 }
}


问:
using interface to define a new type
I am using an interface to define a new type. Is this a correct approach? I do as following:

```<code>export interface IQuestionnaire {
  DataProcessingID: string;
  Qestions : [{
        SecurityControl :  string,
        securityGoal: string[],
          }]
}
</code>```

Then, to instantiate from it I have to do this:

```<code>      IQuestions :  IQuestionnaire = {
    DataProcessingID: "",
     Qestions :[{
           SecurityControl :  "",
           securityGoal: [""]
               }]
  };
</code>```

which actually create an empty object which is not what I want; but without this, it raises an error saying, for example, "Cannot read property 'Questions' of undefined". Is my approach wrong to define a new type?

====EDIT====
Here is what I did according to your comments:

```<code>export interface IQuestionnaire {
  DataProcessingID: string;
  Qestions :  Array<Iquestion>
}
interface Iquestion{
        SecurityControl :  string,
        securityGoal: string[],
}
</code>```

and then I go:

```<code> IQuestions ={} as IQuestionnaire;
</code>```

Then I yet get this error: Can not read property 'push' of undefined . I don't want to initiate them where I define the interface, as it creates an empty object!

答:
I prefer to do it like this:

```<code>interface Foo {
    bar: number
    bas: string
}

let foo = {} as Foo;
foo.bar = 123;
foo.bas = "Hello World";
</code>```

You can read more about object initialization here or in this related stackoverflow question.

Combined with the other answers it could look like this:

```<code>export interface Question {
  securityControl: string,
  securityGoal: string[],
}

export interface Questionnaire {
  dataProcessingID: string;
  questions: Question[];
}

let questionaire = {} as Questionnaire;
questionaire.dataProcessingID = "12345";
questionaire.questions = [];

questionaire.questions.push({
    securityControl: "control"
    securityGoal: ["goal"]
});
</code>```

Title: using interface to define a new type

Body:
I am using an interface to define a new type. Is this a correct approach? I do as following:

export interface IQuestionnaire {
  DataProcessingID: string;
  Qestions : [{
        SecurityControl :  string,
        securityGoal: string[],
          }]
}

Then, to instantiate from it I have to do this:

      IQuestions :  IQuestionnaire = {
    DataProcessingID: "",
     Qestions :[{
           SecurityControl :  "",
           securityGoal: [""]
               }]
  };

which actually create an empty object which is not what I want; but without this, it raises an error saying, for example, "Cannot read property 'Questions' of undefined". Is my approach wrong to define a new type?

====EDIT====
Here is what I did according to your comments:

export interface IQuestionnaire {
  DataProcessingID: string;
  Qestions :  Array<Iquestion>
}
interface Iquestion{
        SecurityControl :  string,
        securityGoal: string[],
}

and then I go:

 IQuestions ={} as IQuestionnaire;

Then I yet get this error: Can not read property 'push' of undefined . I don't want to initiate them where I define the interface, as it creates an empty object!

Body:
I prefer to do it like this:

interface Foo {
    bar: number
    bas: string
}

let foo = {} as Foo;
foo.bar = 123;
foo.bas = "Hello World";

You can read more about object initialization here or in this related stackoverflow question.

Combined with the other answers it could look like this:

export interface Question {
  securityControl: string,
  securityGoal: string[],
}

export interface Questionnaire {
  dataProcessingID: string;
  questions: Question[];
}

let questionaire = {} as Questionnaire;
questionaire.dataProcessingID = "12345";
questionaire.questions = [];

questionaire.questions.push({
    securityControl: "control"
    securityGoal: ["goal"]
});


问:
How to use fancyimpute on PyCharm
I've installed fancyimpute on Anaconda with pip install fancyimpute through the Anaconda terminal but I use PyCharm with Anaconda as its interpreter.  I couldn't find a way to use fancyimpute in PyCharm.  I searched for it through Settings/Project Interpreter/Available Packages but no luck.

答:
use

```<code>python -m pip install fancyimpute
</code>```

this will take you pycharm default python interpreter and install the package in the python site package. you will be able to see this package in your project

Title: How to use fancyimpute on PyCharm

Body:
use

python -m pip install fancyimpute

this will take you pycharm default python interpreter and install the package in the python site package. you will be able to see this package in your project


答:
You should model your interface this way instead:

```<code>export interface IQuestionnaire {
  DataProcessingID: string;
  Qestion: Security[];
}

interface Security {
  SecurityControl: string;
  securityGoal: string[];
}
</code>```

The reason being, Qestion is in fact an array of objects, and each object consists of the SecurityControl and securityGoal properties. Anyways, I believe you meant 'Question' rather than 'Qestion'.

And on your component.ts, you can simply initialise the object.

Title: using interface to define a new type

Body:
You should model your interface this way instead:

export interface IQuestionnaire {
  DataProcessingID: string;
  Qestion: Security[];
}

interface Security {
  SecurityControl: string;
  securityGoal: string[];
}

The reason being, Qestion is in fact an array of objects, and each object consists of the SecurityControl and securityGoal properties. Anyways, I believe you meant 'Question' rather than 'Qestion'.

And on your component.ts, you can simply initialise the object.


问:
POST method is not supported for this route
First, I've checked other question topic, but couldn't find the solution.

when I try to post my form. I am getting this error.

The POST method is not supported for this route. Supported methods:
  GET, HEAD.

Form:

```<code><div class="card-body">
    <form action="{{route('profile.update', ['id' => $id])}}" method="post">
      @csrf
      @put

        <div class="form-group">
            <label for="location">Location</label>
            <input class="form-control" type="text" name="location" value="{{$info->location}}">
        </div>
        <div class="form-group">
            <label for="about">About</label>
            <textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>
        </div>
        <div class="form-control">
            <p class="text-center">
                <button class="btn btn-primary btn-md" type="submit">Update Your Info</button>
            </p>
        </div>
    </form>
</div>
</code>```

Routes:

```<code>Route::group(["middleware" => "auth"], function(){
    route::get("/profile/edit", [
        "uses" => "ProfilesController@edit",
        "as" => "profile.edit"
    ]);
    route::get("/profile/{slug}", [
        "uses" => "ProfilesController@index",
        "as" => "profile"
    ]);
    route::put("/profile/update/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
});
</code>```

in controller:

```<code>public function update(Request $request, $id)
{

    dd($request->all());

}
</code>```

答:
Since you made a form for PUT request, you have to change

```<code>route::post("/profile/update/profile", [
    "uses" => "ProfilesController@update",
    "as" => "profile.update"
]);
</code>```

to this

```<code>route::put("/profile/update/profile", [
    "uses" => "ProfilesController@update",
    "as" => "profile.update"
]);
</code>```

Body:
First, I've checked other question topic, but couldn't find the solution.

when I try to post my form. I am getting this error.

The POST method is not supported for this route. Supported methods:
  GET, HEAD.

Form:

    <form action="{{route('profile.update', ['id' => $id])}}" method="post">
      @csrf
      @put

            Location
            <input class="form-control" type="text" name="location" value="{{$info->location}}">

            About
            <textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>

                <button class="btn btn-primary btn-md" type="submit">Update Your Info</button>

    </form>

Routes:

Route::group(["middleware" => "auth"], function(){
    route::get("/profile/edit", [
        "uses" => "ProfilesController@edit",
        "as" => "profile.edit"
    ]);
    route::get("/profile/{slug}", [
        "uses" => "ProfilesController@index",
        "as" => "profile"
    ]);
    route::put("/profile/update/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
});

in controller:

public function update(Request $request, $id)
{

    dd($request->all());

}

Body:
Since you made a form for PUT request, you have to change

route::post("/profile/update/profile", [
    "uses" => "ProfilesController@update",
    "as" => "profile.update"
]);

to this

route::put("/profile/update/profile", [
    "uses" => "ProfilesController@update",
    "as" => "profile.update"
]);


问:
Element out from container box that already fix
I have a bunch of image that will show random quantity. I try to make every line with 2 images. But it doesn't want to split to 2 each line. but. 1 line 1 image. I already set the container to desire max width I will use and the max size each image. in  code i set max container i will use to 1024px. and each image 512px. i think it should not have problem. i already check with inspect. no padding and margin already. if i set it a bit low example to 509.5px. it will split to 2.

Here's the code:

var caption = document.getElementsByClassName('caption');

for (var i = 0; i < caption.length; i++) {
  caption[i].innerHTML = "";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  display: inline;
  margin: 0;
  padding: 0;
  list-style-type: none;
}

li {
  display: inline;
}

.banner figure {
  display: inline;
  margin: 0;
}

.banner figure .caption {
  display: inline;
}</code>```

banner

banner

banner

banner

banner

banner

banner

```

答:
The issue is you are using display:inline so you might want to remove that and use:

```<code>   ul {
       box-sizing:border-box;
       list-style-type:none;
       padding:0;
       margin:0;
    }

    ul:after {
      display:block;
      clear:both;
      content:"";
    }
    ul li {
      float:left;
      width:50%;
    }
    ul li img {
      max-width:100%;
    }
    figure {
      margin:0;
      padding:0;
    }
</code>```

https://jsfiddle.net/tazpdc2u/

Body:
I have a bunch of image that will show random quantity. I try to make every line with 2 images. But it doesn't want to split to 2 each line. but. 1 line 1 image. I already set the container to desire max width I will use and the max size each image. in  code i set max container i will use to 1024px. and each image 512px. i think it should not have problem. i already check with inspect. no padding and margin already. if i set it a bit low example to 509.5px. it will split to 2.

Here's the code:

var caption = document.getElementsByClassName('caption');

for (var i = 0; i < caption.length; i++) {
  caption[i].innerHTML = "";
}

ul {
  display: inline;
  margin: 0;
  padding: 0;
  list-style-type: none;
}

li {
  display: inline;
}

.banner figure {
  display: inline;
  margin: 0;
}

.banner figure .caption {
  display: inline;
}

banner

banner

banner

banner

banner

banner

banner

Body:
The issue is you are using display:inline so you might want to remove that and use:

   ul {
       box-sizing:border-box;
       list-style-type:none;
       padding:0;
       margin:0;
    }

    ul:after {
      display:block;
      clear:both;
      content:"";
    }
    ul li {
      float:left;
      width:50%;
    }
    ul li img {
      max-width:100%;
    }
    figure {
      margin:0;
      padding:0;
    }

https://jsfiddle.net/tazpdc2u/


问:
Trace not delivered / bounced email with PHP, phpmailer and Message-ID
I have a PHP web app with a section to send invoice by email to all partners.
Each partner could have more than 1 email.

For example: COMPANY-1 with emails: email_1@company1.com and email_2@company1.com

I send all with phpmailer.

I save into my database the send-response from server mail ( in this case gmail).

If sent, i'll save true, else false - foreach email.

But some emails sometimes are incorrect (due to error typing when insert) or are dismissed by the company (in this case the company do not inform us and we still send to this deleted email) and I like to retrieve these "problems" using web app.

(If I login into google webmail I can see the email returned for each sent to an not existing email, with some advice/error code inside... but i don't know how to retrieve using PHP)

I tried using

```<code>$inbox = imap_open($hostname,$username,$password);

$emails = imap_search($inbox,'ALL');
</code>```

This script works, but using ALL i get timeout.

I don't know the best method to retrieve these email of "NOT DELIVERED EMAILS FOR SOME PROBLEMS".

My first ideas was to set a custom Message-ID in the header when I send:

```<code>$messageID = "<" . md5($_SERVER['HTTP_HOST'].(idate("U")-1000000000).uniqid()).'-'.idate("U") . '@' . $_SERVER['HTTP_HOST'] . '>';
$mail->MessageID = $messageID;
</code>```

and then in my script, using a command like:

```<code>$messageID = retrieve_from_database(...);
$emails = imap_search($inbox,'HEADER ' . $messageID);
</code>```

but it doesn't exist a query HEADER

I'd like in my web app to show, for each email sent, eventually problem of bounced or undelivered but I don't know how and what I need to "ask" to imap_search to retrieve responses associated to the original sent email.

I read criterias list from docs, but I don't find anything usefull I think: https://www.php.net/manual/en/function.imap-search.php

Example of a scenario I need:

I send an email with Message-ID: <test@testXYZ> from my_email@mywebapp.com to email_not_existing@test.com. The server response true cause sent is done.

I insert a new entry on my database table emails_sent with send result true: INSERT INTO emails_sent (ID, email_dest, sent, MessageID, when) VALUES (455, 'email_not_existing@test.com', TRUE, $messageID, '2019-05-30 8:00:00')

The gmail daemon reply to my_email@mywebapp.com with a message of undelivered email

In my web app, when I go into page of sent emails, foreach ID from emails_sent table, i need to search on imap eventually response email with errors. In this example case when I ask for ID 455, I need to search on imap_search messages replyes associated with my email sent with MessageID assigned by me (or other method i don't know....)

答:
I would advise you to get away from shared hosting and get a proper server (try scaleway.com). As you're discovering, it means you don't get sufficient control.

I'd recommend against using IMAP as your database - as you're finding it's not good enough for the kind of searching you want to do. If you import all the bounced messages into your own DB, you're free to parse and search in whatever way you like, and it's also easy to get all messages from IMAP.

The most efficient way to handle bounces is to get your SMTP server to pipe bounce messages directly into a script. This will give you the complete bounced message, along with environment variables that tell you more about the delivery. That of course requires that you have config-level access to your mail server, or a hosting provider with a clue.

Be warned that bounce handling is an exceedingly unpleasant task, and is very difficult to do well. You may want to look at a 3rd-party bounce handler like Boogie Tools bounce studio to save you some sanity! Aside from some very broad top-level standards, there is very little consistency at a lower level, and bounces are often useless. For example, MS Exchange can produce bounces that do not contain the bounced message's original target address at all! The way around this is to use VERP, where every address (or even every message) gets its own unique return path, allowing you to know where a message bounced from even if the message content contains no clues.

Body:
I have a PHP web app with a section to send invoice by email to all partners.
Each partner could have more than 1 email.

For example: COMPANY-1 with emails: email_1@company1.com and email_2@company1.com

I send all with phpmailer.

I save into my database the send-response from server mail ( in this case gmail).

If sent, i'll save true, else false - foreach email.

But some emails sometimes are incorrect (due to error typing when insert) or are dismissed by the company (in this case the company do not inform us and we still send to this deleted email) and I like to retrieve these "problems" using web app.

(If I login into google webmail I can see the email returned for each sent to an not existing email, with some advice/error code inside... but i don't know how to retrieve using PHP)

I tried using

$inbox = imap_open($hostname,$username,$password);

$emails = imap_search($inbox,'ALL');

This script works, but using ALL i get timeout.

I don't know the best method to retrieve these email of "NOT DELIVERED EMAILS FOR SOME PROBLEMS".

My first ideas was to set a custom Message-ID in the header when I send:

$messageID = "<" . md5($_SERVER['HTTP_HOST'].(idate("U")-1000000000).uniqid()).'-'.idate("U") . '@' . $_SERVER['HTTP_HOST'] . '>';
$mail->MessageID = $messageID;

and then in my script, using a command like:

$messageID = retrieve_from_database(...);
$emails = imap_search($inbox,'HEADER ' . $messageID);

but it doesn't exist a query HEADER

I'd like in my web app to show, for each email sent, eventually problem of bounced or undelivered but I don't know how and what I need to "ask" to imap_search to retrieve responses associated to the original sent email.

I read criterias list from docs, but I don't find anything usefull I think: https://www.php.net/manual/en/function.imap-search.php

Example of a scenario I need:

I send an email with Message-ID: <test@testXYZ> from my_email@mywebapp.com to email_not_existing@test.com. The server response true cause sent is done.

I insert a new entry on my database table emails_sent with send result true: INSERT INTO emails_sent (ID, email_dest, sent, MessageID, when) VALUES (455, 'email_not_existing@test.com', TRUE, $messageID, '2019-05-30 8:00:00')

The gmail daemon reply to my_email@mywebapp.com with a message of undelivered email

In my web app, when I go into page of sent emails, foreach ID from emails_sent table, i need to search on imap eventually response email with errors. In this example case when I ask for ID 455, I need to search on imap_search messages replyes associated with my email sent with MessageID assigned by me (or other method i don't know....)


问:
Android NDK shared libraries
I am trying to build a native library for an Android application. I have 2 libraries and I need to link them in my final library, but I have some problems.
The Android.mk code:

```<code>LOCAL_CFLAGS     := -Wall -Wfloat-equal -std=c99

LOCAL_PATH := $(call my-dir)/..

include $(CLEAR_VARS)
  LOCAL_MODULE            := cpu-lib
  LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/cpu/inc
  LOCAL_EXPORT_CPPFLAGS   := $(LOCAL_CFLAGS)
  LOCAL_EXPORT_LDLIBS     := -llog
  LOCAL_SRC_FILES         := $(LOCAL_PATH)/cpu/lib/$(TARGET_ARCH_ABI)/libdemoDSP.so
  LOCAL_STATIC_LIBRARIES  := gnustl_static
include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)
  LOCAL_MODULE            := dsp-lib
  LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/dsp/inc
  LOCAL_EXPORT_CPPFLAGS   := $(LOCAL_CFLAGS)
  LOCAL_EXPORT_LDLIBS     := -llog
  LOCAL_SRC_FILES         := $(LOCAL_PATH)/dsp/lib/$(TARGET_ARCH_ABI)/libfn_dsp.so
  LOCAL_STATIC_LIBRARIES  := gnustl_static
include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := process
LOCAL_SRC_FILES := process.cpp
LOCAL_SHARED_LIBRARIES := cpu-lib dsp-lib
include $(BUILD_SHARED_LIBRARY)
</code>```

The problem is that the dlopen won't find the libfn_dsp.so.
The ndk-depends output:

```<code>ndk-depends libs\arm64-v8a\libprocess.so
WARNING: Could not find library: ./obj/local/arm64-v8a/libfn_dsp.so
libprocess.so
liblog.so
libdemoDSP.so
libstdc++.so
libm.so
libdl.so
libc.so
./obj/local/arm64-v8a/libfn_dsp.so
</code>```

It seems that is something strange with that lib. Does somebody know what might be?

答:
The problem is libfn_dsp.so miss SONAME info, you can use "readelf --dynamic libfn_dsp.so |grep SONAME" then check output info is empty, And you can use "readelf --dynamic libdemoDSP.so |grep SONAME", which output info is "libdemoDSP.so".

how to fix:
1. If you have libfn_dsp.so source code, you can compile it with newest NDK, or with older NDK add "-Wl,-soname,libfn_dsp.so" option.
2. Otherwise, you use System.loadLibrary("fn_dsp") manually load libfn_dsp.so before loading libprocess.so.

Title: Android NDK shared libraries

Body:
I am trying to build a native library for an Android application. I have 2 libraries and I need to link them in my final library, but I have some problems.
The Android.mk code:

LOCAL_CFLAGS     := -Wall -Wfloat-equal -std=c99

LOCAL_PATH := $(call my-dir)/..

include $(CLEAR_VARS)
  LOCAL_MODULE            := cpu-lib
  LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/cpu/inc
  LOCAL_EXPORT_CPPFLAGS   := $(LOCAL_CFLAGS)
  LOCAL_EXPORT_LDLIBS     := -llog
  LOCAL_SRC_FILES         := $(LOCAL_PATH)/cpu/lib/$(TARGET_ARCH_ABI)/libdemoDSP.so
  LOCAL_STATIC_LIBRARIES  := gnustl_static
include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)
  LOCAL_MODULE            := dsp-lib
  LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/dsp/inc
  LOCAL_EXPORT_CPPFLAGS   := $(LOCAL_CFLAGS)
  LOCAL_EXPORT_LDLIBS     := -llog
  LOCAL_SRC_FILES         := $(LOCAL_PATH)/dsp/lib/$(TARGET_ARCH_ABI)/libfn_dsp.so
  LOCAL_STATIC_LIBRARIES  := gnustl_static
include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := process
LOCAL_SRC_FILES := process.cpp
LOCAL_SHARED_LIBRARIES := cpu-lib dsp-lib
include $(BUILD_SHARED_LIBRARY)

The problem is that the dlopen won't find the libfn_dsp.so.
The ndk-depends output:

ndk-depends libs\arm64-v8a\libprocess.so
WARNING: Could not find library: ./obj/local/arm64-v8a/libfn_dsp.so
libprocess.so
liblog.so
libdemoDSP.so
libstdc++.so
libm.so
libdl.so
libc.so
./obj/local/arm64-v8a/libfn_dsp.so

It seems that is something strange with that lib. Does somebody know what might be?


问:
N-curses within Python : how to catch and print non ascii character?
I want to make a small program with ncurses/python and to be able to use/type in french and japanese. I understand that I should set the locale and use unicode standard.

But how to deal with the result from screen.getch() ? I would like to display the typed character within the ncurses window regardless of the language.

I understand that some unicode conversion is necessary but can't find what to do (and i've searched quite a bit : this character conversion bussiness isnt easy to understand for amateurs).

Additional question : it seems that for non ascii characters we must used addstr() instead of addch(). Similarly should I use getstr() instead of getch() ?

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import curses
from curses import wrapper
import locale

locale.setlocale(locale.LC_ALL, '')

def main(scr):
    # Following lines are some sort of "proof of concept"
    # Indeed it print latin or japanese characters allright
    scr.addstr(0, 0, u'\u3042'.encode('utf-8')) # print あ
    scr.addstr(1, 0, 'é'.encode('utf-8'))       # print é

    # But here I would like to type in a character and have it displayed onscreen
    while (True):
        car = scr.getch()
        if car == 27: # = Escape key
            break
        else:
        # What should I put between those parenthesis to
        # print the typed character on the third line of the screen
            scr.addstr(3, 0, ???? )

wrapper(main)
```

答:
getch/getkey are broken in Python. They are supposed to return a character when encoding is set up as documented, but instead they return octets from a UTF-8 sequence one by one each time the function is called. You need to work around the defect by collecting the octets in a loop until you have a complete sequence. A sequence is complete when it can be successfully decoded, otherwise incomplete.

Compare with the following program which works just fine (run with perl -C so-56373360.pl):

use Term::ReadKey qw(ReadKey ReadMode);
ReadMode 'raw';
while () {
    my $c = ReadKey 0;
    last if $c eq "\e"; # Escape
    print $c;
}
ReadMode 'restore';
```


问:
wmware workstation don't work with windows 10 pro 1903
I have updated Windows 10 PRO to 1903. Reinstalling VMware Workstation and setting existing virtual machine when i run it give me this error:

"VMware Workstation and Device/Credential Guard are not compatible. VMware Workstation can be run after disabling Device/Credential Guard."

I have done it. And i have looked too here:

http://www.vmware.com/go/turnoff_CG_DG

But nothing to do. Not solved.
So i ask your how i can solve it.
Thanks

答:
This solved my problem (run from command prompt, as admin..)

bcdedit /set hypervisorlaunchtype off

and reboot windows..


问:
html 5 audio tag width
I was wondering if it's possible to set the width of the audio tag. It is not a supported feature by default, so "hacks" will be happily accepted.

I already tried putting them in small div's and tables, but that doesn't look very smooth... As far as I can see, I'm the only one bothering about it, but I really appreciate some help

There is no need for cross-platform/browser support; I'm happy as long as FireFox (3.6 ++) supports it.

Quick example as to what I'll be using:

```<code><audio preload="auto" id="id12" controls="controls" onended="func12();" src="http://192.168.1.68/mymusic.wav"></audio>
</code>```

答:
Set it the same way you'd set the width of any other HTML element, with CSS:

```<code>audio { width: 200px; }
</code>```

Note that audio is an inline element by default in Firefox, so you might also want to set it to display: block.  Here's an example.

Title: html 5 audio tag width

Body:
I was wondering if it's possible to set the width of the audio tag. It is not a supported feature by default, so "hacks" will be happily accepted.

I already tried putting them in small div's and tables, but that doesn't look very smooth... As far as I can see, I'm the only one bothering about it, but I really appreciate some help

There is no need for cross-platform/browser support; I'm happy as long as FireFox (3.6 ++) supports it.

Quick example as to what I'll be using:

<audio preload="auto" id="id12" controls="controls" onended="func12();" src="http://192.168.1.68/mymusic.wav"></audio>

Body:
Set it the same way you'd set the width of any other HTML element, with CSS:

audio { width: 200px; }

Note that audio is an inline element by default in Firefox, so you might also want to set it to display: block.  Here's an example.


问:
how to find collegue Id in table
i have one table as Employee that have two column Id and Branch. i have to find its collegue Id except his own id from table without using subquery.

```<code>Id      Branch
==============
1       Delhi
2       Mumbai
3       Delhi
4       Delhi
5       Mumbai
6       Mumbai
</code>```

if i enter e.g. 3 then my answer has to be 1 and 4.

答:
This query should give you the answer you're after:

```<code>SELECT  E1.Id
FROM    Employee E1
INNER
JOIN    Employee E2
        ON E1.[Branch] = E2.[Branch]
WHERE   E2.Id = 3
AND     E1.Id <> 3
</code>```

It works by joining the Employee table onto itself, by Branch and then:

WHERE E2.Id = 3 - Where the Employee is Id # 3

AND E1.Id <> 3 - excluding any records from the original Employee table where Id is 3

Here's the script I used to create your test data (in SQL Server) for the purposes of validating the query:

```<code>CREATE TABLE [Employee]
(
    [Id] INT,
    [Branch] NVARCHAR(10)
)

INSERT
INTO    [Employee]
        (
            Id,
            [Branch]
        )
VALUES  (1, 'Delhi'),
        (2, 'Mumbai'),
        (3, 'Delhi'),
        (4, 'Delhi'),
        (5, 'Mumbai'),
        (6, 'Mumbai')
</code>```

Title: how to find collegue Id in table

Body:
i have one table as Employee that have two column Id and Branch. i have to find its collegue Id except his own id from table without using subquery.

Id      Branch
==============
1       Delhi
2       Mumbai
3       Delhi
4       Delhi
5       Mumbai
6       Mumbai

if i enter e.g. 3 then my answer has to be 1 and 4.

Body:
This query should give you the answer you're after:

SELECT  E1.Id
FROM    Employee E1
INNER
JOIN    Employee E2
        ON E1.[Branch] = E2.[Branch]
WHERE   E2.Id = 3
AND     E1.Id <> 3

It works by joining the Employee table onto itself, by Branch and then:

WHERE E2.Id = 3 - Where the Employee is Id # 3

AND E1.Id <> 3 - excluding any records from the original Employee table where Id is 3

Here's the script I used to create your test data (in SQL Server) for the purposes of validating the query:

CREATE TABLE [Employee]
(
    [Id] INT,
    [Branch] NVARCHAR(10)
)

INSERT
INTO    [Employee]
        (
            Id,
            [Branch]
        )
VALUES  (1, 'Delhi'),
        (2, 'Mumbai'),
        (3, 'Delhi'),
        (4, 'Delhi'),
        (5, 'Mumbai'),
        (6, 'Mumbai')


问:
grep summarize lines by strings
I have a grep'ed string from curl, and I want to summarize lines of by its content.

e. g.
input

```<code>SomethingA v2.3
SomethingA v2.4

SomethingElse v1.1
SomethingElse v1.2
</code>```

output

```<code>SomethingA 2
SomethingElse 1
</code>```

The numbers in the output are not a must, but if easy to achieve, would be very nice. The "v" as the leading space is a fix prefix for the numerics which don't have to contain a dot.

I tried echo "$str" | grep -Po '(.*(?<=))v[0-9]'  but it still contains the "v1" .. and I don't know how to reduce the leading strings by multiple matches.

答:
You can use </p>

```<code>$ awk '{print $1}' filename  | sort | uniq -c | awk '{print $2,$1}'
</code>```

<p>Note : This will also give a count of the blank lines. If you want to get rid of those, use : </p>

```<code>$ grep -v '^$'  filename |  awk '{print $1}' | sort | uniq -c | awk '{print $2,$1}'
</code>```

Title: grep summarize lines by strings

Body:
I have a grep'ed string from curl, and I want to summarize lines of by its content.

e. g.
input

SomethingA v2.3
SomethingA v2.4

SomethingElse v1.1
SomethingElse v1.2

output

SomethingA 2
SomethingElse 1

The numbers in the output are not a must, but if easy to achieve, would be very nice. The "v" as the leading space is a fix prefix for the numerics which don't have to contain a dot.

I tried echo "$str" | grep -Po '(.*(?<=))v[0-9]'  but it still contains the "v1" .. and I don't know how to reduce the leading strings by multiple matches.

Body:
You can use

$ awk '{print $1}' filename  | sort | uniq -c | awk '{print $2,$1}'

Note : This will also give a count of the blank lines. If you want to get rid of those, use :

$ grep -v '^$'  filename |  awk '{print $1}' | sort | uniq -c | awk '{print $2,$1}'


问:
How to make a Form Input Field Large?
For the form below, how could I make the input field big, like maybe 100 pixels in height by 400 pixels in length?

Thanks in advance,

John

```<code><form action="http://www...com/sandbox/comments/comments2.php" method="post">
    <input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">

    <div class="addacomment"><label for="title">Add a comment:</label></div>
    <div class="submissionfield"><input name="title" type="title" id="title" maxlength="1000"></div>

    <div class="submissionbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
</code>```

答:
for better n bigger input field textarea is effective.

```<code><textarea type="text"
name="pre_book_sugg"
class="form-control"
style="height: calc(2.5em + 4.75rem + 2px);"
</code>```

>

 //input value

Title: How to make a Form Input Field Large?

Body:
For the form below, how could I make the input field big, like maybe 100 pixels in height by 400 pixels in length?

Thanks in advance,

John

<form action="http://www...com/sandbox/comments/comments2.php" method="post">
    <input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">

Add a comment:

<input name="title" type="title" id="title" maxlength="1000">

<input name="submit" type="submit" value="Submit">

</form>

Body:
for better n bigger input field textarea is effective.

<textarea type="text"
name="pre_book_sugg"
class="form-control"
style="height: calc(2.5em + 4.75rem + 2px);"

>

 //input value


问:
Flutter - Regex in TextFormField
I´m trying to only allow numbers and points on a text form field.

I have something like that

```<code>WhitelistingTextInputFormatter(RegExp("\d*[.]\d*"))
</code>```

But does not work, so: Anybody have idea how can only allow digits and point?

答:
Since WhitelistingTextInputFormatter is deprecated in Flutter as of 1.20, FilteringTextInputFormatter can be used:

A TextInputFormatter that prevents the insertion of characters
matching (or not matching) a particular pattern.

Instances of filtered characters found in the new TextEditingValues
will be replaced with the replacementString which defaults to the
empty string.

Since this formatter only removes characters from the text, it
attempts to preserve the existing TextEditingValue.selection to values
it would now fall at with the removed characters.

Example use:

```<code>TextField(
 keyboardType: TextInputType.numberWithOptions(decimal: true),
 inputFormatters: <TextInputFormatter>[
      FilteringTextInputFormatter.allow(RegExp(r'^\d+(?:\.\d+)?$')),
  ],
),
</code>```

Legacy answer

WhitelistingTextInputFormatter "creates a formatter that allows only the insertion of whitelisted characters patterns". It means your pattern should just match any 1 digit  or 1 dot.

Also, you need to use a raw string literal if you want to use a single backslash with regex escapes.

Use

```<code>WhitelistingTextInputFormatter(RegExp(r"[\d.]"))
</code>```

Note that if you want to validate the whole input sequence you need to define a validator: validateMyInput and then add

```<code>String validateMyInput(String value) {
    Pattern pattern = r'^\d+(?:\.\d+)?$';
    RegExp regex = new RegExp(pattern);
    if (!regex.hasMatch(value))
      return 'Enter Valid Number';
    else
      return null;
  }
</code>```

Adapted from Form Validation in Flutter.

Title: Flutter - Regex in TextFormField

Body:
I´m trying to only allow numbers and points on a text form field.

I have something like that

WhitelistingTextInputFormatter(RegExp("\d*[.]\d*"))

But does not work, so: Anybody have idea how can only allow digits and point?

Body:
Since WhitelistingTextInputFormatter is deprecated in Flutter as of 1.20, FilteringTextInputFormatter can be used:

A TextInputFormatter that prevents the insertion of characters
matching (or not matching) a particular pattern.

Instances of filtered characters found in the new TextEditingValues
will be replaced with the replacementString which defaults to the
empty string.

Since this formatter only removes characters from the text, it
attempts to preserve the existing TextEditingValue.selection to values
it would now fall at with the removed characters.

Example use:

TextField(
 keyboardType: TextInputType.numberWithOptions(decimal: true),
 inputFormatters: <TextInputFormatter>[
      FilteringTextInputFormatter.allow(RegExp(r'^\d+(?:\.\d+)?$')),
  ],
),

Legacy answer

WhitelistingTextInputFormatter "creates a formatter that allows only the insertion of whitelisted characters patterns". It means your pattern should just match any 1 digit  or 1 dot.

Also, you need to use a raw string literal if you want to use a single backslash with regex escapes.

Use

WhitelistingTextInputFormatter(RegExp(r"[\d.]"))

Note that if you want to validate the whole input sequence you need to define a validator: validateMyInput and then add

String validateMyInput(String value) {
    Pattern pattern = r'^\d+(?:\.\d+)?$';
    RegExp regex = new RegExp(pattern);
    if (!regex.hasMatch(value))
      return 'Enter Valid Number';
    else
      return null;
  }

Adapted from Form Validation in Flutter.


问:
Why / when would it be appropriate to override ToString?
I'm studying C# and I wonder what the point and benefit of overriding ToString might be, as shown in the example below.

Could this be done in some simpler way, using a common method without the override?

```<code>public string GetToStringItemsHeadings
{
    get { return string.Format("{0,-20} {1, -20}", "Office Email", "Private Email"); }
}

public override string ToString()
{
    string strOut = string.Format("{0,-20} {1, -20}", m_work, m_personal);
    return strOut;
}
</code>```

答:
I'm happy with the Framework Guidelines referred to in other answers.
However, I'd like to emphasize the display and debugging purposes.

Be careful about how you use ToString in your code. Your code shouldn't rely on the string representation of an object. If it does, you should absolutely provide the respective Parse methods.

Since ToString can be used everywhere, it can be a maintainability pain point if you want to change the string representation of an object at a later point in time. You cannot just examine the call hierarchy in this case to study whether some code will break.

Body:
I'm studying C# and I wonder what the point and benefit of overriding ToString might be, as shown in the example below.

Could this be done in some simpler way, using a common method without the override?

public string GetToStringItemsHeadings
{
    get { return string.Format("{0,-20} {1, -20}", "Office Email", "Private Email"); }
}

public override string ToString()
{
    string strOut = string.Format("{0,-20} {1, -20}", m_work, m_personal);
    return strOut;
}