问:
How to mask string after first character
Let's say I have a string that consists of a person's name:

```<code>var name = "Jason, Bruno Mars";
</code>```

How do I mask the string with X for the name behind the comma and returns:

```<code>var name = "Jason, BXXXX MXXX";
</code>```

I have tried using the following methods but only front characters are masked:

```<code>string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}
</code>```

Anyone has a better idea of how can I achieve the same result in a more efficient way?

答:
```<code>static string MaskName(string name)
    {
        string maskedString = string.Empty;

        string[] names = name.Split(',');
        if (names.Length > 0)
        {
            maskedString = names[0] + ",";
        }
        if (names.Length > 1)
        {
            string[] arrName = names[1].Split(' ');
            foreach (string s in arrName)
            {
                if (s.Length > 0)
                    maskedString += " " + s[0].ToString().PadRight(s.Length, 'X');
            }
        }
        return maskedString;
    }
</code>```

Body:
Let's say I have a string that consists of a person's name:

var name = "Jason, Bruno Mars";

How do I mask the string with X for the name behind the comma and returns:

var name = "Jason, BXXXX MXXX";

I have tried using the following methods but only front characters are masked:

string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}

Anyone has a better idea of how can I achieve the same result in a more efficient way?


来源: stackexchange

问:
Read_Csv() not giving expected output ,After If i update any cell in csv
1) Creation of DF

```<code>import pandas as pd
li=[["10","Data","String","01249","0199"],["10","Data","String","",""]]
df=pd.DataFrame(li)
df.to_csv("Dummy.csv")
</code>```

2)Dummy.csv Looks like

```<code>   0   1     2     3   4
0 10 Data String 1249 199
1 10 Data String
</code>```

3) Tested this piece of code for clarification:

```<code>D=pd.read_csv(Dummy.csv,dtype=str)
print(D['3'])
</code>```

Gave Expected output:

```<code>0  01249
1   NAN
</code>```

4) I need to manually fill the empty cell in the 3rd and 4th column with value in before cell here say "01249" and "0199" by opening the csv in a excel.**Successfully changed and saved the Dummy.csv in excel.

5) So again i have validation.py file will open the dummy.csv to validate.So to read the csv and further process by following code same as 3rd step.

```<code>D=pd.read_csv(Dummy.csv,dtype=str)
print(D['3'])
</code>```

Its not my expected output:

```<code>0  1249
1  1249
</code>```

My expected output is:

```<code>0  01249
1  01249
</code>```

So it is some serious issue i cannot omit that leading zeros at front. you all can see that if i not edit that column in csv and tried to read with read_csv giving expected output in string dtype,If i update the cell with "01249" in csv,and tried to read with read_csv not giving expected output in same string dtype. I think excel changing that total column datatype to General, I doesn't what general means.

So at end, After updating the cells in csv also i need to get my expected output please, How can i do this.

Sorry for the long body, i need to clearly explain my all steps i have tried.

答:
It is an Excel issue as opposed to python.

Change the type of the whole column (by clicking on the column letter) to text instead of general.
General means that you are allowing Excel to guess the datatype, and since these are numbers it omits the leading zero.

ContentLicense: CC BY-SA 4.0

Body:
1) Creation of DF

import pandas as pd
li=[["10","Data","String","01249","0199"],["10","Data","String","",""]]
df=pd.DataFrame(li)
df.to_csv("Dummy.csv")

2)Dummy.csv Looks like

   0   1     2     3   4
0 10 Data String 1249 199
1 10 Data String

3) Tested this piece of code for clarification:

D=pd.read_csv(Dummy.csv,dtype=str)
print(D['3'])

Gave Expected output:

0  01249
1   NAN

4) I need to manually fill the empty cell in the 3rd and 4th column with value in before cell here say "01249" and "0199" by opening the csv in a excel.**Successfully changed and saved the Dummy.csv in excel.

5) So again i have validation.py file will open the dummy.csv to validate.So to read the csv and further process by following code same as 3rd step.

D=pd.read_csv(Dummy.csv,dtype=str)
print(D['3'])

Its not my expected output:

0  1249
1  1249

My expected output is:

0  01249
1  01249

So it is some serious issue i cannot omit that leading zeros at front. you all can see that if i not edit that column in csv and tried to read with read_csv giving expected output in string dtype,If i update the cell with "01249" in csv,and tried to read with read_csv not giving expected output in same string dtype. I think excel changing that total column datatype to General, I doesn't what general means.

So at end, After updating the cells in csv also i need to get my expected output please, How can i do this.

Sorry for the long body, i need to clearly explain my all steps i have tried.


问:
Why haven't we designed a computer to directly execute high level programming?
I always thought that computers nowadays are already programmed to directly execute high-level programming, but apparently not. Is there any specific reason why we haven't done that yet? Any cons of high-level programming.</p>

答:
I'm by no means a CS expert, but from my experience dealing with different layers of a computer system, layers of abstraction are very important to enable a collaborative development environment. For instance, when you want to implement a neural network, would you prefer implement everything manually, or use an existing library? Having different layers make systems more secure, debugging easier, and better specialization in development. One can specialize in a higher level API and don't have to worry about the lower level implementation.

When you say a computer that directly executes high-level language, keep in mind that any computer is still composed of transistors, meaning everything would still have to be translated into binary operations. Having a completely packaged system (from high-level directly to hardware) vs having a layered structure (write a high-level program and compile it to instruct the hardware) is much more inefficient.


问:
Why does the output differ when input "i" instead of "j" as the key in HashMap?
I am using 2 for loops as below to get the sum of the numbers in an int[]. getTotal() is suppose to give the sum of the values in array which are below 100. The sum is calculated by adding the values one by one until it exceeds hundred. When it exceeds hundred it starts again with the next value and adds one by one like before.

```<code>private static HashMap<Integer,Integer> getTotal(){
    int total = 0;
    HashMap<Integer,Integer> finalTotal = new HashMap<Integer, Integer>();
    for (int i = 0; i < array.length; i++) {
        total += array.get(i);
        for (int j = i+1; j < array.length; j++) {
            if(total>100){
                finalTotal.put(j,total - array.get(j));
                total = 0;
            }
            else if(total<100){
                total += array.get(j);
            }
        }
    }
    return finalTotal;
}
</code>```

When printing the result in the hash-map it gives 2 different maps of answers when I use i and j for as the key. Isn't it suppose to give the same values and just different keys as answers? Not only the value the amount length of the hashmap also changes.

It would be great if you could point out any mistakes and explain why this happens.

答: You need to define array before using it.

Body:
I am using 2 for loops as below to get the sum of the numbers in an int[]. getTotal() is suppose to give the sum of the values in array which are below 100. The sum is calculated by adding the values one by one until it exceeds hundred. When it exceeds hundred it starts again with the next value and adds one by one like before.

private static HashMap<Integer,Integer> getTotal(){
    int total = 0;
    HashMap<Integer,Integer> finalTotal = new HashMap<Integer, Integer>();
    for (int i = 0; i < array.length; i++) {
        total += array.get(i);
        for (int j = i+1; j < array.length; j++) {
            if(total>100){
                finalTotal.put(j,total - array.get(j));
                total = 0;
            }
            else if(total<100){
                total += array.get(j);
            }
        }
    }
    return finalTotal;
}

When printing the result in the hash-map it gives 2 different maps of answers when I use i and j for as the key. Isn't it suppose to give the same values and just different keys as answers? Not only the value the amount length of the hashmap also changes.

It would be great if you could point out any mistakes and explain why this happens.


问:
Does .Net TDES do enc-dec-enc or end-enc-enc?
I am trying to authenticate a payment card in .Net 4.5.  EMV Book 2 Annex B1.1 says that:
DES3(K)[X] = DES(K L )[DES -1 (K R )[DES(K L )[X]]]
or, 3DES of X means:

Blockquote

encrypt X with the left half of the 16 byte key

decrypt that ciphertext with the right half of the 16 byte key

encrypt that supposed plaintext with the left half of the key.

which you could call enc-dec-enc.
Can anyone assure me that .Net's TripleDESCryptoServiceProvider does it that way, as opposed to enc-enc-enc?  The ms docs page doesn't say.

答:
Irrespective of language, all implementations of TDES follow Encrypt-Decrypt-Encrypt.
For a double length key, Encrypt data using first block[first 8 bytes], decrypt using the second block[second 8 bytes] and encrypt again using first block.
For triple length key, in the last step of encrypting using the first block, third key block is used intead.
If you want to make sure of the same, simply pass some test key and data to the library, and compare the value you get from any online free tools like https://paymentcardtools.com/des-calculator

I can see it is mentioned in the documentation. Click on TripleDES in the begining and then read the remarks section.


问:
Java try-catch input validation with do-while loop
I've been sitting here (embarrassingly) for hours trying to get a do-while loop to to accept user input until it's valid, but I seem to be messing up when it comes to the boolean that I'm using to try and exit the loop.  Whenever I can get the program to partially work the catch exception just ends up repeating itself infinitely.</p>

```<code>Scanner scnr = new Scanner(System.in);

double wallHeight = 0.0;
boolean valid = false;

// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
    try {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        valid = false;

        if (wallHeight <=0) {
            throw new Exception ("Invalid Input");
        }
    }
    catch (Exception e) {
        System.out.println("Invalid Input");
    }
} while (!valid);
</code>```

答:
Here is another take.I just moved the code that sets valid = true after the if check. It can make it that far only when its valid. Otherwise valid will be false and it will loop.

public class BasicDoWhile {

