问:
list index out of range python decompressing text
The code I currently have is shown below. What it does first is ask the user to input a sentence. The program then finds the position of each word in the sentence and also splits the word into a list to get individual words. The program then gets rid of any repeated words to make the words in the list unique. The program then proceeds to save (using son)the position of words in the sentence (e.g 1,2,3,4,1,1,2,3,5) and unique words to a separate file (which the user can name). The next part of the program tries to decompress the unique text from the separate file and tries to recreate the original sentence from the position of words in the sentence and unique words. I know this stage works as I have tested it separately. However when i run the program now, I keep getting this error message:

File "/Users/Sid/Desktop/Task3New.py", line 70, in OutputDecompressed
        decompression.append(orgwords[i])
    IndexError: list index out of range

I have no idea why this isn't working, anyone care to help? All help appreciated, thanks.

```<code>import json
import os.path

def InputSentence():
    global sentence
    global words
    sentence = input("Enter a sentence: ")
    words = sentence.split(' ')

def Validation():
    if sentence == (""):
        print ("No sentence was inputted. \nPlease input a sentence...")
        Error()

def Uniquewords():
    print ("Words in the sentence: " + str(words))
    for i in range(len(words)):
        if words[i] not in unilist:
            unilist.append(words[i])
    print ("Unique words: " + str(unilist))

def PosText():
    global find
    global pos
    find = dict((sentence, words.index(sentence)+1) for sentence in          list(words))
    pos = (list(map(lambda sentence: find [sentence], words)))
    return (pos)

def OutputText():
    print ("The positions of the word(s) in the sentence are: " + str(pos))

def SaveFile():
    filename = input("We are now going to save the contents of this program        into a new file. \nWhat would you like to call the new file? ")
    newfile = open((filename)+'.txt', 'w')
    json.dump([unilist, pos], newfile)
    newfile.close

def InputFile():
    global compfilename
    compfilename = input("Please enter an existing compressed file to be  decompressed: ")

def Validation2():
    if compfilename == (""):
        print ("Nothing was entered for the filename. Please re-enter a  valid filename.")
        Error()
    if os.path.exists(filename + ".txt") == False:
        print ("No such file exists. Please enter a valid existing file.")
        Error()

def OutputDecompressed():
    newfile = open((compfilename)+'.txt', 'r')
    saveddata = json.load(newfile)
    orgpos = saveddata[1]
    orgwords = saveddata[0]
    print ("Unique words in the original sentence: " + str(orgwords) +  "\nPosition of words in the sentence: " + str(orgpos))
    decompression = []
    prev = orgpos[0]
    x=0
    #decomposing the index locations
    for cur in range(1,len(orgpos)):
        if (prev == orgpos[cur]): x+= 1
        else:
            orgpos[cur]-=x
            x=0
        prev = orgpos[cur]
    #Getting the output
    for i in orgpos:
        decompression.append(orgwords[i-1])
    finalsentence = (' '.join(decompression))
    print ("Original sentence from file: " + finalsentence)

def Error():
    MainCompression()

def MainCompression():
    global unilist
    unilist = []
    InputSentence()
    Uniquewords()
    PosText()
    OutputText()
    SaveFile()
    InputFile()
    Validation()
    OutputDecompressed()

MainCompression()
</code>```

答:
The problem is that you are using the indices form words as indices for unilist/orgwords.

Let's take a look at the problem:

```<code>def PosText():
    global find
    global pos
    find = dict((sentence, words.index(sentence)+1) for sentence in          list(words))
    pos = (list(map(lambda sentence: find [sentence], words)))
    return (pos)
</code>```

Here find maps every word to its position in the list words. (BTW why is the variable that iterates over words called sentence?) Then, for every word this position is stored in a new list. This process could be expressed in one line: pos = [words.index(word)+1 for word in words]

When you now look at OutputDecompressed, you see:

```<code>for i in orgpos:
    decompression.append(orgwords[i-1])
</code>```

Here orgpos is pos and orgwords is the list of unique words. Now every stored index is used to get back the original words, but this is flawed because orgpos contains indices of words even though they are used to access orgwords.

The solution to this problem is to rewrite PosText and parts of OutputDecompressed:

```<code>def PosText():
    global pos
    pos = [unilist.index(word)+1 for word in words]
    return pos

def OutputDecompressed():
    newfile = open((compfilename)+'.txt', 'r')
    saveddata = json.load(newfile)
    orgpos = saveddata[1]
    orgwords = saveddata[0]
    print ("Unique words in the original sentence: " + str(orgwords) +  "\nPosition of words in the sentence: " + str(orgpos))
    decompression = []
    # I could not figure out what this middle part was doing, so I left it out
    for i in orgpos:
        decompression.append(orgwords[i-1])
    finalsentence = (' '.join(decompression))
    print ("Original sentence from file: " + finalsentence)
</code>```

Some comments on your code:

After InputSentence() Validation() should be called to validate it

After InputFile() you must call Validation2() and not Validation()

In Validation2() it should be compfilename and not filename

You should use parameters instead of global variables. This makes it more clear what the functions are supposed to do. For example Uniquewords could accept the list of words and return the list of unique words. It also makes the program much easier to debug by just testing every function one-by-one, which is currently not possible.

To make it easier for other Python programmers to read your code you could use the Python coding style specified in PEP 8

Body:
The code I currently have is shown below. What it does first is ask the user to input a sentence. The program then finds the position of each word in the sentence and also splits the word into a list to get individual words. The program then gets rid of any repeated words to make the words in the list unique. The program then proceeds to save (using son)the position of words in the sentence (e.g 1,2,3,4,1,1,2,3,5) and unique words to a separate file (which the user can name). The next part of the program tries to decompress the unique text from the separate file and tries to recreate the original sentence from the position of words in the sentence and unique words. I know this stage works as I have tested it separately. However when i run the program now, I keep getting this error message:

File "/Users/Sid/Desktop/Task3New.py", line 70, in OutputDecompressed
        decompression.append(orgwords[i])
    IndexError: list index out of range

I have no idea why this isn't working, anyone care to help? All help appreciated, thanks.

import json
import os.path

def InputSentence():
    global sentence
    global words
    sentence = input("Enter a sentence: ")
    words = sentence.split(' ')

def Validation():
    if sentence == (""):
        print ("No sentence was inputted. \nPlease input a sentence...")
        Error()

def Uniquewords():
    print ("Words in the sentence: " + str(words))
    for i in range(len(words)):
        if words[i] not in unilist:
            unilist.append(words[i])
    print ("Unique words: " + str(unilist))

def PosText():
    global find
    global pos
    find = dict((sentence, words.index(sentence)+1) for sentence in          list(words))
    pos = (list(map(lambda sentence: find [sentence], words)))
    return (pos)

def OutputText():
    print ("The positions of the word(s) in the sentence are: " + str(pos))

def SaveFile():
    filename = input("We are now going to save the contents of this program        into a new file. \nWhat would you like to call the new file? ")
    newfile = open((filename)+'.txt', 'w')
    json.dump([unilist, pos], newfile)
    newfile.close

def InputFile():
    global compfilename
    compfilename = input("Please enter an existing compressed file to be  decompressed: ")

def Validation2():
    if compfilename == (""):
        print ("Nothing was entered for the filename. Please re-enter a  valid filename.")
        Error()
    if os.path.exists(filename + ".txt") == False:
        print ("No such file exists. Please enter a valid existing file.")
        Error()

def OutputDecompressed():
    newfile = open((compfilename)+'.txt', 'r')
    saveddata = json.load(newfile)
    orgpos = saveddata[1]
    orgwords = saveddata[0]
    print ("Unique words in the original sentence: " + str(orgwords) +  "\nPosition of words in the sentence: " + str(orgpos))
    decompression = []
    prev = orgpos[0]
    x=0
    #decomposing the index locations
    for cur in range(1,len(orgpos)):
        if (prev == orgpos[cur]): x+= 1
        else:
            orgpos[cur]-=x
            x=0
        prev = orgpos[cur]
    #Getting the output
    for i in orgpos:
        decompression.append(orgwords[i-1])
    finalsentence = (' '.join(decompression))
    print ("Original sentence from file: " + finalsentence)

def Error():
    MainCompression()

def MainCompression():
    global unilist
    unilist = []
    InputSentence()
    Uniquewords()
    PosText()
    OutputText()
    SaveFile()
    InputFile()
    Validation()
    OutputDecompressed()

MainCompression()

Body:
The problem is that you are using the indices form words as indices for unilist/orgwords.

Let's take a look at the problem:

def PosText():
    global find
    global pos
    find = dict((sentence, words.index(sentence)+1) for sentence in          list(words))
    pos = (list(map(lambda sentence: find [sentence], words)))
    return (pos)

Here find maps every word to its position in the list words. (BTW why is the variable that iterates over words called sentence?) Then, for every word this position is stored in a new list. This process could be expressed in one line: pos = [words.index(word)+1 for word in words]

When you now look at OutputDecompressed, you see:

for i in orgpos:
    decompression.append(orgwords[i-1])

Here orgpos is pos and orgwords is the list of unique words. Now every stored index is used to get back the original words, but this is flawed because orgpos contains indices of words even though they are used to access orgwords.

The solution to this problem is to rewrite PosText and parts of OutputDecompressed:

def PosText():
    global pos
    pos = [unilist.index(word)+1 for word in words]
    return pos

def OutputDecompressed():
    newfile = open((compfilename)+'.txt', 'r')
    saveddata = json.load(newfile)
    orgpos = saveddata[1]
    orgwords = saveddata[0]
    print ("Unique words in the original sentence: " + str(orgwords) +  "\nPosition of words in the sentence: " + str(orgpos))
    decompression = []
    # I could not figure out what this middle part was doing, so I left it out
    for i in orgpos:
        decompression.append(orgwords[i-1])
    finalsentence = (' '.join(decompression))
    print ("Original sentence from file: " + finalsentence)

Some comments on your code:

After InputSentence() Validation() should be called to validate it

