问:
Why can't we use the let keyword inside a class in typescript
I am new to TypeScript. I want to know why we can't use the let keyword for variable declaration inside a class as below. Thanks in advance.

```<code>class Greeter {
    let greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");
console.log(greeter.greet())
</code>```

答:
I don't think there is any specific documentation as to why but I believe the syntax for how class is transpiled simply requires that class-specific properties should not have any declaration. If you used var, same thing would happen and you can't use const in a class.

It's probably worth looking at the TypeScript Playground for future references. The final code that comes out seems to have it hoisted outside of the class?

```<code>var Greeter = /** @class */ (function () {
    function Greeter() {
    }
    return Greeter;
}());
var greeting; // hmm?
constructor(message, string);
{
    this.greeting = message;
}
greet();
{
    return "Hello, " + this.greeting;
}
var greeter = new Greeter("world");
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
};
document.body.appendChild(button);
</code>```

Interestingly in Babel you get an error when trying to do this. It's possible that Typescript might want to consider doing this too.

Body:
I am new to TypeScript. I want to know why we can't use the let keyword for variable declaration inside a class as below. Thanks in advance.

class Greeter {
    let greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");
console.log(greeter.greet())

Body:
I don't think there is any specific documentation as to why but I believe the syntax for how class is transpiled simply requires that class-specific properties should not have any declaration. If you used var, same thing would happen and you can't use const in a class.

It's probably worth looking at the TypeScript Playground for future references. The final code that comes out seems to have it hoisted outside of the class?

var Greeter = /** @class */ (function () {
    function Greeter() {
    }
    return Greeter;
}());
var greeting; // hmm?
constructor(message, string);
{
    this.greeting = message;
}
greet();
{
    return "Hello, " + this.greeting;
}
var greeter = new Greeter("world");
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
};
document.body.appendChild(button);

Interestingly in <a href="https://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&code_lz=MYGwhgzhAEDiBOBTRAXR9oG8BQ0_RFWgHMlUBLAO2IC5oIV4riBuXfYAe0ofgFdgKTvAAUAW0RQwxRHV7MAlFnb58KABbkIAOlLIUzaAF5oEqTLaqAvipJkUIpTlWqkKPvErQARAAlEICCcADQ-0ADU0BpauvbMlvg2NtiEKHb66MbQlIgA7nD26CLeucIgACbeCmwpRABGfChCXiblnMB8EpQo2sBIYGgAooRdDgDkDU3cY9XYk83aaAAeKADC3GjdWd4AymAAntD-gZzebPPc2tyg5MAA1lkAZnyUguTcjsqqYITwDnqodCxfSOWbJNodUbaOqccr7bRgAAOiMQlHKq00FREF0o1SAA&debug=false&circleciRepo=&evaluate=false&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=6.26.0" rel="nofollow noreferrer">Babel you get an error when trying to do this. It's possible that Typescript might want to consider doing this too.


来源: stackexchange

答:
I believe your question is why can't we use let key word...

In TypeScript:

This is merely a syntactic choice I suppose, but class properties do not need a keyword. You can optionally add a public keyword or if you want the class property to be private for the type you can use the private keyword:

```<code>class Greeter {
  greeting: string;
  // or
  public greeting: string;
  //alternatively
  private greeting: string;
</code>```

This is just to define the property for the purposes of the type. Later, when you do:

```<code>const greeter = new Greeter;
</code>```

Now you will be able to use greeter.greeting and all string methods and TypeScript will transpile successfully. If greeting were not declared you would get an error when attempting to transpile

Property 'greeting' does not exist on type 'Greeter'

In JavaScript:

There is currently no way to declare class properties in JavaScript at all. It's intentionally not supported.

ContentLicense: CC BY-SA 4.0

Title: Why can't we use the let keyword inside a class in typescript

Body:
I believe your question is why can't we use let key word...

In TypeScript:

This is merely a syntactic choice I suppose, but class properties do not need a keyword. You can optionally add a public keyword or if you want the class property to be private for the type you can use the private keyword:

class Greeter {
  greeting: string;
  // or
  public greeting: string;
  //alternatively
  private greeting: string;

This is just to define the property for the purposes of the type. Later, when you do:

const greeter = new Greeter;

Now you will be able to use greeter.greeting and all string methods and TypeScript will transpile successfully. If greeting were not declared you would get an error when attempting to transpile

Property 'greeting' does not exist on type 'Greeter'

In JavaScript:

There is currently no way to declare class properties in JavaScript at all. It's intentionally not supported.

ContentLicense: CC BY-SA 3.0


问:
QPushButton background-color overlaps border
I am using QPushButton class and adding the object to a QGraphicsProxyWidget after setting the style sheet.  However, when I set a border-radius, the background-color still overlaps the border. How do I get rid of this?

Example: (where levelOneEasyProxy is QGrpahicsProxyWidget)

```<code>QPushButton* levelOneEasyButton = new QPushButton();
levelOneEasyButton->setGeometry(QRect(sceneRect().width()*0.05, sceneRect().height()*0.2, 70, 50));
levelOneEasyButton->setText("1");
levelOneEasyButton->setStyleSheet("QPushButton {"
                                  "background-color: rgb(92, 249, 158);"
                                  "color: white;"
                                  "font-size: 16px;"
                                  "border-style: solid;"
                                  "border-width: 2px;"
                                  "border-radius: 10px;"
                                  "}"
                                  "QPushButton:pressed {"
                                  "background-color: rgb(66, 191, 118);"
                                  "}");
levelOneEasyProxy = addWidget(levelOneEasyButton);
levelOneEasyProxy->setZValue(10.0);
</code>```

Current Result:

答:
I discovered that using the code above will set the border-radius but the background needs to be set to translucent by using setAttribute on the QPushButton.  This can be done with the following code:

```<code>qPushButtonObject->setAttribute(Qt::WA_TranslucentBackground);
</code>```

This will get rid of the overlapping background-color.

Body:
I am using QPushButton class and adding the object to a QGraphicsProxyWidget after setting the style sheet.  However, when I set a border-radius, the background-color still overlaps the border. How do I get rid of this?

Example: (where levelOneEasyProxy is QGrpahicsProxyWidget)

QPushButton* levelOneEasyButton = new QPushButton();
levelOneEasyButton->setGeometry(QRect(sceneRect().width()*0.05, sceneRect().height()*0.2, 70, 50));
levelOneEasyButton->setText("1");
levelOneEasyButton->setStyleSheet("QPushButton {"
                                  "background-color: rgb(92, 249, 158);"
                                  "color: white;"
                                  "font-size: 16px;"
                                  "border-style: solid;"
                                  "border-width: 2px;"
                                  "border-radius: 10px;"
                                  "}"
                                  "QPushButton:pressed {"
                                  "background-color: rgb(66, 191, 118);"
                                  "}");
levelOneEasyProxy = addWidget(levelOneEasyButton);
levelOneEasyProxy->setZValue(10.0);

Current Result:

Body:
I discovered that using the code above will set the border-radius but the background needs to be set to translucent by using setAttribute on the QPushButton.  This can be done with the following code:

qPushButtonObject->setAttribute(Qt::WA_TranslucentBackground);

This will get rid of the overlapping background-color.


问:
SQL: How to select one row per day
I have a database that has a row entry for every minute (86,000 values per day) and I am trying to write PHP to select only one row per day. I have a column "timestamp" that has the current timestamp in regular format (2017-12-09 06:49:02).

Does anyone know how to write a select statement to do what I am trying to do?

Example output:

```<code>2017-12-09 06:49:02, datavalue
2017-12-10 06:49:02, datavalue
2017-12-11 06:49:02, datavalue
2017-12-12 06:49:02, datavalue
</code>```

答:
Here is one method:</p>

```<code>select t.*
from t join
     (select min(t2.timestamp) as min_timestamp
      from t t2
      group by date(t2.timestamp)
     ) t2
     on t.timestamp = t2.min_timestamp;
</code>```

Title: SQL: How to select one row per day

Body:
I have a database that has a row entry for every minute (86,000 values per day) and I am trying to write PHP to select only one row per day. I have a column "timestamp" that has the current timestamp in regular format (2017-12-09 06:49:02).

Does anyone know how to write a select statement to do what I am trying to do?

Example output:

2017-12-09 06:49:02, datavalue
2017-12-10 06:49:02, datavalue
2017-12-11 06:49:02, datavalue
2017-12-12 06:49:02, datavalue

Body:
Here is one method:

select t.*
from t join
     (select min(t2.timestamp) as min_timestamp
      from t t2
      group by date(t2.timestamp)
     ) t2
     on t.timestamp = t2.min_timestamp;


问:
Is there any possible to map the default response in dialogflow
```
1st question: Tell me about fees
Response from Intent: Tuition fees or transportation fees
2nd question: Tuition fees
Response from Intent:Please select Grade
3rd question: Grade1
```

Is there any possible way to map both 2nd question and 3rd question such as"tuition fees Grade 1"?

答:
One solution is to use required entities. This is how I solved the problem:

I created entities:

I listed things that the user may say. I also matched the entities that the user may say to the entities that I created.

I set the entities as required

I defined custom prompts for the required entities.

I made a response saying what the person selected. Instead of just repeating what the users says here, you may want to call a webhook. Here I talk about webhooks.

Body:
1st question: Tell me about fees
Response from Intent: Tuition fees or transportation fees
2nd question: Tuition fees
Response from Intent:Please select Grade
3rd question: Grade1

Is there any possible way to map both 2nd question and 3rd question such as"tuition fees Grade 1"?


问:
Ruby - Create a class with a file as a variable - possible?
I need to create a program in which the user can take different tests. As i dont want to copy paste my code all over for every test, i have tried to setup a class for that purpose - but i have problems with this class.
Error message =  undefined variables or method in 'display_test'

I have predefined som test as a .txt file

I want to choose the file in the class depending on what the user answer - is that possible?

Class code:

```<code>  class Test

    @correct_answers = 0

def display_question( question, options, answer )
  puts question
  options.each_with_index { |option, idx| puts "#{ idx + 1 }: #{ option
}" }
  print 'Answer: '
  reply = gets.to_i
  if answer == reply
    puts 'Correct!'
    @correct_answers += 1
    puts "#{@correct_answers}"
  else
    puts 'Wrong. The correct answer was: ' + answer.to_s
  end
end

def display_test()
f = File.new(userinput, 'r')

while ! (f.eof?)        #logikken til at splitte
   line = f.gets()
   question = line.split("|")
   question[1] = question[1].split(";")
   display_question question[0], question[1], question[2].to_i
 end
end

display_test

puts "________________________________________________________"
puts "Total score:"

puts "You've got" + " #{@correct_answers}" + " correct answers!"
</code>```

Before hand i have used ("geografitest.txt") instead of username in the File.new so it looked like this:

```<code>f = File.new('geografitest.txt','r')
</code>```

But now i am trying to let the user decide what test to take.

I am very new to ruby, so please bear with me.
I have tried to do it this way, which obviously is not working.

```<code>puts "Which test do you want to take?"

select = 0

while (select != 3)
  puts "Press 1 to take Geografi test."
  puts "Press 2 to take Math test."
  puts "Press 3 to take Religion test."
  puts "Press 3 to exit"
  select = gets.chomp.to_i

if (select == 1)
  gets.chomp = userinput
  userinput =`geografitest.txt`
  echo $userinput
end

if (select == 2)
  gets.chomp = userinput
  userinput =`matematiktest.txt`
  echo $userinput
  end

if (select == 3)
  gets.chomp = userinput
  userinput =`religionstest.txt`
  echo $userinput
end
if (select > 4)
  puts "Not a correct selection"

elsif (select == 4)
  puts "Goodbye"
end

end
abort
</code>```

So my questions is now;
How can i make the user choose what test to take? Can i make a variable instead of the textfile as i have tried, but in a different way? Or is there a smarter way?

And in what way is my class wrong and how do i fix it? I know its not the way to make it, but i simple cant get my head around how to make it right.

Please help a rookie out.
Cheers!

答:
You can pass file as dependency to you Test class based on user input with object constructor. Something like this

class Test
  attr_reader :correct_answers_count