    public static void main(String[] args) {
        double wallHeight = 0.0;
        boolean valid = false;

        Scanner scnr = new Scanner(System.in);

        // Implement a do-while loop to ensure input is valid
        // Prompt user to input wall's height
        do {
            try {
                System.out.println("Enter wall height (feet): ");
                wallHeight = scnr.nextDouble();

                if (wallHeight <= 0) {
                    throw new Exception("Invalid Input");
                }

                valid = true;

            }
            catch (Exception e) {
                System.out.println("Invalid Input");
            }

        } while (!valid);

    }
}
```

Body:
I've been sitting here (embarrassingly) for hours trying to get a do-while loop to to accept user input until it's valid, but I seem to be messing up when it comes to the boolean that I'm using to try and exit the loop.  Whenever I can get the program to partially work the catch exception just ends up repeating itself infinitely.

Scanner scnr = new Scanner(System.in);

double wallHeight = 0.0;
boolean valid = false;

// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
    try {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        valid = false;

        if (wallHeight <=0) {
            throw new Exception ("Invalid Input");
        }
    }
    catch (Exception e) {
        System.out.println("Invalid Input");
    }
} while (!valid);


问:
use macro to test function return value in C
I want to have a macro which does something like:

#define TEST(_ptr) ({ if ((_ptr) == NULL) ERROR; (_ptr); })

which check _ptr and calls ERROR macro or return its value.

However, if I use something like var = TEST(fun()) this results in fun() being called two times.

I can do something like:

#define TEST(_tmp, _ptr) ({ _tmp = _ptr; if ((_tmp) == NULL) ERROR; (_tmp); })

is there any clean way of doing this without passing temporary storage, e.g. using typeof operator!?

答:
By comparing (_ptr) == NULL I'm assuming your func() returns a pointer.
In this case you can change the TEST(_ptr) macro to:

```<code>#define TEST(_ptr) ({ void* _rt = _ptr; if ((_rt) == NULL) ERROR; (_rt); })
</code>```

Body:
By comparing (_ptr) == NULL I'm assuming your func() returns a pointer.
In this case you can change the TEST(_ptr) macro to:

#define TEST(_ptr) ({ void* _rt = _ptr; if ((_rt) == NULL) ERROR; (_rt); })


问:
Is there a function in C to find a substring overlap?
in C, is there a function that when giver two strings, will return the substring overlap or size of the overlap? So like something that does:

```<code>char s1[5] = {cart};
char s2[4] = {car};
int overlap;
overlap = get_overlap(s1, s2); /*or have overlap be a string if it returns the overlap*.
</code>```

and then overlap would be 3.

If not, how do i make one that will return the int value of the overlap.

答:
Qualification: This function computed overlaps of the type

```<code>string1
    ng1randomcharacters
</code>```

In this case, the overlap is 3

```<code>// Traverses s1 from left to right and s2 from left to right, looking for overlap
int get_overlap(char *s1, char *s2)
{
   int u2 = strlen(s2)-1;
   int p1 = strlen(s1)-1;
   int p2 = 0;

   while( p1>=0 && p2<=u2 )
   {
      if (s1[p1--] != s2[p2++])
      {
         --p2; // no overlap, so correct for incremented value
         break;
      }
   }

   return(p2);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
in C, is there a function that when giver two strings, will return the substring overlap or size of the overlap? So like something that does:

char s1[5] = {cart};
char s2[4] = {car};
int overlap;
overlap = get_overlap(s1, s2); /*or have overlap be a string if it returns the overlap*.

and then overlap would be 3.

If not, how do i make one that will return the int value of the overlap.

Body:
Qualification: This function computed overlaps of the type

string1
    ng1randomcharacters

In this case, the overlap is 3

// Traverses s1 from left to right and s2 from left to right, looking for overlap
int get_overlap(char *s1, char *s2)
{
   int u2 = strlen(s2)-1;
   int p1 = strlen(s1)-1;
   int p2 = 0;

   while( p1>=0 && p2<=u2 )
   {
      if (s1[p1--] != s2[p2++])
      {
         --p2; // no overlap, so correct for incremented value
         break;
      }
   }

   return(p2);
}


问:
Selenium and BeautifulSoup - Trying to scrape content from page 1 THEN go to page 2 and so on
I am having a hard time understanding how to grab all of the pages content that I want. I am able to grab the information I want from page 1 but getting the next 15 pages is the challenge.

I am using selenium and chrome webdriver to get the info from this site.

This is what I have so far, this is an example of grabbing the 1st piece of info I need from the 1st page.

答:
From what I noticed, the URLs of the pages on that website follows a particular pattern with ;page=X appended at the end of the URL to load the content of a specific page, where X is the page number you want.

For example https://www.canadiantire.ca/en/automotive/tires-wheels/tires.html?adlocation=LOL_TiresSCLP_MegaNavAuto_19309_en;page=15 loads the contents of page 15.

In your code, you can loop through each page and scrape the content.


问:
How to convert column into row with header sql

Note : i need the record like this

```<code>Scode value
BR     10
DL      7
</code>```

答:
Please go on this link and See the simple solution my problem is Solve.
https://www.codeproject.com/Answers/5259227/Convert-column-into-row-with-header-in-SQL#answer1</p>

Body:
Note : i need the record like this

Scode value
BR     10
DL      7


问:
Access Django custom user profile field
I added a custom user profile field role with the following models.py.

```<code>from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    ROLE_CHOICES = (
        (792, 'Student'),
        (172, 'Teacher'),
        (864, 'Supervisor'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    role = models.IntegerField(choices=ROLE_CHOICES, null=True, blank=True)

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()
</code>```

What is the best way to return the int value assigned to the role? For example if the current logged in user is assigned the role of "Teacher", I want to be able to use the 172 value elsewhere like in views.py.

答:
Currently logged in user is request.user, so

```<code>request.user.profile.role
</code>```

will return 172, and

```<code>request.user.profile.get_role_display()
</code>```

will return "Teacher". Note that you should omit parentheses if you are using the latter in a template.

Title: Access Django custom user profile field

Body:
I added a custom user profile field role with the following models.py.

from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    ROLE_CHOICES = (
        (792, 'Student'),
        (172, 'Teacher'),
        (864, 'Supervisor'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    role = models.IntegerField(choices=ROLE_CHOICES, null=True, blank=True)

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

What is the best way to return the int value assigned to the role? For example if the current logged in user is assigned the role of "Teacher", I want to be able to use the 172 value elsewhere like in views.py.

Body:
Currently logged in user is request.user, so

request.user.profile.role

will return 172, and

request.user.profile.get_role_display()

will return "Teacher". Note that you should omit parentheses if you are using the latter in a template.


问:
Dynamodb Table Design
I need a table which should have following attributes: userId, commentId, commentTopic, commentCountry. I want to avoid using Secondary Global indexes. What should be best design which will allow me the followings operations:

```<code>1) Get all comments belonging to a userId.
2) Get a comment with commentID = "commentID"
3) Get comments of all users  where topic = "commentTopic" and country = "commentCountry"
</code>```

I am thinking to have:

```<code>1) userId#commentId as partitionKey which will uniformly distribute the load and allow me to perform operation 1 and 2 from above list.
2) commentCountry#commentTopic as RangeKey which will allow me to perform operation 3 efficiently.
</code>```

Is there any drawback of this approach. Will this table design be efficient? What are disadvantages of concatenating multiple keys together?

答:
```<code>PK = USER#userid
SK = COMMENT#commentId(GSIPK)
GSISK = commentTopic#country
</code>```

Get all comments from a user

```<code>PK = USER#userid AND SK START_WITH COMMENT#
</code>```

Get a comment by comment id can be against GSI

```<code>GSIPK = COMMENT#commentId
</code>```

Get comments of all users  where topic = "commentTopic" and country = "commentCountry"

```<code>GSIPK START_WITH COMMENT# AND GSISK = commentTopic#country
</code>```

Title: Dynamodb Table Design

Body:
I need a table which should have following attributes: userId, commentId, commentTopic, commentCountry. I want to avoid using Secondary Global indexes. What should be best design which will allow me the followings operations:

1) Get all comments belonging to a userId.
2) Get a comment with commentID = "commentID"
3) Get comments of all users  where topic = "commentTopic" and country = "commentCountry"

I am thinking to have:

1) userId#commentId as partitionKey which will uniformly distribute the load and allow me to perform operation 1 and 2 from above list.
2) commentCountry#commentTopic as RangeKey which will allow me to perform operation 3 efficiently.

Is there any drawback of this approach. Will this table design be efficient? What are disadvantages of concatenating multiple keys together?

Body:
PK = USER#userid
SK = COMMENT#commentId(GSIPK)
GSISK = commentTopic#country

Get all comments from a user

PK = USER#userid AND SK START_WITH COMMENT#

Get a comment by comment id can be against GSI

GSIPK = COMMENT#commentId

Get comments of all users  where topic = "commentTopic" and country = "commentCountry"

GSIPK START_WITH COMMENT# AND GSISK = commentTopic#country


问:
Subclassing NSDictionary not working
I have a dictionary that I read from a plist. I want to create a subclass of NSDictionary to implement something like the following, so that I can avoid using @"key name" everywhere in my source code:

```<code>@interface MyDict{
}
-(NSString*) textString;
@end

@implementation MyDict
-(NSString*) textString {
    return [self objectForKey:@"textString"];
}
@end
</code>```

In my other method:

```<code>MyDict *d = ... // something i read from plist
NSString *str = [d textString];
</code>```

When I call the method, the app crashes because of "unrecognized selector textString". What is wrong here?

答:
Your class has no superclass. Also, the conventional wisdom is that it's very difficult to subclass NSDictionary because it is an class cluster. You don't actually get an NSDictionary back when you:

```<code>NSDictionary * myDict = [NSDictionary dictionary];
</code>```

You get a private subclass (NSCFDictionary in this case).

You might want to try defining your own dictionary keys, the way Apple does:

```<code>NSString * const MyWonderfulUnicornKey = @"MyWonderfulUnicornKey";
</code>```

Title: Subclassing NSDictionary not working

Body:
I have a dictionary that I read from a plist. I want to create a subclass of NSDictionary to implement something like the following, so that I can avoid using @"key name" everywhere in my source code:

@interface MyDict{
}
-(NSString*) textString;
@end

@implementation MyDict
-(NSString*) textString {
    return [self objectForKey:@"textString"];
}
@end

In my other method:

MyDict *d = ... // something i read from plist
NSString *str = [d textString];

When I call the method, the app crashes because of "unrecognized selector textString". What is wrong here?

Body:
Your class has no superclass. Also, the conventional wisdom is that it's very difficult to subclass NSDictionary because it is an class cluster. You don't actually get an NSDictionary back when you:

NSDictionary * myDict = [NSDictionary dictionary];

You get a private subclass (NSCFDictionary in this case).

You might want to try defining your own dictionary keys, the way Apple does:

NSString * const MyWonderfulUnicornKey = @"MyWonderfulUnicornKey";


问:
laravel mb_strpos() expects parameter 1 to be string, object given
I have this statement in my search function

```<code>if(!empty($project) && !empty($type)){
            $result = Project::where('id', 'LIKE', "%{$project}%")->with(['type', function ($query) use ($type) {
                $query->where('id', 'like', $type);
            }])->get();
}
</code>```

it returns

mb_strpos() expects parameter 1 to be string, object given

Logic

$project = project.id

$type = type.id

If $project and $ type both have values then get project where id = $project

Then eager load type to that project where id = $type

is like we say types, where types.project_id = projects.id and where types.id = $type but with eager load instead of query.

any idea?

答:
You're getting this error because with() takes an associative array in order to constrain eager loads. try this</p>

```<code>if(!empty($project) && !empty($type)){
            $result = Project::where('id', 'LIKE', "%{$project}%")->with(['type'=> function ($query) use ($type) {
                $query->where('id', 'like', $type);
            }])->get();
}
</code>```

Body:
I have this statement in my search function

if(!empty($project) && !empty($type)){
            $result = Project::where('id', 'LIKE', "%{$project}%")->with(['type', function ($query) use ($type) {
                $query->where('id', 'like', $type);
            }])->get();
}

it returns

mb_strpos() expects parameter 1 to be string, object given

Logic

$project = project.id

$type = type.id

If $project and $ type both have values then get project where id = $project

Then eager load type to that project where id = $type

is like we say types, where types.project_id = projects.id and where types.id = $type but with eager load instead of query.

any idea?

Body:
You're getting this error because with() takes an associative array in order to constrain eager loads. try this

if(!empty($project) && !empty($type)){
            $result = Project::where('id', 'LIKE', "%{$project}%")->with(['type'=> function ($query) use ($type) {
                $query->where('id', 'like', $type);
            }])->get();
}


问:
Finding the turning point (inflection point) of COVID-19 infections using inflection package
I am not sure if I have done my inflection point calculation correctly. Based on lab confirmed cumulative case data in the epicenter of the current epidemic, we have tried to identify the inflection point. I used the inflection package and calculated the inflection point as "08 Feb 2020". I have also tried to calculate the first and second directives as estimated increase each and changing rate.

Are those results from the following graphs consistent?

df<-structure(list(date = structure(c(18277, 18278, 18279, 18280,
18281, 18282, 18283, 18284, 18285, 18286, 18287, 18288, 18289,
18290, 18291, 18292, 18293, 18294, 18295, 18296, 18297, 18298,
18299, 18300, 18301, 18302, 18303, 18304, 18305, 18306, 18307),
class = "Date"),
cases = c(45, 62, 121, 198, 258, 363, 425,
        495, 572, 618, 698, 1590, 1905, 2261, 2639, 3125, 4109, 5142,
        6384, 8351, 10117, 11618, 13603, 14982, 16903, 18454, 19558,
       20630, 21960, 22961, 23621)),
class = "data.frame", row.names = c(NA, -31L))
xlb_0<- structure(c(18281, 18285, 18289, 18293,
                    18297, 18301, 18305,
                    18309), class = "Date")
library(tidyverse)
# Smooth cumulative cases over time
df$x = as.numeric(df$date)
fit_1<- loess(cases ~ x, span = 1/3, data = df)
df$case_sm <-fit_1$fitted

# use inflection to obtain inflection point
library(inflection)
guai_0 <- check_curve(df$x, df$case_sm)
check_curve(df$x, df$cases)
#> $ctype
#> [1] "convex_concave"
#>
#> $index
#> [1] 0
guai_1 <- bese(df$x, df$cases, guai_0$index)
structure(guai_1$iplast, class = "Date")
#> [1] "2020-02-08"

# Plot cumulativew numbers of cases
df %>%
  ggplot(aes(x = date, y = cases ))+
  geom_line(aes(y = case_sm), color = "red") +
  geom_point() +
  geom_vline(xintercept = guai_1$iplast) +
  labs(y = "Cumulative lab confirmed infections")
```
<p><img src="https://i.imgur.com/7JN0ufQ.png" alt="" /></p>
<pre class="lang-r prettyprint-override"><code># Daily new cases (first derivative) and changing rate (second derivative)
df$dt1 = c(0, diff(df$case_sm)/diff(df$x))
fit_2<- loess(dt1 ~ x, span = 1/3, data = df)
df$change_sm <-fit_2$fitted
df$dt2 <- c(NA, diff(df$change_sm)/diff(df$x))

df %>%
  ggplot(aes(x = date, y = dt1))+
  geom_line(aes(y = dt1,
                color = "Estimated number of new cases")) +
  geom_point(aes(y = dt2*2, color = "Changing rate")) +
  geom_line(aes(y = dt2*2, color = "Changing rate"))+
  geom_vline(xintercept = guai_1$iplast) +
  labs(y = "Estimatede number of new cases") +
  scale_x_date(breaks = xlb_0,
               date_labels = "%b%d") +
  theme(legend.title = element_blank())
#> Warning: Removed 1 rows containing missing values (geom_point).
#> Warning: Removed 1 row(s) containing missing values (geom_path).
</code>```

Created on 2020-02-17 by the reprex package (v0.3.0)

答:
A very quick back-of-the-envelope plot based on your data shows

```<code>calc_d <- function(x) c(0, diff(x))
df %>%
    mutate(
        first_deriv_cases = calc_d(cases),
        second_deriv_cases = calc_d(calc_d(cases))) %>%
    pivot_longer(-date) %>%
    ggplot(aes(date, value)) +
        geom_line() +
        facet_wrap(~name, scale = "free_y", ncol = 1) +
        geom_smooth()
</code>```

So the inflection point at 8 February is consistent with the first derivative (i.e. the density function) having a maximum at that point.

Body:
I am not sure if I have done my inflection point calculation correctly. Based on lab confirmed cumulative case data in the epicenter of the current epidemic, we have tried to identify the inflection point. I used the inflection package and calculated the inflection point as "08 Feb 2020". I have also tried to calculate the first and second directives as estimated increase each and changing rate.

Are those results from the following graphs consistent?

df<-structure(list(date = structure(c(18277, 18278, 18279, 18280,
18281, 18282, 18283, 18284, 18285, 18286, 18287, 18288, 18289,
18290, 18291, 18292, 18293, 18294, 18295, 18296, 18297, 18298,
18299, 18300, 18301, 18302, 18303, 18304, 18305, 18306, 18307),
class = "Date"),
cases = c(45, 62, 121, 198, 258, 363, 425,
        495, 572, 618, 698, 1590, 1905, 2261, 2639, 3125, 4109, 5142,
        6384, 8351, 10117, 11618, 13603, 14982, 16903, 18454, 19558,
       20630, 21960, 22961, 23621)),
class = "data.frame", row.names = c(NA, -31L))
xlb_0<- structure(c(18281, 18285, 18289, 18293,
                    18297, 18301, 18305,
                    18309), class = "Date")
library(tidyverse)
# Smooth cumulative cases over time
df$x = as.numeric(df$date)
fit_1<- loess(cases ~ x, span = 1/3, data = df)
df$case_sm <-fit_1$fitted

# use inflection to obtain inflection point
library(inflection)
guai_0 <- check_curve(df$x, df$case_sm)
check_curve(df$x, df$cases)
#> $ctype
#> [1] "convex_concave"
#>
#> $index
#> [1] 0
guai_1 <- bese(df$x, df$cases, guai_0$index)
structure(guai_1$iplast, class = "Date")
#> [1] "2020-02-08"

# Plot cumulativew numbers of cases
df %>%
  ggplot(aes(x = date, y = cases ))+
  geom_line(aes(y = case_sm), color = "red") +
  geom_point() +
  geom_vline(xintercept = guai_1$iplast) +
  labs(y = "Cumulative lab confirmed infections")

# Daily new cases (first derivative) and changing rate (second derivative)
df$dt1 = c(0, diff(df$case_sm)/diff(df$x))
fit_2<- loess(dt1 ~ x, span = 1/3, data = df)
df$change_sm <-fit_2$fitted
df$dt2 <- c(NA, diff(df$change_sm)/diff(df$x))

df %>%
  ggplot(aes(x = date, y = dt1))+
  geom_line(aes(y = dt1,
                color = "Estimated number of new cases")) +
  geom_point(aes(y = dt2*2, color = "Changing rate")) +
  geom_line(aes(y = dt2*2, color = "Changing rate"))+
  geom_vline(xintercept = guai_1$iplast) +
  labs(y = "Estimatede number of new cases") +
  scale_x_date(breaks = xlb_0,
               date_labels = "%b%d") +
  theme(legend.title = element_blank())
#> Warning: Removed 1 rows containing missing values (geom_point).
#> Warning: Removed 1 row(s) containing missing values (geom_path).

Created on 2020-02-17 by the reprex package (v0.3.0)

Body:
A very quick back-of-the-envelope plot based on your data shows

calc_d <- function(x) c(0, diff(x))
df %>%
    mutate(
        first_deriv_cases = calc_d(cases),
        second_deriv_cases = calc_d(calc_d(cases))) %>%
    pivot_longer(-date) %>%
    ggplot(aes(date, value)) +
        geom_line() +
        facet_wrap(~name, scale = "free_y", ncol = 1) +
        geom_smooth()

So the inflection point at 8 February is consistent with the first derivative (i.e. the density function) having a maximum at that point.


问:
Click on Image src using Python Selenium which do not have element id
I have arrows in the webpage which will expand and take me to the next, and so on. Manually, if i click on that arrow, it expands and shows me the breakdown.

I am trying to automate the same using Python Selenium module, trying to click on the arrow before "User Directory". When i see the code in developer option (F12), it shows me class name, Image title and src. I tried to get the list of text using class names:-

```<code>a=[]
a=driver.find_elements_by_class_name("bi-tree-view-expand-icon")
print(a)
</code>```

But every time the session and elements i get differs. Output is below:

```<code>> [<selenium.webdriver.remote.webelement.WebElement
> (session="98f30ad2-4ff3-42fa-985e-206c0a778ee8",
> element="270e9246-ee5c-44da-8348-94047ca5d633")>,
> <selenium.webdriver.remote.webelement.WebElement
> (session="98f30ad2-4ff3-42fa-985e-206c0a778ee8",
> element="b53fd15f-6c2d-4d8c-9f37-c79803d5b2fc")>,
> <selenium.webdriver.remote.webelement.WebElement
> (session="98f30ad2-4ff3-42fa-985e-206c0a778ee8",
> element="74f4980e-3cd4-466d-972c-85a3d79de59d")>]
</code>```

Please help?

答:
You are almost there, rather printing a click on it.

```<code>a[1].click()
</code>```

However, we can streamline the xpath, provider you can share the html of the user directories parent element (including the children).

As you are returning all the elements matching with the bi-tree-view-expand-icon class name, there are multiple expand icons and when you print a list a collection of elements. so you are seeing all expand icons references. If you want to access particular expand icon you can use the index or write more precise xpath.

Body:
I have arrows in the webpage which will expand and take me to the next, and so on. Manually, if i click on that arrow, it expands and shows me the breakdown.

I am trying to automate the same using Python Selenium module, trying to click on the arrow before "User Directory". When i see the code in developer option (F12), it shows me class name, Image title and src. I tried to get the list of text using class names:-

a=[]
a=driver.find_elements_by_class_name("bi-tree-view-expand-icon")
print(a)

But every time the session and elements i get differs. Output is below:

> [<selenium.webdriver.remote.webelement.WebElement
> (session="98f30ad2-4ff3-42fa-985e-206c0a778ee8",
> element="270e9246-ee5c-44da-8348-94047ca5d633")>,
> <selenium.webdriver.remote.webelement.WebElement
> (session="98f30ad2-4ff3-42fa-985e-206c0a778ee8",
> element="b53fd15f-6c2d-4d8c-9f37-c79803d5b2fc")>,
> <selenium.webdriver.remote.webelement.WebElement
> (session="98f30ad2-4ff3-42fa-985e-206c0a778ee8",
> element="74f4980e-3cd4-466d-972c-85a3d79de59d")>]

Please help?

Body:
You are almost there, rather printing a click on it.

a[1].click()

However, we can streamline the xpath, provider you can share the html of the user directories parent element (including the children).

As you are returning all the elements matching with the bi-tree-view-expand-icon class name, there are multiple expand icons and when you print a list a collection of elements. so you are seeing all expand icons references. If you want to access particular expand icon you can use the index or write more precise xpath.


问:
OpenCV 4.1.2 - get frame from webcam and split it
I want to grab a frame from my 3D webcam. The webcam grabs the left and right picture and on webcam software they are displayed side by side. In order to get a depth picture for my robot I have to split the picture up in two pictures. But I get a error in croping the image:

```<code>terminate called after throwing an instance of 'cv::Exception'
  what():  OpenCV(4.1.2) /home/pi/opencv/opencv-4.1.2/modules/core/src/matrix.cpp:466: error: (-215:Assertion failed) 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows in function 'Mat'
</code>```

Here is some code I tried:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <stdint.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>
#include <dlfcn.h>
#include <inttypes.h>
#include <unistd.h>
#include <sys/time.h>

#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/xfeatures2d.hpp"
#include "opencv2/objdetect/objdetect.hpp"

#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>

using namespace cv;
using namespace cv::xfeatures2d;
using namespace std;

typedef unsigned char           U1;     /* UBYTE   */
typedef int16_t                 S2;     /* INT     */
typedef uint16_t                U2;     /* UINT    */
typedef int32_t                 S4;     /* LONGINT */