After InputFile() you must call Validation2() and not Validation()

In Validation2() it should be compfilename and not filename

You should use parameters instead of global variables. This makes it more clear what the functions are supposed to do. For example Uniquewords could accept the list of words and return the list of unique words. It also makes the program much easier to debug by just testing every function one-by-one, which is currently not possible.

To make it easier for other Python programmers to read your code you could use the Python coding style specified in PEP 8


来源: stackexchange

问:
Android email validation for english and arabic characters
I am currently using this regular expression pattern to validate email addresses:

```<code>android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches();
</code>```

It doesn't work with Arabic characters. I need it to work with both English and Arabic characters.

This is the regex pattern I have incorporate for android (OS) in my project:

```<code>    public static final Pattern EMAIL_ADDRESS
    = Pattern.compile(
        "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
        "\\@" +
        "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
        "(" +
            "\\." +
            "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
        ")+"
    );
</code>```

I am not regex expert. I could use some help figuring out how to support both.

答:
This may not be the best answer, but I was able to get it to work by adding the aribic characters:

```<code>[\u0621-\u064A\u0660-\u0669a-zA-Z0-9\+\.\_\%\-\+]{1,256}\@[\u0621-\u064A\u0660-\u0669a-zA-Z0-9][\u0621-\u064A\u0660-\u0669a-zA-Z0-9\-]{0,64}(\.[\u0621-\u064A\u0660-\u0669a-zA-Z0-9][\u0621-\u064A\u0660-\u0669a-zA-Z0-9\-]{0,25})+
</code>```

Here's an example on regexr! (it doesn't display Arabic selection properly, but it is selected)

ContentLicense: CC BY-SA 4.0

Body:
I am currently using this regular expression pattern to validate email addresses:

android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches();

It doesn't work with Arabic characters. I need it to work with both English and Arabic characters.

This is the regex pattern I have incorporate for android (OS) in my project:

    public static final Pattern EMAIL_ADDRESS
    = Pattern.compile(
        "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
        "\\@" +
        "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
        "(" +
            "\\." +
            "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
        ")+"
    );

I am not regex expert. I could use some help figuring out how to support both.

Body:
This may not be the best answer, but I was able to get it to work by adding the aribic characters:

[\u0621-\u064A\u0660-\u0669a-zA-Z0-9\+\.\_\%\-\+]{1,256}\@[\u0621-\u064A\u0660-\u0669a-zA-Z0-9][\u0621-\u064A\u0660-\u0669a-zA-Z0-9\-]{0,64}(\.[\u0621-\u064A\u0660-\u0669a-zA-Z0-9][\u0621-\u064A\u0660-\u0669a-zA-Z0-9\-]{0,25})+

Here's an example on regexr! (it doesn't display Arabic selection properly, but it is selected)

ContentLicense: CC BY-SA 3.0


问:
Display items (TextView, ImageView etc) on timers in Android
I'm fairly new to android and was wondering if in my activity I can display different text views for a certain amount of seconds before they vanish, replaced with a different text view.

Is there any way I can handle these events within an activity? I am creating a simple game and would like the Views in the activity to display after one another.

I could not find any help online (may have been searching for the wrong thing)

答:
You can definitely use a timer variable to keep track of time and then use the setVisibility() method to set the textview visible(View.VISIBLE) or invisible(View.INVISIBLE).

For example:

```<code>    TextView textView=(TextView)findViewById(R.id.text);
    textView.setVisibility(View.INVISIBLE);
</code>```

Body:
You can definitely use a timer variable to keep track of time and then use the setVisibility() method to set the textview visible(View.VISIBLE) or invisible(View.INVISIBLE).

For example:

    TextView textView=(TextView)findViewById(R.id.text);
    textView.setVisibility(View.INVISIBLE);


问:
Drupal 7 Webform redirect
We have a Drupal 7 webform that redirects to a url upon successful submission.

What we need to do is redirect the user if they land on the same webform again and have already submitted.

Do we need a module for this, or do it programmatically?

Thanks in advance.

答:
I looked through the webform module and didn't find any setting that will redirect the user if the user has already submitted a form, so I think you need to do it programmatically.

Note: It might be possible without a custom module by using the rules module. I haven't tried this.

To do it programmatically you could do something like below. It implements the hook_node_view() and checks if the user has already submitted anything by using the webform api function webform_get_submission_count(). (edit: the custom module in this example is called example_webform)

```<code><?php

/**
 * Implements hook_node_view().
 */
function example_webform_node_view($node, $view_mode, $langcode) {
  global $user;
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  $submission_count = webform_get_submission_count($node->nid, $user->uid);
  if (!empty($submission_count) && $submission_count > 0) {
    $redirect = $node->webform['redirect_url'];
    drupal_goto($redirect);
  }
}
</code>```

As it is now it will reuse the page that is used when the form is submitted, so if you choose to do this remember to make the success page reflect this. (E.g. it would be strange for the success page to say "your post has been saved" if the user lands on it for the second time.) Or you could replace the $redirect with another page than the one from the webform setting.

Also note that the webform will still add the message "You have already submitted this form. View your previous submissions." if this is enabled.

Title: Drupal 7 Webform redirect

Body:
I looked through the webform module and didn't find any setting that will redirect the user if the user has already submitted a form, so I think you need to do it programmatically.

Note: It might be possible without a custom module by using the rules module. I haven't tried this.

To do it programmatically you could do something like below. It implements the hook_node_view() and checks if the user has already submitted anything by using the webform api function webform_get_submission_count(). (edit: the custom module in this example is called example_webform)

<?php

/**
 * Implements hook_node_view().
 */
function example_webform_node_view($node, $view_mode, $langcode) {
  global $user;
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  $submission_count = webform_get_submission_count($node->nid, $user->uid);
  if (!empty($submission_count) && $submission_count > 0) {
    $redirect = $node->webform['redirect_url'];
    drupal_goto($redirect);
  }
}

As it is now it will reuse the page that is used when the form is submitted, so if you choose to do this remember to make the success page reflect this. (E.g. it would be strange for the success page to say "your post has been saved" if the user lands on it for the second time.) Or you could replace the $redirect with another page than the one from the webform setting.

Also note that the webform will still add the message "You have already submitted this form. View your previous submissions." if this is enabled.


问:
Django Advanced Filter not working in django-material admin Theme
I am using django 1.9.5 and in admin panel i have imported django-advaced-filter and it works well but when i have changed my django admin theme to django-material then django-advanced-filter is not working i am only getting Title of django-material but the pop is not comming

Please see the above screen shot

答:
I solved by copying the files change_list.html (https://github.com/viewflow/django-material/blob/master/material/admin/templates/admin/change_list.html)
in templates/admin/
and adding:

```<code>e.stopImmediatePropagation ( );
</code>```

at line 45

Body:
I solved by copying the files change_list.html (https://github.com/viewflow/django-material/blob/master/material/admin/templates/admin/change_list.html)
in templates/admin/
and adding:

e.stopImmediatePropagation ( );

at line 45


问:
Cropping image with Swift and put it on center position
In Swift programming , how do you crop an image and put it on the center afterwards?

This is what I've got so far ... I've successfully crop the image but I want to put it on the center after

```<code>ImgView.image = OrigImage
var masklayer = CAShapeLayer()
masklayer.frame = ImgView.frame
masklayer.path = path.CGPath
masklayer.fillColor = UIColor.whiteColor().CGColor
masklayer.backgroundColor = UIColor.clearColor().CGColor

ImgView.layer.mask = masklayer

UIGraphicsBeginImageContext(ImgView.bounds.size);
ImgView.layer.renderInContext(UIGraphicsGetCurrentContext())
var image = UIGraphicsGetImageFromCurrentImageContext()
ImgView.image = image
UIGraphicsEndImageContext();
</code>```

UPDATE :

```<code>let rect: CGRect = CGRectMake(path.bounds.minX, path.bounds.minY, path.bounds.width, path.bounds.height)

// Create bitmap image from context using the rect
let imageRef: CGImageRef = CGImageCreateWithImageInRect(image.CGImage, rect)
ImgView.bounds = rect
ImgView.image = UIImage(CGImage: imageRef)
</code>```

I was able to center it by getting the path.bound and size and change the bounds of my ImageView. :)

答:
Working Swift 3 example

```<code>extension UIImage {

    func crop(to:CGSize) -> UIImage {
        guard let cgimage = self.cgImage else { return self }

        let contextImage: UIImage = UIImage(cgImage: cgimage)

        let contextSize: CGSize = contextImage.size

        //Set to square
        var posX: CGFloat = 0.0
        var posY: CGFloat = 0.0
        let cropAspect: CGFloat = to.width / to.height

        var cropWidth: CGFloat = to.width
        var cropHeight: CGFloat = to.height

        if to.width > to.height { //Landscape
            cropWidth = contextSize.width
            cropHeight = contextSize.width / cropAspect
            posY = (contextSize.height - cropHeight) / 2
        } else if to.width < to.height { //Portrait
            cropHeight = contextSize.height
            cropWidth = contextSize.height * cropAspect
            posX = (contextSize.width - cropWidth) / 2
        } else { //Square
            if contextSize.width >= contextSize.height { //Square on landscape (or square)
                cropHeight = contextSize.height
                cropWidth = contextSize.height * cropAspect
                posX = (contextSize.width - cropWidth) / 2
            }else{ //Square on portrait
                cropWidth = contextSize.width
                cropHeight = contextSize.width / cropAspect
                posY = (contextSize.height - cropHeight) / 2
            }
        }

        let rect: CGRect = CGRect(x: posX, y: posY, width: cropWidth, height: cropHeight)
        // Create bitmap image from context using the rect
        let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)!

        // Create a new image based on the imageRef and rotate back to the original orientation
        let cropped: UIImage = UIImage(cgImage: imageRef, scale: self.scale, orientation: self.imageOrientation)

        UIGraphicsBeginImageContextWithOptions(to, true, self.scale)
        cropped.draw(in: CGRect(x: 0, y: 0, width: to.width, height: to.height))
        let resized = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return resized!
    }
}
</code>```

Body:
In Swift programming , how do you crop an image and put it on the center afterwards?

This is what I've got so far ... I've successfully crop the image but I want to put it on the center after

ImgView.image = OrigImage
var masklayer = CAShapeLayer()
masklayer.frame = ImgView.frame
masklayer.path = path.CGPath
masklayer.fillColor = UIColor.whiteColor().CGColor
masklayer.backgroundColor = UIColor.clearColor().CGColor

ImgView.layer.mask = masklayer

UIGraphicsBeginImageContext(ImgView.bounds.size);
ImgView.layer.renderInContext(UIGraphicsGetCurrentContext())
var image = UIGraphicsGetImageFromCurrentImageContext()
ImgView.image = image
UIGraphicsEndImageContext();

UPDATE :

let rect: CGRect = CGRectMake(path.bounds.minX, path.bounds.minY, path.bounds.width, path.bounds.height)

// Create bitmap image from context using the rect
let imageRef: CGImageRef = CGImageCreateWithImageInRect(image.CGImage, rect)
ImgView.bounds = rect
ImgView.image = UIImage(CGImage: imageRef)

I was able to center it by getting the path.bound and size and change the bounds of my ImageView. :)