  def initialize(file)
    @file = file
    @correct_answers_count = 0
  end

  #other code goes here
end

loop do
  case user_input = gets.chomp
  when '1'
    file_name = 'some_file1'
  when '2'
    file_name = 'some_file1'
  when '3'
    break
  else
    puts 'wrong variant'
  end

  test = Test.new(File.new(file_name, 'r'))
  test.display
end
```

Body:
I need to create a program in which the user can take different tests. As i dont want to copy paste my code all over for every test, i have tried to setup a class for that purpose - but i have problems with this class.
Error message =  undefined variables or method in 'display_test'

I have predefined som test as a .txt file

I want to choose the file in the class depending on what the user answer - is that possible?

Class code:

  class Test

    @correct_answers = 0

def display_question( question, options, answer )
  puts question
  options.each_with_index { |option, idx| puts "#{ idx + 1 }: #{ option
}" }
  print 'Answer: '
  reply = gets.to_i
  if answer == reply
    puts 'Correct!'
    @correct_answers += 1
    puts "#{@correct_answers}"
  else
    puts 'Wrong. The correct answer was: ' + answer.to_s
  end
end

def display_test()
f = File.new(userinput, 'r')

while ! (f.eof?)        #logikken til at splitte
   line = f.gets()
   question = line.split("|")
   question[1] = question[1].split(";")
   display_question question[0], question[1], question[2].to_i
 end
end

display_test

puts "________________________________________________________"
puts "Total score:"

puts "You've got" + " #{@correct_answers}" + " correct answers!"

Before hand i have used ("geografitest.txt") instead of username in the File.new so it looked like this:

f = File.new('geografitest.txt','r')

But now i am trying to let the user decide what test to take.

I am very new to ruby, so please bear with me.
I have tried to do it this way, which obviously is not working.

puts "Which test do you want to take?"

select = 0

while (select != 3)
  puts "Press 1 to take Geografi test."
  puts "Press 2 to take Math test."
  puts "Press 3 to take Religion test."
  puts "Press 3 to exit"
  select = gets.chomp.to_i

if (select == 1)
  gets.chomp = userinput
  userinput =`geografitest.txt`
  echo $userinput
end

if (select == 2)
  gets.chomp = userinput
  userinput =`matematiktest.txt`
  echo $userinput
  end

if (select == 3)
  gets.chomp = userinput
  userinput =`religionstest.txt`
  echo $userinput
end
if (select > 4)
  puts "Not a correct selection"

elsif (select == 4)
  puts "Goodbye"
end

end
abort

So my questions is now;
How can i make the user choose what test to take? Can i make a variable instead of the textfile as i have tried, but in a different way? Or is there a smarter way?

And in what way is my class wrong and how do i fix it? I know its not the way to make it, but i simple cant get my head around how to make it right.

Please help a rookie out.
Cheers!


问:
java StringTokenizer - can nextToken return null?
Is there any case where StringTokenizer.nextToken will return null?
I'm trying to debug a NullPointerException in my code, and so far the only possibility I've found is that the string returned from nextToken() returned null. Is that a possibility? Didn't find anything in the java doc.

Thanks

答:
I think it can throw a NullPointerException.

Inspecting the code of nextToken(),

```<code>public String nextToken() {
        /*
         * If next position already computed in hasMoreElements() and
         * delimiters have changed between the computation and this invocation,
         * then use the computed value.
         */

        currentPosition = (newPosition >= 0 && !delimsChanged) ?
            newPosition : skipDelimiters(currentPosition);

        /* Reset these anyway */
        delimsChanged = false;
        newPosition = -1;

        if (currentPosition >= maxPosition)
            throw new NoSuchElementException();
        int start = currentPosition;
        currentPosition = scanToken(currentPosition);
        return str.substring(start, currentPosition);
    }
</code>```

Here, invocation of the method skipDelimiters() can throw NullPointerException.

```<code>private int skipDelimiters(int startPos) {
        if (delimiters == null)
            throw new NullPointerException();

        int position = startPos;
        while (!retDelims && position < maxPosition) {
            if (!hasSurrogates) {
                char c = str.charAt(position);
                if ((c > maxDelimCodePoint) || (delimiters.indexOf(c) < 0))
                    break;
                position++;
            } else {
                int c = str.codePointAt(position);
                if ((c > maxDelimCodePoint) || !isDelimiter(c)) {
                    break;
                }
                position += Character.charCount(c);
            }
        }
        return position;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I think it can throw a NullPointerException.

Inspecting the code of nextToken(),

public String nextToken() {
        /*
         * If next position already computed in hasMoreElements() and
         * delimiters have changed between the computation and this invocation,
         * then use the computed value.
         */

        currentPosition = (newPosition >= 0 && !delimsChanged) ?
            newPosition : skipDelimiters(currentPosition);

        /* Reset these anyway */
        delimsChanged = false;
        newPosition = -1;

        if (currentPosition >= maxPosition)
            throw new NoSuchElementException();
        int start = currentPosition;
        currentPosition = scanToken(currentPosition);
        return str.substring(start, currentPosition);
    }

Here, invocation of the method skipDelimiters() can throw NullPointerException.

private int skipDelimiters(int startPos) {
        if (delimiters == null)
            throw new NullPointerException();

        int position = startPos;
        while (!retDelims && position < maxPosition) {
            if (!hasSurrogates) {
                char c = str.charAt(position);
                if ((c > maxDelimCodePoint) || (delimiters.indexOf(c) < 0))
                    break;
                position++;
            } else {
                int c = str.codePointAt(position);
                if ((c > maxDelimCodePoint) || !isDelimiter(c)) {
                    break;
                }
                position += Character.charCount(c);
            }
        }
        return position;
    }


问:
Custom map in Swift
I am currently developing an iOS application using location.
But I want to have a customized map to show user's location, not the default map given by MapKit.

A map like this for example :

Is it possible to achieve something like this in Swift 4.0 ?

Thanks a lot

答:
This is how you can make a map show your live current location.

Full code:

```<code>    import UIKit
import MapKit

//import CoreLocation

class ViewController: UIViewController, UIScrollViewDelegate ,CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet var map: MKMapView!

    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let userLocation: CLLocation = locations[0]

        let latitude = userLocation.coordinate.latitude

        let longitude = userLocation.coordinate.longitude

        let latDelta: CLLocationDegrees = 0.05

        let lonDelta: CLLocationDegrees = 0.05

        let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)

        let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

        let region = MKCoordinateRegion(center: location, span: span)

        self.map.setRegion(region, animated: false)

        let annotation = MKPointAnnotation()
        annotation.coordinate = location
        annotation.title = "My current Location"

        map.addAnnotation(annotation)

    }

}
</code>```

Note that you also have to add the permissions to the info.plist file
the permissions are:

Privacy - Location When In Use Usage Description

Privacy - Location Always Usage Description

Title: Custom map in Swift

Body:
This is how you can make a map show your live current location.

Full code:

    import UIKit
import MapKit

//import CoreLocation

class ViewController: UIViewController, UIScrollViewDelegate ,CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet var map: MKMapView!

    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let userLocation: CLLocation = locations[0]

        let latitude = userLocation.coordinate.latitude

        let longitude = userLocation.coordinate.longitude

        let latDelta: CLLocationDegrees = 0.05

        let lonDelta: CLLocationDegrees = 0.05

        let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)

        let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

        let region = MKCoordinateRegion(center: location, span: span)

        self.map.setRegion(region, animated: false)

        let annotation = MKPointAnnotation()
        annotation.coordinate = location
        annotation.title = "My current Location"

        map.addAnnotation(annotation)

    }

}

Note that you also have to add the permissions to the info.plist file
the permissions are:

Privacy - Location When In Use Usage Description

Privacy - Location Always Usage Description


问:
dplyr: want to add only 1 y column during a join, not all y columns
I need to join a table with itself in order to realize inheritance of a value in one column, as follows:
There are two types of rows, base and dep (for "dependent").
All rows have a key, but dep rows also have a basekey referring to a base row. There is a column val and any number of other columns.

My goal: Obtain all dep rows, with their val replaced by the val of the corresponding base row.

Here is an example:

