问:
Rails Carierwave deafult_url doesn't return fallback image
I need to render fallback img if object doesnt have own.
The Carierwave uploader looks like:

```<code> def default_url(*args)
   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
 end
</code>```

I'm render a img like: <%= image_tag @teams.last.team_img %>

But the pages show only text: "Default"

JS console says: http://localhost:3000/images/fallback/default.png 404 (Not Found)

But I created dir fallback in app/assets/images and put there dafault.png

答:
The Rails's assets compile all static assets into path /assets

So, for your situation, the default_url pointing to wrong URL. It should be:

```<code> def default_url(*args)
   "/assets/fallback/" + [version_name, "default.png"].compact.join('_')
 end
</code>```

Body:
I need to render fallback img if object doesnt have own.
The Carierwave uploader looks like:

 def default_url(*args)
   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
 end

I'm render a img like: <%= image_tag @teams.last.team_img %>

But the pages show only text: "Default"

JS console says: http://localhost:3000/images/fallback/default.png 404 (Not Found)

But I created dir fallback in app/assets/images and put there dafault.png

Body:
The Rails's assets compile all static assets into path /assets

So, for your situation, the default_url pointing to wrong URL. It should be:

 def default_url(*args)
   "/assets/fallback/" + [version_name, "default.png"].compact.join('_')
 end


来源: stackexchange

问:
router.navigate changes url but the view won't change
i am having trouble when using router.navigate on a click listener for a marker in googlemaps. The page url changes to the desired path but the outlet wont change the view.

loadEquipos(locacion:  Locacion) {
    for (let i = 0; i < this.equipos.length; i++) {
      if(this.equipos[i].idLocacion === locacion.id) {
        const marker = new google.maps.Marker({
          position: new google.maps.LatLng(this.equipos[i].mapData.center.lat, this.equipos[i].mapData.center.lng),
          map: map,
          label: {
            color: 'black',
            fontWeight: 'bold',
            text: this.equipos[i].nombre,
          },
          idEquipo: this.equipos[i].id
        });
        google.maps.event.addListener(marker, 'click',() => {
          this.router.navigate(['/tanque', marker.idEquipo]);
        });
      }
    }
  }```
</div>
</div>
</p>

<p>Thats the method in witch the event listener is added.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>RouterModule.forRoot([
      {
        path: 'admLocaciones',
        component: AdmLocacionesComponent
      },
      {
        path: '',
        redirectTo: '/inicio',
        pathMatch: 'full'
      },
      {
        path: 'inicio',
        component: InicioComponent
      },
      {
        path: 'buscarLocacion/:id',
        component: BuscarLocacionComponent
      },
      {
        path: 'editarLocacion/:id',
        component: EditarLocacionComponent
      },
      {
        path: 'nuevaLocacion',
        component: NuevaLocacionComponent
      },
      {
        path: 'admRegiones',
        component: AdmRegionesComponent
      },
      {
        path: 'locacion/:id',
        component: LocacionComponent
      },
      {
        path: 'tableroTanque',
        component: TableroTanqueComponent
      },
      {
        path: 'tanque/:id',
        component: TanqueComponent
      }
    ])
  ],</code>```

and those are my paths, any other navigation works perfectly fine inside the app.

Thanks for your help.

答:
I ran into the same problem. As it turns out, if the params don't change in the path, then the component won't be reinitialized. Since your path is 'tanque/:id' you need to use Observables to detect when the param has changed and trigger an update.

The Angular Router tutorial has a great example of using routes with params and how to incorporate Observables: https://angular.io/guide/router

ContentLicense: CC BY-SA 3.0

Body:
i am having trouble when using router.navigate on a click listener for a marker in googlemaps. The page url changes to the desired path but the outlet wont change the view.

loadEquipos(locacion:  Locacion) {
    for (let i = 0; i < this.equipos.length; i++) {
      if(this.equipos[i].idLocacion === locacion.id) {
        const marker = new google.maps.Marker({
          position: new google.maps.LatLng(this.equipos[i].mapData.center.lat, this.equipos[i].mapData.center.lng),
          map: map,
          label: {
            color: 'black',
            fontWeight: 'bold',
            text: this.equipos[i].nombre,
          },
          idEquipo: this.equipos[i].id
        });
        google.maps.event.addListener(marker, 'click',() => {
          this.router.navigate(['/tanque', marker.idEquipo]);
        });
      }
    }
  }

Thats the method in witch the event listener is added.

RouterModule.forRoot([
      {
        path: 'admLocaciones',
        component: AdmLocacionesComponent
      },
      {
        path: '',
        redirectTo: '/inicio',
        pathMatch: 'full'
      },
      {
        path: 'inicio',
        component: InicioComponent
      },
      {
        path: 'buscarLocacion/:id',
        component: BuscarLocacionComponent
      },
      {
        path: 'editarLocacion/:id',
        component: EditarLocacionComponent
      },
      {
        path: 'nuevaLocacion',
        component: NuevaLocacionComponent
      },
      {
        path: 'admRegiones',
        component: AdmRegionesComponent
      },
      {
        path: 'locacion/:id',
        component: LocacionComponent
      },
      {
        path: 'tableroTanque',
        component: TableroTanqueComponent
      },
      {
        path: 'tanque/:id',
        component: TanqueComponent
      }
    ])
  ],

and those are my paths, any other navigation works perfectly fine inside the app.

Thanks for your help.


问:
Syntax error in scheme
I have a recursive function in Scheme that returns when I return it:
lambda: expected only one expression for the function body, but found 3 extra parts

What I am trying to do is to call this function with value in the list 'lst'.  This recursively gets all possible partitions in the list,

答:
A define must be the first expression in a lambda. Thus your defien are ill placed.

In addition you cond ended after the first term such that the rest of the code would be executed unconditionally and the cond being dead code as it did not change the outcome.

The closest correct syntax with minimal changes would be:

```<code>(define glcm
  (lambda (lst s1 s2)
    (cond
      [(null? lst) (lcm s1 s2)]
      [else
       (let ([a (glcm (cdr lst) (+ s1 (car lst)) s2)]
             [b (glcm (cdr lst) s1 (+ s2 (car lst)))])
         (if (< a b) a b))])))
</code>```

Alternative, because let is a lambda call you can define inside a let:

```<code>(define glcm
  (lambda (lst s1 s2)
    (cond
      [(null? lst) (lcm s1 s2)]
      [else
       (let ()
         (define a (glcm (cdr lst) (+ s1 (car lst)) s2))
         (define b (glcm (cdr lst) s1 (+ s2 (car lst))))
         (if (< a b) a b))])))
</code>```

However I would have done it like this:

```<code>(define (glcm lst s1 s2)
  (if (null? lst)
      (lcm s1 s2)
      (min (glcm (cdr lst) (+ s1 (car lst)) s2)
           (glcm (cdr lst) s1 (+ s2 (car lst))))))
</code>```

They most likely become very similar object code. Use whatever you think is most readable for you.

Notice I use [...]. These are really indistinguishable with (...) so it's only a visual queue to make it more readable. Before R5RS you'd have to only use (...) to be compatible. DrRacket IDE even rewrites the ending parenthesis to match the type of the matching beginning parenthesis.

Title: Syntax error in scheme

Body:
A define must be the first expression in a lambda. Thus your defien are ill placed.

In addition you cond ended after the first term such that the rest of the code would be executed unconditionally and the cond being dead code as it did not change the outcome.

The closest correct syntax with minimal changes would be:

(define glcm
  (lambda (lst s1 s2)
    (cond
      [(null? lst) (lcm s1 s2)]
      [else
       (let ([a (glcm (cdr lst) (+ s1 (car lst)) s2)]
             [b (glcm (cdr lst) s1 (+ s2 (car lst)))])
         (if (< a b) a b))])))

Alternative, because let is a lambda call you can define inside a let:

(define glcm
  (lambda (lst s1 s2)
    (cond
      [(null? lst) (lcm s1 s2)]
      [else
       (let ()
         (define a (glcm (cdr lst) (+ s1 (car lst)) s2))
         (define b (glcm (cdr lst) s1 (+ s2 (car lst))))
         (if (< a b) a b))])))

However I would have done it like this:

(define (glcm lst s1 s2)
  (if (null? lst)
      (lcm s1 s2)
      (min (glcm (cdr lst) (+ s1 (car lst)) s2)
           (glcm (cdr lst) s1 (+ s2 (car lst))))))

They most likely become very similar object code. Use whatever you think is most readable for you.

Notice I use [...]. These are really indistinguishable with (...) so it's only a visual queue to make it more readable. Before R5RS you'd have to only use (...) to be compatible. DrRacket IDE even rewrites the ending parenthesis to match the type of the matching beginning parenthesis.


问:
cut processing in prolog
can somebody please explain the processing of the following command:

```<code>max(X,Y,Max) :- X >= Y, !, Max = X ; Max = Y.
</code>```

I can't understand, what exactly does it mean ! in the middle, thanks in advance

答:
I think the answered has been given quite clear.

Well, I just conclude a bit from your sample. Here, we can "assume" that there are two rules there, which are

```<code>max(X, Y, Max) :- X >= Y, !, Max = X.
max(X, Y, Max) :- Max = Y.
</code>```

Why is it necessary to put that !? It is because without that, you can query something like max(5,4,Max) and the result would be

```<code>Max = 5;
Max = 4;
</code>```

Why does it happen? Because Prolog system finds every possible answers. When the ! comes, it will stop finding the other(s).

ContentLicense: CC BY-SA 2.5

Title: cut processing in prolog

Body:
can somebody please explain the processing of the following command:

max(X,Y,Max) :- X >= Y, !, Max = X ; Max = Y.

I can't understand, what exactly does it mean ! in the middle, thanks in advance

Body:
I think the answered has been given quite clear.

Well, I just conclude a bit from your sample. Here, we can "assume" that there are two rules there, which are

max(X, Y, Max) :- X >= Y, !, Max = X.
max(X, Y, Max) :- Max = Y.

Why is it necessary to put that !? It is because without that, you can query something like max(5,4,Max) and the result would be

Max = 5;
Max = 4;

Why does it happen? Because Prolog system finds every possible answers. When the ! comes, it will stop finding the other(s).


问:
under what application does dev_appserver.py runs?
I'm not able to understand how
google-cloud-sdk/bin/dev_appserver.py helloworld runs automatically.

I mean to ask that it should run under python command as it is a python file.

is there something added to path??

答:
Yes, dev_appserver.py is an executable python script. If you launch it by itself it will be executed under whichever python is the default one in your environment, see its 1st line:

```<code>#!/usr/bin/env python
</code>```

If you want you can also execute it with a specific python version (it has to be a python 2.7 one, though, the only one supported by GAE standard environment):

```<code>/specific_path/python  /path_to/google-cloud-sdk/bin/dev_appserver.py helloworld
</code>```

Body:
Yes, dev_appserver.py is an executable python script. If you launch it by itself it will be executed under whichever python is the default one in your environment, see its 1st line:

#!/usr/bin/env python

If you want you can also execute it with a specific python version (it has to be a python 2.7 one, though, the only one supported by GAE standard environment):

/specific_path/python  /path_to/google-cloud-sdk/bin/dev_appserver.py helloworld


问:
Windows .batch Choice command always chooses the same choice no matter input
I'm doing a project to help myself learn batch a little better. I have code which is meant to be a "UI" of sorts.

The snippet I have an issue with is this:

```<code>:install_check
if exist UI (
echo UI is already installed; reinstall?
CHOICE
if Errorlevel 1 goto :del
if Errorlevel 2 goto :return
cls && goto :install_check
)
goto :install_yes
</code>```

I know the naming conventions and some of the coding stuff isn't perfect, but I really see no reason why every time it runs it goes to :del no matter what I type in for choice.

I've changed the choice switches and moved it around to be all in one line but it still doesn't want to work. The if that it is nested in is meant to check if a file is present on the computer, so it is a requirement but also may be the issue?

I tried looking around on this site but nothing will help my issue, any help is gladly accepted!!

答:
As a solution has already been determined, the following example, (using your existing label names), restructures your code a little:

:install_check
ClS
If Not Exist "UI" GoTo install_yes
Choice /M "UI is already installed; reinstall"
If Errorlevel 2 GoTo return
GoTo del
```

If the next line/label in your code is :del, you may also remove line six.

If the name UI belonged to a directory instead of a file then you'd change the third line to If Not Exist "UI\" GoTo install_yes.

Body:
I'm doing a project to help myself learn batch a little better. I have code which is meant to be a "UI" of sorts.

The snippet I have an issue with is this:

:install_check
if exist UI (
echo UI is already installed; reinstall?
CHOICE
if Errorlevel 1 goto :del
if Errorlevel 2 goto :return
cls && goto :install_check
)
goto :install_yes

I know the naming conventions and some of the coding stuff isn't perfect, but I really see no reason why every time it runs it goes to :del no matter what I type in for choice.

I've changed the choice switches and moved it around to be all in one line but it still doesn't want to work. The if that it is nested in is meant to check if a file is present on the computer, so it is a requirement but also may be the issue?

I tried looking around on this site but nothing will help my issue, any help is gladly accepted!!

Body:
As a solution has already been determined, the following example, (using your existing label names), restructures your code a little:

:install_check
ClS
If Not Exist "UI" GoTo install_yes
Choice /M "UI is already installed; reinstall"
If Errorlevel 2 GoTo return
GoTo del

If the next line/label in your code is :del, you may also remove line six.

If the name UI belonged to a directory instead of a file then you'd change the third line to If Not Exist "UI\" GoTo install_yes.


问:
WebRTC with SignalR only working on local network
I'm currently looking for a nice asp.net implementation of webrtc for video chat between two people.
I found the following example code that I tried and edited but my understanding in webrtc isn't good enough to see why the code only works on local networks and not with people outside of the network.

The project: https://github.com/mgiuliani/webrtc-video-chat

There is also an issue in the github that tells the same problem but I can't find out what the problem is.

答:
The solution was two things.
First use a TURN server. A Stun server wasn't good enough for my connection. (has something to do with firewalls etc as far as I understand).

Secondly I needed to wait adding the icecandidates till the remotedescription was set, felixhagspiel had a great tutorial on that here:

http://blog.felixhagspiel.de/index.php/posts/create-your-own-videochat-application-with-html-and-javascript

Look at the part with 'otherSDP'.


问:
How to create test cases in VSTS in a programmatic manner?
I have a unit test project for client side (angular) application written using jasmine framework.

In C# unit test projects, there is a possibility to link each test method with a test case in visual studio test explorer.

Since it's not possible to achieve the same for test methods/suites in unit test project for client side (angular) application which is written using jasmine framework, I was looking at the possibility of creating a tool to create test cases in VSTS by programming. And to map each client side unit test method to a test case in VSTS.

Can anyone help me with the API's and idea on how this can be done?

答:
The REST API for Test Management is pretty extensive and documented clearly over at the VSTS documentation website.

The API is separated into two parts:

The Test Management API for creating Test Plans and Test Suites and to link items together.

The Work Item API for creating and updating Test Cases (which are essentially just a work item).


问:
Creating new dataframes by subsetting and reference two dataframes in R
I have two data sets. One with employee preferences and one with a list of potential matches. For each employee, I want to find the matches and create a new dataset for each. The dataset can be one large comprehensive set that can then be split by person, or separate ones from the beginning.

```<code> df1:

> emplid= c("empl1","empl2","empl3")
> c1 = c("HR", "Finance", "HR")
>  c2 = c("x", "y", "z")
>  c3 = c("a","b","C")
>  df1 = data.frame(emplid, c1, c2, c3)

df2:
>  job = c("job1", "job2", "job3", "job4")
>  c4 = c("HR", "HR", "Finance", "Finance")
>  c5 = c("x", "x", "y", "z")
>  c6 = c("a","b", "b","c")
>  df2 = data.frame(job, c4, c5, c6)
</code>```

The result would be

```<code>emplid      job          c4     c5        c6
empl1       job1         HR      x        a
empl3       job4         Finance y        b
</code>```

The above result could be combined, but ultimately I will split it up.

I've only successfully been able to do this when I have only one row in the first dataframe, but that will not be the case. I've tried loops but with no success.

答:
I'd suggest renaming your columns so that they match. Here's an example of what I would do:</p>

```<code>emplid= c("empl1","empl2","empl3")
c1 = c("HR", "Finance", "HR")
c2 = c("x", "y", "x")
c3 = c("a","b","a")
df1 = data.frame(emplid, c1, c2, c3)

job = c("job1", "job2", "job3", "job4")
c1 = c("HR", "HR", "Finance", "Finance")
c2 = c("x", "x", "y", "z")
c3 = c("a","b", "b","c")
df2 = data.frame(job, c1, c2, c3)

temp = df1 %>%
  group_by(c1,c2,c3)

df2 = df2 %>%
  right_join(temp, by = c('c1','c2','c3'))
</code>```

Body:
I have two data sets. One with employee preferences and one with a list of potential matches. For each employee, I want to find the matches and create a new dataset for each. The dataset can be one large comprehensive set that can then be split by person, or separate ones from the beginning.

 df1:

> emplid= c("empl1","empl2","empl3")
> c1 = c("HR", "Finance", "HR")
>  c2 = c("x", "y", "z")
>  c3 = c("a","b","C")
>  df1 = data.frame(emplid, c1, c2, c3)

df2:
>  job = c("job1", "job2", "job3", "job4")
>  c4 = c("HR", "HR", "Finance", "Finance")
>  c5 = c("x", "x", "y", "z")
>  c6 = c("a","b", "b","c")
>  df2 = data.frame(job, c4, c5, c6)

The result would be

emplid      job          c4     c5        c6
empl1       job1         HR      x        a
empl3       job4         Finance y        b

The above result could be combined, but ultimately I will split it up.

I've only successfully been able to do this when I have only one row in the first dataframe, but that will not be the case. I've tried loops but with no success.

Body:
I'd suggest renaming your columns so that they match. Here's an example of what I would do:

emplid= c("empl1","empl2","empl3")
c1 = c("HR", "Finance", "HR")
c2 = c("x", "y", "x")
c3 = c("a","b","a")
df1 = data.frame(emplid, c1, c2, c3)

job = c("job1", "job2", "job3", "job4")
c1 = c("HR", "HR", "Finance", "Finance")
c2 = c("x", "x", "y", "z")
c3 = c("a","b", "b","c")
df2 = data.frame(job, c1, c2, c3)

temp = df1 %>%
  group_by(c1,c2,c3)

df2 = df2 %>%
  right_join(temp, by = c('c1','c2','c3'))


问:
Python: 'Turtle' object has no attribute 'bye'
I am trying to write turtle code where something is triggered and the turtle window closes, so I try to use turtle.bye() but I keep getting the error:

```<code>    Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 1699, in
__call__
    return self.func(*args)
  File "C:\Program Files\Python36\lib\turtle.py", line 686, in eventfun
    fun()
  File "E:\Home made game\Chapter 1 Log Cabin.py", line 346, in k1
    player.bye()
AttributeError: 'Turtle' object has no attribute 'bye'
</code>```

答:
bye() is a method of the Screen singleton instance, not Turtle.  It is also mapped to a top level function in the turtle package.  It will not work with a Turtle instance.  You can invoke it several ways:

```<code>import turtle

turtle.Screen().bye()  # not a turtle instance, the turtle package

turtle.bye()  # not a turtle instance, the turtle package

turtle.getscreen().bye()  # not a turtle instance, the turtle package

yertle = turtle.Turtle()
yertle.getscreen().bye()  # turtle instance gets screen singleton to invoke bye()
</code>```

Once you call bye() the turtle world shuts down in a manner that's not meant to be restarted.

Body:
I am trying to write turtle code where something is triggered and the turtle window closes, so I try to use turtle.bye() but I keep getting the error:

    Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 1699, in
__call__
    return self.func(*args)
  File "C:\Program Files\Python36\lib\turtle.py", line 686, in eventfun
    fun()
  File "E:\Home made game\Chapter 1 Log Cabin.py", line 346, in k1
    player.bye()
AttributeError: 'Turtle' object has no attribute 'bye'

Body:
bye() is a method of the Screen singleton instance, not Turtle.  It is also mapped to a top level function in the turtle package.  It will not work with a Turtle instance.  You can invoke it several ways:

import turtle

turtle.Screen().bye()  # not a turtle instance, the turtle package

turtle.bye()  # not a turtle instance, the turtle package

turtle.getscreen().bye()  # not a turtle instance, the turtle package

yertle = turtle.Turtle()
yertle.getscreen().bye()  # turtle instance gets screen singleton to invoke bye()

Once you call bye() the turtle world shuts down in a manner that's not meant to be restarted.


问:
Attributes of text above specific bar with ios-charts
How can I change attributes (e.g. font size, text color, etc...) of text above a specific bar in a BarChart?

In this example, I want "-$5,000.00" in red and to increase the font size of every text above bars.

Here's some code:

```<code>@IBOutlet weak var barChartView: BarChartView!

// init barChartView --------------------------------------
barChartView.descriptionText = ""

barChartView.legend.enabled = false

// grid lines
barChartView.xAxis.drawAxisLineEnabled = false
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.leftAxis.drawAxisLineEnabled = false
barChartView.leftAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawAxisLineEnabled = false
barChartView.rightAxis.drawGridLinesEnabled = false

// X-axis line
barChartView.xAxis.drawAxisLineEnabled = true
barChartView.xAxis.axisLineColor = axisGridsAndLabelsColor

// X-axis labels
barChartView.xAxis.labelTextColor = axisGridsAndLabelsColor
barChartView.xAxis.labelPosition = .Bottom

// Y-axis labels
accountsBarChartView.leftAxis.labelTextColor = axisGridsAndLabelsColor
accountsBarChartView.rightAxis.drawLabelsEnabled = false
//---------------------------------------------------------

// bar chart's data
var dataPoints = [String]()
var values = [Double]()
var colors = [UIColor]()

// build bar chart's data...

// dataEntries and barChartDataSet
var dataEntries = [ChartDataEntry]()
for i in 0..<dataPoints.count
{
    let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
    dataEntries.append(dataEntry)
}

let barChartDataSet = BarChartDataSet(yVals: dataEntries, label: "")
barChartDataSet.colors = colors

// valueFormatter
let currencyNumberFormatter = NSNumberFormatter()
currencyNumberFormatter.numberStyle = .CurrencyStyle
currencyNumberFormatter.minimumFractionDigits = 2
currencyNumberFormatter.maximumFractionDigits = 2

barChartDataSet.valueFormatter = currencyNumberFormatter

// barChartData
let barChartData = BarChartData(xVals: dataPoints, dataSet: barChartDataSet)
barChartView.data = barChartData
</code>```

答:
If you want to change the text attributes of labels below bars you can use:

barChartView.xAxis.labelFont = UIFont.systemFont(ofSize: 5)

barChartView.xAxis.labelTextColor = UIColor.red

Body:
How can I change attributes (e.g. font size, text color, etc...) of text above a specific bar in a BarChart?

In this example, I want "-$5,000.00" in red and to increase the font size of every text above bars.

Here's some code:

@IBOutlet weak var barChartView: BarChartView!

// init barChartView --------------------------------------
barChartView.descriptionText = ""

barChartView.legend.enabled = false

// grid lines
barChartView.xAxis.drawAxisLineEnabled = false
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.leftAxis.drawAxisLineEnabled = false
barChartView.leftAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawAxisLineEnabled = false
barChartView.rightAxis.drawGridLinesEnabled = false

// X-axis line
barChartView.xAxis.drawAxisLineEnabled = true
barChartView.xAxis.axisLineColor = axisGridsAndLabelsColor

// X-axis labels
barChartView.xAxis.labelTextColor = axisGridsAndLabelsColor
barChartView.xAxis.labelPosition = .Bottom

// Y-axis labels
accountsBarChartView.leftAxis.labelTextColor = axisGridsAndLabelsColor
accountsBarChartView.rightAxis.drawLabelsEnabled = false
//---------------------------------------------------------

// bar chart's data
var dataPoints = [String]()
var values = [Double]()
var colors = [UIColor]()

// build bar chart's data...

// dataEntries and barChartDataSet
var dataEntries = [ChartDataEntry]()
for i in 0..<dataPoints.count
{
    let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
    dataEntries.append(dataEntry)
}

let barChartDataSet = BarChartDataSet(yVals: dataEntries, label: "")
barChartDataSet.colors = colors

// valueFormatter
let currencyNumberFormatter = NSNumberFormatter()
currencyNumberFormatter.numberStyle = .CurrencyStyle
currencyNumberFormatter.minimumFractionDigits = 2
currencyNumberFormatter.maximumFractionDigits = 2

barChartDataSet.valueFormatter = currencyNumberFormatter

// barChartData
let barChartData = BarChartData(xVals: dataPoints, dataSet: barChartDataSet)
barChartView.data = barChartData


问:
R: Simple Random Sample of Massive Dataframe
I have a massive (8GB) dataset, which I am simply unable to read into R using my existing setup.  Attempting to use fread on the dataset crashes the R session immediately, and attempting to read in random lines from the underlying file was insufficient because: (1) I don't have a good way of knowing that total number of rows in the dataset; (2) my method was not a true "random sampling."

These attempts to get the number of rows have failed (they take as long as simply reading the data in:

length(count.fields("file.dat", sep = "|"))

read.csv.sql("file.dat", header = FALSE, sep = "|", sql = "select
count(*) from file")

Is there any way via R or some other program to generate a random sample from a large underlying dataset?

Potential idea: Is it possible, given a "sample" of the first several rows to get a sense of the average amount of information contained on a per-row basis.  And then back-out how many rows there must be given the size of the dataset (8 GB)?  This wouldn't be accurate, but it might give a ball-park figure that I could just under-cut.

答:
Here's one option, using the ability of fread to accept a shell command that preprocesses the file as its input.  Using this option we can run a gawk script to extract the required lines. Note you may need to install gawk if it is not already on your system. If you have awk instead on your system, you can use that instead.

First lets create a dummy file to test on:

```<code>library(data.table)
dt = data.table(1:1e6, sample(letters, 1e6, replace = TRUE))
write.csv(dt, 'test.csv', row.names = FALSE)
</code>```

Now we can use the shell command wc to find how many lines there are in the file:

```<code>nl = read.table(pipe("wc -l test.csv"))[[1]]
</code>```

Take a sample of line numbers and write them (in ascending order) to a temp file which makes them accessible easily to gawk.

```<code>N = 20 # number of lines to sample
sample.lines = sort(sample(2:nl, N)) #start sample at line 2 to exclude header
cat(paste0(sample.lines, collapse = '\n'), file = "lines.txt")
</code>```

Now we are ready to read in the sample using fread and gawk (based on this answer). You can also try some of the other gawk scripts in this linked question which could possibly be be more efficient on very large data.

```<code>dt.sample = fread("gawk 'NR == FNR {nums[$1]; next} FNR in nums' lines.txt test.csv")
</code>```

Body:
Here's one option, using the ability of fread to accept a shell command that preprocesses the file as its input.  Using this option we can run a gawk script to extract the required lines. Note you may need to install gawk if it is not already on your system. If you have awk instead on your system, you can use that instead.

First lets create a dummy file to test on:

library(data.table)
dt = data.table(1:1e6, sample(letters, 1e6, replace = TRUE))
write.csv(dt, 'test.csv', row.names = FALSE)

Now we can use the shell command wc to find how many lines there are in the file:

nl = read.table(pipe("wc -l test.csv"))[[1]]

Take a sample of line numbers and write them (in ascending order) to a temp file which makes them accessible easily to gawk.

N = 20 # number of lines to sample
sample.lines = sort(sample(2:nl, N)) #start sample at line 2 to exclude header
cat(paste0(sample.lines, collapse = '\n'), file = "lines.txt")

Now we are ready to read in the sample using fread and gawk (based on this answer). You can also try some of the other gawk scripts in this linked question which could possibly be be more efficient on very large data.

dt.sample = fread("gawk 'NR == FNR {nums[$1]; next} FNR in nums' lines.txt test.csv")


问:
Bootstrap 4.0.0-Beta 2 Navbar Multi-Column Dropdown Menu
I'm trying to create a navbar based on Bootstrap 4.0.0-Beta 2 wherein the elements are right-aligned. One of the elements is a multi-column dropdown. I got as far as the code below (from bootstrap's website), but I can't seem to make it look right when in full page view. The dropdown is not showing properly as I would have wanted. You can see for yourself if you try the snippet.

    <!doctype html>

        <title>Bootstrap Navbar</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

      Navbar
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home (current)

            Link

              Dropdown

      Link 1
      Link 2
      Link 3

      Link 4
      Link 5
      Link6

      Link 7
      Link 8
      Link 9

            Disabled

        <form class="form-inline my-2 my-lg-0">
          <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>

    ```

Body:
    <!doctype html>
    <html lang="en">
      <head>
        <title>Bootstrap Navbar</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
      </head>
      <body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item active">
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Dropdown
            </a>
            <div class="dropdown-menu" style="width:300px" aria-labelledby="navbarDropdown">
   <div class="container container-sm">
    <div class="row">
     <div class="col-sm-4">
      <a class="dropdown-item" href="#">Link 1</a>
      <a class="dropdown-item" href="#">Link 2</a>
      <a class="dropdown-item" href="#">Link 3</a>
     </div>
     <div class="col-sm-4">
      <a class="dropdown-item" href="#">Link 4</a>
      <a class="dropdown-item" href="#">Link 5</a>
      <a class="dropdown-item" href="#">Link6</a>
     </div>
     <div class="col-sm-4">
      <a class="dropdown-item" href="#">Link 7</a>
      <a class="dropdown-item" href="#">Link 8</a>
      <a class="dropdown-item" href="#">Link 9</a>
     </div>
    </div>
   </div>
            </div>
          </li>
          <li class="nav-item">
            <a class="nav-link disabled" href="#">Disabled</a>
          </li>
        </ul>
        <form class="form-inline my-2 my-lg-0">
          <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>
      </div>
    </nav>

        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
      </body>
    </html>


问:
Create user registration using stored procedure in mysql
I am trying to create user registration stored procedure in mysql but I am getting an error.

Query

```<code>CREATE PROCEDURE `test`.`sp_register`(fullname VARCHAR(50), Mob VARCHAR(10), Email VARCHAR(50), pass VARCHAR(255))
BEGIN
DECLARE s VARCHAR(20);
IF EXISTS(SELECT id FROM users WHERE email = Email)
    THEN SET s = 'User already exists';
ELSE
    INSERT INTO users(`name`,`mobile`,`email`,`password`,`created_at`)
        VALUES(fullname,Mob, Email, pass,CURRENT_TIMESTAMP())
        THEN SET s =  "User Registered";
END IF;

END
</code>```

