问:
SUSER_SID support for Azure SQL
SUSER_SID has two optional parameters. I am using only first 'login'. Documentation for it applies to Azure SQL Database, but it doesn't work. For 'login' parameter is says "Applies to: SQL Server 2008 and later".

When I call SELECT SUSER_SID('test');
using SSMS, I get the error:

'SUSER_SID' cannot be invoked with parameters in this version of SQL Server.

I am using Azure SQL Server ver. 12.0.2000.8

How is that possible, what am I missing?

答:
for this question I asked Azure Support. They told me that:

Based on the online document, the parameter “login” applies to SQL Server 2008 and later version, and the parameter2 applies to SQL Server 2012 and later version. That is the reason why we will get the error message “'SUSER_SID' cannot be invoked with parameters in this version of SQL Server.” while running the command SELECT SUSER_SID('serveradmin') , because Azure SQL database does not support SUSER_SID() with parameters.

If you want to check the SID, please consider running the command in below instead:

```<code>select name, sid from sys.sql_logins where name = 'test'
</code>```

Here's the screenshots:

Hope this helps.

Title: SUSER_SID support for Azure SQL

Body:
for this question I asked Azure Support. They told me that:

Based on the online document, the parameter “login” applies to SQL Server 2008 and later version, and the parameter2 applies to SQL Server 2012 and later version. That is the reason why we will get the error message “'SUSER_SID' cannot be invoked with parameters in this version of SQL Server.” while running the command SELECT SUSER_SID('serveradmin') , because Azure SQL database does not support SUSER_SID() with parameters.

If you want to check the SID, please consider running the command in below instead:

select name, sid from sys.sql_logins where name = 'test'

Here's the screenshots:

Hope this helps.


来源: stackexchange

问:
Trying to fit the Gaussian function to data
I'm trying to fit some data that is approximately Gaussian to the function in python using the curve_fit method. For the initial guesses for the parameters I've calculated the mean and standard deviation of the data. However, I'm getting a really bad fit and I'm not sure why. This is my code:

```<code>import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
import math

def func(x, mu, sig):
    return (1./(sig*math.sqrt(2*math.pi)))*np.exp(-np.power(x-mu,2.)/(2*np.power(sig, 2.)));

xdata = np.linspace(4, 14, 21)
ydata = np.array([0.2,0.8,1.8,1.9,5.9,7,11,12.6,14,13.3,11.8,9.3,5.2,3.1,1.5,0.7,0.4,0.1,0.3,0.1,0.1])
plt.plot(xdata, ydata, 'b-', label='data')

popt, pcov = curve_fit(func, xdata, ydata,[4.8,5.1])
plt.plot(xdata, func(xdata, *popt), 'r-', label='fit')
</code>```

The fitted model (in red) looks like this:
enter image description here

答:
The reason you're getting a nonsense answer is because you're trying to fit the Gaussian function of a normalised curve. See the difference here.

Instead, if you use the generalised form with 3 parameters, you get a much better fit.

```<code>def generalised_gaussian(x, a, b, c):
    return a*np.exp(-np.power((x-b)/(2*c**2), 2))

xdata = np.linspace(4, 14, 21)
ydata = np.array([0.2,0.8,1.8,1.9,5.9,7,11,12.6,14,13.3,11.8,9.3,5.2,3.1,1.5,0.7,0.4,0.1,0.3,0.1,0.1])
plt.plot(xdata, ydata, 'b-', label='data')

popt, pcov = curve_fit(generalised_gaussian, xdata, ydata)
plt.plot(xdata, generalised_gaussian(xdata, *popt), 'r-', label='fit')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to fit some data that is approximately Gaussian to the function in python using the curve_fit method. For the initial guesses for the parameters I've calculated the mean and standard deviation of the data. However, I'm getting a really bad fit and I'm not sure why. This is my code:

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
import math

def func(x, mu, sig):
    return (1./(sig*math.sqrt(2*math.pi)))*np.exp(-np.power(x-mu,2.)/(2*np.power(sig, 2.)));

xdata = np.linspace(4, 14, 21)
ydata = np.array([0.2,0.8,1.8,1.9,5.9,7,11,12.6,14,13.3,11.8,9.3,5.2,3.1,1.5,0.7,0.4,0.1,0.3,0.1,0.1])
plt.plot(xdata, ydata, 'b-', label='data')

popt, pcov = curve_fit(func, xdata, ydata,[4.8,5.1])
plt.plot(xdata, func(xdata, *popt), 'r-', label='fit')

The fitted model (in red) looks like this:
enter image description here

Body:
The reason you're getting a nonsense answer is because you're trying to fit the Gaussian function of a normalised curve. See the difference here.

Instead, if you use the generalised form with 3 parameters, you get a much better fit.

def generalised_gaussian(x, a, b, c):
    return a*np.exp(-np.power((x-b)/(2*c**2), 2))

xdata = np.linspace(4, 14, 21)
ydata = np.array([0.2,0.8,1.8,1.9,5.9,7,11,12.6,14,13.3,11.8,9.3,5.2,3.1,1.5,0.7,0.4,0.1,0.3,0.1,0.1])
plt.plot(xdata, ydata, 'b-', label='data')

popt, pcov = curve_fit(generalised_gaussian, xdata, ydata)
plt.plot(xdata, generalised_gaussian(xdata, *popt), 'r-', label='fit')


问:
Error in v-on handler (Promise/async): "TypeError: Cannot read property 'push' of undefined"
```<code>const res = await this.callApi('post','place_order',this.formItem)
if(res.status == 200){
                this.order.push(res.data)
                this.s("Order Successful !")
                this.formItem = {}
}
</code>```

When I received the response from controller this showing me 'push' is undefined.

And this is my controller

```<code>public function place_order(Request $request){
        $data = $request->all();
        $order= Order::create($data);

        return response()->json([
            'order' => $order,
            'success' => true
        ],200);
    }
</code>```

答:
Check the type of "this.order". Array.prototype.push() will only work on arrays.

Edit: Since that it says that "push 'of' undefined", you should also check if "this.order" is really defined.

Body:
const res = await this.callApi('post','place_order',this.formItem)
if(res.status == 200){
                this.order.push(res.data)
                this.s("Order Successful !")
                this.formItem = {}
}

When I received the response from controller this showing me 'push' is undefined.

And this is my controller

public function place_order(Request $request){
        $data = $request->all();
        $order= Order::create($data);

        return response()->json([
            'order' => $order,
            'success' => true
        ],200);
    }


问:
How can I use number as key?
I have ids like as numbers 374,242,435

I want to use this as key of hash for the object.

```<code>var json = [];
ids = [374,242,435];
for(let i in ids) {
    var id = ids[i];
    json[id] = []; // it makes 372 array!!!
    json[id]['name'] = name;
    json[id]['color'] = color;
}
</code>```

Can I make object using number as key????

This is my silly mistake

I just changed var json = []; -> var json = {}; it works.

and thank you for your comments.

答:
You can use Map to store key-value pair. In Map, key will not just be string.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Title: How can I use number as key?

Body:
I have ids like as numbers 374,242,435

I want to use this as key of hash for the object.

var json = [];
ids = [374,242,435];
for(let i in ids) {
    var id = ids[i];
    json[id] = []; // it makes 372 array!!!
    json[id]['name'] = name;
    json[id]['color'] = color;
}

Can I make object using number as key????

This is my silly mistake

I just changed var json = []; -> var json = {}; it works.

and thank you for your comments.


答:
It's a bit unclear why you want to do like that but it's achievable with a few functions implemented in the query. Refer following query for example:

```<code>SELECT NAME, idperiode,
       SUBSTRING_INDEX(dateclass,',',1) AS date_1,
       SUBSTRING_INDEX(SUBSTRING_INDEX(dateclass,',',2),',',-1) AS date_2,
       SUBSTRING_INDEX(SUBSTRING_INDEX(dateclass,',',3),',',-1) AS date_3,
       SUBSTRING_INDEX(SUBSTRING_INDEX(dateclass,',',4),',',-1) AS date_4,
       SUBSTRING_INDEX(dateclass,',',-1) AS date_5
FROM
(SELECT NAME,
       idperiode,
       GROUP_CONCAT(dateclass ORDER BY dateclass) AS dateclass
 FROM mytable
 GROUP BY NAME, idperiode) A;
</code>```

The first part is a sub-query using GROUP_CONCAT to combine all the dates (assuming that all these are in one table only). Then use SUBSTRING_INDEX to separate the groupconcated dates. You can view the demo fiddle here

IF there are two tables with no relation, then you can use CROSS JOIN on the tables. I've also prepared the fiddle here with just a slight modification in the sub-query whereas the outer query still function the same.

Title: How to display sequence of dates in rows to columns

Body:
Table periods with primary field idPeriod and a few hundred records.
Table date_classes with idPeriod and dateClass
There are also names to display. Each name has the same period and the 5 dates.

Each period has 5 dates.

+-----------+------------+
| idPeriode | dateClass  |
+-----------+------------+
|    302367 | 2020-02-18 |
|    302367 | 2020-02-25 |
|    302367 | 2020-03-03 |
|    302367 | 2020-03-10 |
|    302367 | 2020-03-17 |
+-----------+------------+

I would like to show :

+----------+---------------------+------------+------------+------------+------------+
| Name     | Period | Date1      | Date2      | Date3      | Date4      | Date5      |
+----------+---------------------+------------+------------+------------+------------+
| Bousquet | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
| Grignon  | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
| Rajotte  | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
| Vandal   | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
| Tessier  | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
| Beauvais | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
+----------+--------+------------+------------+------------+------------+------------+

Body:
It's a bit unclear why you want to do like that but it's achievable with a few functions implemented in the query. Refer following query for example:

SELECT NAME, idperiode,
       SUBSTRING_INDEX(dateclass,',',1) AS date_1,
       SUBSTRING_INDEX(SUBSTRING_INDEX(dateclass,',',2),',',-1) AS date_2,
       SUBSTRING_INDEX(SUBSTRING_INDEX(dateclass,',',3),',',-1) AS date_3,
       SUBSTRING_INDEX(SUBSTRING_INDEX(dateclass,',',4),',',-1) AS date_4,
       SUBSTRING_INDEX(dateclass,',',-1) AS date_5
FROM
(SELECT NAME,
       idperiode,
       GROUP_CONCAT(dateclass ORDER BY dateclass) AS dateclass
 FROM mytable
 GROUP BY NAME, idperiode) A;

The first part is a sub-query using GROUP_CONCAT to combine all the dates (assuming that all these are in one table only). Then use SUBSTRING_INDEX to separate the groupconcated dates. You can view the demo fiddle here

IF there are two tables with no relation, then you can use CROSS JOIN on the tables. I've also prepared the fiddle here with just a slight modification in the sub-query whereas the outer query still function the same.


问:
Python - Determine if Item is in a List Using a Function
I'm trying to write a function in Python to determine whether or not an item is in a list. I've been trying variations of this code.

No matter how I try it, it always returns a FALSE Boolean value. Even if I put the print commands inside the functions, it only prints with the results for a false value. I'm pretty sure I'm passing the list to the function properly, but I can't figure out why it only determines FALSE values. Any ideas?

```<code>def newFunction(x, y, z):
   z = 0
   if y in x:
      z = True
   else:
      z = False
   return (z)

newList = [2,4,6,8,10]
r = input ('Enter a number: ')
s = 0
newFunction(newList, r, s)
if s == True:
   print ('The no. IS in the list.')
else:
   print ('The no. IS NOT in the list.')
</code>```

答:
There is a simpler way to do this. Do note that the input would be type string, so you need to convert to int.

```<code>newList = [2,4,6,8,10]

def newFunction(x, newList):
    if x in newList:
        return True
    else:
        return False

x = int(input("Enter a number"))
if newFunction(x, newList) == True:
    print("it is in the list")
else:
    print("it is not in the list")

</code>```

Shorter way:

```<code>newList = [2,4,6,8,10]

x = int(input("enter a number"))
if x in newList:
    print("it is in the list")
else:
    print("it is not in the list")

</code>```

Body:
I'm trying to write a function in Python to determine whether or not an item is in a list. I've been trying variations of this code.

No matter how I try it, it always returns a FALSE Boolean value. Even if I put the print commands inside the functions, it only prints with the results for a false value. I'm pretty sure I'm passing the list to the function properly, but I can't figure out why it only determines FALSE values. Any ideas?

def newFunction(x, y, z):
   z = 0
   if y in x:
      z = True
   else:
      z = False
   return (z)

newList = [2,4,6,8,10]
r = input ('Enter a number: ')
s = 0
newFunction(newList, r, s)
if s == True:
   print ('The no. IS in the list.')
else:
   print ('The no. IS NOT in the list.')

Body:
There is a simpler way to do this. Do note that the input would be type string, so you need to convert to int.

newList = [2,4,6,8,10]

def newFunction(x, newList):
    if x in newList:
        return True
    else:
        return False

x = int(input("Enter a number"))
if newFunction(x, newList) == True:
    print("it is in the list")
else:
    print("it is not in the list")

Shorter way:

newList = [2,4,6,8,10]

x = int(input("enter a number"))
if x in newList:
    print("it is in the list")
else:
    print("it is not in the list")


问:
Showing Images in GridView
I have some image path stored in database and I have to show the image in grid layout.
here is my code

```<code>public class HeadshotAllPhoto extends Activity
{
    GridView imagegrid;
    String path,filemanagerstring;
    String[] ImageNameArr;
    String filePath = null;
    String ImageName ;
    Bitmap bitmap;
    DataHelperHeadshot dbHeadshot;

String sub_list ;
String[] pathArr;
Bitmap[] bmp;
ArrayList<String> items = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.headshotallphoto);
    dbHeadshot = new DataHelperHeadshot(this);

    bg = (ImageView)findViewById(R.id.selectHeadshotView);

    List<String> names = this.dbHeadshot.fetchAllHeadshot();
    StringBuilder sb = new StringBuilder();
    for (String name : names)
    {
       name.trim();
       sb.append(",");
       sb.append(name);
    }

    bmp = new Bitmap[icount+1];
    sub_list = sb.toString();
    Log.i("sub_list .. ",""+sub_list);
    pathArr = sub_list.split(",");

    for(int p=0;p<pathArr.length;p++)
    {
        if(pathArr[p]!=null)
        {
            bitmap = decodeFile(pathArr[p]);
            if(bitmap!=null)
            {
                items.add(pathArr[p]);
                bmp[p] = bitmap;
            }
        }
        if(pathArr[p] == null)
            break;
    }

    imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imagegrid.setAdapter(new ImageAdapter(getApplicationContext(),bmp));
    imagegrid.setOnItemClickListener(this);
    }
}

public class ImageAdapter extends BaseAdapter
{
    private Context mContext;
    Bitmap[] mImageArray;

    public ImageAdapter(Context c, Bitmap[] imgArray)
    {
          mContext = c;
          mImageArray = imgArray;
    }
    public int getCount()
    {
          return mImageArray.length;
    }
    public Object getItem(int position)
    {
          return position;
    }
    public long getItemId(int position)
    {
          return position;
    }

    public View getView(int position,View convertView,ViewGroup parent)
    {
        System.gc();
        ImageView i = null ;

        if (convertView == null )
        {
            i = new ImageView(mContext);
            i.setLayoutParams(new GridView.LayoutParams(92,92));
            i.setScaleType(ImageView.ScaleType.CENTER_CROP);
            i.setImageBitmap(mImageArray[position]);
        }
         else
             i = (ImageView) convertView;
         return i;
    }
}

public Bitmap decodeFile(String filePath)
{
    System.out.println("filepath in decode file .. "+filePath);
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 100;
    final int H = 50;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < H)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    System.out.println("decode file ........... "+filePath);
    bitmap = BitmapFactory.decodeFile(filePath, o2);
    return bitmap;
}
}
</code>```

Pls help me
Thanks

答:
I am unable to understand if you already have list why you created a sing appending "," then again splitting it, what causes problem is that at the end of your string there is a "," resulting in adding of null data, BTW try below code might help, change your onCreate with below one

```<code>protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.headshotallphoto);
    dbHeadshot = new DataHelperHeadshot(this);

    bg = (ImageView)findViewById(R.id.selectHeadshotView);

    List<String> names = this.dbHeadshot.fetchAllHeadshot();
    StringBuilder sb = new StringBuilder();
    for (String name : names)
    {
       name.trim();
       sb.append(",");
       sb.append(name);
    }

    bmp = new Bitmap[10+1];

    for(int p=0;p<names.size();p++)
    {
        if(names.get(p) !=null)
        {
            bitmap = decodeFile(names.get(p));
            if(bitmap!=null)
            {
                items.add(names.get(p));
                bmp[p] = bitmap;
            }
        }
        if(pathArr[p] == null)
            break;
    }

    imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imagegrid.setAdapter(new ImageAdapter(getApplicationContext(),bmp));
    imagegrid.setOnItemClickListener(this);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Showing Images in GridView

Body:
I have some image path stored in database and I have to show the image in grid layout.
here is my code

public class HeadshotAllPhoto extends Activity
{
    GridView imagegrid;
    String path,filemanagerstring;
    String[] ImageNameArr;
    String filePath = null;
    String ImageName ;
    Bitmap bitmap;
    DataHelperHeadshot dbHeadshot;

String sub_list ;
String[] pathArr;
Bitmap[] bmp;
ArrayList<String> items = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.headshotallphoto);
    dbHeadshot = new DataHelperHeadshot(this);

    bg = (ImageView)findViewById(R.id.selectHeadshotView);

    List<String> names = this.dbHeadshot.fetchAllHeadshot();
    StringBuilder sb = new StringBuilder();
    for (String name : names)
    {
       name.trim();
       sb.append(",");
       sb.append(name);
    }

    bmp = new Bitmap[icount+1];
    sub_list = sb.toString();
    Log.i("sub_list .. ",""+sub_list);
    pathArr = sub_list.split(",");

    for(int p=0;p<pathArr.length;p++)
    {
        if(pathArr[p]!=null)
        {
            bitmap = decodeFile(pathArr[p]);
            if(bitmap!=null)
            {
                items.add(pathArr[p]);
                bmp[p] = bitmap;
            }
        }
        if(pathArr[p] == null)
            break;
    }

    imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imagegrid.setAdapter(new ImageAdapter(getApplicationContext(),bmp));
    imagegrid.setOnItemClickListener(this);
    }
}

public class ImageAdapter extends BaseAdapter
{
    private Context mContext;
    Bitmap[] mImageArray;

    public ImageAdapter(Context c, Bitmap[] imgArray)
    {
          mContext = c;
          mImageArray = imgArray;
    }
    public int getCount()
    {
          return mImageArray.length;
    }
    public Object getItem(int position)
    {
          return position;
    }
    public long getItemId(int position)
    {
          return position;
    }

    public View getView(int position,View convertView,ViewGroup parent)
    {
        System.gc();
        ImageView i = null ;

        if (convertView == null )
        {
            i = new ImageView(mContext);
            i.setLayoutParams(new GridView.LayoutParams(92,92));
            i.setScaleType(ImageView.ScaleType.CENTER_CROP);
            i.setImageBitmap(mImageArray[position]);
        }
         else
             i = (ImageView) convertView;
         return i;
    }
}

public Bitmap decodeFile(String filePath)
{
    System.out.println("filepath in decode file .. "+filePath);
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 100;
    final int H = 50;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < H)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    System.out.println("decode file ........... "+filePath);
    bitmap = BitmapFactory.decodeFile(filePath, o2);
    return bitmap;
}
}

Pls help me
Thanks

Body:
I am unable to understand if you already have list why you created a sing appending "," then again splitting it, what causes problem is that at the end of your string there is a "," resulting in adding of null data, BTW try below code might help, change your onCreate with below one

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.headshotallphoto);
    dbHeadshot = new DataHelperHeadshot(this);

    bg = (ImageView)findViewById(R.id.selectHeadshotView);

    List<String> names = this.dbHeadshot.fetchAllHeadshot();
    StringBuilder sb = new StringBuilder();
    for (String name : names)
    {
       name.trim();
       sb.append(",");
       sb.append(name);
    }

    bmp = new Bitmap[10+1];

    for(int p=0;p<names.size();p++)
    {
        if(names.get(p) !=null)
        {
            bitmap = decodeFile(names.get(p));
            if(bitmap!=null)
            {
                items.add(names.get(p));
                bmp[p] = bitmap;
            }
        }
        if(pathArr[p] == null)
            break;
    }

    imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imagegrid.setAdapter(new ImageAdapter(getApplicationContext(),bmp));
    imagegrid.setOnItemClickListener(this);
    }
}


