问:
How do I digitally sign a pdf into a separate file on C#?
How do I digitally sign a pdf into a separate file on C#?
I have worked code with iText lib, but this is internal digital signature.
I want digital signature in separate hash file. So that you can check this digital signature later.
output like:
1. output.pdf
2. output.pdf.sig
This is possible? This is possible with iText?</p>

答:
The following demo code might get you started:</p>

```<code>static void Main(string[] args)
{
    var fileName = args[0];

    //  create signature
    DSACryptoServiceProvider signer = new DSACryptoServiceProvider();
    var bytes = ReadBytes(fileName);
    var signature = signer.SignData(bytes);
    var publicKey = signer.ToXmlString(false);

    //  we could write this signature to a separate file
    Console.WriteLine("Digital signature: " + Convert.ToBase64String(signature));

    //  verify signature
    DSACryptoServiceProvider verifier = new DSACryptoServiceProvider();

    verifier.FromXmlString(publicKey);

    if (verifier.VerifyData(bytes, signature))
        Console.WriteLine("Signature OK");
    else
        Console.WriteLine("Signature not OK");
}

static byte[] ReadBytes(string fileName)
{
    using (var file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    using (var reader = new BinaryReader(file))
    {
        return reader.ReadBytes((int)file.Length);
    }
}
</code>```

Body:
The following demo code might get you started:

static void Main(string[] args)
{
    var fileName = args[0];

    //  create signature
    DSACryptoServiceProvider signer = new DSACryptoServiceProvider();
    var bytes = ReadBytes(fileName);
    var signature = signer.SignData(bytes);
    var publicKey = signer.ToXmlString(false);

    //  we could write this signature to a separate file
    Console.WriteLine("Digital signature: " + Convert.ToBase64String(signature));

    //  verify signature
    DSACryptoServiceProvider verifier = new DSACryptoServiceProvider();

    verifier.FromXmlString(publicKey);

    if (verifier.VerifyData(bytes, signature))
        Console.WriteLine("Signature OK");
    else
        Console.WriteLine("Signature not OK");
}

static byte[] ReadBytes(string fileName)
{
    using (var file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    using (var reader = new BinaryReader(file))
    {
        return reader.ReadBytes((int)file.Length);
    }
}


来源: stackexchange

问:
is it possible to explain why this returns 21
Hello this isn't an assignment or anything but can you explain why this returns 2 1.</p>
```<code>#include <string>
using namespace std;
void fun(int);
int main()
{
    int a = 0;
    fun(a);
    return 0;
}

void fun(int n)
{
    if (n < 2)
    {
        fun(++n);
        cout << n<<" ";
    }
}
</code>```

答:
Flow of fun() :

You are passing a which is initialized to 0 as the parameter to the fun(). So, You call fun(0) from main().

In the call fun(0) the condition n<2 is true since at the start, it is 0. So the function fun(0) will
call fun(++n),that is fun(1) and push the current function call on the stack. Notice, the value of n in the function call which is pushed has increased to 1.

Again, n<2 evaluates to true since now the value of n is 1. The
function will call fun(++n) again, that is fun(2) and push the current function call to stack once again.Notice, the value of n in the function call which is pushed has increased to 2.

Now, the value of n is 2 and hence n<2 evaluates to false. So,
this time it will not do anything and just terminate

Now, the last function call will get popped from stack and cout will get executed. So, the control returns to the function at the top of the stack, which in our case is fun(1). But, here we had increased our n by doing ++n (Check point : 3). So the value printed will be 2. This function call now gets terminated.

Now, at the top of stack is the function call that we pushed at first, that is fun(0) but our value of n was increased by ++n (Check point : 2). So now the value of n which is 1 will be printed.

Hope you understand the above explanation and this solves your doubt !

ContentLicense: CC BY-SA 4.0

Body:
Hello this isn't an assignment or anything but can you explain why this returns 2 1.

#include <string>
using namespace std;
void fun(int);
int main()
{
    int a = 0;
    fun(a);
    return 0;
}

void fun(int n)
{
    if (n < 2)
    {
        fun(++n);
        cout << n<<" ";
    }
}


问:
Selenium : Click on a link inside a div
I'm learning selenium and I'm trying a simple thing : click on the first result of a search on wikipedia.

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PATH = "chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://en.wikipedia.org")

# Input in the search bar
search = driver.find_element_by_id("searchInput")
search.send_keys("python", Keys.RETURN)

wait = WebDriverWait(driver, 10)
first_result = wait.until(
    EC.presence_of_element_located((By.CLASS_NAME, "mw-search-result-heading"))
)

first_result.click()
</code>```

So i'm able to select the heading of the first result. But I can't click on it.
I think it's because I'm clicking on the
 containing the link, rather than the actual link. Here is a snippet of the HTML :

How can I target the actual  link, without it having any class name, id or name ?

答:
To click on link Python (langage) induce WebDriverWait() and wait for element_to_be_clickable() and use either css selector or xpath or link_text

CSS Selector:

```<code>driver.get("https://en.wikipedia.org")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"searchInput"))).send_keys("python", Keys.RETURN)
first_result = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[title='Python (langage)']")))
first_result.click()
</code>```

Xpath:

```<code>driver.get("https://en.wikipedia.org")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"searchInput"))).send_keys("python", Keys.RETURN)
first_result = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH, "//a[@title='Python (langage)']")))
first_result.click()
</code>```

LINK_TEXT:

```<code>driver.get("https://en.wikipedia.org")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"searchInput"))).send_keys("python", Keys.RETURN)
first_result = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Python (langage)")))
first_result.click()
</code>```

Title: Selenium : Click on a link inside a div

Body:
I'm learning selenium and I'm trying a simple thing : click on the first result of a search on wikipedia.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PATH = "chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://en.wikipedia.org")

# Input in the search bar
search = driver.find_element_by_id("searchInput")
search.send_keys("python", Keys.RETURN)

wait = WebDriverWait(driver, 10)
first_result = wait.until(
    EC.presence_of_element_located((By.CLASS_NAME, "mw-search-result-heading"))
)

first_result.click()

So i'm able to select the heading of the first result. But I can't click on it.
I think it's because I'm clicking on the
 containing the link, rather than the actual link. Here is a snippet of the HTML :

How can I target the actual  link, without it having any class name, id or name ?

Body:
To click on link Python (langage) induce WebDriverWait() and wait for element_to_be_clickable() and use either css selector or xpath or link_text

CSS Selector:

driver.get("https://en.wikipedia.org")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"searchInput"))).send_keys("python", Keys.RETURN)
first_result = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[title='Python (langage)']")))
first_result.click()

Xpath:

driver.get("https://en.wikipedia.org")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"searchInput"))).send_keys("python", Keys.RETURN)
first_result = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH, "//a[@title='Python (langage)']")))
first_result.click()

LINK_TEXT:

driver.get("https://en.wikipedia.org")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"searchInput"))).send_keys("python", Keys.RETURN)
first_result = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Python (langage)")))
first_result.click()


问:
java reflection issue
I have this code:

```<code>public static final <TypeVO extends BaseVo> List<SelectItem> populateSelectBoxForType(
            final Class<TypeVO> voClass, final String fieldName) {
        List<SelectItem> listSelectBox = null;
        final List<TypeVO> vosList = GenericEjbProxyFactory
                .getGenericTopValueObjectProxy(voClass)
                .getAllValueObjects(null);
        System.out.println("loaded vosList!!!!");
        if (vosList != null) {
            listSelectBox = new ArrayList<SelectItem>();
            for (final TypeVO currVo : vosList) {
                listSelectBox.add(new SelectItem(currVo.getInternalId(), currVo.getName()));
            }
        }
        return listSelectBox;
    }
