问:
Implementing SmoothL1Loss for specific case
I have been experimenting with L1 and MSE losses in Pytorch and noticing that L1Loss performs better because it is more robust to outliers. I discovered SmoothL1Loss which seems to be the best of both worlds. I understand that it behaves like MSELoss for error<1 and like L1Loss otherwise. My dataset only contains values between 0 and 1. Therefore the largest possible error is 1. Does this mean the function behaves identical to MSELoss? Is it possible adjust the threshold in anyway to work better for my problem?</p>

答:
Yes, in this case it acts just like torch.nn.MSELoss, and it is called Huber Loss all in all.

Due to it's nature threshold doesn't make much sense, let's look at example why that is the case:

How it works

Let's compare errors being larger than 1.0 in case of MSELoss and SmoothL1Loss. Assume our absolute error (|f(x) - y|) is 10. MSELoss would give it value of 100 (or 50 in case of pytorch implementation), while SmoothL1Loss gives just this value of 10, hence it won't punish the model so much for large errors.

In case of value below 1.0 SmoothL1Loss punishes the model less than L1Loss. E.g. 0.5 would become 0.5*0.5 so 0.25 for Huber and 0.5 for L1Loss.

It's not "best of both worlds" it depends what you are after. Mean Squared Error - amplifies large errors and downplays the small ones, L1Loss gives errors "equal" weight let's say.

Custom loss function