```<code>library(tidyverse)

tb = tribble(
    ~key, ~type, ~basekey, ~val, ~col5, ~colN,
    "a", "base", NA,       17,   1,      100,
    "b", "base", NA,       21,   4,      130,
    "d", "dep",  "a",      NA,   11,     320,
    "g", "dep",  "a",      NA,   14,     420,
    "n", "dep",  "a",      NA,   13,     230,
    "y", "dep",  "b",      NA,   66,     665
)
</code>```

My actual data has a few hundred rows and N=20 columns, so runtime or memory performance is not an issue, but operations requiring a complete column list should be avoided.

sqldf

Previously, I used the sqldf package, which can express my requirement nicely:

```<code>sqldf("select tb.*, tb2.val as baseval
       from tb, tb as tb2
       where tb2.key = tb.basekey")
</code>```

The result is almost exactly what I want; I only need to map baseval to val or live with the longer name (which is OK for me):

```<code>  key type basekey val col5 colN baseval
1   d  dep       a  NA   11  320      17
2   g  dep       a  NA   14  420      17
3   n  dep       a  NA   13  230      17
4   y  dep       b  NA   66  665      21
</code>```

dplyr

But then I started learning ggplot2 and encountered the tidyverse.
After some reading, I decided to throw myself into its arms and rework my code according to its readable and tidy style.

readr and tibble worked like a charm, but with dplyr I am not yet entirely happy; my use case appears to be one that is not supported well (maybe it's just that my thinking is not taking the best route yet).

I need to do a left join, but although all I want is the val column, there appears to be no method (as of dplyr 0.7.4) for suppressing the others:

```<code>tbj = left_join(filter(tb, type=='dep'), tb, by=c(basekey='key'))
</code>```

which gives me this:

```<code># A tibble: 4 x 11
    key type.x basekey val.x col5.x colN.x type.y basekey.y val.y col5.y colN.y
  <chr>  <chr>   <chr> <dbl>  <dbl>  <dbl>  <chr>     <chr> <dbl>  <dbl>  <dbl>
1     d    dep       a    NA     11    320   base      <NA>    17      1    100
2     g    dep       a    NA     14    420   base      <NA>    17      1    100
3     n    dep       a    NA     13    230   base      <NA>    17      1    100
4     y    dep       b    NA     66    665   base      <NA>    21      4    130
</code>```

Whew! To get what I want, I now need to

Map val.y to val.

Kick out all the other *.y columns

Kick out val.x

Rename the other *.x columns to remove the suffix

This sounds laborious.
How to do it best?
Is this even the right approach or is there a more dplyr-ish way to achieve my goal?

答:
First, you join the two tables and then select the columns needed. You can take advantage of the argument suffix by leaving the column names of the first table unchanged. Then selecting all columns from the first table and adding the needed column from the second table: val.y.

 All columns from the first table plus val.y from the second.

```<code>tb %>% filter(type == "dep") %>%
  left_join(tb %>% filter(type == "base"),
            by = c("basekey" = "key"),
            suffix = c("", ".y")) %>%
  select(names(tb), "val.y")
</code>```

Output:

```<code># A tibble: 4 x 7
    key  type basekey   val  col5  colN val.y
  <chr> <chr>   <chr> <dbl> <dbl> <dbl> <dbl>
1     d   dep       a    NA    11   320    17
2     g   dep       a    NA    14   420    17
3     n   dep       a    NA    13   230    17
4     y   dep       b    NA    66   665    21
</code>```

 All columns but column val from the first table , plus val.y from the second.
:

```<code>tb %>% filter(type == "dep") %>%
  left_join(tb %>% filter(type == "base"),
            by = c("basekey" = "key"),
            suffix = c("", ".y")) %>%
  select(names(tb), -val, "val.y")
</code>```

Output:

```<code># A tibble: 4 x 6
    key  type basekey  col5  colN val.y
  <chr> <chr>   <chr> <dbl> <dbl> <dbl>
1     d   dep       a    11   320    17
2     g   dep       a    14   420    17
3     n   dep       a    13   230    17
4     y   dep       b    66   665    21
</code>```

Body:
I need to join a table with itself in order to realize inheritance of a value in one column, as follows:
There are two types of rows, base and dep (for "dependent").
All rows have a key, but dep rows also have a basekey referring to a base row. There is a column val and any number of other columns.

My goal: Obtain all dep rows, with their val replaced by the val of the corresponding base row.

Here is an example:

library(tidyverse)

tb = tribble(
    ~key, ~type, ~basekey, ~val, ~col5, ~colN,
    "a", "base", NA,       17,   1,      100,
    "b", "base", NA,       21,   4,      130,
    "d", "dep",  "a",      NA,   11,     320,
    "g", "dep",  "a",      NA,   14,     420,
    "n", "dep",  "a",      NA,   13,     230,
    "y", "dep",  "b",      NA,   66,     665
)

My actual data has a few hundred rows and N=20 columns, so runtime or memory performance is not an issue, but operations requiring a complete column list should be avoided.

sqldf

Previously, I used the sqldf package, which can express my requirement nicely:

sqldf("select tb.*, tb2.val as baseval
       from tb, tb as tb2
       where tb2.key = tb.basekey")

The result is almost exactly what I want; I only need to map baseval to val or live with the longer name (which is OK for me):

  key type basekey val col5 colN baseval
1   d  dep       a  NA   11  320      17
2   g  dep       a  NA   14  420      17
3   n  dep       a  NA   13  230      17
4   y  dep       b  NA   66  665      21

dplyr

But then I started learning ggplot2 and encountered the tidyverse.
After some reading, I decided to throw myself into its arms and rework my code according to its readable and tidy style.

readr and tibble worked like a charm, but with dplyr I am not yet entirely happy; my use case appears to be one that is not supported well (maybe it's just that my thinking is not taking the best route yet).

I need to do a left join, but although all I want is the val column, there appears to be no method (as of dplyr 0.7.4) for suppressing the others:

tbj = left_join(filter(tb, type=='dep'), tb, by=c(basekey='key'))

which gives me this:

# A tibble: 4 x 11
    key type.x basekey val.x col5.x colN.x type.y basekey.y val.y col5.y colN.y
  <chr>  <chr>   <chr> <dbl>  <dbl>  <dbl>  <chr>     <chr> <dbl>  <dbl>  <dbl>
1     d    dep       a    NA     11    320   base      <NA>    17      1    100
2     g    dep       a    NA     14    420   base      <NA>    17      1    100
3     n    dep       a    NA     13    230   base      <NA>    17      1    100
4     y    dep       b    NA     66    665   base      <NA>    21      4    130

Whew! To get what I want, I now need to

Map val.y to val.

Kick out all the other *.y columns

Kick out val.x

Rename the other *.x columns to remove the suffix

This sounds laborious.
How to do it best?
Is this even the right approach or is there a more dplyr-ish way to achieve my goal?

Body:
First, you join the two tables and then select the columns needed. You can take advantage of the argument suffix by leaving the column names of the first table unchanged. Then selecting all columns from the first table and adding the needed column from the second table: val.y.

 All columns from the first table plus val.y from the second.

tb %>% filter(type == "dep") %>%
  left_join(tb %>% filter(type == "base"),
            by = c("basekey" = "key"),
            suffix = c("", ".y")) %>%
  select(names(tb), "val.y")

Output:

# A tibble: 4 x 7
    key  type basekey   val  col5  colN val.y
  <chr> <chr>   <chr> <dbl> <dbl> <dbl> <dbl>
1     d   dep       a    NA    11   320    17
2     g   dep       a    NA    14   420    17
3     n   dep       a    NA    13   230    17
4     y   dep       b    NA    66   665    21

 All columns but column val from the first table , plus val.y from the second.
:

tb %>% filter(type == "dep") %>%
  left_join(tb %>% filter(type == "base"),
            by = c("basekey" = "key"),
            suffix = c("", ".y")) %>%
  select(names(tb), -val, "val.y")

Output:

# A tibble: 4 x 6
    key  type basekey  col5  colN val.y
  <chr> <chr>   <chr> <dbl> <dbl> <dbl>
1     d   dep       a    11   320    17
2     g   dep       a    14   420    17
3     n   dep       a    13   230    17
4     y   dep       b    66   665    21


问:
JavaScript: How to clear most significant bit?
I'm currently working on a coding challenge that tasks me with converting an integer to a hex value and clearing the MSB. I can use (####).toString(16) to get the integer into a hex but I'm not sure how to clear the MSB.</p>

答:
To unset the MSB in a 16 unsigned integer, just use</p>

```<code>value &= 0x7FFF;
</code>```

Body:
To unset the MSB in a 16 unsigned integer, just use

value &= 0x7FFF;


问:
How to call global function from promise function?
When performing the below function:

```<code>        try {
            Auction.deployed().then(function(contractInstance) {
                contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
                    console.log("AUCTION HAS STARTED!!");
                    console.log(result);
                    updateAuction(result.receipt);
                });
            });
        } catch (err) {}
    }
};

updateAuction = function(data) {
    console.log("UPDATE AUCTIONS!");
....
</code>```

The updateAuction function is not called (even though the console.log functions are working correctly and displaying a message). How can I call the updateAuction function?

答:
```<code>var updateAuction = function(data) {
    console.log("UPDATE AUCTIONS!");
    ...
}

try {
            Auction.deployed().then(function(contractInstance) {
                contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
                    console.log("AUCTION HAS STARTED!!");
                    console.log(result);
                    updateAuction(result.receipt);
                });
            });
        } catch (err) {}
</code>```

Body:
When performing the below function:

        try {
            Auction.deployed().then(function(contractInstance) {
                contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
                    console.log("AUCTION HAS STARTED!!");
                    console.log(result);
                    updateAuction(result.receipt);
                });
            });
        } catch (err) {}
    }
};