</code>```

As you see here, I'm using currVo.getName because always, currVo has a name property.

I want to be able to use also other fields from this currVo which has type as voClass, but not all currVo classes will contain this field so I have to use reflection to identify these getField method, something like:

```<code>for (final TypeVO currVo : vosList) {
                for (final Method m : voClass.getMethods()) {
                    if (m.getName().contains(fieldName)) {
                        listSelectBox.add(new SelectItem(
                                currVo.getInternalId(), currVo.m));
                    }
                }
            }
</code>```

What I do not know is HOW I can use that specific method's value when I find it, exactly like currVo.getName (because, of course, currVo.m is wrong)?

Eg: If fieldName is "Age" I want to put in the list: currVo.getAge()... I am simply blocked here...

答:
Use reflection to get the getFieldName method and invoke it, as follows:

```<code> Method method = voClass.getMethod("get" + fieldName); // the getter with no params in the signature
 Object value = method.invoke(currVo}); // invoke with no params
 listSelectBox.add(new SelectItem(currVo.getInternalId(), value));
</code>```

Note: This assumes that fieldName is leading uppercase, eg "Value", not "value", so prepending it with "get" gives the exact method name, eg "getValue"

ContentLicense: CC BY-SA 3.0

Title: java reflection issue

Body:
I have this code:

public static final <TypeVO extends BaseVo> List<SelectItem> populateSelectBoxForType(
            final Class<TypeVO> voClass, final String fieldName) {
        List<SelectItem> listSelectBox = null;
        final List<TypeVO> vosList = GenericEjbProxyFactory
                .getGenericTopValueObjectProxy(voClass)
                .getAllValueObjects(null);
        System.out.println("loaded vosList!!!!");
        if (vosList != null) {
            listSelectBox = new ArrayList<SelectItem>();
            for (final TypeVO currVo : vosList) {
                listSelectBox.add(new SelectItem(currVo.getInternalId(), currVo.getName()));
            }
        }
        return listSelectBox;
    }

As you see here, I'm using currVo.getName because always, currVo has a name property.

I want to be able to use also other fields from this currVo which has type as voClass, but not all currVo classes will contain this field so I have to use reflection to identify these getField method, something like:

for (final TypeVO currVo : vosList) {
                for (final Method m : voClass.getMethods()) {
                    if (m.getName().contains(fieldName)) {
                        listSelectBox.add(new SelectItem(
                                currVo.getInternalId(), currVo.m));
                    }
                }
            }

What I do not know is HOW I can use that specific method's value when I find it, exactly like currVo.getName (because, of course, currVo.m is wrong)?

Eg: If fieldName is "Age" I want to put in the list: currVo.getAge()... I am simply blocked here...

Body:
Use reflection to get the getFieldName method and invoke it, as follows:

 Method method = voClass.getMethod("get" + fieldName); // the getter with no params in the signature
 Object value = method.invoke(currVo}); // invoke with no params
 listSelectBox.add(new SelectItem(currVo.getInternalId(), value));

Note: This assumes that fieldName is leading uppercase, eg "Value", not "value", so prepending it with "get" gives the exact method name, eg "getValue"


问:
Realtime search against only 1 column in Mysql - without any plugins
However I found some threads about this, but nothing fits to my case.

I have a search field in my mobile app, where after text change, the real time search is running via calling my API.

The search request starts only if there are 3 or more characters entered and is searching ONLY in 1 DB column, called TITLE. So each time the user enters a letter, a query is searching for it.

Currently I have it like this (I know this solution is very bad). $searchedword is the word user entered:

```<code>if (!empty($searchedword)&&strlen($searchedword)>2 ) {$searchedword=strtolower($searchedword);

$sql = "SELECT  * FROM TABLE ";$result = $mysqli->query($sql); $output='';
  if ($result->num_rows > 0) {
while($data=$result->fetch_array()) {
      $title=strtolower($data['title']);$content=$data['content'];
if (strpos($title,$searchedword) !== false ) {$output.=$title.','.$content;}
}}
</code>```

So this just checks, if the title from DB contains the searched word. This works very well, but I think it is very bad according to performance, because each time the user enters a letter to the search field, each time all the data from the table are queried and looked for that word.

I want to recreate my code to meet the best performance.

So my first question is, should I add a FULLTEXT INDEX to the TITLE column in DB, will it help or will it just increase the disk space? As I am just searching against 1 column and in this column is just a title (1 or 2 words max).

And second question, what should be the best query for my case and of course with the best performance? As I need to search after each letter which user enters.

Can I use the search this way?

```<code> SELECT * FROM TABLE WHERE MATCH (title) AGAINST ('$searchedword' IN NATURAL LANGUAGE MODE)
</code>```

However it seems, this will return only if the word completely matches the title, but returns nothing when the word is part of the title, so it is not a good solution.

The only solution which works is this:

```<code>SELECT * FROM TABLE WHERE title LIKE '%$searchedword%'  "
</code>```

but what about performance? And I don't understand how this works, because searchedword are converted to lowercase and I have removed the accents from that word, and the TITLE column in DB has accents and also Uppercase, but this search works very well!

答:
If your title column has a collation like utfmb4_general_ci, you don't have to worry about dealing with upper case, lower case, and diacritical marks in your MySQL WHERE clauses. MySQL will do it for you. It is really good at handling character sets and collations in all kinds of languages.  (Such things are very helpful to Swedish-language users, and the inventors of MySQL are Swedish.)

FULLTEXT with NATURAL LANGUAGE MODE is probably not the right approach for this application.  It works on words, not chunks of letters. So it probably won't give you anything until your user has typed a whole word, and not a stop word. And, it is a little squirrely when you search a table with only a few rows.  So, that might be a problem if you're just getting started.

It does order the results by the closeness of the match, so the most likely hit is the first one. So, if you know you have a phrase to search, it's good.

For your progressive-search application you may want to use one of these two LIKE queries.

```<code>SELECT title FROM tbl WHERE title LIKE CONCAT('$searchedword', '%') /*insecure*/
</code>```

or this one which is much slower but finds your partial match anywhere in the title, not just at the beginning.

```<code>SELECT title FROM tbl WHERE title LIKE CONCAT('%', '$searchedword', '%') /*insecure*/
</code>```

Avoid running these queries until you have gathered at least a few letters from your user, otherwise you'll get absurdly many results.

In these cases say SELECT title not SELECT *, and create an ordinary index on the title column. That way MySQL can satisfy the whole query from the index, which will make it much faster.

And, use MySQL's WHERE functionality to do the matching. Don't fetch the whole table from MySQL and search it in your php program.

And, use prepared statements. Because cybercreeps.

Body:
However I found some threads about this, but nothing fits to my case.

I have a search field in my mobile app, where after text change, the real time search is running via calling my API.

The search request starts only if there are 3 or more characters entered and is searching ONLY in 1 DB column, called TITLE. So each time the user enters a letter, a query is searching for it.

Currently I have it like this (I know this solution is very bad). $searchedword is the word user entered:

if (!empty($searchedword)&&strlen($searchedword)>2 ) {$searchedword=strtolower($searchedword);

$sql = "SELECT  * FROM TABLE ";$result = $mysqli->query($sql); $output='';
  if ($result->num_rows > 0) {
while($data=$result->fetch_array()) {
      $title=strtolower($data['title']);$content=$data['content'];
if (strpos($title,$searchedword) !== false ) {$output.=$title.','.$content;}
}}

So this just checks, if the title from DB contains the searched word. This works very well, but I think it is very bad according to performance, because each time the user enters a letter to the search field, each time all the data from the table are queried and looked for that word.

I want to recreate my code to meet the best performance.

So my first question is, should I add a FULLTEXT INDEX to the TITLE column in DB, will it help or will it just increase the disk space? As I am just searching against 1 column and in this column is just a title (1 or 2 words max).

And second question, what should be the best query for my case and of course with the best performance? As I need to search after each letter which user enters.

Can I use the search this way?

 SELECT * FROM TABLE WHERE MATCH (title) AGAINST ('$searchedword' IN NATURAL LANGUAGE MODE)

However it seems, this will return only if the word completely matches the title, but returns nothing when the word is part of the title, so it is not a good solution.

The only solution which works is this:

SELECT * FROM TABLE WHERE title LIKE '%$searchedword%'  "

but what about performance? And I don't understand how this works, because searchedword are converted to lowercase and I have removed the accents from that word, and the TITLE column in DB has accents and also Uppercase, but this search works very well!

Body:
If your title column has a collation like utfmb4_general_ci, you don't have to worry about dealing with upper case, lower case, and diacritical marks in your MySQL WHERE clauses. MySQL will do it for you. It is really good at handling character sets and collations in all kinds of languages.  (Such things are very helpful to Swedish-language users, and the inventors of MySQL are Swedish.)

FULLTEXT with NATURAL LANGUAGE MODE is probably not the right approach for this application.  It works on words, not chunks of letters. So it probably won't give you anything until your user has typed a whole word, and not a stop word. And, it is a little squirrely when you search a table with only a few rows.  So, that might be a problem if you're just getting started.

It does order the results by the closeness of the match, so the most likely hit is the first one. So, if you know you have a phrase to search, it's good.

For your progressive-search application you may want to use one of these two LIKE queries.

SELECT title FROM tbl WHERE title LIKE CONCAT('$searchedword', '%') /*insecure*/

or this one which is much slower but finds your partial match anywhere in the title, not just at the beginning.

SELECT title FROM tbl WHERE title LIKE CONCAT('%', '$searchedword', '%') /*insecure*/

Avoid running these queries until you have gathered at least a few letters from your user, otherwise you'll get absurdly many results.

In these cases say SELECT title not SELECT *, and create an ordinary index on the title column. That way MySQL can satisfy the whole query from the index, which will make it much faster.

And, use MySQL's WHERE functionality to do the matching. Don't fetch the whole table from MySQL and search it in your php program.

And, use prepared statements. Because cybercreeps.


Title: Pandas: Extract date from unconventional timestamp -- YYY/MM/DD:HH:MM:SS AM

Body:
I have data in the following format:

d = {'Name': ['bob', 'george'], 'date1': ['2014/05/12:12:00:00 AM', '2014/05/15:12:00:00 AM'], 'date2': ['2014/08/31:11:59:59 PM', '2014/08/12:11:59:59 PM']}
df = pd.DataFrame(data=d)

   Name                   date1                   date2
0     bob  2014/05/12:12:00:00 AM  2014/08/31:11:59:59 PM
1  george  2014/05/15:12:00:00 AM  2014/08/12:11:59:59 PM

How do I manipute the two date columns to get the following format?

Expected output:

     Name       date1       date2
0     bob  2014-05-12  2014-08-31
1  george  2014-05-15  2014-08-12

Body:
Try this:

d = {'Name': ['bob', 'george'], 'date1': ['2014/05/12:12:00:00 AM', '2014/05/15:12:00:00 AM'], 'date2': ['2014/08/31:11:59:59 PM', '2014/08/12:11:59:59 PM']}
df = pd.DataFrame(data=d)
df['date1'] = pd.to_datetime(df['date1'], format='%Y/%m/%d:%H:%M:%S %p').dt.date
df['date2'] = pd.to_datetime(df['date2'], format='%Y/%m/%d:%H:%M:%S %p').dt.date
print(df)

     Name       date1       date2
0     bob  2014-05-12  2014-08-31
1  george  2014-05-15  2014-08-12


问:
When and why would I want to use i8 instead of i32?
I think the default size in rust is 32 bits, signed, when assigning a variable to an integer value.

Provided I'm dealing with a value that fits in 16 bits (e.g 15000) or even 8 bits (e.g 120), why would I want to NOT still just use the default?

I'd probably be saving some memory - but is this worth the consideration?
And is there any speed advantage?
What else, if anything?

答:
In cases such as an embedded system, a data transfer protocol or anything else where the net storage and transfer of data is a main concern, using i8 and i16 and such others is a really good idea. Also, the compiler rearranges struct fields to make the struct more compact, which it can do more efficiently when the fields are smaller.

But for the general case, so whenever as you say, you have values that always fit in 16 or 8 bits... I'm not sure there's a clear-cut answer. I would say that the speed at least would end up being architecture-dependent.

User trentcl has just linked to this post over at the Discourse forums, which I think illustrates many points of view regarding the general case.


问:
how to remove a project from coverity-scan
I've registered a project with coverity-scan in the past.

I would now like to remove that project from coverity-scan (or at least from my dashboard; but preferrably i'd like to remove the project entirely).

I'm stuck as there seems to be no such option in the web-interface. am i missing something?

答: The Delete Your Project button is only available to the administrator of a project and only if a build has not yet been submitted for analysis.</p>


问:
SurfaceView display size is half for portrait
I have created simple android application to test the camera functionality. When I set the display orientation to 'portrait', it open the camera in half of the screen on version 2.1. my requirement is to open the camera on full screen.</p>

答:
```<code>Intent i8 = new Intent("android.media.action.IMAGE_CAPTURE");
activity.startActivity(i8);
</code>```


问:
How can I destroy an object after X seconds?
The problem is in that way it will create more and more objects if automatic or if using the mouse.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScifiEffects : MonoBehaviour
{
    public GameObject spawnEffect;
    public bool automaticFire = false;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (automaticFire == false)
        {
            if (Input.GetMouseButtonDown(0))
            {
                GameObject effect = Instantiate(spawnEffect, transform.position, Quaternion.FromToRotation(Vector3.up, spawnEffect.transform.forward)) as GameObject;
            }
        }
        else
        {
            GameObject effect = Instantiate(spawnEffect, transform.position, Quaternion.FromToRotation(Vector3.up, spawnEffect.transform.forward)) as GameObject;
        }
    }
}
</code>```

If I add :

```<code>Destroy(effect);
</code>```

Either in the mouse or if automatic the gameobject will be destroy at once and the effect will not happen. I could use a coroutine but then I will have to call the StartCoroutine inside the Update either if automatic or not and it will start many coroutines.

答: You can add Thread.Sleep(miliseconds); to wait before it happens. You could also make a Task which sleeps for a while and then does the delete, make sure to await it.

Body:
The problem is in that way it will create more and more objects if automatic or if using the mouse.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScifiEffects : MonoBehaviour
{
    public GameObject spawnEffect;
    public bool automaticFire = false;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (automaticFire == false)
        {
            if (Input.GetMouseButtonDown(0))
            {
                GameObject effect = Instantiate(spawnEffect, transform.position, Quaternion.FromToRotation(Vector3.up, spawnEffect.transform.forward)) as GameObject;
            }
        }
        else
        {
            GameObject effect = Instantiate(spawnEffect, transform.position, Quaternion.FromToRotation(Vector3.up, spawnEffect.transform.forward)) as GameObject;
        }
    }
}