typedef long long               S8;     /* 64 bit long */
typedef double                  F8;     /* DOUBLE */

int main ()
{
    S2 deviceId = 0;
    S2 retry = 0, drop;

    // Get a handle to the Video device:
    VideoCapture cap (deviceId);
    usleep (5000);

    open_cams:
    // Check if we can use this device at all:
    if(!cap.isOpened()) {
        cerr << "Capture Device ID " << deviceId << " cannot be opened." << endl;
        retry--;
    }

    if (retry < 6)
    {
        if (retry != 0)
        {
            usleep (4000);
            goto open_cams;
        }
    }

    Mat cam_left_out;
    Mat cam_right_out;
    Mat cam_out;

    for (;;)
    {
        // drop frames to get real time frames, was 10
        // for (drop = 5; drop > 1; drop--)
        for (;;)
        {
            for (drop = 5; drop > 1; drop--)
            {
                cap >> cam_out;
            }

            cap >> cam_out;

            if (! cam_out.empty()) break;
        }

        Rect left_roi (0, 0, 640, 480);
        Rect right_roi (640, 0, 640, 480);

        Mat crop_left (cam_out, left_roi);
        Mat crop_right (cam_out, right_roi);

        crop_left.copyTo (cam_left_out);
        crop_right.copyTo (cam_right_out);

        imshow("cam", cam_out);
        imshow("cam-left", cam_left_out);
        imshow("cam-right", cam_right_out);
    }
}
</code>```

What is wrong with this? The frame grabbed from my webcam should be in 1280x480 in size!

答:
Seems like the wrong order. I bet your image has the shape of (480, 1280, 3), so instead of this:

```<code>    Rect left_roi (0, 0, 640, 480);
    Rect right_roi (640, 0, 640, 480);