Though it's not usually done you could use any loss function you'd like, depending on your goal (threshold doesn't really make sense here). If you want smaller errors to be more severe you could, for example, do something like this:

```<code>import torch

def fancy_squared_loss(y_true, y_pred):
    return torch.mean(torch.sqrt(torch.abs(y_true - y_pred)))
</code>```

For value 0.2 you would get ~0.447, for 0.5 ~0.7 and so on. Experiment and check whether any specific loss functions exist for task at hand, though I think it's unlikely those experiments will give you significant boost over L1Loss if any.

Custom threshold

If you really want to set custom threshold for MSELoss and L1Loss you could implement it on your own though:

```<code>import torch

class CustomLoss:
    def __init__(self, threshold: float = 0.5):
        self.threshold = threshold

    def __call__(self, predicted, true):
        errors = torch.abs(predicted - true)
        mask = errors < self.threshold
        return (0.5 * mask * (errors ** 2)) + ~mask * errors
</code>```

Everything below threshold would get MSELoss while all above would have L1Loss.

Body:
Yes, in this case it acts just like torch.nn.MSELoss, and it is called Huber Loss all in all.

Due to it's nature threshold doesn't make much sense, let's look at example why that is the case:

How it works

Let's compare errors being larger than 1.0 in case of MSELoss and SmoothL1Loss. Assume our absolute error (|f(x) - y|) is 10. MSELoss would give it value of 100 (or 50 in case of pytorch implementation), while SmoothL1Loss gives just this value of 10, hence it won't punish the model so much for large errors.

In case of value below 1.0 SmoothL1Loss punishes the model less than L1Loss. E.g. 0.5 would become 0.5*0.5 so 0.25 for Huber and 0.5 for L1Loss.

It's not "best of both worlds" it depends what you are after. Mean Squared Error - amplifies large errors and downplays the small ones, L1Loss gives errors "equal" weight let's say.

Custom loss function

Though it's not usually done you could use any loss function you'd like, depending on your goal (threshold doesn't really make sense here). If you want smaller errors to be more severe you could, for example, do something like this:

import torch

def fancy_squared_loss(y_true, y_pred):
    return torch.mean(torch.sqrt(torch.abs(y_true - y_pred)))

For value 0.2 you would get ~0.447, for 0.5 ~0.7 and so on. Experiment and check whether any specific loss functions exist for task at hand, though I think it's unlikely those experiments will give you significant boost over L1Loss if any.

Custom threshold

If you really want to set custom threshold for MSELoss and L1Loss you could implement it on your own though:

import torch

class CustomLoss:
    def __init__(self, threshold: float = 0.5):
        self.threshold = threshold

    def __call__(self, predicted, true):
        errors = torch.abs(predicted - true)
        mask = errors < self.threshold
        return (0.5 * mask * (errors ** 2)) + ~mask * errors

Everything below threshold would get MSELoss while all above would have L1Loss.


来源: stackexchange

问:
JAVA return longest value if a string contains any of the items from a List
I have the following array of code types:

```<code>["sample_code","code","formal_code"]
</code>```

and the following ids:

```<code>String id="123456789_sample_code_xyz";
String id2="91343486_code_zxy";
</code>```

I want to extract the code type from the ids

this is my code snippet:

```<code>    String codeTypes[] = {"sample_code","code","formal_code"};
    String id= "123456789_sample_code_xyz";
    String codeType = Arrays.stream(codeTypes).parallel().filter(id::contains).findAny().get();
    System.out.println(codeType);
</code>```

it doesnt work with the 1st id, because it returns "code" instead of "sample_code", I want to get the longest code type.

```<code>for the 1st id the code type should be "sample_code"
for the 2nd id the code type should be "code"
</code>```

答:
Well, stream API is not suitable for every problem. I think you can use a non-stream version to solve your problem.

I just looped over codeTypes array and for every codeType, have replaced idx with empty string then calculate its length and find min length between idX string and replace.
now if minSize length with replace string length is the same, then it is the candidate for the final result.  minSize != id.length() is for when the time that there is not any codeType.

```<code>private static String findCodeType(String id, String[] codeTypes) {
    int minSize = id.length();
    String codeType = "NotFound";
    for (String code : codeTypes) {
        String replace = id.replaceAll(code, "");
        minSize = Integer.min(minSize, replace.length());
        if (minSize == replace.length() && minSize != id.length())
            codeType = code;
    }
    return codeType;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following array of code types:

["sample_code","code","formal_code"]

and the following ids:

String id="123456789_sample_code_xyz";
String id2="91343486_code_zxy";

I want to extract the code type from the ids

this is my code snippet:

    String codeTypes[] = {"sample_code","code","formal_code"};
    String id= "123456789_sample_code_xyz";
    String codeType = Arrays.stream(codeTypes).parallel().filter(id::contains).findAny().get();
    System.out.println(codeType);

it doesnt work with the 1st id, because it returns "code" instead of "sample_code", I want to get the longest code type.

for the 1st id the code type should be "sample_code"
for the 2nd id the code type should be "code"

Body:
Well, stream API is not suitable for every problem. I think you can use a non-stream version to solve your problem.

I just looped over codeTypes array and for every codeType, have replaced idx with empty string then calculate its length and find min length between idX string and replace.
now if minSize length with replace string length is the same, then it is the candidate for the final result.  minSize != id.length() is for when the time that there is not any codeType.

private static String findCodeType(String id, String[] codeTypes) {
    int minSize = id.length();
    String codeType = "NotFound";
    for (String code : codeTypes) {
        String replace = id.replaceAll(code, "");
        minSize = Integer.min(minSize, replace.length());
        if (minSize == replace.length() && minSize != id.length())
            codeType = code;
    }
    return codeType;
}


问:
How do I split a .txt file into a multidimensional array or dictionary in Swift?
The body of my txt file that I need to parse in in this format:

```<code>Name: LittleX
Package: com.ioscreatix.littlex
Description: iPhone X features for Non-X devices on iOS 11, and iPad Dock and PiP for All iOS 11 Devices on iOS 11

Name: InteliX
Package: com.ioscreatix.intelix
Description: Grouped Notifications for iOS 11
</code>```

I want my array to have each package separately in an array listed by their name values with a dictionary for  description and package. How would I accomplish this?

This is the code i have so far:

```<code>var unfilteredPackagesArray = [String]()
    var secondFilteredPackagesArray = [String]()
    var finalFilteredPackagesArray = [String]()

if let startWordsURL = Bundle.main.url(forResource: "Packages", withExtension: "") {
            if let startWords = try? String(contentsOf: startWordsURL) {
                unfilteredPackagesArray = startWords.components(separatedBy: "\n\n")

                print(unfilteredPackagesArray)
                secondFilteredPackagesArray = startWords.components(separatedBy: "\n")

                finalFilteredPackagesArray = startWords.components(separatedBy: ":")

                print(secondFilteredPackagesArray)
</code>```

What is the best way to do this? Create Package objects and make an array of them?

答:
Yes, go ahead!

Yes, I think you should create a Package struct and then generate an array of Package(s).

Here's the code.

1. Define the Package struct

```<code>struct Package {
    let name: String
    let package: String
    let description: String
}
</code>```

2. Load the file

```<code>guard
    let url = Bundle.main.url(forResource: "Packages", withExtension: "txt"),
    let content = try? String(contentsOf: url)
else { fatalError() }
</code>```

3. Extract the lines

```<code>let lines = content
    .components(separatedBy: CharacterSet.newlines)
    .filter { !$0.isEmpty }
    .compactMap { $0.components(separatedBy: ": ").last }
</code>```

4. Extract the 3 arrays

```<code>let nameLines = lines.enumerated().filter { $0.offset % 3 == 0 }.map { $0.element }
let packageLines = lines.enumerated().filter { $0.offset % 3 == 1 }.map { $0.element }
let descriptionLines = lines.enumerated().filter { $0.offset % 3 == 2 }.map { $0.element }
</code>```

5. Generate an array of Package(s)

```<code>let packages = zip(nameLines, zip(packageLines, descriptionLines))
    .map { (name: $0, package: $1.0, description: $1.1) }
    .map (Package.init)
</code>```

6. Test

```<code>print(packages)

[
    Package(name: "LittleX",
            package: "com.ioscreatix.littlex",
            description: "iPhone X features for Non-X devices on iOS 11, and iPad Dock and PiP for All iOS 11 Devices on iOS 11"
    ),
    Package(name: "InteliX",
            package: "com.ioscreatix.intelix",
            description: "Grouped Notifications for iOS 11"
    )
]
</code>```

Body:
The body of my txt file that I need to parse in in this format:

Name: LittleX
Package: com.ioscreatix.littlex
Description: iPhone X features for Non-X devices on iOS 11, and iPad Dock and PiP for All iOS 11 Devices on iOS 11

Name: InteliX
Package: com.ioscreatix.intelix
Description: Grouped Notifications for iOS 11

I want my array to have each package separately in an array listed by their name values with a dictionary for  description and package. How would I accomplish this?

This is the code i have so far:

var unfilteredPackagesArray = [String]()
    var secondFilteredPackagesArray = [String]()
    var finalFilteredPackagesArray = [String]()

if let startWordsURL = Bundle.main.url(forResource: "Packages", withExtension: "") {
            if let startWords = try? String(contentsOf: startWordsURL) {
                unfilteredPackagesArray = startWords.components(separatedBy: "\n\n")

                print(unfilteredPackagesArray)
                secondFilteredPackagesArray = startWords.components(separatedBy: "\n")

                finalFilteredPackagesArray = startWords.components(separatedBy: ":")

                print(secondFilteredPackagesArray)

What is the best way to do this? Create Package objects and make an array of them?

Body:
Yes, go ahead!

Yes, I think you should create a Package struct and then generate an array of Package(s).

Here's the code.

1. Define the Package struct

struct Package {
    let name: String
    let package: String
    let description: String
}

2. Load the file

guard
    let url = Bundle.main.url(forResource: "Packages", withExtension: "txt"),
    let content = try? String(contentsOf: url)
else { fatalError() }

3. Extract the lines

let lines = content
    .components(separatedBy: CharacterSet.newlines)
    .filter { !$0.isEmpty }
    .compactMap { $0.components(separatedBy: ": ").last }

4. Extract the 3 arrays

let nameLines = lines.enumerated().filter { $0.offset % 3 == 0 }.map { $0.element }
let packageLines = lines.enumerated().filter { $0.offset % 3 == 1 }.map { $0.element }
let descriptionLines = lines.enumerated().filter { $0.offset % 3 == 2 }.map { $0.element }

5. Generate an array of Package(s)

let packages = zip(nameLines, zip(packageLines, descriptionLines))
    .map { (name: $0, package: $1.0, description: $1.1) }
    .map (Package.init)

6. Test

print(packages)

[
    Package(name: "LittleX",
            package: "com.ioscreatix.littlex",
            description: "iPhone X features for Non-X devices on iOS 11, and iPad Dock and PiP for All iOS 11 Devices on iOS 11"
    ),
    Package(name: "InteliX",
            package: "com.ioscreatix.intelix",
            description: "Grouped Notifications for iOS 11"
    )
]


问:
matching row values (text) with column names and return value
I am trying to find the column name with the same name as the text in another column called "region", and return the corresponding value. My data "df" looks like something similar to this

```<code>region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396
</code>```

And I want to get something that looks like this:

```<code>region  A   B   C   D   E   F
H       NA  NA  NA  NA  NA  NA
J       NA  NA  NA  NA  NA  NA
A       820 NA  NA  NA  NA  NA
X       NA  NA  NA  NA  NA  NA
M       NA  NA  NA  NA  NA  NA
N       NA  NA  NA  NA  NA  NA
C       NA  NA  952 NA  NA  NA
L       NA  NA  NA  NA  NA  NA
E       NA  NA  NA  NA  944 NA
F       NA  NA  NA  NA  NA  616
P       NA  NA  NA  NA  NA  NA
Q       NA  NA  NA  NA  NA  NA
</code>```

To do this, I tried this piece of code from this other questions (Loop that matches row to column names and computes an average of the 3 preceding columns) but it only returns the position, and I would like to get the value as shown in the example above.

apply (df, MARGIN = 1, FUN = function(x, i){
  position <- (which(x[['region']] == colnames(df)))
})

How can I modify the code to get the real value?
Thanks

Body:
I am trying to find the column name with the same name as the text in another column called "region", and return the corresponding value. My data "df" looks like something similar to this

region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396

And I want to get something that looks like this:

region  A   B   C   D   E   F
H       NA  NA  NA  NA  NA  NA
J       NA  NA  NA  NA  NA  NA
A       820 NA  NA  NA  NA  NA
X       NA  NA  NA  NA  NA  NA
M       NA  NA  NA  NA  NA  NA
N       NA  NA  NA  NA  NA  NA
C       NA  NA  952 NA  NA  NA
L       NA  NA  NA  NA  NA  NA
E       NA  NA  NA  NA  944 NA
F       NA  NA  NA  NA  NA  616
P       NA  NA  NA  NA  NA  NA
Q       NA  NA  NA  NA  NA  NA

To do this, I tried this piece of code from this other questions (Loop that matches row to column names and computes an average of the 3 preceding columns) but it only returns the position, and I would like to get the value as shown in the example above.

apply (df, MARGIN = 1, FUN = function(x, i){
  position <- (which(x[['region']] == colnames(df)))
})

How can I modify the code to get the real value?
Thanks

Body:
Here is an option using base R.

for (col in names(dat[-1])){
  dat[[col]] <- ifelse(dat$region == col, dat[[col]], NA)
}

DATA

dat <- read.table(text = "region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396",
                  stringsAsFactors = FALSE, header = TRUE)


问:
Majority element using divide&conquer
I want to find the majority element from a list using divide & conquer algorithm.

I saw this code on Leetcode with this solution:

```<code>class Solution:
def majorityElement(self, nums, lo=0, hi=None):
    def majority_element_rec(lo, hi):
        # base case; the only element in an array of size 1 is the majority
        # element.
        if lo == hi:
            return nums[lo]

        # recurse on left and right halves of this slice.
        mid = (hi-lo)//2 + lo
        left = majority_element_rec(lo, mid)
        right = majority_element_rec(mid+1, hi)

        # if the two halves agree on the majority element, return it.
        if left == right:
            return left

        # otherwise, count each element and return the "winner".
        left_count = sum(1 for i in range(lo, hi+1) if nums[i] == left)
        right_count = sum(1 for i in range(lo, hi+1) if nums[i] == right)

        return left if left_count > right_count else right

    return majority_element_rec(0, len(nums)-1)
</code>```

when there is a majority element, the result is right but when there is not such an element, it returns the wrong result.

I tried to change the return statement to:

```<code>    if left_count > right_count:
        return left
    elif left_count < right_count:
        return right
    else:
        return -1
</code>```

so it returns -1 when there is no right answer.
When the input is [1,2,1,3] the result is -1(right answer) but when the input is [1,2,3,3] the output is 3 which is wrong.

It seems that everyone use this solution but it isn't working. Any ideas about how to fix it?

TIA

答:
I think the recursive step is OK since if there is a majority element, it must be the majority element of at least one of the halves of the array, and the recursive step will find it. If there is no majority element the recursive algorithm will still return a (wrong) candidate.

If you want the program to detect if the element is indeed the majority element,
I would just change the final step.

```<code>def majorityElement(self, nums):
    ...
    candidate = majority_element_rec(0, len(nums)-1)
    if nums.count(candidate) > len(nums)//2:
        return count
    else:
        return -1
</code>```

Alternatively the recursive step could perform the same check whether the found candidate is indeed a majority element by replacing the last line:

```<code>return left if left_count > right_count else right
</code>```

with

```<code>majority = ((hi - lo) + 1) / 2
if left_count > majority:
     return left
if right_count > majority:
     return right
return -1
</code>```

This should still work because the majority element if it exists must be the majority element in one half of the array recursively and must thus still propagate.

Title: Majority element using divide&conquer

Body:
I want to find the majority element from a list using divide & conquer algorithm.

I saw this code on Leetcode with this solution:

class Solution:
def majorityElement(self, nums, lo=0, hi=None):
    def majority_element_rec(lo, hi):
        # base case; the only element in an array of size 1 is the majority
        # element.
        if lo == hi:
            return nums[lo]

        # recurse on left and right halves of this slice.
        mid = (hi-lo)//2 + lo
        left = majority_element_rec(lo, mid)
        right = majority_element_rec(mid+1, hi)

        # if the two halves agree on the majority element, return it.
        if left == right:
            return left

        # otherwise, count each element and return the "winner".
        left_count = sum(1 for i in range(lo, hi+1) if nums[i] == left)
        right_count = sum(1 for i in range(lo, hi+1) if nums[i] == right)

        return left if left_count > right_count else right

    return majority_element_rec(0, len(nums)-1)

when there is a majority element, the result is right but when there is not such an element, it returns the wrong result.

I tried to change the return statement to:

    if left_count > right_count:
        return left
    elif left_count < right_count:
        return right
    else:
        return -1

so it returns -1 when there is no right answer.
When the input is [1,2,1,3] the result is -1(right answer) but when the input is [1,2,3,3] the output is 3 which is wrong.

It seems that everyone use this solution but it isn't working. Any ideas about how to fix it?

TIA

Body:
I think the recursive step is OK since if there is a majority element, it must be the majority element of at least one of the halves of the array, and the recursive step will find it. If there is no majority element the recursive algorithm will still return a (wrong) candidate.

If you want the program to detect if the element is indeed the majority element,
I would just change the final step.

def majorityElement(self, nums):
    ...
    candidate = majority_element_rec(0, len(nums)-1)
    if nums.count(candidate) > len(nums)//2:
        return count
    else:
        return -1

Alternatively the recursive step could perform the same check whether the found candidate is indeed a majority element by replacing the last line:

return left if left_count > right_count else right

with

majority = ((hi - lo) + 1) / 2
if left_count > majority:
     return left
if right_count > majority:
     return right
return -1

This should still work because the majority element if it exists must be the majority element in one half of the array recursively and must thus still propagate.


问:
Remove numbers if greater than X - PHP
I am removing numbers from $name, as follows:

```<code>$name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);
</code>```

Is it possible to remove numbers only if there are more than X numbers, example: joe123456 (six characters) and not if: joe123 or 1joe1234?

Title: Remove numbers if greater than X - PHP

Body:
I am removing numbers from $name, as follows:

$name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);

Is it possible to remove numbers only if there are more than X numbers, example: joe123456 (six characters) and not if: joe123 or 1joe1234?

Body:
Another option:

<?php

$names = array('joe123456',
               'joe123',
               '1joe1234',
               '123joe456',
               '1234567joe12345');

$new_names = [];

foreach ($names as $name) {
    if (preg_match("/\d{6}+/", $name)) {
        $new_names[] = preg_replace('/\d/', '', $name);
    } else {
        $new_names[] = $name;
    }
}

var_dump($new_names);

Yields:

array(5) {
  [0]=>
  string(3) "joe"
  [1]=>
  string(6) "joe123"
  [2]=>
  string(8) "1joe1234"
  [3]=>
  string(9) "123joe456"
  [4]=>
  string(3) "joe"
}


问:
Laravel Error Composer Update
```<code>user@user:/opt/lampp/htdocs/gitrepo$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel/framework v5.6.1 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.6.0 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework 5.6.x-dev requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - Installation request for laravel/framework 5.6.* -> satisfiable by laravel/framework[5.6.x-dev, v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v5.6.13, v5.6.14, v5.6.15, v5.6.16, v5.6.17, v5.6.18, v5.6.19, v5.6.2, v5.6.20, v5.6.21, v5.6.22, v5.6.23, v5.6.3, v5.6.4, v5.6.5, v5.6.6, v5.6.7, v5.6.8, v5.6.9].

  To enable extensions, verify that they are enabled in those .ini files:
    - /etc/php/7.1/cli/php.ini
    - /etc/php/7.1/cli/conf.d/10-opcache.ini
    - /etc/php/7.1/cli/conf.d/10-pdo.ini
    - /etc/php/7.1/cli/conf.d/15-xml.ini
    - /etc/php/7.1/cli/conf.d/20-calendar.ini
    - /etc/php/7.1/cli/conf.d/20-ctype.ini
    - /etc/php/7.1/cli/conf.d/20-dom.ini
    - /etc/php/7.1/cli/conf.d/20-exif.ini
    - /etc/php/7.1/cli/conf.d/20-fileinfo.ini
    - /etc/php/7.1/cli/conf.d/20-ftp.ini
    - /etc/php/7.1/cli/conf.d/20-gettext.ini
    - /etc/php/7.1/cli/conf.d/20-iconv.ini
    - /etc/php/7.1/cli/conf.d/20-json.ini
    - /etc/php/7.1/cli/conf.d/20-phar.ini
    - /etc/php/7.1/cli/conf.d/20-posix.ini
    - /etc/php/7.1/cli/conf.d/20-readline.ini
    - /etc/php/7.1/cli/conf.d/20-shmop.ini
    - /etc/php/7.1/cli/conf.d/20-simplexml.ini
    - /etc/php/7.1/cli/conf.d/20-sockets.ini
    - /etc/php/7.1/cli/conf.d/20-sysvmsg.ini
    - /etc/php/7.1/cli/conf.d/20-sysvsem.ini
    - /etc/php/7.1/cli/conf.d/20-sysvshm.ini
    - /etc/php/7.1/cli/conf.d/20-tokenizer.ini
    - /etc/php/7.1/cli/conf.d/20-wddx.ini
    - /etc/php/7.1/cli/conf.d/20-xmlreader.ini
    - /etc/php/7.1/cli/conf.d/20-xmlwriter.ini
    - /etc/php/7.1/cli/conf.d/20-xsl.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode
</code>```

I got this error when i tried to update composer. what solution can resolve it? i have installed php7.1 and i have installed composer too (sudo apt-get install composer)

答:
After uncommenting, the said extensions in php.ini file and the composer doesn't function correctly. if you run into the error below, then you need to uncomment some other extensions in php.ini file.

```<code>// Error on the terminal when I ran: composer install

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for league/flysystem 1.0.64 -> satisfiable by league/flysystem[1.0.64].
    - league/flysystem 1.0.64 requires ext-fileinfo * -> the requested PHP extension fileinfo is missing from your system.
  Problem 2
    - league/flysystem 1.0.64 requires ext-fileinfo * -> the requested PHP extension fileinfo is missing from your system.
    - laravel/framework v6.14.0 requires league/flysystem ^1.0.8 -> satisfiable by league/flysystem[1.0.64].
    - Installation request for laravel/framework v6.14.0 -> satisfiable by laravel/framework[v6.14.0].

  To enable extensions, verify that they are enabled in your .ini files:
    - C:\PHP7\php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI
mode.
</code>```

As this resource and others didn't mention the installation for PHP7.4, but you can still follow them. After I uncommented as mentioned in this article. You'll also need to uncomment

```<code>extension=fileinfo
extension=mbstring // probabily this too
</code>```

Title: Laravel Error Composer Update

Body:
user@user:/opt/lampp/htdocs/gitrepo$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel/framework v5.6.1 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.6.0 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework 5.6.x-dev requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - Installation request for laravel/framework 5.6.* -> satisfiable by laravel/framework[5.6.x-dev, v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v5.6.13, v5.6.14, v5.6.15, v5.6.16, v5.6.17, v5.6.18, v5.6.19, v5.6.2, v5.6.20, v5.6.21, v5.6.22, v5.6.23, v5.6.3, v5.6.4, v5.6.5, v5.6.6, v5.6.7, v5.6.8, v5.6.9].

  To enable extensions, verify that they are enabled in those .ini files:
    - /etc/php/7.1/cli/php.ini
    - /etc/php/7.1/cli/conf.d/10-opcache.ini
    - /etc/php/7.1/cli/conf.d/10-pdo.ini
    - /etc/php/7.1/cli/conf.d/15-xml.ini
    - /etc/php/7.1/cli/conf.d/20-calendar.ini
    - /etc/php/7.1/cli/conf.d/20-ctype.ini
    - /etc/php/7.1/cli/conf.d/20-dom.ini
    - /etc/php/7.1/cli/conf.d/20-exif.ini
    - /etc/php/7.1/cli/conf.d/20-fileinfo.ini
    - /etc/php/7.1/cli/conf.d/20-ftp.ini
    - /etc/php/7.1/cli/conf.d/20-gettext.ini
    - /etc/php/7.1/cli/conf.d/20-iconv.ini
    - /etc/php/7.1/cli/conf.d/20-json.ini
    - /etc/php/7.1/cli/conf.d/20-phar.ini
    - /etc/php/7.1/cli/conf.d/20-posix.ini
    - /etc/php/7.1/cli/conf.d/20-readline.ini
    - /etc/php/7.1/cli/conf.d/20-shmop.ini
    - /etc/php/7.1/cli/conf.d/20-simplexml.ini
    - /etc/php/7.1/cli/conf.d/20-sockets.ini
    - /etc/php/7.1/cli/conf.d/20-sysvmsg.ini
    - /etc/php/7.1/cli/conf.d/20-sysvsem.ini
    - /etc/php/7.1/cli/conf.d/20-sysvshm.ini
    - /etc/php/7.1/cli/conf.d/20-tokenizer.ini
    - /etc/php/7.1/cli/conf.d/20-wddx.ini
    - /etc/php/7.1/cli/conf.d/20-xmlreader.ini
    - /etc/php/7.1/cli/conf.d/20-xmlwriter.ini
    - /etc/php/7.1/cli/conf.d/20-xsl.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode

I got this error when i tried to update composer. what solution can resolve it? i have installed php7.1 and i have installed composer too (sudo apt-get install composer)

Body:
After uncommenting, the said extensions in php.ini file and the composer doesn't function correctly. if you run into the error below, then you need to uncomment some other extensions in php.ini file.

// Error on the terminal when I ran: composer install

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for league/flysystem 1.0.64 -> satisfiable by league/flysystem[1.0.64].
    - league/flysystem 1.0.64 requires ext-fileinfo * -> the requested PHP extension fileinfo is missing from your system.
  Problem 2
    - league/flysystem 1.0.64 requires ext-fileinfo * -> the requested PHP extension fileinfo is missing from your system.
    - laravel/framework v6.14.0 requires league/flysystem ^1.0.8 -> satisfiable by league/flysystem[1.0.64].
    - Installation request for laravel/framework v6.14.0 -> satisfiable by laravel/framework[v6.14.0].

  To enable extensions, verify that they are enabled in your .ini files:
    - C:\PHP7\php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI
mode.

As this resource and others didn't mention the installation for PHP7.4, but you can still follow them. After I uncommented as mentioned in this article. You'll also need to uncomment

extension=fileinfo
extension=mbstring // probabily this too


问:
Can I have an enum with unlabelled values in C++?
Basically I want to restrict variables to the values 0, 1 or 2.

I have tried doing this with the following:

```<code>enum Value
{
    0,
    1,
    2
};
Value var;
</code>```

But this is a compile error because the enum values are unlabelled. It just makes the code less readable to assign names like "ZERO", "ONE" and "TWO" rather than referring to the values as 0, 1 and 2. Is there any way around this or should I just get rid of the enum and enforce the rule elsewhere?

答:
You are looking for the builtin int type, AFAICT

If you really want to behave like a Java programmer use ADT religiously, you can always:

```<code>template <typename ordinal=int>
struct Value
{
    ordinal _val;
    /*implicit*/ Value(ordinal val) : _val(val) {}
    /*implicit*/ operator const ordinal&() const { return _val; }
    /*implicit*/ operator       ordinal&()       { return _val; }
};

int main()
{
    Value<> x = 3;
    int y = x;
    x = y;

    x += 17;
    x++;

    return x;
}
</code>```

This will return 22

Of course, it is entirely possible to make the Value<> less generic and more useful in many ways, but you didn't really tell us anything about what you want with that

ContentLicense: CC BY-SA 3.0

Body:
Basically I want to restrict variables to the values 0, 1 or 2.

I have tried doing this with the following:

enum Value
{
    0,
    1,
    2
};
Value var;

But this is a compile error because the enum values are unlabelled. It just makes the code less readable to assign names like "ZERO", "ONE" and "TWO" rather than referring to the values as 0, 1 and 2. Is there any way around this or should I just get rid of the enum and enforce the rule elsewhere?

Body:
You are looking for the builtin int type, AFAICT

If you really want to behave like a Java programmer use ADT religiously, you can always:

template <typename ordinal=int>
struct Value
{
    ordinal _val;
    /*implicit*/ Value(ordinal val) : _val(val) {}
    /*implicit*/ operator const ordinal&() const { return _val; }
    /*implicit*/ operator       ordinal&()       { return _val; }
};

int main()
{
    Value<> x = 3;
    int y = x;
    x = y;

    x += 17;
    x++;

    return x;
}

This will return 22

Of course, it is entirely possible to make the Value<> less generic and more useful in many ways, but you didn't really tell us anything about what you want with that


问:
spring jms - perform action before message received
Is it possible to perform an action before a jms message is received in spring boot?  I know I could put it at the very top of my @JmsListener, but I have several listeners and I'd prefer avoiding adding a call to all of them.

I'm trying to use the logging MDC (a threadlocal, if you're not familiar with the MDC,) to track various things and I'd like to set some properties before beginning to process the message.  I can do this on my controllers with a Filter, but does spring jms have the same concept?

答:
I would try to start with an Before or Around (in case there should be some logic implemented after handling message as well) aspect:

```<code>@Before("@annotation(JmsListener)")
public void handle(ProceedingJoinPoint joinPoint) { ... }

@Around("@annotation(JmsListener)")
public void handle(ProceedingJoinPoint joinPoint) { ... }
</code>```

Couple of links: enabling aspectj support, before advice, around advice.

Body:
I would try to start with an Before or Around (in case there should be some logic implemented after handling message as well) aspect:

@Before("@annotation(JmsListener)")
public void handle(ProceedingJoinPoint joinPoint) { ... }

@Around("@annotation(JmsListener)")
public void handle(ProceedingJoinPoint joinPoint) { ... }

Couple of links: enabling aspectj support, before advice, around advice.


问:
Bookmarklet not working on ios or android browser
I have this code, it’s a bookmarklet:

```<code>javascript:(function(e,a,g,h,f,c,b,d){if(!(f=e.jQuery)||g>f.fn.jquery||h(f)){c=a.createElement("script");c.type="text/javascript";c.src="cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js";c.onload=c.onreadystatechange=function(){if(!b&&(!(d=this.readyState)||d=="loaded"||d=="complete")){h((f=e.jQuery).noConflict(1),b=1);f(c).remove()}};a.documentElement.childNodes[0].appendChild(c)}})(window,document,"3.4.1",function($,L){var url1 = "download-video-youtube1.p.rapidapi.com/mp3/";var url2 = window.location.href.substring(32);var url3 = url1 + url2;var settings = { "url": url3 , "method": "GET", "headers": {"x-rapidapi-host": "download-video-youtube1.p.rapidapi.com","x-rapidapi-key": "[my apikey here]" } }; $.ajax(settings).done(function(response){ window.location.href = "https://" + response.vidInfo[0].dloadUrl;});});
</code>```

It works great on firefox and chrome but there is no way it works with ios safari or ios shortcut or chrome on  android.

It checks whether there is a specific version of jquery, if not it appends it in the DOM and them runs an api request and returns the Mp3’s download link of any video of youtube.

It’s my third and last question here since I received no answer so far.
I know I won’t this time either, never mind i keep it here as a diary.

Good bye

答:
Not sure what could be the issue, the code looks ok (as I have reverse-engineered). If you created the bookmarklet, please include the full source code.

Maybe you need to include the protocol in the script url?

Also, make sure the version of jQuery is compatible with your Safari/Android browser.

Note: If you want, you can throw jQuery in the trash and use promises. Take a look at Fetch API.

(function() {
  let script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js";
  script.onload = script.onreadystatechange = function(e) {
    $.ajax({
      "url": "download-video-youtube1.p.rapidapi.com/mp3/" + window.location.href.substring(32),
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "download-video-youtube1.p.rapidapi.com",
        "x-rapidapi-key": "[my apikey here]"
      }
    }).done(function(response) {
      window.location.href = "https://" + response.vidInfo[0].dloadUrl;
    });
  };
  document.documentElement.childNodes[0].appendChild(script);
})();```
</div>
</div>
</p>

<p>Re-minified using javascript-minifier.com:</p>

<pre class="lang-js prettyprint-override"><code>javascript:!function(){let e=document.createElement("script");e.type="text/javascript",e.src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js",e.onload=e.onreadystatechange=function(e){$.ajax({url:"download-video-youtube1.p.rapidapi.com/mp3/"+window.location.href.substring(32),method:"GET",headers:{"x-rapidapi-host":"download-video-youtube1.p.rapidapi.com","x-rapidapi-key":"[my apikey here]"}}).done(function(e){window.location.href="https://"+e.vidInfo[0].dloadUrl})},document.documentElement.childNodes[0].appendChild(e)}();
</code>```

Using the fetch API

It's ~17% longer (after minification), but does not rely on jQuery. It also features a YouTube video ID extraction function, so it is more robust.

The script below is a UserScript that can be used with Greasemonkey, Tampermonkey, or Violentmonkey.

// ==UserScript==
// @name         YouTube MP3
// @namespace    com.youtube.mp3
// @version      1.0.0
// @description  Parse the YouTube video ID and request the MP3 version.
// @author       Mr. Polywhirl
// @match        https://www.youtube.com/*
// @match        https://youtube.com/*
// @match        https://youtu.be/*
// @grant        GM_log
// ==/UserScript==
(function() {
  'use strict';
  // See: https://stackoverflow.com/a/8260383/1762224
  const ytUrlParser = (url) => {
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
    var match = url.match(regExp);
    return (match && match[7].length == 11) ? match[7] : false;
  }
  const videoId = ytUrlParser(window.location.href);
  if (videoId) {
    const reqUrl = 'download-video-youtube1.p.rapidapi.com/mp3/' + videoId;
    const reqHead = new Headers();
    reqHead.append('x-rapidapi-host', 'download-video-youtube1.p.rapidapi.com');
    reqHead.append('x-rapidapi-key', '[my apikey here]');
    const reqObj = new Request(reqUrl, {
      method: 'GET',
      headers: reqHead,
      mode: 'cors',
      cache: 'default',
    });
    fetch(reqObj)
      .then(function(response) {
        if (!response.ok) { throw Error(response.statusText); }
        return response;
      })
      .then(response => response.vidInfo[0].dloadUrl)
      .then(url => { window.location.href = "https://" + url })
      .catch(error => console.log(error));
  }
})();```
</div>
</div>
</p>

<p>Minified:</p>

<pre class="lang-js prettyprint-override"><code>javascript:!function(){"use strict";const e=(o=window.location.href,!(!(t=o.match(/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/))||11!=t[7].length)&&t[7]);var o,t;if(e){const o="download-video-youtube1.p.rapidapi.com/mp3/"+e,t=new Headers;t.append("x-rapidapi-host","download-video-youtube1.p.rapidapi.com"),t.append("x-rapidapi-key","[my apikey here]");const a=new Request(o,{method:"GET",headers:t,mode:"cors",cache:"default"});fetch(a).then(function(e){if(!e.ok)throw Error(e.statusText);return e}).then(e=>e.vidInfo[0].dloadUrl).then(e=>{window.location.href="https://"+e}).catch(e=>console.log(e))}}();
</code>```

Body:
I have this code, it’s a bookmarklet:

javascript:(function(e,a,g,h,f,c,b,d){if(!(f=e.jQuery)||g>f.fn.jquery||h(f)){c=a.createElement("script");c.type="text/javascript";c.src="cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js";c.onload=c.onreadystatechange=function(){if(!b&&(!(d=this.readyState)||d=="loaded"||d=="complete")){h((f=e.jQuery).noConflict(1),b=1);f(c).remove()}};a.documentElement.childNodes[0].appendChild(c)}})(window,document,"3.4.1",function($,L){var url1 = "download-video-youtube1.p.rapidapi.com/mp3/";var url2 = window.location.href.substring(32);var url3 = url1 + url2;var settings = { "url": url3 , "method": "GET", "headers": {"x-rapidapi-host": "download-video-youtube1.p.rapidapi.com","x-rapidapi-key": "[my apikey here]" } }; $.ajax(settings).done(function(response){ window.location.href = "https://" + response.vidInfo[0].dloadUrl;});});

It works great on firefox and chrome but there is no way it works with ios safari or ios shortcut or chrome on  android.

It checks whether there is a specific version of jquery, if not it appends it in the DOM and them runs an api request and returns the Mp3’s download link of any video of youtube.

It’s my third and last question here since I received no answer so far.
I know I won’t this time either, never mind i keep it here as a diary.

Good bye

Body:
Not sure what could be the issue, the code looks ok (as I have reverse-engineered). If you created the bookmarklet, please include the full source code.

Maybe you need to include the protocol in the script url?

Also, make sure the version of jQuery is compatible with your Safari/Android browser.

Note: If you want, you can throw jQuery in the trash and use promises. Take a look at Fetch API.

(function() {
  let script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js";
  script.onload = script.onreadystatechange = function(e) {
    $.ajax({
      "url": "download-video-youtube1.p.rapidapi.com/mp3/" + window.location.href.substring(32),
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "download-video-youtube1.p.rapidapi.com",
        "x-rapidapi-key": "[my apikey here]"
      }
    }).done(function(response) {
      window.location.href = "https://" + response.vidInfo[0].dloadUrl;
    });
  };
  document.documentElement.childNodes[0].appendChild(script);
})();

Re-minified using javascript-minifier.com:

javascript:!function(){let e=document.createElement("script");e.type="text/javascript",e.src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js",e.onload=e.onreadystatechange=function(e){$.ajax({url:"download-video-youtube1.p.rapidapi.com/mp3/"+window.location.href.substring(32),method:"GET",headers:{"x-rapidapi-host":"download-video-youtube1.p.rapidapi.com","x-rapidapi-key":"[my apikey here]"}}).done(function(e){window.location.href="https://"+e.vidInfo[0].dloadUrl})},document.documentElement.childNodes[0].appendChild(e)}();

Using the fetch API

It's ~17% longer (after minification), but does not rely on jQuery. It also features a YouTube video ID extraction function, so it is more robust.

The script below is a UserScript that can be used with Greasemonkey, Tampermonkey, or Violentmonkey.

// ==UserScript==
// @name         YouTube MP3
// @namespace    com.youtube.mp3
// @version      1.0.0
// @description  Parse the YouTube video ID and request the MP3 version.
// @author       Mr. Polywhirl
// @match        https://www.youtube.com/*
// @match        https://youtube.com/*
// @match        https://youtu.be/*
// @grant        GM_log
// ==/UserScript==
(function() {
  'use strict';
  // See: https://stackoverflow.com/a/8260383/1762224
  const ytUrlParser = (url) => {
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
    var match = url.match(regExp);
    return (match && match[7].length == 11) ? match[7] : false;
  }
  const videoId = ytUrlParser(window.location.href);
  if (videoId) {
    const reqUrl = 'download-video-youtube1.p.rapidapi.com/mp3/' + videoId;
    const reqHead = new Headers();
    reqHead.append('x-rapidapi-host', 'download-video-youtube1.p.rapidapi.com');
    reqHead.append('x-rapidapi-key', '[my apikey here]');
    const reqObj = new Request(reqUrl, {
      method: 'GET',
      headers: reqHead,
      mode: 'cors',
      cache: 'default',
    });
    fetch(reqObj)
      .then(function(response) {
        if (!response.ok) { throw Error(response.statusText); }
        return response;
      })
      .then(response => response.vidInfo[0].dloadUrl)
      .then(url => { window.location.href = "https://" + url })
      .catch(error => console.log(error));
  }
})();

Minified:

javascript:!function(){"use strict";const e=(o=window.location.href,!(!(t=o.match(/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/))||11!=t[7].length)&&t[7]);var o,t;if(e){const o="download-video-youtube1.p.rapidapi.com/mp3/"+e,t=new Headers;t.append("x-rapidapi-host","download-video-youtube1.p.rapidapi.com"),t.append("x-rapidapi-key","[my apikey here]");const a=new Request(o,{method:"GET",headers:t,mode:"cors",cache:"default"});fetch(a).then(function(e){if(!e.ok)throw Error(e.statusText);return e}).then(e=>e.vidInfo[0].dloadUrl).then(e=>{window.location.href="https://"+e}).catch(e=>console.log(e))}}();


问:
How to rewrite '__extends = function () {}' to an object
First of all sorry that the title makes no sense. Here's what I'm dealing with plus a TL;DR at the end.

I'm using the tslib library from Microsoft, here's the full source code for context. I needed to make some minor adjustments to the library to make it work with my project so I copy-pasted the code to a file and edited it there. The modified code works with a React project I was working on earlier but it breaks with React Native because of these lines:

```<code>(function (exporter) {

   // some irrelevant stuff

    __extends = function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
});
</code>```

(I didn't modify this part, you can find it on line 66 in the original source code)

When React Native tries to compile this to native code it breaks with the error message
Prototype value can only be an object or null with the error coming out of the __extends = function(d, b) { assignment.

So I somehow need to convert that inner anonymous function into an object, the problem is even though I've been working with JavaScript for ages, I genuinely have no clue what this code is supposed to do. I'm an ES6+ guy, this stuff is like Egyptian hieroglyphs to me. Could some of you JS veterans come over and save me please?

TL;DR: I somehow need to convert __extends = fuction() {} to an object that would do the same thing as the function.

答:
This is a really old pattern used for setting up class inheritance. A similar thing can be found here. The use of new __() predates the existence of Object.create. You should be able to replace the thing with

```<code>function __extends(d, b) {
    extendStatics(d, b);
    d.prototype = b === null
      ? Object.create(b)
      : Object.assign(Object.create(b.prototype), {constructor: d});
}
</code>```

Body:
First of all sorry that the title makes no sense. Here's what I'm dealing with plus a TL;DR at the end.

I'm using the tslib library from Microsoft, here's the full source code for context. I needed to make some minor adjustments to the library to make it work with my project so I copy-pasted the code to a file and edited it there. The modified code works with a React project I was working on earlier but it breaks with React Native because of these lines:

(function (exporter) {

   // some irrelevant stuff

    __extends = function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
});

(I didn't modify this part, you can find it on line 66 in the original source code)

When React Native tries to compile this to native code it breaks with the error message
Prototype value can only be an object or null with the error coming out of the __extends = function(d, b) { assignment.

So I somehow need to convert that inner anonymous function into an object, the problem is even though I've been working with JavaScript for ages, I genuinely have no clue what this code is supposed to do. I'm an ES6+ guy, this stuff is like Egyptian hieroglyphs to me. Could some of you JS veterans come over and save me please?

TL;DR: I somehow need to convert __extends = fuction() {} to an object that would do the same thing as the function.

Body:
This is a really old pattern used for setting up class inheritance. A similar thing can be found here. The use of new __() predates the existence of Object.create. You should be able to replace the thing with

function __extends(d, b) {
    extendStatics(d, b);
    d.prototype = b === null
      ? Object.create(b)
      : Object.assign(Object.create(b.prototype), {constructor: d});
}


问:
Xamarin SimpleAudioPlayer returns System.NullReferenceException
I am trying to play a .wav file in Xamarin.

The file is found but I get the below execption using this code. How is that possible as it does find the emailalert.wav file and should get a stream?

System.NullReferenceException: Object reference not set to an instance of an object.

Happens on this line:

audio.Load(stream);```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>        public void Play()
        {
            String path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            String filename2 = "Folder1/emailalert.wav"; String filenameB = Path.Combine(path, filename2);

            if (File.Exists(filenameB))
            {
                var stream = GetStreamFromFile(filenameB);
                var audio = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
                audio.Load(stream);
                audio.Play();
            }
        }</code>```

答:
I found a solution to embedd the file directly under the Resources folder and then using this code. I also in the Properties of the .wav file choosed "Build Action" and "Embedded Resource".

Now this code plays the file nicely:

        public void Play()
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            string[] resources = assembly.GetManifestResourceNames();
            foreach (string resource in resources)
            {
                if (resource.Contains("emailalert.wav"))
                {
                    Stream stream = assembly.GetManifestResourceStream(resource);
                    if (stream != null)
                    {
                        var audio = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
                        audio.Load(stream);
                        audio.Play(); break;
                    }
                }
            }
        }```

Body:
I am trying to play a .wav file in Xamarin.

The file is found but I get the below execption using this code. How is that possible as it does find the emailalert.wav file and should get a stream?

System.NullReferenceException: Object reference not set to an instance of an object.

Happens on this line:

audio.Load(stream);

        public void Play()
        {
            String path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            String filename2 = "Folder1/emailalert.wav"; String filenameB = Path.Combine(path, filename2);

            if (File.Exists(filenameB))
            {
                var stream = GetStreamFromFile(filenameB);
                var audio = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
                audio.Load(stream);
                audio.Play();
            }
        }


问:
Concrete info on iOS app upgrade process
Can someone provide concrete info on how the app upgrade process works on iOS as far as the developer is concerned? I've been rummaging through Stackoverflow only to find hand-waving explanations and no links to official documentation. Google search results only led to Cisco's IOS and the end-user upgrade process. I'd like to know the following:

How does the App Store know when you've provided a new version? Do I have to implement something in my app, which the App Store pings? Or do I set things up stuff through the Apple Developer website? I've been waiting 2 months for developer approval and have no idea what's going on behind those doors because I get access-denied messages when trying to read official articles.

Is there any Objective-C code I need to write for an upgrade to be possible? Any plist I need to edit?

How is payment affected when version 1 of the app is free, then version 2 is paid or version 1 is paid and version 2 changes its price.

Does Apple allow me to do forced upgrades? All the answers on Stackoverflow have been, "I think this is bad business logic" or "I think Apple forbids this, but I don't have the official documentation to prove it." At a certain point, very old versions will be too time consuming to support. You don't see Microsoft still supporting Windows 95, do you?

答:
You just submit the new version to Apple. When it's approved, it will appear in the App Store.

Same as above, Apple pretty much does it all for you.

If you transition from free to paid, everyone that has downloaded the app for free will not have to pay to upgrade to the paid version.

IIRC you cannot force users to upgrade, but you can display a notification within the app to alert users that an update is available. To implement this, I would just have the app request a file on your server that tells the app what the current version number is. You do not need to support users on old version, if they have problems with an old version, it's fine to tell them to upgrade.


问:
Google Sheet creating an IF or IFS
I am trying to auto populate information based on what I am inputting into one column to another.

For example: Column D has a list I choose from:  CD, DD, CC, Closed.  Based on what is input in Column D in each row I am looking to populate that information in each individual rows for column N though P.

D2=Closed,  N though P should state NA.

D3=CD or DD or CC.  N though P is left blank.

When I try IFS function it will state the NA if D is Closed but for CD, DD or CC it will spilt out False.  How do I leave the N-P columns blank if D3 or other D columns are not equal to Closed?

答:
try:</p>

```<code>=ARRAYFORMULA(IF(D2:D="Closed", {"NA","NA","NA","NA"}, ))
</code>```

Title: Google Sheet creating an IF or IFS

Body:
try:

=ARRAYFORMULA(IF(D2:D="Closed", {"NA","NA","NA","NA"}, ))


问:
Java: invalid selector: An invalid or illegal selector was specified
I'm trying to click an element on payment pop-up:

```<code><label data-v-533987c6="" xpath="1">Card Number:</label>
<input data-v-533987c6="" type="tel" data-mask="#### #### #### ####" data-previous-value="" xpath="1">
</code>```

with following xPath:

@FindBy(name = "//div[contains(@class,'buy-tickets')]//div/label[text()='Card Number:']/following-sibling::input")

but I receive this error:

```<code>org.openqa.selenium.InvalidSelectorException: invalid selector: An invalid or illegal selector was specified
  (Session info: chrome=80.0.3987.87)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-VQ56FMV', ip: '192.168.0.13', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_231'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 80.0.3987.87, chrome: {chromedriverVersion: 80.0.3987.106 (f68069574609..., userDataDir: C:\Users\Nastya\AppData\Loc...}, goog:chromeOptions: {debuggerAddress: localhost:64958}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webdriver.remote.sessionid: 3ca3f388f2b3cf47642733a6f03...}
Session ID: 3ca3f388f2b3cf47642733a6f0383c1e
*** Element info: {Using=name, value=//div[contains(@class,'buy-tickets')]//div/label[text()='Card Number:']/following-sibling::input}
</code>```

Why? Hope, you can help me!

答:
You seem to be close. Though you have mentioned the Locator Strategy as By.name in your code, but the value which you have passed:

```<code>//label[text()='Expiration Date:']//following::input[@type='tel'][1]
</code>```

resembles a xpath. So instead of using By.name you need to use By.xpath and you can use either of the following solutions:

xpath 1 using following:

```<code>driver.findElement(By.xpath("//label[text()='Card Number:']//following::input[1]"))
</code>```

xpath 2 using following-sibling:

```<code>driver.findElement(By.xpath("//label[text()='Card Number:']//following-sibling::input[1]"))
</code>```

Body:
I'm trying to click an element on payment pop-up:

Card Number:
<input data-v-533987c6="" type="tel" data-mask="#### #### #### ####" data-previous-value="" xpath="1">

with following xPath:

@FindBy(name = "//div[contains(@class,'buy-tickets')]//div/label[text()='Card Number:']/following-sibling::input")

but I receive this error:

org.openqa.selenium.InvalidSelectorException: invalid selector: An invalid or illegal selector was specified
  (Session info: chrome=80.0.3987.87)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-VQ56FMV', ip: '192.168.0.13', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_231'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 80.0.3987.87, chrome: {chromedriverVersion: 80.0.3987.106 (f68069574609..., userDataDir: C:\Users\Nastya\AppData\Loc...}, goog:chromeOptions: {debuggerAddress: localhost:64958}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webdriver.remote.sessionid: 3ca3f388f2b3cf47642733a6f03...}
Session ID: 3ca3f388f2b3cf47642733a6f0383c1e
*** Element info: {Using=name, value=//div[contains(@class,'buy-tickets')]//div/label[text()='Card Number:']/following-sibling::input}

Why? Hope, you can help me!

Body:
You seem to be close. Though you have mentioned the Locator Strategy as By.name in your code, but the value which you have passed:

//label[text()='Expiration Date:']//following::input[@type='tel'][1]

resembles a xpath. So instead of using By.name you need to use By.xpath and you can use either of the following solutions:

xpath 1 using following:

driver.findElement(By.xpath("//label[text()='Card Number:']//following::input[1]"))

xpath 2 using following-sibling:

driver.findElement(By.xpath("//label[text()='Card Number:']//following-sibling::input[1]"))


问:
Debug an Azure Function that is triggered using an Event Grid
I have an Azure Function (C#) that is triggered by an Event Grid. I am having difficulty debugging my Function locally as it can only be triggered via the Event Grid.

I'm not sure if there is a way to wire the Event Grid up to my local host address for my Function? I have tried using a Web Hook but it only support HTTPS which my localhost uses HTTP.

```<code>public static void Run([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log)
{
 ID = eventGridEvent.Subject;
 log.LogInformation($"ID: {ID.ToString()}");
}
</code>```

Any advice is appreciated.

答:
I found this blog post that helped me resolve this when debugging event grid azure function locally: https://blog.mcilreavy.com/articles/2018-12/debug-eventgrid-triggered-azure-function (Web archive link)

One piece that was missing in my case was the aeg-event-type header.
aeg-event-type: Notification

After adding it, I was able to debug locally using this url:
 http://localhost:7071/runtime/webhooks/EventGrid?functionName=nameOfYourFunction

And include this event json in the request body, something like this:

 [  { "id": "'1",  "eventType": "yourEventType",  "eventTime":"10:59:00.000", "subject": "subject1",  "data":{"make": "Ducati", "model": "Monster"}, "dataVersion": "1.0" }  ]

Body:
I have an Azure Function (C#) that is triggered by an Event Grid. I am having difficulty debugging my Function locally as it can only be triggered via the Event Grid.

I'm not sure if there is a way to wire the Event Grid up to my local host address for my Function? I have tried using a Web Hook but it only support HTTPS which my localhost uses HTTP.

public static void Run([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log)
{
 ID = eventGridEvent.Subject;
 log.LogInformation($"ID: {ID.ToString()}");
}

Any advice is appreciated.


问:
Losing merged cells border while editing Excel file with openpyxl
I have two sheets in an Excel file and the first one is a cover sheet which I don't need to edit. There are a few merged cells in the cover sheet, and when I edit the file using openpyxl, without even touching the cover sheet, I lose borders from the merged cells. I am using load_workbook('excel file') to load the Excel file and saving it with a different filename.

Is there any way to fix this problem?

答:
For me this code work perfectly:

```<code>wb = load_workbook(template_path)
ws = wb.active
for merged_cells in ws.merged_cells.ranges:
style = ws.cell(merged_cells.min_row, merged_cells.min_col)._style
for col in range(merged_cells.min_col, merged_cells.max_col + 1):
    for row in range(merged_cells.min_row, merged_cells.max_row + 1):
        ws.cell(row, col)._style = style
</code>```

I simply find all merged cells and apply style of left top cell to the rest of the cells.

Body:
For me this code work perfectly:

wb = load_workbook(template_path)
ws = wb.active
for merged_cells in ws.merged_cells.ranges:
style = ws.cell(merged_cells.min_row, merged_cells.min_col)._style
for col in range(merged_cells.min_col, merged_cells.max_col + 1):
    for row in range(merged_cells.min_row, merged_cells.max_row + 1):
        ws.cell(row, col)._style = style

I simply find all merged cells and apply style of left top cell to the rest of the cells.


问:
Hide/Show table columns depending on the element clicked
I would like to create some type of buttons that would only show the table columns affected to them and hidding every others, and add/remove the active class to the buttons, for example:

```<code><a href="#" class="btn active" id="fruits">Data 1</a>
<a href="#" class="btn" id="vegetables">Data 2</a>
<a href="#" class="btn" id="nuts">Data 3</a>

<table>

    <thead>
        <tr>
            <th class="fruits">First column</th>
            <th class="vegetables">Second column</th>
            <th class="nuts">Third column</th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td class="fruits">Test 1</td>
            <td class="vegetables">Test 2</td>
            <td class="nuts">Test 3</td>
        </tr>
    </tbody>

</table>
</code>```

For example, when I click on the "Data 2" button, it adds the "active" class to it, hides every other columns and only shows the items having the class called "vegetables".

I am a beginner and I would like to know if that's possible and how? Thank you.

答:
Hope this suits you.

Some tweaks may be needed if you'll need extra classes on the

$(() => { // wait until DOM is ready
  $('.btn').click(function onclick() { // set up onclick handler for all buttons of class 'btn'
    // on click
    $('.btn').removeClass('active');
        // remove 'active' class from all buttons
    $(this).toggleClass('active');
        // but add 'active' class to the clicked one (this)
    $('table').attr('class', $(this).attr('id'))
        // finally set the table class to be the id of the clicked button
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a.active { color: green }
table .fruits     { display: none }
table .vegetables { display: none }
table .nuts       { display: none }

table.fruits     .fruits     { display: table-cell }
table.vegetables .vegetables { display: table-cell }
table.nuts       .nuts       { display: table-cell }</code>```

Data 1
Data 2
Data 3

            First column
            Second column
            Third column

            Test 1
            Test 2
            Test 3

```

Body:
I would like to create some type of buttons that would only show the table columns affected to them and hidding every others, and add/remove the active class to the buttons, for example:

Data 1
Data 2
Data 3

            First column
            Second column
            Third column

            Test 1
            Test 2
            Test 3

For example, when I click on the "Data 2" button, it adds the "active" class to it, hides every other columns and only shows the items having the class called "vegetables".

I am a beginner and I would like to know if that's possible and how? Thank you.

Body:
Hope this suits you.

Some tweaks may be needed if you'll need extra classes on the <table>

$(() => { // wait until DOM is ready
  $('.btn').click(function onclick() { // set up onclick handler for all buttons of class 'btn'
    // on click
    $('.btn').removeClass('active');
        // remove 'active' class from all buttons
    $(this).toggleClass('active');
        // but add 'active' class to the clicked one (this)
    $('table').attr('class', $(this).attr('id'))
        // finally set the table class to be the id of the clicked button
  })
})

a.active { color: green }
table .fruits     { display: none }
table .vegetables { display: none }
table .nuts       { display: none }

table.fruits     .fruits     { display: table-cell }
table.vegetables .vegetables { display: table-cell }
table.nuts       .nuts       { display: table-cell }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="btn" id="fruits"    >Data 1</a>
<a href="#" class="btn" id="vegetables">Data 2</a>
<a href="#" class="btn" id="nuts"      >Data 3</a>

<table>

    <thead>
        <tr>
            <th class="fruits"    >First column</th>
            <th class="vegetables">Second column</th>
            <th class="nuts"      >Third column</th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td class="fruits"    >Test 1</td>
            <td class="vegetables">Test 2</td>
            <td class="nuts"      >Test 3</td>
        </tr>
    </tbody>

</table>


问:
help with a PHP regex to extract text around a string
I am trying to use a regular expression and it's just breaking my brain.  I'll think I have it and the the script just breaks. I need to try to give people a way to report their location via SMS. I ask them to text me a string that looks like this:

I give up, stopping for the night.
  Find me at Main Street and Pine,
  Atlanta, GA.

And I want to break it at Find me at. I need to capture everything to the right of that (essentially their street corner) and I need to be able to detect if they didn't use proper capitalization for Find.

Any suggestions?

答:
I would just preg_split(). If you know what you want should always be at the end.</p>

```<code>$str = "I give up, stopping for the night. Find me at Main Street and Pine, Atlanta, GA."

$strSplit = preg_split("/Find me at /i", $str);

$whatYouWant = $strSplit[1];
</code>```

Body:
I would just preg_split(). If you know what you want should always be at the end.

$str = "I give up, stopping for the night. Find me at Main Street and Pine, Atlanta, GA."

$strSplit = preg_split("/Find me at /i", $str);

$whatYouWant = $strSplit[1];


问:
How to write a Linux kernel module makefile?
I'm trying to write a simple hello world kernel module. I'm working in Ubuntu 18.04.2 LTS on Virtual Box. In the directory /usr/src I created a directory named hello and inside that hello directory I've created hello.c and a makefile. Here is my makefile:

```<code>obj-m += hello.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
</code>```

When I make the command "sudo make" I get this output:

```<code>make -C /lib/modules/5.3.0-28-generic/build M= modules
make[1]: Entering directory '/usr/src/linux-headers-5.3.0-28-generic'
make[2]: *** No rule to make target 'arch/x89/tools/relocs_32.c', needed by 'arch/x86/tools/relocs_32.o'. Stop.
arch/x86/Makefile:232: recipe for target 'archscripts' failed
make[1]: *** [archscripts] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-5.3.0-28-generic'
makefile:4: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

I've tried a few variations of my makefile including changing "PWD" to "shell pwd". I've installed all the essential tools and libraries as far as I know. What could be the problem here?

答:
Your Makefile should look like this

```<code>obj-m += hello.o
</code>```

Then your build command will look like

make -C $KDIR M=$PWD
```

Where $KDIR is the source tree of your kernel build.

is the way. The rest is handled by the kbuild system.

Please refer to refer to the official documentation for building off-tree modules

Body:
I'm trying to write a simple hello world kernel module. I'm working in Ubuntu 18.04.2 LTS on Virtual Box. In the directory /usr/src I created a directory named hello and inside that hello directory I've created hello.c and a makefile. Here is my makefile:

obj-m += hello.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

When I make the command "sudo make" I get this output:

make -C /lib/modules/5.3.0-28-generic/build M= modules
make[1]: Entering directory '/usr/src/linux-headers-5.3.0-28-generic'
make[2]: *** No rule to make target 'arch/x89/tools/relocs_32.c', needed by 'arch/x86/tools/relocs_32.o'. Stop.
arch/x86/Makefile:232: recipe for target 'archscripts' failed
make[1]: *** [archscripts] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-5.3.0-28-generic'
makefile:4: recipe for target 'all' failed
make: *** [all] Error 2

I've tried a few variations of my makefile including changing "PWD" to "shell pwd". I've installed all the essential tools and libraries as far as I know. What could be the problem here?

Body:
Your Makefile should look like this

obj-m += hello.o

Then your build command will look like

make -C $KDIR M=$PWD

Where $KDIR is the source tree of your kernel build.

is the way. The rest is handled by the kbuild system.

Please refer to refer to the official documentation for building off-tree modules


问:
Ray tracing: Ellipsoid Hit function
We are working with shape generation using ray tracing. We believe that the hit function is not working appropriately. Currently, the "front" side of the ellipsoid is lit correctly. As the shape rotates, it has problems reflecting light. Example of rotating the ellipsoid.

Below is the current version of the Hit function.

```<code>bool Ellipsoid::Hit(const Ray& ray,
                 const double minHitDistance,
                 const double maxHitDistance,
                 HitRecord& hitRecord,
                 const Vector3d& light) const {

    if (hitRecord.shapeHit == this) {
        return false;
    }

    // M is a 3x3 matrix
    const Vector3d& direction = (M.inverse()*ray.Direction());
    const Vector3d oc = M.inverse()*(ray.Origin() -this->center);

    const double a = direction.dot(direction);

    const double b = oc.dot(direction);

    const double c = oc.dot(oc) - 1;

    const double discriminant = b*b - a*c;
    if (discriminant > 0) {

        const double sqrtDiscriminant = sqrt(discriminant);
        const double aReciprocal = 1.0 / a;
        double temp = (-b - sqrtDiscriminant) * aReciprocal;
        if (temp < maxHitDistance && temp > minHitDistance) {
            hitRecord.distance = temp;
            hitRecord.closestIntersection = ray.PointAtParameter(hitRecord.distance);

            hitRecord.normal = M.inverse()*((hitRecord.closestIntersection - center) / 1);
            hitRecord.shapeHit = this;
            return true;
        }
        temp = (-b + sqrtDiscriminant) * aReciprocal;
        if (temp < maxHitDistance && temp > minHitDistance) {
            hitRecord.distance = temp;
            hitRecord.closestIntersection = ray.PointAtParameter(hitRecord.distance);

            hitRecord.normal =      M.inverse()*((hitRecord.closestIntersection - center) / 1);
            hitRecord.shapeHit = this;
            return true;
        }
    }

    return false;
}
</code>```

The first thing we tried was changing M.transpose() to M.inverse() on the lines where we set hitRecord.normal. This made the light look significantly better but did not completely help the light accuracy after rotating the object. We are unsure if the Hit function is completely correct. We just need some guidance to see if we need to look for other faults in the program. Any advice helps.

Edit: We have tried modifying the discriminant as well. This causes the function to break because the "4" is accounted for throughout the function (as seen in comment section).

答: After completely rewriting the function, we have determined the issue does not lie within the hit function.</p>

Title: Ray tracing: Ellipsoid Hit function

Body:
We are working with shape generation using ray tracing. We believe that the hit function is not working appropriately. Currently, the "front" side of the ellipsoid is lit correctly. As the shape rotates, it has problems reflecting light. Example of rotating the ellipsoid.

Below is the current version of the Hit function.

bool Ellipsoid::Hit(const Ray& ray,
                 const double minHitDistance,
                 const double maxHitDistance,
                 HitRecord& hitRecord,
                 const Vector3d& light) const {

    if (hitRecord.shapeHit == this) {
        return false;
    }

    // M is a 3x3 matrix
    const Vector3d& direction = (M.inverse()*ray.Direction());
    const Vector3d oc = M.inverse()*(ray.Origin() -this->center);

    const double a = direction.dot(direction);

    const double b = oc.dot(direction);

    const double c = oc.dot(oc) - 1;

    const double discriminant = b*b - a*c;
    if (discriminant > 0) {

        const double sqrtDiscriminant = sqrt(discriminant);
        const double aReciprocal = 1.0 / a;
        double temp = (-b - sqrtDiscriminant) * aReciprocal;
        if (temp < maxHitDistance && temp > minHitDistance) {
            hitRecord.distance = temp;
            hitRecord.closestIntersection = ray.PointAtParameter(hitRecord.distance);

            hitRecord.normal = M.inverse()*((hitRecord.closestIntersection - center) / 1);
            hitRecord.shapeHit = this;
            return true;
        }
        temp = (-b + sqrtDiscriminant) * aReciprocal;
        if (temp < maxHitDistance && temp > minHitDistance) {
            hitRecord.distance = temp;
            hitRecord.closestIntersection = ray.PointAtParameter(hitRecord.distance);

            hitRecord.normal =      M.inverse()*((hitRecord.closestIntersection - center) / 1);
            hitRecord.shapeHit = this;
            return true;
        }
    }

    return false;
}

The first thing we tried was changing M.transpose() to M.inverse() on the lines where we set hitRecord.normal. This made the light look significantly better but did not completely help the light accuracy after rotating the object. We are unsure if the Hit function is completely correct. We just need some guidance to see if we need to look for other faults in the program. Any advice helps.

Edit: We have tried modifying the discriminant as well. This causes the function to break because the "4" is accounted for throughout the function (as seen in comment section).


问:
What is the correct type for p5.js
I have installed @types/p5@0.9.0 for react-p5 but vs code isn't giving me any code hints for what type to use for p5 and I've reverted to any just to make it work, how should I go about finding the correct type to use?

```<code>import React from 'react';
import Sketch from 'react-p5';

const App: React.FC = () => {

  const setup = (p5: any) => {
    p5.createCanvas(window.innerWidth, window.innerHeight);
  };

  const draw = (p5: any) => {
    p5.background(50);
  };

  return (
    <React.Fragment>
      <Sketch setup={setup} draw={draw} />
    </React.Fragment>
  );
};

export { App };
</code>```

答:
The interface is p5InstanceExtensions
So try:

```<code>import {p5InstanceExtensions} from 'p5';
...
const setup = (p5: p5InstanceExtensions) => {
</code>```

Title: What is the correct type for p5.js

Body:
I have installed @types/p5@0.9.0 for react-p5 but vs code isn't giving me any code hints for what type to use for p5 and I've reverted to any just to make it work, how should I go about finding the correct type to use?

import React from 'react';
import Sketch from 'react-p5';

const App: React.FC = () => {

  const setup = (p5: any) => {
    p5.createCanvas(window.innerWidth, window.innerHeight);
  };

  const draw = (p5: any) => {
    p5.background(50);
  };

  return (
    <React.Fragment>
      <Sketch setup={setup} draw={draw} />
    </React.Fragment>
  );
};

export { App };

Body:
The interface is p5InstanceExtensions
So try:

import {p5InstanceExtensions} from 'p5';
...
const setup = (p5: p5InstanceExtensions) => {


问:
virtual box installation causes error while launching
The virtual machine 'cloudera-quickstart-vm-5.12.0-0-virtualbox' has terminated unexpectedly during startup with exit code 1 (0x1). More details may be available in 'C:\Users\Sri Dhanasheelan\VirtualBox VMs\cloudera-quickstart-vm-5.12.0-0-virtualbox\Logs\VBoxHardening.log'.

```<code>Result Code:
E_FAIL (0x80004005)
Component: MachineWrap Interface: IMachine {b2547866-a0a1-4391-8b86-6952d82efaa0}
</code>```

I have installed JDK ,visual studio-2015 in my windows10 system . But still get the error that the session to open virtual machine has been failed.

答: For me the problem occurred when running the VM with VBoxManage, and the fix was that I had forgotten to specify --type headless on the command line.

Body:
The virtual machine 'cloudera-quickstart-vm-5.12.0-0-virtualbox' has terminated unexpectedly during startup with exit code 1 (0x1). More details may be available in 'C:\Users\Sri Dhanasheelan\VirtualBox VMs\cloudera-quickstart-vm-5.12.0-0-virtualbox\Logs\VBoxHardening.log'.

Result Code:
E_FAIL (0x80004005)
Component: MachineWrap Interface: IMachine {b2547866-a0a1-4391-8b86-6952d82efaa0}

I have installed JDK ,visual studio-2015 in my windows10 system . But still get the error that the session to open virtual machine has been failed.


问:
Human-readable date formats
You may have noticed that certain web applications (for example, certain parts of GMail) display dates in a more human-readable format than simply DD/MM/YYYY.

For example, if I open up a mail item from the 23rd (which happens to be 3 days ago at the time of writing, I'll get the following:

Dec 23 (3 days ago)

I'd like to implement similar logic to this in my own web application.

For example, when dealing with a .NET TimeSpan object, I'd like to convert it to text such as the following:

2 months

3 days

Is there a .NET library capable of doing this already?

If not I might build something basic and open-source it.

I've made a basic start here:

```<code>public static class TimeSpanHelpers
{
    public static string ToHumanReadableString(
        this TimeSpan timeSpan)
    {
        if (timeSpan.TotalDays > 30)
            return (timeSpan.TotalDays / 30) + " month(s)";

        if (timeSpan.TotalDays > 7)
            return (timeSpan.TotalDays / 7) + " week(s)";

        return (timeSpan.TotalDays) + " day(s)";
    }
}
</code>```

答:
Another library for doing this: http://relativetime.codeplex.com/

(Available on NuGet)

ContentLicense: CC BY-SA 2.5

Title: Human-readable date formats

Body:
You may have noticed that certain web applications (for example, certain parts of GMail) display dates in a more human-readable format than simply DD/MM/YYYY.

For example, if I open up a mail item from the 23rd (which happens to be 3 days ago at the time of writing, I'll get the following:

Dec 23 (3 days ago)

I'd like to implement similar logic to this in my own web application.

For example, when dealing with a .NET TimeSpan object, I'd like to convert it to text such as the following:

2 months

3 days

Is there a .NET library capable of doing this already?

If not I might build something basic and open-source it.

I've made a basic start here:

public static class TimeSpanHelpers
{
    public static string ToHumanReadableString(
        this TimeSpan timeSpan)
    {
        if (timeSpan.TotalDays > 30)
            return (timeSpan.TotalDays / 30) + " month(s)";

        if (timeSpan.TotalDays > 7)
            return (timeSpan.TotalDays / 7) + " week(s)";

        return (timeSpan.TotalDays) + " day(s)";
    }
}


问:
JAVA: How do I determine if the input is a palindrome?
Please use the method below.

I am trying to get rid of all white spaces, punctuations and make everything lowercase. Then I want to see whether the string is a palindrome (same when read from the front and back.

I can't figure it out.

```<code>public static void main(String[] args) {

        String word=null;
        String reverse="";
        Scanner console = new Scanner(System.in);

        System.out.print("Please enter a word or a phrase:");
        word = console.nextLine();

        word=word.replaceAll("\\s+",""); //removes white space
        word=word.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
        word=word.toLowerCase();

        for(int i=word.length()-1; i>=0; i--) {
        reverse +=word.charAt(i);

        }

        for(int i=0; i<word.length(); i++) {
            System.out.print(word);
        if(word.charAt(i) != reverse.charAt(i)) {
            System.out.println("Not a Palindrome");
        }else {
                System.out.println("Palindrome");```

```

答:
You can have two indices i and j, where i starts at 0-index and j starts at the end of array. Do i++ and j-- and at each iteration check if the element is same and when j>i you break the loop and say its palindrome or else it is not Palindrome.

You can do this iteratively or recursively.

Hope it helps!

Body:
Please use the method below.

I am trying to get rid of all white spaces, punctuations and make everything lowercase. Then I want to see whether the string is a palindrome (same when read from the front and back.

I can't figure it out.

public static void main(String[] args) {

        String word=null;
        String reverse="";
        Scanner console = new Scanner(System.in);

        System.out.print("Please enter a word or a phrase:");
        word = console.nextLine();

        word=word.replaceAll("\\s+",""); //removes white space
        word=word.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
        word=word.toLowerCase();

        for(int i=word.length()-1; i>=0; i--) {
        reverse +=word.charAt(i);

        }

        for(int i=0; i<word.length(); i++) {
            System.out.print(word);
        if(word.charAt(i) != reverse.charAt(i)) {
            System.out.println("Not a Palindrome");
        }else {
                System.out.println("Palindrome");```


问:
How can I compile with LLVM/Clang to RISC-V target?
I want to compile a simple program "int main(){return 0;}" to RISC-V processor.
LLVM/Clang version is 9.0 and I want to run the compiled program with a RISC-V simulator like this https://github.com/riscv/riscv-tools

My problem is that I can't list the clang supported targets only the LLC-s whith these commands:

```<code>llc --version
llc -march=xxARCHTYPExx -mattr=help
</code>```

And there is no any type of riscv processor listed.

So I tried to look the triple file: llvm-project\llvm\include\llvm\ADT\Triple.h

and try a command like: clang hello.c -target riscv32 -march=rv32imafd

But I get the following error:

error: unable to create target: 'No available targets are compatible
  with triple "riscv32"'

Can somebody help me to how get a valid RISC-V target? I just simple can't compile the program but I know LLVM has a RISC-V support.

答:
LLVM 9 release notes explicitly state that RISC-V support was promoted from experimental to official.

And indeed, on my Fedora 31 machine, the LLVM 9 Fedora package does support RISC-V:

```<code>$ llvm-objdump --version | grep riscv
    riscv32    - 32-bit RISC-V
    riscv64    - 64-bit RISC-V
</code>```

Also, I can create RISC-V binary code with the LLVM toolchain:

```<code>$ clang --target=riscv64 -march=rv64gc rotate.s -c -o rotate.o
$ file rotate.o
rotate.o: ELF 64-bit LSB relocatable, UCB RISC-V, version 1 (SYSV), not stripped
</code>```

Although it doesn't include a libc for RISC-V targets:

```<code>$ clang --target=riscv64 -march=rv64gc hello-world.c -o hello-world
hello-world.c:1:10: fatal error: 'stdio.h' file not found
#include <stdio.h>
         ^~~~~~~~~
1 error generated.
</code>```

However, you don't really need one - you could directly call syscalls for your hello world, e.g.:

```<code>$ clang  --target=riscv64 -march=rv64gc  hello.s -c -o hello.o
$ ld.lld hello.o -o hello
$ spike --isa=RV64gc ~/local/riscv/pk/riscv64-unknown-elf/bin/pk ./hello
bbl loader
Hello World
</code>```

I don't use clang for linking because it seems that I can't convince clang with -fuse-ld to use another linker besides /usr/bin/ld.

Body:
I want to compile a simple program "int main(){return 0;}" to RISC-V processor.
LLVM/Clang version is 9.0 and I want to run the compiled program with a RISC-V simulator like this https://github.com/riscv/riscv-tools

My problem is that I can't list the clang supported targets only the LLC-s whith these commands:

llc --version
llc -march=xxARCHTYPExx -mattr=help

And there is no any type of riscv processor listed.

So I tried to look the triple file: llvm-project\llvm\include\llvm\ADT\Triple.h

and try a command like: clang hello.c -target riscv32 -march=rv32imafd

But I get the following error:

error: unable to create target: 'No available targets are compatible
  with triple "riscv32"'

Can somebody help me to how get a valid RISC-V target? I just simple can't compile the program but I know LLVM has a RISC-V support.

Body:
LLVM 9 release notes explicitly state that RISC-V support was promoted from experimental to official.

And indeed, on my Fedora 31 machine, the LLVM 9 Fedora package does support RISC-V:

$ llvm-objdump --version | grep riscv
    riscv32    - 32-bit RISC-V
    riscv64    - 64-bit RISC-V

Also, I can create RISC-V binary code with the LLVM toolchain:

$ clang --target=riscv64 -march=rv64gc rotate.s -c -o rotate.o
$ file rotate.o
rotate.o: ELF 64-bit LSB relocatable, UCB RISC-V, version 1 (SYSV), not stripped

Although it doesn't include a libc for RISC-V targets:

$ clang --target=riscv64 -march=rv64gc hello-world.c -o hello-world
hello-world.c:1:10: fatal error: 'stdio.h' file not found
#include <stdio.h>
         ^~~~~~~~~
1 error generated.

However, you don't really need one - you could directly call syscalls for your hello world, e.g.:

$ clang  --target=riscv64 -march=rv64gc  hello.s -c -o hello.o
$ ld.lld hello.o -o hello
$ spike --isa=RV64gc ~/local/riscv/pk/riscv64-unknown-elf/bin/pk ./hello
bbl loader
Hello World

I don't use clang for linking because it seems that I can't convince clang with -fuse-ld to use another linker besides /usr/bin/ld.