If I add :

Destroy(effect);

Either in the mouse or if automatic the gameobject will be destroy at once and the effect will not happen. I could use a coroutine but then I will have to call the StartCoroutine inside the Update either if automatic or not and it will start many coroutines.


问:
LinkedIn social share url with parameter not possible because of redirect
I've got some question about the linkedin api regarding the share link for social media.
The api (https://developer.linkedin.com/docs/share-on-linkedin) shows, disregarding the url parameter, further parameters like title or summary.
But if i call the url, for instance from the doc:
https://www.linkedin.com/shareArticle?mini=true&url=http://developer.linkedin.com&title=LinkedIn%20Developer%20Network
&summary=My%20favorite%20developer%20program&source=LinkedIn

it redirects to
https://www.linkedin.com/sharing/share-offsite/?url=http%3A%2F%2Fdeveloper.linkedin.com
but without parameter..

Is it a change in the linkedin api or a temporary issue? Or do I have a problem in my understanding?

Best regards
Richard

答:
Much has changed with LinkedIn since it was purchased by Microsoft.  What you had used to work for title, etc., but no longer.  This is the only available format you're allowed to use...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Source: Official LinkedIn Sharing Documentation.

The only way to have a preview of your title, image, etc., is to use og: tags.  Insert these within the  block of your HTML...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

And, if you want to be sure that you did everything right, insert your website's URL into LinkedIn Post Inspector.

Body:
Much has changed with LinkedIn since it was purchased by Microsoft.  What you had used to work for title, etc., but no longer.  This is the only available format you're allowed to use...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Official LinkedIn Sharing Documentation.

The only way to have a preview of your title, image, etc., is to use og: tags.  Insert these within the <head> block of your HTML...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

And, if you want to be sure that you did everything right, insert your website's URL into LinkedIn Post Inspector.


答:
Use pandas.to_datetime with the format argument:

```<code>df['date1'] = pandas.to_datetime(df['date1'], format='%Y/%m/%d:%H:%M:%S %p')
</code>```

Pandas documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

Formatting documentation: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

Body:
Use pandas.to_datetime with the format argument:

df['date1'] = pandas.to_datetime(df['date1'], format='%Y/%m/%d:%H:%M:%S %p')

Pandas documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

Formatting documentation: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior


问:
Is there any way to emulate inline let expressions in JavaScript?
I'm writing a compiler from a functional language to JavaScript. Since my language is based on expressions, it is natural to compile it to a JavaScript expression too. The problem is that when compiling let expressions, we need the ability to declare and assign variables "inline". For example:

```<code>function foo(x) {
  return (let y = x * x; y);
}
</code>```

This code, obviously, doesn't work since we can't use let inside expressions. One solution would be to wrap everything inside a lambda:

```<code>function foo(x) {
  return (()=>{let y = x*x; return y})();
}
</code>```

But this has a significant runtime cost in some cases. The other alternative would be to just adjust the compiler to produce statements instead of expressions, but this would be a non-trivial change and I'd rather avoid it if possible.

Is there any way to declare and assign local variables to JavaScript as an expression rather than a statement that has no extra runtime costs?

答:
Is there any way to declare and assign local variables to JavaScript as an expression rather than a statement that has no extra runtime costs?

Not really, but you can use eval() with the comma operator. I know, I know, eval() is evil, but it's the only way to declare local variables in an expression (AFAIK), though I wouldn't recommend it because engines don't optimize eval() calls.

function foo(x) {
  return (eval("var y"), y = x * x, y);
}
```

Edit: As Bergi pointed out, using let makes the variable local to the code inside executed using eval(), causing y = x * x to create a global variable named y. var should be used instead.

Body:
I'm writing a compiler from a functional language to JavaScript. Since my language is based on expressions, it is natural to compile it to a JavaScript expression too. The problem is that when compiling let expressions, we need the ability to declare and assign variables "inline". For example:

function foo(x) {
  return (let y = x * x; y);
}

This code, obviously, doesn't work since we can't use let inside expressions. One solution would be to wrap everything inside a lambda:

function foo(x) {
  return (()=>{let y = x*x; return y})();
}

But this has a significant runtime cost in some cases. The other alternative would be to just adjust the compiler to produce statements instead of expressions, but this would be a non-trivial change and I'd rather avoid it if possible.

Is there any way to declare and assign local variables to JavaScript as an expression rather than a statement that has no extra runtime costs?

Body:
Is there any way to declare and assign local variables to JavaScript as an expression rather than a statement that has no extra runtime costs?

Not really, but you can use eval() with the comma operator. I know, I know, eval() is evil, but it's the only way to declare local variables in an expression (AFAIK), though I wouldn't recommend it because engines don't optimize eval() calls.

function foo(x) {
  return (eval("var y"), y = x * x, y);
}

Edit: As Bergi pointed out, using let makes the variable local to the code inside executed using eval(), causing y = x * x to create a global variable named y. var should be used instead.


问:
How can I test css properties for a React component using react-testing-library?
The philosophy behind the react-testing-library makes sense to me, but I am struggling to apply it to css properties.

For example, let's say I have a simple toggle component that shows a different background color when clicked:

import React, { useState } from "react";
import "./Toggle.css";

const Toggle = () => {
  const [ selected, setSelected ] = useState(false);
  return (

 setSelected(!selected)}>
      {selected ? "On" : "Off"}

  );
}

export default Toggle;
```

<pre class="lang-css prettyprint-override"><code>.on {
  background-color: green;
}

.off {
  background-color: red;
}
</code>```

How should I test this component? I wrote the following test, which works for inline component styles, but fails when using css classes as shown above.

import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Toggle from "./Toggle";

const backgroundColor = (element) => window.getComputedStyle(element).backgroundColor;

describe("Toggle", () => {
  it("updates the background color when clicked",  () => {
    render(<Toggle />);
    fireEvent.click(screen.getByText("Off"));
    expect(backgroundColor(screen.getByText("On"))).toBe("green");
  });
});
```

答:
So that's not what unit or integration test frameworks do. They only test logic.

If you want to test styling then you need an end-to-end/snapshot testing framework like Selenium.

Body:
The philosophy behind the react-testing-library makes sense to me, but I am struggling to apply it to css properties.

For example, let's say I have a simple toggle component that shows a different background color when clicked:

import React, { useState } from "react";
import "./Toggle.css";

const Toggle = () => {
  const [ selected, setSelected ] = useState(false);
  return (

 setSelected(!selected)}>
      {selected ? "On" : "Off"}

  );
}