答:
You don't need a "THEN" statement in an ELSE block

```<code>IF EXISTS(SELECT id FROM users WHERE email = Email) THEN
    SET s = 'User already exists';
ELSE
    INSERT INTO users(`name`,`mobile`,`email`,`password`,`created_at`)
      VALUES(fullname,Mob, Email, pass,CURRENT_TIMESTAMP())
    SET s =  "User Registered";
END IF;
</code>```

https://dev.mysql.com/doc/refman/5.7/en/if.html

Body:
I am trying to create user registration stored procedure in mysql but I am getting an error.

Query

CREATE PROCEDURE `test`.`sp_register`(fullname VARCHAR(50), Mob VARCHAR(10), Email VARCHAR(50), pass VARCHAR(255))
BEGIN
DECLARE s VARCHAR(20);
IF EXISTS(SELECT id FROM users WHERE email = Email)
    THEN SET s = 'User already exists';
ELSE
    INSERT INTO users(`name`,`mobile`,`email`,`password`,`created_at`)
        VALUES(fullname,Mob, Email, pass,CURRENT_TIMESTAMP())
        THEN SET s =  "User Registered";
END IF;

END

Body:
You don't need a "THEN" statement in an ELSE block

IF EXISTS(SELECT id FROM users WHERE email = Email) THEN
    SET s = 'User already exists';
ELSE
    INSERT INTO users(`name`,`mobile`,`email`,`password`,`created_at`)
      VALUES(fullname,Mob, Email, pass,CURRENT_TIMESTAMP())
    SET s =  "User Registered";
END IF;

https://dev.mysql.com/doc/refman/5.7/en/if.html


问:
U-SQL How to select first value in column that is different from current row?
I am struggling on how to make a "multi-row" formula in U-SQL. I have ordered the data by Date, and for each for I want to find the first value of "Port" that is not equal to the current row's value. In a similar way I want to find the last row in the date value with the current port value to figure out how many days a vessel has been in the port. Keep in mind here that is has to be the row with the same port name, with no new/other ports in between.

I am loading my data in like this:

```<code>@res = SELECT
        Port,
        Date
        FROM @data;
</code>```

This is how my date is structured:

```<code>Port      |   Date       |
Port A    |   1/1/2017   |
Port A    |   1/1/2017   |
Port A    |   1/2/2017   |
Port B    |   1/4/2017   |
Port B    |   1/4/2017   |
Port B    |   1/4/2017   |
Port B    |   1/5/2017   |
Port B    |   1/6/2017   |
Port C    |   1/9/2017   |
Port C    |   1/10/2017  |
Port C    |   1/11/2017  |
Port A    |   1/14/2017  |
Port A    |   1/15/2017  |
</code>```

How I would like the data to be structured:

```<code>Port      |   Date       |  Time in Port   | Previous Port
Port A    |   1/1/2017   |      0          |   N/A
Port A    |   1/1/2017   |      0          |   N/A
Port A    |   1/2/2017   |      1          |   N/A
Port B    |   1/4/2017   |      0          |   Port  A
Port B    |   1/4/2017   |      0          |   Port  A
Port B    |   1/4/2017   |      0          |   Port  A
Port B    |   1/5/2017   |      1          |   Port  A
Port B    |   1/6/2017   |      2          |   Port  A
Port C    |   1/9/2017   |      0          |   Port  B
Port C    |   1/10/2017  |      1          |   Port  B
Port C    |   1/11/2017  |      2          |   Port  B
Port A    |   1/14/2017  |      0          |   Port  C
Port A    |   1/15/2017  |      1          |   Port  C
</code>```

I am new to U-SQL and so I am having a bit of trouble on how to approach this.
My first instinct would be to use some combination of LEAD()/LAG() and ROW_NUMBER() OVER(PARTITION BY xx ORDER BY Date), but I am unsure of how to get the exact effect I am looking for.

Could anyone point me in the right direction?

答:
You can do what you need with the so-called Ranking and Analytic functions like LAG, DENSE_RANK and the OVER clause, although it's not entirely straightforward.  This simple rig worked for your test data, I would suggest testing thoroughly with a larger and more complex dataset.

```<code>// Test data
@input = SELECT *
     FROM (
        VALUES
        ( "Port A", DateTime.Parse("1/1/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port A", DateTime.Parse("1/1/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port A", DateTime.Parse("1/2/2017", new CultureInfo("en-US") ), 1 ),
        ( "Port B", DateTime.Parse("1/4/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port B", DateTime.Parse("1/4/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port B", DateTime.Parse("1/4/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port B", DateTime.Parse("1/5/2017", new CultureInfo("en-US") ), 1 ),
        ( "Port B", DateTime.Parse("1/6/2017", new CultureInfo("en-US") ), 2 ),
        ( "Port C", DateTime.Parse("1/9/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port C", DateTime.Parse("1/10/2017", new CultureInfo("en-US") ), 1 ),
        ( "Port C", DateTime.Parse("1/11/2017", new CultureInfo("en-US") ), 2 ),
        ( "Port A", DateTime.Parse("1/14/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port A", DateTime.Parse("1/15/2017", new CultureInfo("en-US") ), 1 )
     ) AS x ( Port, Date, timeInPort );

// Add a group id to the dataset
@working =
    SELECT Port,
           Date,
           timeInPort,
           DENSE_RANK() OVER(ORDER BY Date) - DENSE_RANK() OVER(PARTITION BY Port ORDER BY Date) AS groupId

    FROM @input;

// Use the group id to work out the datediff with previous row
@working =
    SELECT Port,
           Date,
           timeInPort,
           groupId,
           Date.Date.Subtract((DateTime)(LAG(Date) OVER(PARTITION BY groupId ORDER BY Date) ?? Date)).TotalDays AS diff    // datediff

    FROM @working;

// Work out the previous port, based on group id
@ports =
    SELECT Port, groupId
    FROM @working
    GROUP BY Port, groupId;

@ports =
    SELECT Port, groupId, LAG(Port) OVER( ORDER BY groupId ) AS previousPort
    FROM @ports;

// Prep the final output
@output =
    SELECT w.Port,
           w.Date.ToString("M/d/yyyy") AS Date,
           SUM(w.diff) OVER( PARTITION BY w.groupId ORDER BY w.Date ROWS BETWEEN 1 PRECEDING AND CURRENT ROW ) AS timeInPort,
           p.previousPort
    FROM @working AS w
         INNER JOIN
             @ports AS p
         ON w.Port == p.Port
            AND w.groupId == p.groupId;

OUTPUT @output TO "/output/output.csv"
ORDER BY Date, Port
USING Outputters.Csv(quoting:false);
</code>```

My results:

Body:
I am struggling on how to make a "multi-row" formula in U-SQL. I have ordered the data by Date, and for each for I want to find the first value of "Port" that is not equal to the current row's value. In a similar way I want to find the last row in the date value with the current port value to figure out how many days a vessel has been in the port. Keep in mind here that is has to be the row with the same port name, with no new/other ports in between.

I am loading my data in like this:

@res = SELECT
        Port,
        Date
        FROM @data;

This is how my date is structured:

Port      |   Date       |
Port A    |   1/1/2017   |
Port A    |   1/1/2017   |
Port A    |   1/2/2017   |
Port B    |   1/4/2017   |
Port B    |   1/4/2017   |
Port B    |   1/4/2017   |
Port B    |   1/5/2017   |
Port B    |   1/6/2017   |
Port C    |   1/9/2017   |
Port C    |   1/10/2017  |
Port C    |   1/11/2017  |
Port A    |   1/14/2017  |
Port A    |   1/15/2017  |

How I would like the data to be structured:

Port      |   Date       |  Time in Port   | Previous Port
Port A    |   1/1/2017   |      0          |   N/A
Port A    |   1/1/2017   |      0          |   N/A
Port A    |   1/2/2017   |      1          |   N/A
Port B    |   1/4/2017   |      0          |   Port  A
Port B    |   1/4/2017   |      0          |   Port  A
Port B    |   1/4/2017   |      0          |   Port  A
Port B    |   1/5/2017   |      1          |   Port  A
Port B    |   1/6/2017   |      2          |   Port  A
Port C    |   1/9/2017   |      0          |   Port  B
Port C    |   1/10/2017  |      1          |   Port  B
Port C    |   1/11/2017  |      2          |   Port  B
Port A    |   1/14/2017  |      0          |   Port  C
Port A    |   1/15/2017  |      1          |   Port  C

I am new to U-SQL and so I am having a bit of trouble on how to approach this.
My first instinct would be to use some combination of LEAD()/LAG() and ROW_NUMBER() OVER(PARTITION BY xx ORDER BY Date), but I am unsure of how to get the exact effect I am looking for.

Could anyone point me in the right direction?

Body:
You can do what you need with the so-called Ranking and Analytic functions like LAG, DENSE_RANK and the OVER clause, although it's not entirely straightforward.  This simple rig worked for your test data, I would suggest testing thoroughly with a larger and more complex dataset.