问:
3 Timeout intervals to show div jquery
```<code><div class="popup_div">Form here</div>
</code>```

What I am doing is to make this "div" popup when the page loads after 5 seconds, then when the user closes the popup div it will count again to 15 seconds to appear again, then when the user closes it again it will show for another 30 seconds

This is the interval

```<code>5 secs (on page load)
15 secs
30 secs (final popup, it won't popup after this)
</code>```

Here is My fiddle, hope this helps

https://jsfiddle.net/3xk725ts/

答:
Here I wrote a solution using setTimeout instead of setInterval so you don't need to take care about clearing it.</p>

```<code>    var iteration = 0;
    var times = [5000, 15000, 30000]
    var showPopUp = function(time) {
        setTimeout(function() {
        $('#timer').show();
        $('#timer').html("<span class='close'>X</span><h3>Count down complete</h3>"); }, time)
    }

    showPopUp(times[iteration]);

    $('body').on('click', '.close', function() {
        $('#timer').hide();
        iteration +=1;
        if (iteration < 3) {
          showPopUp(times[iteration])
        }
    });

</code>```

Title: 3 Timeout intervals to show div jquery

Body:
Form here

What I am doing is to make this "div" popup when the page loads after 5 seconds, then when the user closes the popup div it will count again to 15 seconds to appear again, then when the user closes it again it will show for another 30 seconds

This is the interval