export default Toggle;

.on {
  background-color: green;
}

.off {
  background-color: red;
}

How should I test this component? I wrote the following test, which works for inline component styles, but fails when using css classes as shown above.

import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Toggle from "./Toggle";

const backgroundColor = (element) => window.getComputedStyle(element).backgroundColor;

describe("Toggle", () => {
  it("updates the background color when clicked",  () => {
    render(<Toggle />);
    fireEvent.click(screen.getByText("Off"));
    expect(backgroundColor(screen.getByText("On"))).toBe("green");
  });
});


问:
Node, React, with concurrently, EADDRINUSE :::8000 error
I'm trying to use the NPM package concurrently with a Node/Express server on the backend, and running create-react-app's server on the front end. Here is the package.json script:

```<code>"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"client": "yarn start --prefix client",
"dev": "concurrently \"yarn server\" \"yarn client\""
},
</code>```

When I execute yarn dev I get the following error:

```<code>$ concurrently "yarn server" "yarn client"
$ nodemon index.js
$ yarn start --prefix client
[0] [nodemon] 1.17.5
[0] [nodemon] to restart at any time, enter `rs`
[0] [nodemon] watching: *.*
[0] [nodemon] starting `node index.js`
$ node index.js --prefix client
[1] events.js:183
[1]       throw er; // Unhandled 'error' event
[1]       ^
[1]
[1] Error: listen EADDRINUSE :::8000
[1]     at Object._errnoException (util.js:1022:11)
[1]     at _exceptionWithHostPort (util.js:1044:20)
[1]     at Server.setupListenHandle [as _listen2] (net.js:1367:14)
[1]     at listenInCluster (net.js:1408:12)
[1]     at Server.listen (net.js:1492:7)
[1]     at Function.listen
...
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about
this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about
this command.
</code>```