updateAuction = function(data) {
    console.log("UPDATE AUCTIONS!");
....

The updateAuction function is not called (even though the console.log functions are working correctly and displaying a message). How can I call the updateAuction function?


问:
Handling information from a prolog sentence parser
I have created a sentence parser in prolog. It successfully parses sentences that are inputted with...
?- sentence([input,sentence,here],Parse).

This is the code I'm using to parse the sentence:

```<code>np([X|T],np(det(X),NP2),Rem):- /* Det NP2 */
    det(X),
    np2(T,NP2,Rem).
np(Sentence,Parse,Rem):- np2(Sentence,Parse,Rem). /* NP2 */
np(Sentence,np(NP,PP),Rem):- /* NP PP */
    np(Sentence,NP,Rem1),
    pp(Rem1,PP,Rem).

np2([H|T],np2(noun(H)),T):- noun(H). /* Noun */
np2([H|T],np2(adj(H),Rest),Rem):- adj(H),np2(T,Rest,Rem).

pp([H|T],pp(prep(H),Parse),Rem):- /* PP NP */
    prep(H),
    np(T,Parse,Rem).

vp([H| []], vp(verb(H))):- /* Verb */
    verb(H).

vp([H|T], vp(verb(H), Rem)):- /* VP PP */
    vp(H, Rem),
    pp(T, Rem, _).

vp([H|T], vp(verb(H), Rem)):- /* Verb NP */
    verb(H),
    np(T, Rem, _).
</code>```

I should mention that the output would be: sentence(np(det(a), np2(adj(very), np2(adj(young), np2(noun(boy))))), vp(verb(loves), np(det(a), np2(adj(manual), np2(noun(problem)))))).

Using the predefined vocabulary: det(a), adj(very), adj(young), noun(boy), verb(loves), det(a), adj(manual), noun(problem).

What I want to do is pass the parsed output to predicates that would separate the words into three different categories, which are "subject, verb, and object".

(1) The subject will hold the first two adjectives and then a noun.

(2) The verb will hold the verb from the "verb phrase".

(3) And the object will hold the adjectives and nouns in the "verb phrase".

All determiners should be ignored.

For example, I would want a predicate that would look for adjectives in the output.

I have tried many things to try and get this working but none work. Any help will be much appreciated.

答:
The DCG below produces this behaviour:

```<code>?- s(Sem,[a,young,boy,loves,a,manual,problem],[]).
Sem = [noun(boy),verb(loves),noun(problem)]
</code>```

There are some problems in your grammar. Your third np clause calls itself directly (not consuming input in between), which means infinite loop. The grammar you posted does not seem to be able to produce your output (very young). Anyway, here is the DCG:

```<code>s(Sem) -->
  np(Sem1), vp(Sem2), { append(Sem1,Sem2,Sem) }.

np(Sem) -->
  [W], { det(W) },
  np2(Sem).
np(Sem) -->
  np2(Sem).
np(Sem) -->
  np2(Sem1),
  pp(Sem2), { append(Sem1,Sem2,Sem) }.

np2([noun(W)]) -->
  [W], { noun(W) }.
np2(Sem) -->
  [W], { adj(W) },
  np2(Sem).

pp(Sem) -->
  [W], { prep(W) },
  np(Sem).

vp([verb(W)]) -->
  [W], { verb(W) }.
vp(Sem) -->
  [W], { verb(W) },
  np(Sem0), { Sem = [verb(W)|Sem0] }.
vp(Sem) -->
  [W], { verb(W) },
  pp(Sem0), { Sem = [verb(W)|Sem0] }.
</code>```

Addition: if you want to handle modification (e.g. adjectives), then there are simple obvious solutions that quickly become impractical, and then there are more general techniques, like adding a logical variable to the np.

```<code>np(X,Sem) -->
  [W], { det(W) },
  np2(X,Sem).
np(X,Sem) -->
  np2(X,Sem).
np(X,Sem) -->
  np2(X,Sem1),
  pp(Sem2), { append(Sem1,Sem2,Sem) }.

np2(X,[noun(X,W)]) -->
  [W], { noun(W) }.
np2(X,[adj(X,W)|Sem]) -->
  [W], { adj(W) },
  np2(X,Sem).
</code>```

This variable (X) is never instantiated, it only serves to link the parts of the noun phrase meaning together.

```<code>?- s(Sem,[a,young,boy,loves,a,manual,problem],[]).
Sem = [adj(_A,young),noun(_A,boy),verb(loves),adj(_B,manual),noun(_B,problem)]
</code>```

There are various additional possibilities. Good books are Gazdar & Mellish, NLP in Prolog, and Norvig, Paradigms of AI programming (if you speak Lisp), as well as Pereira & Shieber, Prolog and natural-language analysis.

Addition #2: after reading your question again, and this other question, I realised that you actually want three separate lists. No problem.

```<code>s(L1,L2,L3) -->
  np(_,L1), vp(L2,L3).

np(X,L) -->
  [W], { det(W) },
  np2(X,L).
np(X,L) -->
  np2(X,L).
np(X,L) -->
  np2(X,L),
  pp(_).

np2(X,[noun(X,W)]) -->
  [W], { noun(W) }.
np2(X,[adj(X,W)|L]) -->
  [W], { adj(W) },
  np2(X,L).

pp(L) -->
  [W], { prep(W) },
  np(_,L).

vp([verb(W)],[]) -->
  [W], { verb(W) }.
vp([verb(W)],L) -->
  [W], { verb(W) },
  np(_,L).
vp([verb(W)],L) -->
  [W], { verb(W) },
  pp(L).
</code>```

Output:

```<code>| ?- s(L1,L2,L3,[a,young,boy,loves,a,manual,problem],[]).
L1 = [adj(_A,young),noun(_A,boy)],
L2 = [verb(loves)],
L3 = [adj(_B,manual),noun(_B,problem)] ?
</code>```

Now maybe you don't need the logical variables, but one the other hand, you could have more complicated modifiers, like "a young boy loves a manual problem involving red bolts and white cubes". Then the variables would keep track of which adjective modifies which noun.

Body:
I have created a sentence parser in prolog. It successfully parses sentences that are inputted with...
?- sentence([input,sentence,here],Parse).

This is the code I'm using to parse the sentence:

np([X|T],np(det(X),NP2),Rem):- /* Det NP2 */
    det(X),
    np2(T,NP2,Rem).
np(Sentence,Parse,Rem):- np2(Sentence,Parse,Rem). /* NP2 */
np(Sentence,np(NP,PP),Rem):- /* NP PP */
    np(Sentence,NP,Rem1),
    pp(Rem1,PP,Rem).

np2([H|T],np2(noun(H)),T):- noun(H). /* Noun */
np2([H|T],np2(adj(H),Rest),Rem):- adj(H),np2(T,Rest,Rem).

pp([H|T],pp(prep(H),Parse),Rem):- /* PP NP */
    prep(H),
    np(T,Parse,Rem).

vp([H| []], vp(verb(H))):- /* Verb */
    verb(H).

vp([H|T], vp(verb(H), Rem)):- /* VP PP */
    vp(H, Rem),
    pp(T, Rem, _).

vp([H|T], vp(verb(H), Rem)):- /* Verb NP */
    verb(H),
    np(T, Rem, _).

I should mention that the output would be: sentence(np(det(a), np2(adj(very), np2(adj(young), np2(noun(boy))))), vp(verb(loves), np(det(a), np2(adj(manual), np2(noun(problem)))))).

Using the predefined vocabulary: det(a), adj(very), adj(young), noun(boy), verb(loves), det(a), adj(manual), noun(problem).

What I want to do is pass the parsed output to predicates that would separate the words into three different categories, which are "subject, verb, and object".

(1) The subject will hold the first two adjectives and then a noun.

(2) The verb will hold the verb from the "verb phrase".

(3) And the object will hold the adjectives and nouns in the "verb phrase".

All determiners should be ignored.

For example, I would want a predicate that would look for adjectives in the output.

I have tried many things to try and get this working but none work. Any help will be much appreciated.

Body:
The DCG below produces this behaviour:

?- s(Sem,[a,young,boy,loves,a,manual,problem],[]).
Sem = [noun(boy),verb(loves),noun(problem)]

There are some problems in your grammar. Your third np clause calls itself directly (not consuming input in between), which means infinite loop. The grammar you posted does not seem to be able to produce your output (very young). Anyway, here is the DCG:

s(Sem) -->
  np(Sem1), vp(Sem2), { append(Sem1,Sem2,Sem) }.

np(Sem) -->
  [W], { det(W) },
  np2(Sem).
np(Sem) -->
  np2(Sem).
np(Sem) -->
  np2(Sem1),
  pp(Sem2), { append(Sem1,Sem2,Sem) }.

np2([noun(W)]) -->
  [W], { noun(W) }.
np2(Sem) -->
  [W], { adj(W) },
  np2(Sem).

pp(Sem) -->
  [W], { prep(W) },
  np(Sem).

vp([verb(W)]) -->
  [W], { verb(W) }.
vp(Sem) -->
  [W], { verb(W) },
  np(Sem0), { Sem = [verb(W)|Sem0] }.
vp(Sem) -->
  [W], { verb(W) },
  pp(Sem0), { Sem = [verb(W)|Sem0] }.

Addition: if you want to handle modification (e.g. adjectives), then there are simple obvious solutions that quickly become impractical, and then there are more general techniques, like adding a logical variable to the np.

np(X,Sem) -->
  [W], { det(W) },
  np2(X,Sem).
np(X,Sem) -->
  np2(X,Sem).
np(X,Sem) -->
  np2(X,Sem1),
  pp(Sem2), { append(Sem1,Sem2,Sem) }.

np2(X,[noun(X,W)]) -->
  [W], { noun(W) }.
np2(X,[adj(X,W)|Sem]) -->
  [W], { adj(W) },
  np2(X,Sem).

This variable (X) is never instantiated, it only serves to link the parts of the noun phrase meaning together.

?- s(Sem,[a,young,boy,loves,a,manual,problem],[]).
Sem = [adj(_A,young),noun(_A,boy),verb(loves),adj(_B,manual),noun(_B,problem)]

There are various additional possibilities. Good books are Gazdar & Mellish, NLP in Prolog, and Norvig, Paradigms of AI programming (if you speak Lisp), as well as Pereira & Shieber, Prolog and natural-language analysis.

Addition #2: after reading your question again, and this other question, I realised that you actually want three separate lists. No problem.

s(L1,L2,L3) -->
  np(_,L1), vp(L2,L3).

np(X,L) -->
  [W], { det(W) },
  np2(X,L).
np(X,L) -->
  np2(X,L).
np(X,L) -->
  np2(X,L),
  pp(_).

np2(X,[noun(X,W)]) -->
  [W], { noun(W) }.
np2(X,[adj(X,W)|L]) -->
  [W], { adj(W) },
  np2(X,L).

pp(L) -->
  [W], { prep(W) },
  np(_,L).

vp([verb(W)],[]) -->
  [W], { verb(W) }.
vp([verb(W)],L) -->
  [W], { verb(W) },
  np(_,L).
vp([verb(W)],L) -->
  [W], { verb(W) },
  pp(L).

Output:

| ?- s(L1,L2,L3,[a,young,boy,loves,a,manual,problem],[]).
L1 = [adj(_A,young),noun(_A,boy)],
L2 = [verb(loves)],
L3 = [adj(_B,manual),noun(_B,problem)] ?

Now maybe you don't need the logical variables, but one the other hand, you could have more complicated modifiers, like "a young boy loves a manual problem involving red bolts and white cubes". Then the variables would keep track of which adjective modifies which noun.


问:
There is blank space present at the top of website page
I am creating a web page. Even though i have added margin:0px and padding:0px still some blank space is present at the top of my web page. here is my css code for body section.Any solutions?Thanx in advance..</p>

```<code><html >
    <head>
       <style>

        html {
          margin: 0;
          padding: 0;
        }
        #navR
        {float:right;
        margin-right:0px;
        }
        #mR{
        float: right;
        }
        .bodyl{
         height: 100%;
        background-color: #F8FADE;
        font-family: Arial;
        font-size:15px;
        margin:0px;
        top: -22px;
         clear: both;
        }
        .local{
            background-color:#DEB887;
            margin-left:0px;
            margin-right:0px;
            margin-top:0px;
            margin-bottom:0px;
            padding:0px;
            width:100%;
            vertical-align: baseline;
            }
            .heading{
            font-size: 250%;
            color:#5B3205;
            margin-top:10px;

            font-style: oblique;
        }
        </style>
    </head>
    <body>
         <div class="local">
            <p id="mR"><strong>My name</strong></p>
            <h3 id="navR"> <a>logout</a> </h3>
            <h1 class="heading">My space</h1>
        </div> </br>
            </body>
        </html>
</code>```

答:
Please also set margin to 0 on your html attribute

```<code>body, html {
  margin: 0;
  padding: 0;
}
</code>```

Then it should work perfectly for you, as it does for me. It could also be possible that you have a child attribute that has a certain margin and so it could lead to that white space.

Body:
I am creating a web page. Even though i have added margin:0px and padding:0px still some blank space is present at the top of my web page. here is my css code for body section.Any solutions?Thanx in advance..

My name

 logout

My space

Body:
Please also set margin to 0 on your html attribute

body, html {
  margin: 0;
  padding: 0;
}

Then it should work perfectly for you, as it does for me. It could also be possible that you have a child attribute that has a certain margin and so it could lead to that white space.


问:
PHP Array: Calculate difference among values in same array
I am trying to compute the difference between all values in an array and store them (the differences) in a single array.

An ideal example would be something like this:

```<code><?php

$data = array('1', '5', '12');

// Compute the difference between each value with another value.

?>
</code>```

And then I like to have the following results in an array:

```<code>4, 11, 7
</code>```

How can I achieve it?

答:
Check this https://3v4l.org/9oiqs

```<code>$data = [1, 5, 12, 15, 20, 25,];

function getDifferences($aValues)
{
    $aDiff = [];
    $iSize = count($aValues);
    for ($i = 0; $i < $iSize; $i++)
    {
        for ($j = $i + 1; $j < $iSize; $j++)
        {
            $aDiff[$aValues[$i]][] = abs($aValues[$i] - $aValues[$j]);
        }
    }
    return $aDiff;
}

function printDifferences($aValues){
    foreach ($aValues as $iNumber => $aDiffs){
        echo "Differences for $iNumber: " . implode(', ', $aDiffs) . PHP_EOL;
    }
}

$aDiff = getDifferences($data);
printDifferences($aDiff);
</code>```

Result

  Differences for 1: 4, 11, 14, 19, 24

  Differences for 5: 7, 10, 15, 20

  Differences for 12: 3, 8, 13

  Differences for 15: 5, 10

  Differences for 20: 5

Body:
I am trying to compute the difference between all values in an array and store them (the differences) in a single array.

An ideal example would be something like this:

<?php

$data = array('1', '5', '12');

// Compute the difference between each value with another value.

?>

And then I like to have the following results in an array:

4, 11, 7

How can I achieve it?

Body:
Check this https://3v4l.org/9oiqs

$data = [1, 5, 12, 15, 20, 25,];

function getDifferences($aValues)
{
    $aDiff = [];
    $iSize = count($aValues);
    for ($i = 0; $i < $iSize; $i++)
    {
        for ($j = $i + 1; $j < $iSize; $j++)
        {
            $aDiff[$aValues[$i]][] = abs($aValues[$i] - $aValues[$j]);
        }
    }
    return $aDiff;
}

function printDifferences($aValues){
    foreach ($aValues as $iNumber => $aDiffs){
        echo "Differences for $iNumber: " . implode(', ', $aDiffs) . PHP_EOL;
    }
}

$aDiff = getDifferences($data);
printDifferences($aDiff);

Result

  Differences for 1: 4, 11, 14, 19, 24

  Differences for 5: 7, 10, 15, 20

  Differences for 12: 3, 8, 13

  Differences for 15: 5, 10

  Differences for 20: 5


问:
No module named 'tqdm'
I am running the following pixel recurrent neural network (RNN) code using Python 3.6

```<code>import os
import logging

import numpy as np
from tqdm import trange
import tensorflow as tf

from utils import *
from network import Network
from statistic import Statistic
</code>```

However, there was an error:

```<code>ModuleNotFoundError: No module named 'tqdm'
</code>```

Does anyone know how to solve it?

答:
For Python 3 as you specified, you use the pip3 command, like so...

```<code>pip3 install tqdm
</code>```

For Python 2, you use pip command, like so...

```<code>pip install tqdm
</code>```

Hope this helps!

Title: No module named 'tqdm'

Body:
I am running the following pixel recurrent neural network (RNN) code using Python 3.6

import os
import logging

import numpy as np
from tqdm import trange
import tensorflow as tf

from utils import *
from network import Network
from statistic import Statistic

However, there was an error:

ModuleNotFoundError: No module named 'tqdm'

Does anyone know how to solve it?

Body:
For Python 3 as you specified, you use the pip3 command, like so...

pip3 install tqdm

For Python 2, you use pip command, like so...

pip install tqdm

Hope this helps!


问:
how to handle interactive shell in fabric python
1.after executing expect('OPR>','show alef-users') it go to infinite means it
  run continuesly.</p>

```<code>from fabric.api import *
from fabric.context_managers import settings
from ilogue.fexpect import expect, expecting, run

prompts = []
prompts += expect('Username:','kirti')
prompts += expect('Password:','kirti')
prompts += expect('OPR>','show users')
prompts +=expect('OPR>','exit')
env.password = "kirti@123"
with cd('/home/kirti/opr'):
with expecting(prompts):
run('./kirti', combine_stderr=False)
</code>```

答:
Fabric >= 1.9 allows to handle multiple prompts at the same time, in a single with clause: you just have use Fabric's settings function, and feed it with a dict; the keys will be the questions, and the values will be the answers. In your case, it will look like :

```<code>with settings(prompts={'Username:':'admin',
                       'Password:':'admin',
                       'OPR>':'show alef-users',
                       'OPR>':'exit'}):
    run('./go_opr_cli', combine_stderr=False)
</code>```

My answer is inspired by that section of Fabric's official documentation. It worked very well for me, but make sure, when writing the dict's keys, that you respect the number of spaces between the last character of the question and the cursor, in the command line, otherwise it will fail.

Example: The last prompt is 'OPR>'. If you see in the regular Linux CLI, that there is one space between 'OPR>' and the cursor, then the key should be 'OPR> '

Body:
1.after executing expect('OPR>','show alef-users') it go to infinite means it
  run continuesly.

from fabric.api import *
from fabric.context_managers import settings
from ilogue.fexpect import expect, expecting, run

prompts = []
prompts += expect('Username:','kirti')
prompts += expect('Password:','kirti')
prompts += expect('OPR>','show users')
prompts +=expect('OPR>','exit')
env.password = "kirti@123"
with cd('/home/kirti/opr'):
with expecting(prompts):
run('./kirti', combine_stderr=False)

Body:
Fabric >= 1.9 allows to handle multiple prompts at the same time, in a single with clause: you just have use Fabric's settings function, and feed it with a dict; the keys will be the questions, and the values will be the answers. In your case, it will look like :

with settings(prompts={'Username:':'admin',
                       'Password:':'admin',
                       'OPR>':'show alef-users',
                       'OPR>':'exit'}):
    run('./go_opr_cli', combine_stderr=False)

My answer is inspired by that section of Fabric's official documentation. It worked very well for me, but make sure, when writing the dict's keys, that you respect the number of spaces between the last character of the question and the cursor, in the command line, otherwise it will fail.

Example: The last prompt is 'OPR>'. If you see in the regular Linux CLI, that there is one space between 'OPR>' and the cursor, then the key should be 'OPR> '


问:
Run powershell from an ASP.net web app as a different user?
I want to be able to run a powershell script from an ASP.NET app as a different user. I can successfully run powershell commands and see the output but I cannot figure out how to execute it as a different user.
I have followed this guide:

http://jeffmurr.com/blog/?p=142

It is just a textbox where I enter my powershell-command and the output will show in another textbox.

I have created a new IIS site and an application pool which runs as a domain user, associated the new site with the pool. I can see that the only w3wp.exe process that exist is running as my domain user that I specified in the pool. Still if I run the command:

```<code>write-output $Env:USERNAME
</code>```

It returns the System Account username, "SERVERNAME$".
Anybody knows why? What have I missed? Is there another way to achieve the same?

The code...

HTML:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PowerShellExecution.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
    <div>
        <table>
            <tr><td> </td><td><h1 align="left">PowerShell Command Harness</h1></td></tr>
            <tr><td> </td><td> </td></tr>
            <tr><td> </td><td>PowerShell Command</td></tr>
            <tr><td>
                <br />
                </td><td>
                <asp:TextBox ID="Input" runat="server" TextMode="MultiLine" Width="433px" Height="73px" ></asp:TextBox>
            </td></tr>
            <tr><td>
                 </td><td>
                <asp:Button ID="ExecuteCode" runat="server" Text="Execute" Width="200" onclick="ExecuteCode_Click" />
            </td></tr>
                <tr><td> </td><td><h3>Result</h3></td></tr>
                <tr><td>
                     </td><td>
                    <asp:TextBox ID="ResultBox" TextMode="MultiLine" Width="700" Height="200" runat="server"></asp:TextBox>
            </td></tr>
        </table>
    </div>
</form>
</body>
</html>
</code>```

C#

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Text;

namespace PowerShellExecution
{
    public partial class Default : System.Web.UI.Page
    {
        public TextBox ResultBox;
        public TextBox Input;

        protected void Page_Load(object sender, EventArgs e)
        {
            ResultBox = (TextBox)this.FindControl("ResultBox");
            Input = (TextBox)this.FindControl("Input");
        }

        protected void ExecuteCode_Click(object sender, EventArgs e)
        {
            // Clean the Result TextBox
            ResultBox.Text = string.Empty;

            // Initialize PowerShell engine
            var shell = PowerShell.Create();

            // Add the script to the PowerShell object
            shell.Commands.AddScript(Input.Text);
            // shell.Commands.AddScript("C:\\TestSite\\test.ps1");

            // Execute the script
            var results = shell.Invoke();

            // display results, with BaseObject converted to string
            // Note : use |out-string for console-like output
            if (results.Count > 0)
            {
                // We use a string builder ton create our result text
                var builder = new StringBuilder();

                foreach (var psObject in results)
                {
                    // Convert the Base Object to a string and append it to the string builder.
                    // Add \r\n for line breaks
                    builder.Append(psObject.BaseObject.ToString() + "\r\n");
                }

                // Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
                ResultBox.Text = Server.HtmlEncode(builder.ToString());
            }
        }
    }
}
</code>```

答:
its because you have published your website on a host server. When you access the website you are accessing an application that is running on Azure (or wherever the server is) and therefore sending command that runs in that server machine.

Sorry to say that you cant get those command run in your computer as a website user since the script calling method is developed in a way to ensure user environment safe otherwise unknown dangerous codes can execute at their end by just pushing the button.

If you used Azure, then note that its a 'platform as a service' where your role is to deploy website and build application over a preconfigured system and is managed by Azure. Any system level changes including user name change are not permitted. try out https://yourwebsitename.scm.azurewebsites.net/DebugConsole/?shell=powershell

I tried to change it too sometime back but learned the hard way.

Body:
I want to be able to run a powershell script from an ASP.NET app as a different user. I can successfully run powershell commands and see the output but I cannot figure out how to execute it as a different user.
I have followed this guide:

http://jeffmurr.com/blog/?p=142

It is just a textbox where I enter my powershell-command and the output will show in another textbox.

I have created a new IIS site and an application pool which runs as a domain user, associated the new site with the pool. I can see that the only w3wp.exe process that exist is running as my domain user that I specified in the pool. Still if I run the command:

write-output $Env:USERNAME

It returns the System Account username, "SERVERNAME$".
Anybody knows why? What have I missed? Is there another way to achieve the same?

The code...

HTML:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PowerShellExecution.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

<form id="form1" runat="server">

PowerShell Command Harness

 	PowerShell Command

                <asp:TextBox ID="Input" runat="server" TextMode="MultiLine" Width="433px" Height="73px" ></asp:TextBox>

                <asp:Button ID="ExecuteCode" runat="server" Text="Execute" Width="200" onclick="ExecuteCode_Click" />

Result

                    <asp:TextBox ID="ResultBox" TextMode="MultiLine" Width="700" Height="200" runat="server"></asp:TextBox>

</form>

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Text;

namespace PowerShellExecution
{
    public partial class Default : System.Web.UI.Page
    {
        public TextBox ResultBox;
        public TextBox Input;

        protected void Page_Load(object sender, EventArgs e)
        {
            ResultBox = (TextBox)this.FindControl("ResultBox");
            Input = (TextBox)this.FindControl("Input");
        }

        protected void ExecuteCode_Click(object sender, EventArgs e)
        {
            // Clean the Result TextBox
            ResultBox.Text = string.Empty;

            // Initialize PowerShell engine
            var shell = PowerShell.Create();

            // Add the script to the PowerShell object
            shell.Commands.AddScript(Input.Text);
            // shell.Commands.AddScript("C:\\TestSite\\test.ps1");

            // Execute the script
            var results = shell.Invoke();

            // display results, with BaseObject converted to string
            // Note : use |out-string for console-like output
            if (results.Count > 0)
            {
                // We use a string builder ton create our result text
                var builder = new StringBuilder();

                foreach (var psObject in results)
                {
                    // Convert the Base Object to a string and append it to the string builder.
                    // Add \r\n for line breaks
                    builder.Append(psObject.BaseObject.ToString() + "\r\n");
                }

                // Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
                ResultBox.Text = Server.HtmlEncode(builder.ToString());
            }
        }
    }
}


问:
Better way to write many if statements in Java?
So I have this homework where I need to build a vending machine, and I assigned a coordinate to every product (A1, A2, A3..) and when the user enters the coin value I have to calculate if he can buy the product that he chose and if yes calculate the change, since i'm still new to programming I now have ended up with many statements like this

```<code>if ("a1".equals(choice)) {
    System.out.println("You chose SNICKERS!");
    if (money < 50) {
        System.out.println("This is not enough money to buy this product");
    } else if (money >= 50) {
        System.out.println(" Price = 50  Your change = " + (money - 50));
    }
}
</code>```

where the only things changing are the coordinates (a1, a2, a3, a4, b1, b2 and so on) and the prices. What would be a better way to do this?

答:
Switch case is the desired functionality.
```<code>switch(choice) {
    case 'a' : <some code>
         break;
    case 'b': <some other code>
         break;
    default: <if none of the choices matched>
}
</code>```

The only caveat is that your choice value has to be a char or an int

EDIT:

This was a bad answer from my side. Clearly, you need a more cleaner way to write your vending machine.

A good way to structure it would be to first create a Product class which can store the name and the price of the product.

class Product {
    private String name;
    private String price;

    // Implement a constructor and an equals() method to equate two
    // instances of product
}
```
<ul>
<li>You could then create a function (which could be used in your <code>main()</code>) which takes the text input from your user and map it to an actual product.</li>
</ul>
<pre class="lang-java prettyprint-override"><code>public static Main(String[] args) {
    // ...
    private Product processUserInput(String productName) {
        // Add logic to process the string and return a Product
    }
    // ...
}
</code>```

Then you could add a function that would process the Product and the amount the user has and return the change remaining or maybe -1 if the product costs more than the available amount.

public static Main(String[] args) {
    // ...
    private int processUserProductChoice(Product product, int amountAvailable) {
        // Add logic to process the product and amount
        // Probably use switch case now.
    }
    // ...
}
```

Body:
So I have this homework where I need to build a vending machine, and I assigned a coordinate to every product (A1, A2, A3..) and when the user enters the coin value I have to calculate if he can buy the product that he chose and if yes calculate the change, since i'm still new to programming I now have ended up with many statements like this

if ("a1".equals(choice)) {
    System.out.println("You chose SNICKERS!");
    if (money < 50) {
        System.out.println("This is not enough money to buy this product");
    } else if (money >= 50) {
        System.out.println(" Price = 50  Your change = " + (money - 50));
    }
}

where the only things changing are the coordinates (a1, a2, a3, a4, b1, b2 and so on) and the prices. What would be a better way to do this?

Body:
Switch case is the desired functionality.

switch(choice) {
    case 'a' : <some code>
         break;
    case 'b': <some other code>
         break;
    default: <if none of the choices matched>
}

The only caveat is that your choice value has to be a char or an int

EDIT:

This was a bad answer from my side. Clearly, you need a more cleaner way to write your vending machine.

A good way to structure it would be to first create a Product class which can store the name and the price of the product.

class Product {
    private String name;
    private String price;

    // Implement a constructor and an equals() method to equate two
    // instances of product
}

You could then create a function (which could be used in your main()) which takes the text input from your user and map it to an actual product.

public static Main(String[] args) {
    // ...
    private Product processUserInput(String productName) {
        // Add logic to process the string and return a Product
    }
    // ...
}

Then you could add a function that would process the Product and the amount the user has and return the change remaining or maybe -1 if the product costs more than the available amount.

public static Main(String[] args) {
    // ...
    private int processUserProductChoice(Product product, int amountAvailable) {
        // Add logic to process the product and amount
        // Probably use switch case now.
    }
    // ...
}


问:
FireFox word breaks OK with css, but one letter at a time, not where hyphens go
FireFox word breaks OK with css, but one letter at a time, not where hyphens are supposed to be???

NOT FireFox:

FireFox:

Here's the CSS:

```<code>.superLongStuff {
    /*
        SUPER LOOOOOOOOOOOONG WORD STUFF ...
    */
    /* These are technically the same, but use both */
    overflow-wrap: break-word;
    word-wrap:     break-word;

    -ms-word-break: break-all;
    /* This is the dangerous one in WebKit, as it breaks things wherever */
    word-break:     break-all;
    /* Instead use this non-standard one: */
    word-break:     break-word;

    /* Adds a hyphen where the word breaks, if supported (No Blink) */
    -ms-hyphens:     auto;
    -moz-hyphens:    auto;
    -webkit-hyphens: auto;
    hyphens:         auto;
}
</code>```

答:
When you want to use hyphenation don't use word-break. Let the browser automatically insert hyphens where appropriate.</p>

```<code>.superLongStuff {
    -ms-hyphens:     auto;
    -moz-hyphens:    auto;
    -webkit-hyphens: auto;
    hyphens:         auto;
}
</code>```

Body:
FireFox word breaks OK with css, but one letter at a time, not where hyphens are supposed to be???

NOT FireFox:

FireFox:

Here's the CSS:

.superLongStuff {
    /*
        SUPER LOOOOOOOOOOOONG WORD STUFF ...
    */
    /* These are technically the same, but use both */
    overflow-wrap: break-word;
    word-wrap:     break-word;

    -ms-word-break: break-all;
    /* This is the dangerous one in WebKit, as it breaks things wherever */
    word-break:     break-all;
    /* Instead use this non-standard one: */
    word-break:     break-word;

    /* Adds a hyphen where the word breaks, if supported (No Blink) */
    -ms-hyphens:     auto;
    -moz-hyphens:    auto;
    -webkit-hyphens: auto;
    hyphens:         auto;
}

Body:
When you want to use hyphenation don't use word-break. Let the browser automatically insert hyphens where appropriate.

.superLongStuff {
    -ms-hyphens:     auto;
    -moz-hyphens:    auto;
    -webkit-hyphens: auto;
    hyphens:         auto;
}


问:
Haskell: Retrieve nth value from type which is a tuple
I am trying to access some data inside a type from an imported package.

The type is declared (by the package authors) as so:

```<code>newtype MultiBalanceReport =
  MultiBalanceReport ([DateSpan]
                     ,[MultiBalanceReportRow]
                     ,MultiBalanceReportTotals
                     )
</code>```

And I'm trying to extract the first list in the type with a function like so:

```<code>getDates :: MultiBalanceReport -> [DateSpan]
getDates (date,_,_) = date
</code>```

But when I use the function, the compiler complains that the types aren't the same:

```<code>• Couldn't match expected type ‘MultiBalanceReport’
              with actual type ‘([DateSpan], t7, t8)’
</code>```

I feel like the compiler just doesn't know the inner details of the MultiBalanceReport type? Am I not importing the package which defines the type correctly?

I'm new to Haskell, so sorry if I'm using the wrong nomenclature to try to describe my problem.

答:
You need to include the newtype in your pattern match</p>

```<code>getDates :: MultiBalanceReport -> [DateSpan]
getDates (MultiBalanceReport (date,_,_)) = date
</code>```

Body:
I am trying to access some data inside a type from an imported package.

The type is declared (by the package authors) as so:

newtype MultiBalanceReport =
  MultiBalanceReport ([DateSpan]
                     ,[MultiBalanceReportRow]
                     ,MultiBalanceReportTotals
                     )

And I'm trying to extract the first list in the type with a function like so:

getDates :: MultiBalanceReport -> [DateSpan]
getDates (date,_,_) = date

But when I use the function, the compiler complains that the types aren't the same:

• Couldn't match expected type ‘MultiBalanceReport’
              with actual type ‘([DateSpan], t7, t8)’

I feel like the compiler just doesn't know the inner details of the MultiBalanceReport type? Am I not importing the package which defines the type correctly?

I'm new to Haskell, so sorry if I'm using the wrong nomenclature to try to describe my problem.

Body:
You need to include the newtype in your pattern match

getDates :: MultiBalanceReport -> [DateSpan]
getDates (MultiBalanceReport (date,_,_)) = date


问:
iOS: Capture image from front facing camera
I am making an application where I would like to capture an image from the front facing camera, without presenting a capture screen of any kind. I want to take a picture completely in code without any user interaction. How would I do this for the front facing camera?</p>

答:
Convert above code to Swift 4</p>

```<code>import UIKit
import AVFoundation

class CameraViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {

@IBOutlet weak var cameraImageView: UIImageView!

var device: AVCaptureDevice?
var captureSession: AVCaptureSession?
var previewLayer: AVCaptureVideoPreviewLayer?
var cameraImage: UIImage?

override func viewDidLoad() {
    super.viewDidLoad()

    setupCamera()
    setupTimer()
}

func setupCamera() {
    let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera],
                                                            mediaType: AVMediaType.video,
                                                           position: .front)
    device = discoverySession.devices[0]

    let input: AVCaptureDeviceInput
    do {
        input = try AVCaptureDeviceInput(device: device!)
    } catch {
        return
    }

    let output = AVCaptureVideoDataOutput()
    output.alwaysDiscardsLateVideoFrames = true

    let queue = DispatchQueue(label: "cameraQueue")
    output.setSampleBufferDelegate(self, queue: queue)
    output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable as! String: kCVPixelFormatType_32BGRA]

    captureSession = AVCaptureSession()
    captureSession?.addInput(input)
    captureSession?.addOutput(output)
    captureSession?.sessionPreset = AVCaptureSession.Preset.photo

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
    previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    previewLayer?.frame = CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: view.frame.height)

    view.layer.insertSublayer(previewLayer!, at: 0)

        captureSession?.startRunning()
    }

    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
    CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0))
        let baseAddress = UnsafeMutableRawPointer(CVPixelBufferGetBaseAddress(imageBuffer!))
        let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!)
        let width = CVPixelBufferGetWidth(imageBuffer!)
        let height = CVPixelBufferGetHeight(imageBuffer!)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let newContext = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo:
        CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)

        let newImage = newContext!.makeImage()
         cameraImage = UIImage(cgImage: newImage!)

        CVPixelBufferUnlockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0))
    }

    func setupTimer() {
        _ = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(snapshot), userInfo: nil, repeats: true)
    }

    @objc func snapshot() {
        print("SNAPSHOT")
        cameraImageView.image = cameraImage
    }
}
</code>```

Body:
Convert above code to Swift 4

import UIKit
import AVFoundation

class CameraViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {

@IBOutlet weak var cameraImageView: UIImageView!

var device: AVCaptureDevice?
var captureSession: AVCaptureSession?
var previewLayer: AVCaptureVideoPreviewLayer?
var cameraImage: UIImage?

override func viewDidLoad() {
    super.viewDidLoad()

    setupCamera()
    setupTimer()
}

func setupCamera() {
    let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera],
                                                            mediaType: AVMediaType.video,
                                                           position: .front)
    device = discoverySession.devices[0]

    let input: AVCaptureDeviceInput
    do {
        input = try AVCaptureDeviceInput(device: device!)
    } catch {
        return
    }

    let output = AVCaptureVideoDataOutput()
    output.alwaysDiscardsLateVideoFrames = true

    let queue = DispatchQueue(label: "cameraQueue")
    output.setSampleBufferDelegate(self, queue: queue)
    output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable as! String: kCVPixelFormatType_32BGRA]

    captureSession = AVCaptureSession()
    captureSession?.addInput(input)
    captureSession?.addOutput(output)
    captureSession?.sessionPreset = AVCaptureSession.Preset.photo

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
    previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    previewLayer?.frame = CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: view.frame.height)

    view.layer.insertSublayer(previewLayer!, at: 0)

        captureSession?.startRunning()
    }

    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
    CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0))
        let baseAddress = UnsafeMutableRawPointer(CVPixelBufferGetBaseAddress(imageBuffer!))
        let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!)
        let width = CVPixelBufferGetWidth(imageBuffer!)
        let height = CVPixelBufferGetHeight(imageBuffer!)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let newContext = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo:
        CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)

        let newImage = newContext!.makeImage()
         cameraImage = UIImage(cgImage: newImage!)

        CVPixelBufferUnlockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0))
    }

    func setupTimer() {
        _ = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(snapshot), userInfo: nil, repeats: true)
    }

    @objc func snapshot() {
        print("SNAPSHOT")
        cameraImageView.image = cameraImage
    }
}


问:
Capture Currency in Span Class, Divide by 12 Round up and Display
I'm not very good at this and have tried last few days searching up and down for any kind of answer to help solve my problem.  I've only pieced together the below.  I would like to grab the generated span class value, / by 12, round up to the nearest penny and than display elsewhere on the same webpage.  Any help would be greatly appreciated and thank you in advance.

const price = document.getElementsByClassName('price-value')[0].innerHTML;  // Price of item before tax

// Calculate total after tax to two decimal places
let totalPrice = price / 12;
totalPrice.toFixed(2);

document.getElementById("demo").innerHTML =totalPrice```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="price-value model-price-value-sale">
         $1,349.95
        </span>
                <p id="demo"></p></code>```

答:
First you need to convert the price from currency to an actual number by:

```<code>Number(price.replace(/[^0-9\.-]+/g,""))
</code>```

Then use the Math.ceil() function to round up.

So it will be like that:

const price = document.getElementsByClassName('price-value')[0].innerHTML;  // Price of item before tax

// Calculate total after tax to two decimal places
//let totalPrice = Math.ceil(Number(price.replace(/[^0-9\.-]+/g,"")) / 12);

let totalPrice = Math.round((Number(price.replace(/[^0-9\.-]+/g,"")) / 12)* 100)/100;

document.getElementById("demo").innerHTML =totalPrice```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="price-value model-price-value-sale">
         $1,349.95
        </span>
                <p id="demo"></p></code>```

Body:
I'm not very good at this and have tried last few days searching up and down for any kind of answer to help solve my problem.  I've only pieced together the below.  I would like to grab the generated span class value, / by 12, round up to the nearest penny and than display elsewhere on the same webpage.  Any help would be greatly appreciated and thank you in advance.

const price = document.getElementsByClassName('price-value')[0].innerHTML;  // Price of item before tax

// Calculate total after tax to two decimal places
let totalPrice = price / 12;
totalPrice.toFixed(2);

document.getElementById("demo").innerHTML =totalPrice

         $1,349.95

Body:
First you need to convert the price from currency to an actual number by:

Number(price.replace(/[^0-9\.-]+/g,""))

Then use the Math.ceil() function to round up.

So it will be like that:

const price = document.getElementsByClassName('price-value')[0].innerHTML;  // Price of item before tax

// Calculate total after tax to two decimal places
//let totalPrice = Math.ceil(Number(price.replace(/[^0-9\.-]+/g,"")) / 12);

let totalPrice = Math.round((Number(price.replace(/[^0-9\.-]+/g,"")) / 12)* 100)/100;

document.getElementById("demo").innerHTML =totalPrice

<span class="price-value model-price-value-sale">
         $1,349.95
        </span>
                <p id="demo"></p>


问:
How can I remove existing fields in the default User DB in Django?

I have created and AbstractUser with some fields that I want the User Class to have. But after successfully creating a new User Model, the user table now has the previous columns (the ones which would have been added on migration of the default User Model) and also has the columns which I have added in the Custom User Model.

Is there a way to remove the columns which are added by default?

Here's my models.py

```<code>class CustomUser(AbstractUser):
    ''' SOME UNIQUE FIELDS '''
    class Meta:
        swappable = 'AUTH_USER_MODEL'
        db_table = 'users'
</code>```

These are the fields that appear even without specifying in the model. How can I get rid of them?

答:
As you are extending the model AbstractUser, it has all the fields of that class, https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#extending-django-s-default-user.

If you want a complete custom user, you should extend AbstractBaseUser. https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#specifying-a-custom-user-model.

Body:
I have created and AbstractUser with some fields that I want the User Class to have. But after successfully creating a new User Model, the user table now has the previous columns (the ones which would have been added on migration of the default User Model) and also has the columns which I have added in the Custom User Model.

Is there a way to remove the columns which are added by default?

Here's my models.py

class CustomUser(AbstractUser):
    ''' SOME UNIQUE FIELDS '''
    class Meta:
        swappable = 'AUTH_USER_MODEL'
        db_table = 'users'

These are the fields that appear even without specifying in the model. How can I get rid of them?


问:
Laravel app deploy on linux server using nginx got 404 error
This is my last step for my class final project. I follow the steps from the Digital-Ocean {{ https://www.digitalocean.com/community/tutorials/how-to-deploy-a-laravel-application-with-nginx-on-ubuntu-16-04 }} but I got the 404 error when I call the URL.

The following code is the nginx configuration. As I am a new to laravel, i also don't know how to deploy it. This is my first time deployment using the server also.

```<code>    # Default server configuration
    #
    server {
            listen 80;
            listen [::]:80;
 # SSL configuration
        #
         #listen 443 ssl http2;
        # listen [::]:443 ssl http2;

        access_log            /var/log/nginx/jenkins.access.log;
        error_log            /var/log/nginx/jenkins.error.log;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
 # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/ssl-marikhu.com.conf;
        #include snippest/ssl-params.conf;

        root /var/www/laravel/smartroom/public;

        # Add index.php to the list if you are using PHP
        index index.php index.html index.htm index.ngix-debian.html;

        server_name marikhu.com www.marikhu.com;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
  try_files $uri $uri//index.php?query_string;
                include /etc/nginx/proxy_params;
                proxy_pass          http://localhost:8080;
                proxy_read_timeout  90s;
                # Fix potential "It appears that your reverse proxy set up is b$
                proxy_redirect      http://localhost:8080 https://marikhu.com;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
      location ~ \.php$ {
                include snippets/fastcgi-php.conf;
        #
        #       # With php7.0-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php7.0-fpm:
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        }

        # deny access to .htaccess files, if Apache's document root
  # concurs with nginx's one
        #
        location ~ /\.ht {
                deny all;
        }

    listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/marikhu.com/fullchain.pem; # managed by C$
ssl_certificate_key /etc/letsencrypt/live/marikhu.com/privkey.pem; # managed by$
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
}

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name moodymountains.marikhu.com;
#
#       root /var/www/html;
#       index index.php;
#
}

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name moodymountains.marikhu.com;
#
#       root /var/www/html;
#       index index.php;
#
}

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name moodymountains.marikhu.com;
#
#       root /var/www/html;
#       index index.php;
#}
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}
</code>```

答:
Replace this block

```<code>location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
  try_files $uri $uri//index.php?query_string;
                include /etc/nginx/proxy_params;
                proxy_pass          http://localhost:8080;
                proxy_read_timeout  90s;
                # Fix potential "It appears that your reverse proxy set up is b$
                proxy_redirect      http://localhost:8080 https://marikhu.com;
        }
</code>```

with this:

```<code>location / {
    try_files $uri $uri/ /index.php?$query_string;
}
</code>```

save the file, restart your nginx server and try to visit again.

Body:
This is my last step for my class final project. I follow the steps from the Digital-Ocean {{ https://www.digitalocean.com/community/tutorials/how-to-deploy-a-laravel-application-with-nginx-on-ubuntu-16-04 }} but I got the 404 error when I call the URL.

The following code is the nginx configuration. As I am a new to laravel, i also don't know how to deploy it. This is my first time deployment using the server also.

    # Default server configuration
    #
    server {
            listen 80;
            listen [::]:80;
 # SSL configuration
        #
         #listen 443 ssl http2;
        # listen [::]:443 ssl http2;

        access_log            /var/log/nginx/jenkins.access.log;
        error_log            /var/log/nginx/jenkins.error.log;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
 # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/ssl-marikhu.com.conf;
        #include snippest/ssl-params.conf;

        root /var/www/laravel/smartroom/public;

        # Add index.php to the list if you are using PHP
        index index.php index.html index.htm index.ngix-debian.html;

        server_name marikhu.com www.marikhu.com;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
  try_files $uri $uri//index.php?query_string;
                include /etc/nginx/proxy_params;
                proxy_pass          http://localhost:8080;
                proxy_read_timeout  90s;
                # Fix potential "It appears that your reverse proxy set up is b$
                proxy_redirect      http://localhost:8080 https://marikhu.com;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
      location ~ \.php$ {
                include snippets/fastcgi-php.conf;
        #
        #       # With php7.0-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php7.0-fpm:
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        }

        # deny access to .htaccess files, if Apache's document root
  # concurs with nginx's one
        #
        location ~ /\.ht {
                deny all;
        }

    listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/marikhu.com/fullchain.pem; # managed by C$
ssl_certificate_key /etc/letsencrypt/live/marikhu.com/privkey.pem; # managed by$
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
}

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name moodymountains.marikhu.com;
#
#       root /var/www/html;
#       index index.php;
#
}

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name moodymountains.marikhu.com;
#
#       root /var/www/html;
#       index index.php;
#
}

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name moodymountains.marikhu.com;
#
#       root /var/www/html;
#       index index.php;
#}
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}

Body:
Replace this block

location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
  try_files $uri $uri//index.php?query_string;
                include /etc/nginx/proxy_params;
                proxy_pass          http://localhost:8080;
                proxy_read_timeout  90s;
                # Fix potential "It appears that your reverse proxy set up is b$
                proxy_redirect      http://localhost:8080 https://marikhu.com;
        }

with this:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

save the file, restart your nginx server and try to visit again.


问:
WCF and return Custom collection
How any method of WCF application can return custom collection to calling environment.
please help with sample code.

thanks.

答:
First of all, you need to define an interface as a ServiceContract and the method that returns the Custom Collection as an OperationContract. I will give you the code in VB.net, bus is very very easy to translate it to c#

```<code>Imports System.ServiceModel
<ServiceContract()>
Public Interface IClientContract

    <OperationContract()>
    Function GetClientList() As IList(Of POCOClients)