5 secs (on page load)
15 secs
30 secs (final popup, it won't popup after this)

Here is My fiddle, hope this helps

https://jsfiddle.net/3xk725ts/

Body:
Here I wrote a solution using setTimeout instead of setInterval so you don't need to take care about clearing it.

    var iteration = 0;
    var times = [5000, 15000, 30000]
    var showPopUp = function(time) {
        setTimeout(function() {
        $('#timer').show();
        $('#timer').html("<span class='close'>X</span><h3>Count down complete</h3>"); }, time)
    }

    showPopUp(times[iteration]);

    $('body').on('click', '.close', function() {
        $('#timer').hide();
        iteration +=1;
        if (iteration < 3) {
          showPopUp(times[iteration])
        }
    });


问:
Is this the correct way to use ConfigureAwait(false)?
I am building a WPF application and calling this custom event.
The question here is should I call ConfigureAwait(false) at everywhere? As you can see now that I am calling it 2 times. Or even 3 times in second approach with double ConfigureAwait(false) in the same line.

```<code>// First approach
void RaiseProcessEvent(object sender, EventArgs e)
{
    Task.Run(async () => await APIManager.GetInstance.ProcessMethod()).ConfigureAwait(false);
}

// Second approach
void RaiseProcessEvent(object sender, EventArgs e)
{
    Task.Run(async () => await APIManager.GetInstance.ProcessMethod().ConfigureAwait(false)).ConfigureAwait(false);
}

// This function is in a singleton class
public async Task ProcessMethod()
{
    var result = await GetInstance.GetFinalResultFromHttpClientAsync().ConfigureAwait(false);
}
</code>```

答:
The question here is should i call ConfigureAwait(false) at everywhere?

Generally speaking, ConfigureAwait(false) should be used if the method does not need to resume on its calling context. The decision of whether or not to use ConfigureAwait(false) should be made on a per-method basis, and should either be used for every await in that method, or it should not be used for every await in that method.

More pragmatically, ConfigureAwait(false) should be used in code that is intended for reuse, possibly in different contexts. Application code seldom needs to use ConfigureAwait(false), although there have been situations I've encountered where it was necessary to prevent having a bunch of continuations interrupting the UI thread.

as you can see now that i am calling 2 time. or even 3 times in second approach with double configure(false) in the same line.

In those cases, the ConfigureAwait(false) is meaningless. Here's why:

```<code>//first approach
Task.Run(async () => await APIManager.GetInstance.ProcessMethod()).ConfigureAwait(false);
</code>```

ConfigureAwait configures an await. It does not configure a task. Since the task returned from Task.Run is never awaited, this ConfigureAwait does nothing.

```<code>//second approach
Task.Run(async () => await APIManager.GetInstance.ProcessMethod().ConfigureAwait(false)).ConfigureAwait(false);
</code>```

The false part of ConfigureAwait(false) is for the continueOnCapturedContext parameter. So ConfigureAwait(false) is saying "this method does not need to continue on the captured context". But in this case, the async delegate is being run on the thread pool (that's what Task.Run does), so you know that there's no context to capture anyway.

Side note 1: When using Task.Run to call an asynchronous method, it's common to elide the async and await keywords. E.g.: Task.Run(() => APIManager.GetInstance.ProcessMethod());. So the ConfigureAwait(false) question becomes moot anyway because there's no await anymore.

Side note 2: Discarding the task returned from Task.Run means that the code is doing fire-and-forget, which is almost always a terrible mistake. Among other things, this means that any exceptions are silently swallowed. It is almost always better to use await:

```<code>async void RaiseProcessEvent(object sender, EventArgs e)
{
  await Task.Run(() => APIManager.GetInstance.ProcessMethod());
}
</code>```

Now there's an await for the task returned from Task.Run, so it's appropriate to ask the question at this point: should this await be using ConfigureAwait(false)? Opinions can vary here, but I would say no, because this is clearly application-level code (a UI event handler), and most developers would assume code running an event handler would be on the UI thread (even if there was an await previously in that method). So for maximum maintainability I would not use a ConfigureAwait(false) in a UI event handler method, unless I had to add it for performance reasons.

Body:
I am building a WPF application and calling this custom event.
The question here is should I call ConfigureAwait(false) at everywhere? As you can see now that I am calling it 2 times. Or even 3 times in second approach with double ConfigureAwait(false) in the same line.

// First approach
void RaiseProcessEvent(object sender, EventArgs e)
{
    Task.Run(async () => await APIManager.GetInstance.ProcessMethod()).ConfigureAwait(false);
}

// Second approach
void RaiseProcessEvent(object sender, EventArgs e)
{
    Task.Run(async () => await APIManager.GetInstance.ProcessMethod().ConfigureAwait(false)).ConfigureAwait(false);
}

// This function is in a singleton class
public async Task ProcessMethod()
{
    var result = await GetInstance.GetFinalResultFromHttpClientAsync().ConfigureAwait(false);
}

Body:
The question here is should i call ConfigureAwait(false) at everywhere?

Generally speaking, ConfigureAwait(false) should be used if the method does not need to resume on its calling context. The decision of whether or not to use ConfigureAwait(false) should be made on a per-method basis, and should either be used for every await in that method, or it should not be used for every await in that method.

More pragmatically, ConfigureAwait(false) should be used in code that is intended for reuse, possibly in different contexts. Application code seldom needs to use ConfigureAwait(false), although there have been situations I've encountered where it was necessary to prevent having a bunch of continuations interrupting the UI thread.

as you can see now that i am calling 2 time. or even 3 times in second approach with double configure(false) in the same line.

In those cases, the ConfigureAwait(false) is meaningless. Here's why:

//first approach
Task.Run(async () => await APIManager.GetInstance.ProcessMethod()).ConfigureAwait(false);

ConfigureAwait configures an await. It does not configure a task. Since the task returned from Task.Run is never awaited, this ConfigureAwait does nothing.

//second approach
Task.Run(async () => await APIManager.GetInstance.ProcessMethod().ConfigureAwait(false)).ConfigureAwait(false);

The false part of ConfigureAwait(false) is for the continueOnCapturedContext parameter. So ConfigureAwait(false) is saying "this method does not need to continue on the captured context". But in this case, the async delegate is being run on the thread pool (that's what Task.Run does), so you know that there's no context to capture anyway.

Side note 1: When using Task.Run to call an asynchronous method, it's common to elide the async and await keywords. E.g.: Task.Run(() => APIManager.GetInstance.ProcessMethod());. So the ConfigureAwait(false) question becomes moot anyway because there's no await anymore.

Side note 2: Discarding the task returned from Task.Run means that the code is doing fire-and-forget, which is almost always a terrible mistake. Among other things, this means that any exceptions are silently swallowed. It is almost always better to use await:

async void RaiseProcessEvent(object sender, EventArgs e)
{
  await Task.Run(() => APIManager.GetInstance.ProcessMethod());
}

Now there's an await for the task returned from Task.Run, so it's appropriate to ask the question at this point: should this await be using ConfigureAwait(false)? Opinions can vary here, but I would say no, because this is clearly application-level code (a UI event handler), and most developers would assume code running an event handler would be on the UI thread (even if there was an await previously in that method). So for maximum maintainability I would not use a ConfigureAwait(false) in a UI event handler method, unless I had to add it for performance reasons.


问:
What is default hash algorithm that ASP.NET membership uses?
What is default hash algorithm that ASP.NET membership uses? And how can I change it?</p>

答:
Let's discuss answers to this question which are secure and time-tested:

Zetetic Just two line of code and done! The hashing algorithm PBKDF2 is much better than having SHA1 or SHA256-SHA512 etc. Latest algorithms like PBKDF2, SCRYPT or ARGON2 are leaders when it comes to hashing. But using PBKDF2 is useful in this case as it is implemented by .NET in Rfc2898DeriveBytes class. Using this library was awesome till now but there are some minor issues like:

a. Zetetic use 5000 iterations by default. Customizable if you use Pbkdf2Hash256K

b. Zetetic use Rfc2898DeriveBytes and Rfc2898DeriveBytes is based on HMACSHA1 for some reason and can not be customized.

Good news! I have customized Rfc2898DeriveBytes to use HMACSHA512 with 128,000 iterations so that SQLMembershipProvider can use PBKDF2 which was not available so far. To achieve this, I have combined Zetetic's code with my implementation of Rfc2898DeriveBytes as shown below:

using System.Security.Cryptography;

```<code>namespace custom.hashing.keyderivation
{
/// <summary>
/// This derived class of PBKDF2Hash provided necessary capabilities to SQLMembershipProvider in order to hash passwords in PBKDF2 way with 128,000 iterations.
/// </summary>
public class PBKDF2Hash : KeyedHashAlgorithm
{
    private const int kHashBytes = 64;

    private System.IO.MemoryStream _ms;

    public int WorkFactor { get; set; }

    public PBKDF2Hash()
        : base()
    {
        this.WorkFactor = 128000;
        this.Key = new byte[32]; // 32 Bytes will give us 256 bits.
        using (var rngCsp = new RNGCryptoServiceProvider())
        {
            // Fill the array with cryptographically secure random bytes.
            rngCsp.GetBytes(this.Key);
        }
    }

    /// <summary>
    /// Hash size in bits
    /// </summary>
    public override int HashSize
    {
        get
        {
            return kHashBytes * 8;
        }
    }

    protected override void HashCore(byte[] array, int ibStart, int cbSize)
    {
        (_ms = _ms ?? new System.IO.MemoryStream()).Write(array, ibStart, cbSize);
    }

    protected override byte[] HashFinal()
    {
        if (this.Key == null || this.Key.Length == 0)
        {
            throw new CryptographicException("Missing KeyedAlgorithm key");
        }

        _ms.Flush();

        var arr = _ms.ToArray();

        _ms = null;

        using (var hmac = new HMACSHA512())
        {
            return new MyRfc2898DeriveBytes(arr, this.Key, this.WorkFactor, hmac).GetBytes(kHashBytes);
        }
    }

    public override void Initialize()
    {
        _ms = null;
    }
}

// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
//
// ==--==
// <OWNER>Microsoft</OWNER>
//

//
// Rfc2898DeriveBytes.cs
//

// This implementation follows RFC 2898 recommendations. See http://www.ietf.org/rfc/Rfc2898.txt
/// <summary>
/// Microsoft has implemented PBKDF2 but with HMACSHA1. We are customizing this class to use HMACSHA512 in hashing process.
/// </summary>
public class MyRfc2898DeriveBytes : DeriveBytes
{
    private byte[] m_buffer;
    private byte[] m_salt;
    private HMAC m_hmac;  // The pseudo-random generator function used in PBKDF2

    private uint m_iterations;
    private uint m_block;
    private int m_startIndex;
    private int m_endIndex;

    private int m_blockSize;

    //
    // public constructors
    //

    // This method needs to be safe critical, because in debug builds the C# compiler will include null
    // initialization of the _safeProvHandle field in the method.  Since SafeProvHandle is critical, a
    // transparent reference triggers an error using PasswordDeriveBytes.
    [SecuritySafeCritical]
    public MyRfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, HMAC hmac)
    {
        Salt = salt;
        IterationCount = iterations;
        hmac.Key = password;
        m_hmac = hmac;
        // m_blockSize is in bytes, HashSize is in bits.
        m_blockSize = hmac.HashSize >> 3;

        Initialize();
    }

    //
    // public properties
    //

    public int IterationCount
    {
        get { return (int)m_iterations; }
        set
        {
            if (value <= 0)
                throw new ArgumentOutOfRangeException("value", "Error: Iteration count is zero or less");

            m_iterations = (uint)value;
            Initialize();
        }
    }

    public byte[] Salt
    {
        get { return (byte[])m_salt.Clone(); }
        set
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (value.Length < 8)
                throw new ArgumentException("Error: Salt size is less than 8");

            m_salt = (byte[])value.Clone();
            Initialize();
        }
    }

    //
    // public methods
    //

    public override byte[] GetBytes(int cb)
    {
        if (cb <= 0)
        {    throw new ArgumentOutOfRangeException("cb", "Error: Hash size is zero or less"); }

        Contract.Assert(m_blockSize > 0);

        byte[] password = new byte[cb];

        int offset = 0;
        int size = m_endIndex - m_startIndex;
        if (size > 0)
        {
            if (cb >= size)
            {
                Buffer.BlockCopy(m_buffer, m_startIndex, password, 0, size);
                m_startIndex = m_endIndex = 0;
                offset += size;
            }
            else
            {
                Buffer.BlockCopy(m_buffer, m_startIndex, password, 0, cb);
                m_startIndex += cb;
                return password;
            }
        }

        Contract.Assert(m_startIndex == 0 && m_endIndex == 0, "Invalid start or end index in the internal buffer.");

        while (offset < cb)
        {
            byte[] T_block = Func();
            int remainder = cb - offset;
            if (remainder > m_blockSize)
            {
                Buffer.BlockCopy(T_block, 0, password, offset, m_blockSize);
                offset += m_blockSize;
            }
            else
            {
                Buffer.BlockCopy(T_block, 0, password, offset, remainder);
                offset += remainder;
                Buffer.BlockCopy(T_block, remainder, m_buffer, m_startIndex, m_blockSize - remainder);
                m_endIndex += (m_blockSize - remainder);
                return password;
            }
        }
        return password;
    }

    public override void Reset()
    {
        Initialize();
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        if (disposing)
        {
            if (m_hmac != null)
            {
                ((IDisposable)m_hmac).Dispose();
            }

            if (m_buffer != null)
            {
                Array.Clear(m_buffer, 0, m_buffer.Length);
            }
            if (m_salt != null)
            {
                Array.Clear(m_salt, 0, m_salt.Length);
            }
        }
    }

    private void Initialize()
    {
        if (m_buffer != null)
            Array.Clear(m_buffer, 0, m_buffer.Length);
        m_buffer = new byte[m_blockSize];
        m_block = 1;
        m_startIndex = m_endIndex = 0;
    }

    internal static byte[] GetBytesFromInt(uint i)
    {
        return unchecked(new byte[] { (byte)(i >> 24), (byte)(i >> 16), (byte)(i >> 8), (byte)i });
    }

    // This function is defined as follow :
    // Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i)
    // where i is the block number.
    private byte[] Func()
    {
        byte[] INT_block = GetBytesFromInt(m_block);

        m_hmac.TransformBlock(m_salt, 0, m_salt.Length, null, 0);
        m_hmac.TransformBlock(INT_block, 0, INT_block.Length, null, 0);
        m_hmac.TransformFinalBlock(new byte[0], 0, 0);
        byte[] temp = m_hmac.Hash;
        m_hmac.Initialize();

        byte[] ret = temp;
        for (int i = 2; i <= m_iterations; i++)
        {
            m_hmac.TransformBlock(temp, 0, temp.Length, null, 0);
            m_hmac.TransformFinalBlock(new byte[0], 0, 0);
            temp = m_hmac.Hash;
            for (int j = 0; j < m_blockSize; j++)
            {
                ret[j] ^= temp[j];
            }
            m_hmac.Initialize();
        }

        // increment the block count.
        if (m_block == uint.MaxValue)
        { throw new InvalidOperationException("Derived key too long."); }

        m_block++;
        return ret;
    }
}
</code>```

After creating this class do this:

Add following line to Application_Start event of Global.asax or respective startup file of your project:

System.Security.Cryptography.CryptoConfig.AddAlgorithm(typeof(custom.hashing.keyderivation.PBKDF2Hash), "PBKDF2Hash_HB");

And change web.config as:

<membership defaultProvider="sitecore" hashAlgorithmType="PBKDF2Hash_HB">

References for constructing this answer are taken from:

Zetetic's github code

EVK's answer

Microsoft reference code

ContentLicense: CC BY-SA 2.5

Body:
Let's discuss answers to this question which are secure and time-tested:

Zetetic Just two line of code and done! The hashing algorithm PBKDF2 is much better than having SHA1 or SHA256-SHA512 etc. Latest algorithms like PBKDF2, SCRYPT or ARGON2 are leaders when it comes to hashing. But using PBKDF2 is useful in this case as it is implemented by .NET in Rfc2898DeriveBytes class. Using this library was awesome till now but there are some minor issues like:

a. Zetetic use 5000 iterations by default. Customizable if you use Pbkdf2Hash256K

b. Zetetic use Rfc2898DeriveBytes and Rfc2898DeriveBytes is based on HMACSHA1 for some reason and can not be customized.

Good news! I have customized Rfc2898DeriveBytes to use HMACSHA512 with 128,000 iterations so that SQLMembershipProvider can use PBKDF2 which was not available so far. To achieve this, I have combined Zetetic's code with my implementation of Rfc2898DeriveBytes as shown below:

using System.Security.Cryptography;

namespace custom.hashing.keyderivation
{
/// <summary>
/// This derived class of PBKDF2Hash provided necessary capabilities to SQLMembershipProvider in order to hash passwords in PBKDF2 way with 128,000 iterations.
/// </summary>
public class PBKDF2Hash : KeyedHashAlgorithm
{
    private const int kHashBytes = 64;

    private System.IO.MemoryStream _ms;

    public int WorkFactor { get; set; }

    public PBKDF2Hash()
        : base()
    {
        this.WorkFactor = 128000;
        this.Key = new byte[32]; // 32 Bytes will give us 256 bits.
        using (var rngCsp = new RNGCryptoServiceProvider())
        {
            // Fill the array with cryptographically secure random bytes.
            rngCsp.GetBytes(this.Key);
        }
    }

    /// <summary>
    /// Hash size in bits
    /// </summary>
    public override int HashSize
    {
        get
        {
            return kHashBytes * 8;
        }
    }

    protected override void HashCore(byte[] array, int ibStart, int cbSize)
    {
        (_ms = _ms ?? new System.IO.MemoryStream()).Write(array, ibStart, cbSize);
    }

    protected override byte[] HashFinal()
    {
        if (this.Key == null || this.Key.Length == 0)
        {
            throw new CryptographicException("Missing KeyedAlgorithm key");
        }

        _ms.Flush();

        var arr = _ms.ToArray();

        _ms = null;

        using (var hmac = new HMACSHA512())
        {
            return new MyRfc2898DeriveBytes(arr, this.Key, this.WorkFactor, hmac).GetBytes(kHashBytes);
        }
    }

    public override void Initialize()
    {
        _ms = null;
    }
}

// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
//
// ==--==
// <OWNER>Microsoft</OWNER>
//

//
// Rfc2898DeriveBytes.cs
//

// This implementation follows RFC 2898 recommendations. See http://www.ietf.org/rfc/Rfc2898.txt
/// <summary>
/// Microsoft has implemented PBKDF2 but with HMACSHA1. We are customizing this class to use HMACSHA512 in hashing process.
/// </summary>
public class MyRfc2898DeriveBytes : DeriveBytes
{
    private byte[] m_buffer;
    private byte[] m_salt;
    private HMAC m_hmac;  // The pseudo-random generator function used in PBKDF2

    private uint m_iterations;
    private uint m_block;
    private int m_startIndex;
    private int m_endIndex;

    private int m_blockSize;

    //
    // public constructors
    //

    // This method needs to be safe critical, because in debug builds the C# compiler will include null
    // initialization of the _safeProvHandle field in the method.  Since SafeProvHandle is critical, a
    // transparent reference triggers an error using PasswordDeriveBytes.
    [SecuritySafeCritical]
    public MyRfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, HMAC hmac)
    {
        Salt = salt;
        IterationCount = iterations;
        hmac.Key = password;
        m_hmac = hmac;
        // m_blockSize is in bytes, HashSize is in bits.
        m_blockSize = hmac.HashSize >> 3;

        Initialize();
    }

    //
    // public properties
    //

    public int IterationCount
    {
        get { return (int)m_iterations; }
        set
        {
            if (value <= 0)
                throw new ArgumentOutOfRangeException("value", "Error: Iteration count is zero or less");

            m_iterations = (uint)value;
            Initialize();
        }
    }

    public byte[] Salt
    {
        get { return (byte[])m_salt.Clone(); }
        set
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (value.Length < 8)
                throw new ArgumentException("Error: Salt size is less than 8");

            m_salt = (byte[])value.Clone();
            Initialize();
        }
    }

    //
    // public methods
    //

    public override byte[] GetBytes(int cb)
    {
        if (cb <= 0)
        {    throw new ArgumentOutOfRangeException("cb", "Error: Hash size is zero or less"); }

        Contract.Assert(m_blockSize > 0);

        byte[] password = new byte[cb];

        int offset = 0;
        int size = m_endIndex - m_startIndex;
        if (size > 0)
        {
            if (cb >= size)
            {
                Buffer.BlockCopy(m_buffer, m_startIndex, password, 0, size);
                m_startIndex = m_endIndex = 0;
                offset += size;
            }
            else
            {
                Buffer.BlockCopy(m_buffer, m_startIndex, password, 0, cb);
                m_startIndex += cb;
                return password;
            }
        }

        Contract.Assert(m_startIndex == 0 && m_endIndex == 0, "Invalid start or end index in the internal buffer.");

        while (offset < cb)
        {
            byte[] T_block = Func();
            int remainder = cb - offset;
            if (remainder > m_blockSize)
            {
                Buffer.BlockCopy(T_block, 0, password, offset, m_blockSize);
                offset += m_blockSize;
            }
            else
            {
                Buffer.BlockCopy(T_block, 0, password, offset, remainder);
                offset += remainder;
                Buffer.BlockCopy(T_block, remainder, m_buffer, m_startIndex, m_blockSize - remainder);
                m_endIndex += (m_blockSize - remainder);
                return password;
            }
        }
        return password;
    }

    public override void Reset()
    {
        Initialize();
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        if (disposing)
        {
            if (m_hmac != null)
            {
                ((IDisposable)m_hmac).Dispose();
            }

            if (m_buffer != null)
            {
                Array.Clear(m_buffer, 0, m_buffer.Length);
            }
            if (m_salt != null)
            {
                Array.Clear(m_salt, 0, m_salt.Length);
            }
        }
    }

    private void Initialize()
    {
        if (m_buffer != null)
            Array.Clear(m_buffer, 0, m_buffer.Length);
        m_buffer = new byte[m_blockSize];
        m_block = 1;
        m_startIndex = m_endIndex = 0;
    }

    internal static byte[] GetBytesFromInt(uint i)
    {
        return unchecked(new byte[] { (byte)(i >> 24), (byte)(i >> 16), (byte)(i >> 8), (byte)i });
    }

    // This function is defined as follow :
    // Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i)
    // where i is the block number.
    private byte[] Func()
    {
        byte[] INT_block = GetBytesFromInt(m_block);

        m_hmac.TransformBlock(m_salt, 0, m_salt.Length, null, 0);
        m_hmac.TransformBlock(INT_block, 0, INT_block.Length, null, 0);
        m_hmac.TransformFinalBlock(new byte[0], 0, 0);
        byte[] temp = m_hmac.Hash;
        m_hmac.Initialize();

        byte[] ret = temp;
        for (int i = 2; i <= m_iterations; i++)
        {
            m_hmac.TransformBlock(temp, 0, temp.Length, null, 0);
            m_hmac.TransformFinalBlock(new byte[0], 0, 0);
            temp = m_hmac.Hash;
            for (int j = 0; j < m_blockSize; j++)
            {
                ret[j] ^= temp[j];
            }
            m_hmac.Initialize();
        }

        // increment the block count.
        if (m_block == uint.MaxValue)
        { throw new InvalidOperationException("Derived key too long."); }

        m_block++;
        return ret;
    }
}

After creating this class do this:

Add following line to Application_Start event of Global.asax or respective startup file of your project:

System.Security.Cryptography.CryptoConfig.AddAlgorithm(typeof(custom.hashing.keyderivation.PBKDF2Hash), "PBKDF2Hash_HB");

And change web.config as:

<membership defaultProvider="sitecore" hashAlgorithmType="PBKDF2Hash_HB">

References for constructing this answer are taken from:

Zetetic's github code

EVK's answer

Microsoft reference code


问:
My Office 365 Developer account is inactive (E5 subscription)
First, a bit of background on me: I have been developing a macro-enabled Excel workbook for almost 2 years now.  It is for creating budgets for film/video projects such as TV commercials, and I released a beta version back in November.  It can be found here: www.truebudget.net

I had signed up for an Office 365 Developer account about 3 months ago, but could never login to any of my Office apps using the Developer account.  The other day I finally got someone from Microsoft Technical Support on a chat, and they were able to help me solve that problem. (Something was leftover on my computer from an old VPN I used to use that was blocking my ability to login.)  So I am finally logged in to Developer account in Excel.  Today I spend a few hours working on the next version of my Excel workbook.  However, the Developer website still says "This subscription is inactive and will expire soon. If you don't start using this subscription for development, non-admin users will lose access on Mar 22, 2020. Your subscription will be deleted on Apr 10, 2020."  I'm not sure what to do.  I used it today to write macro code in the Excel VBE, so I'm not sure what else I need to do in order to make it realize I am using it to develop for Excel.

Does anyone have any suggestions, or know of a way for me to contact someone at Microsoft about this?  I looked all around on the Developer website for a way to contact someone, but was unable to find one.

答:
It usually takes a couple of days after you perform some development work in your tenant before it extends your free subscription out a another 100 days.  I am not sure whether your Excel work would trigger it though.  I think something has to make calls to the Graph API in your tenant, or SPFx solutions need to be deployed.  To be on the safe side, I would download some sample SPFx webparts from someone's blog that you can upload to your AppCatalog.  That should trigger the extension.

If you go to your developer dashboard, you should see a link there to submit an extension request if you haven't triggered the auto-extension.

Failing that, if you log in to your Office 365 Admin portal for your Dev Tenant, you can click on "support" and open a support request.


问:
Adding functions to content navigation drawer
I am trying to add functions to my kivymd navigation drawer but i cant find a way to do it. i want the items to pen defferent pages. an example is the settings item should open the settings page when clicked. i an using the new updated kivymd version 0.103.0

this is an example code

```<code>from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty

class TestNavigationDrawer(MDApp):
    def build(self):
        return Builder.load_string(KV)

    def on_start(self):
        icons_item = {
            "folder": "My files",
            "account-multiple": "Shared with me",
            "star": "Starred",
            "history": "Recent",
            "checkbox-marked": "Shared with me",
            "upload": "Upload",
        }
        for icon_name in icons_item.keys():
            self.root.ids.content_drawer.ids.md_list.add_widget(
                ItemDrawer(icon=icon_name, text=icons_item[icon_name])
            )
</code>```

答:
As Lothric said, you need to add an 'on_release' attribute to the ItemDrawer instantiation. The value of this attribute should be whatever function you want called when the button is pressed (usually lambda if using a method callback).

Not that you asked, but KivyMD has a "kitchensink" demo app in GitLab that serves to demonstrate the functionality of some of their widgets. Here's the link

Body:
I am trying to add functions to my kivymd navigation drawer but i cant find a way to do it. i want the items to pen defferent pages. an example is the settings item should open the settings page when clicked. i an using the new updated kivymd version 0.103.0

this is an example code

from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty

class TestNavigationDrawer(MDApp):
    def build(self):
        return Builder.load_string(KV)

    def on_start(self):
        icons_item = {
            "folder": "My files",
            "account-multiple": "Shared with me",
            "star": "Starred",
            "history": "Recent",
            "checkbox-marked": "Shared with me",
            "upload": "Upload",
        }
        for icon_name in icons_item.keys():
            self.root.ids.content_drawer.ids.md_list.add_widget(
                ItemDrawer(icon=icon_name, text=icons_item[icon_name])
            )


问:
Pivot table with no calculation
I am a question about how to do something in excel with Pivot tables.

I have data that looks like this:

I want a pivot table (I will add more policies and more targetted options constantly) that let me filter by policy type, hierarchy, and policy status and I want to show Policies in column A and the targetted options in row A and for the values, I was expecting just 1 or 0 because all I want to show is the targeted action for each policy ad filter them.
So it can look something like this:

So then I can see that Policy 1 has targetted option E1, E2, E3, E4 and E5 and filter with the other information.

until now I have tried with normal pivot (does not work) and with Power Query application following this tutorial here:
https://www.danbp.org/p/en/node/127
and try to play in that Power Query window to see if I can do it, but even when I chose "count" so it can represent the binary information I want it does not look like the table I need.

All the information I have si text, no numbers for calculations, that why the power query.

Thank you in advance

答:
You need to Unpivot your source data, so you have a normalised table with multiple rows, one for each targetted option.

This can be done easily with Power Query, and you will find many answered questions and tutorials for this if you search.

The normalised data can then be used in a Pivot table to have the targetted values in the pivot table columns.

Take the data in your screenshot.

unmerge the cell with the text "Targeted" and replace it with one value per column, for example T1, T2, T3 etc.

Load the data into Power query

Select all but the T1, T2, T3 etc columns

On the Transform ribbon select Unpivot > Unpivot other columns

Rename the columns called Attribute and Value

Load the query into the worksheet

Build a pivot table from the query result table

Title: Pivot table with no calculation


问:
How do I change unique row values into another set of unique row values in a data frame in R?
I have a data frame with the experimental results coming from participants who took my test online. In the data file, each unique participant is identified by a randomly generated code given to them at the end of the experiment. Since it is cumbersome to identify each person by a random code that looks like gibberish, I would like to replace these codes by readable labels like Participant_1, Participant_2, etc.

So I think I need a piece of code that identifies each unique random code in the data file and replaces them with the participant labels one by one. But I could not figure it out and any help would be much appreciated.

Here is a piece of code that shows the output I have vs. the output I want. Note that each participant has answered different numbers of questions, so this cannot be used as an easy way out to parse them.

```<code>Participant_Identifiers <- c(rep("QHDKWEFHWKHFFH", 4), rep("WHWIHFJNWFKWF", 7), rep("HEIFFFBBKQLSD", 3))

Participant_Scores <- c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97)

df <- data.frame("Participant_Identifiers" = c(rep("QHDKWEFHWKHFFH", 4), rep("WHWIHFJNWFKWF", 7), rep("HEIFFFBBKQLSD", 3)),
                  "Participant_Scores" = c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97, 35, 67))

df

df_I_want <- data.frame("Participant_Identifiers" = c(rep("Participant_1", 4), rep("Participant_2", 7), rep("Participant_3", 3)),
                       "Participant_Scores" = c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97, 35, 67))

df_I_want
</code>```

答:
You could use match with unique

```<code>df$new_col <- paste0("Participant_", match(df$Participant_Identifiers,
                                     unique(df$Participant_Identifiers)))
</code>```

Or since Participant_Identifiers is factor, you can convert them to integer

```<code>df$new_col <- paste0("Participant_", as.integer(df$Participant_Identifiers))
</code>```

Body:
I have a data frame with the experimental results coming from participants who took my test online. In the data file, each unique participant is identified by a randomly generated code given to them at the end of the experiment. Since it is cumbersome to identify each person by a random code that looks like gibberish, I would like to replace these codes by readable labels like Participant_1, Participant_2, etc.

So I think I need a piece of code that identifies each unique random code in the data file and replaces them with the participant labels one by one. But I could not figure it out and any help would be much appreciated.

Here is a piece of code that shows the output I have vs. the output I want. Note that each participant has answered different numbers of questions, so this cannot be used as an easy way out to parse them.

Participant_Identifiers <- c(rep("QHDKWEFHWKHFFH", 4), rep("WHWIHFJNWFKWF", 7), rep("HEIFFFBBKQLSD", 3))

Participant_Scores <- c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97)

df <- data.frame("Participant_Identifiers" = c(rep("QHDKWEFHWKHFFH", 4), rep("WHWIHFJNWFKWF", 7), rep("HEIFFFBBKQLSD", 3)),
                  "Participant_Scores" = c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97, 35, 67))