Body:
Working Swift 3 example

extension UIImage {

    func crop(to:CGSize) -> UIImage {
        guard let cgimage = self.cgImage else { return self }

        let contextImage: UIImage = UIImage(cgImage: cgimage)

        let contextSize: CGSize = contextImage.size

        //Set to square
        var posX: CGFloat = 0.0
        var posY: CGFloat = 0.0
        let cropAspect: CGFloat = to.width / to.height

        var cropWidth: CGFloat = to.width
        var cropHeight: CGFloat = to.height

        if to.width > to.height { //Landscape
            cropWidth = contextSize.width
            cropHeight = contextSize.width / cropAspect
            posY = (contextSize.height - cropHeight) / 2
        } else if to.width < to.height { //Portrait
            cropHeight = contextSize.height
            cropWidth = contextSize.height * cropAspect
            posX = (contextSize.width - cropWidth) / 2
        } else { //Square
            if contextSize.width >= contextSize.height { //Square on landscape (or square)
                cropHeight = contextSize.height
                cropWidth = contextSize.height * cropAspect
                posX = (contextSize.width - cropWidth) / 2
            }else{ //Square on portrait
                cropWidth = contextSize.width
                cropHeight = contextSize.width / cropAspect
                posY = (contextSize.height - cropHeight) / 2
            }
        }

        let rect: CGRect = CGRect(x: posX, y: posY, width: cropWidth, height: cropHeight)
        // Create bitmap image from context using the rect
        let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)!

        // Create a new image based on the imageRef and rotate back to the original orientation
        let cropped: UIImage = UIImage(cgImage: imageRef, scale: self.scale, orientation: self.imageOrientation)

        UIGraphicsBeginImageContextWithOptions(to, true, self.scale)
        cropped.draw(in: CGRect(x: 0, y: 0, width: to.width, height: to.height))
        let resized = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return resized!
    }
}


问:
Barplot and Binning Issue
I am having trouble producing a meaningful barplot for a project that I am working on in R. This is a sample of the df that I am working with.

```<code>     State JobCode      AverageYearlySalary
2404    CA 15-1031               95820
2408    IN 15-1031               94750
2429    CA 15-2041               85570
2451    NY 15-2041               79300
2452    IN 15-2041               79150
</code>```

Let me outline my struggles to this point. I have tried to organize the values by JobCode using: data1 <- reshape(data, idvar = "JobCode", timevar = "State", direction = "wide"). I then transform the df into a matrix test <- as.matrix(data1). My data type for JobCode is a character, which I believe is causing some of my issues. Once done, I use barplot(test4[,2:4], beside = TRUE) but always recieve the error -0.01*height : non-numeric argument to binary operator.

I want the barplot to organize the individual for JobCode on the x-axis and then AverageYearlySalary on the y-axis to compare the different states involved. I'm quite new to R and can't figure out a solution after about an hour and a half of google and brute force coding.

I would appreciate any help. Thank you.

答:
You just need to make the right matrix for your barplot.

```<code>XT = xtabs(AverageYearlySalary ~ State + JobCode, data=test4)
barplot(XT, beside=TRUE, col=rainbow(3), ylim=c(0,99000))
legend("topright", legend=rownames(XT), pt.bg=rainbow(3), pch=22)
</code>```

Title: Barplot and Binning Issue

Body:
I am having trouble producing a meaningful barplot for a project that I am working on in R. This is a sample of the df that I am working with.

     State JobCode      AverageYearlySalary
2404    CA 15-1031               95820
2408    IN 15-1031               94750
2429    CA 15-2041               85570
2451    NY 15-2041               79300
2452    IN 15-2041               79150

Let me outline my struggles to this point. I have tried to organize the values by JobCode using: data1 <- reshape(data, idvar = "JobCode", timevar = "State", direction = "wide"). I then transform the df into a matrix test <- as.matrix(data1). My data type for JobCode is a character, which I believe is causing some of my issues. Once done, I use barplot(test4[,2:4], beside = TRUE) but always recieve the error -0.01*height : non-numeric argument to binary operator.

I want the barplot to organize the individual for JobCode on the x-axis and then AverageYearlySalary on the y-axis to compare the different states involved. I'm quite new to R and can't figure out a solution after about an hour and a half of google and brute force coding.

I would appreciate any help. Thank you.

Body:
You just need to make the right matrix for your barplot.

XT = xtabs(AverageYearlySalary ~ State + JobCode, data=test4)
barplot(XT, beside=TRUE, col=rainbow(3), ylim=c(0,99000))
legend("topright", legend=rownames(XT), pt.bg=rainbow(3), pch=22)


问:
Random() instance in web farm
I'm running an application on multiple web servers that communicate with a distributed in-memory caching cluster, where I generate exclusive lock IDs on the application server -- the problem is that in high concurrency of parallel execution it is possible that more than one execution across all servers would generate the same pseudo random lock value.

The idea would be to initiate a single instance of the Random class per application pool using an incrementing seed within the distributed caching cluster, and to re-seed the randomizer after each helper method to generate a thread safe random number has reached a specific number of invocations.

Interested to see what thoughts you would have on this.

答:
Random is just that - RANDOM. Not guaranteed to be unique. Rolling a die is an example of a random event, yet you may get the same result 6 out of 6 times.

GUID objects are (almost) guaranteed to be unique, so just use those instead.

Title: Random() instance in web farm


问:
Modifying reference type parameters in Swift; are changes immediately visible outside?
I have a Swift playground that contains several classes in the source folder. These classes have tick() functions that are called as fast as possible with a while true { }. I am using a parallel thread to do this, to stop Xcode from locking up, with this code:

```<code>DispatchQueue.global(qos: .background).async {
    BackgroundThread.startMainLoop(scene: scene)
}

// other file
public struct BackgroundThread {
    public static func startMainLoop (scene: SKScene) {
        let songController = SongController()
        let uiManager = UIManager(scene: scene)

// The UIManager is going to modify this scene.
// Will the changes be available to BackgroundThread and/or the main file?

        while true {
            songController.tick()
            uiManager.tick()
        }
    }
}
</code>```

Because the main playground script is very slow, I have moved the repeating loop to a compiled class in the Sources folder.

I am passing an SKScene object to a UIManager compiled class, which I will need to update the UI in this (relatively complicated) scene faster than the main playground script can manage.

The main playground script calls a startMainLoop() function in the parallel thread. It passes in the SKScene object. This function never returns, since it contains a never-ending loop. Is there a way I can modify the passed object in a manner that modifies the scene displayed on the screen, live, without the function ever having to return (which means that inout is not an option), assuming this does not happen by default?

答: Reference type means the value is a reference -- i.e. a pointer to an object. When you pass or assign a reference, you get a copy of the reference (it is pass-by-value without inout), but multiple copies of the reference point to the same object, and modifications to the object through any reference that points to it is visible through any other reference that points to it.

Body:
I have a Swift playground that contains several classes in the source folder. These classes have tick() functions that are called as fast as possible with a while true { }. I am using a parallel thread to do this, to stop Xcode from locking up, with this code:

DispatchQueue.global(qos: .background).async {
    BackgroundThread.startMainLoop(scene: scene)
}

// other file
public struct BackgroundThread {
    public static func startMainLoop (scene: SKScene) {
        let songController = SongController()
        let uiManager = UIManager(scene: scene)

// The UIManager is going to modify this scene.
// Will the changes be available to BackgroundThread and/or the main file?

        while true {
            songController.tick()
            uiManager.tick()
        }
    }
}

Because the main playground script is very slow, I have moved the repeating loop to a compiled class in the Sources folder.

I am passing an SKScene object to a UIManager compiled class, which I will need to update the UI in this (relatively complicated) scene faster than the main playground script can manage.

The main playground script calls a startMainLoop() function in the parallel thread. It passes in the SKScene object. This function never returns, since it contains a never-ending loop. Is there a way I can modify the passed object in a manner that modifies the scene displayed on the screen, live, without the function ever having to return (which means that inout is not an option), assuming this does not happen by default?


问:
use createHash in angular-md5
When I wanna use the createHash function in angular, this error raises : md5.createHash is not a function

Here's my code :

```<code>MyCtrl.$inject = ['md5'];
function MyCtrl(md5) {
var vm = this;

vm.reg = reg;

function reg() {
    vm.avatar = md5.createHash('salam'); // This Line Has Error
    console.log(vm.avatar);
...
</code>```

Note: I added the module dependency fine !

答:
You need to add angular-md5 to your project module as well le below.</p>

```<code>angular.module('YOUR_APP', [
    'angular-md5', // you may also use 'ngMd5' or 'gdi2290.md5'
    'controllers'
  ]);
</code>```

Title: use createHash in angular-md5

