问:
R Shiny - Inserting dynamic UI inside a Shiny module
The app below contains a module that inserts a UI object each time the Add button is clicked. The UI object consists of two inputs:

Input 1 is a selectInput with choices A and B.

Input 2 is a textInput if the user chooses A and a
numericInput if they choose B.

However, when I click Add, the inserted UI only contains Input 1 (the selectInput) - Input 2 is not rendered, as shown below:

Whereas the desired output looks like this:

I'm not sure if this is a namespacing issue or if there is a problem in the scoping of the module. Printing the IDs to the console checks out:

The app is as follows:

```<code>library(shiny)

# module UI function
modUI <- function(id){

  ns <- NS(id)

  tagList(
    actionButton(ns('add'), 'Add'),
    div(id = ns('placeholder'))
  )
}

# module server function
modServer <- function(input, output, session) {

  ns = session$ns

  ctn <- reactiveVal(0)

  Id <- reactive({
    function(id){
      ns(paste0(id, ctn()))
    }
  })

  observeEvent(input$add, {

    ctn(ctn() + 1)

    insertUI(
      selector = paste0('#', ns('placeholder')),
      ui = div(
        id = Id()('div'),
        selectInput(Id()('letter'), 'Letter:', LETTERS[1:2]),
        uiOutput(Id()('input'))
      )
    )
  })

  observeEvent(ctn(), {

    id <- Id()('input')
    selection <- Id()('letter')
    print(list(id = id, selection = selection))

    req(input[[selection]])

    output[[id]] <- renderUI({

      req(input[[selection]])

      switch(
        input[[selection]],
        'A' = textInput(Id()('text'), 'ENTER TEXT', ''),
        'B' = numericInput(Id()('numeric'), 'ENTER NUMBER', '')
      )
    })

  }, ignoreInit = TRUE)
}

# main ui
ui <- fluidPage(
  modUI('mod1')
)

# main server
server <- function(input, output, session) {
  callModule(modServer, "mod1")
}

# run app
shinyApp(ui, server)
</code>```

I tried splitting the module up into an inner and outer module. The inner mod creates Input 1 and Input 2 and the outer mod inserts them into the main app using insertUI. This gives me the same outcome as before though. The code for this can be viewed below:

library(shiny)

# INNER MOD ---------------------------------------------------------------

innermodUI <- function(id) {

  ns = NS(id)

  tagList(
    selectInput(ns('letter'), 'Letter:', LETTERS[1:2]),
    uiOutput(ns('names'))
  )
}

innermodServer <- function(input, output, session) {

  ns = session$ns

  output$names <- renderUI({

    selection = req(input$letter)

    switch(
      selection,
      'A' = textInput(ns('text'), 'ENTER TEXT', ''),
      'B' = numericInput(ns('numeric'), 'ENTER NUMBER', '')
    )
  })
}

# OUTER MOD ---------------------------------------------------------------

modUI <- function(id){

  ns <- NS(id)

  tagList(
    actionButton(ns('add'), 'Add'),
    div(id = ns('placeholder'))
  )
}

modServer <- function(input, output, session) {

  ns = session$ns

  ctn <- reactiveVal(0)

  Id <- reactive({
    function(id){
      ns(paste0(id, ctn()))
    }
  })

  observeEvent(input$add, {

    ctn(ctn() + 1)

    filterId = Id()('filter')

    insertUI(
      selector = paste0('#', ns('placeholder')),
      ui = innermodUI(filterId)
    )

    callModule(innermodServer, filterId)

  })
}

# MAIN --------------------------------------------------------------------

ui <- fluidPage(
  modUI('mod1')
)

server <- function(input, output, session) {
  callModule(modServer, "mod1")
}

shinyApp(ui, server)```

I also tried wrapping the renderUI in a shinyjs::delay() to no avail. I would really appreciate any help on this since I'm not well-versed in Shiny modules and don't know what to try next.

答:
I've managed to make it work by multiple trials-errors. As I understand (I'm still new in Shiny modules), you have to use session$ns only for the inputs created in the server.

```<code>library(shiny)

# module UI function
modUI <- function(id){

  ns <- NS(id)

  tagList(
    actionButton(ns('add'), 'Add'),
    div(id = ns('placeholder'))
  )
}

# module server function
modServer <- function(input, output, session) {

  ns = session$ns

  ctn <- reactiveVal(0)

  Id <- reactive({
    function(id){
      paste0(id, ctn())
    }
  })
  IdNS <- reactive({
    function(id){
      ns(paste0(id, ctn()))
    }
  })

  observeEvent(input$add, {

    ctn(ctn() + 1)

    insertUI(
      selector = paste0('#', ns('placeholder')),
      ui = div(
        id = Id()('div'),
        selectInput(IdNS()('letter'), 'Letter:', LETTERS[1:2]),
        uiOutput(IdNS()('input'))
      )
    )
  })

  observeEvent(ctn(), {

    id <- Id()('input')
    selection <- Id()('letter')

    output[[id]] <- renderUI({

      switch(
        input[[selection]],
        'A' = textInput(IdNS()('text'), 'ENTER TEXT', ''),
        'B' = numericInput(IdNS()('numeric'), 'ENTER NUMBER', '')
      )

    })

  }, ignoreInit = TRUE)
}

# main ui
ui <- fluidPage(
  modUI('mod1')
)

# main server
server <- function(input, output, session) {
  callModule(modServer, "mod1")
}

# run app
shinyApp(ui, server)
</code>```

Body:
The app below contains a module that inserts a UI object each time the Add button is clicked. The UI object consists of two inputs:

Input 1 is a selectInput with choices A and B.

Input 2 is a textInput if the user chooses A and a
numericInput if they choose B.

However, when I click Add, the inserted UI only contains Input 1 (the selectInput) - Input 2 is not rendered, as shown below:

Whereas the desired output looks like this:

I'm not sure if this is a namespacing issue or if there is a problem in the scoping of the module. Printing the IDs to the console checks out:

The app is as follows:

library(shiny)

# module UI function
modUI <- function(id){

  ns <- NS(id)

  tagList(
    actionButton(ns('add'), 'Add'),
    div(id = ns('placeholder'))
  )
}

# module server function
modServer <- function(input, output, session) {

  ns = session$ns

  ctn <- reactiveVal(0)

  Id <- reactive({
    function(id){
      ns(paste0(id, ctn()))
    }
  })

  observeEvent(input$add, {

    ctn(ctn() + 1)

    insertUI(
      selector = paste0('#', ns('placeholder')),
      ui = div(
        id = Id()('div'),
        selectInput(Id()('letter'), 'Letter:', LETTERS[1:2]),
        uiOutput(Id()('input'))
      )
    )
  })

  observeEvent(ctn(), {

    id <- Id()('input')
    selection <- Id()('letter')
    print(list(id = id, selection = selection))

    req(input[[selection]])

    output[[id]] <- renderUI({

      req(input[[selection]])

      switch(
        input[[selection]],
        'A' = textInput(Id()('text'), 'ENTER TEXT', ''),
        'B' = numericInput(Id()('numeric'), 'ENTER NUMBER', '')
      )
    })

  }, ignoreInit = TRUE)
}

# main ui
ui <- fluidPage(
  modUI('mod1')
)

# main server
server <- function(input, output, session) {
  callModule(modServer, "mod1")
}

# run app
shinyApp(ui, server)

I tried splitting the module up into an inner and outer module. The inner mod creates Input 1 and Input 2 and the outer mod inserts them into the main app using insertUI. This gives me the same outcome as before though. The code for this can be viewed below:

library(shiny)

# INNER MOD ---------------------------------------------------------------

innermodUI <- function(id) {

  ns = NS(id)

  tagList(
    selectInput(ns('letter'), 'Letter:', LETTERS[1:2]),
    uiOutput(ns('names'))
  )
}

innermodServer <- function(input, output, session) {

  ns = session$ns

  output$names <- renderUI({

    selection = req(input$letter)

    switch(
      selection,
      'A' = textInput(ns('text'), 'ENTER TEXT', ''),
      'B' = numericInput(ns('numeric'), 'ENTER NUMBER', '')
    )
  })
}

# OUTER MOD ---------------------------------------------------------------

modUI <- function(id){

  ns <- NS(id)

  tagList(
    actionButton(ns('add'), 'Add'),
    div(id = ns('placeholder'))
  )
}

modServer <- function(input, output, session) {

  ns = session$ns

  ctn <- reactiveVal(0)

  Id <- reactive({
    function(id){
      ns(paste0(id, ctn()))
    }
  })

  observeEvent(input$add, {

    ctn(ctn() + 1)

    filterId = Id()('filter')

    insertUI(
      selector = paste0('#', ns('placeholder')),
      ui = innermodUI(filterId)
    )

    callModule(innermodServer, filterId)

  })
}

# MAIN --------------------------------------------------------------------

ui <- fluidPage(
  modUI('mod1')
)

server <- function(input, output, session) {
  callModule(modServer, "mod1")
}

shinyApp(ui, server)

I also tried wrapping the renderUI in a shinyjs::delay() to no avail. I would really appreciate any help on this since I'm not well-versed in Shiny modules and don't know what to try next.

Body:
I've managed to make it work by multiple trials-errors. As I understand (I'm still new in Shiny modules), you have to use session$ns only for the inputs created in the server.

library(shiny)

# module UI function
modUI <- function(id){

  ns <- NS(id)

  tagList(
    actionButton(ns('add'), 'Add'),
    div(id = ns('placeholder'))
  )
}

# module server function
modServer <- function(input, output, session) {

  ns = session$ns

  ctn <- reactiveVal(0)

  Id <- reactive({
    function(id){
      paste0(id, ctn())
    }
  })
  IdNS <- reactive({
    function(id){
      ns(paste0(id, ctn()))
    }
  })

  observeEvent(input$add, {

    ctn(ctn() + 1)

    insertUI(
      selector = paste0('#', ns('placeholder')),
      ui = div(
        id = Id()('div'),
        selectInput(IdNS()('letter'), 'Letter:', LETTERS[1:2]),
        uiOutput(IdNS()('input'))
      )
    )
  })

  observeEvent(ctn(), {

    id <- Id()('input')
    selection <- Id()('letter')

    output[[id]] <- renderUI({

      switch(
        input[[selection]],
        'A' = textInput(IdNS()('text'), 'ENTER TEXT', ''),
        'B' = numericInput(IdNS()('numeric'), 'ENTER NUMBER', '')
      )

    })

  }, ignoreInit = TRUE)
}

# main ui
ui <- fluidPage(
  modUI('mod1')
)

# main server
server <- function(input, output, session) {
  callModule(modServer, "mod1")
}

# run app
shinyApp(ui, server)


来源: stackexchange

问:
Weak References in python
I have been trying to understand how python weak reference lists/dictionaries work. I've read the documentation for it, however I cannot  figure out how they work, and what they can be used for. Could anyone give me a basic example of what they do and an explanation of how they work?

(EDIT) Using Thomas's code, when i substitute obj for [1,2,3] it throws:

```<code>Traceback (most recent call last):
File "C:/Users/nonya/Desktop/test.py", line 9, in <module>
r = weakref.ref(obj)
TypeError: cannot create weak reference to 'list' object
</code>```

答:
Here is the example comparing dict and WeakValueDictionary:

```<code>class C: pass
ci=C()
print(ci)