df

df_I_want <- data.frame("Participant_Identifiers" = c(rep("Participant_1", 4), rep("Participant_2", 7), rep("Participant_3", 3)),
                       "Participant_Scores" = c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97, 35, 67))

df_I_want

Body:
You could use match with unique

df$new_col <- paste0("Participant_", match(df$Participant_Identifiers,
                                     unique(df$Participant_Identifiers)))

Or since Participant_Identifiers is factor, you can convert them to integer

df$new_col <- paste0("Participant_", as.integer(df$Participant_Identifiers))


问:
How to store Emoji Character in MySQL Database
I have a MySQL database configured with the default collation utf8mb4_general_ci. When I try to insert a row containing an emoji character in the text using the following query

insert into tablename
(column1,column2,column3,column4,column5,column6,column7)
values
('273','3','Hdhdhdhhzhzhzzhjzj 我爱你 ❌',49,1,'2016-09-13 08:02:29','2016-09-13 08:02:29');
```

MySQL is raising the following error

1366 Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column
'comment' at row 1

答:
For anyone trying to solve this on a managed MySQL instance (in my case on AWS RDS), the easiest way was to modify the parameter group and set the server character set and collation to be utf8mb4 and utf8mb4_bin, respectively. After rebooting the server, a quick query verifies the settings for system databases and any newly created ones:

```<code>SELECT * FROM information_schema.SCHEMATA S;
</code>```

Body:
I have a MySQL database configured with the default collation utf8mb4_general_ci. When I try to insert a row containing an emoji character in the text using the following query

insert into tablename
(column1,column2,column3,column4,column5,column6,column7)
values
('273','3','Hdhdhdhhzhzhzzhjzj 我爱你 ❌',49,1,'2016-09-13 08:02:29','2016-09-13 08:02:29');

MySQL is raising the following error

1366 Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column
'comment' at row 1

Body:
For anyone trying to solve this on a managed MySQL instance (in my case on AWS RDS), the easiest way was to modify the parameter group and set the server character set and collation to be utf8mb4 and utf8mb4_bin, respectively. After rebooting the server, a quick query verifies the settings for system databases and any newly created ones:

SELECT * FROM information_schema.SCHEMATA S;


问:
perl open() always returns the PID of the sh instead of the underlying program
I have to kill a program that I am opening via

$pid = open(FH, "program|")

or

$pid = or open(FH, "-|", "program")

However, the program (mosquittto_sub, to be specific) still lingers around in the background, because open is returning the PID of the sh that perl is using to run the program, so I am only killing the sh wrapper instead of the actual program.

Is there a way to get the programs real PID? What is the point of getting the sh's PID?

答:
There are a few ways to deal with this.

First, you can use a list form to open a process and then no shell is involved so the child process (with pid returned by open) is precisely the one with the program you need to stop

```<code>my @cmd = ('progname', '-arg1', ...);