When I use lsof -i tcp:8000 it returns nothing. I don't know what else to do. All help is appreciated.

Here is the server code:

```<code>const express = require('express');
const mongoose = require('mongoose');
const keys = require('./config/keys');
const cookieSession = require('cookie-session');
const passport = require('passport');
require('./models/User');
require('./services/passport');

mongoose.connect(keys.mongoURI);

const app = express();

// enable cookies
app.use(
  cookieSession({
    // cookie good for 30 days
    maxAge: 30 * 24 * 60 * 60 * 1000,
    // authenticate cookie
    keys: [keys.cookieKey]
  })
);
// tell passport to use cookies
app.use(passport.initialize());
app.use(passport.session());

// get the routes
require('./routes/authRoutes')(app);

const PORT = process.env.PORT || 5000;
app.listen(PORT);
</code>```

No matter what I change the PORT to, it gives the same error for that port.

答: In your package.json change the the client script to this <code>"client": "yarn --cwd client start"</code> it should work </p>

Body:
I'm trying to use the NPM package concurrently with a Node/Express server on the backend, and running create-react-app's server on the front end. Here is the package.json script:

"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"client": "yarn start --prefix client",
"dev": "concurrently \"yarn server\" \"yarn client\""
},

When I execute yarn dev I get the following error:

$ concurrently "yarn server" "yarn client"
$ nodemon index.js
$ yarn start --prefix client
[0] [nodemon] 1.17.5
[0] [nodemon] to restart at any time, enter `rs`
[0] [nodemon] watching: *.*
[0] [nodemon] starting `node index.js`
$ node index.js --prefix client
[1] events.js:183
[1]       throw er; // Unhandled 'error' event
[1]       ^
[1]
[1] Error: listen EADDRINUSE :::8000
[1]     at Object._errnoException (util.js:1022:11)
[1]     at _exceptionWithHostPort (util.js:1044:20)
[1]     at Server.setupListenHandle [as _listen2] (net.js:1367:14)
[1]     at listenInCluster (net.js:1408:12)
[1]     at Server.listen (net.js:1492:7)
[1]     at Function.listen
...
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about
this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about
this command.

When I use lsof -i tcp:8000 it returns nothing. I don't know what else to do. All help is appreciated.

Here is the server code:

const express = require('express');
const mongoose = require('mongoose');
const keys = require('./config/keys');
const cookieSession = require('cookie-session');
const passport = require('passport');
require('./models/User');
require('./services/passport');

mongoose.connect(keys.mongoURI);

const app = express();

// enable cookies
app.use(
  cookieSession({
    // cookie good for 30 days
    maxAge: 30 * 24 * 60 * 60 * 1000,
    // authenticate cookie
    keys: [keys.cookieKey]
  })
);
// tell passport to use cookies
app.use(passport.initialize());
app.use(passport.session());

// get the routes
require('./routes/authRoutes')(app);

const PORT = process.env.PORT || 5000;
app.listen(PORT);

No matter what I change the PORT to, it gives the same error for that port.

Body: In your package.json change the the client script to this "client": "yarn --cwd client start" it should work


问:
How to extract a portion of a datframe column and create another column with that extraction
I have a Pandas dataframe like this:

```<code>id        Month
 1     Month  01
 1     Month  05
 2     Month  12
...
</code>```

And I wanted to extract the value from the Month column and add that extraction to a new column  Month_no and obtain this output:

```<code>id         Month     Month_no
 1     Month  01            1
 1     Month  05            5
 2     Month  12           12
...
</code>```

答:
Alternatively:</p>

```<code>df['Month_no'] = df['Month'].str.strip('Month').astype(int)
</code>```

Body:
I have a Pandas dataframe like this:

id        Month
 1     Month  01
 1     Month  05
 2     Month  12
...

And I wanted to extract the value from the Month column and add that extraction to a new column  Month_no and obtain this output:

id         Month     Month_no
 1     Month  01            1
 1     Month  05            5
 2     Month  12           12
...

Body:
Alternatively:

df['Month_no'] = df['Month'].str.strip('Month').astype(int)


问:
CSS width of a  tag
I use  tags in my module titles,
e.g.

Categories.

I specify the span's background color/image, width and height in css.

But the span's width depends on its content/text.

So, if I do , with just a background image/color in css, nothing appears.

Of course, I want something to appear.

How can I resolve this?

答:
You can't specify the width of an element with display inline.  You could put something in it like a non-breaking space ( ) and then set the padding to give it some more width but you can't control it directly.

You could use display inline-block but that isn't widely supported.

A real hack would be to put an image inside and then set the width of that.  Something like a transparent 1 pixel GIF.  Not the recommended approach however.

ContentLicense: CC BY-SA 2.5

Title: CSS width of a <span> tag

OwnerDisplayName: cletus


问:
The model backing the <Database> context has changed since the database was created
The error message :

"The model backing the 'AddressBook' context has changed since the database was created.  Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance.  For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."

I am trying to use the code-first feature and following is what I wrote:

```<code>var modelBuilder = new ModelBuilder();
var model = modelBuilder.CreateModel();
using (AddressBook context = new AddressBook(model))
{
    var contact = new Contact
    {
        ContactID = 10000,
        FirstName = "Brian",
        LastName = "Lara",
        ModifiedDate = DateTime.Now,
        AddDate = DateTime.Now,
        Title = "Mr."

    };
    context.contacts.Add(contact);
    int result = context.SaveChanges();
    Console.WriteLine("Result :- "+ result.ToString());
}
</code>```

The context class:

```<code>public class AddressBook : DbContext
{
    public AddressBook()
    { }
    public AddressBook(DbModel AddressBook)
        : base(AddressBook)
    {

    }
    public DbSet<Contact> contacts { get; set; }
    public DbSet<Address> Addresses { get; set; }
}
</code>```

and the connection string:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
    <add name="AddressBook" providerName="System.Data.SqlClient"
         connectionString="Data Source=MyMachine;Initial Catalog=AddressBook;
         Integrated Security=True;MultipleActiveResultSets=True;"/>
    </connectionStrings>
</configuration>
</code>```

So, the database name is "AddressBook" and the error happens when I trying to add the contact object to the context. Am I missing anything here?

答:
Here's some information from Scott Gu's Blog posted by Jeff on what's actually taking place:

For those who are seeing this exception:

"The model backing the 'Production' context has changed since the
  database was created. Either manually delete/update the database, or
  call Database.SetInitializer with an IDatabaseInitializer instance."

Here is what is going on and what to do about it:

When a model is first created, we run a DatabaseInitializer to do
  things like create the database if it's not there or add seed data.
  The default DatabaseInitializer tries to compare the database schema
  needed to use the model with a hash of the schema stored in an
  EdmMetadata table that is created with a database (when Code First is
  the one creating the database). Existing databases won’t have the
  EdmMetadata table and so won’t have the hash…and the implementation
  today will throw if that table is missing. We'll work on changing this
  behavior before we ship the fial version since it is the default.
  Until then, existing databases do not generally need any database
  initializer so it can be turned off for your context type by calling:

```<code>Database.SetInitializer<YourDbContext>(null);
</code>```

Jeff

Body:
The error message :

"The model backing the 'AddressBook' context has changed since the database was created.  Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance.  For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."

I am trying to use the code-first feature and following is what I wrote:

var modelBuilder = new ModelBuilder();
var model = modelBuilder.CreateModel();
using (AddressBook context = new AddressBook(model))
{
    var contact = new Contact
    {
        ContactID = 10000,
        FirstName = "Brian",
        LastName = "Lara",
        ModifiedDate = DateTime.Now,
        AddDate = DateTime.Now,
        Title = "Mr."

    };
    context.contacts.Add(contact);
    int result = context.SaveChanges();
    Console.WriteLine("Result :- "+ result.ToString());
}

The context class:

public class AddressBook : DbContext
{
    public AddressBook()
    { }
    public AddressBook(DbModel AddressBook)
        : base(AddressBook)
    {

    }
    public DbSet<Contact> contacts { get; set; }
    public DbSet<Address> Addresses { get; set; }
}

and the connection string:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
    <add name="AddressBook" providerName="System.Data.SqlClient"
         connectionString="Data Source=MyMachine;Initial Catalog=AddressBook;
         Integrated Security=True;MultipleActiveResultSets=True;"/>
    </connectionStrings>
</configuration>

So, the database name is "AddressBook" and the error happens when I trying to add the contact object to the context. Am I missing anything here?

Body:
Here's some information from Scott Gu's Blog posted by Jeff on what's actually taking place:

For those who are seeing this exception:

"The model backing the 'Production' context has changed since the
  database was created. Either manually delete/update the database, or
  call Database.SetInitializer with an IDatabaseInitializer instance."

Here is what is going on and what to do about it:

When a model is first created, we run a DatabaseInitializer to do
  things like create the database if it's not there or add seed data.
  The default DatabaseInitializer tries to compare the database schema
  needed to use the model with a hash of the schema stored in an
  EdmMetadata table that is created with a database (when Code First is
  the one creating the database). Existing databases won’t have the
  EdmMetadata table and so won’t have the hash…and the implementation
  today will throw if that table is missing. We'll work on changing this
  behavior before we ship the fial version since it is the default.
  Until then, existing databases do not generally need any database
  initializer so it can be turned off for your context type by calling:

Database.SetInitializer<YourDbContext>(null);

Jeff


答:
Use pd.to_datetime with format:

```<code>In [1177]: df.date1 = pd.to_datetime(df.date1, format='%Y/%m/%d:%I:%M:%S %p').dt.date
In [1178]: df.date2 = pd.to_datetime(df.date2, format='%Y/%m/%d:%I:%M:%S %p').dt.date

In [1179]: df
Out[1179]:
     Name       date1       date2
0     bob  2014-05-12  2014-08-31
1  george  2014-05-15  2014-08-12
</code>```

Body:
Use pd.to_datetime with format:

In [1177]: df.date1 = pd.to_datetime(df.date1, format='%Y/%m/%d:%I:%M:%S %p').dt.date
In [1178]: df.date2 = pd.to_datetime(df.date2, format='%Y/%m/%d:%I:%M:%S %p').dt.date

In [1179]: df
Out[1179]:
     Name       date1       date2
0     bob  2014-05-12  2014-08-31
1  george  2014-05-15  2014-08-12


问:
How to edit user's profile view with django
I am making a form in which the user can edit their profile, so currentley I have 2 forms, one that edits the User model(first_name, Username and Email) and other one that edits the Profile model(biography). The problem is that everytime I edit, just the User model is the one that gets saved while the Profile model doesnt. I think that the error is on the views.py file.

views.py

```<code>    def edit_profile(request):
      if request.method == 'POST':
        form = EditProfileForm(request.POST, instance=request.user)
        form1 = UpdateProfileForm(request.POST, instance=request.user)
        if form.is_valid:
          form.save()
          form1.save()
          return redirect('profile')
      else:
        form = EditProfileForm(instance=request.user)
        form1 = UpdateProfileForm(instance=request.user)
        args = {
          'form': form,
          'form1': form1,
          }
        return render(request, 'profile-edit.html', args)
</code>```

forms.py

```<code>    class EditProfileForm(UserChangeForm):

      class Meta:
        model = User
        fields = (
          'first_name',
          'username',
          'email',
        )
        exclude = ('password',)

    class UpdateProfileForm(forms.ModelForm):

      class Meta:
        model = Profile
        fields = (
          'bio',
          'profile_pic',
        )
        exclude = ('user',)
</code>```

models.py

```<code>    class Profile(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE)
      bio = models.CharField(max_length=400, default=1)

      def __str__(self):
        return f'{self.user.username} Profile'
</code>```

profile-edit.html (I replaced the {{form.as_p}} and {{ form1.as_p }} to the following html code)

```<code>    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      <div class="edit-profile">
        <h3>Name</h3>
        <input type="text" name="first_name" value="{{ user.first_name }}" maxlength="30" id="id_first_name">
        <h3>Username</h3>
        <input type="text" name="username" value="{{ user.username }}" maxlength="150" required="" id="id_username">
        <h3>Bio</h3>
        <input type="text" name="bio" value="{{ user.profile.bio }}" maxlength="400" id="id_bio">
        <h3>Email</h3>
        <input type="email" name="email" value="{{ user.email }}" maxlength="254" id="id_email">
        <button type="submit">Submit</button>
      </div>
    </form>
</code>```

答:
I found the error on my code, i missed to pass the .profile from the model in the views.py file

Bad

```<code>    form1 = UpdateProfileForm(request.POST, instance=request.user)
</code>```

Good

```<code>    form1 = UpdateProfileForm(request.POST, instance=request.user.profile)
</code>```

Body:
I am making a form in which the user can edit their profile, so currentley I have 2 forms, one that edits the User model(first_name, Username and Email) and other one that edits the Profile model(biography). The problem is that everytime I edit, just the User model is the one that gets saved while the Profile model doesnt. I think that the error is on the views.py file.

views.py

    def edit_profile(request):
      if request.method == 'POST':
        form = EditProfileForm(request.POST, instance=request.user)
        form1 = UpdateProfileForm(request.POST, instance=request.user)
        if form.is_valid:
          form.save()
          form1.save()
          return redirect('profile')
      else:
        form = EditProfileForm(instance=request.user)
        form1 = UpdateProfileForm(instance=request.user)
        args = {
          'form': form,
          'form1': form1,
          }
        return render(request, 'profile-edit.html', args)

forms.py

    class EditProfileForm(UserChangeForm):

      class Meta:
        model = User
        fields = (
          'first_name',
          'username',
          'email',
        )
        exclude = ('password',)

    class UpdateProfileForm(forms.ModelForm):

      class Meta:
        model = Profile
        fields = (
          'bio',
          'profile_pic',
        )
        exclude = ('user',)

models.py

    class Profile(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE)
      bio = models.CharField(max_length=400, default=1)

      def __str__(self):
        return f'{self.user.username} Profile'

profile-edit.html (I replaced the {{form.as_p}} and {{ form1.as_p }} to the following html code)

    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}

Name

        <input type="text" name="first_name" value="{{ user.first_name }}" maxlength="30" id="id_first_name">

Username

        <input type="text" name="username" value="{{ user.username }}" maxlength="150" required="" id="id_username">

Bio

        <input type="text" name="bio" value="{{ user.profile.bio }}" maxlength="400" id="id_bio">

Email

        <input type="email" name="email" value="{{ user.email }}" maxlength="254" id="id_email">
        <button type="submit">Submit</button>

    </form>

Body:
I found the error on my code, i missed to pass the .profile from the model in the views.py file

Bad

    form1 = UpdateProfileForm(request.POST, instance=request.user)

Good

    form1 = UpdateProfileForm(request.POST, instance=request.user.profile)


问:
Convert "keyof GenericType" to string
I am trying to write an interface like this:

```<code>interface IGFilter<T> {
  [key: keyof T]: GQuery | IGFilter<T>,
  _NOT?: GQuery
}
</code>```

However I keep getting the error: An index signature parameter type must be either 'string' or 'number'.. Why is this? If keys can only be strings or numbers, then why does it think keyof T is not a string or number? Shouldn't keyof Type always result in string or number?

What is the correct way to make an interface that includes all properties of the generic interface type passed in?

答:
I think you're looking for this:

```<code>type IGFilter<T extends object> = {
  [K in keyof T]: GQuery | IGFilter<T>
} & {
  _NOT?: GQuery;
}
</code>```

Takeaways:

Restrict T to be of type object by doing T extends object

To iterate over keys of a generic type, use mapped types: { [K in keyof T]: ... }

When using index signatures (like { [key: string]: Foo }), all right-hand side properties must conform to the type Foo. If you want to mix properties of different kinds, use a type alias and intersect it with another type (as per my solution).

keyof T can be one of 3 things: string, number, or symbol

Title: Convert "keyof GenericType" to string

Body:
I am trying to write an interface like this:

interface IGFilter<T> {
  [key: keyof T]: GQuery | IGFilter<T>,
  _NOT?: GQuery
}

However I keep getting the error: An index signature parameter type must be either 'string' or 'number'.. Why is this? If keys can only be strings or numbers, then why does it think keyof T is not a string or number? Shouldn't keyof Type always result in string or number?

What is the correct way to make an interface that includes all properties of the generic interface type passed in?

Body:
I think you're looking for this:

type IGFilter<T extends object> = {
  [K in keyof T]: GQuery | IGFilter<T>
} & {
  _NOT?: GQuery;
}

Takeaways:

Restrict T to be of type object by doing T extends object

To iterate over keys of a generic type, use mapped types: { [K in keyof T]: ... }

When using index signatures (like { [key: string]: Foo }), all right-hand side properties must conform to the type Foo. If you want to mix properties of different kinds, use a type alias and intersect it with another type (as per my solution).

keyof T can be one of 3 things: string, number, or symbol


问:
Create my own authorization and authentication system in ASP.NET MVC
I'm working on an ASP.NET project, and i want to create and use my own authorization and authentication system to manage users (in a sql server database) like login, check authorization, and check authentication, i know in ASP.NET we have Identity but I want to create my own system.

so my question is do anyone have a good algorithm or a structure or just and idea for a custom system ?

Massive thanks in advance.

答: You could fork from Identity Server 4 and create your own implementation. They have a good base to build a solution from and has integration with many app types using OpenID and OAuth. https://identityserver4.readthedocs.io/en/latest/</p>


问:
Does Fabric8io K8s java client support patch() or rollingupdate() using YAML snippets?
I am trying to program the patching/rolling upgrade of k8s apps by taking deployment snippets as input. I use patch() method to apply the snippet onto an existing deployment as part of rollingupdate using fabric8io's k8s client APIS.. Fabric8.io kubernetes-client version 4.10.1
I'm also using some loadYaml helper methods from kubernetes-api 3.0.12.

Here is my sample snippet - adminpatch.yaml file:

```<code>    kind: Deployment
    spec:
      strategy:
        type: RollingUpdate
        rollingUpdate:
          maxSurge: 1
          maxUnavailable: 0
      template:
        spec:
          containers:
            - name: ${PATCH_IMAGE_NAME}
              image: ${PATCH_IMAGE_URL}
              imagePullPolicy: Always
</code>```

I'm sending the above file content (with all the placeholders replaced) to patchDeployment() method as string.
Here is my call to fabric8 patch() method:

```<code>     public static String patchDeployment(String deploymentName, String namespace, String deploymentYaml) {
    try {
    Deployment deploymentSnippet = (Deployment) getK8sObject(deploymentYaml);
    if(deploymentSnippet instanceof Deployment) {
            logger.debug("Valid deployment object.");
    Deployment deployment = getK8sClient().apps().deployments().inNamespace(namespace).withName(deploymentName)
        .rolling().patch(deploymentSnippet);
    System.out.println(deployment.toString());
    return getLastConfig(deployment.getMetadata(), deployment);
    }
    } catch (Exception Ex) {
      Ex.printStackTrace();
    }
      return "Failed";
  }