</code>```

you should have used this:

```<code>    Rect left_roi (0, 0, 480, 640);
    Rect right_roi (0, 640, 480, 640);
</code>```

or, better yet, a totally bulletproof solution, instead of explicitly hard-coding your numbers, use cam_out.shape to figure out the size of your picture, and use cam_out.shape[1]/2 or something like that instead of hard-coded numbers.

Body:
I want to grab a frame from my 3D webcam. The webcam grabs the left and right picture and on webcam software they are displayed side by side. In order to get a depth picture for my robot I have to split the picture up in two pictures. But I get a error in croping the image:

terminate called after throwing an instance of 'cv::Exception'
  what():  OpenCV(4.1.2) /home/pi/opencv/opencv-4.1.2/modules/core/src/matrix.cpp:466: error: (-215:Assertion failed) 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows in function 'Mat'

Here is some code I tried:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <stdint.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>
#include <dlfcn.h>
#include <inttypes.h>
#include <unistd.h>
#include <sys/time.h>

#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/xfeatures2d.hpp"
#include "opencv2/objdetect/objdetect.hpp"

#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>

using namespace cv;
using namespace cv::xfeatures2d;
using namespace std;

typedef unsigned char           U1;     /* UBYTE   */
typedef int16_t                 S2;     /* INT     */
typedef uint16_t                U2;     /* UINT    */
typedef int32_t                 S4;     /* LONGINT */

typedef long long               S8;     /* 64 bit long */
typedef double                  F8;     /* DOUBLE */

int main ()
{
    S2 deviceId = 0;
    S2 retry = 0, drop;

    // Get a handle to the Video device:
    VideoCapture cap (deviceId);
    usleep (5000);

    open_cams:
    // Check if we can use this device at all:
    if(!cap.isOpened()) {
        cerr << "Capture Device ID " << deviceId << " cannot be opened." << endl;
        retry--;
    }

    if (retry < 6)
    {
        if (retry != 0)
        {
            usleep (4000);
            goto open_cams;
        }
    }

    Mat cam_left_out;
    Mat cam_right_out;
    Mat cam_out;

    for (;;)
    {
        // drop frames to get real time frames, was 10
        // for (drop = 5; drop > 1; drop--)
        for (;;)
        {
            for (drop = 5; drop > 1; drop--)
            {
                cap >> cam_out;
            }

            cap >> cam_out;

            if (! cam_out.empty()) break;
        }

        Rect left_roi (0, 0, 640, 480);
        Rect right_roi (640, 0, 640, 480);

        Mat crop_left (cam_out, left_roi);
        Mat crop_right (cam_out, right_roi);

        crop_left.copyTo (cam_left_out);
        crop_right.copyTo (cam_right_out);

        imshow("cam", cam_out);
        imshow("cam-left", cam_left_out);
        imshow("cam-right", cam_right_out);
    }
}

What is wrong with this? The frame grabbed from my webcam should be in 1280x480 in size!

Body:
Seems like the wrong order. I bet your image has the shape of (480, 1280, 3), so instead of this:

    Rect left_roi (0, 0, 640, 480);
    Rect right_roi (640, 0, 640, 480);

you should have used this:

    Rect left_roi (0, 0, 480, 640);
    Rect right_roi (0, 640, 480, 640);

or, better yet, a totally bulletproof solution, instead of explicitly hard-coding your numbers, use cam_out.shape to figure out the size of your picture, and use cam_out.shape[1]/2 or something like that instead of hard-coded numbers.


问:
spyder4 - hide background variables in variable explorer on Mac?

I think that the variable explorer is showing background variables of spyder. How can I hide them?

答:
Thanks Carlos Cordoba

I found the option in preferences. Automatically load Pylab and Numpy Modules option should be unchecked.

preference snapshot


问:
Enable/Disable a dropdownbox in jquery
I am new to jQuery and I want to enable and disable a dropdown list using a checkbox. This is my html:

```<code><select id="dropdown" style="width:200px">
    <option value="feedback" name="aft_qst">After Quest</option>
    <option value="feedback" name="aft_exm">After Exam</option>