my $pid = open my $fh, '-|', @cmd  // die "Can't open \"@cmd\": $!";

...

my $num_signaled = kill 15, $pid;
</code>```

This sketch needs some checks added.  Please see the linked documentation (look for "pipe").

If this isn't suitable for some reason -- perhaps you need the shell to run that program -- then you can find the program's pid,  and Proc::ProcessTable module is good for this.  A basic demo

```<code>use Proc::ProcessTable;

my $prog_name = ...

my $pid;
my $pt = Proc::ProcessTable->new();

foreach my $proc (@{$pt->table}) {
    if ($proc->cmndline =~ /\Q$prog_name/) {  # is this enough to identify it?
        $pid = $proc->pid;
        last;
    }
}
my $num_signaled = kill 15, $pid;
</code>```

Please be careful with identifying the program by its name -- on a modern system there may be all kinds of processes running that contain the name of the program you want to terminate.  For more detail and discussion please see this post and this post, for starters.

Finally, you can use a module to run your external programs and then you'll be able to manage and control them far more nicely. Here I'd recommend IPC::Run.

Body:
There are a few ways to deal with this.

First, you can use a list form to open a process and then no shell is involved so the child process (with pid returned by open) is precisely the one with the program you need to stop

my @cmd = ('progname', '-arg1', ...);

my $pid = open my $fh, '-|', @cmd  // die "Can't open \"@cmd\": $!";

...

my $num_signaled = kill 15, $pid;

This sketch needs some checks added.  Please see the linked documentation (look for "pipe").

If this isn't suitable for some reason -- perhaps you need the shell to run that program -- then you can find the program's pid,  and Proc::ProcessTable module is good for this.  A basic demo

use Proc::ProcessTable;

my $prog_name = ...

my $pid;
my $pt = Proc::ProcessTable->new();

foreach my $proc (@{$pt->table}) {
    if ($proc->cmndline =~ /\Q$prog_name/) {  # is this enough to identify it?
        $pid = $proc->pid;
        last;
    }
}
my $num_signaled = kill 15, $pid;

Please be careful with identifying the program by its name -- on a modern system there may be all kinds of processes running that contain the name of the program you want to terminate.  For more detail and discussion please see this post and this post, for starters.

Finally, you can use a module to run your external programs and then you'll be able to manage and control them far more nicely. Here I'd recommend IPC::Run.


问:
Define an array as having a mandatory value, plus optional others
I am trying to do something like this:

I have a Student type and Teacher type, they are similar, except that all teachers always have the "staffroom_access" privilege. Students can optionally have this privilege.

I've tried to do this as below with this line:

```<code>privileges: Role[] extends ["staffroom_access"]
</code>```

But this gives me:

```<code>Property 'privileges' of exported interface has or is using private name ''.(4033)
</code>```

Full code:

```<code>type Role = "staffroom_access" | "sportsroom_access";

type Teacher = {
    name: string;
    privileges: Role[] extends ["staffroom_access"]; //Property 'privileges' of exported interface has or is using private name ''.(4033)
}

type Student = {
    name: string;
    privileges: Role[];
}

const mrJones: Teacher = {
    name: "Mr Jones",
    privileges: [] //Should error
};

const mrSmith: Teacher = {
    name: "Mr Smith",
    privileges: ["staffroom_access"] //Should be Ok
};
</code>```

How would I achieve the functionality that I want?

答:
You can use rest elements in tuple types as follows:

```<code>type Teacher = {
    name: string;
    privileges: ["staffroom_access", ...Role[]];
}
</code>```

This will give you the exact behavior you want.

Body:
I am trying to do something like this:

I have a Student type and Teacher type, they are similar, except that all teachers always have the "staffroom_access" privilege. Students can optionally have this privilege.

I've tried to do this as below with this line:

privileges: Role[] extends ["staffroom_access"]

But this gives me:

Property 'privileges' of exported interface has or is using private name ''.(4033)

Full code:

type Role = "staffroom_access" | "sportsroom_access";

type Teacher = {
    name: string;
    privileges: Role[] extends ["staffroom_access"]; //Property 'privileges' of exported interface has or is using private name ''.(4033)
}

type Student = {
    name: string;
    privileges: Role[];
}

const mrJones: Teacher = {
    name: "Mr Jones",
    privileges: [] //Should error
};

const mrSmith: Teacher = {
    name: "Mr Smith",
    privileges: ["staffroom_access"] //Should be Ok
};

How would I achieve the functionality that I want?

Body:
You can use rest elements in tuple types as follows:

type Teacher = {
    name: string;
    privileges: ["staffroom_access", ...Role[]];
}

This will give you the exact behavior you want.


问:
How would you programmatically test a file for viruses?
I want to programmatically test a file for viruses.

I'm aware of this thread, which didn't get a satisfactory answer in my opinion, but I'm not looking for an API here. Any kind of workaround to make it possible to test a file would be fine.

Of course, an API would probably be the best solution (I'm using .net on a Windows platform), but maybe it's possible to drop the file in the folder, and to then check whether I can still open it or if it's been quarantined by the antivirus software.

Has someone run into the same sort of situation?

答: It really depends on which AV program you're going to use. Read the documentation for whatever solution you choose and you'll probably find a command-line interface or some other API you can call. There's no "generic" way of doing this (across AVs).</p>

OwnerDisplayName: Brann

LastEditorDisplayName: Svante

OwnerDisplayName: Assaf


问:
java out of memory then exit
I have a piece of software that has to analyze big files. Constraining the input or giving infinite memory is not an option, so I have to live with flying OOMEs. Because the OOME only kills the Thread, my software runs in some crappy state.

From outside everything looks okay because the process is running but on the inside it's braindead.

I would like to pull the plug on it. But how can I do this?

Catching a OOME does not guranteee that the next line of code will be executed. e.g System.exit(9). So the JVM has to notice OOME and destory itself.

Is their some vm option for this?

答:
So the JVM has to notice OOME and destroy itself.  Is their some vm option for this?

No there is not.

However, I have to question your assumption that you cannot catch an OutOfMemoryError and  and immediately call System.exit() in the exception handler.

In practice it should work.  The only potential problem is if you have called Runtime.setRunFinalizersOnExit(true) ... and even that is ignored if you exit with a non-zero exit status.

(The caveat about catching OOME's and other random Error exceptions is that the JVM may not be in a fit state to continue executing.  But calling System.exit(nonzero) ain't doing that!)

Title: java out of memory then exit


问:
How can I solve this strange error with SSH Task in Azure Pipeline
I'm trying to use the SSH deploy task in Azure devops, but I'm struggling to get it to work.

Steps:

I generated a ssh-key

The key is added to the server

(optional) tested key locally (works)

Created a Service connection in Azure Devops (with the private key data and the passfrase in the password field)

Allow the correct pipeline in Service connection security

Added the SSH task to the release pipeline.

Added an inline script.

Connection succeeds

It seems to connect but doesn't execute the commands. I've checked the /var/log/auth.log file on the server and that does show a successfull connection. The authentication log on the remote server does show a successfull authentication from devops, the connects lasts exactly the value set for the timeout.

Wrong order, logging shows commands then connected

In the logging it shows my second (docker-compose pull) and third command (docker-compose up -d) but not the first command. And the commands are shown before the trying to connect line. The first command isn't shown at all.

Did I make a mistake or is their something else going on?

Here is the logging of the task

```<code>2020-02-12T15:05:23.7258315Z ##[section]Starting: Run SSH
2020-02-12T15:05:23.8777631Z ==============================================================================
2020-02-12T15:05:23.8778469Z Task         : SSH
2020-02-12T15:05:23.8778560Z Description  : Run shell commands or a script on a remote machine using SSH
2020-02-12T15:05:23.8778657Z Version      : 0.151.1
2020-02-12T15:05:23.8778735Z Author       : Microsoft Corporation
2020-02-12T15:05:23.8778839Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/ssh
2020-02-12T15:05:23.8778953Z ==============================================================================
2020-02-12T15:05:24.5860676Z docker-compose pull
2020-02-12T15:05:24.5860824Z docker-compose up -d
2020-02-12T15:05:24.5861194Z Trying to establish an SSH connection to ***@my-server.domain.com:22
2020-02-12T15:05:25.4787782Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4789160Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4791265Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4791477Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792286Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792439Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792552Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792648Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792757Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792851Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792960Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4793055Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.7447781Z Successfully connected.
2020-02-12T15:05:25.7564295Z ##[error]Unhandled: Cannot parse privateKey: Unsupported key format
2020-02-12T15:09:23.7874932Z ##[error]The task has timed out.
2020-02-12T15:09:23.7877908Z ##[section]Finishing: Run SSH
</code>```

Task YAML

```<code>- task: SSH@0
  displayName: 'Run remote docker-compose commands'
  inputs:
    sshEndpoint: 'Endpoint name redacted'
    runOptions: inline
    inline: |
     cd ~/correct-folder/
     docker-compose pull
     docker-compose up -d
  timeoutInMinutes: 4

</code>```

I've tried both Windows and Ubuntu hosted agents.

Unrelated issues that show same error:

https://github.com/microsoft/azure-pipelines-tasks/issues/12147

Node Cipheriv Warning in Azure DevOps Extension - Release Task

Issue on with node https://github.com/nodejs/node/issues/16746

Same issue, with explaination

https://stackoverflow.com/a/55093077/639153

It seems like the Task library is calling the wrong node function, as "solved" in march '19.

答:
What about using private agent? Just try to run a simple command such like ipconfig and check the result.

Besides, according to the error message Unhandled: Cannot parse privateKey: Unsupported key format this seems a privateKey format issue.

So, please try to convert the existing key using ssh-keygen utility to the old PEM format and try it again to check if that works.

ssh-keygen -p -m PEM -f ~/.ssh/id_rsa

Body:
I'm trying to use the SSH deploy task in Azure devops, but I'm struggling to get it to work.

Steps:

I generated a ssh-key

The key is added to the server

(optional) tested key locally (works)

Created a Service connection in Azure Devops (with the private key data and the passfrase in the password field)

Allow the correct pipeline in Service connection security

Added the SSH task to the release pipeline.

Added an inline script.

Connection succeeds

It seems to connect but doesn't execute the commands. I've checked the /var/log/auth.log file on the server and that does show a successfull connection. The authentication log on the remote server does show a successfull authentication from devops, the connects lasts exactly the value set for the timeout.

Wrong order, logging shows commands then connected

In the logging it shows my second (docker-compose pull) and third command (docker-compose up -d) but not the first command. And the commands are shown before the trying to connect line. The first command isn't shown at all.

Did I make a mistake or is their something else going on?

Here is the logging of the task

2020-02-12T15:05:23.7258315Z ##[section]Starting: Run SSH
2020-02-12T15:05:23.8777631Z ==============================================================================
2020-02-12T15:05:23.8778469Z Task         : SSH
2020-02-12T15:05:23.8778560Z Description  : Run shell commands or a script on a remote machine using SSH
2020-02-12T15:05:23.8778657Z Version      : 0.151.1
2020-02-12T15:05:23.8778735Z Author       : Microsoft Corporation
2020-02-12T15:05:23.8778839Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/ssh
2020-02-12T15:05:23.8778953Z ==============================================================================
2020-02-12T15:05:24.5860676Z docker-compose pull
2020-02-12T15:05:24.5860824Z docker-compose up -d
2020-02-12T15:05:24.5861194Z Trying to establish an SSH connection to ***@my-server.domain.com:22
2020-02-12T15:05:25.4787782Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4789160Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4791265Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4791477Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792286Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792439Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792552Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792648Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792757Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792851Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4792960Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.4793055Z (node:4364) Warning: Use Cipheriv for counter mode of aes-256-ctr
2020-02-12T15:05:25.7447781Z Successfully connected.
2020-02-12T15:05:25.7564295Z ##[error]Unhandled: Cannot parse privateKey: Unsupported key format
2020-02-12T15:09:23.7874932Z ##[error]The task has timed out.
2020-02-12T15:09:23.7877908Z ##[section]Finishing: Run SSH

Task YAML

- task: SSH@0
  displayName: 'Run remote docker-compose commands'
  inputs:
    sshEndpoint: 'Endpoint name redacted'
    runOptions: inline
    inline: |
     cd ~/correct-folder/
     docker-compose pull
     docker-compose up -d
  timeoutInMinutes: 4

I've tried both Windows and Ubuntu hosted agents.

Unrelated issues that show same error:

https://github.com/microsoft/azure-pipelines-tasks/issues/12147

Node Cipheriv Warning in Azure DevOps Extension - Release Task

Issue on with node https://github.com/nodejs/node/issues/16746

Same issue, with explaination

https://stackoverflow.com/a/55093077/639153

It seems like the Task library is calling the wrong node function, as "solved" in march '19.


问:
How to create and update the value of Dynamic Widgets through Flutter Provider
So I am implementing something like below:

```<code>class TempProvider extends ChangeNotifier(){
    List<Widget> _list = <Widget>[];
    List<Widget get list => _list;
    int _count = 0;
    int get count => _count;

    Future<List<Widget>> getList() async{
        addToList(Text('$count'));

        List _result = await db....
        _result.forEach((_item){
            addToList(Button(
                onTap: () => increment();
                child: Text('Press'),
            ));
        });
    }

    addToList(Widget widget){
        _list.add(widget);
        notifyListeners();
    }

    increment(){
        _count += 1;
        notifyListeners();
    }
}

class Parent extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
        return FutureProvider(
        create: (context) => TempProvider().getList(),
        child: Child(),
        );
    }
}

class Child extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
    var futureProvider = Provider.of<List<Widget>>(context);

        return Container(
        child: futureProvider == null
            ? Text('Loading...'
            : ListView.builder(
                itemCount: futureProvider.length,
                itemBuilder: (BuildContext context, int index){
                    return futureProvider[index];
                }
            ),
        ));
    }
}
</code>```

Basically, what this does is that a List of Widgets from a Future is the content of ListView Builder that I have as its objects are generated from a database query. Those widgets are buttons that when pressed should update the "Count" value and should update the Text Widget displaying the latest "Count" value.

I was able to test the buttons and they seem to work and are incrementing the _count value via backend, however, the displayed "Count" on the Text Widget is not updating even if the Provider values are updated.

I'd like to ask for your help for what's wrong here, with my understanding, things should just update whenever the value changes, is this a Provider anti-pattern, do I have to rebuild the entire ListView, or I missed something else?

I'm still getting myself acquainted with this package and dart/flutter in general, hoping you can share me your expertise on this. Thank you very much in advance.

答:
so I have been on a lot of research and a lot of trial and errors last night and this morning, and I just accidentally bumped into an idea that worked!

You just have to have put the listening value on a consumer widget making sure it listens to the nearest Provider that we have already implemented higher in the widget tree. (Considering that I have already finished drawing my ListView builder below the FutureProvider Widget)

```<code>..getList() async{
    Consumer<ChallengeViewProvider>(
        builder: (_, foo, __) => Text(
            '${foo.count}',
        ),
    );

    List _result = await db....
    _result.forEach((_item){
        addToList(Button(
            onTap: () => increment();
            child: Text('Press'),
        ));
    });
}
</code>```

I have also refactored my widgets and pulled out the Button as a stateless widget for reuse. Though make sure that referenced Buttons are subscribed to the same parent provider having the Counter value and have the onTap property call out the increment() function through Provider<>.of

Hoping this will help anyone in the future!

Body:
So I am implementing something like below:

class TempProvider extends ChangeNotifier(){
    List<Widget> _list = <Widget>[];
    List<Widget get list => _list;
    int _count = 0;
    int get count => _count;

    Future<List<Widget>> getList() async{
        addToList(Text('$count'));

        List _result = await db....
        _result.forEach((_item){
            addToList(Button(
                onTap: () => increment();
                child: Text('Press'),
            ));
        });
    }

    addToList(Widget widget){
        _list.add(widget);
        notifyListeners();
    }

    increment(){
        _count += 1;
        notifyListeners();
    }
}

class Parent extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
        return FutureProvider(
        create: (context) => TempProvider().getList(),
        child: Child(),
        );
    }
}

class Child extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
    var futureProvider = Provider.of<List<Widget>>(context);

        return Container(
        child: futureProvider == null
            ? Text('Loading...'
            : ListView.builder(
                itemCount: futureProvider.length,
                itemBuilder: (BuildContext context, int index){
                    return futureProvider[index];
                }
            ),
        ));
    }
}

Basically, what this does is that a List of Widgets from a Future is the content of ListView Builder that I have as its objects are generated from a database query. Those widgets are buttons that when pressed should update the "Count" value and should update the Text Widget displaying the latest "Count" value.

I was able to test the buttons and they seem to work and are incrementing the _count value via backend, however, the displayed "Count" on the Text Widget is not updating even if the Provider values are updated.

I'd like to ask for your help for what's wrong here, with my understanding, things should just update whenever the value changes, is this a Provider anti-pattern, do I have to rebuild the entire ListView, or I missed something else?

I'm still getting myself acquainted with this package and dart/flutter in general, hoping you can share me your expertise on this. Thank you very much in advance.

Body:
so I have been on a lot of research and a lot of trial and errors last night and this morning, and I just accidentally bumped into an idea that worked!

You just have to have put the listening value on a consumer widget making sure it listens to the nearest Provider that we have already implemented higher in the widget tree. (Considering that I have already finished drawing my ListView builder below the FutureProvider Widget)

..getList() async{
    Consumer<ChallengeViewProvider>(
        builder: (_, foo, __) => Text(
            '${foo.count}',
        ),
    );

    List _result = await db....
    _result.forEach((_item){
        addToList(Button(
            onTap: () => increment();
            child: Text('Press'),
        ));
    });
}

I have also refactored my widgets and pulled out the Button as a stateless widget for reuse. Though make sure that referenced Buttons are subscribed to the same parent provider having the Counter value and have the onTap property call out the increment() function through Provider<>.of

Hoping this will help anyone in the future!


问:
Send dynamic object throught HTTP POST request in c#
I'm trying to send a dynamic object throught and HTTP POst request, but when I Receive that object, it is null.

I cannot USE JObject, cause I have a "virtual" api, and it does not accept JObjects.

I tried to send the type object and dynamic. Both of them do not work. Can some body help me ?

Here's my post request:

```<code>public static void Post(string uri, object parameter, string serviceName)
        {
            StringBuilder url = new StringBuilder();
            url.Append(uri);
            var client = GetClient(url.ToString(), 300, "application/json");
            var urlParameters = GetUrlParameters(new List<KeyValuePair<string, object>>() { });

            var response = client.PostAsync(
                urlParameters,
                new StringContent(
                    JsonConvert.SerializeObject(parameter).ToString(),
                    Encoding.UTF8,
                    "application/json")
                ).Result;

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
                throw new Exception($"{serviceName}: {response.StatusCode}");
        }
</code>```

Here is where i Receive that post:

Interce for method:

```<code> [OperationContract]
        [WebInvoke(Method = "POST",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Bare,
           UriTemplate = "Teste")]
        void Teste(object requestData);
</code>```

Method implemented in class( this is acctually where i get the data):

```<code>public void Teste(object requestData)
        {
            var teste = requestData;
            var t1 = JsonConvert.SerializeObject(requestData); // this returns {}; (empty)
        }
</code>```

答:
Can you tweak your POST a bit to troubleshoot the issue a bit more?  Something like the following? (not compiled)</p>

```<code>var rawJson = await client.PostAsync(
                urlParameters,
                new StringContent(
                    JsonConvert.SerializeObject(parameter).ToString(),
                    Encoding.UTF8,
                    "application/json")
                ).Content.ReadAsStringAsync();

var mappedObj = JsonConvert.DeserializeObject<T>(rawJson,
    new JsonSerializerSettings
    {
        Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
        {
            // convert this to your logger
            LogHelper.Instance.Warning(2000, string.Format("Failed object mapping: {0}\n{1}",
                args.ErrorContext.Error, rawJson));
            args.ErrorContext.Handled = true;
        },
        // set culture to mitigate mapping issues related to dates/numbers
        // https://stackoverflow.com/a/34529198
        Culture = CultureInfo.InvariantCulture
    });
</code>```

Body:
I'm trying to send a dynamic object throught and HTTP POst request, but when I Receive that object, it is null.

I cannot USE JObject, cause I have a "virtual" api, and it does not accept JObjects.

I tried to send the type object and dynamic. Both of them do not work. Can some body help me ?

Here's my post request:

public static void Post(string uri, object parameter, string serviceName)
        {
            StringBuilder url = new StringBuilder();
            url.Append(uri);
            var client = GetClient(url.ToString(), 300, "application/json");
            var urlParameters = GetUrlParameters(new List<KeyValuePair<string, object>>() { });

            var response = client.PostAsync(
                urlParameters,
                new StringContent(
                    JsonConvert.SerializeObject(parameter).ToString(),
                    Encoding.UTF8,
                    "application/json")
                ).Result;

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
                throw new Exception($"{serviceName}: {response.StatusCode}");
        }

Here is where i Receive that post:

Interce for method:

 [OperationContract]
        [WebInvoke(Method = "POST",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Bare,
           UriTemplate = "Teste")]
        void Teste(object requestData);

Method implemented in class( this is acctually where i get the data):

public void Teste(object requestData)
        {
            var teste = requestData;
            var t1 = JsonConvert.SerializeObject(requestData); // this returns {}; (empty)
        }

Body:
Can you tweak your POST a bit to troubleshoot the issue a bit more?  Something like the following? (not compiled)

var rawJson = await client.PostAsync(
                urlParameters,
                new StringContent(
                    JsonConvert.SerializeObject(parameter).ToString(),
                    Encoding.UTF8,
                    "application/json")
                ).Content.ReadAsStringAsync();

var mappedObj = JsonConvert.DeserializeObject<T>(rawJson,
    new JsonSerializerSettings
    {
        Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
        {
            // convert this to your logger
            LogHelper.Instance.Warning(2000, string.Format("Failed object mapping: {0}\n{1}",
                args.ErrorContext.Error, rawJson));
            args.ErrorContext.Handled = true;
        },
        // set culture to mitigate mapping issues related to dates/numbers
        // https://stackoverflow.com/a/34529198
        Culture = CultureInfo.InvariantCulture
    });


问:
filter file with numeric column
I have an excel file with the following structure

```<code>ColumnA  ColumnB
NA       NA
Coord    Value
(1,2,3)  -23
(4,5,6)  -56
</code>```

I need to do the following:

Filter out rows that only have a numeric column in Column B

Once I filter out the rows, I need to create 3 columns from Column A

So for the above, I need a data set that looks like

```<code>x   y   z   value
1   2   3   -23
4   5   6   -56
</code>```

For starters, when I import the dataset, all columns a 'chr' and I'm having trouble forcing Column B to be numeric

答:
The following is another approach. Your data is called foo. The two columns in foo are in character now. First, I get rows that contain numeric characters. Then, I used extract() to get numeric characters in ColumnA. The function can create three columns while it extracts the characters. Finally, I changed the column name (ColumnB) to value as you specified.

```<code>library(dplyr)
library(tidyr)

filter(foo, grepl(x = ColumnB, pattern = "\\d+")) %>%
extract(col = "ColumnA", into = c("x", "y", "z"),
        regex = "(\\d+),(\\d+),(\\d+)") %>%
rename(value = "ColumnB")

#  x y z value
#1 1 2 3   -23
#2 4 5 6   -56
</code>```

DATA

```<code>foo <- structure(list(ColumnA = c(NA, "Coord", "(1,2,3)", "(4,5,6)"),
ColumnB = c(NA, "Value", "-23", "-56")), class = "data.frame", row.names = c(NA,
-4L))
</code>```

Title: filter file with numeric column

Body:
I have an excel file with the following structure

ColumnA  ColumnB
NA       NA
Coord    Value
(1,2,3)  -23
(4,5,6)  -56

I need to do the following:

Filter out rows that only have a numeric column in Column B

Once I filter out the rows, I need to create 3 columns from Column A

So for the above, I need a data set that looks like

x   y   z   value
1   2   3   -23
4   5   6   -56

For starters, when I import the dataset, all columns a 'chr' and I'm having trouble forcing Column B to be numeric

Body:
The following is another approach. Your data is called foo. The two columns in foo are in character now. First, I get rows that contain numeric characters. Then, I used extract() to get numeric characters in ColumnA. The function can create three columns while it extracts the characters. Finally, I changed the column name (ColumnB) to value as you specified.

library(dplyr)
library(tidyr)

filter(foo, grepl(x = ColumnB, pattern = "\\d+")) %>%
extract(col = "ColumnA", into = c("x", "y", "z"),
        regex = "(\\d+),(\\d+),(\\d+)") %>%
rename(value = "ColumnB")

#  x y z value
#1 1 2 3   -23
#2 4 5 6   -56

DATA

foo <- structure(list(ColumnA = c(NA, "Coord", "(1,2,3)", "(4,5,6)"),
ColumnB = c(NA, "Value", "-23", "-56")), class = "data.frame", row.names = c(NA,
-4L))


问:
SQL Query Merge 2 Columns Into 1 Column By Eliminating Selected Value
I have a data like this:

How to merge the columns into one column without 110? Like this:

答:
Simply use case.  For your data, this seems to work:

```<code>select name,
       (case when credit_code = 110 then debit_code else credit_code end)
from t;
</code>```

If both could be 110, then you would want:

```<code>select name,
       (case when credit_code <> 110 then credit_code
             when debit_code <> 110 then debit_code
        end) as code
from t;
</code>```

Body:
Simply use case.  For your data, this seems to work:

select name,
       (case when credit_code = 110 then debit_code else credit_code end)
from t;

If both could be 110, then you would want:

select name,
       (case when credit_code <> 110 then credit_code
             when debit_code <> 110 then debit_code
        end) as code
from t;