Body:
When I wanna use the createHash function in angular, this error raises : md5.createHash is not a function

Here's my code :

MyCtrl.$inject = ['md5'];
function MyCtrl(md5) {
var vm = this;

vm.reg = reg;

function reg() {
    vm.avatar = md5.createHash('salam'); // This Line Has Error
    console.log(vm.avatar);
...

Note: I added the module dependency fine !

Body:
You need to add angular-md5 to your project module as well le below.

angular.module('YOUR_APP', [
    'angular-md5', // you may also use 'ngMd5' or 'gdi2290.md5'
    'controllers'
  ]);


问:
Detecting Android (not chrome) with javascript?
I've found plenty of answers on this.  The one I'm trying now is:

```<code> /(android)/i.test(navigator.userAgent)
</code>```

But in Chrome on Windows I get true.  I'm trying to detect when my user is on an Android device (to point them to the Play Store listing).  Is there any reliable way to achieve this?

答:
I just tried this answer, and the code worked for me: Detect Android phone via Javascript / jQuery

Here is their code:

```<code>var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
  // Do something!
  // Redirect to Android-site?
  window.location = 'http://android.davidwalsh.name';
}
</code>```

I also made a CodePen here where you can test it out.

I tested my CodePen on Chrome for Windows, Chrome for Mac, and Chrome for Android, and it worked correctly for all.

Body:
I've found plenty of answers on this.  The one I'm trying now is:

 /(android)/i.test(navigator.userAgent)

But in Chrome on Windows I get true.  I'm trying to detect when my user is on an Android device (to point them to the Play Store listing).  Is there any reliable way to achieve this?

Body:
I just tried this answer, and the code worked for me: Detect Android phone via Javascript / jQuery

Here is their code:

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
  // Do something!
  // Redirect to Android-site?
  window.location = 'http://android.davidwalsh.name';
}

I also made a CodePen here where you can test it out.

I tested my CodePen on Chrome for Windows, Chrome for Mac, and Chrome for Android, and it worked correctly for all.


问:
Trouble loading CFF embedded fonts in an external SWF at runtime
We have a large flash site which is translated into 11 languages. We have a font loading system whereby all the characters required to display the site in each language are embedded in external swfs (so 11 swfs).

A recent update to the site requires us to use the Text Layout Framework (TLF) for one area of text display, which of course only supports fonts embedded in the new CFF format. I've attempted to embed a second instance of the font using the tag embedAsCFF="true", and after loading in the font SWF I can see this font is correctly registered as it shows up in the array returned by Font.enumerateFonts.

The TextFlow instance I am using has the following properties set:

```<code>textFlow.fontLookup = FontLookup.EMBEDDED_CFF;
textFlow.renderingMode = RenderingMode.CFF;
textFlow.fontFamily = "HeadingFontCFF";
</code>```

However the text that is displayed is not finding the embedded font. It is displayed in the Times New Roman device font. I'm pretty sure I have the TLF set up correct, as when I put the [Embed] tag in the same class (i.e. embedding in same SWF) as my TLF code, the font is displayed correctly. So it seems to relate just to fonts loaded in external SWFs.

I think this problem is related to the one listed here: Example of using embedded fonts loaded at runtime Flex 4 runtime loaded modules, although this post refers to a Flex 4 build whereas ours is a pure Flash 10 build.

答:
Okay so after a lot of digging I found the answer. It turns out we were using a compiler argument

```<code>-managers flash.fonts.AFEFontManager
</code>```

which instructs the compiler to use the AFEFontManager when transcoding the fonts, rather than the default (BatikFontManager/AFEFontManager/JREFontManager). These font managers take font files and turn them into vector outlines to be rendered in Flash. There's more information here: About the font managers.

It seems that when this argument is included, all fonts are embedded using the old DefineFont3 method, rather than DefineFont4 (CFF), even if you use the tag embedAsCff="true".

An easy way to see which method was actually used to embed the font is by checking the fontType property of the fonts returned by Font.enumerateFonts(). If the value is "embedded" then DefineFont3 was used, if it's "embeddedCFF" then DefineFont4 was used.

Hope this helps someone out there!

ContentLicense: CC BY-SA 2.5

Body:
We have a large flash site which is translated into 11 languages. We have a font loading system whereby all the characters required to display the site in each language are embedded in external swfs (so 11 swfs).

A recent update to the site requires us to use the Text Layout Framework (TLF) for one area of text display, which of course only supports fonts embedded in the new CFF format. I've attempted to embed a second instance of the font using the tag embedAsCFF="true", and after loading in the font SWF I can see this font is correctly registered as it shows up in the array returned by Font.enumerateFonts.

The TextFlow instance I am using has the following properties set:

textFlow.fontLookup = FontLookup.EMBEDDED_CFF;
textFlow.renderingMode = RenderingMode.CFF;
textFlow.fontFamily = "HeadingFontCFF";

However the text that is displayed is not finding the embedded font. It is displayed in the Times New Roman device font. I'm pretty sure I have the TLF set up correct, as when I put the [Embed] tag in the same class (i.e. embedding in same SWF) as my TLF code, the font is displayed correctly. So it seems to relate just to fonts loaded in external SWFs.

I think this problem is related to the one listed here: Example of using embedded fonts loaded at runtime Flex 4 runtime loaded modules, although this post refers to a Flex 4 build whereas ours is a pure Flash 10 build.

Body:
Okay so after a lot of digging I found the answer. It turns out we were using a compiler argument

-managers flash.fonts.AFEFontManager

which instructs the compiler to use the AFEFontManager when transcoding the fonts, rather than the default (BatikFontManager/AFEFontManager/JREFontManager). These font managers take font files and turn them into vector outlines to be rendered in Flash. There's more information here: About the font managers.

It seems that when this argument is included, all fonts are embedded using the old DefineFont3 method, rather than DefineFont4 (CFF), even if you use the tag embedAsCff="true".

An easy way to see which method was actually used to embed the font is by checking the fontType property of the fonts returned by Font.enumerateFonts(). If the value is "embedded" then DefineFont3 was used, if it's "embeddedCFF" then DefineFont4 was used.

Hope this helps someone out there!


问:
Jekyll includes and YAML frontmatter
Is it possible to offload frontmatter to an include in some manner? My Jekyll site uses a frontmatter variable for the page title, however I have some pages that share an include due to code repetition. Putting the frontmatter for the page title in the include treats it like raw HTML. Is there a way to simulate this and set variables in an include?</p>

答:
You can pass a parameter to an include. Try:

```<code>{% include name.html var={{page.title}} %}
</code>```

Then in the include, access the parameter using include.var.

See "Pass Parameters to Includes" at https://jekyllrb.com/docs/includes/

Title: Jekyll includes and YAML frontmatter

Body:
You can pass a parameter to an include. Try:

{% include name.html var={{page.title}} %}

Then in the include, access the parameter using include.var.

See "Pass Parameters to Includes" at https://jekyllrb.com/docs/includes/


问:
Testing AngularUI Bootstrap modal instance controller
This is a somewhat of a follow-on question to this one: Mocking $modal in AngularJS unit tests

The referenced SO is an excellent question with very useful answer. The question I am left with after this however is this: how do I unit test the modal instance controller? In the referenced SO, the invoking controller is tested, but the modal instance controller is mocked. Arguably the latter should also be tested, but this has proven to be very tricky. Here's why:

I'll copy the same example from the referenced SO here:

```<code>.controller('ModalInstanceCtrl', function($scope, $modalInstance, items){
  $scope.items = items;
  $scope.selected = {
    item: $scope.items[0]
  };

  $scope.ok = function () {
    $modalInstance.close($scope.selected.item);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});
</code>```

So my first thought was that I would just instantiate the controller directly in a test, just like any other controller under test:

```<code>beforeEach(inject(function($rootScope) {
  scope = $rootScope.$new();
  ctrl = $controller('ModalInstanceCtrl', {$scope: scope});
});
</code>```

This does not work because in this context, angular does not have a provider to inject $modalInstance, since that is supplied by the UI modal.

Next, I turn to plan B: use $modal.open to instantiate the controller. This will run as expected:

```<code>beforeEach(inject(function($rootScope, $modal) {
  scope = $rootScope.$new();
  modalInstance = $modal.open({
    template: '<html></html>',
    controller: 'ModalInstanceCtrl',
    scope: scope
  });
});
</code>```

(Note, template can't be an empty string or it will fail cryptically.)

The problem now is that I have no visibility into the scope, which is the customary way to unit test resource gathering, etc. In my real code, the controller calls a resource service to populate a list of choices; my attempt to test this sets an expectGet to satisfy the service my controller is using, and I want to validate that the controller is putting the result in its scope. But the modal is creating a new scope for the modal instance controller (using the scope I pass in as a prototype), and I can't figure out how I can get a hole of that scope. The modalInstance object does not have a window into the controller.

Any suggestions on the "right" way to test this?

(N.B.: the behavior of creating a derivative scope for the modal instance controller is not unexpected – it is documented behavior. My question of how to test it is still valid regardless.)

答:
Follow below given steps:

Define stub for ModalInstance like give below

```<code>        uibModalInstanceStub = {
            close: sinon.stub(),
            dismiss: sinon.stub()
        };
</code>```

Pass the modal instance stub while creating controller

```<code>    function createController() {
        return $controller(
            ppcConfirmGapModalComponentFullName,
            {
                $scope: scopeStub,
                $uibModalInstance: uibModalInstanceStub
            });
    }
});
</code>```

Stub methods close(), dismiss() will get called as part of the tests

it('confirm modal - verify confirm action, on ok() call calls modalInstance close() function', function() {
                        action = 'Ok';
                        scopeStub.item = testItem;
                        createController();
                        scopeStub.ok();
});

Body:
This is a somewhat of a follow-on question to this one: Mocking $modal in AngularJS unit tests

The referenced SO is an excellent question with very useful answer. The question I am left with after this however is this: how do I unit test the modal instance controller? In the referenced SO, the invoking controller is tested, but the modal instance controller is mocked. Arguably the latter should also be tested, but this has proven to be very tricky. Here's why:

I'll copy the same example from the referenced SO here:

.controller('ModalInstanceCtrl', function($scope, $modalInstance, items){
  $scope.items = items;
  $scope.selected = {
    item: $scope.items[0]
  };

  $scope.ok = function () {
    $modalInstance.close($scope.selected.item);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

So my first thought was that I would just instantiate the controller directly in a test, just like any other controller under test:

beforeEach(inject(function($rootScope) {
  scope = $rootScope.$new();
  ctrl = $controller('ModalInstanceCtrl', {$scope: scope});
});

This does not work because in this context, angular does not have a provider to inject $modalInstance, since that is supplied by the UI modal.

Next, I turn to plan B: use $modal.open to instantiate the controller. This will run as expected:

beforeEach(inject(function($rootScope, $modal) {
  scope = $rootScope.$new();
  modalInstance = $modal.open({
    template: '',
    controller: 'ModalInstanceCtrl',
    scope: scope
  });
});

(Note, template can't be an empty string or it will fail cryptically.)

The problem now is that I have no visibility into the scope, which is the customary way to unit test resource gathering, etc. In my real code, the controller calls a resource service to populate a list of choices; my attempt to test this sets an expectGet to satisfy the service my controller is using, and I want to validate that the controller is putting the result in its scope. But the modal is creating a new scope for the modal instance controller (using the scope I pass in as a prototype), and I can't figure out how I can get a hole of that scope. The modalInstance object does not have a window into the controller.

Any suggestions on the "right" way to test this?

(N.B.: the behavior of creating a derivative scope for the modal instance controller is not unexpected – it is documented behavior. My question of how to test it is still valid regardless.)

Body:
Follow below given steps:

Define stub for ModalInstance like give below

        uibModalInstanceStub = {
            close: sinon.stub(),
            dismiss: sinon.stub()
        };

Pass the modal instance stub while creating controller

    function createController() {
        return $controller(
            ppcConfirmGapModalComponentFullName,
            {
                $scope: scopeStub,
                $uibModalInstance: uibModalInstanceStub
            });
    }
});

Stub methods close(), dismiss() will get called as part of the tests

it('confirm modal - verify confirm action, on ok() call calls modalInstance close() function', function() {
                        action = 'Ok';
                        scopeStub.item = testItem;
                        createController();
                        scopeStub.ok();
});


问:
Is there a way to easily make a specific directory slow for a unit test?
My goal is to run a test against a file system which is intentionally slow, to test performance metrics in chaotic storage scenarios.  In the same sense that there are ways to limit memory and cpu with cgroups in containers, i've considered wether or not there is a io limitation i can impose.

Is there a way to mount a simple file system to a directory which is intentionally slowed down ?

Alternatively, is there a way to make a docker container limit disk operation qoutas on a container, by issuing a command line operation (not that the command line operation part is important here - because if I run this on a docker container, it will be started inside of kubernetes for me).

答:
FUSE gives one path to this. I cloned the example at https://github.com/fntlnz/fuse-example.git and added a sleep() call to fuse-example.c in a strategic location:

```<code> 21   if (strcmp(path, filepath) == 0) {
 22     stbuf->st_mode = S_IFREG | 0777;
 23     stbuf->st_nlink = 1;
 24     stbuf->st_size = strlen(filecontent);
 25     sleep(1); // Right here
 26     return 0;
 27   }
</code>```

Then I mounted it up:

```<code>./bin/fuse-example -d -s -f /tmp/example
</code>```

And gave it a shot:

```<code>% cd /tmp/example
% time cat file
I'm the content of the only file available there
cat file  0.00s user 0.00s system 0% cpu 1.008 total
%
</code>```

While it takes a little coding, an advantage of this route is that you have full control over nearly all of the salient attributes and qualities of the file system.

Body:
FUSE gives one path to this. I cloned the example at https://github.com/fntlnz/fuse-example.git and added a sleep() call to fuse-example.c in a strategic location:

 21   if (strcmp(path, filepath) == 0) {
 22     stbuf->st_mode = S_IFREG | 0777;
 23     stbuf->st_nlink = 1;
 24     stbuf->st_size = strlen(filecontent);
 25     sleep(1); // Right here
 26     return 0;
 27   }

Then I mounted it up:

./bin/fuse-example -d -s -f /tmp/example

And gave it a shot:

% cd /tmp/example
% time cat file
I'm the content of the only file available there
cat file  0.00s user 0.00s system 0% cpu 1.008 total
%

While it takes a little coding, an advantage of this route is that you have full control over nearly all of the salient attributes and qualities of the file system.


问:
How to assign values from array to buttons in Swift
Hi I'm a beginner in Swift and I would like to know how I can make string values, stored in an array, the title of buttons.

Specific to my case: I have 24 buttons in my storyboard, all put into one action in the controller view. In my model I have an array with 24 emoji's and I would like to know how I can (randomly) assign these emoji's to my buttons.

```<code>var emoji : [String] = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]
</code>```

Thank you in advance.

答:
This solution leverages shuffled() and zip()

```<code>class MyViewController: UIViewController {

    // Add the face buttons to the collection in the storyboard
    @IBOutlet var faceButtons: [UIButton]!
    let faces = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]

    func randomizeFaces() {
        // zip() combines faceButtons and faces, shuffled() randomizes faces
        zip(faceButtons, faces.shuffled()).forEach { faceButtton, face in
            faceButtton.setTitle(face, for: .normal)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        randomizeFaces()
    }

}
</code>```

Here is the definition of shuffled() from: How do I shuffle an array in Swift?

```<code>extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Iterator.Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}
</code>```

Body:
Hi I'm a beginner in Swift and I would like to know how I can make string values, stored in an array, the title of buttons.

Specific to my case: I have 24 buttons in my storyboard, all put into one action in the controller view. In my model I have an array with 24 emoji's and I would like to know how I can (randomly) assign these emoji's to my buttons.

var emoji : [String] = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]

Thank you in advance.

Body:
This solution leverages shuffled() and zip()

class MyViewController: UIViewController {

    // Add the face buttons to the collection in the storyboard
    @IBOutlet var faceButtons: [UIButton]!
    let faces = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]

    func randomizeFaces() {
        // zip() combines faceButtons and faces, shuffled() randomizes faces
        zip(faceButtons, faces.shuffled()).forEach { faceButtton, face in
            faceButtton.setTitle(face, for: .normal)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        randomizeFaces()
    }

}

Here is the definition of shuffled() from: How do I shuffle an array in Swift?

extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Iterator.Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}


问:
SQL JOIN COUNT then using that count value in where clause
I'm trying to select if a user rating (user.rating) is greater then 6 or if the user has more then 100 transactions (transaction table count). Basically count how many transactions the user has then where (transaction count >= 100 OR user rating >= 6).</p>

```<code>SELECT *
FROM   `user`
JOIN   (SELECT COUNT(*)
        FROM   transaction
        WHERE  transaction.user_id=user.id
        AND type='L'
        AND status='S') AS tcount
WHERE  (user.rating >= '6' OR tcount >= '100')
</code>```

答:
Just another possible answer. I've created simplified schemas to test it, please try it and let me know the result.</p>

```<code>SELECT *
FROM user
WHERE user.rating >= 6 OR (SELECT COUNT(*) FROM transaction WHERE user_id = user.id and type = 'L' and status = 'S') >= 100;
</code>```

Body:
I'm trying to select if a user rating (user.rating) is greater then 6 or if the user has more then 100 transactions (transaction table count). Basically count how many transactions the user has then where (transaction count >= 100 OR user rating >= 6).

SELECT *
FROM   `user`
JOIN   (SELECT COUNT(*)
        FROM   transaction
        WHERE  transaction.user_id=user.id
        AND type='L'
        AND status='S') AS tcount
WHERE  (user.rating >= '6' OR tcount >= '100')

Body:
Just another possible answer. I've created simplified schemas to test it, please try it and let me know the result.

SELECT *
FROM user
WHERE user.rating >= 6 OR (SELECT COUNT(*) FROM transaction WHERE user_id = user.id and type = 'L' and status = 'S') >= 100;


问:
VB.NET Limit to Tab Ordering?
I have inherited a frankenstein VB6 "Converted" to VB.NET winform application. This application has a metric ton of fields in it, the users rightfully complained that the tab order is off (after a certain point it starts jumping all over the form).

Figuring something in tab order was off, I went in and turned on View > Tab Order and it looked good.

To be sure I went through the form again fresh and when I'm in tab order view all is well, but when the app runs it still starts jumping around the same area as before?! Has anyone else encountered this and how did you resolve if you did?

[Edit]: These input forms are all on separate tabs within a tab control, which probably muddies the situation even more.

答:
Are there any strange Focus calls in the code that are overriding the tab order and setting the focus of the application manually?

I've had problems in the past with tab ordering getting itself all confused and I've usually just resorted to going through the application from scratch and setting the order myself manually. I realise that this may well not be what you are looking for but I don't know of anything else

Title: VB.NET Limit to Tab Ordering?


问:
Jmeter video call scenario
I need to achieve the below scenario using jmeter how can i do it please help

Login in to site with general user and schedule a appointment with doctor.

Login with doctor and accept appointment and video call the user at that time.

The user need to lift the video call and keep the session open for one min

Logout both the sessions.

please help how to achieve the above.

答:
Use the WebDriver sampler as a core element and build your scenario with it.
Here's the basic tutorial.</p>

Title: Jmeter video call scenario


问:
Tensorflow: Using neural network to classify positive or negative phrases
I am following through the tutorial here:
https://pythonprogramming.net/train-test-tensorflow-deep-learning-tutorial/

I can get the Neural Network trained and print out the accuracy.

However, I do not know how to use the Neural Network to make a prediction.

Here is my attempt.  Specifically the issue is this line - I believe my issue is that I cannot get my input string into the format the model expects:

```<code>features = get_features_for_input("This was the best store i've ever seen.")
result = (sess.run(tf.argmax(prediction.eval(feed_dict={x:features}),1)))
</code>```

Here is a larger listing:

```<code>def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            i = 0
            while i < len(train_x):
                start = i
                end = i + batch_size

                batch_x = np.array(train_x[start:end])
                batch_y = np.array(train_y[start:end])

                _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})

                epoch_loss += c
                i+=batch_size

            print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:', epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct,'float'))
        print('Accuracy', accuracy.eval({x:test_x, y:test_y}))

        # pos: [1,0] , argmax: 0
        # neg: [0,1] , argmax: 1
        features = get_features_for_input("This was the best store i've ever seen.")
        result = (sess.run(tf.argmax(prediction.eval(feed_dict={x:features}),1)))
        if result[0] == 0:
            print('Positive:',input_data)
        elif result[0] == 1:
            print('Negative:',input_data)

def get_features_for_input(input):
    current_words = word_tokenize(input.lower())
    current_words = [lemmatizer.lemmatize(i) for i in current_words]
    features = np.zeros(len(lexicon))

    for word in current_words:
        if word.lower() in lexicon:
            index_value = lexicon.index(word.lower())
            # OR DO +=1, test both
            features[index_value] += 1

    features = np.array(list(features))

train_neural_network(x)
</code>```

答:
Following your comment above, it feels like your error ValueError: Cannot feed value of shape () is due to the fact that features is None, because your function get_features_for_input doesn't return anything.

I added the return features line and gave features a correct shape of [1, len(lexicon)] to match the shape of the placeholder.

```<code>def get_features_for_input(input):
    current_words = word_tokenize(input.lower())
    current_words = [lemmatizer.lemmatize(i) for i in current_words]
    features = np.zeros((1, len(lexicon)))

    for word in current_words:
        if word.lower() in lexicon:
            index_value = lexicon.index(word.lower())
            # OR DO +=1, test both
            features[0, index_value] += 1

    return features
</code>```

Body:
I am following through the tutorial here:
https://pythonprogramming.net/train-test-tensorflow-deep-learning-tutorial/

I can get the Neural Network trained and print out the accuracy.

However, I do not know how to use the Neural Network to make a prediction.

Here is my attempt.  Specifically the issue is this line - I believe my issue is that I cannot get my input string into the format the model expects:

features = get_features_for_input("This was the best store i've ever seen.")
result = (sess.run(tf.argmax(prediction.eval(feed_dict={x:features}),1)))

Here is a larger listing:

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            i = 0
            while i < len(train_x):
                start = i
                end = i + batch_size

                batch_x = np.array(train_x[start:end])
                batch_y = np.array(train_y[start:end])

                _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})

                epoch_loss += c
                i+=batch_size

            print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:', epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct,'float'))
        print('Accuracy', accuracy.eval({x:test_x, y:test_y}))

        # pos: [1,0] , argmax: 0
        # neg: [0,1] , argmax: 1
        features = get_features_for_input("This was the best store i've ever seen.")
        result = (sess.run(tf.argmax(prediction.eval(feed_dict={x:features}),1)))
        if result[0] == 0:
            print('Positive:',input_data)
        elif result[0] == 1:
            print('Negative:',input_data)

def get_features_for_input(input):
    current_words = word_tokenize(input.lower())
    current_words = [lemmatizer.lemmatize(i) for i in current_words]
    features = np.zeros(len(lexicon))

    for word in current_words:
        if word.lower() in lexicon:
            index_value = lexicon.index(word.lower())
            # OR DO +=1, test both
            features[index_value] += 1

    features = np.array(list(features))

train_neural_network(x)

Body:
Following your comment above, it feels like your error ValueError: Cannot feed value of shape () is due to the fact that features is None, because your function get_features_for_input doesn't return anything.

I added the return features line and gave features a correct shape of [1, len(lexicon)] to match the shape of the placeholder.

def get_features_for_input(input):
    current_words = word_tokenize(input.lower())
    current_words = [lemmatizer.lemmatize(i) for i in current_words]
    features = np.zeros((1, len(lexicon)))

    for word in current_words:
        if word.lower() in lexicon:
            index_value = lexicon.index(word.lower())
            # OR DO +=1, test both
            features[0, index_value] += 1

    return features


问:
MVC Ajax prevent redirect to action controller
In my view I have a modal window, it have the next form...

```<code>@using (Html.BeginForm("controllerAction", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="container" id="editRecordForm">
        <div class="row">
            <div class="col-md-6">
                @Html.LabelFor(model => model.Author)
                @Html.TextBoxFor(model => model.Author, new { @class = "form-control", @style = "height:auto" })
                @Html.ValidationMessageFor(model => model.Author)
            </div>
        </div>
        <br/>
        <div class="row">
            <div class="col-md-6">
                @Html.LabelFor(model => model.Image)
                <input type="file" name="file" accept="image/*">
            </div>
        </div>
        <br />
        <input type="submit" value="Submit" class="btn btn-primary">
    </div>
}
</code>```

this is the JS that contains the ajax request

```<code><script>
    var formdata = new FormData($('form').get(0));
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                cache: false,
                data: formdata,
                success: function (status, data) {
                    console.log(data);
                }
            });
        }
        return false;
    });
</script>
</code>```

The action controller receives two parameters the model and file

```<code>[HttpPost]
public async Task<JsonResult> controllerAction(HttpPostedFileBase file, Model model)
{
  var json = new
  {
      Success = true,
      StatusCode = "200",
      ErrorDesc = "OK",
      ErrorCode = "",
      NewId = ""
  };

  //some process

  return Json(json, JsonRequestBehavior.AllowGet);
}
</code>```

The problem is why when the controller action finish, it redirects to the action controller url

```<code>http://controller/action
</code>```

and it does not stay on the same page?

What Im doing wrong?

答:
You are not preventing the default action of the form.</p>

```<code>$('form').submit(function (e) {
    e.preventDefault();
    if ($(this).valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            cache: false,
            data: formdata,
            success: function (status, data) {
                console.log(data);
            }
        });
    }
    return false;
});
</code>```

Body:
In my view I have a modal window, it have the next form...

@using (Html.BeginForm("controllerAction", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

                @Html.LabelFor(model => model.Author)
                @Html.TextBoxFor(model => model.Author, new { @class = "form-control", @style = "height:auto" })
                @Html.ValidationMessageFor(model => model.Author)

                @Html.LabelFor(model => model.Image)
                <input type="file" name="file" accept="image/*">

        <input type="submit" value="Submit" class="btn btn-primary">

}

this is the JS that contains the ajax request

The action controller receives two parameters the model and file

[HttpPost]
public async Task<JsonResult> controllerAction(HttpPostedFileBase file, Model model)
{
  var json = new
  {
      Success = true,
      StatusCode = "200",
      ErrorDesc = "OK",
      ErrorCode = "",
      NewId = ""
  };

  //some process

  return Json(json, JsonRequestBehavior.AllowGet);
}

The problem is why when the controller action finish, it redirects to the action controller url

http://controller/action

and it does not stay on the same page?

What Im doing wrong?

Body:
You are not preventing the default action of the form.

$('form').submit(function (e) {
    e.preventDefault();
    if ($(this).valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            cache: false,
            data: formdata,
            success: function (status, data) {
                console.log(data);
            }
        });
    }
    return false;
});


问:
Triggering Branch Indexing on Multibranch Pipelines (Jenkins/Git)
I'm trying to automatically trigger 'Branch Indexing' on a Multibranch Pipelines job in Jenkins.

At the moment, only one method seems to actually work, which is polling, but I am unable to do that and polling is a bad solution anyway.

The plug-in doesn't support 'Trigger builds remotely (e.g., from scripts)' (options are not saved), so I cannot trigger it via a web hook on push etc.

I tried creating a 'trigger' freestyle build on the repo but the 'Post-build Actions - Build other projects' claims the Multibranch Pipeline project is not a buildable project.

If polling is the only way I can do this, then I need to disable automatic SCM triggering (otherwise we get duplicate builds when we re-index) because I'll need to enable web hook triggering on the branch projects.

But that doesn't work, because I'm setting up the web hook via a pipeline script in the branch project, and you need to have built it at least once to have that property registered.

I've been going around in circles for a while, so hopefully I've just missed something obvious, but any help would be appreciated.

I imagined being able to do one of the following

Somehow trigger the multi-branch project as a downstream project

Poll the multibranch project, and only build branch projects which have not been built before

Cheers

答:
The method ComputedFolder.scheduleBuild() can be invoked from a groovy script.

I have just triggered branch indexing in one multibranch pipeline project from the groovy code in a different multibranch pipeline project, which is then triggering a downstream build in that project.

The code is something like:

@NonCPS
void scanRepo(String downStreamProjectName) {
    Jenkins.instance.getItemByFullName(downStreamProjectName).scheduleBuild()
}
...
String downStreamProject = 'my-folder/my-multibranch-project'
String downStreamJob = "${downStreamProject}/${env.BRANCH_NAME}"
if (Jenkins.instance.getItemByFullName(downStreamJob) == null) {
    scanRepo(downStreamProject)
    while (Jenkins.instance.getItemByFullName(downStreamJob) == null) {
        sleep(1)
    }
}
build([job: downStreamJob, wait: false, quietPeriod: 0])
```

Notice that Jenkins.instance.getItemByFullName(downStreamProjectName) is the WorkflowMultiBranchProject which is not Serializable, so some care needs to be taken.

Body:
The method ComputedFolder.scheduleBuild() can be invoked from a groovy script.

I have just triggered branch indexing in one multibranch pipeline project from the groovy code in a different multibranch pipeline project, which is then triggering a downstream build in that project.

The code is something like:

@NonCPS
void scanRepo(String downStreamProjectName) {
    Jenkins.instance.getItemByFullName(downStreamProjectName).scheduleBuild()
}
...
String downStreamProject = 'my-folder/my-multibranch-project'
String downStreamJob = "${downStreamProject}/${env.BRANCH_NAME}"
if (Jenkins.instance.getItemByFullName(downStreamJob) == null) {
    scanRepo(downStreamProject)
    while (Jenkins.instance.getItemByFullName(downStreamJob) == null) {
        sleep(1)
    }
}
build([job: downStreamJob, wait: false, quietPeriod: 0])

Notice that Jenkins.instance.getItemByFullName(downStreamProjectName) is the WorkflowMultiBranchProject which is not Serializable, so some care needs to be taken.


问:
Sorting directory filenames with Perl
I want to sort/print the files in a directory by name.  My code lists them all, but the sorting is skewed.  Here is my code and results.  Any suggestions will be most welcomed!

```<code>my $file;
opendir (DIR, "$dir");
while ($file = readdir(DIR)) {
    push (my @files, $file);
    @files = sort {$a cmp $b} @files;   #NOT sorting!
    foreach $file (@files) {
        print "$file\n";
    }
}
</code>```

And here are the "sorted" results:

```<code>Screenshot-Chess_-_Human_versus_GNUchess.png
test.html
katyperry.gif
test.cgi
Californication.S04E05.HDTV.XviD-ASAP.avi
FreeWatch_13.exe
proxy.jpg
test.pl-
.
attachment2.jpg
attachment.jpg
Californication.S04E06.HDTV.XviD-LOL.avi
Californication.S04E07.HDTV.XviD-LOL.avi
boxter.jpg
..
</code>```

答:
I don't understand why you guys are doing this so complicatedly. This works perfectly for sorting files or folders. </p>

```<code>opendir (my $DIR, "$dir") || die "Error while opening $dir: $!\n";

foreach my $dirFileName(sort readdir $DIR)
{
      next if $dirFileName eq '.' or $dirFileName eq '..';
      print("fileName: $dirFileName ... \n");
}
</code>```

Title: Sorting directory filenames with Perl

Body:
I want to sort/print the files in a directory by name.  My code lists them all, but the sorting is skewed.  Here is my code and results.  Any suggestions will be most welcomed!

my $file;
opendir (DIR, "$dir");
while ($file = readdir(DIR)) {
    push (my @files, $file);
    @files = sort {$a cmp $b} @files;   #NOT sorting!
    foreach $file (@files) {
        print "$file\n";
    }
}

And here are the "sorted" results:

Screenshot-Chess_-_Human_versus_GNUchess.png
test.html
katyperry.gif
test.cgi
Californication.S04E05.HDTV.XviD-ASAP.avi
FreeWatch_13.exe
proxy.jpg
test.pl-
.
attachment2.jpg
attachment.jpg
Californication.S04E06.HDTV.XviD-LOL.avi
Californication.S04E07.HDTV.XviD-LOL.avi
boxter.jpg
..

Body:
I don't understand why you guys are doing this so complicatedly. This works perfectly for sorting files or folders.

opendir (my $DIR, "$dir") || die "Error while opening $dir: $!\n";

foreach my $dirFileName(sort readdir $DIR)
{
      next if $dirFileName eq '.' or $dirFileName eq '..';
      print("fileName: $dirFileName ... \n");
}


问:
apache camel for jira
I want to build an Apache camel application to download a Jira
issue report, parse it, and store it into a .csv file.
I'm new at Apache camel, I do believe the jira here should be an endpoint, how to setup this configuration, I want to set is as from:("Jira") to (csv file).
I believe it could be something like this:

```<code>public void configure() throws Exception {

from("jira://pullRequestComment?ProjectKey=CAMEL-0000&IssueTypeId=1&IssueSummary=title")
.process(new MyLogProcessor())
.bean(new MyTransformer(),"transformContent")
.to("file:D:/camel/output");
}
</code>```

I tried the above code, I got an exception for java conversion type.

Exception:

答:
The pullRequestComment endpoint is for a producer endpoint (i.e. it can only go in to("jira:pullRequestComment?..."). Since you want to poll for new comments, you should use the newComment endpoint. So your route would look something like:

```<code>from("jira:newComment?serverUrl={host}&username={username}password={password}")
  .process(new MyLogProcessor())
  .bean(new MyTransformer(),"transformContent")
  .to("file:D:/camel/output");
</code>```

Note that this endpoint returns an object of type com.atlassian.jira.rest.client.domain.Comment, so in MyLogProcessor if you do exchange.getIn().getBody(), it will return an object of type Comment (or maybe a List if there are multiple objects, you'll have to test this).

If you want to post a pull request comment, then you can use the pullRequestComment endpoint like the following:

```<code>from("direct://some/uri/name")
  .header("ProjectKey", "CAMEL-0000")
  .header("IssueTypeId", 1L)
  .header("IssueSummary", "title")
  .to("jira:pullRequestComment?serverUrl={host}&username={username}password={password}")
  .... // More processing here
</code>```

Then if you invoke the route from("direct://some/uri/name"), it should post the comment that's in the exchange body.

Title: apache camel for jira

Body:
I want to build an Apache camel application to download a Jira
issue report, parse it, and store it into a .csv file.
I'm new at Apache camel, I do believe the jira here should be an endpoint, how to setup this configuration, I want to set is as from:("Jira") to (csv file).
I believe it could be something like this:

public void configure() throws Exception {

from("jira://pullRequestComment?ProjectKey=CAMEL-0000&IssueTypeId=1&IssueSummary=title")
.process(new MyLogProcessor())
.bean(new MyTransformer(),"transformContent")
.to("file:D:/camel/output");
}

I tried the above code, I got an exception for java conversion type.

Exception:

Body:
The pullRequestComment endpoint is for a producer endpoint (i.e. it can only go in to("jira:pullRequestComment?..."). Since you want to poll for new comments, you should use the newComment endpoint. So your route would look something like:

from("jira:newComment?serverUrl={host}&username={username}password={password}")
  .process(new MyLogProcessor())
  .bean(new MyTransformer(),"transformContent")
  .to("file:D:/camel/output");

Note that this endpoint returns an object of type com.atlassian.jira.rest.client.domain.Comment, so in MyLogProcessor if you do exchange.getIn().getBody(), it will return an object of type Comment (or maybe a List if there are multiple objects, you'll have to test this).

If you want to post a pull request comment, then you can use the pullRequestComment endpoint like the following:

from("direct://some/uri/name")
  .header("ProjectKey", "CAMEL-0000")
  .header("IssueTypeId", 1L)
  .header("IssueSummary", "title")
  .to("jira:pullRequestComment?serverUrl={host}&username={username}password={password}")
  .... // More processing here

Then if you invoke the route from("direct://some/uri/name"), it should post the comment that's in the exchange body.


问:
Idiomatic way of requiring HTTP Basic Auth in Go?
Situation:

I'm building a REST API using Gorilla's mux as the router.

I'm wondering how I can protect specific routes with simple HTTP Basic Auth. I don't have a need to read the credentials from a file or any external source, I really just want to protect selected routes by a hard coded HTTP Basic Auth username and password.

Question:

What is the idiomatic way of doing so in Go? Does Gorilla offer anything to make it more easy? If you could provide a few lines of code, that would be just wonderful.

答:
I realize I'm late to the party here. I just happened to be revisiting HTTP Basic Authentication. After going through all the answers here I actually settled on a variation of Timmmm's solution. I even took it the step farther and added the hashing as per his suggestion to improve security. Figured I might as well share my variation of the code.</p>

```<code>userhash := hasher("admin")
passhash := hasher("$CrazyUnforgettablePassword?")
realm := "Please enter username and password"

http.HandleFunc("/", authHandler(indexHandler, userhash, passhash, realm))

// Above code should obviously be in main() along with the http listener, etc.

// hasher uses package "crypto/sha256"
func hasher(s string) []byte {
    val := sha256.Sum256([]byte(s))
    return val[:]
}

func authHandler(handler http.HandlerFunc, userhash, passhash []byte, realm string) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        user, pass, ok := r.BasicAuth()
        if !ok || subtle.ConstantTimeCompare(hasher(user),
            userhash) != 1 || subtle.ConstantTimeCompare(hasher(pass), passhash) != 1 {
            w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
            http.Error(w, "Unauthorized.", http.StatusUnauthorized)
            return
        }
        handler(w, r)
    }
}
</code>```

Body:
I realize I'm late to the party here. I just happened to be revisiting HTTP Basic Authentication. After going through all the answers here I actually settled on a variation of Timmmm's solution. I even took it the step farther and added the hashing as per his suggestion to improve security. Figured I might as well share my variation of the code.

userhash := hasher("admin")
passhash := hasher("$CrazyUnforgettablePassword?")
realm := "Please enter username and password"

http.HandleFunc("/", authHandler(indexHandler, userhash, passhash, realm))

// Above code should obviously be in main() along with the http listener, etc.

// hasher uses package "crypto/sha256"
func hasher(s string) []byte {
    val := sha256.Sum256([]byte(s))
    return val[:]
}

func authHandler(handler http.HandlerFunc, userhash, passhash []byte, realm string) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        user, pass, ok := r.BasicAuth()
        if !ok || subtle.ConstantTimeCompare(hasher(user),
            userhash) != 1 || subtle.ConstantTimeCompare(hasher(pass), passhash) != 1 {
            w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
            http.Error(w, "Unauthorized.", http.StatusUnauthorized)
            return
        }
        handler(w, r)
    }
}


问:
AVPlayer Fairplay HLS won't stop audio playback when video is paused
I am using Fairplay implementation as per Apple's Fairplay Streaming sample code at https://developer.apple.com/streaming/fps/, although I tried to choose only parts that are related to Online Fairplay Streaming, not the persistence/offline playback. In the below code a video without Fairplay plays/pauses/seeks normally, but when I play a Fairplay protected video, only the video track behaves correctly.

Pausing playback won't stop the audio playback, changing audio track won't stop the previous audio track, so both plays together and perhaps the seek also does not work.

Besides this helper class below, I have AssetLoaderDelegate and AssetPlaybackManager from Apple's client sample code of FairPlay Streaming Server SDK https://developer.apple.com/streaming/fps/ and I have updated the code to handle SPC/CKC for our DRM keys provider.

Did I miss to implement some important part of the code to handle audio for FPS Streaming? Can you please point me into right direction? Many thanks.

```<code>class PlayHelper {

    static let shared = PlayHelper()

    fileprivate var playerViewController: PlayerViewController?

    init() {

        AssetPlaybackManager.sharedManager.delegate = self
    }

    // Play video without DRM
    func playVideo(from urlString: String, at context: UIViewController) {

        guard let videoURL = URL(string: urlString) else {
            Log.error("Video URL can't be created from string: \(urlString)")
            return }

        let player = AVPlayer(url: videoURL)

        let playerViewController = PlayerViewController()
        playerViewController.player = player

        context.present(playerViewController, animated: true) {
            playerViewController.player?.play()
        }
    }

    // Play FPS video
    func playFpsVideo(with asset: AVURLAsset, at context: UIViewController) {

        // Cleanup, should be done when playerViewController is actually dismissed
        if self.playerViewController != nil {
            // The view reappeared as a results of dismissing an AVPlayerViewController.
            // Perform cleanup.
            AssetPlaybackManager.sharedManager.setAssetForPlayback(nil)
            self.playerViewController?.player = nil
            self.playerViewController = nil
        }

        let item = AVPlayerItem(asset: asset)

        let player = AVPlayer(playerItem: item)

        // Customize player
        player.appliesMediaSelectionCriteriaAutomatically = true

        let playerViewController = PlayerViewController()
        playerViewController.player = player

        self.playerViewController = playerViewController

        context.present(playerViewController, animated: true) {
            playerViewController.player?.play()
        }
    }

    // Stop video
    func stop() {

        // Cleanup, should be done when playerViewController is dismissed
        if self.playerViewController != nil {

            // Results of dismissing an AVPlayerViewController, perform cleanup
            AssetPlaybackManager.sharedManager.setAssetForPlayback(nil)
            self.playerViewController?.player = nil
            self.playerViewController = nil
        }
    }
}

// MARK: - Extend `PlayHelper` to conform to the `AssetPlaybackDelegate` protocol

extension PlayHelper: AssetPlaybackDelegate {

    func streamPlaybackManager(_ streamPlaybackManager: AssetPlaybackManager, playerReadyToPlay player: AVPlayer) {

        player.play()
    }

    func streamPlaybackManager(_ streamPlaybackManager: AssetPlaybackManager, playerCurrentItemDidChange player: AVPlayer) {

        guard let playerViewController = playerViewController, player.currentItem != nil else { return }

        playerViewController.player = player
    }
}
</code>```

I can also provide the code in AssetLoaderDelegate and AssetPlaybackManager if needed.

答: My bad. I called play() twice in the code above... Grrr.. Once when the presentation of the PlayerViewController finished and second time in the callback from AssetPlaybackDelegate that is triggered by KVO in AssetPlaybackManager. This way the player controls stopped playing the video, but most probably a second (audio) stream was still playing there. I removed the play() in playerReadyToPlay callback and now all the controls in the Player works as expected. I can pause, resume, seek, change audio tracks.

Body:
I am using Fairplay implementation as per Apple's Fairplay Streaming sample code at https://developer.apple.com/streaming/fps/, although I tried to choose only parts that are related to Online Fairplay Streaming, not the persistence/offline playback. In the below code a video without Fairplay plays/pauses/seeks normally, but when I play a Fairplay protected video, only the video track behaves correctly.

Pausing playback won't stop the audio playback, changing audio track won't stop the previous audio track, so both plays together and perhaps the seek also does not work.

Besides this helper class below, I have AssetLoaderDelegate and AssetPlaybackManager from Apple's client sample code of FairPlay Streaming Server SDK https://developer.apple.com/streaming/fps/ and I have updated the code to handle SPC/CKC for our DRM keys provider.

Did I miss to implement some important part of the code to handle audio for FPS Streaming? Can you please point me into right direction? Many thanks.

class PlayHelper {

    static let shared = PlayHelper()

    fileprivate var playerViewController: PlayerViewController?

    init() {

        AssetPlaybackManager.sharedManager.delegate = self
    }

    // Play video without DRM
    func playVideo(from urlString: String, at context: UIViewController) {

        guard let videoURL = URL(string: urlString) else {
            Log.error("Video URL can't be created from string: \(urlString)")
            return }

        let player = AVPlayer(url: videoURL)

        let playerViewController = PlayerViewController()
        playerViewController.player = player

        context.present(playerViewController, animated: true) {
            playerViewController.player?.play()
        }
    }

    // Play FPS video
    func playFpsVideo(with asset: AVURLAsset, at context: UIViewController) {

        // Cleanup, should be done when playerViewController is actually dismissed
        if self.playerViewController != nil {
            // The view reappeared as a results of dismissing an AVPlayerViewController.
            // Perform cleanup.
            AssetPlaybackManager.sharedManager.setAssetForPlayback(nil)
            self.playerViewController?.player = nil
            self.playerViewController = nil
        }

        let item = AVPlayerItem(asset: asset)

        let player = AVPlayer(playerItem: item)

        // Customize player
        player.appliesMediaSelectionCriteriaAutomatically = true

        let playerViewController = PlayerViewController()
        playerViewController.player = player

        self.playerViewController = playerViewController

        context.present(playerViewController, animated: true) {
            playerViewController.player?.play()
        }
    }

    // Stop video
    func stop() {

        // Cleanup, should be done when playerViewController is dismissed
        if self.playerViewController != nil {

            // Results of dismissing an AVPlayerViewController, perform cleanup
            AssetPlaybackManager.sharedManager.setAssetForPlayback(nil)
            self.playerViewController?.player = nil
            self.playerViewController = nil
        }
    }
}

// MARK: - Extend `PlayHelper` to conform to the `AssetPlaybackDelegate` protocol

extension PlayHelper: AssetPlaybackDelegate {

    func streamPlaybackManager(_ streamPlaybackManager: AssetPlaybackManager, playerReadyToPlay player: AVPlayer) {

        player.play()
    }

    func streamPlaybackManager(_ streamPlaybackManager: AssetPlaybackManager, playerCurrentItemDidChange player: AVPlayer) {

        guard let playerViewController = playerViewController, player.currentItem != nil else { return }

        playerViewController.player = player
    }
}

I can also provide the code in AssetLoaderDelegate and AssetPlaybackManager if needed.


问:
What does "cd -P" / "pwd -P" code do that "$(basename -- "$BASH_SOURCE")" does not?
I am reading a environment variable setup shell program for spark. I don't quite understand this part.

Codes are shown below:

```<code># resolve links - $0 may be a softlink
this="${BASH_SOURCE:-$0}"
common_bin="$(cd -P -- "$(dirname -- "$this")" && pwd -P)"
script="$(basename -- "$this")"
this="$common_bin/$script"