</code>```

It throws the below exception:

```<code>> io.fabric8.kubernetes.client.KubernetesClientException: Failure
> executing: PATCH at:
> https://10.44.4.126:6443/apis/apps/v1/namespaces/default/deployments/patch-demo.
> Message: Deployment.apps "patch-demo" is invalid: spec.selector:
> Invalid value:
> v1.LabelSelector{MatchLabels:map[string]string{"app":"nginx",
> "deployment":"3470574ffdbd6e88d426a77dd951ed45"},
> MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: field is
> immutable. Received status: Status(apiVersion=v1, code=422,
> details=StatusDetails(causes=[StatusCause(field=spec.selector,
> message=Invalid value:
> v1.LabelSelector{MatchLabels:map[string]string{"app":"nginx",
> "deployment":"3470574ffdbd6e88d426a77dd951ed45"},
> MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: field is
> immutable, reason=FieldValueInvalid, additionalProperties={})],
> group=apps, kind=Deployment, name=patch-demo, retryAfterSeconds=null,
> uid=null, additionalProperties={}), kind=Status,
> message=Deployment.apps "patch-demo" is invalid: spec.selector:
> Invalid value:
> v1.LabelSelector{MatchLabels:map[string]string{"app":"nginx",
> "deployment":"3470574ffdbd6e88d426a77dd951ed45"},
> MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: field is
> immutable, metadata=ListMeta(_continue=null, remainingItemCount=null,
> resourceVersion=null, selfLink=null, additionalProperties={}),
> reason=Invalid, status=Failure, additionalProperties={}).

</code>```

I also tried the original snippet(with labels and selectors) with kubectl patch deployment <DEPLOYMENT_NAME>  -n <MY_NAMESPACE> --patch "$(cat adminpatch.yaml) and this applies the same snippet fine.

I could not get much documentation on fabric8io k8s client patch() java API. Any help will be appreciated.

答:
Here is the related bug in Fabric8io rolling API: https://github.com/fabric8io/kubernetes-client/issues/1868

As of now, one way I found to achieve patching with fabri8io APIs is to :

Get the running deployment object

add/replace containers in it with new containers

use the createOrReplace() API to redeploy the deployment object

But your patch understandably could be more than just an update to the containers field. In that case, processing each editable field becomes messy.

I went ahead with using the official K8s client's patchNamespacedDeployment() API to implement patching. https://github.com/kubernetes-client/java/blob/356109457499862a581a951a710cd808d0b9c622/examples/src/main/java/io/kubernetes/client/examples/PatchExample.java

Body:
I am trying to program the patching/rolling upgrade of k8s apps by taking deployment snippets as input. I use patch() method to apply the snippet onto an existing deployment as part of rollingupdate using fabric8io's k8s client APIS.. Fabric8.io kubernetes-client version 4.10.1
I'm also using some loadYaml helper methods from kubernetes-api 3.0.12.

Here is my sample snippet - adminpatch.yaml file:

    kind: Deployment
    spec:
      strategy:
        type: RollingUpdate
        rollingUpdate:
          maxSurge: 1
          maxUnavailable: 0
      template:
        spec:
          containers:
            - name: ${PATCH_IMAGE_NAME}
              image: ${PATCH_IMAGE_URL}
              imagePullPolicy: Always

I'm sending the above file content (with all the placeholders replaced) to patchDeployment() method as string.
Here is my call to fabric8 patch() method:

     public static String patchDeployment(String deploymentName, String namespace, String deploymentYaml) {
    try {
    Deployment deploymentSnippet = (Deployment) getK8sObject(deploymentYaml);
    if(deploymentSnippet instanceof Deployment) {
            logger.debug("Valid deployment object.");
    Deployment deployment = getK8sClient().apps().deployments().inNamespace(namespace).withName(deploymentName)
        .rolling().patch(deploymentSnippet);
    System.out.println(deployment.toString());
    return getLastConfig(deployment.getMetadata(), deployment);
    }
    } catch (Exception Ex) {
      Ex.printStackTrace();
    }
      return "Failed";
  }

It throws the below exception:

> io.fabric8.kubernetes.client.KubernetesClientException: Failure
> executing: PATCH at:
> https://10.44.4.126:6443/apis/apps/v1/namespaces/default/deployments/patch-demo.
> Message: Deployment.apps "patch-demo" is invalid: spec.selector:
> Invalid value:
> v1.LabelSelector{MatchLabels:map[string]string{"app":"nginx",
> "deployment":"3470574ffdbd6e88d426a77dd951ed45"},
> MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: field is
> immutable. Received status: Status(apiVersion=v1, code=422,
> details=StatusDetails(causes=[StatusCause(field=spec.selector,
> message=Invalid value:
> v1.LabelSelector{MatchLabels:map[string]string{"app":"nginx",
> "deployment":"3470574ffdbd6e88d426a77dd951ed45"},
> MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: field is
> immutable, reason=FieldValueInvalid, additionalProperties={})],
> group=apps, kind=Deployment, name=patch-demo, retryAfterSeconds=null,
> uid=null, additionalProperties={}), kind=Status,
> message=Deployment.apps "patch-demo" is invalid: spec.selector:
> Invalid value:
> v1.LabelSelector{MatchLabels:map[string]string{"app":"nginx",
> "deployment":"3470574ffdbd6e88d426a77dd951ed45"},
> MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: field is
> immutable, metadata=ListMeta(_continue=null, remainingItemCount=null,
> resourceVersion=null, selfLink=null, additionalProperties={}),
> reason=Invalid, status=Failure, additionalProperties={}).

I also tried the original snippet(with labels and selectors) with kubectl patch deployment <DEPLOYMENT_NAME>  -n <MY_NAMESPACE> --patch "$(cat adminpatch.yaml) and this applies the same snippet fine.

I could not get much documentation on fabric8io k8s client patch() java API. Any help will be appreciated.


问:
Multi-State Toggle Button
In the app I've been working on, I would like to have a multiple-state (in my case, three) toggle button, instead of the two that ToggleButton provides. I've tried to start my own that extends Button, following the CompoundButton source, but quite honestly reading over its source got a bit overwhelming.

Is there a way to do a three-state toggle button using just a selector xml or something, or perhaps another method I haven't thought of? I'm rather at a loss of how to do this.

答:
Chip is a very good native option.

```<code> <com.google.android.material.chip.ChipGroup
      android:id="@+id/chip_group"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:singleSelection="true">

      <com.google.android.material.chip.Chip
           android:id="@+id/first_chip"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:gravity="center"
           android:text="Todo"
           android:textAppearance="?android:attr/textAppearance"
           android:textColor="@color/black"
           android:checkable="true"
           style="@style/Widget.MaterialComponents.Chip.Choice"
           app:chipBackgroundColor="@color/colorAccent"/>

           <!-- Second Chip -->
           <!-- Third Chip -->

   </com.google.android.material.chip.ChipGroup>
</code>```

```<code>binding.chipGroup.setOnCheckedChangeListener { chipGroup, i ->
    when (i) {
        binding.firstChip -> {
            binding.firstChip.setChipBackgroundColorResource(R.color.colorAccent)
        }
        else -> {}
    }
}
binding.firstChip.isChecked = true  //default
</code>```

GL

Source

Title: Multi-State Toggle Button

Body:
Chip is a very good native option.

 <com.google.android.material.chip.ChipGroup
      android:id="@+id/chip_group"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:singleSelection="true">

      <com.google.android.material.chip.Chip
           android:id="@+id/first_chip"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:gravity="center"
           android:text="Todo"
           android:textAppearance="?android:attr/textAppearance"
           android:textColor="@color/black"
           android:checkable="true"
           style="@style/Widget.MaterialComponents.Chip.Choice"
           app:chipBackgroundColor="@color/colorAccent"/>

           <!-- Second Chip -->
           <!-- Third Chip -->

   </com.google.android.material.chip.ChipGroup>

binding.chipGroup.setOnCheckedChangeListener { chipGroup, i ->
    when (i) {
        binding.firstChip -> {
            binding.firstChip.setChipBackgroundColorResource(R.color.colorAccent)
        }
        else -> {}
    }
}
binding.firstChip.isChecked = true  //default

GL

Source