</select>
<input type="checkbox" id="chkdwn2" value="feedback" />
</code>```

What jQuery code do I need to do this? Also searching for a good jQuery documentation/study material.

答:
this is to disable dropdown2 , dropdown 3 if you select the option from dropdown1 that has the value 15</p>

```<code>$("#dropdown1").change(function(){
            if ( $(this).val()!= "15" ) {
                $("#dropdown2").attr("disabled",true);
                $("#dropdown13").attr("disabled",true);

            }
</code>```

Title: Enable/Disable a dropdownbox in jquery

Body:
I am new to jQuery and I want to enable and disable a dropdown list using a checkbox. This is my html:

<select id="dropdown" style="width:200px">
    <option value="feedback" name="aft_qst">After Quest</option>
    <option value="feedback" name="aft_exm">After Exam</option>
</select>
<input type="checkbox" id="chkdwn2" value="feedback" />

What jQuery code do I need to do this? Also searching for a good jQuery documentation/study material.

Body:
this is to disable dropdown2 , dropdown 3 if you select the option from dropdown1 that has the value 15

$("#dropdown1").change(function(){
            if ( $(this).val()!= "15" ) {
                $("#dropdown2").attr("disabled",true);
                $("#dropdown13").attr("disabled",true);

            }


问:
Plot is not displaying when executing script
When I execute my script via command line py planck.py the plot is not displaying but when I use my Spyder IDE, the plot is able to display but I am not sure why it isn't showing via command line.

```<code>import numpy as np
from pylab import *

def BB_wl(wavel, temp):
    # wavel in micron
    c1=1.191042E8 # W/m2-sr-um4
    c2=1.4387752E4 # K mu
    value = c1 / (wavel**5*(np.exp(c2/(wavel*temp))+5.0E4))
    return value # in W/m2-sr-um

my_figure = figure(figsize=(10,4))
main_axes = my_figure.add_axes([0.1, 0.1, 0.8, 0.8])
main2_axes = main_axes.twiny()
main2_axes.set_xlabel('Frequency [THz]',size="x-large")
main2_axes.set_xticklabels(["3000", "2257", "1515", "772", "30"])
small_ax  = my_figure.add_axes( [0.35, 0.5, 0.25, 0.3] )
main_axes.set_xlabel('Wavelength [micron]', size="x-large")
main_axes.set_ylabel(r'$[\mathrm{Wm^{-2} \, \mu m^{-1}}]$',size="x-large")
wave = np.linspace(1,10,1000)
spectral = BB_wl(wave, 1000)/100
main_axes.plot(wave, spectral, color="red", linewidth=3)
small_ax.plot(wave, spectral, color="blue", linewidth=3)
my_figure.show()
my_figure.savefig('planck.png', bbox_inches='tight')
</code>```

答:
Because the script runs till end.

Try to stop the script via

```<code>x = input("press key to exit")
</code>```

add it to the end of the script.
in this case your script will wait and you will be able to see the figure. I hope this helps.

Body:
When I execute my script via command line py planck.py the plot is not displaying but when I use my Spyder IDE, the plot is able to display but I am not sure why it isn't showing via command line.

import numpy as np
from pylab import *

def BB_wl(wavel, temp):
    # wavel in micron
    c1=1.191042E8 # W/m2-sr-um4
    c2=1.4387752E4 # K mu
    value = c1 / (wavel**5*(np.exp(c2/(wavel*temp))+5.0E4))
    return value # in W/m2-sr-um

my_figure = figure(figsize=(10,4))
main_axes = my_figure.add_axes([0.1, 0.1, 0.8, 0.8])
main2_axes = main_axes.twiny()
main2_axes.set_xlabel('Frequency [THz]',size="x-large")
main2_axes.set_xticklabels(["3000", "2257", "1515", "772", "30"])
small_ax  = my_figure.add_axes( [0.35, 0.5, 0.25, 0.3] )
main_axes.set_xlabel('Wavelength [micron]', size="x-large")
main_axes.set_ylabel(r'$[\mathrm{Wm^{-2} \, \mu m^{-1}}]$',size="x-large")
wave = np.linspace(1,10,1000)
spectral = BB_wl(wave, 1000)/100
main_axes.plot(wave, spectral, color="red", linewidth=3)
small_ax.plot(wave, spectral, color="blue", linewidth=3)
my_figure.show()
my_figure.savefig('planck.png', bbox_inches='tight')

Body:
Because the script runs till end.

Try to stop the script via

x = input("press key to exit")

add it to the end of the script.
in this case your script will wait and you will be able to see the figure. I hope this helps.


问:
Why don't we just keep all dynamic memory in arrays?
In C/C++, when you allocate dynamic memory, the OS gives you an unpredictable address to some distant region of memory.  If you allocate a lot of dynamic memory, and need to travel between it (for example, linked lists, trees), then you have to waste time waiting for the CPU to consult RAM, because, more than likely, the piece of memory you wanted wasn't close to the piece of memory you had.

Recently, for a project in one of my university courses, I had to implement a tree such that nodes could have any number of children, and I had to be able to merge nodes into single trees in constant time.  So, I had a bunch of internal Node objects with a bunch of pointers to surrounding nodes.

Because this was C++, it was fast, of course, but with the time and memory it was being tested on, it had just okay performance.

So, I decided to try implementing pointer replacements which would really be indices of static vectors, and a function to grow the vector when a new object was needed, and a stack of 'deleted' indices that could be re-used.  This way, everything would be close together in memory, and dereferences were less likely to result in cache misses.  Also, because I knew the tree would not be tested on the scale of gigabytes of data, I could restrict these indices to 32 bits, reducing the memory overhead of the tree structure significantly.

The results were amazing -- in most cases a third the time and memory of the staff implementation for my course.

My question is, if the cache benefits are so extreme, why do we bother directly using new and delete at all?  Why not just stick everything in vectors, one for each type?

答:
You use the standard allocators when they're "good enough" for what you need to do.  The difference between a program that runs in 10ms vs one that runs in 100ms may be 10x, but in practice that difference is meaningless.  Both run "instantly".

That's not to say you should never use your own allocation strategy.  In general, you should use an allocation strategy that matches your use-case and requirements.  What you've described sounds a lot like object pooling, which is a well-known and frequently used pattern in situations where you have lots of objects of the same type.

Keep in mind that the standard memory allocators have to support every possible use-case.
 Since your special-purpose allocator is aware of your usage patterns, you're able to squeeze a bit more performance out of it for your specific use-case, but it's unlikely it would be faster than the heavily tuned standard allocators in general across all possible use-cases.

What most standard library implementations use for new/malloc is a pooling allocator, which is somewhat of a generalization of the object pool you've implemented.  The first time some memory is requested, they allocate a big chunk of memory from the OS and then hand out pieces of that pool as its requested, keeping track of which pieces are in use and which are available for later (re-)use.  When the pool runs out they'll get another chunk of memory from the OS and start handing out bits of that.

The biggest difference from what you've implemented is that when you allocate a new pool you move everything from the old one into the new one.  In the general case for large amounts of data that copying will likely become a bottleneck that would overcome any benefit you would get from locality and if your data is larger than a cache line it doesn't really matter if it's all contiguous or not.

Your approach also requires that every user of the allocator be aware of its implementation, since each re-allocation will invalidate any pointers or references to the old pool.  That means you've traded ease-of-maintenance for performance.  That may not matter for a school project that you'll never look at again, but for real-world applications ongoing maintenance cost is a very big consideration.


问:
Pass express server instance to other node files
I have a project set up where in my bin/www file I have my node server set up with the following line which works:

const server = http.createServer(app);

I am working on setting up socket.io so I would like to make another file called socket.js and in there do all the socket.io set up but I need to be able to get access to my server variable. I tried to export my server variable like this:

module.exports = server;

and then use it in my new file like this:

```<code>const server = require("./bin/www");
const io = require('socket.io')(server); //server doesn't seem to be working here

io.on("connection", socket => {
    socket.on('sendMessage', data => {
        socket.join(socket.id, () => {
            console.log('Joined group');
            io.sockets.in(socket.id).emit('sendMessage', data)
        });
    });
});
</code>```

But it doesn't look like this is setting up the socket on the server as I am getting the following error:

GET /socket.io/?EIO=3&transport=polling&t=N1HOkXK which happens when it isn't set up correctly.

答:
Using a function with exports:

In your bin/www file:

```<code>module.exports = init;

function init(){
  // All other relevant code for your server declaration
  return http.createServer(app);
}
</code>```

In your new file:

```<code>const server = require("./bin/www")();
</code>```

Using a variable with exports:

In your bin/www file:

```<code>exports.server = server;
</code>```

In your new file:

```<code>const server = require(".bin/www").server;
</code>```

Body:
I have a project set up where in my bin/www file I have my node server set up with the following line which works:

const server = http.createServer(app);

I am working on setting up socket.io so I would like to make another file called socket.js and in there do all the socket.io set up but I need to be able to get access to my server variable. I tried to export my server variable like this:

module.exports = server;

and then use it in my new file like this:

const server = require("./bin/www");
const io = require('socket.io')(server); //server doesn't seem to be working here

io.on("connection", socket => {
    socket.on('sendMessage', data => {
        socket.join(socket.id, () => {
            console.log('Joined group');
            io.sockets.in(socket.id).emit('sendMessage', data)
        });
    });
});

But it doesn't look like this is setting up the socket on the server as I am getting the following error:

GET /socket.io/?EIO=3&transport=polling&t=N1HOkXK which happens when it isn't set up correctly.

Body:
Using a function with exports:

In your bin/www file:

module.exports = init;

function init(){
  // All other relevant code for your server declaration
  return http.createServer(app);
}

In your new file:

const server = require("./bin/www")();

Using a variable with exports:

In your bin/www file:

exports.server = server;

In your new file:

const server = require(".bin/www").server;


问:
Set-OrganizationConfing not recognised, even though I can Get-OrganizationConfig
I'm trying to set the 'Focused Inbox' to disabled for the whole organisation. I've found lots of scripts and tutorials online, most of which point toward using the Exchange Online Session in PowerShell.

e.g.:

https://learn.microsoft.com/en-us/office365/admin/setup/configure-focused-inbox?view=o365-worldwide

https://learn.microsoft.com/en-au/powershell/exchange/exchange-online/connect-to-exchange-online-powershell/connect-to-exchange-online-powershell?view=exchange-ps

My PS script is as follows:

```<code># Set up Credential
$UserCredential = Get-Credential

# Create the Exchange Online session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection

# Import the cmdlets into this session
Import-PSSession $Session -DisableNameChecking

# Get a list of the organisation's current settings
Get-OrganizationConfig

# Now set the 'Focused Inbox' option to 'off' for everyone
Set-OrganizationConfig -FocusedInboxOn $false

# Must remove the session to avoid clogging and clutter
Remove-PSSession $Session
</code>```

The 'Get-OrganizationConfig' command returns a full list of the current config:

However, when I execute the 'Set-OrganizationConfig' command, it fails with the following message:

```<code>Set-OrganizationConfig : The term 'Set-OrganizationConfig' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
</code>```

path was included, verify that the path is correct and try again.

My presumption is that it's a permissions issue, however, I can see all the organisation's config, and it's the cmdlet that's missing.

What is the problem?

I am:

Running PS as 'Adminstrator'

Using the 'SharePointAdmin' administrator account for the credentials

答:
This was a permissions issue.

Create the $Session using an account that has Global Admin privileges in your O365 Tenant and you'll see that the 'Set-...' cmdlets automatically get downloaded and inserted into your session.

Body:
I'm trying to set the 'Focused Inbox' to disabled for the whole organisation. I've found lots of scripts and tutorials online, most of which point toward using the Exchange Online Session in PowerShell.

e.g.:

https://learn.microsoft.com/en-us/office365/admin/setup/configure-focused-inbox?view=o365-worldwide

https://learn.microsoft.com/en-au/powershell/exchange/exchange-online/connect-to-exchange-online-powershell/connect-to-exchange-online-powershell?view=exchange-ps

My PS script is as follows:

# Set up Credential
$UserCredential = Get-Credential

# Create the Exchange Online session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection

# Import the cmdlets into this session
Import-PSSession $Session -DisableNameChecking

# Get a list of the organisation's current settings
Get-OrganizationConfig

# Now set the 'Focused Inbox' option to 'off' for everyone
Set-OrganizationConfig -FocusedInboxOn $false

# Must remove the session to avoid clogging and clutter
Remove-PSSession $Session

The 'Get-OrganizationConfig' command returns a full list of the current config:

However, when I execute the 'Set-OrganizationConfig' command, it fails with the following message:

Set-OrganizationConfig : The term 'Set-OrganizationConfig' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a

path was included, verify that the path is correct and try again.

My presumption is that it's a permissions issue, however, I can see all the organisation's config, and it's the cmdlet that's missing.

What is the problem?

I am:

Running PS as 'Adminstrator'

Using the 'SharePointAdmin' administrator account for the credentials


问:
Calculating the index of an element in non-repetitive permutation
The following question is about math. The matter is, how to calculate the index of an element in a non-repetitive permutation. Example,

A={a,b,c}  The permutation is then 3!=6 therefore: (a,b,c);(a,c,b);(b,a,c);(b,c,a);(c,a,b);(c,b,a)

I researched for algorithm to get the index of an element in this permutation. In internet there are only repetitive permutation algorithms.
The index of (b,c,a) is in this zero-based list, obviously 3. Is there an easy way to calculate the position directly by formula ?
I do not need the itertools from python. Because i use very large permutations.(Example 120!) I messed once with python's itertools' permutations function to get the index of an element over the list iterator. But the results were weary. I need a mathematical solution to get the index directly.
Thanks for reading.

答:
Some clues:

You have n! permutations. Note that (n-1)! permutations start from the first element (a), next (n-1)! permutations start from the second element (b) and so on.

So you can calculate the first term of permutation rank as (n-1)! * Ord(P[0]) where Ord gives ordering number of the first element of permutation in initial sequence (0 for a, 1 for b etc).

Then continue with the second element using (n-2)! multiplier and so on.

Don't forget to exclude used elements from order - for your example b is used, so at the second stage c has index 1 rather 0, ad rank is 2!*1 + 1!*1 + 0! * 0 = 3


问:
I can't find the Syntax Error writing a formula with FormulaR1C1
```<code>ActiveCell.FormulaR1C1 = _
    "=IFERROR(VLOOKUP(C[-2],'PivotTable of DBS'!C[-2]:C[-1],2,0),"NOT FOUND")"
</code>```

when I'm running the macro it show me

"compile error: syntax error"

I don't know what I'm missing .

答:
May be its first cell reference as C[-2] and double quotes for Not Found words

Try This

```<code>ActiveCell.FormulaR1C1 = _
    "=IFERROR(VLOOKUP(RC[-2],'PivotTable of DBS'!C[-2]:C[-1],2,0),""Not
Found"")"
</code>```

Body:
ActiveCell.FormulaR1C1 = _
    "=IFERROR(VLOOKUP(C[-2],'PivotTable of DBS'!C[-2]:C[-1],2,0),"NOT FOUND")"

when I'm running the macro it show me

"compile error: syntax error"

I don't know what I'm missing .

Body:
May be its first cell reference as C[-2] and double quotes for Not Found words

Try This

ActiveCell.FormulaR1C1 = _
    "=IFERROR(VLOOKUP(RC[-2],'PivotTable of DBS'!C[-2]:C[-1],2,0),""Not
Found"")"


问:
How could I upload an icon I made in Adobe Illustrator to my HTML document?
I can export the file as an SVG, but how would I actually customize it with a hover effect afterwards? I use FontAwesome for most of my icons, but I'm not sure how I'd get my own icon to carry the  tag so that I could modify it the same way as the others.

Body:
you can use the svg that you've exported.and when you want to hover it and change the color you can change the "fill" of the svg o path tag!

svg:hover path{
  fill:blue;
}

<svg fill="red" xmlns="http://www.w3.org/2000/svg" width="26.484" height="26.484" viewBox="0 0 26.484 26.484">
  <path id="price-tag" d="M26.484,5.206,21.266,0H14.692L12.1,2.583A19.584,19.584,0,0,0,.391,5.721a.469.469,0,1,0,.546.763A18.724,18.724,0,0,1,11.209,3.471L2.816,11.837l0,0L0,14.653,11.805,26.484l4.713-4.7a6.965,6.965,0,0,0,3.208.756A6.1,6.1,0,0,0,24,20.988a7.184,7.184,0,0,0,1.616-8.278l.868-.866V5.206ZM20.878.939,25.545,5.6v5.859L16.373,20.6c-1.917-1.375-2.5-3.954-1.64-7.336a.469.469,0,1,0-.91-.232c-1.215,4.773.418,7.127,1.877,8.238L14.624,22.34,4.148,11.842l8.3-8.278a14.369,14.369,0,0,1,6.125,2.191,1.824,1.824,0,0,0-.032.318A1.871,1.871,0,1,0,18.974,4.9a15.291,15.291,0,0,0-5.689-2.17L15.08.939ZM19.63,6.479a.469.469,0,1,0,.563-.751c-.145-.108-.291-.2-.436-.306a.907.907,0,1,1-.207,1C19.577,6.442,19.6,6.458,19.63,6.479Zm-18.3,8.177,2.156-2.15,10.479,10.5-2.156,2.15Zm22.008,5.669a5.881,5.881,0,0,1-6.117.761l7.687-7.667A6.168,6.168,0,0,1,23.336,20.324Z" fill="red"/>
</svg>


问:
Can we Scaffold DbContext from selected tables of an existing database
As in previous versions of Entity Framework, is it possible in Entity Framework Core to reverse engineer only the selected tables of an existing database to create model classes out of them. This official ASP.NET site reverse engineers the entire database. In past, as shown in this ASP.NET tutorial, using old EF you could reverse engineer only the selected tables/Views if you chose to.</p>

答:
.NET Core CLI:

```<code>dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -o sakila -t actor -t film -t film_actor -t language -f
</code>```

Package Manager Console in Visual Studio:

```<code>Scaffold-DbContext "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -OutputDir Sakila -Tables actor,film,film_actor,language -f
</code>```

EF Core,MS SQL PM :

```<code>Scaffold-DbContext "server=PC\SQL2012;user=test;password=test123;database=student" Microsoft.EntityFrameworkCore.SqlServer -OutputDir student-Tables stu.names,stu.grades -f
</code>```

For more reference Visit entityframework-core-scaffold

Body:
.NET Core CLI:

dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -o sakila -t actor -t film -t film_actor -t language -f

Package Manager Console in Visual Studio:

Scaffold-DbContext "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -OutputDir Sakila -Tables actor,film,film_actor,language -f

EF Core,MS SQL PM :

Scaffold-DbContext "server=PC\SQL2012;user=test;password=test123;database=student" Microsoft.EntityFrameworkCore.SqlServer -OutputDir student-Tables stu.names,stu.grades -f

For more reference Visit entityframework-core-scaffold


问:
Faking HTTP request responses for testing in Android
I'm writing an Android app which sometimes needs to request data through HTTP from a REST API. I'm using the Apache DefaultHttpClient for performing requests. Is there a way to write tests for this app and "replace" DefaultHttpClient's response when running the tests so that test results are always consistent?

As an example of the things I'd like to test, one of the web services I'm accessing takes a string and performs a text search, returning a paged list of objects. I need to test the cases where the list is empty, the list fits in the first page, or the list is larger than a page and the app needs to make several requests to get the complete list.

I'm not the developer of this web API nor can modify its responses, so I can't change what it returns. For the above example, if I want to test the case where the list returned is empty, I could just search for a string which I'm sure won't return any results, but the other two cases are harder because what the service can return is always changing.

I think ideally I would have a way to get a modified DefaultHttpClient when running tests, that returns a hardcoded result for requests to a given URL instead of actually doing the network request. This way I would always get consistent results independently of the real web service's response.

I'm currently using Robotium for testing but I'm open to using other tools too.

答:
Yes, you can definitely "fake" responses when using the HttpClient framework. It's quite convoluted, and I will have to leave most of the details up to you, but I will give you a quick overview:

Implement ClientHttpRequestFactory, mainly so you can override the createRequest() method so you can...

Return your custom implementation of ClientHttpRequest, in which you can override the execute() method so you can ...

Return your custom implementation of ClientHttpResponse in which you will finally be able to return your fake response data, e.g. getBody() can return the content of a file, you can hardcode the headers in getHeaders(), etc.

The rest is figuring out how to best tie all these shenanigans to your service layer.


问:
LoggedInSessionBean reference
Trying travelocity.com for SAML with wso2 and unable to show the SAML returned claim because of this error:

```<code>HTTP Status 500 – Internal Server Error
Type Exception Report

Message javax.xml.parsers.FactoryConfigurationError: Provider org.apache.xerces.jaxp.DocumentBuilderFactoryImpl not found
Exception

javax.servlet.ServletException: javax.xml.parsers.FactoryConfigurationError: Provider org.apache.xerces.jaxp.DocumentBuilderFactoryImpl not found
Root Cause

javax.xml.parsers.FactoryConfigurationError: Provider org.apache.xerces.jaxp.DocumentBuilderFactoryImpl not found
`
Jar file xercesImpl-2.8.1.jar is in lib folder under travelocity.com application but seems it is not able to read it.

I saw that in the runtime tomcat : HTTP Session created without LoggedInSessionBean and the page getting the 500 error is using this reference:  <%@ page import="org.wso2.carbon.identity.sso.agent.bean.LoggedInSessionBean" %>
</code>```

Any clue why getting this?

答:
This similar issue was already reported here and can be solved  when copying xercesimpl-2.8.1.jar into /usr/share/tomcat7/lib in tomcat instance and restart the tomcat server.

Please try the workareound mentioned in the jira

Title: LoggedInSessionBean reference

Body:
Trying travelocity.com for SAML with wso2 and unable to show the SAML returned claim because of this error:

HTTP Status 500 – Internal Server Error
Type Exception Report

Message javax.xml.parsers.FactoryConfigurationError: Provider org.apache.xerces.jaxp.DocumentBuilderFactoryImpl not found
Exception

javax.servlet.ServletException: javax.xml.parsers.FactoryConfigurationError: Provider org.apache.xerces.jaxp.DocumentBuilderFactoryImpl not found
Root Cause

javax.xml.parsers.FactoryConfigurationError: Provider org.apache.xerces.jaxp.DocumentBuilderFactoryImpl not found
`
Jar file xercesImpl-2.8.1.jar is in lib folder under travelocity.com application but seems it is not able to read it.

I saw that in the runtime tomcat : HTTP Session created without LoggedInSessionBean and the page getting the 500 error is using this reference:  <%@ page import="org.wso2.carbon.identity.sso.agent.bean.LoggedInSessionBean" %>

Any clue why getting this?


问:
How do I include HTML bits from another file in a bookmarklet?
I have a bookmarklet written in jQuery where I'm creating elements and adding them to the DOM.

```<code>$dot = $('<span class="dot" style="left:0;top:0;" />');
$('body').append($dot);
</code>```

Is there a way I can include HTML without writing it directly in the .js file? The span above is pretty simple, but how can I create a sophisticated form without making it a maintenance nightmare?

EDIT

To clarify, I know how to load the script via bookmarklet, but I was wondering if there's any easy way to refrence complex pieces of HTML in the .js file so I don't have long, complex, embedded strings of HTML to maintain inside that one file.

答:
Use an ajax request to load some html data from your server, but be sure to add a cache param to your bookmarklet's script include.

document.createElement("script");, add the source, and append it to the current page somewhere (head, body, it's up to you).

EDIT: I may not have been clear enough, but you will want to load the script file from your domain which would then run any ajax requests. Your bookmarklet would then just become a container to test if the dom is ready and append a script (from your server) if so.

Body:
I have a bookmarklet written in jQuery where I'm creating elements and adding them to the DOM.

$dot = $('');
$('body').append($dot);

Is there a way I can include HTML without writing it directly in the .js file? The span above is pretty simple, but how can I create a sophisticated form without making it a maintenance nightmare?

EDIT

To clarify, I know how to load the script via bookmarklet, but I was wondering if there's any easy way to refrence complex pieces of HTML in the .js file so I don't have long, complex, embedded strings of HTML to maintain inside that one file.


问:
vscode activating extension failed: Cannot find module with non-relative import
I am working on a Visual Studio Code extension, where I am using non-relative imports in typescript, for example:

```<code>import ModuleA from 'modules/ModuleA';
</code>```

Where the actual folder to ModuleA is src/modules/ModuleA and the tsconfig.json is as follows, where I specify src as the baseUrl:

```<code>{
  "compilerOptions": {
    "baseUrl": "./src",
    "module": "commonjs",
    "target": "es6",
    "outDir": "out",
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "lib": [
      "es6"
    ],
    "sourceMap": true,
    "strictNullChecks": true,
    "experimentalDecorators": true,
    "moduleResolution": "node"
  },
  "exclude": [
    "node_modules",
    ".vscode-test"
  ]
}
</code>```

Everything compiles and builds just fine, however, when I attempt to launch the extension for testing, I get the error: Activating extension failed: Cannot find module 'modules/ModuleA'. My .vscode/launch.json file that I use to launch the extension looks like this:

```<code>// A launch configuration that compiles the extension and then opens it inside a new window
{
  "version": "0.1.0",
  "configurations": [
    {
      "name": "Launch Extension",
      "type": "extensionHost",
      "request": "launch",
      "runtimeExecutable": "${execPath}",
      "args": ["--extensionDevelopmentPath=${workspaceRoot}" ],
      "stopOnEntry": false,
      "sourceMaps": true,
      "outFiles": ["${workspaceRoot}/out"],
      "preLaunchTask": "build",
      "internalConsoleOptions" : "openOnSessionStart"
  }
  ]
}
</code>```

How do I get non-relative paths working for developing vscode extensions?

答:
I have a similar experience, I reinstall the node, the same version, and the problem was solved.

I am using Mac, so:

```<code>sudo rm -rf /usr/local/lib/node_modules/npm
brew reinstall node
</code>```

Reference: Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

Body:
I am working on a Visual Studio Code extension, where I am using non-relative imports in typescript, for example:

import ModuleA from 'modules/ModuleA';

Where the actual folder to ModuleA is src/modules/ModuleA and the tsconfig.json is as follows, where I specify src as the baseUrl:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "module": "commonjs",
    "target": "es6",
    "outDir": "out",
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "lib": [
      "es6"
    ],
    "sourceMap": true,
    "strictNullChecks": true,
    "experimentalDecorators": true,
    "moduleResolution": "node"
  },
  "exclude": [
    "node_modules",
    ".vscode-test"
  ]
}

Everything compiles and builds just fine, however, when I attempt to launch the extension for testing, I get the error: Activating extension failed: Cannot find module 'modules/ModuleA'. My .vscode/launch.json file that I use to launch the extension looks like this:

// A launch configuration that compiles the extension and then opens it inside a new window
{
  "version": "0.1.0",
  "configurations": [
    {
      "name": "Launch Extension",
      "type": "extensionHost",
      "request": "launch",
      "runtimeExecutable": "${execPath}",
      "args": ["--extensionDevelopmentPath=${workspaceRoot}" ],
      "stopOnEntry": false,
      "sourceMaps": true,
      "outFiles": ["${workspaceRoot}/out"],
      "preLaunchTask": "build",
      "internalConsoleOptions" : "openOnSessionStart"
  }
  ]
}

How do I get non-relative paths working for developing vscode extensions?

Body:
I have a similar experience, I reinstall the node, the same version, and the problem was solved.

I am using Mac, so:

sudo rm -rf /usr/local/lib/node_modules/npm
brew reinstall node

Reference: Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic


问:
What could be causing epub, mobi and zip files to fail to download on an iPhone running ios 13?
I am having problems on my local server when trying to serve files to an iPhone running ios13. The problems only occur with file types that cannot be rendered in the browser, by that I mean files such as epub, mobi and zip that require me to manually click on download.

Files such as text and pdf have no issue in any browser.

Safari is able to download Mobi, Epub and Zip files, but Chrome, Firefox and Edge all fail giving vague messages like “Couldn’t Download” or “Download Failed”. Try Again.

Originally I was serving the files using Nginx, X-Accel-Redirect and PHP, but I found that using a direct url had the same problem. The server is running HTTPS and HTTP2. Mime types are properly configured in Nginx.

In each case, regardless of whether the file was successfully downloaded or not, the access logs showed status code 200.

My questions are:

What could be causing the failed downloads and how can I fix it?

What other things should I investigate to shed more light on this
issue?

答:
It seems that the SSL certificate on the local server was causing the download issues. It was a self signed certificate and it often causes warnings to be displayed in the browser.

I uploaded the epub/mobi/zip files to a server that didn’t use HTTPS and found that mobi, epub and zip files successfully downloaded regardless of the mobile browser used.

I did the same with another server using a properly signed HTTPS certificate (letsencrypt) and again found that the mobi, epub and zip files successfully downloaded regardless of the mobile browser used.


问:
How Do I Output Multiselect Attribute Values In Magento 2.3.x?
In a Magento 2.3.3 store I am trying to ouput the values of a multiselect custom attribute on a category page, but not having any luck.
I have set the attribute to be used in product listing and tried to output it on catalog/product/listing.phtml template page in my custom theme.
I am using the using the following code:
<?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('custom_attribute')->getFrontend()->getValue($_product); ?>
This is working for dropdown attributes but not multi select attributes.
Kind of stuck on this...

答:
You can use the below code to get MultiSelect Attribute value

create block in "catalog_product_view.xml"

```<code><referenceBlock name="product.info.main">
    <block class="Magento\Catalog\Block\Product\View" name="attribue.name" template="Magento_Catalog::product/view/attribute_name.phtml" after="-"  />
</referenceBlock>
</code>```

create "phtml" file under "Magento_Catalog::product/view/attribute_name.phtml"

```<code><?php $product = $block->getProduct(); ?>
<div>
  <?php
    $data = explode(',',$product->getData('attribute_code'));
    foreach($data as $value):
  ?>
  <?php
    $attr = $product->getResource()->getAttribute('attribute_code');
    if ($attr->usesSource()):
  ?>
        <?php
            $option_value = $attr->getSource()->getOptionText($value);
        ?>
        <p><?php echo $option_value; ?></p>
    <?php endif;?>
 <?php endforeach;?>
</div>
</code>```

Body:
You can use the below code to get MultiSelect Attribute value

create block in "catalog_product_view.xml"

<referenceBlock name="product.info.main">
    <block class="Magento\Catalog\Block\Product\View" name="attribue.name" template="Magento_Catalog::product/view/attribute_name.phtml" after="-"  />
</referenceBlock>

create "phtml" file under "Magento_Catalog::product/view/attribute_name.phtml"

<?php $product = $block->getProduct(); ?>
<div>
  <?php
    $data = explode(',',$product->getData('attribute_code'));
    foreach($data as $value):
  ?>
  <?php
    $attr = $product->getResource()->getAttribute('attribute_code');
    if ($attr->usesSource()):
  ?>
        <?php
            $option_value = $attr->getSource()->getOptionText($value);
        ?>
        <p><?php echo $option_value; ?></p>
    <?php endif;?>
 <?php endforeach;?>
</div>


问:
I have click event attached to elements
, but it only fires once on the first

I have click event attached to elements
, but it only fires once on the first
. I can see its child element also has click event attached. Please help.

$(document).ready(function(){
  $(".nav-item").click(function(){
    console.log("I am clicked");
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <!-- Brand -->
  Navbar

  <!-- Toggler/collapsibe Button -->
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>

  <!-- Navbar links -->
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="myclick nav-item dropdown">
        Link A
        <div class="dropdown-menu">
          Link 1
          Link 2
          Link 3
        </div>
      </li>
      <li class="myclick nav-item">
        Link B
      </li>
      <li class="myclick nav-item">
        Link C
      </li>
    </ul>
  </div>
</nav>

</body>
</html></code>```

答:
Location of Javascript inside your HTML is very crucial. Looks like the click event is not properly attached with the HTML DOM elements.

Solution:

```<code>$(document).ready(function(){
   $(".nav-item").on("click", function(e){
     console.log("I am clicked");
   });
})
</code>```

Title: I have click event attached to elements <li>, but it only fires once on the first <li>

Body:
I have click event attached to elements
, but it only fires once on the first
. I can see its child element also has click event attached. Please help.

$(document).ready(function(){
  $(".nav-item").click(function(){
    console.log("I am clicked");
  });
})

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

  Navbar

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

  </button>

        Link A

          Link 1
          Link 2
          Link 3

        Link B

        Link C

Body:
Location of Javascript inside your HTML is very crucial. Looks like the click event is not properly attached with the HTML DOM elements.

Solution:

$(document).ready(function(){
   $(".nav-item").on("click", function(e){
     console.log("I am clicked");
   });
})


问:
Add Background to ImageSpan
I am trying to add a background span to the image. I can set a background span to strings, but the imagespan in the same string does not show the background.

This is a sample of what I want, the selected part shows an image and text with background span.

This is what I have tried.

```<code>    public void applySpannable(String lastString, String changeString, int type, String title) {

        String totalString = lastString + title;
        Spannable spanText = new SpannableString(totalString);

        Drawable d;
        if (type == 1) {
            d = getResources().getDrawable(R.drawable.type_flag_bg_red);
        } else {
            d = getResources().getDrawable(R.drawable.type_flag_bg_red);
        }
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);

        ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.WHITE);
        BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.RED);

        spanText.setSpan(foregroundSpan, lowerBound, upperBound, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spanText.setSpan(backgroundSpan, lowerBound, upperBound, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spanText.setSpan(span, lastString.length(), lastString.length()+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        edtAddTask.setText(spanText);
        edtAddTask.setSelection(edtAddTask.getText().toString().length());
    }
</code>```

The string appears with background, but transparent image is shown without background. I have set the lower index ahead of image position.

Thanks

答:
You can't use BackgroundColorSpan and ImageSpan at the same time. The idea is creating an ImageSpan from LayerDrawable with background and image layers. Please look at the following code:

Try this for java:

```<code>Spannable span = new SpannableString("This is   ic launcher with background");
Drawable myImage = context.getResources().getDrawable(R.drawable.ic_launcher_foreground);
ShapeDrawable background = new ShapeDrawable();
background.getPaint().setColor(Color.RED);
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{background, myImage});
layerDrawable.setBounds(0, 0, 64, 64);
ImageSpan image = new ImageSpan(layerDrawable, ImageSpan.ALIGN_BASELINE);
span.setSpan(image, 8, 9, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

textView.setText(span);
</code>```

For kotlin:

```<code>val span: Spannable = SpannableString("This is   ic launcher with background")
val myImage: Drawable = resources.getDrawable(R.drawable.ic_launcher_foreground)
val background = ShapeDrawable()
background.paint.color = Color.RED
val layerDrawable = LayerDrawable(arrayOf(background, myImage))
layerDrawable.setBounds(0, 0, 64, 64)
val image = ImageSpan(layerDrawable, ImageSpan.ALIGN_BASELINE)
span.setSpan(image, 8, 9, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)

textView.setText(span)
</code>```

From this answer: https://stackoverflow.com/a/60150320/6160172

Title: Add Background to ImageSpan

Body:
I am trying to add a background span to the image. I can set a background span to strings, but the imagespan in the same string does not show the background.

This is a sample of what I want, the selected part shows an image and text with background span.

This is what I have tried.

    public void applySpannable(String lastString, String changeString, int type, String title) {

        String totalString = lastString + title;
        Spannable spanText = new SpannableString(totalString);

        Drawable d;
        if (type == 1) {
            d = getResources().getDrawable(R.drawable.type_flag_bg_red);
        } else {
            d = getResources().getDrawable(R.drawable.type_flag_bg_red);
        }
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);

        ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.WHITE);
        BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.RED);

        spanText.setSpan(foregroundSpan, lowerBound, upperBound, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spanText.setSpan(backgroundSpan, lowerBound, upperBound, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spanText.setSpan(span, lastString.length(), lastString.length()+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        edtAddTask.setText(spanText);
        edtAddTask.setSelection(edtAddTask.getText().toString().length());
    }

The string appears with background, but transparent image is shown without background. I have set the lower index ahead of image position.

Thanks

Body:
You can't use BackgroundColorSpan and ImageSpan at the same time. The idea is creating an ImageSpan from LayerDrawable with background and image layers. Please look at the following code:

Try this for java:

Spannable span = new SpannableString("This is   ic launcher with background");
Drawable myImage = context.getResources().getDrawable(R.drawable.ic_launcher_foreground);
ShapeDrawable background = new ShapeDrawable();
background.getPaint().setColor(Color.RED);
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{background, myImage});
layerDrawable.setBounds(0, 0, 64, 64);
ImageSpan image = new ImageSpan(layerDrawable, ImageSpan.ALIGN_BASELINE);
span.setSpan(image, 8, 9, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

textView.setText(span);

For kotlin:

val span: Spannable = SpannableString("This is   ic launcher with background")
val myImage: Drawable = resources.getDrawable(R.drawable.ic_launcher_foreground)
val background = ShapeDrawable()
background.paint.color = Color.RED
val layerDrawable = LayerDrawable(arrayOf(background, myImage))
layerDrawable.setBounds(0, 0, 64, 64)
val image = ImageSpan(layerDrawable, ImageSpan.ALIGN_BASELINE)
span.setSpan(image, 8, 9, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)

textView.setText(span)

From this answer: https://stackoverflow.com/a/60150320/6160172


问:
Make the hover work even after a jquery bind('click')?
Basically, I wanted to make the hover work even after a bind click, but I set the .image26 and 27 to it's default background. The hover works at first, but when clicked, since I reset it back to default, does not work again.

Is there a better approach on this? If I did not put the rest of the image to it's default position, then all of them will be marked as clicked.

Working sample:
http://jsfiddle.net/louiemiranda/RkM3t/

The jquery code:

```<code>$(".image22").bind("click", function(event){
    $(this).css("background-position", "0 100%");
    $('#package22').attr("checked", "checked");
    $('.image26').css("background-position", "0 0");
    $('.image27').css("background-position", "0 0");
    var cashcredit = $('#package22').val();
    $('#fyi').html(cashcredit);
});

$(".image22").bind("mouseenter mouseleave", function(event){
    $(this).toggleClass("image22-selected");
});
</code>```

Any help is appreciated. Thanks!

答: gutted a lot of your code but I think this is what your going for? http://jsfiddle.net/locrizak/LqWxt/</p>

Body:
Basically, I wanted to make the hover work even after a bind click, but I set the .image26 and 27 to it's default background. The hover works at first, but when clicked, since I reset it back to default, does not work again.

Is there a better approach on this? If I did not put the rest of the image to it's default position, then all of them will be marked as clicked.

Working sample:
http://jsfiddle.net/louiemiranda/RkM3t/

The jquery code:

$(".image22").bind("click", function(event){
    $(this).css("background-position", "0 100%");
    $('#package22').attr("checked", "checked");
    $('.image26').css("background-position", "0 0");
    $('.image27').css("background-position", "0 0");
    var cashcredit = $('#package22').val();
    $('#fyi').html(cashcredit);
});

$(".image22").bind("mouseenter mouseleave", function(event){
    $(this).toggleClass("image22-selected");
});

Any help is appreciated. Thanks!


问:
Many to many relation entries not added by .add() method in Django
I am having a problem regarding adding entry to a many to many relation field. I have the models as follows

class Address(models.Model):
    id = models.AutoField(primary_key=True)
    country = CountryField(blank_label='(select country)', blank=False, null=False, verbose_name='Country')
    state = models.CharField(
        max_length=50,
        choices=STATE_CHOICES,
        verbose_name='State',
        blank=False,
        null=False
    )
    ...

class Volunteer(models.Model):
    userID = models.OneToOneField(User, on_delete=models.CASCADE, to_field='id', primary_key=True, related_name='volunteer')
    identificationNumber = models.CharField(max_length=50, unique=True, blank=False, null=False, verbose_name='Identification   Number')
    currentAddress = models.ManyToManyField(Address, related_name='volunteerCurrentAddress', verbose_name='Current Address', blank=False)
    permanentAddress = models.ManyToManyField(Address, related_name='volunteerPermanentAddress', verbose_name='Permanent Address', blank=False)
    ...

    def save(self, *args, **kwargs):
        self.slug = self.userID.username
        super(Volunteer, self).save(*args, **kwargs)

class TemporaryVolunteer(Volunteer):
    pass
```

<p>And in the views, I get both the <code>currentAddress</code> and <code>permanentAddress</code> fields as a <code>ManyToManyRelatedManager</code>. They are <code>temporaryVolunteer.currentAddress</code> and <code>temporaryVolunteer.permanentAddress</code>. I use these to create a new Volunteer instance as</p>

<pre class="lang-py prettyprint-override"><code>volunteer = Volunteer(...)
volunteer.save()
volunteer.currentAddress.add(temporaryVolunteer.currentAddress.all()[0])
volunteer.permanentAddress.add(temporaryVolunteer.permanentAddress.all()[0])
volunteer.save()
</code>```

But when I do print(volunteer.currentAddress.all()) or print(volunteer.permanentAddress.all()), it returns an empty queryset. I also checked the admin site for confirmation and there are no entries of address on the volunteer instance.
Is there any way the entries can be added with this approach?

答:
The problem was in the design of the database. I had used a new class TemporaryVolunteer in order to store unverified accounts and later moved to the Volunteer class after they were verfied. As I had inherited TemporaryVolunteer from Volunteer class, the way Django handles Many to many relationships without making duplicates (Source: https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_many/) led to the problem of no entries being added in the corresponding Volunteer class.

Initially, I checked this by copying all the members of Volunteer to TemporaryVolunteer. After verifying that it worked, I changed the database design as this is a bad approach and kept a boolean value isVerified in the Volunteer class and removed the TemporaryVolunteer class entirely.

Body:
I am having a problem regarding adding entry to a many to many relation field. I have the models as follows

class Address(models.Model):
    id = models.AutoField(primary_key=True)
    country = CountryField(blank_label='(select country)', blank=False, null=False, verbose_name='Country')
    state = models.CharField(
        max_length=50,
        choices=STATE_CHOICES,
        verbose_name='State',
        blank=False,
        null=False
    )
    ...

class Volunteer(models.Model):
    userID = models.OneToOneField(User, on_delete=models.CASCADE, to_field='id', primary_key=True, related_name='volunteer')
    identificationNumber = models.CharField(max_length=50, unique=True, blank=False, null=False, verbose_name='Identification   Number')
    currentAddress = models.ManyToManyField(Address, related_name='volunteerCurrentAddress', verbose_name='Current Address', blank=False)
    permanentAddress = models.ManyToManyField(Address, related_name='volunteerPermanentAddress', verbose_name='Permanent Address', blank=False)
    ...

    def save(self, *args, **kwargs):
        self.slug = self.userID.username
        super(Volunteer, self).save(*args, **kwargs)

class TemporaryVolunteer(Volunteer):
    pass

And in the views, I get both the currentAddress and permanentAddress fields as a ManyToManyRelatedManager. They are temporaryVolunteer.currentAddress and temporaryVolunteer.permanentAddress. I use these to create a new Volunteer instance as

volunteer = Volunteer(...)
volunteer.save()
volunteer.currentAddress.add(temporaryVolunteer.currentAddress.all()[0])
volunteer.permanentAddress.add(temporaryVolunteer.permanentAddress.all()[0])
volunteer.save()

But when I do print(volunteer.currentAddress.all()) or print(volunteer.permanentAddress.all()), it returns an empty queryset. I also checked the admin site for confirmation and there are no entries of address on the volunteer instance.
Is there any way the entries can be added with this approach?


问:
VS code extension "HelloWorld" sample in typescript is not working
I'm trying to create VS code extension and followed the steps provided in documentation here

I setup "helloworld" project in typescript but when i press "F5", nothing happening. I saw, typescript files complied to JS but project is not opening new instance of VS code and enable debug mode not enabled on "F5".

Any suggestions ?.

launch.json file

```<code>{
"version": "0.2.0",
"configurations": [
    {
        "name": "Extension",
        "type": "extensionHost",
        "request": "launch",
        "runtimeExecutable": "${execPath}",
        "args": [
            "--extensionDevelopmentPath=${workspaceFolder}"
        ],
        "outFiles": [
            "${workspaceFolder}/out/**/*.js"
        ],
        "preLaunchTask": "npm: watch"
    },
    {
        "name": "Extension Tests",
        "type": "extensionHost",
        "request": "launch",
        "runtimeExecutable": "${execPath}",
        "args": [
            "--extensionDevelopmentPath=${workspaceFolder}",
            "--extensionTestsPath=${workspaceFolder}/out/test"
        ],
        "outFiles": [
            "${workspaceFolder}/out/test/**/*.js"
        ],
        "preLaunchTask": "npm: watch"
    },

]
</code>```

}

Steps i followed is same as mentioned in VS code doc

npm install -g yo generator-code

yo code

Launch VS Code,

choose File > Open Folder and pick the folder that you generated.

Press F5 or click on the Debug icon and click Start.

For me step #5 is not working and not doing anything

答:
For my case, I just reinstall the node, the same version, the problem solved.

```<code>sudo rm -rf /usr/local/lib/node_modules/npm
brew reinstall node
</code>```

Reference: Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

Body:
I'm trying to create VS code extension and followed the steps provided in documentation here

I setup "helloworld" project in typescript but when i press "F5", nothing happening. I saw, typescript files complied to JS but project is not opening new instance of VS code and enable debug mode not enabled on "F5".

Any suggestions ?.

launch.json file

{
"version": "0.2.0",
"configurations": [
    {
        "name": "Extension",
        "type": "extensionHost",
        "request": "launch",
        "runtimeExecutable": "${execPath}",
        "args": [
            "--extensionDevelopmentPath=${workspaceFolder}"
        ],
        "outFiles": [
            "${workspaceFolder}/out/**/*.js"
        ],
        "preLaunchTask": "npm: watch"
    },
    {
        "name": "Extension Tests",
        "type": "extensionHost",
        "request": "launch",
        "runtimeExecutable": "${execPath}",
        "args": [
            "--extensionDevelopmentPath=${workspaceFolder}",
            "--extensionTestsPath=${workspaceFolder}/out/test"
        ],
        "outFiles": [
            "${workspaceFolder}/out/test/**/*.js"
        ],
        "preLaunchTask": "npm: watch"
    },

]

}

Steps i followed is same as mentioned in VS code doc

npm install -g yo generator-code

yo code

Launch VS Code,

choose File > Open Folder and pick the folder that you generated.

Press F5 or click on the Debug icon and click Start.

For me step #5 is not working and not doing anything

Body:
For my case, I just reinstall the node, the same version, the problem solved.

sudo rm -rf /usr/local/lib/node_modules/npm
brew reinstall node

Reference: Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic