问:
How to create a link with parameter in django
Hi I am trying to create a link with paremeter but I am getting an error (Page not found)

error

```<code>Reverse for 'hexcode' with arguments '('#d4cbd0',)' not found. 1 pattern(s) tried: ['hexcode/(?P<color>\\w)$']
</code>```

template

```<code>{% for color in palette_dominant_color %}
<a href="{% url 'brandcolors:hexcode' color %}" style="text-decoration:none;color:inherit">
  {{color}}
</a>
<br>
{% endfor %}
</code>```

urls.py

```<code>url(r'^hexcode/(?P<color>\w)/$', ThemeView.as_view(), name="hexcode"),
</code>```

views.py

```<code>class ThemeView(TemplateView):
    template_name='fabric/theme.html'

    def get_context_data(self, **kwargs):
        context = super(ThemeView, self).get_context_data(**kwargs)
        colors = Color.objects.filter(color=kwargs['color']).all()
        return context
</code>```

答:
Your link should be:</p>

```<code><a href="{% url 'brandcolors:hexcode' color=color %}" style="text-decoration:none;color:inherit">{{color}}</a>
</code>```

Body:
Hi I am trying to create a link with paremeter but I am getting an error (Page not found)

error

Reverse for 'hexcode' with arguments '('#d4cbd0',)' not found. 1 pattern(s) tried: ['hexcode/(?P<color>\\w)$']

template

{% for color in palette_dominant_color %}

  {{color}}

{% endfor %}

urls.py

url(r'^hexcode/(?P<color>\w)/$', ThemeView.as_view(), name="hexcode"),

views.py

class ThemeView(TemplateView):
    template_name='fabric/theme.html'

    def get_context_data(self, **kwargs):
        context = super(ThemeView, self).get_context_data(**kwargs)
        colors = Color.objects.filter(color=kwargs['color']).all()
        return context

Body:
Your link should be:

<a href="{% url 'brandcolors:hexcode' color=color %}" style="text-decoration:none;color:inherit">{{color}}</a>


来源: stackexchange

问:
regex to extract field
I have one regex to extract the scriptname from a full command. It's working fine for most of the cases, but not working for the first row in sample data.

Sample Data

```<code>qcst_out_macroPlayback_13918_14112017-163000.29129.xml
qcst_mxtimingMonitoring.sh -SpecificInputLaunchers
qcst_tps_monitoring.sh -LatestDeals
</code>```

Output Should be

```<code>macroPlayback (not working)
mxtimingMonitoring (working)
monitoring (working)
</code>```

Regex which is not working for 1st row

```<code>\S+_(?<ScriptName>[^\.]+)\.\S+
</code>```

https://regex101.com/r/cFjn85/1

答:
Code

See regex in use here

```<code>^\S+_\K[a-z]+
</code>```

If \K is not available in your flavour of regex, you can use the following instead. This will capture the contents you are looking for into the first capture group.

```<code>^\S+_([a-z]+)
</code>```

Explanation

^ Assert position at start of line

\S+ Match any non-whitespace character one or more times

_ Match the underscore character _ literally

\K Reset the starting point of the reported match. Any previously consumed characters are no longer included in the final match

[a-z]+ Match one or more characters in the set a-z (lowercase ASCII alpha characters)

Note: The modifiers gmi are used to make the regex global, multiline and case-insensitive (to match uppercase ASCII alpha characters with [a-z])

ContentLicense: CC BY-SA 3.0

Title: regex to extract field

Body:
I have one regex to extract the scriptname from a full command. It's working fine for most of the cases, but not working for the first row in sample data.

Sample Data

qcst_out_macroPlayback_13918_14112017-163000.29129.xml
qcst_mxtimingMonitoring.sh -SpecificInputLaunchers
qcst_tps_monitoring.sh -LatestDeals

Output Should be

macroPlayback (not working)
mxtimingMonitoring (working)
monitoring (working)

Regex which is not working for 1st row

\S+_(?

Body:
Code

See regex in use here

^\S+_\K[a-z]+

If \K is not available in your flavour of regex, you can use the following instead. This will capture the contents you are looking for into the first capture group.

^\S+_([a-z]+)

Explanation

^ Assert position at start of line

\S+ Match any non-whitespace character one or more times

_ Match the underscore character _ literally

\K Reset the starting point of the reported match. Any previously consumed characters are no longer included in the final match

[a-z]+ Match one or more characters in the set a-z (lowercase ASCII alpha characters)

Note: The modifiers gmi are used to make the regex global, multiline and case-insensitive (to match uppercase ASCII alpha characters with [a-z])


问:
Modulo and order of operation in Python
In Zed Shaw's Learn Python the Hard Way (page 15-16), he has an example exercise

```<code> 100 - 25 * 3 % 4
</code>```

the result is 97 (try it!)

I cannot see the order of operations that could do this..

100 - 25 = 75

3 % 4 = 0

or (100-25*3) =225 % 4 = ???   but anyhow not 97 I don't think...

A similar example is 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 which yields 7

In what order are the operations done?

答:
Multiplication >> mod >> subtraction

```<code>In [3]: 25 * 3
Out[3]: 75

In [4]: 75 % 4
Out[4]: 3

In [5]: 100 - 3
Out[5]: 97
</code>```

Multiplication and modulo operator have the same precedence, so you evaluate from left to right for this example.

Title: Modulo and order of operation in Python

Body:
In Zed Shaw's Learn Python the Hard Way (page 15-16), he has an example exercise

 100 - 25 * 3 % 4

the result is 97 (try it!)

I cannot see the order of operations that could do this..

100 - 25 = 75

3 % 4 = 0

or (100-25*3) =225 % 4 = ???   but anyhow not 97 I don't think...

A similar example is 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 which yields 7

In what order are the operations done?

Body:
Multiplication >> mod >> subtraction

In [3]: 25 * 3
Out[3]: 75

In [4]: 75 % 4
Out[4]: 3

In [5]: 100 - 3
Out[5]: 97

Multiplication and modulo operator have the same precedence, so you evaluate from left to right for this example.

ContentLicense: CC BY-SA 2.5


问:
Merging two created histograms in order to compare them
I would like to compare election results (Percentatge.of.Votes) of two different candidates by states and plot them in one graphic.

For that I compiled the following:

```<code>swing.obama = filter(swing.states, Candidate == "Barack Obama")

swing.romney = filter(swing.states, Candidate != "Barack Obama")

par(mfrow=c(2,1))

ro.swing = barplot(swing.romney$Percentatge.of.Votes, names.arg = swing.romney$State.or.district,
                    col = "red2", main = "Results by State - Mitt Romney")

ob.swing = barplot(swing.obama$Percentatge.of.Votes, names.arg = swing.obama$State.or.district,
                   col = "darkblue", main = "Results by State - Barack Obama")
</code>```

Here you can see both results in histograms side by side.

Results by State:

How can "merge" the two files in order to get the blue and red bars side by side?

答:
Please test this ggplot2 solution:

```<code>library(ggplot2)
ggplot(swing.states,
       aes(State.or.district, Percentatge.of.Votes, fill = Candidate)) +
geom_bar(stat = "identity", position = "dodge") +
labs(title = "Results by state",
     x = "State/district",
     y = "Votes, %")
</code>```

Body:
I would like to compare election results (Percentatge.of.Votes) of two different candidates by states and plot them in one graphic.

For that I compiled the following:

swing.obama = filter(swing.states, Candidate == "Barack Obama")

swing.romney = filter(swing.states, Candidate != "Barack Obama")

par(mfrow=c(2,1))

ro.swing = barplot(swing.romney$Percentatge.of.Votes, names.arg = swing.romney$State.or.district,
                    col = "red2", main = "Results by State - Mitt Romney")

ob.swing = barplot(swing.obama$Percentatge.of.Votes, names.arg = swing.obama$State.or.district,
                   col = "darkblue", main = "Results by State - Barack Obama")

Here you can see both results in histograms side by side.

Results by State:

How can "merge" the two files in order to get the blue and red bars side by side?

Body:
Please test this ggplot2 solution:

library(ggplot2)
ggplot(swing.states,
       aes(State.or.district, Percentatge.of.Votes, fill = Candidate)) +
geom_bar(stat = "identity", position = "dodge") +
labs(title = "Results by state",
     x = "State/district",
     y = "Votes, %")


问:
Fire JS event handler always as the last one, regardless of adding order
Is there some way to force event handler in JS to fire always as the last one? Say I know that some new event handlers will occur in the future, but I want to be sure that every new handler will be fired before my special one.</p>

答:
One way would be to wrap your main function in setTimeout function and pass 0 delay, so Javascript engine will add it to its functions stack and execute that function last.

```<code>document.getElementById("div1").addEventListener('click', function(e) {
    setTimeout(function(){
    console.log('MAIN Event');
  },0);
})
document.getElementById("div1").addEventListener('click', function(e) {
    console.log('dosmth2');
})
document.getElementById("div1").addEventListener('click', function(e) {
    console.log('dosmth3asd');
})
</code>```

P.s. using many setTimeouts might decrease performance.

ContentLicense: CC BY-SA 4.0

Body:
One way would be to wrap your main function in setTimeout function and pass 0 delay, so Javascript engine will add it to its functions stack and execute that function last.

document.getElementById("div1").addEventListener('click', function(e) {
    setTimeout(function(){
    console.log('MAIN Event');
  },0);
})
document.getElementById("div1").addEventListener('click', function(e) {
    console.log('dosmth2');
})
document.getElementById("div1").addEventListener('click', function(e) {
    console.log('dosmth3asd');
})

P.s. using many setTimeouts might decrease performance.


问:
Creating Postman like client in Spring Boot Oauth2
I have Resource server and Authorization server, both are working fine when I use Postman to generate to token from authorization server and then use Get request with that token, and then I see the text in my Resource server.

Is there way to create similar Client application in Spring Boot to fill the same function as postman does? Checks if user has token, if not then sends me to Authorization server where user can login, and then takes the user back with the token to see the message what is on Resource server.

答: A tutorial which explains oauth2 configuration in spring boot is directly from spring pages available: Spring Boot OAuth Tutorial</p>


问:
Get id of an element with the same class
I have multiple div boxes with the class printPic which will have their own unique id. On hover in/out, toggle the display of printPicOverlay which is a child of printPic. The way I have it set up now, printPicOverlay for all ids are toggled on hover.

What would be the best way to show/hide printPicOverlay on hover for each individual id?

$(".printPic").hover(function () {
$(".printPicOverlay").toggle();
}, function () {
$(".printPicOverlay").toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}</code>```

```

答:
Just to add another alternative – this is really easy in plain CSS, without any Javascript/JQuery:

.printPic {
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay {
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}

.printPic:hover .printPicOverlay {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="printPic" id="1">
  <div class="printPicOverlay"></div>
</div>

<div class="printPic" id="2">
  <div class="printPicOverlay"></div>
</div>

<div class="printPic" id="3">
  <div class="printPicOverlay"></div>
</div></code>```

It's also probably a bit more performant – using native browser functionality rather than finding elements via jquery.

Docs on :hover pseudoclass

If you want to animate the overlay appearance, it's possible with a bit of tweaking (visibility instead of display etc.):

.printPic {
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay {
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  position: absolute;
  visibility: hidden;
  opacity: 0;
  transform: scale(0.8) translate(0, 10%);
  transition: visibility 0s, opacity 0.5s ease-in, transform 0.3s ease-in;
}

.printPic:hover .printPicOverlay {
  transform: scale(1);
  visibility: visible;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="printPic" id="1">
  <div class="printPicOverlay"></div>
</div>

<div class="printPic" id="2">
  <div class="printPicOverlay"></div>
</div>

<div class="printPic" id="3">
  <div class="printPicOverlay"></div>
</div></code>```

Body:
I have multiple div boxes with the class printPic which will have their own unique id. On hover in/out, toggle the display of printPicOverlay which is a child of printPic. The way I have it set up now, printPicOverlay for all ids are toggled on hover.

What would be the best way to show/hide printPicOverlay on hover for each individual id?

$(".printPic").hover(function () {
$(".printPicOverlay").toggle();
}, function () {
$(".printPicOverlay").toggle();
});

.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}

Body:
Just to add another alternative – this is really easy in plain CSS, without any Javascript/JQuery:

.printPic {
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay {
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}

.printPic:hover .printPicOverlay {
  display: block;
}

<div class="printPic" id="1">
  <div class="printPicOverlay"></div>
</div>

<div class="printPic" id="2">
  <div class="printPicOverlay"></div>
</div>

<div class="printPic" id="3">
  <div class="printPicOverlay"></div>
</div>

It's also probably a bit more performant – using native browser functionality rather than finding elements via jquery.

Docs on :hover pseudoclass

If you want to animate the overlay appearance, it's possible with a bit of tweaking (visibility instead of display etc.):

.printPic {
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay {
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  position: absolute;
  visibility: hidden;
  opacity: 0;
  transform: scale(0.8) translate(0, 10%);
  transition: visibility 0s, opacity 0.5s ease-in, transform 0.3s ease-in;
}

.printPic:hover .printPicOverlay {
  transform: scale(1);
  visibility: visible;
  opacity: 1;
}

<div class="printPic" id="1">
  <div class="printPicOverlay"></div>
</div>

<div class="printPic" id="2">
  <div class="printPicOverlay"></div>
</div>

<div class="printPic" id="3">
  <div class="printPicOverlay"></div>
</div>


问:
Align buttons to line up with fieldset
Background:The website I am working on there are several different filters that people can use in order to show only the data they need; basic stuff. To make things look nice since I am not css inclined, I am using bootstrap to make things look clean.

Problem: I can't seem to get the buttons to line up with the right side of the fields. I can make them pull to the very edge of the field set, I can make push/pull them to the general area they should be in, but I can't get them to line up nicely and stay that way regardless of how you rearrange the size of the page window.

JSFiddle: https://jsfiddle.net/v3cugpx1/1/

```<code><div class="form-group col-md-12">
    <div class="input-group-btn">
        <div class="pull-right">
            <a class="btn btn-info" href="#" title="Clear"><i class="glyphicon glyphicon-arrow-left"></i> Clear</a>
            <button class="btn btn-primary" title="Filter" type="submit"><i class="glyphicon glyphicon-search"></i> Filter</button>
        </div>
    </div>
</div>
</code>```

Any help would be greatly appreciated.

Cheers!

答:
You are using wrapper cols for the inputs. I included one "col-md-12" before the button's "form-group" and another one after it. This way your code stay consistent and you achieve what you want.

```<code><div class="col-md-12"> <----
    <div class="form-group col-md-12">
        <div class="col-md-12"> <----
            <div class="input-group-btn">
</code>```

Updated Fiddle

Title: Align buttons to line up with fieldset

Body:
Background:The website I am working on there are several different filters that people can use in order to show only the data they need; basic stuff. To make things look nice since I am not css inclined, I am using bootstrap to make things look clean.

Problem: I can't seem to get the buttons to line up with the right side of the fields. I can make them pull to the very edge of the field set, I can make push/pull them to the general area they should be in, but I can't get them to line up nicely and stay that way regardless of how you rearrange the size of the page window.

JSFiddle: https://jsfiddle.net/v3cugpx1/1/

             Clear
            <button class="btn btn-primary" title="Filter" type="submit"> Filter</button>

Any help would be greatly appreciated.

Cheers!

Body:
You are using wrapper cols for the inputs. I included one "col-md-12" before the button's "form-group" and another one after it. This way your code stay consistent and you achieve what you want.

<div class="col-md-12"> <----
    <div class="form-group col-md-12">
        <div class="col-md-12"> <----
            <div class="input-group-btn">

Updated Fiddle


问:
Why is my .on("click") function for the AuthorButton only returning my variable every other quote?
Some background: I am working through FreeCodeCamps Front-End Development projects and this project represents a Random Quote Machine.

I would like to keep the author hidden for each quote, but at the moment, the "Click to Reveal" button only reveals an author every other quote...

https://codepen.io/DecisiveIndecisive/pen/KXjXXd

The code in question is the Javascript. Thank You!

```<code>$(document).ready(function() {
  var url =
    "https://api.forismatic.com/api/1.0/?method=getQuote&key=1&lang=en&format=jsonp&jsonp=?";

  $("#refreshButton").on("click", function() {
    $.getJSON(url, function(json) {
      var jsonQuote = json.quoteText;
      var jsonAuthor = json.quoteAuthor;
      $(".counter").html(jsonAuthor);
      $("#authorButton").text("Click to Reveal");

      if (jsonAuthor === "") {
        $("#refreshButton").trigger("click");
      } else {
        $(".message").html(jsonQuote);
        $("#authorButton").click(function() {
          $(this).text(function(i, text) {
            return text === "Click to Reveal"
             ? "- " + jsonAuthor
              : "Click to Reveal";
          });
        });
      } //else close
    }); //getJSON close
  }); //refreshButton Close
});
</code>```

答: Every time you're loading a new quote, you're adding a new click listener. Then, when you check text === "Click to Reveal", the listener is called x times and the text is updated every time.

Body:
Some background: I am working through FreeCodeCamps Front-End Development projects and this project represents a Random Quote Machine.

I would like to keep the author hidden for each quote, but at the moment, the "Click to Reveal" button only reveals an author every other quote...

https://codepen.io/DecisiveIndecisive/pen/KXjXXd

The code in question is the Javascript. Thank You!

$(document).ready(function() {
  var url =
    "https://api.forismatic.com/api/1.0/?method=getQuote&key=1&lang=en&format=jsonp&jsonp=?";

  $("#refreshButton").on("click", function() {
    $.getJSON(url, function(json) {
      var jsonQuote = json.quoteText;
      var jsonAuthor = json.quoteAuthor;
      $(".counter").html(jsonAuthor);
      $("#authorButton").text("Click to Reveal");

      if (jsonAuthor === "") {
        $("#refreshButton").trigger("click");
      } else {
        $(".message").html(jsonQuote);
        $("#authorButton").click(function() {
          $(this).text(function(i, text) {
            return text === "Click to Reveal"
             ? "- " + jsonAuthor
              : "Click to Reveal";
          });
        });
      } //else close
    }); //getJSON close
  }); //refreshButton Close
});


问:
in jenkins, how to copy artifacts from another server?
I have another project from which I need to copy artifacts.

However the problem I have is that it's from another server. Is there a way to do so with the copy artifact or I'll have to go through code?

答: Publish over ssh plugin can also be used for copying the files/artifacts from one server (local/linux) to another server. It has retries option also in case there is network issue and no. of retires and timeout also can be configured. </p>


问:
Save JFrame as image with transparent background
I'm sorry I know there are a lot of questions like that but I just couldn't find the solution. I tried different things but just I can't get the background transparent. Here is my test code:

```<code>public class Pngs extends JPanel {

public void paint(Graphics g) {
    Image img = createImage();
    g.drawImage(img, 0, 0, this);
}

public static BufferedImage getScreenShot(
        Component component) {

    BufferedImage image = new BufferedImage(
            component.getWidth(),
            component.getHeight(),
            BufferedImage.TYPE_INT_RGB
    );
// call the Component's paint method, using
    // the Graphics object of the image.
    component.paint(image.getGraphics());
    return image;
}

private static Image createImage() {
    BufferedImage img = null;
    try {
        img = ImageIO.read(new File("oneImg.png"));
    } catch (IOException e) {
    }
    return img;
}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new Pngs());
    frame.setUndecorated(true);
    frame.getContentPane().setBackground(new Color(1.0f, 1.0f, 1.0f, 0.5f));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(512, 512);
    frame.setVisible(true);
    try { //saves the image
        // retrieve image
        BufferedImage bi = getScreenShot(frame.getContentPane());
        File outputfile = new File("saved.png");
        ImageIO.write(bi, "png", outputfile);
    } catch (IOException e) {
    }
}

}
</code>```

I tried to set the 4th argument of the Color constructor to 0 so it will be fully transparent but then I just get a black background. Also when it is set to 0.5f it's not transparent at all.

What could be the problem?

答:
This work for me:
      Try This:

```<code>public Pngs(){  // constructor
 setBackground(new Color(0,0,0,0));
 setUndecorated(true);
 setOpacity(0.5F);

}
</code>```

This make your Jframe Transparent and close option invisible. So, add an exit button to close your frame.
For more information about opacity and make JFrame transparent see THIS

Body:
I'm sorry I know there are a lot of questions like that but I just couldn't find the solution. I tried different things but just I can't get the background transparent. Here is my test code:

public class Pngs extends JPanel {

public void paint(Graphics g) {
    Image img = createImage();
    g.drawImage(img, 0, 0, this);
}

public static BufferedImage getScreenShot(
        Component component) {

    BufferedImage image = new BufferedImage(
            component.getWidth(),
            component.getHeight(),
            BufferedImage.TYPE_INT_RGB
    );
// call the Component's paint method, using
    // the Graphics object of the image.
    component.paint(image.getGraphics());
    return image;
}

private static Image createImage() {
    BufferedImage img = null;
    try {
        img = ImageIO.read(new File("oneImg.png"));
    } catch (IOException e) {
    }
    return img;
}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new Pngs());
    frame.setUndecorated(true);
    frame.getContentPane().setBackground(new Color(1.0f, 1.0f, 1.0f, 0.5f));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(512, 512);
    frame.setVisible(true);
    try { //saves the image
        // retrieve image
        BufferedImage bi = getScreenShot(frame.getContentPane());
        File outputfile = new File("saved.png");
        ImageIO.write(bi, "png", outputfile);
    } catch (IOException e) {
    }
}

}

I tried to set the 4th argument of the Color constructor to 0 so it will be fully transparent but then I just get a black background. Also when it is set to 0.5f it's not transparent at all.

What could be the problem?

Body:
This work for me:
      Try This:

public Pngs(){  // constructor
 setBackground(new Color(0,0,0,0));
 setUndecorated(true);
 setOpacity(0.5F);

}

This make your Jframe Transparent and close option invisible. So, add an exit button to close your frame.
For more information about opacity and make JFrame transparent see THIS


问:
CVS ampersand modules equivalent in git
I'm trying to transition my cvs repository to git and have been stuck on this last issue for a while.

I currently use CVS ampersand modules to share code between projets. Those allow you to basically "alias" a different repository as a subdirectory in your project, so you can update / commit the whole project and it's included remote repositories as if it was one repository.

I've seen threads that recommend subtree merges or submodules for doing this, in reference to (svn:externals). This won't work because:

subtree merges apparently don't allow you to easily push back / update the external repos.

submodules still require you to manually push / pull every submodule. I have a large number of submodules and going into every single one to push my changes would be tedious and could lead to omissions as changes would forget to be committed.

Just to be clear, I would like to have a git repository that contains other git repositories as subdirectories, and be able to commit / push / pull to all of them at the same time with one command.

答:
That's very much un-git.  If they are separate projects, they belong in separate repositories.

However, the repo tool is used by projects such as Android to provide a layer above git that encompasses a large number of dependent projects which may come from different locations and allows you to have a workflow from local branching of all of them through revision control (which may go to different locations by project).

It's a layer up and if you're expecting the exact git experience, you'll not get that.  You can use your standard git tools in any subproject, but at the top level, you're using a different tool for the coordination.

Title: CVS ampersand modules equivalent in git


问:
Error in omnisharp extension for vs code
I've been facing the next issue from quite a while now.
I'm starting with asp.net core 2.0 and vs code. I have installed VS Code 1.17.2, dotnet sdk 2.0 and C# extension 1.13.0 by omnisharp.
I created a mvc project runing dotnet new mvc. When I open vs code I'm getting a lot of error all over .cs files.

I'm able of build and run the application without any issue.

Also IntelliSense and debugging works.
When I see the errors tab I notice the next error among a lot  others:

The type 'TargetFrameworkAttribute' exists in both 'System.Runtime,
  Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' and
  'System.Runtime, Version=4.1.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a'

I'm guessing I have some problem with my environment but I can't figure out what is. Any idea is appreciated.

答:
Looks to be a bug related to how Omnisharp uses the MSBuild from a local installation of Visual Studio 2017. If your VS installation is out of date, you may see this error.

The issue has supposedly been fixed in the 1.13.1 release of the Omnisharp extension for VS Code.

The ticket mentions that Visual Studio 2017 RTM was the culprit, but anecdotally, I was on 15.2 and had the same issue.

See bug ticket here for additional details: github.com/OmniSharp/omnisharp-vscode/issues/1855

Solutions from ticket:

Update VS 2017 - this is generally worthwhile anyway as there have been 4 updates since RTM.

Download and use a version of OmniSharp with the a fix that will cause OmniSharp not to use VS 2017 RTM. You can follow the instructions here to do that.

Install the last release of C# for VS Code (1.12.1) and change the "extensions.autoUpdate" to false.


问:
Sending data in a loop causes malloc memory corruption
I'm working on an assignment on socket networking, and have a client and a server that connect and communicate fine, as long as I only send requests for one piece of data at the time. Once I send a request for for example 5 pieces of data, the server crashes due to malloc memory corruption.

I have:

```<code>int number_of_jobs;
msg[0] = '0';

read(sd, &number_of_jobs, 4);

for(int i = 0; i < number_of_jobs; i++){
    printf("Total bytes read: %lu\n", total_bytes_read);
    printf("Size: %lu\n", size);
    printf("i: %d\n", i);
    char jobtype;
    unsigned int len;
    fread(&jobtype, sizeof(jobtype), 1, fp);
    DEBUG_PRINT(("\n>>%d<< Jobtype: %c\n", getpid(), jobtype));

    fread(&len, 4, 1, fp);
    DEBUG_PRINT((">>%d<< Len: %d\n", getpid(), len));

    header = make_header(jobtype, len, size);

    read_line = malloc(sizeof(char)*len + 1);
    int n = fread(read_line, sizeof(char), len, fp);
    if(n <= 0){
        printf(">>%d<< ", getpid());
        perror("Fread error");
    }
    *(read_line + strlen(read_line)-1) = '\0';
    total_bytes_read += strlen(read_line);

    package = malloc(sizeof(char)*40 + sizeof(char)* strlen(read_line+1));

    strncpy(package, header, 41);
    strcat(package, read_line);

    printf("%s\n", package);

    if(write(sd, package, strlen(package)) < 0){
        printf(">>%d<< ", getpid());
        perror("Write error");
    }
    printf("Writing %zu bytes\n", strlen(read_line));

    free(package);
    free(header);
    free(read_line);
}
</code>```

I know it's something to do with overwriting memory (at least I think so?), but I don't know where or why.

The part that works, is essentially everything inside the for i < number_of_jobs part, which I can call as many times as I want.

答: What makes you think that read_line is null-terminated to call *(read_line + strlen(read_line)-1) = '\0';? If you need to make it null-terminated you better write read_line[n] = '\0'. Also there is no need to call strlen afterwards since you already know that that you've read n bytes.

Body:
I'm working on an assignment on socket networking, and have a client and a server that connect and communicate fine, as long as I only send requests for one piece of data at the time. Once I send a request for for example 5 pieces of data, the server crashes due to malloc memory corruption.

I have:

int number_of_jobs;
msg[0] = '0';

read(sd, &number_of_jobs, 4);

for(int i = 0; i < number_of_jobs; i++){
    printf("Total bytes read: %lu\n", total_bytes_read);
    printf("Size: %lu\n", size);
    printf("i: %d\n", i);
    char jobtype;
    unsigned int len;
    fread(&jobtype, sizeof(jobtype), 1, fp);
    DEBUG_PRINT(("\n>>%d<< Jobtype: %c\n", getpid(), jobtype));

    fread(&len, 4, 1, fp);
    DEBUG_PRINT((">>%d<< Len: %d\n", getpid(), len));

    header = make_header(jobtype, len, size);

    read_line = malloc(sizeof(char)*len + 1);
    int n = fread(read_line, sizeof(char), len, fp);
    if(n <= 0){
        printf(">>%d<< ", getpid());
        perror("Fread error");
    }
    *(read_line + strlen(read_line)-1) = '\0';
    total_bytes_read += strlen(read_line);

    package = malloc(sizeof(char)*40 + sizeof(char)* strlen(read_line+1));

    strncpy(package, header, 41);
    strcat(package, read_line);

    printf("%s\n", package);

    if(write(sd, package, strlen(package)) < 0){
        printf(">>%d<< ", getpid());
        perror("Write error");
    }
    printf("Writing %zu bytes\n", strlen(read_line));

    free(package);
    free(header);
    free(read_line);
}

I know it's something to do with overwriting memory (at least I think so?), but I don't know where or why.

The part that works, is essentially everything inside the for i < number_of_jobs part, which I can call as many times as I want.


问:
YouTube API to fetch all videos on a channel
We need a video list by channel name of YouTube (using the API).

We can get a channel list (only channel name) by using the below API:

```<code>https://gdata.youtube.com/feeds/api/channels?v=2&q=tendulkar
</code>```

Below is a direct link of channels

```<code>https://www.youtube.com/channel/UCqAEtEr0A0Eo2IVcuWBfB9g
</code>```

Or

```<code>WWW.YouTube.com/channel/HC-8jgBP-4rlI
</code>```

Now, we need videos of channel >> UCqAEtEr0A0Eo2IVcuWBfB9g or HC-8jgBP-4rlI.

We tried

https://gdata.youtube.com/feeds/api/videos?v=2&uploader=partner&User=UC7Xayrf2k0NZiz3S04WuDNQ
 https://gdata.youtube.com/feeds/api/videos?v=2&uploader=partner&q=UC7Xayrf2k0NZiz3S04WuDNQ

But, it does not help.

We need all the videos posted on the channel. Videos uploaded to a channel can be from multiple users thus I don't think providing a user parameter would help...

答:
Below is a Python alternative that does not require any special packages. By providing the channel id it returns a list of video links for that channel. Please note that you need an API Key for it to work.</p>

```<code>import urllib
import json

def get_all_video_in_channel(channel_id):
    api_key = YOUR API KEY

    base_video_url = 'https://www.youtube.com/watch?v='
    base_search_url = 'https://www.googleapis.com/youtube/v3/search?'

    first_url = base_search_url+'key={}&channelId={}&part=snippet,id&order=date&maxResults=25'.format(api_key, channel_id)

    video_links = []
    url = first_url
    while True:
        inp = urllib.urlopen(url)
        resp = json.load(inp)

        for i in resp['items']:
            if i['id']['kind'] == "youtube#video":
                video_links.append(base_video_url + i['id']['videoId'])

        try:
            next_page_token = resp['nextPageToken']
            url = first_url + '&pageToken={}'.format(next_page_token)
        except:
            break
    return video_links
</code>```

Body:
We need a video list by channel name of YouTube (using the API).

We can get a channel list (only channel name) by using the below API:

https://gdata.youtube.com/feeds/api/channels?v=2&q=tendulkar

Below is a direct link of channels

https://www.youtube.com/channel/UCqAEtEr0A0Eo2IVcuWBfB9g

Or

WWW.YouTube.com/channel/HC-8jgBP-4rlI

Now, we need videos of channel >> UCqAEtEr0A0Eo2IVcuWBfB9g or HC-8jgBP-4rlI.

We tried

https://gdata.youtube.com/feeds/api/videos?v=2&uploader=partner&User=UC7Xayrf2k0NZiz3S04WuDNQ
 https://gdata.youtube.com/feeds/api/videos?v=2&uploader=partner&q=UC7Xayrf2k0NZiz3S04WuDNQ

But, it does not help.

We need all the videos posted on the channel. Videos uploaded to a channel can be from multiple users thus I don't think providing a user parameter would help...

Body:
Below is a Python alternative that does not require any special packages. By providing the channel id it returns a list of video links for that channel. Please note that you need an API Key for it to work.

import urllib
import json

def get_all_video_in_channel(channel_id):
    api_key = YOUR API KEY

    base_video_url = 'https://www.youtube.com/watch?v='
    base_search_url = 'https://www.googleapis.com/youtube/v3/search?'

    first_url = base_search_url+'key={}&channelId={}&part=snippet,id&order=date&maxResults=25'.format(api_key, channel_id)

    video_links = []
    url = first_url
    while True:
        inp = urllib.urlopen(url)
        resp = json.load(inp)

        for i in resp['items']:
            if i['id']['kind'] == "youtube#video":
                video_links.append(base_video_url + i['id']['videoId'])

        try:
            next_page_token = resp['nextPageToken']
            url = first_url + '&pageToken={}'.format(next_page_token)
        except:
            break
    return video_links


答:
The issue is because you need to use the this keyword to find() the .printPicOverlay element within the hovered .printPic, like this:

$(".printPic").hover(function() {
  $(this).find(".printPicOverlay").toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.printPic {
  height: 10em;
  width: 10em;
  display: inline-block;
  background-color: red;
  position: relative;
}

.printPicOverlay {
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: none;
  position: absolute;
}</code>```

```
</div>
</div>
</p>

<p><strong><em>However</em></strong>, it would be much better, and more simple to achieve this in CSS alone. There's no need for JS at all:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.printPic {
  height: 10em;
  width: 10em;
  display: inline-block;
  background-color: red;
  position: relative;
}

.printPicOverlay {
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: none;
  position: absolute;
}

.printPic:hover .printPicOverlay {
  display: block;
}</code>```

```

Title: Get id of an element with the same class

Body:
The issue is because you need to use the this keyword to find() the .printPicOverlay element within the hovered .printPic, like this:

$(".printPic").hover(function() {
  $(this).find(".printPicOverlay").toggle();
});

.printPic {
  height: 10em;
  width: 10em;
  display: inline-block;
  background-color: red;
  position: relative;
}

.printPicOverlay {
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: none;
  position: absolute;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="printPic" id="1">
  <div class="printPicOverlay"></div>
</div>
<div class="printPic" id="2">
  <div class="printPicOverlay"></div>
</div>
<div class="printPic" id="3">
  <div class="printPicOverlay"></div>
</div>

However, it would be much better, and more simple to achieve this in CSS alone. There's no need for JS at all:

.printPic {
  height: 10em;
  width: 10em;
  display: inline-block;
  background-color: red;
  position: relative;
}

.printPicOverlay {
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: none;
  position: absolute;
}

.printPic:hover .printPicOverlay {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="printPic" id="1">
  <div class="printPicOverlay"></div>
</div>
<div class="printPic" id="2">
  <div class="printPicOverlay"></div>
</div>
<div class="printPic" id="3">
  <div class="printPicOverlay"></div>
</div>


问:
Navbar li elements not floating to right?
I need a help to make my li elements float to the right of navbar.</p>

```<code><nav class="navbar navbar-toggleable-md navbar-fixed-top topnav" role="navigation">
  <div class="navbar-header">
    <a class="navbar-brand" href="#" target="_blank" id="heading">Samrat Luitel</a>
  </div>
  <div>
    <ul class="navbar-nav navbar-right">
      <li class="nav-item"><a href="#home" style="color:black" class="nav-link">Home</a></li>
      <li class="nav-item"><a href="#home" style="color:black" class="nav-link">About Us</a></li>
      <li class="nav-item"><a href="#home" style="color:black" class="nav-link">Contact Us</a></li>
    </ul>
  </div>
</nav>
</code>```

答:
Where are your classes coming from? Easiest way to force them to float right would be to define it in an external style sheet or in the HTML document. To do it in HTML all you need to do is:</p>

```<code>    <style>
    .navbar-nav>li {
        float: right;
    }
    </style>
</code>```

Body:
I need a help to make my li elements float to the right of navbar.

    Samrat Luitel

Home

About Us

Contact Us

Body:
Where are your classes coming from? Easiest way to force them to float right would be to define it in an external style sheet or in the HTML document. To do it in HTML all you need to do is:

    <style>
    .navbar-nav>li {
        float: right;
    }
    </style>


问:
Mongoose update returns undefined
How can I update a field with new properties that is initially set to be an empty object?

For example, I have the following schema:

```<code>import mongoose from 'mongoose';

var RunSchema = mongoose.Schema(
  {
    runId: { type: String },
    reports: {
      cookieSummary: {
        name: String,
        path: String
      }
    }
  }
)

export default mongoose.model('Run', RunSchema);
</code>```

And I'm trying to update the following document:

```<code>{
    "_id": {
        "$oid": "5a0565c2537e0b5d9d08ee6b"
    },
    "__v": 0,
    "reports": {},
    "runId": "8r4LNN3fRqd3qNgdW"
}
</code>```

But when I run this code, it returns undefined:

```<code>  Run.findOneAndUpdate({runId: '8r4LNN3fRqd3qNgdW'},
  {
    $set: {'reports.cookieSummary': { 'name': 'test' }},
  }, (err, doc) => { console.log(doc) })
</code>```

The object notation works after adding type to fields, like this: name: { type: String }

答:
I made a small change. Test this solution.</p>

```<code>    Run.findOneAndUpdate({runId: '8r4LNN3fRqd3qNgdW'},
    {
        $set: {"reports": {'cookieSummary':{'name': 'test'}}},
    }, (err, doc) => { console.log(doc) })
</code>```

Title: Mongoose update returns undefined

Body:
How can I update a field with new properties that is initially set to be an empty object?

For example, I have the following schema:

import mongoose from 'mongoose';

var RunSchema = mongoose.Schema(
  {
    runId: { type: String },
    reports: {
      cookieSummary: {
        name: String,
        path: String
      }
    }
  }
)

export default mongoose.model('Run', RunSchema);

And I'm trying to update the following document:

{
    "_id": {
        "$oid": "5a0565c2537e0b5d9d08ee6b"
    },
    "__v": 0,
    "reports": {},
    "runId": "8r4LNN3fRqd3qNgdW"
}

But when I run this code, it returns undefined:

  Run.findOneAndUpdate({runId: '8r4LNN3fRqd3qNgdW'},
  {
    $set: {'reports.cookieSummary': { 'name': 'test' }},
  }, (err, doc) => { console.log(doc) })

The object notation works after adding type to fields, like this: name: { type: String }

Body:
I made a small change. Test this solution.

    Run.findOneAndUpdate({runId: '8r4LNN3fRqd3qNgdW'},
    {
        $set: {"reports": {'cookieSummary':{'name': 'test'}}},
    }, (err, doc) => { console.log(doc) })


问:
Looping through multi dimensional array and getting common data
I have an array called open and within that I have arrays for each day indexing from 0 - 6. Within each day array I have times and a day set. Within some of the days the times will be the same and therefore want to group the values that are the same. e.g

```<code>open[] ->    [0] -> {open: 12:00, close: 16:00, Monday}
             [1] -> {open: 12:00, close: 16:00, tuesday}
</code>```

How could i group these value so that I can have an array that has the time and all the days associated with it. OR The best way to display that these days have this time.

this open array can also contain times that arent the same e.g:

```<code>open[] ->    [0] -> {open: 12:00, close: 16:00, monday}
             [1] -> {open: 12:00, close: 16:00, tuesday}
             [1] -> {open: 14:00, close: 16:00, sunday}
</code>```

Any help is appreciated!

答:
I'm not sure if I understand your requirements 100%, but based on what you've said I think you want to group days of the week based on having the same open & close times. To do this, you can create a "key" by concatenating the open & close times, then use this key to lookup the group array in an object. Here's an example:

//Set up an array of randomized test data
var initTestData = function(){
  var testReferenceData = {
    openTimes: ["08:00","08:30","09:00"],
    closeTimes: ["05:00","05:30"],
    daysOfWeek: ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
  }
  var data = [];
  for(var d=0; d<testReferenceData.daysOfWeek.length; ++d){
    var randOpen = Math.floor(Math.random() * testReferenceData.openTimes.length),
        randClose = Math.floor(Math.random() * testReferenceData.closeTimes.length);
    var day = {
      day: testReferenceData.daysOfWeek[d],
      open: testReferenceData.openTimes[randOpen],
      close: testReferenceData.closeTimes[randClose]
    };
    data.push(day);
  }
  return data;
}

//Group days by times
var groupByTime = function(days){
  var groups = {};
  for(var d=0; d<days.length; ++d){
    //Create a key by concatenating the start & end times of a day
    var key = days[d].open+"_"+days[d].close;
    //If this is the first one, initialize an array
    if(!groups[key]){
      groups[key] = [];
    }
    //Add the day to the group by its key
    groups[key].push(days[d]);
  }
  //Return an array of our groups
  return Object.values(groups);
}

var open = initTestData();
console.log("Initial array", open);
var grouped = groupByTime(open);
console.log("Grouped array", grouped);```

Body:
I have an array called open and within that I have arrays for each day indexing from 0 - 6. Within each day array I have times and a day set. Within some of the days the times will be the same and therefore want to group the values that are the same. e.g

open[] ->    [0] -> {open: 12:00, close: 16:00, Monday}
             [1] -> {open: 12:00, close: 16:00, tuesday}

How could i group these value so that I can have an array that has the time and all the days associated with it. OR The best way to display that these days have this time.

this open array can also contain times that arent the same e.g:

open[] ->    [0] -> {open: 12:00, close: 16:00, monday}
             [1] -> {open: 12:00, close: 16:00, tuesday}
             [1] -> {open: 14:00, close: 16:00, sunday}

Any help is appreciated!


答:
How about using Grids in this scenario

You give grid of col-4 to you List Item and Grid col-8 to your Brand Name.

In that way you will be able to achieve what you are looking for.

And a little bit of CSS styling will make it better.

.navbar-right{
  float:right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-toggleable-md navbar-fixed-top topnav col-12" role="navigation">
  <div class="navbar-header col-8">
    Samrat Luitel
  </div>
  <div class="col-4">
    <ul class="nav navbar-nav navbar-right">
      <li class="nav-item">Home</li>
      <li class="nav-item">About Us</li>
      <li class="nav-item">Contact Us</li>
    </ul>
  </div>
</nav></code>```

Title: Navbar li elements not floating to right?

Body:
How about using Grids in this scenario

You give grid of col-4 to you List Item and Grid col-8 to your Brand Name.

In that way you will be able to achieve what you are looking for.

And a little bit of CSS styling will make it better.

.navbar-right{
  float:right;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-toggleable-md navbar-fixed-top topnav col-12" role="navigation">
  <div class="navbar-header col-8">
    <a class="navbar-brand" href="#" target="_blank" id="heading">Samrat Luitel</a>
  </div>
  <div class="col-4">
    <ul class="nav navbar-nav navbar-right">
      <li class="nav-item"><a href="#home" style="color:black" class="nav-link">Home</a></li>
      <li class="nav-item"><a href="#home" style="color:black" class="nav-link">About Us</a></li>
      <li class="nav-item"><a href="#home" style="color:black" class="nav-link">Contact Us</a></li>
    </ul>
  </div>
</nav>


问:
Subtract from an input appended list with a running balance output
Noob

I am trying to write a script that gives a running balance.  I am messing up on the elementary declared functions of python.

I need it too:

accept a balance via input

append a list of transactions

take those out one by one in the order they were input

print a running total

use pyhtmltable to make the output in html table ready form for copy and pasting

Code:

```<code># transaction posting on available balance

import PyHtmlTable
import twodarr
import string,re
import copy
import sys

posting_trans = [] #creating a list of posting debits here

avail_bal = int(input('What is the balance available to pay transactions?')) #getting the starting balance

while True:  #building up the list of transactions
    ans = input('Please enter the debits in order of posting one at a time.  If there is no more, please enter 0:')
    if int(ans) == 0:
        break
    if ans > 0:    # to get out of loop
        posting_trans.append(ans)

num_trans = int(len(posting_trans))   #counting the number of transactions

print "<b> Beginning available balance of",avail_bal," </b> "  # start of the html table

tabledict = {'width':'400','border':2,'bgcolor':'white'}

t  = PyHtmlTable.PyHtmlTable( 2, 1 , tabledict )

t.setCellcontents(0,0,"Transactions")  #header cells
t.setCellcontents(1,0,"Available Balance")

while True:      #trying to create the rest of a dynamic table
    if countdown == 0:
        break

    for countdown in range(1,num_trans):
        t.add_row(1)

        def newer_bal():
            newer_bal(avail_bal - posting_trans[countdown])

            t.setCellcontents(0, 1, posting_trans[countdown])
            t.setCellcontents(1, 1, newer_bal)

t.display()
</code>```

答:
Something like that?

```<code># transaction posting on available balance
import PyHtmlTable

posting_trans = [] #creating a list of posting debits here

#getting the starting balance
print 'What is the balance available to pay transactions? '
avail_bal = float(raw_input('Value: '))

while True:  #building up the list of transactions
    print 'Please enter the debits in order of posting one at a time.'
    print 'If there is no more, please enter 0:'
    ans = float(raw_input('Value: '))
    if ans == 0:
        break # to get out of loop
    posting_trans.append(ans)

# start of the html table
print "<b> Beginning available balance of %.2f</b>" % avail_bal

tabledict = {'width': '400', 'border': 2, 'bgcolor': 'white'}
t  = PyHtmlTable.PyHtmlTable(2, 1, tabledict)

t.setCellcontents(0, 0, "Transaction Value")  #header cells
t.setCellcontents(0, 1, "Available Balance")

for line, trans in enumerate(posting_trans):
    avail_bal -= trans
    t.setCellcontents(line + 1, 0, '%.2f' % trans)
    t.setCellcontents(line + 1, 1, '%.2f' % avail_bal)

t.display()
</code>```

Hints:

Don't use input(). Use raw_input() instead. It has been renamed to input() in python 3.0.

You don't need to store the values in the list. You could store them in the table already, that is the point into using PyHtmlTable. I left the list for didactic purposes.

Read a tutorial. Read documentation. Write lots of code.

LastEditorDisplayName: nosklo

Body:
Noob

I am trying to write a script that gives a running balance.  I am messing up on the elementary declared functions of python.

I need it too:

accept a balance via input

append a list of transactions

take those out one by one in the order they were input

print a running total

use pyhtmltable to make the output in html table ready form for copy and pasting

Code:

# transaction posting on available balance

import PyHtmlTable
import twodarr
import string,re
import copy
import sys

posting_trans = [] #creating a list of posting debits here

avail_bal = int(input('What is the balance available to pay transactions?')) #getting the starting balance

while True:  #building up the list of transactions
    ans = input('Please enter the debits in order of posting one at a time.  If there is no more, please enter 0:')
    if int(ans) == 0:
        break
    if ans > 0:    # to get out of loop
        posting_trans.append(ans)

num_trans = int(len(posting_trans))   #counting the number of transactions

print " Beginning available balance of",avail_bal,"  "  # start of the html table

tabledict = {'width':'400','border':2,'bgcolor':'white'}

t  = PyHtmlTable.PyHtmlTable( 2, 1 , tabledict )

t.setCellcontents(0,0,"Transactions")  #header cells
t.setCellcontents(1,0,"Available Balance")

while True:      #trying to create the rest of a dynamic table
    if countdown == 0:
        break

    for countdown in range(1,num_trans):
        t.add_row(1)

        def newer_bal():
            newer_bal(avail_bal - posting_trans[countdown])

            t.setCellcontents(0, 1, posting_trans[countdown])
            t.setCellcontents(1, 1, newer_bal)

t.display()

Body:
Something like that?

# transaction posting on available balance
import PyHtmlTable

posting_trans = [] #creating a list of posting debits here

#getting the starting balance
print 'What is the balance available to pay transactions? '
avail_bal = float(raw_input('Value: '))

while True:  #building up the list of transactions
    print 'Please enter the debits in order of posting one at a time.'
    print 'If there is no more, please enter 0:'
    ans = float(raw_input('Value: '))
    if ans == 0:
        break # to get out of loop
    posting_trans.append(ans)

# start of the html table
print "<b> Beginning available balance of %.2f</b>" % avail_bal

tabledict = {'width': '400', 'border': 2, 'bgcolor': 'white'}
t  = PyHtmlTable.PyHtmlTable(2, 1, tabledict)

t.setCellcontents(0, 0, "Transaction Value")  #header cells
t.setCellcontents(0, 1, "Available Balance")

for line, trans in enumerate(posting_trans):
    avail_bal -= trans
    t.setCellcontents(line + 1, 0, '%.2f' % trans)
    t.setCellcontents(line + 1, 1, '%.2f' % avail_bal)

t.display()

Hints:

Don't use input(). Use raw_input() instead. It has been renamed to input() in python 3.0.

You don't need to store the values in the list. You could store them in the table already, that is the point into using PyHtmlTable. I left the list for didactic purposes.

Read a tutorial. Read documentation. Write lots of code.

OwnerDisplayName: nosklo


问:
Find/Grep in all VI buffers
With many buffers open, I need a simple way to search all buffers for a regex and navigate the search result (quick list?)

I know I can :bufdo command, and it is easy to search and replace with %s, but I can't find a way to do just a simple search and then navigate the results.

I found plugins for that (e.g., buffergrep), but I'll be surprised if this simple task is not natively supported with a vim trick.. is it?

答:
from :help grepadd

```<code>:grepa[dd][!] [arguments]
            Just like ":grep", but instead of making a new list of
            errors the matches are appended to the current list.
            Example:
                :call setqflist([])
                :bufdo grepadd! something %
            The first command makes a new error list which is
            empty.  The second command executes "grepadd" for each
            listed buffer.  Note the use of ! to avoid that
            ":grepadd" jumps to the first error, which is not
            allowed with |:bufdo|.
            An example that uses the argument list and avoids
            errors for files without matches:
                                :silent argdo try
                  \ | grepadd! something %
                  \ | catch /E480:/
                  \ | endtry"
</code>```

Title: Find/Grep in all VI buffers

Body:
from :help grepadd

:grepa[dd][!] [arguments]
            Just like ":grep", but instead of making a new list of
            errors the matches are appended to the current list.
            Example:
                :call setqflist([])
                :bufdo grepadd! something %
            The first command makes a new error list which is
            empty.  The second command executes "grepadd" for each
            listed buffer.  Note the use of ! to avoid that
            ":grepadd" jumps to the first error, which is not
            allowed with |:bufdo|.
            An example that uses the argument list and avoids
            errors for files without matches:
                                :silent argdo try
                  \ | grepadd! something %
                  \ | catch /E480:/
                  \ | endtry"


问:
Chef: How to gather local network.interface attribute with state key equal to up?
I'm interested in gathering the key value for any network_interfaces_*_state:up attribute's running on the host with the chef-client being run on. So any network interface with a state 'up' attribute.

I have a template containing a configuration file, in which I need to gather the active network devices, using the above chef attribute. I've tried writing a few things within the default recipe file, such as:

```<code>template '/etc/foo.conf' do
    ....
    variables ({
        netdev: search(node, 'network_interfaces_*_state:up').each {r |r| puts "#{r['network']['interfaces'].select { |i,j| j['state'] == 'up' }.keys } " }
    })
end
</code>```

So there are two things that are obviously wrong.

Running this as knife exec -E "......" returns the interface name for state:up on all nodes. I only want it from the current node that the chef-client is being run on.

chef-client is returning an undefined method 'search' for Chef::Resource::Template, tracing back to the 'netdev' variable as posted above.

I'm unfamiliar with Ruby and using Chef at this level, and was really hoping that I could get help with understanding two things. How do I pull a attribute value from a local host, and how the heck can I write this into a recipe/cookbook?

答:
So what you need is the first 'up' interface, assuming the loopback interface should be avoided, this should do:

```<code>template '/etc/foo.conf' do
    ....
    variables ({
        netdev: node['network']['interfaces'].select { |i,j| j['state'] == 'up' && i != 'lo' }.keys[0]
    })
end
</code>```

The main idea is to filter the interfaces hash on the interface state and name, keep the keys and take the first one of the resulting array.

Previous answer kept for information.

Attributes are indexed and flattened so you may search for just state:up but may find other attributes named state.

Using the flattened version you could do:

knife node search 'network_interface_*_state:up' -a network.interfaces

This is derived from the examples of nested fields in the documentation linked above.

In case you wish to get each interface up for each node you can play with the search and a little of ruby with knife exec like this :

```<code> knife exec -E "nodes.search('network_interfaces_*_state:up').each { |n| puts \"#{n} #{n['network']['interfaces'].select { |i,j| j['state'] == 'up' }.keys } \" }"
node[xxxxxxx] ["eth1", "eth2", "eth3", "usb0"]
node[yyyyyyy] ["docker0"]
node[zzzzzzz] ["eth1", "eth2", "eth3", "usb0"]
</code>```

The idea is to search for nodes with up interfaces and for each filtering the interfaces whose property (j in select block as they are a hash within a hash) state is up and then keep only the keys of the resulting filtered hash which are the interfaces with state up. (side note my examples above were done with state:down to limit the results)

Body:
I'm interested in gathering the key value for any network_interfaces_*_state:up attribute's running on the host with the chef-client being run on. So any network interface with a state 'up' attribute.

I have a template containing a configuration file, in which I need to gather the active network devices, using the above chef attribute. I've tried writing a few things within the default recipe file, such as:

template '/etc/foo.conf' do
    ....
    variables ({
        netdev: search(node, 'network_interfaces_*_state:up').each {r |r| puts "#{r['network']['interfaces'].select { |i,j| j['state'] == 'up' }.keys } " }
    })
end

So there are two things that are obviously wrong.

Running this as knife exec -E "......" returns the interface name for state:up on all nodes. I only want it from the current node that the chef-client is being run on.

chef-client is returning an undefined method 'search' for Chef::Resource::Template, tracing back to the 'netdev' variable as posted above.

I'm unfamiliar with Ruby and using Chef at this level, and was really hoping that I could get help with understanding two things. How do I pull a attribute value from a local host, and how the heck can I write this into a recipe/cookbook?

Body:
So what you need is the first 'up' interface, assuming the loopback interface should be avoided, this should do:

template '/etc/foo.conf' do
    ....
    variables ({
        netdev: node['network']['interfaces'].select { |i,j| j['state'] == 'up' && i != 'lo' }.keys[0]
    })
end

The main idea is to filter the interfaces hash on the interface state and name, keep the keys and take the first one of the resulting array.

Previous answer kept for information.

Attributes are indexed and flattened so you may search for just state:up but may find other attributes named state.

Using the flattened version you could do:

knife node search 'network_interface_*_state:up' -a network.interfaces

This is derived from the examples of nested fields in the documentation linked above.

In case you wish to get each interface up for each node you can play with the search and a little of ruby with knife exec like this :

 knife exec -E "nodes.search('network_interfaces_*_state:up').each { |n| puts \"#{n} #{n['network']['interfaces'].select { |i,j| j['state'] == 'up' }.keys } \" }"
node[xxxxxxx] ["eth1", "eth2", "eth3", "usb0"]
node[yyyyyyy] ["docker0"]
node[zzzzzzz] ["eth1", "eth2", "eth3", "usb0"]

The idea is to search for nodes with up interfaces and for each filtering the interfaces whose property (j in select block as they are a hash within a hash) state is up and then keep only the keys of the resulting filtered hash which are the interfaces with state up. (side note my examples above were done with state:down to limit the results)


问:
How to enable allow_url_fopen for phpMyAdmin?
After updating phpMyAdmin to v4.7.5 on my Apache/2.4.10 (Debian) I'm getting:

The curl extension was not found and allow_url_fopen is disabled. Due
  to this some features such as error reporting or version check are
  disabled.

phpinfo() says Local Value: Off, Master Value: On

In my /etc/php5/cli/php.ini I've: /etc/php5/cli/php.ini

I tried allow_url_fopen Local Value=Off Master Value=Off but it didn't help.

php --ini shows the following files:

```<code>Configuration File (php.ini) Path: /etc/php5/cli
Loaded Configuration File:         /etc/php5/cli/php.ini
Scan for additional .ini files in: /etc/php5/cli/conf.d
Additional .ini files parsed:      /etc/php5/cli/conf.d/05-opcache.ini,
/etc/php5/cli/conf.d/10-pdo.ini,
/etc/php5/cli/conf.d/20-gd.ini,
/etc/php5/cli/conf.d/20-json.ini,
/etc/php5/cli/conf.d/20-mcrypt.ini,
/etc/php5/cli/conf.d/20-mysql.ini,
/etc/php5/cli/conf.d/20-mysqli.ini,
/etc/php5/cli/conf.d/20-pdo_mysql.ini,
/etc/php5/cli/conf.d/20-readline.ini
</code>```

(Of course I rebooted after making the changes.)

What can I do?

答:
Check if php5-curl is installed with one of those two command

```<code>dpkg -s php5-curl
sudo apt-cache policy php5-curl
</code>```

If it if not try to install it with a:

```<code>sudo apt-get install php5-curl
</code>```

And after that you should retart apache server
No need to reboot

Body:
After updating phpMyAdmin to v4.7.5 on my Apache/2.4.10 (Debian) I'm getting:

The curl extension was not found and allow_url_fopen is disabled. Due
  to this some features such as error reporting or version check are
  disabled.

phpinfo() says Local Value: Off, Master Value: On

In my /etc/php5/cli/php.ini I've: /etc/php5/cli/php.ini

I tried allow_url_fopen Local Value=Off Master Value=Off but it didn't help.

php --ini shows the following files:

Configuration File (php.ini) Path: /etc/php5/cli
Loaded Configuration File:         /etc/php5/cli/php.ini
Scan for additional .ini files in: /etc/php5/cli/conf.d
Additional .ini files parsed:      /etc/php5/cli/conf.d/05-opcache.ini,
/etc/php5/cli/conf.d/10-pdo.ini,
/etc/php5/cli/conf.d/20-gd.ini,
/etc/php5/cli/conf.d/20-json.ini,
/etc/php5/cli/conf.d/20-mcrypt.ini,
/etc/php5/cli/conf.d/20-mysql.ini,
/etc/php5/cli/conf.d/20-mysqli.ini,
/etc/php5/cli/conf.d/20-pdo_mysql.ini,
/etc/php5/cli/conf.d/20-readline.ini

(Of course I rebooted after making the changes.)

What can I do?

Body:
Check if php5-curl is installed with one of those two command

dpkg -s php5-curl
sudo apt-cache policy php5-curl

If it if not try to install it with a:

sudo apt-get install php5-curl

And after that you should retart apache server
No need to reboot


问:
How do I boost queries in Lucene 7?
I want to boost a query in Lucene 7. In the previous versions (< 6) I was just using the setBoost(float boost) method. i.e.

```<code>TermQuery termQuery = new TermQuery(new Term("field", "value"));
termQuery.setBoost(2);
</code>```

In Lucene 7 there is only a method that contains the boost as a parameter:

```<code>public Weight createWeight(IndexSearcher searcher,
                       boolean needsScores,
                       float boost)
</code>```

which isn't the method responsible for the boost!
Do you know how to apply the boosting to the queries?

答:
All queries are now immutable, which also extends to boosts, per LUCENE-6590. As such, to apply boosts you would use a BoostQuery to wrap the query. Like this:</p>

```<code>Query termQuery = new TermQuery(new Term("field", "value"));
Query boostedTermQuery = new BoostQuery(termQuery, 2);
</code>```

Title: How do I boost queries in Lucene 7?

Body:
I want to boost a query in Lucene 7. In the previous versions (< 6) I was just using the setBoost(float boost) method. i.e.

TermQuery termQuery = new TermQuery(new Term("field", "value"));
termQuery.setBoost(2);

In Lucene 7 there is only a method that contains the boost as a parameter:

public Weight createWeight(IndexSearcher searcher,
                       boolean needsScores,
                       float boost)

which isn't the method responsible for the boost!
Do you know how to apply the boosting to the queries?

Body:
All queries are now immutable, which also extends to boosts, per LUCENE-6590. As such, to apply boosts you would use a BoostQuery to wrap the query. Like this:

Query termQuery = new TermQuery(new Term("field", "value"));
Query boostedTermQuery = new BoostQuery(termQuery, 2);


问:
SSRS CSV export - whole tablix ignored, only data from last page is exported
The report

The report consists of, in this order:

A header

A tablix containing the main data. It has one grouping containing the detail group.

A rectangle set to add a page break before. The rectangle contains text boxes with metadata.

A footer

The problem

When the report is exported to CSV the only data is the metadata from inside the rectangle. I need the data from the tablix.

Additional details

There are no visibility expressions set on the tablix, it's columns or rows, any individual text boxes, or groupings.

The report exports to excel (.xlsx) just fine.

The issue occurs on the report server and in SSDT locally.

答:
SSRS treats XLSX vs CSV exports quite differently.  XLSX export is a layout renderer, where SSRS tries to be smart and mimic the layout of the reports into Excel.  CSV export, on the other hand, is just a data renderer and SSRS doesn't care how the page is laid out, it simply tries to export data.

There are several reasons why the data renderers of XML and CSV might actually omit elements in your report.

Static Values - Values that are hardcoded and don't change from row to row will not get exported.

Items that are controlled by conditional expressions (even if they evaluate to false and should show) will not be exported.  One of MS's many "by design", "nice" features :(

This all said, there is a property on elements called "DataElementOutput" that controls whether the specific item should be visible in a CSV/XML data export. Can you try setting this to "Output" for your tablix and see if that forces it to be shown?


问:
When to use multiple foreign keys in a single table vs using associative tables?
I'm trying to understand when to include multiple foreign keys into a table vs when to use associative tables.

Edit: Added a diagram to hopefully make it easier to understand.

I have a settings system that many settings are specific to a division or classification. So, for example, a setting like "number per team" might be different in division 1, class A than in division 3, class A. And "minimum score" might be different in Division 1, class A than in Division 1, class C. Obviously there are also settings that have nothing to do with a division or classification that I feel should be in the same table.

So one way I could do this is to just put the div/class IDs as FKs in the settings table. Then any settings that don't depend on one or the other (or either) would be null for those IDs.

```<code>divisions
----------
id (int)
label (varchar)
description (varchar)

classification
--------------
id (int)
label (varchar)
description (varchar)

settings
---------
id (int)
division_id (int) (FK)
class_id (int) (FK)
key (varchar)
value (varchar)
</code>```

Since there'd only ever be one combination of division, classification, and settings key, that should work, right? But that "feels" wrong somehow - almost like putting the different events one is competing in all in the competitor table. I also cannot guarantee they won't come up with some additional category/type they'd wish to apply settings to later. So that makes me want to do something like:

```<code>divisions
----------
id (int)
label (varchar)
description (varchar)

classifications
--------------
id (int)
label (varchar)
description (varchar)

settings
---------
id (int)
key (varchar)
value (varchar)

settings_to_divisions
-------------------------
setting_id (int)
division_id (int)

settings_to_classifications
------------------------------
setting_id (int)
class_id (int)
</code>```

I think this would allow for easier growth when they come up with some new category (just create 'categories' and a 'settings_to_categories' tables). But then I'd likely have a whole set of nearly duplicate records in the settings table ([id], "min_score",5) and multiple, almost identical tables (id, label, description) for the associated items - all just to create one unique setting record.

Then what happens when they say they want different settings for men vs women? Do I just add an extra field into the settings table and hard code the 'Male' and 'Female' strings into the record, null everywhere except for settings that are gender specific? Or at the other end of things, create a separate 'gender' table with only 2 records and use that in the user table as well? Suddenly, I'm at:

```<code>divisions
---------
id (int)
label (varchar)
description (varchar)

classifications
---------------
id (int)
label (varchar)
description (varchar)

categories
----------
id (int)
label (varchar)
description (varchar)

type
----
id (int)
label (varchar)
description (varchar)

gender
------
id (int)
label (varchar)
description (varchar)

settings
---------
id (int)
key (varchar)
value (varchar)

settings_to_divisions
---------------------
setting_id (int)
division_id (int)

settings_to_classifications
---------------------------
setting_id (int)
class_id (int)

settings_to_categories
----------------------
setting_id (int)
category_id (int)

settings_to_type
----------------
setting_id (int)
type_id (int)

settings_to_gender
------------------
setting_id (int)
gender_id (int)
</code>```

It begins to feel almost ... overly normalized. Though maybe that's just me.

I'm just trying to design this intelligently so that even though some settings apply to all Division 3 players, when they tell me that they need further categories and that the application should behave differently for Division 3, Class A, Category Green, Rogue, Male players vs Female players, I don't have to redesign my database or application too much in order to easily get/set whatever that different setting should be.

I'm sure this isn't a new concept. This has to be a recognized design pattern out there somewhere, but it's hard trying to search for methods and approaches for dealing with a situation where you might have 3 (or 5 or 8) different ways of associating a single database entity.

I'm currently leaning toward the association table approach (significant normalization), but I'm not really a DBA. So am I making a stupid design decision? What would be the negatives/challenges of that approach? Would a still different approach be better?

答:
This post is a bit old but I will still answer for future readers:

The simple answer:  Use Approach 1

The only reason you would need a table between divisions/classification is to associate a single setting with multiple divisions/classification records.

I can tell you from experience you don't want that.  While using the same setting over and over sounds like a great time and space saving mechanism, you will regret it in the future.  The second you need to create a new setting for a subset records associated with a single setting or, worse, you will need to make a change to setting table that forces a vast majority records to be associate a single divisions/classification record with a single setting - you will hate your life.

Secondly, creating a setting table where the settings are text strings is very flexible but not over efficient.  If you have multiple settings for a single divisions/classification your application must loop through the results performing if statements on each record.

The alternative, of course, is to create a column for each setting.  This too can be a pain point as new settings require a deployment.  However, if a good number of settings are Boolean, you can achieve significant performance gains but using BIT values.

Example:

If you have 6 BIT fields, the database engine needs to only compare one byte
of data/record to find the value needed - versus searching on text which must compare multiple bytes over multiple records.

Lastly, if the number of settings grows significantly in future, performance could be affected using text strings.

Body:
I'm trying to understand when to include multiple foreign keys into a table vs when to use associative tables.

Edit: Added a diagram to hopefully make it easier to understand.

I have a settings system that many settings are specific to a division or classification. So, for example, a setting like "number per team" might be different in division 1, class A than in division 3, class A. And "minimum score" might be different in Division 1, class A than in Division 1, class C. Obviously there are also settings that have nothing to do with a division or classification that I feel should be in the same table.

So one way I could do this is to just put the div/class IDs as FKs in the settings table. Then any settings that don't depend on one or the other (or either) would be null for those IDs.

divisions
----------
id (int)
label (varchar)
description (varchar)

classification
--------------
id (int)
label (varchar)
description (varchar)

settings
---------
id (int)
division_id (int) (FK)
class_id (int) (FK)
key (varchar)
value (varchar)

Since there'd only ever be one combination of division, classification, and settings key, that should work, right? But that "feels" wrong somehow - almost like putting the different events one is competing in all in the competitor table. I also cannot guarantee they won't come up with some additional category/type they'd wish to apply settings to later. So that makes me want to do something like:

divisions
----------
id (int)
label (varchar)
description (varchar)

classifications
--------------
id (int)
label (varchar)
description (varchar)

settings
---------
id (int)
key (varchar)
value (varchar)

settings_to_divisions
-------------------------
setting_id (int)
division_id (int)

settings_to_classifications
------------------------------
setting_id (int)
class_id (int)

I think this would allow for easier growth when they come up with some new category (just create 'categories' and a 'settings_to_categories' tables). But then I'd likely have a whole set of nearly duplicate records in the settings table ([id], "min_score",5) and multiple, almost identical tables (id, label, description) for the associated items - all just to create one unique setting record.

Then what happens when they say they want different settings for men vs women? Do I just add an extra field into the settings table and hard code the 'Male' and 'Female' strings into the record, null everywhere except for settings that are gender specific? Or at the other end of things, create a separate 'gender' table with only 2 records and use that in the user table as well? Suddenly, I'm at:

divisions
---------
id (int)
label (varchar)
description (varchar)

classifications
---------------
id (int)
label (varchar)
description (varchar)

categories
----------
id (int)
label (varchar)
description (varchar)

type
----
id (int)
label (varchar)
description (varchar)

gender
------
id (int)
label (varchar)
description (varchar)

settings
---------
id (int)
key (varchar)
value (varchar)

settings_to_divisions
---------------------
setting_id (int)
division_id (int)

settings_to_classifications
---------------------------
setting_id (int)
class_id (int)

settings_to_categories
----------------------
setting_id (int)
category_id (int)

settings_to_type
----------------
setting_id (int)
type_id (int)

settings_to_gender
------------------
setting_id (int)
gender_id (int)

It begins to feel almost ... overly normalized. Though maybe that's just me.

I'm just trying to design this intelligently so that even though some settings apply to all Division 3 players, when they tell me that they need further categories and that the application should behave differently for Division 3, Class A, Category Green, Rogue, Male players vs Female players, I don't have to redesign my database or application too much in order to easily get/set whatever that different setting should be.

I'm sure this isn't a new concept. This has to be a recognized design pattern out there somewhere, but it's hard trying to search for methods and approaches for dealing with a situation where you might have 3 (or 5 or 8) different ways of associating a single database entity.

I'm currently leaning toward the association table approach (significant normalization), but I'm not really a DBA. So am I making a stupid design decision? What would be the negatives/challenges of that approach? Would a still different approach be better?


问:
How can you create a file inside a hadoop map-reduce job?
I searched the web, but all I found was a site that claimed that it could be done. It didn't say how.</p>

答:
```<code>FileSystem fs = FileSystem.get(conf);
Path path = new Path("/my/path/file")
OutputStream os = fs.create(path)
// write to os
os.close()
</code>```


问:
Android 8 (Oreo) emulator binaries
I'm trying to build Android 8 (Oreo) and run the emulator for the aosp_arm64-eng build.
When I built it and run the command emulator, it starts but the screen is blank. Logcat shows me some native exception due to the lack of opengl libraries.

After some research, I'm pretty sure I need the vendor images (or binary drivers) for the emulator (probably named mini-arm64), as for physical devices (https://developers.google.com/android/drivers).

Where can I find them?

答: Unfortunately, opengl drivers from real devices won't work. The emulator needs some special drivers in order to render on the host side. You can try to extract the swiftshader somewhere, and put into the image. Then run emulator with -gpu guest option.</p>

Title: Android 8 (Oreo) emulator binaries


问:
Cannot import certificate to AWS ACM
I need to import a certificate to AWS ACM but I'm facing an issue with limit excess although I have never used ACM before. Did I do something wrong or miss any steps?

```<code>Sorry!
You have reached the maximum number of certificates. Delete certificates that are not in use, or contact AWS Support to request an increase. Choose Previous button below and fix it.
</code>```

Screenshots:

Error

答:
Your account probably has a limit of 0 ACM certificates allowed in your region.

Please see this AWS forum post: https://forums.aws.amazon.com/thread.jspa?messageID=773934

The original user needed to contact AWS support to increase the limit to 10.

Title: Cannot import certificate to AWS ACM

Body:
I need to import a certificate to AWS ACM but I'm facing an issue with limit excess although I have never used ACM before. Did I do something wrong or miss any steps?

Sorry!
You have reached the maximum number of certificates. Delete certificates that are not in use, or contact AWS Support to request an increase. Choose Previous button below and fix it.

Screenshots:

Error


问:
Check if umbraco user can see published content
I have Umbraco User Id (not current user id) and published content Id, how can I check that user is able to see this content?
  I found this api:

```<code>  Access.HasAccess(int documentId, memberId)
</code>```

But it`s marked as obsolete. Any other ways to achieve this?

答:
I am using this:</p>

```<code>int memberId;
int nodeId;

var publicAccessService  = ApplicationContext.Current.Services.PublicAccessService;
var contentService = ApplicationContext.Current.Services.ContentService;
var memberService = ApplicationContext.Current.Services.MemberService;

var member = memberService.GetById(memberId);
var rolesList = Roles.GetRolesForUser(member.Username);

if(publicAccessService.HasAccess(nodeId, contentService, rolesList))
{
    // has access
}
{
    // does NOT have access
}
</code>```

Body:
I have Umbraco User Id (not current user id) and published content Id, how can I check that user is able to see this content?
  I found this api:

  Access.HasAccess(int documentId, memberId)

But it`s marked as obsolete. Any other ways to achieve this?

Body:
I am using this:

int memberId;
int nodeId;

var publicAccessService  = ApplicationContext.Current.Services.PublicAccessService;
var contentService = ApplicationContext.Current.Services.ContentService;
var memberService = ApplicationContext.Current.Services.MemberService;

var member = memberService.GetById(memberId);
var rolesList = Roles.GetRolesForUser(member.Username);

if(publicAccessService.HasAccess(nodeId, contentService, rolesList))
{
    // has access
}
{
    // does NOT have access
}


问:
How to get colormap from image to save it as colorimage with imwrite()
I have a matrix holding a picture which is in colors using image()

```<code>load image_matrix.mat;
image(image_matrix);
imsave(image_matrix, 'test.png', 'png', 'Compression', 'none');
</code>```

This code results in a greyscale image.
Somehow I should use the colormap to save the image. But where to get it from?

答:
the image is grayscale, imgage() just puts another colormap on it. Try

```<code>cm=parula; % or a different colormap
imsave(image_matrix,cm, 'test.png', 'png', 'Compression', 'none');
</code>```

Make sure that image_matrix is double in range [0-1] or uint8 [0-255]

Body:
I have a matrix holding a picture which is in colors using image()

load image_matrix.mat;
image(image_matrix);
imsave(image_matrix, 'test.png', 'png', 'Compression', 'none');

This code results in a greyscale image.
Somehow I should use the colormap to save the image. But where to get it from?

Body:
the image is grayscale, imgage() just puts another colormap on it. Try

cm=parula; % or a different colormap
imsave(image_matrix,cm, 'test.png', 'png', 'Compression', 'none');

Make sure that image_matrix is double in range [0-1] or uint8 [0-255]


问:
Create a Column that Counts (one at a time) Repeated Occurrences Within Groups? (in R)
```<code>mydata <- read.table(header=TRUE, text="
  Away    Home   Game.ID   Points.A   Points.H   Series.ID   Series.Wins
  Denver  Utah   aaa123      121        123       aaabbb          Utah
  Denver  Utah   aaa124      132        116       aaabbb          Denver
  Utah    Denver aaa125      117        121       aaabbb          Denver
  Utah    Denver aaa126      112        120       aaabbb          Denver
  Denver  Utah   aaa127      115        122       aaabbb          Utah
  Atlanta Boston aab123      112        114       aaaccc          Boston
")
</code>```

I am trying to create an additional column that counts, one at a time, the Series.Wins within each Series.ID group. So, from the data above, that column column would look like:

```<code>new.column <- c(1, 1, 2, 3, 2, 1)
</code>```

The ultimate goal is to come up with a series record column with "home wins -
 away wins":

```<code>Record <- c(1-0, 1-1, 2-1, 3-1, 2-3, 1-0)
</code>```

答:
This seemed to work: </p>

```<code>mydata <- mydata %>% group_by(Series.Wins) %>% group_by(Series.ID, add = TRUE) %>% mutate(id = seq_len(n()))
</code>```

Body:
mydata <- read.table(header=TRUE, text="
  Away    Home   Game.ID   Points.A   Points.H   Series.ID   Series.Wins
  Denver  Utah   aaa123      121        123       aaabbb          Utah
  Denver  Utah   aaa124      132        116       aaabbb          Denver
  Utah    Denver aaa125      117        121       aaabbb          Denver
  Utah    Denver aaa126      112        120       aaabbb          Denver
  Denver  Utah   aaa127      115        122       aaabbb          Utah
  Atlanta Boston aab123      112        114       aaaccc          Boston
")

I am trying to create an additional column that counts, one at a time, the Series.Wins within each Series.ID group. So, from the data above, that column column would look like:

new.column <- c(1, 1, 2, 3, 2, 1)

The ultimate goal is to come up with a series record column with "home wins -
 away wins":

Record <- c(1-0, 1-1, 2-1, 3-1, 2-3, 1-0)

Body:
This seemed to work:

mydata <- mydata %>% group_by(Series.Wins) %>% group_by(Series.ID, add = TRUE) %>% mutate(id = seq_len(n()))


问:
where are the point clouds saved when using the Constructor app?
I'm using the Constructor app and after I have scanned a room, I can't seem to find the saved point cloud anywhere on the device. I don't want to use the "Share" button, I would like to know where the data is saved locally. Would it be possible to know where the point clouds are saved on the device?

Thank you

答:
I am on a Lenovo Phab Pro and the scanned data of te Constructor app are saved in the following folder : /sdcard/TangoConstructor/ as a .zip folder for each scene you captured. Inside, you should find your mesh as a .obj file.

It is not a raw point cloud that is saved but you can get the point cloud from the .obj file.

After the capture, it can takes several minutes for the app to process the mesh, you get a notification when it is done. Then, if you wait some minutes you should get a notification telling you where the data have been exported. Only after that you can access the target folder, it is not visible beforehand.


问:
Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime
I'm trying to convert a date in a varchar column in the dd/mm/yyyy format into the datetime dd/mm/yyyy format, so then I can run date range queries on the data.

So far I have the following which is not working

```<code>CONVERT(varchar, CAST(date_started AS datetime), 103)
</code>```

I have also tried

```<code>convert(date_started as datetime, 103)
</code>```

I need to make sure the output is as dd/mm/yyyy as we're in the UK and not the mm/dd/yyyy format

答:
If you want to return a format mm/dd/yyyy, then use 101 instead of 103:
CONVERT(VARCHAR(10), [MyDate], 101)</p>

Body:
I'm trying to convert a date in a varchar column in the dd/mm/yyyy format into the datetime dd/mm/yyyy format, so then I can run date range queries on the data.

So far I have the following which is not working

CONVERT(varchar, CAST(date_started AS datetime), 103)

I have also tried

convert(date_started as datetime, 103)

I need to make sure the output is as dd/mm/yyyy as we're in the UK and not the mm/dd/yyyy format


问:
Excluding query result with in and not in
I have two tables:

Person (BusinessEntityID, FirstName, LastName)

Sales (OrderID, CustomerID, OrderDate)

I want to list people that made orders both in 2011 and 2014 but never made orders in 2012 and 2013

I would expect this query to work, but it is still listing orders in 2013

```<code>SELECT
    s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM
    Sales.SalesOrderHeader s,Person.Person p
WHERE
    s.CustomerID = p.BusinessEntityID
    AND s.CustomerID IN (SELECT CustomerID
                         FROM Sales.SalesOrderHeader
                         WHERE YEAR(OrderDate) IN (2011, 2014)
                         GROUP BY CustomerID
                         HAVING COUNT(CustomerID) > 1)
    AND s.CustomerID NOT IN (SELECT CustomerID
                             FROM Sales.SalesOrderHeader
                             WHERE YEAR(OrderDate) IN (2012, 2013)
                             GROUP BY CustomerID
                             HAVING COUNT(CustomerID) > 1)
GROUP BY
    s.CustomerID, p.LastName, p.FirstName, s.OrderDate
</code>```

Results:

```<code>CustomerID     LastName    FirstName    OrderDate
---------------------------------------------------------------
11001          Young       Amber        2011-06-17 00:00:00.000
11001          Young       Amber        2013-06-18 00:00:00.000
11001          Young       Amber        2014-05-12 00:00:00.000
11017          Clark       Chloe        2011-06-14 00:00:00.000
11017          Clark       Chloe        2013-06-03 00:00:00.000
11017          Clark       Chloe        2014-03-16 00:00:00.000
11018          Mehta       Joe          2011-06-19 00:00:00.000
11018          Mehta       Joe          2013-06-18 00:00:00.000
11018          Mehta       Joe          2014-03-26 00:00:00.000
</code>```

答:
You could do like this.</p>

```<code>create table #Person(BussinessEntityID int ,FirstName varchar(100), LastName varchar(100));
create table #Sales(OrderID int ,CustomerID int ,OrderDate datetime);

SELECT s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM #Sales s,#Person p
WHERE s.CustomerID = p.BussinessEntityID
and exists (select top 1 1 from #Sales X Where x.CustomerID=p.BussinessEntityID and Year(x.OrderDate)=2011)
and exists (select top 1 1 from #Sales X Where x.CustomerID=p.BussinessEntityID and Year(x.OrderDate)=2014)
and not exists (select top 1 1 from #Sales X Where x.CustomerID=p.BussinessEntityID and Year(x.OrderDate) in (2012,2013));
</code>```

Body:
I have two tables:

Person (BusinessEntityID, FirstName, LastName)

Sales (OrderID, CustomerID, OrderDate)

I want to list people that made orders both in 2011 and 2014 but never made orders in 2012 and 2013

I would expect this query to work, but it is still listing orders in 2013

SELECT
    s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM
    Sales.SalesOrderHeader s,Person.Person p
WHERE
    s.CustomerID = p.BusinessEntityID
    AND s.CustomerID IN (SELECT CustomerID
                         FROM Sales.SalesOrderHeader
                         WHERE YEAR(OrderDate) IN (2011, 2014)
                         GROUP BY CustomerID
                         HAVING COUNT(CustomerID) > 1)
    AND s.CustomerID NOT IN (SELECT CustomerID
                             FROM Sales.SalesOrderHeader
                             WHERE YEAR(OrderDate) IN (2012, 2013)
                             GROUP BY CustomerID
                             HAVING COUNT(CustomerID) > 1)
GROUP BY
    s.CustomerID, p.LastName, p.FirstName, s.OrderDate

Results:

CustomerID     LastName    FirstName    OrderDate
---------------------------------------------------------------
11001          Young       Amber        2011-06-17 00:00:00.000
11001          Young       Amber        2013-06-18 00:00:00.000
11001          Young       Amber        2014-05-12 00:00:00.000
11017          Clark       Chloe        2011-06-14 00:00:00.000
11017          Clark       Chloe        2013-06-03 00:00:00.000
11017          Clark       Chloe        2014-03-16 00:00:00.000
11018          Mehta       Joe          2011-06-19 00:00:00.000
11018          Mehta       Joe          2013-06-18 00:00:00.000
11018          Mehta       Joe          2014-03-26 00:00:00.000

Body:
You could do like this.

create table #Person(BussinessEntityID int ,FirstName varchar(100), LastName varchar(100));
create table #Sales(OrderID int ,CustomerID int ,OrderDate datetime);

SELECT s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM #Sales s,#Person p
WHERE s.CustomerID = p.BussinessEntityID
and exists (select top 1 1 from #Sales X Where x.CustomerID=p.BussinessEntityID and Year(x.OrderDate)=2011)
and exists (select top 1 1 from #Sales X Where x.CustomerID=p.BussinessEntityID and Year(x.OrderDate)=2014)
and not exists (select top 1 1 from #Sales X Where x.CustomerID=p.BussinessEntityID and Year(x.OrderDate) in (2012,2013));


问:
laravel eloquent with sum multiple rows from linked table
I have a table Quotes that has a one-to-many relationship with the QuoteDetails table.

The table structure looks like this:

```<code>return $this->quotes->with('quotedetails')
    ->orderBy('created_at', 'DESC')->paginate(10);
</code>```

Results in:

```<code>{
   "current_page":1,
   "data":[
      {
         "id":2,
         "subject":"demo",
         "quotedetails":[
            {
               "id":2,
               "quotes_id":2,
               "description":"testing data",
               "total":1080
            },
            {
               "id":3,
               "quotes_id":2,
               "description":"testing",
               "total":180
            }
         ]
      },
      {
         "id":1,
         "subject":"demo",
         "quotedetails":[
            {
               "id":1,
               "quotes_id":1,
               "description":"data",
               "total":360
            }
         ]
      }
   ],
   "per_page":10,
   "prev_page_url":null,
   "to":2,
   "total":2
}
</code>```

I want to include the sum of quotedetails.total rather than the full list of QuoteDetails rows. I am not sure how this should be done.

Here is how I am querying in my model (Quotes)

```<code>public function quotedetails(){
        return $this->hasMany('App\Models\QuotesDetail', 'quotes_id', 'id');
    }
</code>```

How can i get the total sum.

Here is how i expect the output

```<code>{
   "current_page":1,
   "data":[
      {
         "id":2,
         "subject":"demo link data",
         "quotesum": 1260
      },
      {
         "id":1,
         "subject":"demo",
         "quotesum": 360
      }
   ],
   "per_page":10,
   "prev_page_url":null,
   "to":2,
   "total":2
}
</code>```

答:
```<code>$query->withCount([
'quotedetail AS quotesum' => function ($query) {
            $query->select(DB::raw("SUM(total) as quotesum"));
        }
    ]);
</code>```

Body:
I have a table Quotes that has a one-to-many relationship with the QuoteDetails table.

The table structure looks like this:

return $this->quotes->with('quotedetails')
    ->orderBy('created_at', 'DESC')->paginate(10);

Results in:

{
   "current_page":1,
   "data":[
      {
         "id":2,
         "subject":"demo",
         "quotedetails":[
            {
               "id":2,
               "quotes_id":2,
               "description":"testing data",
               "total":1080
            },
            {
               "id":3,
               "quotes_id":2,
               "description":"testing",
               "total":180
            }
         ]
      },
      {
         "id":1,
         "subject":"demo",
         "quotedetails":[
            {
               "id":1,
               "quotes_id":1,
               "description":"data",
               "total":360
            }
         ]
      }
   ],
   "per_page":10,
   "prev_page_url":null,
   "to":2,
   "total":2
}

I want to include the sum of quotedetails.total rather than the full list of QuoteDetails rows. I am not sure how this should be done.

Here is how I am querying in my model (Quotes)

public function quotedetails(){
        return $this->hasMany('App\Models\QuotesDetail', 'quotes_id', 'id');
    }

How can i get the total sum.

Here is how i expect the output

{
   "current_page":1,
   "data":[
      {
         "id":2,
         "subject":"demo link data",
         "quotesum": 1260
      },
      {
         "id":1,
         "subject":"demo",
         "quotesum": 360
      }
   ],
   "per_page":10,
   "prev_page_url":null,
   "to":2,
   "total":2
}


问:
Modulo and order of operation in Python
In Zed Shaw's Learn Python the Hard Way (page 15-16), he has an example exercise

```<code> 100 - 25 * 3 % 4
</code>```

the result is 97 (try it!)

I cannot see the order of operations that could do this..

100 - 25 = 75

3 % 4 = 0

or (100-25*3) =225 % 4 = ???   but anyhow not 97 I don't think...

A similar example is 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 which yields 7

In what order are the operations done?

答: For the first example: * and % take precedence over -, so we first evaluate 25 * 3 % 4.  * and % have the same priority and associativity from left to right, so we evaluate from left to right, starting with 25 * 3.  This yields 75.  Now we evaluate 75 % 4, yielding 3.  Finally, 100 - 3 is 97.

Title: Modulo and order of operation in Python

Body:
In Zed Shaw's Learn Python the Hard Way (page 15-16), he has an example exercise

 100 - 25 * 3 % 4

the result is 97 (try it!)

I cannot see the order of operations that could do this..

100 - 25 = 75

3 % 4 = 0

or (100-25*3) =225 % 4 = ???   but anyhow not 97 I don't think...

A similar example is 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 which yields 7

In what order are the operations done?