# convert relative path to absolute path
config_bin="`dirname "$this"`"
script="`basename "$this"`"
config_bin="`cd "$config_bin"; pwd`"
this="$config_bin/$script"

export SPARK_PREFIX="`dirname "$this"`"/..
export SPARK_HOME="${SPARK_PREFIX}"
export SPARK_CONF_DIR="${SPARK_CONF_DIR:-"$SPARK_HOME/conf"}"
# Add the PySpark classes to the PYTHONPATH:
export PYTHONPATH="$SPARK_HOME/python:$PYTHONPATH"
export PYTHONPATH="$SPARK_HOME/python/lib/py4j-0.9-src.zip:$PYTHONPATH"
</code>```

In the first part it is said by comment that the part is to resolve the links, and in the second part, it is said to convert relative path to absolute path.

But I don't see any difference between these 2 "this": this="$common_bin/$script" and this="$config_bin/$script". I think first 4 lines already resolve link and give variable "this" an absolute path, why the shell does the same thing again in the second part(commands after the second comment)?

Thanks in advance.

答:
config_bin trusts the script's view of its source location to be correct. This is allowed to be a logical location.

common_bin goes to substantial lengths to get a physical location (not including any symlinks).

Let's say that this script is /opt/foobar-1.23/bin/something.

If you have a symlink to foobar-1.23 at /opt/foobar, and ran your script as /opt/foobar/bin/something, then config_bin will contain /opt/foobar-1.23/bin. By contrast, common_bin will include /opt/foobar/bin.

Thus, you would want to use "$config_bin" when you want to write a path that refers specifically to the version of the software currently in use at the time when the above script is running; whereas you'd want to use "$common_bin" when you want to write a path that will always refer to the version of the software that's then pointed to by the symlink, even if that version is different from the one that was running at the time when the variable was evaluated.

Body:
I am reading a environment variable setup shell program for spark. I don't quite understand this part.

Codes are shown below:

# resolve links - $0 may be a softlink
this="${BASH_SOURCE:-$0}"
common_bin="$(cd -P -- "$(dirname -- "$this")" && pwd -P)"
script="$(basename -- "$this")"
this="$common_bin/$script"

# convert relative path to absolute path
config_bin="`dirname "$this"`"
script="`basename "$this"`"
config_bin="`cd "$config_bin"; pwd`"
this="$config_bin/$script"

export SPARK_PREFIX="`dirname "$this"`"/..
export SPARK_HOME="${SPARK_PREFIX}"
export SPARK_CONF_DIR="${SPARK_CONF_DIR:-"$SPARK_HOME/conf"}"
# Add the PySpark classes to the PYTHONPATH:
export PYTHONPATH="$SPARK_HOME/python:$PYTHONPATH"
export PYTHONPATH="$SPARK_HOME/python/lib/py4j-0.9-src.zip:$PYTHONPATH"

In the first part it is said by comment that the part is to resolve the links, and in the second part, it is said to convert relative path to absolute path.

But I don't see any difference between these 2 "this": this="$common_bin/$script" and this="$config_bin/$script". I think first 4 lines already resolve link and give variable "this" an absolute path, why the shell does the same thing again in the second part(commands after the second comment)?

Thanks in advance.