// Test data
@input = SELECT *
     FROM (
        VALUES
        ( "Port A", DateTime.Parse("1/1/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port A", DateTime.Parse("1/1/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port A", DateTime.Parse("1/2/2017", new CultureInfo("en-US") ), 1 ),
        ( "Port B", DateTime.Parse("1/4/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port B", DateTime.Parse("1/4/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port B", DateTime.Parse("1/4/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port B", DateTime.Parse("1/5/2017", new CultureInfo("en-US") ), 1 ),
        ( "Port B", DateTime.Parse("1/6/2017", new CultureInfo("en-US") ), 2 ),
        ( "Port C", DateTime.Parse("1/9/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port C", DateTime.Parse("1/10/2017", new CultureInfo("en-US") ), 1 ),
        ( "Port C", DateTime.Parse("1/11/2017", new CultureInfo("en-US") ), 2 ),
        ( "Port A", DateTime.Parse("1/14/2017", new CultureInfo("en-US") ), 0 ),
        ( "Port A", DateTime.Parse("1/15/2017", new CultureInfo("en-US") ), 1 )
     ) AS x ( Port, Date, timeInPort );

// Add a group id to the dataset
@working =
    SELECT Port,
           Date,
           timeInPort,
           DENSE_RANK() OVER(ORDER BY Date) - DENSE_RANK() OVER(PARTITION BY Port ORDER BY Date) AS groupId

    FROM @input;

// Use the group id to work out the datediff with previous row
@working =
    SELECT Port,
           Date,
           timeInPort,
           groupId,
           Date.Date.Subtract((DateTime)(LAG(Date) OVER(PARTITION BY groupId ORDER BY Date) ?? Date)).TotalDays AS diff    // datediff

    FROM @working;

// Work out the previous port, based on group id
@ports =
    SELECT Port, groupId
    FROM @working
    GROUP BY Port, groupId;

@ports =
    SELECT Port, groupId, LAG(Port) OVER( ORDER BY groupId ) AS previousPort
    FROM @ports;

// Prep the final output
@output =
    SELECT w.Port,
           w.Date.ToString("M/d/yyyy") AS Date,
           SUM(w.diff) OVER( PARTITION BY w.groupId ORDER BY w.Date ROWS BETWEEN 1 PRECEDING AND CURRENT ROW ) AS timeInPort,
           p.previousPort
    FROM @working AS w
         INNER JOIN
             @ports AS p
         ON w.Port == p.Port
            AND w.groupId == p.groupId;

OUTPUT @output TO "/output/output.csv"
ORDER BY Date, Port
USING Outputters.Csv(quoting:false);

My results:


问:
Button content closes on click of next button
I have two buttons which store tables, but I want the table to disappear on click of the second button and show the contents of the second button immediately after clicking it, rather than clicking it twice (first click hides the table from the previous button, next clicks opens table from the current button).I don't seem to know how to do that.

function myFunction2() {
  var x = document.getElementById("displaytable");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" id="Button1" value="Button1" onClick="myFunction2()" />
<div id="displaytable" style="display:none">
  <table id="displaytable" width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">1</td>
      <td align="center">2</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div>

<input type="button" id="Button2" value="Button1" onClick="myFunction2()" />
<div id="displaytable" style="display:none">
  <table id="displaytable" width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">36</td>
      <td align="center">45</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div></code>```

答:
You will have to make the following updates:

You cannot have elements with same id as you had with your button and divs. See the modifications, I renamed them as displaytable1 , 2 and so on.

This code works even if you have multiple number  of buttons and its corresponding tables (10,20 or even 100). You don't have to make a seperate function for each button click and can run a loop, so when you click 1 button it will just open that table and close all the remaining tables in this line:

for(i=1;i<=2;++i) where '2' is the last table id index and likewise the maximum id of a table as displaytable2.

The function gets a parameter which is an integer, depending on the serial id of the button or the corresponding table that is, 1 for the first, 2 for the second like demonstrated in the code.

You might want to get all your buttons lined up together separately and the tables separately like shown below so when a button is clicked, the rest of the buttons don't go down below the table.

function myFunction2(index) {
  var x = document.getElementById("displaytable"+index);
  for(i=1;i<=3;++i) //3 because we have 3 tables
  {
    if(index==i){
      x.style.display = "block";
    }
    else{
      document.getElementById("displaytable"+i).style.display = "none";
    }
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" id="Button1" value="Button1" onClick="myFunction2('1')" />
<input type="button" id="Button2" value="Button2" onClick="myFunction2('2')" />
<input type="button" id="Button3" value="Button3" onClick="myFunction2('3')" />
<div id="displaytable1" style="display:none">

  <table width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">1</td>
      <td align="center">2</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div>

<div id="displaytable2" style="display:none">
  <table width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column2</td>
      <td class="lbl">column4</td>
      <td class="lbl">column5</td>
    </tr>
    <tr>
      <td align="center">36</td>
      <td align="center">45</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div>

<div id="displaytable3" style="display:none">
  <table width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column11</td>
      <td class="lbl">column23</td>
      <td class="lbl">column2</td>
    </tr>
    <tr>
      <td align="center">3</td>
      <td align="center">45</td>
      <td align="center">3</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">00</td>
      <td align="center">6</td>
    </tr>
  </table>
</div></code>```

Body:
I have two buttons which store tables, but I want the table to disappear on click of the second button and show the contents of the second button immediately after clicking it, rather than clicking it twice (first click hides the table from the previous button, next clicks opens table from the current button).I don't seem to know how to do that.

function myFunction2() {
  var x = document.getElementById("displaytable");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

<input type="button" id="Button1" value="Button1" onClick="myFunction2()" />

      column1
      column2
      column3

      1
      2
      33

      4
      5
      6

<input type="button" id="Button2" value="Button1" onClick="myFunction2()" />

      column1
      column2
      column3

      36
      45
      33

      4
      5
      6

Body:
You will have to make the following updates:

You cannot have elements with same id as you had with your button and divs. See the modifications, I renamed them as displaytable1 , 2 and so on.

This code works even if you have multiple number  of buttons and its corresponding tables (10,20 or even 100). You don't have to make a seperate function for each button click and can run a loop, so when you click 1 button it will just open that table and close all the remaining tables in this line:

for(i=1;i<=2;++i) where '2' is the last table id index and likewise the maximum id of a table as displaytable2.

The function gets a parameter which is an integer, depending on the serial id of the button or the corresponding table that is, 1 for the first, 2 for the second like demonstrated in the code.

You might want to get all your buttons lined up together separately and the tables separately like shown below so when a button is clicked, the rest of the buttons don't go down below the table.

function myFunction2(index) {
  var x = document.getElementById("displaytable"+index);
  for(i=1;i<=3;++i) //3 because we have 3 tables
  {
    if(index==i){
      x.style.display = "block";
    }
    else{
      document.getElementById("displaytable"+i).style.display = "none";
    }
  }

}

<input type="button" id="Button1" value="Button1" onClick="myFunction2('1')" />
<input type="button" id="Button2" value="Button2" onClick="myFunction2('2')" />
<input type="button" id="Button3" value="Button3" onClick="myFunction2('3')" />
<div id="displaytable1" style="display:none">

  <table width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">1</td>
      <td align="center">2</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div>

<div id="displaytable2" style="display:none">
  <table width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column2</td>
      <td class="lbl">column4</td>
      <td class="lbl">column5</td>
    </tr>
    <tr>
      <td align="center">36</td>
      <td align="center">45</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div>

<div id="displaytable3" style="display:none">
  <table width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column11</td>
      <td class="lbl">column23</td>
      <td class="lbl">column2</td>
    </tr>
    <tr>
      <td align="center">3</td>
      <td align="center">45</td>
      <td align="center">3</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">00</td>
      <td align="center">6</td>
    </tr>
  </table>
</div>


问:
Second click on floating button with image (example: Add to favorite)
First click: image on floating button will turn into filled red and submit data to Firebase.

Second click: image on floating button will turn back into just border and will delete the item from Firebase.

But appears to be my second click to remove item from Firebase is not working by any chance.

```<code>btnLove.setOnClickListener(new View.OnClickListener() {
        boolean showingFirst;
        @Override
        public void onClick(View v) {
            if(showingFirst == true){
                btnLove.setImageResource(R.drawable.fav_filled_50);
                showingFirst = false;

                fav =  new Favorites(Common.currentUser.getPhone(),
                        drinkId,
                        currentDrink.getName(),
                        currentDrink.getImage(),
                        currentDrink.getPrice()
                        );
                favorites.child(Common.currentUser.getPhone()).child(drinkId).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if(dataSnapshot.child(Common.currentUser.getPhone()).exists())
                        {
                            favorites.child(Common.currentUser.getPhone()).child(drinkId).removeValue();
                            favorites.child(Common.currentUser.getPhone()).child(drinkId).setValue(fav);
                        }
                        else
                        {
                            favorites.child(Common.currentUser.getPhone()).child(drinkId).setValue(fav);
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            } else {
                btnLove.setImageResource(R.drawable.fav_border_50);
                btnLove.setTag(70);
                showingFirst = true;
                favorites.child(Common.currentUser.getPhone()).child(drinkId).removeValue();

            }

        }
    });
</code>```

答:
Remove

```<code>boolean showingFirst = true;
</code>```

form the setOnClickListener and put this into outside of setOnClickListener method. when u clicking the button showingFirst will be always true coz you just creating this.

Body:
First click: image on floating button will turn into filled red and submit data to Firebase.

Second click: image on floating button will turn back into just border and will delete the item from Firebase.

But appears to be my second click to remove item from Firebase is not working by any chance.

btnLove.setOnClickListener(new View.OnClickListener() {
        boolean showingFirst;
        @Override
        public void onClick(View v) {
            if(showingFirst == true){
                btnLove.setImageResource(R.drawable.fav_filled_50);
                showingFirst = false;

                fav =  new Favorites(Common.currentUser.getPhone(),
                        drinkId,
                        currentDrink.getName(),
                        currentDrink.getImage(),
                        currentDrink.getPrice()
                        );
                favorites.child(Common.currentUser.getPhone()).child(drinkId).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if(dataSnapshot.child(Common.currentUser.getPhone()).exists())
                        {
                            favorites.child(Common.currentUser.getPhone()).child(drinkId).removeValue();
                            favorites.child(Common.currentUser.getPhone()).child(drinkId).setValue(fav);
                        }
                        else
                        {
                            favorites.child(Common.currentUser.getPhone()).child(drinkId).setValue(fav);
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            } else {
                btnLove.setImageResource(R.drawable.fav_border_50);
                btnLove.setTag(70);
                showingFirst = true;
                favorites.child(Common.currentUser.getPhone()).child(drinkId).removeValue();

            }

        }
    });

Body:
Remove

boolean showingFirst = true;

form the setOnClickListener and put this into outside of setOnClickListener method. when u clicking the button showingFirst will be always true coz you just creating this.


问:
Too much recursion in Firefox when using custom elements
I am trying to create new custom elements.

I have a very simple html index file :

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script src="dist/webcomponents-lite.js"></script>
    </head>

    <body>

        <h1>WebComponents</h1>
        <hello-world></hello-world>

        <script src="src/components/hello-world.js"></script>
    </body>
</html>
</code>```

My hello-world component is as follows :

```<code>class HelloWorldElement extends HTMLElement {

    constructor(){
        super()

        this.innerHTML = `<h1>Hello Meetup !</h1>`;
    }

    connectedCallback(){
        console.log("I'm here!");
    }

    disconnectedCallback(){
        console.log("I'm gone!");
    }

}

    window.customElements.define(
                    'hello-world',
                     HelloWorldElement);
</code>```

This code snippet works perfectly fine in Chrome and Safari.

I have added the webcomponents-lite.js import to add support for other browsers.

However when trying to run the code in Firefox I get the following error:

```<code>too much recursion
[Learn More]
webcomponents-lite.js:93:170
</code>```

I have found very little info on the web as to what can be going on.

I think I am following the recommended path explained in the polyfills page from the web components website.

Any idea what is going on?

Thanks

EDIT:

I am able to get the custom element showing by enabling dom.webcomponents.customelements.enabled and dom.webcomponents.enabled in the firefox config and removing the polyfill, but that's obviously not something desired on production.

答:
The error is due to the fact that you modify the inner HTML content of the custom element in its constructor, which is unexpected and therefore should not be done.

Instead, you should do that after, for example in the connectedCallback() method.

Alternately, if you want to define the content in the constructor, you should insert it into a Shadow DOM.

NB: the custom element polyfill is effectively included in webcomponents-lite.js.

Body:
I am trying to create new custom elements.

I have a very simple html index file :

<!DOCTYPE html>

        <meta charset="UTF-8">

WebComponents

        <hello-world></hello-world>

My hello-world component is as follows :

class HelloWorldElement extends HTMLElement {

    constructor(){
        super()

        this.innerHTML = `<h1>Hello Meetup !</h1>`;
    }

    connectedCallback(){
        console.log("I'm here!");
    }

    disconnectedCallback(){
        console.log("I'm gone!");
    }

}

    window.customElements.define(
                    'hello-world',
                     HelloWorldElement);

This code snippet works perfectly fine in Chrome and Safari.

I have added the webcomponents-lite.js import to add support for other browsers.

However when trying to run the code in Firefox I get the following error:

too much recursion
[Learn More]
webcomponents-lite.js:93:170

I have found very little info on the web as to what can be going on.

I think I am following the recommended path explained in the polyfills page from the web components website.

Any idea what is going on?

Thanks

EDIT:

I am able to get the custom element showing by enabling dom.webcomponents.customelements.enabled and dom.webcomponents.enabled in the firefox config and removing the polyfill, but that's obviously not something desired on production.


问:
How to automate a FTP file transfer on Linux?
I'm trying to automate an FTP file transfer on linux to keep some backups on our intranet. My main problem is that I can't use SCP because SHH breaks our samba server and other stuff, so we are stuck with vsftp.

What I'm probably going to do, is create a bash to run in Cron every week. This is an example I found in the internet:

```<code>#!/bin/bash
HOST='your.ftp.site'
USER='remoteusername'
PASSWD='remotepasswd'

ftp -n -v $HOST << EOT

   ascii
    user $USER $PASSWD
    prompt
   [COMMANDS GO HERE]
    bye
    EOT
</code>```

But I can't really find what codes to use beyond that to transfer files between the two computers. Would it be a simple CAT?

I would appreciate any help, thanks!

答:
There are several possibilities:
First: use lftp. Of course you should read the fine manual, but as an example:

```<code>echo "mirror --reverse --delete" | lftp -u $username,$password $mysite
</code>```

Or use expect:

```<code>spawn ftp mysite
expect "Login:"
send "username\r"
expect "ssword:"
send "S0m3ting\r"
expect "ftp>"
send "prompt\r"
expect "ftp>"
send "cd somewher\r"
expect "ftp>"
send "mget allfiles.*\r"
expect "ftp>"
send "mput loadsofotherfiles.*\r"
expect "ftp>"
send "bye\r"
</code>```

(note: this will work as a first test, but you shouldn't run like this in production)

Also note that man ftp will give you a list of the [COMMANDS (that) GO HERE].

As a side note: ssh and SAMBA should run fine on the same server. You might want to research a bit what goes wrong there.

Body:
I'm trying to automate an FTP file transfer on linux to keep some backups on our intranet. My main problem is that I can't use SCP because SHH breaks our samba server and other stuff, so we are stuck with vsftp.

What I'm probably going to do, is create a bash to run in Cron every week. This is an example I found in the internet:

#!/bin/bash
HOST='your.ftp.site'
USER='remoteusername'
PASSWD='remotepasswd'

ftp -n -v $HOST << EOT

   ascii
    user $USER $PASSWD
    prompt
   [COMMANDS GO HERE]
    bye
    EOT

But I can't really find what codes to use beyond that to transfer files between the two computers. Would it be a simple CAT?

I would appreciate any help, thanks!

Body:
There are several possibilities:
First: use lftp. Of course you should read the fine manual, but as an example:

echo "mirror --reverse --delete" | lftp -u $username,$password $mysite

Or use expect:

spawn ftp mysite
expect "Login:"
send "username\r"
expect "ssword:"
send "S0m3ting\r"
expect "ftp>"
send "prompt\r"
expect "ftp>"
send "cd somewher\r"
expect "ftp>"
send "mget allfiles.*\r"
expect "ftp>"
send "mput loadsofotherfiles.*\r"
expect "ftp>"
send "bye\r"

(note: this will work as a first test, but you shouldn't run like this in production)

Also note that man ftp will give you a list of the [COMMANDS (that) GO HERE].

As a side note: ssh and SAMBA should run fine on the same server. You might want to research a bit what goes wrong there.


问:
Function that returns the row in an UNSORTED multidimensional array, A, that sums to the closest number to B?
Related to my other recent question Function that returns the closest number to B that's in an UNSORTED multidimensional array, A?

What I've made sense of so far:

```<code>import numpy as np
def get_R(A,B):
  A = np.asanyarray(A)
  assert A.ndim == 2
  sums = A.sum(axis=1)
  close = sums.argmin(B)
  return A.flat[close]
</code>```

I'm being returned an error ValueError: axis(=9) out of bounds

for get_r([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9)

when I should be getting array([2,7,1,0])

答:
Consider the following modification to your function

```<code>def get_R(A,B):
  A = np.asanyarray(A)
  assert A.ndim == 2
  sums = A.sum(axis=1)
  sums = abs(sums - B)
  close = sums.argmin()
  return A[close,:]
</code>```

There were two changes made here.

First we replace sums with abs(sums - B) before we call the argmin() function. This is a correct way to get the element of the sums array that is closer to B.

Second we return A[close,:] which is a correct way to get a row out of a 2D array.

Tracing the execution

Let's examine how this works line by line

```<code>>>> A=np.asanyarray([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]])
>>> sums = A.sum(axis=1)
>>> sums
array([ 2, 10, 19, 22])
>>> abs(sums - 9)
array([ 7,  1, 10, 13])
>>> abs(sums - 9).argmin()
1
>>> A[1,:]
array([2, 7, 1, 0])
</code>```

Your error message

The error message ValueError: axis(=9) out of bounds was reported because numpy.argmin(self, axis=None, out=None) when called as a method of a Numpy array treats its argument as an axis argument. Calling axis = 9 on a vector is certainly an error.

Body:
Related to my other recent question Function that returns the closest number to B that's in an UNSORTED multidimensional array, A?

What I've made sense of so far:

import numpy as np
def get_R(A,B):
  A = np.asanyarray(A)
  assert A.ndim == 2
  sums = A.sum(axis=1)
  close = sums.argmin(B)
  return A.flat[close]

I'm being returned an error ValueError: axis(=9) out of bounds

for get_r([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9)

when I should be getting array([2,7,1,0])

Body:
Consider the following modification to your function

def get_R(A,B):
  A = np.asanyarray(A)
  assert A.ndim == 2
  sums = A.sum(axis=1)
  sums = abs(sums - B)
  close = sums.argmin()
  return A[close,:]

There were two changes made here.

First we replace sums with abs(sums - B) before we call the argmin() function. This is a correct way to get the element of the sums array that is closer to B.

Second we return A[close,:] which is a correct way to get a row out of a 2D array.

Tracing the execution

Let's examine how this works line by line

>>> A=np.asanyarray([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]])
>>> sums = A.sum(axis=1)
>>> sums
array([ 2, 10, 19, 22])
>>> abs(sums - 9)
array([ 7,  1, 10, 13])
>>> abs(sums - 9).argmin()
1
>>> A[1,:]
array([2, 7, 1, 0])

Your error message

The error message ValueError: axis(=9) out of bounds was reported because numpy.argmin(self, axis=None, out=None) when called as a method of a Numpy array treats its argument as an axis argument. Calling axis = 9 on a vector is certainly an error.


问:
choosing the largest weights when connecting with fuzzy logic in R
I need merge two datasets

df1

```<code>df1=structure(list(id = structure(c(1L, 4L, 5L, 6L, 2L, 3L), .Label = c("195/75 R16C-Tire CORDIANT Business CA",
"215/75 R17,5-Tires KAMA NR-201 driving axle", "235/70 R16-Tire KAMA-221",
"275/70 R22,5-Tire TYREX ALL STEEL VC-1 (Я-646)", "315/80 R22,5-Tire TYREX ALL STEEL DR-1 driving axle",
"315/80 R22,5-Tire TYREX ALL STEEL FR-401 steering axle"), class = "factor")), .Names = "id", class = "data.frame", row.names = c(NA,
-6L))
</code>```

df2

```<code> df2= structure(list(id = structure(c(2L, 4L, 5L, 6L, 3L, 1L), .Label = c("Auto-cutting 245 / 70R16 K-214",
    "Auto-rubber 195/75 R16C Cordiant Business CA 107 / 105R all-season",
    "Auto-rubber 215 / 75R17,5 K-166", "Auto-rubber 275 / 70R22,5 (11 / 70R22,5) I-646 (Tyrex all steel VC-1)",
    "Auto-rubber 315 / 80R22,5 DR-1Tyrex All Steel (Я-636)", "Auto-rubber 315 / 80R22,5 FR-401 Tyrex All Steel (Я-626)"
    ), class = "factor")), .Names = "id", class = "data.frame", row.names = c(NA,
    -6L))
</code>```

I use fuzzylogic

```<code>library("RecordLinkage")
    #get weights
rpairs_jar <- compare.linkage(df1, df2,
                              strcmp = c("id"),
                              strcmpfun = jarowinkler)

rpairs_epiwt <- epiWeights(rpairs_jar)
#get wright to data frame
b=rpairs_epiwt$pairs
View(b)
</code>```

On output i see

we have weights between all id.
For example, the weight id1 is calculated with respect to all 6 denominations.
But we see that the greatest weight between the first item of df1(id1) and the first item of df2 (id1) (0,61).

What about second item(id2 of df1) the greatest weight between third item(id3 of df2)(0.58).

How to leave only those comparisons, between the id of which are the greatest weight?

I.E
on output, we have table not with 36 entries, but six

```<code>id1 id2     id
1   1   0,6106743
2   3   0,5994314
3   3   0,5874915
4   4   0,6288133
5   4   0,5552018
6   6   0,5642857
</code>```

答:
I would do something like this, although I'm not sure that I've understood your question entirely. Ah, I've just found it: your data is different than in the picture. Here are the first 12 rows that I get:

```<code>   id1 id2        id is_match
1    1   1 0.6106743       NA
2    1   2 0.5014481       NA
3    1   3 0.4869703       NA
4    1   4 0.4752647       NA
5    1   5 0.4671400       NA
6    1   6 0.4358859       NA
7    2   1 0.4428541       NA
8    2   2 0.5752810       NA
9    2   3 0.6090623       NA
10   2   4 0.5946931       NA
11   2   5 0.5320353       NA
12   2   6 0.5055347       NA
</code>```

If you're after the largest id for each id1, here's what I'd do:

```<code>library(tidyverse)

b %>%
  group_by(id1) %>%
  summarise(maxId1 = max(id)) %>%
  left_join(b, by = c("maxId1" = "id", "id1")) %>%
  select(id1, id2, "id" = "maxId1")
</code>```

And this is what it yields (which isn't what you've said above, given the different data, but I think is what you seek):

```<code># A tibble: 6 x 3
    id1   id2        id
  <int> <int>     <dbl>
1     1     1 0.6106743
2     2     3 0.6090623
3     3     3 0.5837645
4     4     4 0.6249495
5     5     5 0.5889200
6     6     6 0.5642857
</code>```

I hope this helps you.

Body:
I need merge two datasets

df1

df1=structure(list(id = structure(c(1L, 4L, 5L, 6L, 2L, 3L), .Label = c("195/75 R16C-Tire CORDIANT Business CA",
"215/75 R17,5-Tires KAMA NR-201 driving axle", "235/70 R16-Tire KAMA-221",
"275/70 R22,5-Tire TYREX ALL STEEL VC-1 (Я-646)", "315/80 R22,5-Tire TYREX ALL STEEL DR-1 driving axle",
"315/80 R22,5-Tire TYREX ALL STEEL FR-401 steering axle"), class = "factor")), .Names = "id", class = "data.frame", row.names = c(NA,
-6L))

df2

 df2= structure(list(id = structure(c(2L, 4L, 5L, 6L, 3L, 1L), .Label = c("Auto-cutting 245 / 70R16 K-214",
    "Auto-rubber 195/75 R16C Cordiant Business CA 107 / 105R all-season",
    "Auto-rubber 215 / 75R17,5 K-166", "Auto-rubber 275 / 70R22,5 (11 / 70R22,5) I-646 (Tyrex all steel VC-1)",
    "Auto-rubber 315 / 80R22,5 DR-1Tyrex All Steel (Я-636)", "Auto-rubber 315 / 80R22,5 FR-401 Tyrex All Steel (Я-626)"
    ), class = "factor")), .Names = "id", class = "data.frame", row.names = c(NA,
    -6L))

I use fuzzylogic

library("RecordLinkage")
    #get weights
rpairs_jar <- compare.linkage(df1, df2,
                              strcmp = c("id"),
                              strcmpfun = jarowinkler)

rpairs_epiwt <- epiWeights(rpairs_jar)
#get wright to data frame
b=rpairs_epiwt$pairs
View(b)

On output i see

we have weights between all id.
For example, the weight id1 is calculated with respect to all 6 denominations.
But we see that the greatest weight between the first item of df1(id1) and the first item of df2 (id1) (0,61).

What about second item(id2 of df1) the greatest weight between third item(id3 of df2)(0.58).

How to leave only those comparisons, between the id of which are the greatest weight?

I.E
on output, we have table not with 36 entries, but six

id1 id2     id
1   1   0,6106743
2   3   0,5994314
3   3   0,5874915
4   4   0,6288133
5   4   0,5552018
6   6   0,5642857

Body:
I would do something like this, although I'm not sure that I've understood your question entirely. Ah, I've just found it: your data is different than in the picture. Here are the first 12 rows that I get:

   id1 id2        id is_match
1    1   1 0.6106743       NA
2    1   2 0.5014481       NA
3    1   3 0.4869703       NA
4    1   4 0.4752647       NA
5    1   5 0.4671400       NA
6    1   6 0.4358859       NA
7    2   1 0.4428541       NA
8    2   2 0.5752810       NA
9    2   3 0.6090623       NA
10   2   4 0.5946931       NA
11   2   5 0.5320353       NA
12   2   6 0.5055347       NA

If you're after the largest id for each id1, here's what I'd do:

library(tidyverse)

b %>%
  group_by(id1) %>%
  summarise(maxId1 = max(id)) %>%
  left_join(b, by = c("maxId1" = "id", "id1")) %>%
  select(id1, id2, "id" = "maxId1")

And this is what it yields (which isn't what you've said above, given the different data, but I think is what you seek):

# A tibble: 6 x 3
    id1   id2        id
  <int> <int>     <dbl>
1     1     1 0.6106743
2     2     3 0.6090623
3     3     3 0.5837645
4     4     4 0.6249495
5     5     5 0.5889200
6     6     6 0.5642857

I hope this helps you.


问:
Varying Line Width in Drop Down Menu
How do you create varying line heights using CSS in a drop down menu? As you can see below, I am changing the font sizes of each element, however, the new font is not being applied once selected. Thanks!

```<code><select>
        <option class="w1">&#9472&#9472&#9472&#9472</option>
        <option class="w2">&#9472&#9472&#9472&#9472</option>
</select>

option.w1  {
  font-size: 5px;
}
option.w2  {
  font-size:8px;
}
</code>```

https://jsfiddle.net/kwham1bf/1/

答:
Unfortunately, there is no way to select an element's parent using CSS. In this case, the parent is the select and the child is the selected option.

If you need to style the select based on the selected option, you'll have to resort to using JavaScript:

var select = document.querySelector("select");

select.addEventListener("change", function() {
    var selected = document.querySelector("option:checked");
    var selectedFontSize = getComputedStyle(selected, null).getPropertyValue("font-size");
    select.style.fontSize = selectedFontSize;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>option.w1  {
  font-size: 5px;
  background-repeat: repeat;
  display: inline-block;
  position: static;

}

option.w2  {
  font-size:8px;
  background-repeat: repeat;
  display: inline-block;
  position: static;
}

option.w3 {
  font-size: 11px;
  background-repeat: repeat;
  display: inline-block;
  position: static;
}

option.w4 {
  font-size: 14px;
  background-repeat: repeat;
  display: inline-block;
  position: static;
}

option.w5 {
  font-size: 17px;
  background-repeat: repeat;
  display: inline-block;
  position: static;
}

option.w6 {
  font-size: 20px;
  background-repeat: repeat;
  display: inline-block;
  position: static;
}</code>```

Width

  <select>
    <option class="w1">&#9472&#9472&#9472&#9472</option>
    <option class="w2">&#9472&#9472&#9472&#9472</option>
    <option class="w3">&#9472&#9472&#9472&#9472</option>
    <option class="w4">&#9472&#9472&#9472&#9472</option>
    <option class="w5">&#9472&#9472&#9472&#9472</option>
    <option class="w6">&#9472&#9472&#9472&#9472</option>
  </select>

```

Title: Varying Line Width in Drop Down Menu

Body:
How do you create varying line heights using CSS in a drop down menu? As you can see below, I am changing the font sizes of each element, however, the new font is not being applied once selected. Thanks!

<select>
        <option class="w1">&#9472&#9472&#9472&#9472</option>
        <option class="w2">&#9472&#9472&#9472&#9472</option>
</select>

option.w1  {
  font-size: 5px;
}
option.w2  {
  font-size:8px;
}

https://jsfiddle.net/kwham1bf/1/

Body:
Unfortunately, there is no way to select an element's parent using CSS. In this case, the parent is the select and the child is the selected option.

If you need to style the select based on the selected option, you'll have to resort to using JavaScript:

var select = document.querySelector("select");

select.addEventListener("change", function() {
    var selected = document.querySelector("option:checked");
    var selectedFontSize = getComputedStyle(selected, null).getPropertyValue("font-size");
    select.style.fontSize = selectedFontSize;
});

option.w1  {
  font-size: 5px;
  background-repeat: repeat;
  display: inline-block;
  position: static;

}

option.w2  {
  font-size:8px;
  background-repeat: repeat;
  display: inline-block;
  position: static;
}

option.w3 {
  font-size: 11px;
  background-repeat: repeat;
  display: inline-block;
  position: static;
}

option.w4 {
  font-size: 14px;
  background-repeat: repeat;
  display: inline-block;
  position: static;
}

option.w5 {
  font-size: 17px;
  background-repeat: repeat;
  display: inline-block;
  position: static;
}

option.w6 {
  font-size: 20px;
  background-repeat: repeat;
  display: inline-block;
  position: static;
}

<div class="row add-top-margin">
  <div class="col-xs-3 section-label">Width</div>
  <select>
    <option class="w1">&#9472&#9472&#9472&#9472</option>
    <option class="w2">&#9472&#9472&#9472&#9472</option>
    <option class="w3">&#9472&#9472&#9472&#9472</option>
    <option class="w4">&#9472&#9472&#9472&#9472</option>
    <option class="w5">&#9472&#9472&#9472&#9472</option>
    <option class="w6">&#9472&#9472&#9472&#9472</option>
  </select>
</div>


问:
How to change Background color of table row based on respective cell data using angularjs?
I want to change Background color of row based on cell data, like if it matches first four characters from table cell "td", then row should change its color to red.

here is my example, it is working but it takes whole cell data.but i want row color should change once it matches first four characters from cell.

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

<body ng-app="myApp">
    <div ng-controller="myController">
        <div class="container" style="margin-top:40px;">
            <div class="row">
                {{error}}
                <div class="col-md-6">
                    <table class="table table-bordered table-condensed">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Class Name</th>
                                <th>Roll No</th>
                                <th>Email</th>
                            </tr>
                        </thead>
                        <tbody ng-repeat="std in students">
                            **<tr ng-class="{'bgRed': std.Name === 'Prash'}>**
                                <td>{{std.Name}}</td>
                                <td>{{std.ClassName}}</td>
                                <td>{{std.RollNo}}</td>
                                <td>{{std.Email}}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</code>```

and my table is

Table row should change to red if table cell data "Prash or Prashant" matches.instead of taking "Prashant Olekar"

how to achive this please help. Thank you

答:
Using substring you can trim the characters of the string,
 here I'm creating one more variable(filed) "trimmed_name" which is a substring of your "name" which gives you first 4 characters of your string "name".

```<code><tr ng-repeat="std in students" ng-init="trimName(std)">
   <td ng-class="{'bgRed': std.trimmed_name === 'Prash', 'bgBlue': std.trimmed_name === 'Pavi', 'bgBlack' : std.trimmed_name === 'Pava'}">{{std.Name}}</td>
   <td>{{std.ClassName}}</td>
   <td>{{std.RollNo}}</td>
   <td>{{std.Email}}</td>
</tr>
</code>```

In Css add respective colours for respective classes

in your controller

```<code>  $scope.trimName = function (std) {
  std.trimmed_name = std.Name.substring(0, 4);
  return std;
};
</code>```

Just in case if 'Prash' dose not work use {'bgRed': std.trimmed_name === "Prash"}

Hope it helps you.

Body:
I want to change Background color of row based on cell data, like if it matches first four characters from table cell "td", then row should change its color to red.

here is my example, it is working but it takes whole cell data.but i want row color should change once it matches first four characters from cell.

                {{error}}

                                Name
                                Class Name
                                Roll No
                                Email

                            **
**
                                {{std.Name}}
                                {{std.ClassName}}
                                {{std.RollNo}}
                                {{std.Email}}

and my table is

Table row should change to red if table cell data "Prash or Prashant" matches.instead of taking "Prashant Olekar"

how to achive this please help. Thank you

Body:
Using substring you can trim the characters of the string,
 here I'm creating one more variable(filed) "trimmed_name" which is a substring of your "name" which gives you first 4 characters of your string "name".

<tr ng-repeat="std in students" ng-init="trimName(std)">
   <td ng-class="{'bgRed': std.trimmed_name === 'Prash', 'bgBlue': std.trimmed_name === 'Pavi', 'bgBlack' : std.trimmed_name === 'Pava'}">{{std.Name}}</td>
   <td>{{std.ClassName}}</td>
   <td>{{std.RollNo}}</td>
   <td>{{std.Email}}</td>
</tr>

In Css add respective colours for respective classes

in your controller

  $scope.trimName = function (std) {
  std.trimmed_name = std.Name.substring(0, 4);
  return std;
};

Just in case if 'Prash' dose not work use {'bgRed': std.trimmed_name === &quot;Prash&quot;}

Hope it helps you.


问:
How do I break out of this if?
I need to break out of the if statement when one of the for loops is used. But when I compile and run it, all three for loops give back info when I only need one. I know the answer is staring me in the face, but I just can't figure out what it is.</p>

```<code>if (filestat == 'S' || filestat == 's')
{

  for ( a = 0; a < 5000; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .15;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

  for (a = 5000; a <= 20000; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .22;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

  for (a = 20001; a >= 20001; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .31;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

}
</code>```

答:
I guess you are trying to do calculations based on the value of a, you can use nested if-else statements instead of using loop and breaking it on the very first iteration.

```<code>    `if (filestat == 'S' || filestat == 's')
    {
      if( a >= 0 && a < 5000 )
        //do some work
      else if( a >= 5000 && a <= 20000 )
      //do some work
      else if( a > 20000)
     //do some work
    }`
</code>```

You may choose to wrap the code inside a function and pass tax rate as a parameter since it is the only variable quantity which depends on value of a.

Title: How do I break out of this if?

Body:
I need to break out of the if statement when one of the for loops is used. But when I compile and run it, all three for loops give back info when I only need one. I know the answer is staring me in the face, but I just can't figure out what it is.

if (filestat == 'S' || filestat == 's')
{

  for ( a = 0; a < 5000; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .15;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

  for (a = 5000; a <= 20000; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .22;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

  for (a = 20001; a >= 20001; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .31;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

}

Body:
I guess you are trying to do calculations based on the value of a, you can use nested if-else statements instead of using loop and breaking it on the very first iteration.

    `if (filestat == 'S' || filestat == 's')
    {
      if( a >= 0 && a < 5000 )
        //do some work
      else if( a >= 5000 && a <= 20000 )
      //do some work
      else if( a > 20000)
     //do some work
    }`

You may choose to wrap the code inside a function and pass tax rate as a parameter since it is the only variable quantity which depends on value of a.


问:
Object Normalization
In the same line as Database Normalization - is there an approach to object normalization, not design pattern, but the same mathematical like approach to normalizing object creation.  For example: first normal form: no repeating fields....
here's some links to DB Normalization:

http://en.wikipedia.org/wiki/Database_normalization
  http://databases.about.com/od/specificproducts/a/normalization.htm

Would this make object creation and self-documentation better?

Here's a link to a book about class normalization (guess we're really talking about classes)
http://www.agiledata.org/essays/classNormalization.html

答:
Interesting.

You may also be interested in looking at the Law of Demeter.

Another thing you may be interested in is c2's FearOfAddingClasses, as, arguably, the same reasoning that lead programmers to denormalise databases also leads to god classes and other code smells. For both OO and DB normalisation, we want to decompose everything. For databases this means more tables, for OO, more classes.

Now, it is worth bearing in mind the object relational impedance mismatch, that is, probably not everything will translate cleanly.

Object relational models or 'persistence layers', usually have 1-to-1 mappings between object attributes and database fields. So, can we normalise? Say we have department object with employee1, employee2 ... etc. attributes. Obviously that should be replaced with a list of employees. So we can say 1NF works.

With that in mind, let's go straight for the kill and look at 6NF database design, a good example is Anchor Modeling, (ignore the naming convention). Anchor Modeling/6NF provides highly decomposed and flexible database schemas; how does this translate to OO 'normalisation'?

Anchor Modeling has these kinds of relationships:

Anchors - unique object IDs.

Attributes, which translate to object attributes: (Anchor, value, metadata).

Ties - relationships between two or more objects (themselves anchors): (Anchor, Anchor... , metadata)

Knots, attributed Ties.

Attribute metadata can be anything - who changed an attribute, when, why, etc.

The OO translation of this is looks extremely flexible:

Anchors suggest attribute-less placeholders, like a proxy which knows how to deal with the attribute composition.

Attributes suggest classes representing attributes and what they belong to. This suggests applying reuse to how attributes are looked up and dealt with, e.g automatic constraint checking, etc. From this we have a basis to generically implement the GOF-style Structural patterns.

Ties and Knots suggest classes representing relationships between objects. A basis for generic implementation of the Behavioural design patterns?

Interesting and desirable properties of Anchor Modeling that also translate across are:

All this requires replacing inheritance with composition (good) in the exposed objects.

Attribute have owners rather than owners having attributes. Although this make attribute lookup more complex, it neatly solves certain aliasing problems, as there can only ever be one owner.

No need for NULL. This translates to clearer NULL handling. Empty-case attribute classes could provide methods for handling the lack of a particular attribute, instead of performing NULL-checking everywhere.

Attribute metadata. Attribute-level full historisation and blaming: 'play' objects back in time, see what changed, when and why, etc. (if required - metadata is entirely optional)

There would probably be a lot of very simple classes (which is good), and a very declarative programming style (also good).

Thanks for such a thought provoking question, I hope this is useful for you.

OwnerDisplayName: meade

Title: Object Normalization

LastEditorDisplayName: meade


问:
Swift constants: Struct or Enum
I'm not sure which of both are better to define constants. A struct or a enum. A struct will be copied every time i use it or not? When i think about a struct with static let constants it makes no sense that it will  copied all the time, in my opinion. But if it won't copied then it doesn't matter what I take?

What advantages does the choice of a struct or enum?

Francescu says use structs.

Ray Wenderlich says use enums. But I lack the justification.

答:
Here's a short answer: Do your constants need to be unique? Then use an enum, which enforces this. </p>

<p>Want to use several different constants to contain the same value (often useful for clarity)? Then use a struct, which allows this. </p>

ContentLicense: CC BY-SA 4.0

Title: Swift constants: Struct or Enum

Body:
Here's a short answer: Do your constants need to be unique? Then use an enum, which enforces this.

Want to use several different constants to contain the same value (often useful for clarity)? Then use a struct, which allows this.


问:
IE10 flexbox widths include padding, causing overflow. box-sizing: border-box doesn't fix
The LHS flex child in this example has 1em padding, and it will cause RHS to overflow the parent:

```<code><div style="display: -ms-flexbox; box-sizing: border-box; width: 200px; border: 5px solid black">

    <div style="padding: 1em; -ms-flex-positive: 0; -ms-flex-negative: 0; -ms-flex-preferred-size: 33%; background-color: blue; box-sizing: border-box">
        LHS
    </div>

    <div style="-ms-flex-positive: 0; -ms-flex-negative: 0; -ms-flex-preferred-size: 67%; background-color: red; box-sizing: border-box">
        RHS
    </div>

</div>
</code>```

Here's the fiddle:

http://jsfiddle.net/GY4F4/6/

How can I eliminate the overflow when flex children have padding? box-sizing: border-box doesn't work.

答:
I was able to solve this by adding:

```<code>-ms-flex-preferred-size: calc($basisValue - $paddingValue * 2);
</code>```

So this combination worked, even when using autoprefixer:

```<code>.element {
    padding: 1rem;
    flex: 0 1 20%;
    -ms-flex-preferred-size: calc(20% - 2rem);
}
</code>```

The calc value handily overrode the auto-generated prefixes, only noticed by IE.

Body:
The LHS flex child in this example has 1em padding, and it will cause RHS to overflow the parent:

        LHS

        RHS

Here's the fiddle:

http://jsfiddle.net/GY4F4/6/

How can I eliminate the overflow when flex children have padding? box-sizing: border-box doesn't work.

Body:
I was able to solve this by adding:

-ms-flex-preferred-size: calc($basisValue - $paddingValue * 2);

So this combination worked, even when using autoprefixer:

.element {
    padding: 1rem;
    flex: 0 1 20%;
    -ms-flex-preferred-size: calc(20% - 2rem);
}

The calc value handily overrode the auto-generated prefixes, only noticed by IE.