wvd = weakref.WeakValueDictionary({'key' : ci})
print(dict(wvd), len(wvd)) #1
del ci
print(dict(wvd), len(wvd)) #0

ci2=C()
d=dict()
d['key']=ci2
print(d, len(d))
del ci2
print(d, len(d))
</code>```

And here is the output:

```<code><__main__.C object at 0x00000213775A1E10>
{'key': <__main__.C object at 0x00000213775A1E10>} 1
{} 0
{'key': <__main__.C object at 0x0000021306B0E588>} 1
{'key': <__main__.C object at 0x0000021306B0E588>} 1
</code>```

Note how in the first case once we del ci the actual object will be also removed from the dictionary wvd.

In the case or regular Python dictionary dict class, we may try to remove the object but it will still be there as shown.

Note: if we use del, we do not to call gc.collect() after that, since just del effectively removes the object.

ContentLicense: CC BY-SA 4.0

Title: Weak References in python

Body:
I have been trying to understand how python weak reference lists/dictionaries work. I've read the documentation for it, however I cannot  figure out how they work, and what they can be used for. Could anyone give me a basic example of what they do and an explanation of how they work?

(EDIT) Using Thomas's code, when i substitute obj for [1,2,3] it throws:

Traceback (most recent call last):
File "C:/Users/nonya/Desktop/test.py", line 9, in <module>
r = weakref.ref(obj)
TypeError: cannot create weak reference to 'list' object

Body:
Here is the example comparing dict and WeakValueDictionary:

class C: pass
ci=C()
print(ci)

wvd = weakref.WeakValueDictionary({'key' : ci})
print(dict(wvd), len(wvd)) #1
del ci
print(dict(wvd), len(wvd)) #0

ci2=C()
d=dict()
d['key']=ci2
print(d, len(d))
del ci2
print(d, len(d))

And here is the output:

<__main__.C object at 0x00000213775A1E10>
{'key': <__main__.C object at 0x00000213775A1E10>} 1
{} 0
{'key': <__main__.C object at 0x0000021306B0E588>} 1
{'key': <__main__.C object at 0x0000021306B0E588>} 1

Note how in the first case once we del ci the actual object will be also removed from the dictionary wvd.

In the case or regular Python dictionary dict class, we may try to remove the object but it will still be there as shown.

Note: if we use del, we do not to call gc.collect() after that, since just del effectively removes the object.


问:
Flutter Channel Method String Not Working as URL
I have a Channel Method in my Flutter project which takes a String (url), downloads an image and presents it as part of a new contact.

However, the image won't be displayed for most urls.

This is the code I use to get the image and add to the new contact, before displaying it in a CNContactViewController.

```<code>let urlString : String = (arguments["imgUrl"] as? String)!
            let url = URL(string: urlString)
            let data = try? Data(contentsOf: url!)
            newContact.imageData = data
</code>```

I have tried encoding the url and casting it as an NSString with no luck.

Interesting, if I hard code the url in like below, it works. So what is happening between sending it from my Dart source code, over to Swift?

(URL modified to conceal contents, real URL returns image)

```<code>let url = URL(string: "https://23ee7ca4ch9430946b76-4f3bba1a032272305d39a357e474f3b2.ssl.cf1.rackcdn.com/talent/81843293_1556369106.jpeg")
            let data = try? Data(contentsOf: url!)
            newContact.imageData = data
</code>```

Update:

Here is the full code...

Dart:

```<code>static const platform = const MethodChannel('contacts');

  static Future<String> addSystemContact({
    String firstName,
    String lastName,
    String jobTitle,
    String company,
    String phone,
    String email,
    String city,
    String country,
    String profile,
    String imgUrl,
  }) async {
    try {
      var result = await platform.invokeMethod(
          'addSystemContact',
          {
            'firstName' : firstName != null && firstName.isNotEmpty ? firstName : "",
            'lastName' : lastName != null && lastName.isNotEmpty ? lastName : "",
            'jobTitle' : jobTitle,
            'company' : company,
            'phone' : phone,
            'email' : email,
            'city' : city,
            'country' : country,
            'profile' : profile,
            'imgUrl': imgUrl,
          },
      );
      return result;
    } on PlatformException catch (e) {
      return null;
    }
  }
</code>```

Swift:

```<code>let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let contactChannel = FlutterMethodChannel(name: "contacts", binaryMessenger: controller)
    contactChannel.setMethodCallHandler({(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
        //ADD SYSTEM CONTACT
        //
        if (call.method == "addSystemContact") {
            let arguments : Dictionary = call.arguments as! Dictionary<String,Any>
            guard let firstName : String = arguments["firstName"] as? String else { return result(false); }
            guard let lastName : String = arguments["lastName"] as? String else { return result(false); }

            //create contact
            let newContact = CNMutableContact()
            newContact.contactType = CNContactType.person
            newContact.givenName = firstName
            newContact.familyName = lastName

            if let jobTitle : String = arguments["jobTitle"] as? String {
                newContact.jobTitle = jobTitle
            }
            if let company : String = arguments["company"] as? String {
                newContact.organizationName = company
            }
            if let phone : String = arguments["phone"] as? String {
                newContact.phoneNumbers = [CNLabeledValue(
                    label:CNLabelPhoneNumberMain,
                    value:CNPhoneNumber(stringValue:phone))]
            }
            if let email : NSString = arguments["email"] as? NSString {
                newContact.emailAddresses = [CNLabeledValue(label:CNLabelWork, value:email)]
            }

            let address = CNMutablePostalAddress()
            if let city : String = arguments["city"] as? String {
                address.city = city
            }
            if let country : String = arguments["country"] as? String {
                address.country = country
            }
            newContact.postalAddresses = [CNLabeledValue(label:CNLabelWork, value:address)]

            if let profile : String = arguments["profile"] as? String {
                newContact.socialProfiles = [CNLabeledValue(label:

CNSocialProfileServiceLinkedIn, value: CNSocialProfile.init(urlString: profile, username: nil, userIdentifier: nil, service: nil))]
                }

                // Offending code...
                //
                let urlString : String = (arguments["imgUrl"] as? String)!

                let url = URL(string: urlString)
                let data = try? Data(contentsOf: url!)
                newContact.imageData = data
                //
                //

                //presents nav controller with CNContactViewController
                self.displayConactViewController(newContact: newContact, result: result)
            }
        })
</code>```

答:
You seem to have a mix of methodologies. Are you passing a single string as the argument, or a map? Unfortunately you don't show the Dart end.

Here are some working examples, adapted from a working plugin.

Single String

Dart end

```<code>  static void ping(String pong) {
    _channel.invokeMethod('ping', pong);
  }
</code>```

Swift end - call.arguments is a String

```<code>case "ping":
  NSLog("ping")
  if let pong = call.arguments as! String  {
    // do something
  } else {
    NSLog("ping - Invalid Args")
  }
  break
</code>```

String as map member

Dart end

```<code>  static void foo(String bar, String baz) {
    _channel.invokeMethod('foo', <String, dynamic>{
      'bar': bar,
      'baz': baz,
    });
  }
</code>```

Swift end - call.arguments is a Dictionary

```<code>case "foo":
  NSLog("foo")
  if let args = call.arguments as? Dictionary<String, Any>, let bar = args["bar"] as! String {
    // do something with bar and/or args["baz"] as! String
  } else {
    NSLog("foo - Args is not a Dictionary")
  }
  break
</code>```

Body:
I have a Channel Method in my Flutter project which takes a String (url), downloads an image and presents it as part of a new contact.

However, the image won't be displayed for most urls.

This is the code I use to get the image and add to the new contact, before displaying it in a CNContactViewController.

let urlString : String = (arguments["imgUrl"] as? String)!
            let url = URL(string: urlString)
            let data = try? Data(contentsOf: url!)
            newContact.imageData = data

I have tried encoding the url and casting it as an NSString with no luck.

Interesting, if I hard code the url in like below, it works. So what is happening between sending it from my Dart source code, over to Swift?

(URL modified to conceal contents, real URL returns image)

let url = URL(string: "https://23ee7ca4ch9430946b76-4f3bba1a032272305d39a357e474f3b2.ssl.cf1.rackcdn.com/talent/81843293_1556369106.jpeg")
            let data = try? Data(contentsOf: url!)
            newContact.imageData = data

Update:

Here is the full code...

Dart:

static const platform = const MethodChannel('contacts');

  static Future<String> addSystemContact({
    String firstName,
    String lastName,
    String jobTitle,
    String company,
    String phone,
    String email,
    String city,
    String country,
    String profile,
    String imgUrl,
  }) async {
    try {
      var result = await platform.invokeMethod(
          'addSystemContact',
          {
            'firstName' : firstName != null && firstName.isNotEmpty ? firstName : "",
            'lastName' : lastName != null && lastName.isNotEmpty ? lastName : "",
            'jobTitle' : jobTitle,
            'company' : company,
            'phone' : phone,
            'email' : email,
            'city' : city,
            'country' : country,
            'profile' : profile,
            'imgUrl': imgUrl,
          },
      );
      return result;
    } on PlatformException catch (e) {
      return null;
    }
  }

Swift:

let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let contactChannel = FlutterMethodChannel(name: "contacts", binaryMessenger: controller)
    contactChannel.setMethodCallHandler({(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
        //ADD SYSTEM CONTACT
        //
        if (call.method == "addSystemContact") {
            let arguments : Dictionary = call.arguments as! Dictionary<String,Any>
            guard let firstName : String = arguments["firstName"] as? String else { return result(false); }
            guard let lastName : String = arguments["lastName"] as? String else { return result(false); }

            //create contact
            let newContact = CNMutableContact()
            newContact.contactType = CNContactType.person
            newContact.givenName = firstName
            newContact.familyName = lastName

            if let jobTitle : String = arguments["jobTitle"] as? String {
                newContact.jobTitle = jobTitle
            }
            if let company : String = arguments["company"] as? String {
                newContact.organizationName = company
            }
            if let phone : String = arguments["phone"] as? String {
                newContact.phoneNumbers = [CNLabeledValue(
                    label:CNLabelPhoneNumberMain,
                    value:CNPhoneNumber(stringValue:phone))]
            }
            if let email : NSString = arguments["email"] as? NSString {
                newContact.emailAddresses = [CNLabeledValue(label:CNLabelWork, value:email)]
            }

            let address = CNMutablePostalAddress()
            if let city : String = arguments["city"] as? String {
                address.city = city
            }
            if let country : String = arguments["country"] as? String {
                address.country = country
            }
            newContact.postalAddresses = [CNLabeledValue(label:CNLabelWork, value:address)]

            if let profile : String = arguments["profile"] as? String {
                newContact.socialProfiles = [CNLabeledValue(label:

CNSocialProfileServiceLinkedIn, value: CNSocialProfile.init(urlString: profile, username: nil, userIdentifier: nil, service: nil))]
                }

                // Offending code...
                //
                let urlString : String = (arguments["imgUrl"] as? String)!

                let url = URL(string: urlString)
                let data = try? Data(contentsOf: url!)
                newContact.imageData = data
                //
                //

                //presents nav controller with CNContactViewController
                self.displayConactViewController(newContact: newContact, result: result)
            }
        })

Body:
You seem to have a mix of methodologies. Are you passing a single string as the argument, or a map? Unfortunately you don't show the Dart end.

Here are some working examples, adapted from a working plugin.

Single String

Dart end

  static void ping(String pong) {
    _channel.invokeMethod('ping', pong);
  }

Swift end - call.arguments is a String

case "ping":
  NSLog("ping")
  if let pong = call.arguments as! String  {
    // do something
  } else {
    NSLog("ping - Invalid Args")
  }
  break

String as map member

Dart end

  static void foo(String bar, String baz) {
    _channel.invokeMethod('foo', <String, dynamic>{
      'bar': bar,
      'baz': baz,
    });
  }

Swift end - call.arguments is a Dictionary

case "foo":
  NSLog("foo")
  if let args = call.arguments as? Dictionary<String, Any>, let bar = args["bar"] as! String {
    // do something with bar and/or args["baz"] as! String
  } else {
    NSLog("foo - Args is not a Dictionary")
  }
  break


问:
Continue Transition from where Animation Ended
See the following button animation:

html {
  background: white;
  font-family: Arial;
}

.button {
  position: relative;
  display: inline-block;
  color: #000;
  border: 2px solid #000;
  padding: 10px 24px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  text-decoration: none;
  transition-property: color, background, border-color;
  transition-duration: 0.3s;
}
.button:hover {
  color: #fff;
}
.button:hover ._background:after {
  transform: translateX(0);
  animation: fill-horizontal 0.3s linear 0s 1;
}
.button ._background {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: -1;
  overflow: hidden;
}
.button ._background:after {
  content: "";
  position: absolute;
  display: block;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: #000;
  transform: translateX(100%);
  transition: transform .3s;
}

@keyframes fill-horizontal {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <div class="_background"></div>
  Button
</code>```

The intended animation is to sweep the ._background:after element in from the left, and then out to the right like so:

translateX(-100%)

translateX(0) - Hover

translateX(100%) - Remove Hover

Whilst the animation works as intended when the user hovers for the duration of the CSS animation (.3s), it looks terrible if the user 'unhovers' before the CSS animation completes.

I would like the transition to translateX(100%) to continue from where the animation finished. Is this even possible?

NOTE - I am aware that the div._background element is not necessary, this has additional functionality that is not relevant to this question.

答:
You can consider the same effect differently in order to avoid this bad effect:

Here is an idea using background animation where the trick is to change the position only after the size has changed.

.button {
  position: relative;
  display: inline-block;
  color: #000;
  border: 2px solid #000;
  padding: 10px 24px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  text-decoration: none;
  background-image:linear-gradient(#000,#000);
  background-size:0% 100%;
  background-position:left;
  background-repeat:no-repeat;
  background-origin:border-box;
  transition:color 0.3s, background-size 0.3s, background-position 0s 0.3s;
}
.button:hover {
  color:#fff;
  background-size:100% 100%;
  background-position:right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="button">Some text</div></code>```

Using this method, you will have a transition back in case you unhover rapidly.

A hacky idea to force the animation to complete is to consider a pseudo element that will make the hover area bigger and be sure you will keep the hover until the end:

.button {
  position: relative;
  display: inline-block;
  color: #000;
  border: 2px solid #000;
  padding: 10px 24px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  text-decoration: none;
  background-image:linear-gradient(#000,#000);
  background-size:0% 100%;
  background-position:left;
  background-repeat:no-repeat;
  background-origin:border-box;
  transition:color 0.3s, background-size 0.3s, background-position 0s 0.3s;
}
.button:hover {
  color:#fff;
  background-size:100% 100%;
  background-position:right;
}

.button:hover:before {
  content:"";
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  z-index:99;
  animation:remove 0s 0.3s forwards;
}
@keyframes remove {
  to {
    top:100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="button">Some text</div></code>```

Body:
See the following button animation:

html {
  background: white;
  font-family: Arial;
}

.button {
  position: relative;
  display: inline-block;
  color: #000;
  border: 2px solid #000;
  padding: 10px 24px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  text-decoration: none;
  transition-property: color, background, border-color;
  transition-duration: 0.3s;
}
.button:hover {
  color: #fff;
}
.button:hover ._background:after {
  transform: translateX(0);
  animation: fill-horizontal 0.3s linear 0s 1;
}
.button ._background {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: -1;
  overflow: hidden;
}
.button ._background:after {
  content: "";
  position: absolute;
  display: block;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: #000;
  transform: translateX(100%);
  transition: transform .3s;
}

@keyframes fill-horizontal {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}

  Button

The intended animation is to sweep the ._background:after element in from the left, and then out to the right like so:

translateX(-100%)

translateX(0) - Hover

translateX(100%) - Remove Hover

Whilst the animation works as intended when the user hovers for the duration of the CSS animation (.3s), it looks terrible if the user 'unhovers' before the CSS animation completes.

I would like the transition to translateX(100%) to continue from where the animation finished. Is this even possible?

NOTE - I am aware that the div._background element is not necessary, this has additional functionality that is not relevant to this question.

Body:
You can consider the same effect differently in order to avoid this bad effect:

Here is an idea using background animation where the trick is to change the position only after the size has changed.

.button {
  position: relative;
  display: inline-block;
  color: #000;
  border: 2px solid #000;
  padding: 10px 24px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  text-decoration: none;
  background-image:linear-gradient(#000,#000);
  background-size:0% 100%;
  background-position:left;
  background-repeat:no-repeat;
  background-origin:border-box;
  transition:color 0.3s, background-size 0.3s, background-position 0s 0.3s;
}
.button:hover {
  color:#fff;
  background-size:100% 100%;
  background-position:right;
}

<div class="button">Some text</div>

Using this method, you will have a transition back in case you unhover rapidly.

A hacky idea to force the animation to complete is to consider a pseudo element that will make the hover area bigger and be sure you will keep the hover until the end:

.button {
  position: relative;
  display: inline-block;
  color: #000;
  border: 2px solid #000;
  padding: 10px 24px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  text-decoration: none;
  background-image:linear-gradient(#000,#000);
  background-size:0% 100%;
  background-position:left;
  background-repeat:no-repeat;
  background-origin:border-box;
  transition:color 0.3s, background-size 0.3s, background-position 0s 0.3s;
}
.button:hover {
  color:#fff;
  background-size:100% 100%;
  background-position:right;
}

.button:hover:before {
  content:"";
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  z-index:99;
  animation:remove 0s 0.3s forwards;
}
@keyframes remove {
  to {
    top:100%;
  }
}

<div class="button">Some text</div>


问:
Processing large arrays in PowerShell
I am having a difficult time understanding the most efficient to process large datasets/arrays in PowerShell. I have arrays that have several million items that I need to process and group. This list is always different in size meaning it could be 3.5 million items or 10 million items.

Example: 3.5 million items they group by "4's" like the following:

Items 0,1,2,3 Group together 4,5,6,7 Group Together and so on.

I have tried processing the array using a single thread by looping through the list and assigning to a pscustomobject which works it just takes 45-50+ minutes to complete.

I have also attempted to break up the array into smaller arrays but that causes the process to run even longer.

$i=0
$d_array = @()
$item_array # Large dataset

While ($i -lt $item_array.length){

    $o = "Test"
    $oo = "Test"
    $n = $item_array[$i];$i++
    $id = $item_array[$i];$i++
    $ir = $item_array[$i];$i++
    $cs = $item_array[$i];$i++

    $items = [PSCustomObject]@{
        'field1' = $o
        'field2' = $oo
        'field3' = $n
        'field4' = $id
        'field5' = $ir
        'field6'= $cs
    }
    $d_array += $items

}
```

I would imagine if I applied a job scheduler that would allow me to run the multiple jobs would cut the process time down by a significant amount, but I wanted to get others takes on a quick effective way to tackle this.

答:
How's this?  32.5x faster.  Making arrays with += kills puppies.  It copies the whole array every time.</p>

```<code>$i=0
$item_array = 1..100000 # Large dataset

'measuring...'

# original 1 min 5 sec
# mine 2 sec
# other answer, 2 or 3 sec
# c# version 0.029 sec, 2241x faster!

measure-command {

$d_array =
While ($i -lt $item_array.length){
    $o = "Test"
    $oo = "Test"
    $n = $item_array[$i];$i++
    $id = $item_array[$i];$i++
    $ir = $item_array[$i];$i++
    $cs = $item_array[$i];$i++
    # $items =
    [PSCustomObject]@{
        'field1' = $o
        'field2' = $oo
        'field3' = $n
        'field4' = $id
        'field5' = $ir
        'field6'= $cs
    }
    # $d_array += $items
}

}
</code>```

Title: Processing large arrays in PowerShell

Body:
I am having a difficult time understanding the most efficient to process large datasets/arrays in PowerShell. I have arrays that have several million items that I need to process and group. This list is always different in size meaning it could be 3.5 million items or 10 million items.

Example: 3.5 million items they group by "4's" like the following:

Items 0,1,2,3 Group together 4,5,6,7 Group Together and so on.

I have tried processing the array using a single thread by looping through the list and assigning to a pscustomobject which works it just takes 45-50+ minutes to complete.

I have also attempted to break up the array into smaller arrays but that causes the process to run even longer.

$i=0
$d_array = @()
$item_array # Large dataset

While ($i -lt $item_array.length){

    $o = "Test"
    $oo = "Test"
    $n = $item_array[$i];$i++
    $id = $item_array[$i];$i++
    $ir = $item_array[$i];$i++
    $cs = $item_array[$i];$i++

    $items = [PSCustomObject]@{
        'field1' = $o
        'field2' = $oo
        'field3' = $n
        'field4' = $id
        'field5' = $ir
        'field6'= $cs
    }
    $d_array += $items

}

I would imagine if I applied a job scheduler that would allow me to run the multiple jobs would cut the process time down by a significant amount, but I wanted to get others takes on a quick effective way to tackle this.

Body:
How's this?  32.5x faster.  Making arrays with += kills puppies.  It copies the whole array every time.

$i=0
$item_array = 1..100000 # Large dataset

'measuring...'

# original 1 min 5 sec
# mine 2 sec
# other answer, 2 or 3 sec
# c# version 0.029 sec, 2241x faster!

measure-command {

$d_array =
While ($i -lt $item_array.length){
    $o = "Test"
    $oo = "Test"
    $n = $item_array[$i];$i++
    $id = $item_array[$i];$i++
    $ir = $item_array[$i];$i++
    $cs = $item_array[$i];$i++
    # $items =
    [PSCustomObject]@{
        'field1' = $o
        'field2' = $oo
        'field3' = $n
        'field4' = $id
        'field5' = $ir
        'field6'= $cs
    }
    # $d_array += $items
}

}


问:
How to install ossbrowser?
I need to download some files using the preset oss path, access key id, and access key secret. I downloaded the file for ubuntu from https://www.alibabacloud.com/help/doc-detail/61872.htm?spm=a2c63.p38356.b99.112.26f94e20idgreZ, however,  I am unable to install the browser.

Can someone guide me on how to install the oss browser?

I found no guide on installation and launching the browser on ubuntu.

答:
Yes there is no official documentation from Alibaba Cloud for the installation guide for the OSS Browser at this time.

There are a few suggestions for your consideration.

You may do these 3 suggestions at the same time.

Log a new issue on this in the OSS Browser GitHub Repo.

https://github.com/aliyun/oss-browser/issues

Open a new support ticket on this in your Alibaba Cloud console
under Support and Services.

Post a new suggestion on the Alibaba Cloud Connect platform for the
product team to review and adopt.
https://connect.alibabacloud.com/suggestion/add

Hope this helps.

Title: How to install ossbrowser?


问:
How to insert many values in arrays efficiently (with C++17 or earlier)?
Given an array with a size with m entries having size of 3: n = m * 3. On every position after m values a new value should be inserted that the size is afterwards n = m * 4.

My naive approach would be to create a larger array with the new size and than iterate over the arrays copying the values into the new one and every m steps to add another step for the new-array-iteration and filling in the new value.
The example code below might help understanding what I try to achieve.

I guess this might not be efficient. Unfortunately this array interleaving is carried out often. Therefore, the code should be efficient to avoid long computing times.

What are some other stategies and are there tools in the current standard library to use? The example uses an array but I am open to other containers.

Edit: Example code

```<code>#include <omp.h>
#include <cstdlib>

int main(int argc, char* argv[])
{

    const auto arrSize = 52428800; // entries for the initial array
    auto arr = new double[arrSize * 3]; // 3 sequential elements are a group

    #pragma omp parallel for
    for( auto i = 0; i < arrSize*3; ++i)
    {
        arr[i] = 1.0*i/arrSize;
    }

    auto larr = new double[arrSize * 4]; // larger array with space for interleaving elements

    #pragma omp parallel
    #pragma omp for
    for (auto i = 0; i < arrSize; ++i) // after each element group of three a new element should be inserted
    {
        auto k = 0;
        auto j = i*3;
        for(k=0; k < 3; ++k)
        {
            larr[i*4+k] = arr[j+k];
        }
        larr[i*4+k] = 0;
    }

    delete[] arr;
    delete[] larr;

    return EXIT_SUCCESS;
}
</code>```

答:
Do your elements need to be sequential in memory? If not you can have a vector of vectors and do the interleaving when accessing the vectors.

Personally, I would use a custom container class that wraps a vector< vector<foo>>:

```<code>template <class T>
class interleaved_vector
{
    std::vector< std::vector <T> > data;

  public:
    void interleave(const std::vector <T> & v)
    {
       data.push_back(v);
    }

    /* I am a little bit rusty on move-semantics, so I don't guarantee this is
       correct */
    void interleave(std::vector &&v)
    {
       data.push_back(std::move(v));
    }

    // Access the data in an interleaved way
    // This assumes all the interleaved vectors have the same size.
    T operator[] (size_t i) const
    {
       size_t i1 = i / data.front().size();
       size_t i2 = i % data.front().size();

       return data[i1][i2];
    }

    T & operator[] (size_t i)
    {
       size_t i1 = i / data.front().size();
       size_t i2 = i % data.front().size();

       return data[i1][i2];
    }

 }
</code>```

Now, you can declare a container of interleaved ints:

```<code>interleaved_vector<int> iv;

// populate the vector

std::vector<int> v(m)

iv.interleave(v);
iv.interleave(v);
iv.interleave(v);

// populate it using move-semantic
iv.interleave(std::move(v));

// read the n-th element after interleaving
int i = iv[n];

// set the n-th element after interleaving
iv[n] = 1234;
</code>```

This is not a complete container class, just a generic idea. It lacks iterators etc.... How to complete it, and better fit it to your use-case, is left as an exercise to the reader

Body:
Given an array with a size with m entries having size of 3: n = m * 3. On every position after m values a new value should be inserted that the size is afterwards n = m * 4.

My naive approach would be to create a larger array with the new size and than iterate over the arrays copying the values into the new one and every m steps to add another step for the new-array-iteration and filling in the new value.
The example code below might help understanding what I try to achieve.

I guess this might not be efficient. Unfortunately this array interleaving is carried out often. Therefore, the code should be efficient to avoid long computing times.

What are some other stategies and are there tools in the current standard library to use? The example uses an array but I am open to other containers.

Edit: Example code

#include <omp.h>
#include <cstdlib>

int main(int argc, char* argv[])
{

    const auto arrSize = 52428800; // entries for the initial array
    auto arr = new double[arrSize * 3]; // 3 sequential elements are a group

    #pragma omp parallel for
    for( auto i = 0; i < arrSize*3; ++i)
    {
        arr[i] = 1.0*i/arrSize;
    }

    auto larr = new double[arrSize * 4]; // larger array with space for interleaving elements

    #pragma omp parallel
    #pragma omp for
    for (auto i = 0; i < arrSize; ++i) // after each element group of three a new element should be inserted
    {
        auto k = 0;
        auto j = i*3;
        for(k=0; k < 3; ++k)
        {
            larr[i*4+k] = arr[j+k];
        }
        larr[i*4+k] = 0;
    }

    delete[] arr;
    delete[] larr;

    return EXIT_SUCCESS;
}

Body:
Do your elements need to be sequential in memory? If not you can have a vector of vectors and do the interleaving when accessing the vectors.

Personally, I would use a custom container class that wraps a vector< vector<foo>>:

template <class T>
class interleaved_vector
{
    std::vector< std::vector <T> > data;

  public:
    void interleave(const std::vector <T> & v)
    {
       data.push_back(v);
    }

    /* I am a little bit rusty on move-semantics, so I don't guarantee this is
       correct */
    void interleave(std::vector &&v)
    {
       data.push_back(std::move(v));
    }

    // Access the data in an interleaved way
    // This assumes all the interleaved vectors have the same size.
    T operator[] (size_t i) const
    {
       size_t i1 = i / data.front().size();
       size_t i2 = i % data.front().size();

       return data[i1][i2];
    }

    T & operator[] (size_t i)
    {
       size_t i1 = i / data.front().size();
       size_t i2 = i % data.front().size();

       return data[i1][i2];
    }

 }

Now, you can declare a container of interleaved ints:

interleaved_vector<int> iv;

// populate the vector

std::vector<int> v(m)

iv.interleave(v);
iv.interleave(v);
iv.interleave(v);

// populate it using move-semantic
iv.interleave(std::move(v));

// read the n-th element after interleaving
int i = iv[n];

// set the n-th element after interleaving
iv[n] = 1234;

This is not a complete container class, just a generic idea. It lacks iterators etc.... How to complete it, and better fit it to your use-case, is left as an exercise to the reader


问:
Tilemap layer not colliding with player
I have a problem with the tilemap, i'm using a single layer and i have set the tile number 5 so it functions like a barrier that the player cannot move through, or so i hoped. But it dosn't work, i used the graphics method to shows if the barrier is collidable, as you notice from the picture it is. Note: the console shows no errors, any help would be great !
https://i.stack.imgur.com/UB4S8.png
https://i.stack.imgur.com/cLzcu.png

{ "height":6,
 "infinite":false,
 "layers":[
        {
         "data":[1, 1, 1, 1, 1, 1, 1, 5, 5, 1, 1, 1, 5, 1, 1, 1, 1, 5, 1, 1, 1, 5, 5, 1, 1, 1, 1, 1, 1, 1],
         "height":6,
         "id":1,
         "name":"Tile Layer 1",
         "opacity":1,
         "type":"tilelayer",
         "visible":true,
         "width":5,
         "x":0,
         "y":0
        }],
 "nextlayerid":2,
 "nextobjectid":1,
 "orientation":"orthogonal",
 "renderorder":"right-down",
 "tiledversion":"2019.05.08",
 "tileheight":32,
 "tilesets":[
        {
         "columns":25,
         "firstgid":1,
         "image":"ground_1x1.png",
         "imageheight":32,
         "imagewidth":800,
         "margin":0,
         "name":"ground_1x1",
         "spacing":0,
         "tilecount":25,
         "tileheight":32,
         "tilewidth":32,
         "transparentcolor":"#ff0000"
        }],
 "tilewidth":32,
 "type":"map",
 "version":1.2,
 "width":5
}```
</div>
</div>
</p>

```function create ()
{

    map = this.make.tilemap({key: 'map'});

   groundTiles = map.addTilesetImage('ground_1x1', 'ground');
    map.createStaticLayer('Tile Layer 1', groundTiles,0,0);
    map.setCollision(5);

    var debugGraphics = this.add.graphics();
    map.renderDebug(debugGraphics);
    debugGraphics.visible = true;

indi= this.physics.add.sprite(200, 60, 'mario');
indi.body.allowGravity = false;
indi.setInteractive();
this.cursors = this.input.keyboard.createCursorKeys();
indi.setCollideWorldBounds(true);
this.physics.add.collider(indi, groundTiles);

}
```

答:
var config = {
    type: Phaser.WEBGL,
    width: 400,
    height: 288,
    parent: 'phaser-example',
    loader: {
      baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/',
      crossOrigin: 'anonymous'
    },
    physics: {
      default: 'arcade',
      arcade: {
        gravity: { y: 10 }
      }
    },
    scene: {
        preload: preload,
        create: create
    }
};

var game = new Phaser.Game(config);
var map;
var cursors;
var player;
var groundLayer;

function preload ()
{
    this.load.image('tileset', 'maps/super-pixel-platformer-set/tileset.png');
    this.load.tilemapTiledJSON('map', 'maps/super-pixel-platformer-set/level0.json');
    this.load.image('alien', 'sprites/phaser-alien.png');
}

function create ()
{
  map = this.make.tilemap({ key: 'map' });
  var groundTiles = map.addTilesetImage('tileset');

  groundLayer = map.createStaticLayer('ground', groundTiles, 0, 0);
  map.createStaticLayer('jumpThrough', groundTiles, 0, 0);

  //groundLayer.setCollision(7);
  groundLayer.setCollisionBetween(7,9);

  player = this.physics.add.sprite(100, 50, 'alien');
  player.setCollideWorldBounds(true);

  this.physics.add.collider(player, groundLayer);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdn.jsdelivr.net/npm/phaser@3.17.0/dist/phaser.min.js"></script></code>```

Title: Tilemap layer not colliding with player

Body:
I have a problem with the tilemap, i'm using a single layer and i have set the tile number 5 so it functions like a barrier that the player cannot move through, or so i hoped. But it dosn't work, i used the graphics method to shows if the barrier is collidable, as you notice from the picture it is. Note: the console shows no errors, any help would be great !
https://i.stack.imgur.com/UB4S8.png
https://i.stack.imgur.com/cLzcu.png

{ "height":6,
 "infinite":false,
 "layers":[
        {
         "data":[1, 1, 1, 1, 1, 1, 1, 5, 5, 1, 1, 1, 5, 1, 1, 1, 1, 5, 1, 1, 1, 5, 5, 1, 1, 1, 1, 1, 1, 1],
         "height":6,
         "id":1,
         "name":"Tile Layer 1",
         "opacity":1,
         "type":"tilelayer",
         "visible":true,
         "width":5,
         "x":0,
         "y":0
        }],
 "nextlayerid":2,
 "nextobjectid":1,
 "orientation":"orthogonal",
 "renderorder":"right-down",
 "tiledversion":"2019.05.08",
 "tileheight":32,
 "tilesets":[
        {
         "columns":25,
         "firstgid":1,
         "image":"ground_1x1.png",
         "imageheight":32,
         "imagewidth":800,
         "margin":0,
         "name":"ground_1x1",
         "spacing":0,
         "tilecount":25,
         "tileheight":32,
         "tilewidth":32,
         "transparentcolor":"#ff0000"
        }],
 "tilewidth":32,
 "type":"map",
 "version":1.2,
 "width":5
}

function create ()
{

    map = this.make.tilemap({key: 'map'});

   groundTiles = map.addTilesetImage('ground_1x1', 'ground');
    map.createStaticLayer('Tile Layer 1', groundTiles,0,0);
    map.setCollision(5);

    var debugGraphics = this.add.graphics();
    map.renderDebug(debugGraphics);
    debugGraphics.visible = true;

indi= this.physics.add.sprite(200, 60, 'mario');
indi.body.allowGravity = false;
indi.setInteractive();
this.cursors = this.input.keyboard.createCursorKeys();
indi.setCollideWorldBounds(true);
this.physics.add.collider(indi, groundTiles);

}

Body:
var config = {
    type: Phaser.WEBGL,
    width: 400,
    height: 288,
    parent: 'phaser-example',
    loader: {
      baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/',
      crossOrigin: 'anonymous'
    },
    physics: {
      default: 'arcade',
      arcade: {
        gravity: { y: 10 }
      }
    },
    scene: {
        preload: preload,
        create: create
    }
};

var game = new Phaser.Game(config);
var map;
var cursors;
var player;
var groundLayer;

function preload ()
{
    this.load.image('tileset', 'maps/super-pixel-platformer-set/tileset.png');
    this.load.tilemapTiledJSON('map', 'maps/super-pixel-platformer-set/level0.json');
    this.load.image('alien', 'sprites/phaser-alien.png');
}

function create ()
{
  map = this.make.tilemap({ key: 'map' });
  var groundTiles = map.addTilesetImage('tileset');

  groundLayer = map.createStaticLayer('ground', groundTiles, 0, 0);
  map.createStaticLayer('jumpThrough', groundTiles, 0, 0);

  //groundLayer.setCollision(7);
  groundLayer.setCollisionBetween(7,9);

  player = this.physics.add.sprite(100, 50, 'alien');
  player.setCollideWorldBounds(true);

  this.physics.add.collider(player, groundLayer);
}

<script src="//cdn.jsdelivr.net/npm/phaser@3.17.0/dist/phaser.min.js"></script>


问:
How to get authorization code from redirect response
I am using a Java wrapper for Spotify and I am trying to find a way to get the authorization code from the redirect URI so I can use it when requesting an access token. I am new to OAuth so any help would be great! Thanks!

I am able to copy the code from the browser redirect and hard code it into my code.

答:
You need to set the redirect_uri parameter as a Servlet url.</p>

```<code>@WebServlet("your/servlet/Url")
public class MyServlet extends HttpServlet
{

    private static final long serialVersionUID = 1L;

    public MyServlet()
    {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //get the authorization code
        String code = request.getParameter("code");
        //get tokens and use them as per your requirement using code
        ...
        //redirect user to the final destination
        response.sendRedirect("url");
    }
}
</code>```

Body:
You need to set the redirect_uri parameter as a Servlet url.

@WebServlet("your/servlet/Url")
public class MyServlet extends HttpServlet
{

    private static final long serialVersionUID = 1L;

    public MyServlet()
    {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //get the authorization code
        String code = request.getParameter("code");
        //get tokens and use them as per your requirement using code
        ...
        //redirect user to the final destination
        response.sendRedirect("url");
    }
}


问:
Uploading files with HTML form via "Uppy"
Uppy, a great javascript file upload library but I was unable to upload images with HTML form.

Javascript Code:

```<code> var uppy = Uppy.Core();
 uppy.use(Form, {
   target: '#upload',
   getMetaFromForm: true,
   addResultToForm: true,
   resultName: 'uppyResult',
   triggerUploadOnSubmit: false,
   submitOnSuccess: false
 });
</code>```

HTML Code:

```<code><form>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="text" class="form-control" id="exampleInputEmail1">
  </div>
  <div class="form-group">
    <label>Images Upload</label>
    <div id="upload">
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>
</code>```

on JSFiddle demo

The upload area does not appear. What could be the reason?

答:
Starting the debugger, it shows that Form in
uppy.use(Form,         is unkown or not declared.you should examine the examples(https://uppy.io/examples/xhrupload/ ) on uppy.io a little better by using the web developer tools of your browser. you should it also when encountering problems on you website.

Body:
Uppy, a great javascript file upload library but I was unable to upload images with HTML form.

Javascript Code:

 var uppy = Uppy.Core();
 uppy.use(Form, {
   target: '#upload',
   getMetaFromForm: true,
   addResultToForm: true,
   resultName: 'uppyResult',
   triggerUploadOnSubmit: false,
   submitOnSuccess: false
 });

HTML Code:

<form>

    Email address
    <input type="text" class="form-control" id="exampleInputEmail1">

    Images Upload

  <button type="submit" class="btn btn-primary">Submit</button>
</form>

on JSFiddle demo

The upload area does not appear. What could be the reason?


问:
I cannot find an img element just created in document
I need to create an img element, set it an ID and then find it using the document function getElementById

The first console displays correctly the ID of the element but the second one says null

```<code>const image = document.createElement("IMG")
image.id="inn"
console.log(image.id)//this is fine
const innUI = document.getElementById('inn')
console.log(innUI.id)//i get null here
</code>```

Is it because i need to append the element to any part of the HTML?

答:
You need to add the object in DOM then only you can find it using getElementById

   const image = document.createElement("IMG")
image.id="inn"
document.body.appendChild(image);
console.log(image.id)//this is fine
const innUI = document.getElementById('inn')
console.log(innUI.id)//i get null here```

Body:
I need to create an img element, set it an ID and then find it using the document function getElementById

The first console displays correctly the ID of the element but the second one says null

const image = document.createElement("IMG")
image.id="inn"
console.log(image.id)//this is fine
const innUI = document.getElementById('inn')
console.log(innUI.id)//i get null here

Is it because i need to append the element to any part of the HTML?


问:
How to store arbitrary data for some HTML tags
I'm making a page which has some interaction provided by javascript. Just as an example: links which send an AJAX request to get the content of articles and then display that data in a div. Obviously in this example, I need each link to store an extra bit of information: the id of the article. The way I've been handling it in case was to put that information in the href link this:

```<code><a class="article" href="#5">
</code>```

I then use jQuery to find the a.article elements and attach the appropriate event handler. (don't get too hung up on the usability or semantics here, it's just an example)

Anyway, this method works, but it smells a bit, and isn't extensible at all (what happens if the click function has more than one parameter? what if some of those parameters are optional?)

The immediately obvious answer was to use attributes on the element. I mean, that's what they're for, right? (Kind of).

```<code><a articleid="5" href="link/for/non-js-users.html">
</code>```

In my recent question I asked if this method was valid, and it turns out that short of defining my own DTD (I don't), then no, it's not valid or reliable. A common response was to put the data into the class attribute (though that might have been because of my poorly-chosen example), but to me, this smells even more. Yes it's technically valid, but it's not a great solution.

Another method I'd used in the past was to actually generate some JS and insert it into the page in a

答:
In html, we can store custom attributes with the prefix 'data-' before the attribute name like

This animal is a dog.
.
Check documentation

We can use this property to dynamically set and get attributes using jQuery like:
If we have a p tag like

This animal is a dog.

Then to create an attribute called 'breed' for the above tag, we can write:

$('#animal').attr('data-breed', 'pug');

To retrieve the data anytime, we can write:

var breedtype = $('#animal').data('breed');

OwnerDisplayName: nickf

ContentLicense: CC BY-SA 2.5

Body:
I'm making a page which has some interaction provided by javascript. Just as an example: links which send an AJAX request to get the content of articles and then display that data in a div. Obviously in this example, I need each link to store an extra bit of information: the id of the article. The way I've been handling it in case was to put that information in the href link this:

I then use jQuery to find the a.article elements and attach the appropriate event handler. (don't get too hung up on the usability or semantics here, it's just an example)

Anyway, this method works, but it smells a bit, and isn't extensible at all (what happens if the click function has more than one parameter? what if some of those parameters are optional?)

The immediately obvious answer was to use attributes on the element. I mean, that's what they're for, right? (Kind of).

In my recent question I asked if this method was valid, and it turns out that short of defining my own DTD (I don't), then no, it's not valid or reliable. A common response was to put the data into the class attribute (though that might have been because of my poorly-chosen example), but to me, this smells even more. Yes it's technically valid, but it's not a great solution.

Another method I'd used in the past was to actually generate some JS and insert it into the page in a

Body:
In html, we can store custom attributes with the prefix 'data-' before the attribute name like

<p data-animal='dog'>This animal is a dog.</p>.
Check documentation

We can use this property to dynamically set and get attributes using jQuery like:
If we have a p tag like

<p id='animal'>This animal is a dog.</p>

Then to create an attribute called 'breed' for the above tag, we can write:

$('#animal').attr('data-breed', 'pug');

To retrieve the data anytime, we can write:

var breedtype = $('#animal').data('breed');


问:
How to make the removal of lines from the file?
the key is the name of the player, the value is the record (in seconds) there is a code that needs to be improved

I have a file with the name and result of the player (they are written in a different form), on this form, these data are recorded in the dictionary and then the 5 best results are distributed by rating.

Objective: make removal from file

below are my attempts to do this:

```<code>private static Dictionary<string, int> AllNames()
{
    return File
      .ReadLines(@"C:\Users\D205\Desktop\картинки\results.txt")
      .Where(line => !string.IsNullOrWhiteSpace(line))
      .Select(item => item.Split(' '))
      .ToDictionary(items => items[0],
                    items => int.Parse(items[1]));
}

private void updateRatingLabels()
{
    var tops = AllNames()
      .OrderBy(pair => pair.Value)
      .ThenBy(pair => pair.Key, StringComparer.Ordinal)
      .Take(5)
      .ToArray();

    if (System.IO.File.ReadAllLines(@"C:\Users\D205\Desktop\картинки\results.txt").Length >5)
    {

        for (int i = 18; i <= 22; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 28; i <= 32; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 0; i < tops.Length; ++i)
        {
            Controls.Find($"label{i + 18}", true).First().Text = tops[i].Key;
            Controls.Find($"label{i + 28}", true).First().Text = $"{tops[i].Value / 60}:{tops[i].Value % 60:00}";  //Controls.Find($"label{i + 28}", true).First().Text = tops[i].Value.ToString();
               // remove tops.key

        }

        for (...)
        {
            // set delete from file by key
            // remove these items from the dictionary
        }

    }
</code>```

答:
So many ways you can do this...here's one:</p>

```<code>// @"C:\Users\D205\Desktop\картинки\results.txt"
private static String FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "SomeFile.txt");

private static Dictionary<string, int> AllNames()
{
    return File
      .ReadLines(FileName)
      .Where(line => !string.IsNullOrWhiteSpace(line))
      .Select(item => item.Split(' '))
      .ToDictionary(items => items[0],
                    items => int.Parse(items[1]));
}

private static void WriteNames(Dictionary<string, int> AllNames)
{
    var lines = AllNames
       .Select(kvp => kvp.Key + " " + kvp.Value.ToString())
       .ToArray();
    File.WriteAllLines(FileName, lines);
}

private void button1_Click(object sender, EventArgs e)
{
    var top5 = AllNames()
       .OrderBy(pair => pair.Value)
      .ThenBy(pair => pair.Key, StringComparer.Ordinal)
      .Take(5);

    var tops = top5.ToArray();

    // ... your existing code to work with "tops" ...

    // write out the new file
    Dictionary<string, int> top5dict = new Dictionary<string, int>();
    foreach(var pair in top5)
    {
        top5dict.Add(pair.Key, pair.Value);
    }
    WriteNames(top5dict);
}
</code>```

Body:
the key is the name of the player, the value is the record (in seconds) there is a code that needs to be improved

I have a file with the name and result of the player (they are written in a different form), on this form, these data are recorded in the dictionary and then the 5 best results are distributed by rating.

Objective: make removal from file

below are my attempts to do this:

private static Dictionary<string, int> AllNames()
{
    return File
      .ReadLines(@"C:\Users\D205\Desktop\картинки\results.txt")
      .Where(line => !string.IsNullOrWhiteSpace(line))
      .Select(item => item.Split(' '))
      .ToDictionary(items => items[0],
                    items => int.Parse(items[1]));
}

private void updateRatingLabels()
{
    var tops = AllNames()
      .OrderBy(pair => pair.Value)
      .ThenBy(pair => pair.Key, StringComparer.Ordinal)
      .Take(5)
      .ToArray();

    if (System.IO.File.ReadAllLines(@"C:\Users\D205\Desktop\картинки\results.txt").Length >5)
    {

        for (int i = 18; i <= 22; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 28; i <= 32; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 0; i < tops.Length; ++i)
        {
            Controls.Find($"label{i + 18}", true).First().Text = tops[i].Key;
            Controls.Find($"label{i + 28}", true).First().Text = $"{tops[i].Value / 60}:{tops[i].Value % 60:00}";  //Controls.Find($"label{i + 28}", true).First().Text = tops[i].Value.ToString();
               // remove tops.key

        }

        for (...)
        {
            // set delete from file by key
            // remove these items from the dictionary
        }

    }

Body:
So many ways you can do this...here's one:

// @"C:\Users\D205\Desktop\картинки\results.txt"
private static String FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "SomeFile.txt");

private static Dictionary<string, int> AllNames()
{
    return File
      .ReadLines(FileName)
      .Where(line => !string.IsNullOrWhiteSpace(line))
      .Select(item => item.Split(' '))
      .ToDictionary(items => items[0],
                    items => int.Parse(items[1]));
}

private static void WriteNames(Dictionary<string, int> AllNames)
{
    var lines = AllNames
       .Select(kvp => kvp.Key + " " + kvp.Value.ToString())
       .ToArray();
    File.WriteAllLines(FileName, lines);
}

private void button1_Click(object sender, EventArgs e)
{
    var top5 = AllNames()
       .OrderBy(pair => pair.Value)
      .ThenBy(pair => pair.Key, StringComparer.Ordinal)
      .Take(5);

    var tops = top5.ToArray();

    // ... your existing code to work with "tops" ...

    // write out the new file
    Dictionary<string, int> top5dict = new Dictionary<string, int>();
    foreach(var pair in top5)
    {
        top5dict.Add(pair.Key, pair.Value);
    }
    WriteNames(top5dict);
}


问:
How to solve this TypeError issue in python3? "TypeError: a bytes-like object is required, not 'str'"
Recently I switched from python2.7 to python3.7.3 In my project, very frequently facing this typeerror. "TypeError: a bytes-like object is required, not 'str'". I want to define it as string only. I read to encode str objects in one of the posts. but it gives an error like "pass arguments to encode()", it is not working. Is there any permanent solution for this? like importing or defining something at the beginning only.

Thank You.
My code is as follows.

```<code>ids = [1,2,3,4,5]
list_ = ['A','B','X','Y','Z','W']
df = [None for i in ids]
print(type(df))
</code>```

TypeError: a bytes-like object is required, not 'str'

答:
If you are looking to convert a string object to byte object you should do something
like this

```<code>st = "Roushan" #  a string object
byte_object = st.encode('utf-8')
</code>```

here byte_object is the actual object and 'utf-8' is encoding scheme
There are a lot of encoding schemes

ASCII

UTF-16

For more on types of encoding  Encoding

After this just figure out which argument was needed to be passed as byte instead of str and change that object to byte.

As i dont have nk module installed in my system i leave this to you

EDIT:

open a fresh new empty python file

write the following code

```<code>ids = [1,2,3,4,5]
list_ = ['A','B','X','Y','Z','W']
df = [None for i in ids]
print(type(df))
</code>```

open a terminal and execute

python2.7 mycode.py

python3.7 mycode.py

in case 1 you get

in case 2

and please post the error Traceback you get . I believe the error is originating at other part of the code as this one is fine

Body:
Recently I switched from python2.7 to python3.7.3 In my project, very frequently facing this typeerror. "TypeError: a bytes-like object is required, not 'str'". I want to define it as string only. I read to encode str objects in one of the posts. but it gives an error like "pass arguments to encode()", it is not working. Is there any permanent solution for this? like importing or defining something at the beginning only.

Thank You.
My code is as follows.

ids = [1,2,3,4,5]
list_ = ['A','B','X','Y','Z','W']
df = [None for i in ids]
print(type(df))

TypeError: a bytes-like object is required, not 'str'

Body:
If you are looking to convert a string object to byte object you should do something
like this

st = "Roushan" #  a string object
byte_object = st.encode('utf-8')

here byte_object is the actual object and 'utf-8' is encoding scheme
There are a lot of encoding schemes

ASCII

UTF-16

For more on types of encoding  Encoding

After this just figure out which argument was needed to be passed as byte instead of str and change that object to byte.

As i dont have nk module installed in my system i leave this to you

EDIT:

open a fresh new empty python file

write the following code

ids = [1,2,3,4,5]
list_ = ['A','B','X','Y','Z','W']
df = [None for i in ids]
print(type(df))

open a terminal and execute

python2.7 mycode.py

python3.7 mycode.py

in case 1 you get

in case 2

and please post the error Traceback you get . I believe the error is originating at other part of the code as this one is fine


问:
using distinct command
using distinct command in SQL is good practice or not? is there any drawback of distinct command?</p>

答:
If you want the work to make sure the results are distinct to happen inside the SQL server on the SQL machine, then use it.  If you don't mind sending extra results to the client and doing the work there (to reduce server load) then do that.  It depends on your performance requirements and the characteristics of your database.

For example, if it's extremely unlikely that distinct will reduce the result set much, and you don't have the right columns indexed to make it fast, and you need to reduce SQL Server load, and you have spare cycles on the client, and it's easy to ensure distinctness on the client -- then you might want to do that.

That's a lot of ifs, ands, and mights.  If you don't know -- just use it.

ContentLicense: CC BY-SA 3.0

Title: using distinct command


问:
Explicitly call static constructor
I want to write unit test for below class.

If name is other than "MyEntity" then mgr should be blank.

Negative Unit test

Using Manager private accessor I want to change name to "Test" so that mgr should be null.
And then will verify the mgr value.
To achieve this, I want to explicitly call the static constructor
but when I call the static constructor using

```<code>Manager_Accessor.name = "Test"
typeof(Manager).TypeInitializer.Invoke(null, null);
</code>```

name is always set to "MyEntity" how to set name to "Test" and invoke the static constructor.

```<code>public class Manager
{
        private static string name= "MyEntity";

        private static object mgr;

        static Manager()
        {
            try
            {
                mgr = CreateMgr(name);
            }
            catch (Exception ex)
            {
                mgr=null;
            }
        }
}
</code>```

答: Just add public static void Initialize() { } method to your static class and call it when you want. This is very similar to call constructor, because static constructor will be called automatically.

Title: Explicitly call static constructor

Body:
I want to write unit test for below class.

If name is other than "MyEntity" then mgr should be blank.

Negative Unit test

Using Manager private accessor I want to change name to "Test" so that mgr should be null.
And then will verify the mgr value.
To achieve this, I want to explicitly call the static constructor
but when I call the static constructor using

Manager_Accessor.name = "Test"
typeof(Manager).TypeInitializer.Invoke(null, null);

name is always set to "MyEntity" how to set name to "Test" and invoke the static constructor.

public class Manager
{
        private static string name= "MyEntity";

        private static object mgr;

        static Manager()
        {
            try
            {
                mgr = CreateMgr(name);
            }
            catch (Exception ex)
            {
                mgr=null;
            }
        }
}


问:
flutter nfc plugin only scans once
I'm new to flutter. I'm using this nfc plugin to read an nfc tag in an android app. Currently, when i open my app, i can scan a tag once. But if I try to scan more than one tag, nothing is read. Here is the sample code I have used from the plugin example.
Any help would be much appreciated</p>

答:
I have similar problem with this code (correct me if I'm wrong but it seems to be sample from package description)). In my case I can read many tags after starting an app and after starting reading tags (Start NFC button). But after pressing Stop NFC button and again Start NFC button, app doesn't read and doesn't show tags. I think the tags are read by nfc module (Samsung A5 in my case, I can hear the same sound) but app form (page) stays the same - no tag info (null only). When I closed an app and started it again tags were read again. I tried to change a little startNFC() method which is like this in my case:

```<code>Future<void> startNFC() async {
    NfcData response;

    setState(() {
      _nfcData = NfcData();
      _nfcData.status = NFCStatus.reading;
    });

    print('NFC: Scan started');

    try {
      print('NFC: Scan readed NFC tag');
       Stream<NfcData> res = await FlutterNfcReader.read;
       if (res != null) {
         response = await res.first;
       }
    } on PlatformException {
      print('NFC: Scan stopped exception');
    }
    setState(() {
      _nfcData = response;
    });
  }
</code>```

Now, I can read tag once after tap Start NFC button. If I tap Stop NFC button and again Start NFC button everything works fine (one read). Of course you can call startNFC() method programaticaly and controll this way entire read process. Good luck!

Title: flutter nfc plugin only scans once

Body:
I have similar problem with this code (correct me if I'm wrong but it seems to be sample from package description)). In my case I can read many tags after starting an app and after starting reading tags (Start NFC button). But after pressing Stop NFC button and again Start NFC button, app doesn't read and doesn't show tags. I think the tags are read by nfc module (Samsung A5 in my case, I can hear the same sound) but app form (page) stays the same - no tag info (null only). When I closed an app and started it again tags were read again. I tried to change a little startNFC() method which is like this in my case:

Future<void> startNFC() async {
    NfcData response;

    setState(() {
      _nfcData = NfcData();
      _nfcData.status = NFCStatus.reading;
    });

    print('NFC: Scan started');

    try {
      print('NFC: Scan readed NFC tag');
       Stream<NfcData> res = await FlutterNfcReader.read;
       if (res != null) {
         response = await res.first;
       }
    } on PlatformException {
      print('NFC: Scan stopped exception');
    }
    setState(() {
      _nfcData = response;
    });
  }

Now, I can read tag once after tap Start NFC button. If I tap Stop NFC button and again Start NFC button everything works fine (one read). Of course you can call startNFC() method programaticaly and controll this way entire read process. Good luck!


问:
how to set different PYTHONPATH variables for python3 and python2 respectively
I want to add a specific library path only to python2. After adding export PYTHONPATH="/path/to/lib/" to my .bashrc, however, executing python3 gets the error: Your PYTHONPATH points to a site-packages dir for Python 2.x but you are running Python 3.x!

I think it is due to that python2 and python3 share the common PYTHONPATH variable.

So, can I set different PYTHONPATH variables respectively for python2 and python3. If not, how can I add a library path exclusively to a particular version of python?

答:
If you don't want to bother with moving/adding documents in lib/site-packages, try adding two lines of code in the python2.7 script you would like to run (below.)

```<code>import sys
sys.path = [p for p in sys.path if p.startswith(r'C:\Python27')]
</code>```

This way, PYTHONPATH will be updated (ignore all python3.x packages) every time you run your code.

Body:
If you don't want to bother with moving/adding documents in lib/site-packages, try adding two lines of code in the python2.7 script you would like to run (below.)

import sys
sys.path = [p for p in sys.path if p.startswith(r'C:\Python27')]

This way, PYTHONPATH will be updated (ignore all python3.x packages) every time you run your code.


问:
I am getting Integer value as 'Integer' in the list in my Java 8 code
I am new to java.
In java i can see that int and Integer are different.
int is primitive and Integer is class.
I have done following code.

```<code>import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Builder
public class Student {

    private Integer roleNo;
    private String name;
    private String city;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        List<Student> lstStudent = new LinkedList<Student>();
        lstStudent.add(new Student(111, "aaa", "Moon"));
        lstStudent.add(new Student(333, "ccc", "Sun"));
        lstStudent.add(new Student(222, "bbb", "Jupiter"));

        List<Student> sortedStudents = lstStudent.stream().sorted(Comparator.comparing(Student::getRoleNo))
                                                          .collect(Collectors.toList());

        System.out.println(sortedStudents);

    }

}
</code>```

I have given breakpoint at sortedstudent list and I can see that I am getting all the values but I am not getting integer value. It shows as 'Integer' ......... why?
Am I missing some key concept here?

答:
This answer here explains quite well what's going on:

Integer is a class, no different from any other in the Java language. Variables of type Integer store references to Integer objects, just as with any other reference (object) type. Integer.parseInt("1") is a call to the static method parseInt from class Integer (note that this method actually returns an int and not an Integer).

To be more specific, Integer is a class with a single field of type int. This class is used where you need an int to be treated like any other object, such as in generic types or situations where you need nullability.

Like @NicholasK says in the comments; if you expand the Integer object in your Debugger you will see that it's an object that contains a single field called value which holds the actual value represented as a primitive int.

Although you can see this for yourself in your IDE, here is a screenshot to provide more context for all those that might stumble upon this having the same question:

Read more about Java Debugging with Eclipse.

Body:
I am new to java.
In java i can see that int and Integer are different.
int is primitive and Integer is class.
I have done following code.

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Builder
public class Student {

    private Integer roleNo;
    private String name;
    private String city;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        List<Student> lstStudent = new LinkedList<Student>();
        lstStudent.add(new Student(111, "aaa", "Moon"));
        lstStudent.add(new Student(333, "ccc", "Sun"));
        lstStudent.add(new Student(222, "bbb", "Jupiter"));

        List<Student> sortedStudents = lstStudent.stream().sorted(Comparator.comparing(Student::getRoleNo))
                                                          .collect(Collectors.toList());

        System.out.println(sortedStudents);

    }

}

I have given breakpoint at sortedstudent list and I can see that I am getting all the values but I am not getting integer value. It shows as 'Integer' ......... why?
Am I missing some key concept here?


问:
Create wavy borders in CSS for top and bottom borders
I'm trying to create a wavy top and bottom border like the image here

I tried recreating the same effect using the following code

```<code>.wave{
  background: white;
  height: 25px;
  position: relative;
}
.wave::before, .wave::after{
  border-bottom: 5px solid rgba(237, 30, 30, 1);
}
.wave::before{
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 12px;
  background-size: 20px 40px;
  background-image:
    radial-gradient(circle at 10px -15px, transparent 20px, rgba(237, 30, 30, 1) 21px);
}
.wave::after{
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 18px;
  background-size: 40px 40px;
  background-image:
    radial-gradient(circle at 10px 26px, rgba(237, 30, 30, 1) 20px, transparent 21px);
}

.wavebottom{
  background: rgba(237, 30, 30, 1);
  height: 25px;
  position: relative;
}
.wavebottom::before, .wave::after{
  border-bottom: 5px solid rgba(237, 30, 30, 1);
}
.wave::before{
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 12px;
  background-size: 20px 40px;
  background-image:
    radial-gradient(circle at 10px -15px, transparent 20px, white 21px);
}
.wavebottom::after{
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 18px;
  background-size: 40px 40px;
  background-image:
    radial-gradient(circle at 10px 26px, white 20px, transparent 21px);
}
</code>```

Where I have the code in 3 divs.. first div has the wave class

second div has the background color and the content

and the third div has the wavebottom class

but I'm getting the results of the waves looking like that

I'm working on a page with the width of 1920px, I'm not sure how can I make this look the same like the first image

答:
Try using this:

.wave-top {
  position: relative;
  margin-top: 20px;
}

.wave-top::before,
.wave-top::after {
  border-bottom: 5px solid rgba(237, 30, 30, 1);
}

.wave-top::before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 10px;
  background-size: 20px 40px;
  background-image: radial-gradient(circle at 10px -15px, transparent 20px, rgba(237, 30, 30, 1) 21px);
}

.wave-top::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 15px;
  background-size: 40px 40px;
  background-image: radial-gradient(circle at 10px 26px, rgba(237, 30, 30, 1) 20px, transparent 21px);
}

.wave-mid {
  background-color: rgba(237, 30, 30, 1);
  height: 50px;
}

.wave-bottom {
  position: relative;
}

.wave-bottom::before,
.wave-bottom::after {
  border-top: 5px solid rgba(237, 30, 30, 1);
}

.wave-bottom::before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 10px;
  background-size: 20px 40px;
  background-image: radial-gradient(circle at 10px -15px, transparent 20px, #fff 21px);
}

.wave-bottom::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 15px;
  background-size: 40px 40px;
  background-image: radial-gradient(circle at 10px 26px, #fff 20px, transparent 21px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='wave-top'></div>
<div class="wave-mid"></div>
<div class="wave-bottom"></div></code>```

You can increase the height of the middle-div according to your need. Here I have kept it 50px

Body:
I'm trying to create a wavy top and bottom border like the image here

I tried recreating the same effect using the following code

.wave{
  background: white;
  height: 25px;
  position: relative;
}
.wave::before, .wave::after{
  border-bottom: 5px solid rgba(237, 30, 30, 1);
}
.wave::before{
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 12px;
  background-size: 20px 40px;
  background-image:
    radial-gradient(circle at 10px -15px, transparent 20px, rgba(237, 30, 30, 1) 21px);
}
.wave::after{
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 18px;
  background-size: 40px 40px;
  background-image:
    radial-gradient(circle at 10px 26px, rgba(237, 30, 30, 1) 20px, transparent 21px);
}

.wavebottom{
  background: rgba(237, 30, 30, 1);
  height: 25px;
  position: relative;
}
.wavebottom::before, .wave::after{
  border-bottom: 5px solid rgba(237, 30, 30, 1);
}
.wave::before{
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 12px;
  background-size: 20px 40px;
  background-image:
    radial-gradient(circle at 10px -15px, transparent 20px, white 21px);
}
.wavebottom::after{
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 18px;
  background-size: 40px 40px;
  background-image:
    radial-gradient(circle at 10px 26px, white 20px, transparent 21px);
}

Where I have the code in 3 divs.. first div has the wave class

second div has the background color and the content

and the third div has the wavebottom class

but I'm getting the results of the waves looking like that

I'm working on a page with the width of 1920px, I'm not sure how can I make this look the same like the first image

Body:
Try using this:

.wave-top {
  position: relative;
  margin-top: 20px;
}

.wave-top::before,
.wave-top::after {
  border-bottom: 5px solid rgba(237, 30, 30, 1);
}

.wave-top::before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 10px;
  background-size: 20px 40px;
  background-image: radial-gradient(circle at 10px -15px, transparent 20px, rgba(237, 30, 30, 1) 21px);
}

.wave-top::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 15px;
  background-size: 40px 40px;
  background-image: radial-gradient(circle at 10px 26px, rgba(237, 30, 30, 1) 20px, transparent 21px);
}

.wave-mid {
  background-color: rgba(237, 30, 30, 1);
  height: 50px;
}

.wave-bottom {
  position: relative;
}

.wave-bottom::before,
.wave-bottom::after {
  border-top: 5px solid rgba(237, 30, 30, 1);
}

.wave-bottom::before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 10px;
  background-size: 20px 40px;
  background-image: radial-gradient(circle at 10px -15px, transparent 20px, #fff 21px);
}

.wave-bottom::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 15px;
  background-size: 40px 40px;
  background-image: radial-gradient(circle at 10px 26px, #fff 20px, transparent 21px);
}

<div class='wave-top'></div>
<div class="wave-mid"></div>
<div class="wave-bottom"></div>

You can increase the height of the middle-div according to your need. Here I have kept it 50px


问:
FileSystemWatcher - Reading last line of file after update?
I'm trying to write a simple console application that waits for a change to a file then reads just the last line of that file. The file watcher works and the change event fires.  But I'm struggling to work out how read from the file.

```<code>        static void Main(string[] args)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Path = "E:\\myFilePath";
            watcher.Filter = "";
            watcher.EnableRaisingEvents = true;
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            Console.ReadKey();
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(File.ReadLines(e.FullPath).Last());
        }
</code>```

when testing (editing the file in notepad) it will work once, then after a second edit I get the error...

System.IO.IOException: 'The process cannot access the file '' because
  it is being used by another process.'

答:
I still ran into problems using lines.GetEnumerator().Dispose();

You can add a pause before opening the file, just chose your poison for doing so.

```<code>    static void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        for (int x = 0; x <= 500000; x++)
        {
            int t = x;
        }
        Console.WriteLine(File.ReadLines(e.FullPath).Last());
    }
</code>```

I tried using SreamReader too but still ran into the same problem.

```<code>        // Does not work
        using (StreamReader r = new StreamReader(e.FullPath))
        {
            while (r.EndOfStream == false)
            {
                m = r.ReadLine();
            }
            r.Close();
        }
        Console.WriteLine("{0}\n", m);
</code>```

Body:
I'm trying to write a simple console application that waits for a change to a file then reads just the last line of that file. The file watcher works and the change event fires.  But I'm struggling to work out how read from the file.

        static void Main(string[] args)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Path = "E:\\myFilePath";
            watcher.Filter = "";
            watcher.EnableRaisingEvents = true;
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            Console.ReadKey();
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(File.ReadLines(e.FullPath).Last());
        }

when testing (editing the file in notepad) it will work once, then after a second edit I get the error...

System.IO.IOException: 'The process cannot access the file '' because
  it is being used by another process.'

Body:
I still ran into problems using lines.GetEnumerator().Dispose();

You can add a pause before opening the file, just chose your poison for doing so.

    static void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        for (int x = 0; x <= 500000; x++)
        {
            int t = x;
        }
        Console.WriteLine(File.ReadLines(e.FullPath).Last());
    }

I tried using SreamReader too but still ran into the same problem.

        // Does not work
        using (StreamReader r = new StreamReader(e.FullPath))
        {
            while (r.EndOfStream == false)
            {
                m = r.ReadLine();
            }
            r.Close();
        }
        Console.WriteLine("{0}\n", m);


问:
Graphvis output is not shown in Colab
Colab is not showing the output of a Graphviz plot (for example https://graphviz.readthedocs.io/en/stable/examples.html). How can I achieve it simply in Colab? I even tried to plot it's generated PDF file but it's not straightforward.</p>

答:
You don't need to call g.view(). Just end the code with g is enough, like this:

```<code>g = Digraph('G')
g.edge('Hello', 'World')
g
</code>```

Here's a minimal example notebook

Title: Graphvis output is not shown in Colab

Body:
You don't need to call g.view(). Just end the code with g is enough, like this:

g = Digraph('G')
g.edge('Hello', 'World')
g

Here's a minimal example notebook


问:
Uncaught TypeError: Cannot read property 'checked' of undefined Javascript
The first time the loop runs, there's no problem. The get's shown when the loop ends, and every other time the loop runs.
The .checked property works fine, to my knowledge, there's just the error...
Does someone know what to do about this?
My background in javascript isn't that broad, and I'm still learning.
Thanks you.

I have already tried .checked === true and
             .checked == checked
              ...

In the code snippet below dishes is an array of radiobuttons.

```<code>    for (i = 0; i <= dishes.length; i++) {
       if (dishes[i].checked) {
         switch (dishesClass) {
        .........
         }
       }
     }
</code>```

I expect no error in the console, but there are multiple. Every time the loop ends, the console states the same error.

Uncaught TypeError: Cannot read property 'checked' of undefined

答: As pointed by @Alicia, the problem is in your loop condition i<= whereas it should be i<. The array index i tries to access an element outside of the array bounds on the last iteration. Array's index starts at zero and ends at the array length - 1

Body:
The first time the loop runs, there's no problem. The get's shown when the loop ends, and every other time the loop runs.
The .checked property works fine, to my knowledge, there's just the error...
Does someone know what to do about this?
My background in javascript isn't that broad, and I'm still learning.
Thanks you.

I have already tried .checked === true and
             .checked == checked
              ...

In the code snippet below dishes is an array of radiobuttons.

    for (i = 0; i <= dishes.length; i++) {
       if (dishes[i].checked) {
         switch (dishesClass) {
        .........
         }
       }
     }

I expect no error in the console, but there are multiple. Every time the loop ends, the console states the same error.

Uncaught TypeError: Cannot read property 'checked' of undefined


问:
What is the Pythonic ordering of function definitions?
Is it this one?

```<code>def main():
    a()

def a():
    b()

def b():
    print("foo")

if __name__ == "__main__":
    main()
</code>```

Or this one?

```<code>def b():
    print("foo")

def a():
    b()

def main():
    a()

if __name__ == "__main__":
    main()
</code>```

They both work, but what is the more Pythonic or recommended way of ordering function definitions?

I feel like this is a silly and useless question (since they both achieve the same thing), but at the same time it bothers me that both choices seem equally sane and it's hard to pick one, and I'm wondering if there's a convention between one or the other in the Python community, or something in the PEPs that touches on this.

答: I don’t think there’s anything discussing this subject in the docs. I would just say pick your preferred order and stick with it throughout your project. It’s mostly a question of readability - choose whichever suits you and the other developers working with you.</p>

Body:
Is it this one?

def main():
    a()

def a():
    b()

def b():
    print("foo")

if __name__ == "__main__":
    main()

Or this one?

def b():
    print("foo")

def a():
    b()

def main():
    a()

if __name__ == "__main__":
    main()

They both work, but what is the more Pythonic or recommended way of ordering function definitions?

I feel like this is a silly and useless question (since they both achieve the same thing), but at the same time it bothers me that both choices seem equally sane and it's hard to pick one, and I'm wondering if there's a convention between one or the other in the Python community, or something in the PEPs that touches on this.


问:
check how many times string contains character 'g' in eligible string
How we can check any string that contains any character how may time....
example:
engineering  is a string contains how many times 'g' in complete string

答:
You can try Java-8 way. Easy, simple and more readable.</p>

```<code>long countOfA = str.chars().filter(ch -> ch == 'g').count();
</code>```

Body:
You can try Java-8 way. Easy, simple and more readable.

long countOfA = str.chars().filter(ch -> ch == 'g').count();


问:
How to get only one answer if there is no match after loop
My code has a for loop in array and has if statement, and I want to get only one answer if there is no match.

```<code>for (int i = 0; i < arr.Length; i++)
{
    if (arr[i].GetSomeValue() >= 1 && i].GetSomeValue() <= 5)
        Console.WriteLine(arr[i]);
    else
       Console.WriteLine("No data");
}
</code>```

However, I get these:

```<code>No data
No data
No data
No data
</code>```

I want only one "No data" if there is no match.
I tried adding

```<code>    else break;
}
Console.WriteLine("No data");
</code>```

But it does not work.

How do I get what I want?

答:
I suggest Use flag like This Code :</p>

```<code>bool flag = false ;

for (int i = 0; i < arr.Length; i++)
{
    if (arr[i].GetSomeValue() >= 1 && arr[i].GetSomeValue() <= 5)
    {
        Console.WriteLine(arr[i]);
        flag=true;
    }
}

if(!flag)
{
    Console.WriteLine("No data");
}
</code>```

Body:
My code has a for loop in array and has if statement, and I want to get only one answer if there is no match.

for (int i = 0; i < arr.Length; i++)
{
    if (arr[i].GetSomeValue() >= 1 && i].GetSomeValue() <= 5)
        Console.WriteLine(arr[i]);
    else
       Console.WriteLine("No data");
}

However, I get these:

No data
No data
No data
No data

I want only one "No data" if there is no match.
I tried adding

    else break;
}
Console.WriteLine("No data");

But it does not work.

How do I get what I want?

Body:
I suggest Use flag like This Code :

bool flag = false ;

for (int i = 0; i < arr.Length; i++)
{
    if (arr[i].GetSomeValue() >= 1 && arr[i].GetSomeValue() <= 5)
    {
        Console.WriteLine(arr[i]);
        flag=true;
    }
}

if(!flag)
{
    Console.WriteLine("No data");
}