End Interface
</code>```

Here, the IList(of POCOClients) is the custom collection. Then, implement the interface.

```<code>Public Class ClientContractImplementation
    Implements IClientContract

    Private ClientOp As IClientsOperations

    Sub New()
'I use a IoC container here, but you can make a standar New() at this point'
        ClientOp = BLIoC.Container.Resolve(Of IClientsOperations)()
    End Sub

    Public Function GetClientList() As System.Collections.Generic.IList(Of ServiceLayerContract.POCOClients) Implements ServiceLayerContract.IClientContract.GetClientList

        Return ClientOp.SearchClients()

    End Function
End Class
</code>```

And, then you need to configure the app.config to expose the WCF service, in the Service.ServiceModel section:

```<code></endpoint>
<endpoint address="mex" binding="mexHttpBinding" name="MEX" contract="IMetadataExchange"/>
<host>
  <baseAddresses>
    <add baseAddress="http://localhost:81/Client"/>
  </baseAddresses>
</host>
</code>```

Now, when a client calls to the service, a custom collection of IList(Of POCOClients) (or whatever you want) will be returned.

Title: WCF and return Custom collection

Body:
First of all, you need to define an interface as a ServiceContract and the method that returns the Custom Collection as an OperationContract. I will give you the code in VB.net, bus is very very easy to translate it to c#

Imports System.ServiceModel
<ServiceContract()>
Public Interface IClientContract

    <OperationContract()>
    Function GetClientList() As IList(Of POCOClients)

End Interface

Here, the IList(of POCOClients) is the custom collection. Then, implement the interface.

Public Class ClientContractImplementation
    Implements IClientContract

    Private ClientOp As IClientsOperations

    Sub New()
'I use a IoC container here, but you can make a standar New() at this point'
        ClientOp = BLIoC.Container.Resolve(Of IClientsOperations)()
    End Sub

    Public Function GetClientList() As System.Collections.Generic.IList(Of ServiceLayerContract.POCOClients) Implements ServiceLayerContract.IClientContract.GetClientList

        Return ClientOp.SearchClients()

    End Function
End Class

And, then you need to configure the app.config to expose the WCF service, in the Service.ServiceModel section:

</endpoint>
<endpoint address="mex" binding="mexHttpBinding" name="MEX" contract="IMetadataExchange"/>
<host>
  <baseAddresses>
    <add baseAddress="http://localhost:81/Client"/>
  </baseAddresses>
</host>

Now, when a client calls to the service, a custom collection of IList(Of POCOClients) (or whatever you want) will be returned.


问:
Can't load expo app: Something went wrong
I've created an expo app with exp init MyApp command and started it by running exp start in MyApp directory.

Then I'm scanning barcode which was printed in console with expo mobile app on android device.

Then "Something went wrong" screen is rendered instead of the app.

View log shows "Uncaught Error: Couldn't load exp://.....".

No errors in expo packager console output.

It used to work sometimes ago.

答:
I had the same problem and fixed it on Windows 10 by making my machine discoverable on the network:

Click wifi icon in app drawer.

Go to the list of wifi connections and click your connection.

Click "Properties". This opens up the page associated with your connection.

Under "Make this PC discoverable", turn the slider to "On".


问:
From where is GitHub taking the time of the push?
If I change time on my computer, then commit and push, I saw github takes the time that it was set on my pc when I commited my changes. Is there a way to make github show the real hour/date?</p>

答:
The time of the push doesn't matter; you can push the same commit many times on many remote repositories. It is not stored anywhere.

Each commit stores two timestamps: the time when it was created (author date) and the time when it was applied (committer date). These times are identical when the commit is created. The committer date changes when the commit is amended, applied from a patch, cherry-picked, rebased etc.

These timestamps are, by default, generated using the current time on the computer where the commit is created/updated but you can override them if needed.

Read more about the difference between author and committer in the Git book.