问:
git checkout only certain file types for entire project
Is there a way to perform a git checkout for only certain file types (.xlf), which recurses down through the entire repository? The results should contain the struture of the repository, meaning the folders, and the contained files of a certain extension.

Repo A

```<code>file.xlf
file.txt
level2/
    file2.xlf
    file2.txt
    level3/
        file3.xlf
        file3.txt
</code>```

After checkout repo B looks like:

Repo B

```<code>file.xlf
    /level2
    file2.xlf
        /level3
        file3.xlf
</code>```

This is what I have so far:

```<code>$ git checkout FETCH_HEAD -- '*.xlf'
</code>```

This gives all of the ".xlf" files at the root level, but is not recursive down to subdirectories.

Thank you for the help.

答:
You don't need find or sed, you can use wildcards as git understands them (doesn't depend on your shell):

```<code>git checkout -- "*.xml"
</code>```

The quotes will prevent your shell to expand the command to only files in the current directory before its execution.

You can also disable shell glob expansion (with bash) :

```<code>set -f
git checkout -- *.xml
</code>```

This, of course, will irremediably erase your changes!

Body:
Is there a way to perform a git checkout for only certain file types (.xlf), which recurses down through the entire repository? The results should contain the struture of the repository, meaning the folders, and the contained files of a certain extension.

Repo A

file.xlf
file.txt
level2/
    file2.xlf
    file2.txt
    level3/
        file3.xlf
        file3.txt

After checkout repo B looks like:

Repo B

file.xlf
    /level2
    file2.xlf
        /level3
        file3.xlf

This is what I have so far:

$ git checkout FETCH_HEAD -- '*.xlf'

This gives all of the ".xlf" files at the root level, but is not recursive down to subdirectories.

Thank you for the help.

Body:
You don't need find or sed, you can use wildcards as git understands them (doesn't depend on your shell):

git checkout -- "*.xml"

The quotes will prevent your shell to expand the command to only files in the current directory before its execution.

You can also disable shell glob expansion (with bash) :

set -f
git checkout -- *.xml

This, of course, will irremediably erase your changes!


来源: stackexchange

问:
When I try to delete list I got a list size greater than list size+1
```<code>List<Studentdb> list = teacherDao.viewstudent(facultyid, batchid1);
System.out.println("" + list);
int i = 0;
for (Iterator<Studentdb> s = list.iterator(); s.hasNext(); ) {
     System.out.println("" + i);
     System.out.println("list========" + list.get(i).getRoll());
     if (teacherDao.viewmarks(subjectcode, list.get(i).getRoll())) {
           list.remove(s);
     }
    i++;
}
</code>```

When I try to delete a selected list i get the error java.lang.IndexOutOfBoundsException: Index: 3, Size: 3.

Here I have list size 3 i.e index 0 1 2 and I got the error in index 3.

答:
Removing items from lists in a for loop is always a mess.

It's best to place the desired items in another list, or if using Java 8 use streams and filter the list.

ContentLicense: CC BY-SA 3.0

Body:
List<Studentdb> list = teacherDao.viewstudent(facultyid, batchid1);
System.out.println("" + list);
int i = 0;
for (Iterator<Studentdb> s = list.iterator(); s.hasNext(); ) {
     System.out.println("" + i);
     System.out.println("list========" + list.get(i).getRoll());
     if (teacherDao.viewmarks(subjectcode, list.get(i).getRoll())) {
           list.remove(s);
     }
    i++;
}

When I try to delete a selected list i get the error java.lang.IndexOutOfBoundsException: Index: 3, Size: 3.

Here I have list size 3 i.e index 0 1 2 and I got the error in index 3.


问:
Node.js quick file server (static files over HTTP)
Is there Node.js ready-to-use tool (installed with npm), that would help me expose folder content as file server over HTTP.

Example, if I have

```<code>D:\Folder\file.zip
D:\Folder\file2.html
D:\Folder\folder\file-in-folder.jpg
</code>```

Then starting in D:\Folder\ node node-file-server.js
I could access file via

```<code>http://hostname/file.zip
http://hostname/file2.html
http://hostname/folder/file-in-folder.jpg
</code>```

Why is my node static file server dropping requests?
reference some mystical

standard node.js static file server

If there's no such tool, what framework should I use?

Related:
Basic static file server in NodeJS

答:
You also asked why requests are dropping - not sure what's the specific reason on your case, but in overall you better server static content using dedicated middleware (nginx, S3, CDN) because Node is really not optimized for this networking pattern. See further explanation here (bullet 13):
http://goldbergyoni.com/checklist-best-practice-of-node-js-in-production/</p>

Body:
Is there Node.js ready-to-use tool (installed with npm), that would help me expose folder content as file server over HTTP.

Example, if I have

D:\Folder\file.zip
D:\Folder\file2.html
D:\Folder\folder\file-in-folder.jpg

Then starting in D:\Folder\ node node-file-server.js
I could access file via

http://hostname/file.zip
http://hostname/file2.html
http://hostname/folder/file-in-folder.jpg

Why is my node static file server dropping requests?
reference some mystical

standard node.js static file server

If there's no such tool, what framework should I use?

Related:
Basic static file server in NodeJS


问:
Use Google Maps marker coordinates as form input
From the below javascript function, I get a javascript variable marker with coordinates when the user clicks a position on the map.

```<code>var marker;
function placeMarker(location) {
  if ( marker ) {
    marker.setPosition(location);
  } else {
    marker = new google.maps.Marker({
      position: location,
      map: map
    });
  }
}
google.maps.event.addListener(map, 'click', function(event) {
  placeMarker(event.latLng);
});
</code>```

Question
How can these coordinates be used as form input?

```<code><form method="POST" action="/authors" target="" enctype="multipart/form-data">
   ...
</form>
</code>```

答:
All you have to do is take the location variable and assign it to your form input like this:

First, add a hidden input field

```<code><form method="POST" action="/authors" target="" enctype="multipart/form-data">
   <input id="location" name="location" type="hidden" value="" />
</form>
</code>```

Second, make sure the location variable gets added to your input

```<code>var marker;
function placeMarker(location) {
  if ( marker ) {
    marker.setPosition(location);
  } else {
    marker = new google.maps.Marker({
      position: location,
      map: map
    });
  }

  $("#location").val(location);

}
google.maps.event.addListener(map, 'click', function(event) {
  placeMarker(event.latLng);
});
</code>```

Now, whenever placeMarker(location) gets called it will update the input with the id of "location" and its value is the output of location.

Body:
From the below javascript function, I get a javascript variable marker with coordinates when the user clicks a position on the map.

var marker;
function placeMarker(location) {
  if ( marker ) {
    marker.setPosition(location);
  } else {
    marker = new google.maps.Marker({
      position: location,
      map: map
    });
  }
}
google.maps.event.addListener(map, 'click', function(event) {
  placeMarker(event.latLng);
});

Question
How can these coordinates be used as form input?

<form method="POST" action="/authors" target="" enctype="multipart/form-data">
   ...
</form>

Body:
All you have to do is take the location variable and assign it to your form input like this:

First, add a hidden input field

<form method="POST" action="/authors" target="" enctype="multipart/form-data">
   <input id="location" name="location" type="hidden" value="" />
</form>

Second, make sure the location variable gets added to your input

var marker;
function placeMarker(location) {
  if ( marker ) {
    marker.setPosition(location);
  } else {
    marker = new google.maps.Marker({
      position: location,
      map: map
    });
  }

  $("#location").val(location);

}
google.maps.event.addListener(map, 'click', function(event) {
  placeMarker(event.latLng);
});

Now, whenever placeMarker(location) gets called it will update the input with the id of "location" and its value is the output of location.


问:
PHP: Get http status code that own script just sent out via shutdown function
I have a shutdown function that checks to see if a redirect was just issued. From headers_list() I can get the headers sent and see the location header. My question is how would I figure out what http_response_code was used in the header() function. Headers list doesn't have the response code.

Example code to play around with. I don't use redirects in the example code, otherwise it would loop. Main thing is I would like to detect a 301 vs any other kind of redirect. This would be inside drupal (via drupal_goto using hook_exit); but the example code below shows the issue. I have no way of knowing what status number was passed to the browser via header().

```<code><?php
register_shutdown_function('test');

if (mt_rand(0, 1)) {
  header('X-test: junk 1', TRUE, 201);
}
else {
  header('X-test: junk 0', TRUE, 202);
}

exit();

function test() {
  if ($location = test_headers_contain('X-test: ')) {
    // Would like to check the status code that was sent out
    echo $location . '<br>';
    $list = headers_list();
    $txt = str_replace('    ', '    ', nl2br(htmlentities(print_r($list, TRUE))));
    echo $txt;
  }
}

function test_headers_contain($text) {
  if (function_exists('headers_list')) {
    $list = headers_list();
    if (empty($list)) {
      return FALSE;
    }
    foreach ($list as $header) {
      $info = stristr($header, $text);
      if ($info !== FALSE) {
        return $info;
      }
    }
  }
  return FALSE;
}
?>
</code>```

This code outputs this

```<code>X-test: junk 1
Array
(
    [0] => X-Powered-By: PHP/5.2.10
    [1] => X-test: junk 1
)
</code>```

答: Revision 302033 added the function http_response_code in response to just the sort of issue you describe, but I'm not certain when it will be included in a release. It's not in 5.3.4. If you have access, you could build a patched version of PHP with this function added. If not, you could request it of whoever on your host does have access.

ContentLicense: CC BY-SA 2.5

Body:
I have a shutdown function that checks to see if a redirect was just issued. From headers_list() I can get the headers sent and see the location header. My question is how would I figure out what http_response_code was used in the header() function. Headers list doesn't have the response code.

Example code to play around with. I don't use redirects in the example code, otherwise it would loop. Main thing is I would like to detect a 301 vs any other kind of redirect. This would be inside drupal (via drupal_goto using hook_exit); but the example code below shows the issue. I have no way of knowing what status number was passed to the browser via header().

<?php
register_shutdown_function('test');

if (mt_rand(0, 1)) {
  header('X-test: junk 1', TRUE, 201);
}
else {
  header('X-test: junk 0', TRUE, 202);
}

exit();

function test() {
  if ($location = test_headers_contain('X-test: ')) {
    // Would like to check the status code that was sent out
    echo $location . '
';
    $list = headers_list();
    $txt = str_replace('    ', '    ', nl2br(htmlentities(print_r($list, TRUE))));
    echo $txt;
  }
}

function test_headers_contain($text) {
  if (function_exists('headers_list')) {
    $list = headers_list();
    if (empty($list)) {
      return FALSE;
    }
    foreach ($list as $header) {
      $info = stristr($header, $text);
      if ($info !== FALSE) {
        return $info;
      }
    }
  }
  return FALSE;
}
?>

This code outputs this

X-test: junk 1
Array
(
    [0] => X-Powered-By: PHP/5.2.10
    [1] => X-test: junk 1
)


问:
git rebase to a different branch
I have the following situation:

```<code>Master ---X---X---X
               \
   Alpha branch A1---A2---A3---A4---A5---A6
                      \              \
                       \  beta branch B1---B2
                        \
              My Branch M1---M2---M3
</code>```

I want to move my branch to "B2", ending up like this:

```<code>Master ---X---X---X
               \
   Alpha branch A1---A2---A3---A4---A5---A6
                                     \
                          beta branch B1---B2
                                            \
                                  My Branch M1---M2---M3
</code>```

To do that, should I make, in my branch, a git rebase beta or should I add the option --onto like this: git rebase --onto beta alpha My? I had read the documentation, but I still didn't figure out the difference...

答:
Here's four ways to do it:

git rebase <branch>

Reset checked out branch to <branch>, apply differences (between
previous HEAD and the common ancestor) and commit.

```<code>git checkout my
git rebase beta
</code>```

git rebase <branch1> <branch2>

Reset <branch2> to <branch1>, apply differences (between previous <branch2> and the common ancestor) and commit.

```<code>git rebase beta my
</code>```

git rebase --onto <branch1> <branch2>

Reset checked out branch to <branch1>, apply differences (between previous HEAD and <branch2>) and commit.

```<code>git checkout my
git rebase --onto beta A2
</code>```

git rebase --onto <branch1> <branch2> <branch3>

Reset <branch2> to <branch1>, apply differences (between previous HEAD and <branch2>) and commit.

```<code>git rebase --onto beta A2 my
</code>```

Title: git rebase to a different branch

Body:
I have the following situation:

Master ---X---X---X
               \
   Alpha branch A1---A2---A3---A4---A5---A6
                      \              \
                       \  beta branch B1---B2
                        \
              My Branch M1---M2---M3

I want to move my branch to "B2", ending up like this:

Master ---X---X---X
               \
   Alpha branch A1---A2---A3---A4---A5---A6
                                     \
                          beta branch B1---B2
                                            \
                                  My Branch M1---M2---M3

To do that, should I make, in my branch, a git rebase beta or should I add the option --onto like this: git rebase --onto beta alpha My? I had read the documentation, but I still didn't figure out the difference...

Body:
Here's four ways to do it:

git rebase <branch>

Reset checked out branch to <branch>, apply differences (between
previous HEAD and the common ancestor) and commit.

git checkout my
git rebase beta

git rebase <branch1> <branch2>

Reset <branch2> to <branch1>, apply differences (between previous <branch2> and the common ancestor) and commit.

git rebase beta my

git rebase --onto <branch1> <branch2>

Reset checked out branch to <branch1>, apply differences (between previous HEAD and <branch2>) and commit.

git checkout my
git rebase --onto beta A2

git rebase --onto <branch1> <branch2> <branch3>

Reset <branch2> to <branch1>, apply differences (between previous HEAD and <branch2>) and commit.

git rebase --onto beta A2 my


问:
Is the code valid. If i want to display first element? if not then what will s.begin() return?
I am trying to display first element inserted into a vector.Can i use the begin() to access it?</p>

```<code> vector<int>s;
 s.push_back(5);
 cout<<s.begin();
</code>```

答:
Access with the std::vector::operator[].

```<code>vector<int>s;
s.push_back(5);
cout << s[0];
</code>```

Body:
I am trying to display first element inserted into a vector.Can i use the begin() to access it?

 vector<int>s;
 s.push_back(5);
 cout<<s.begin();

Body:
Access with the std::vector::operator[].

vector<int>s;
s.push_back(5);
cout << s[0];


问:
Making a TIME SERIES graph THAT SCROLLS WITH THE DATA in R
I need to do exactly the graph that has been made on this page (the second one)
http://www.animatedgraphs.co.uk/line.html

Here is my actual code :

```<code>timemax<-151737 # number of frames (and observations - so no interpolation needed)
setwd("C:/Users/victo/Downloads/ffmpeg/ffmpeg/bin/")
vis<-100 # how many time points are on the screen at one time
gdata<-data.frame('Temps'= data$time,'RH_Xacc'= data$RH_Xacc)

gname<-paste("g",1:timemax,".tif", sep="") # holds the names of the picture files
right<-(((1:timemax)<=vis)*100)+(((1:timemax)>vis)*1:timemax) # rightmost time on screen
left<- right-vis+2 # leftmost time on screen
leftlab<-200*ceiling((left-1)/200) # leftmost x label
rightlab<-200*floor(right/200) # rightmost x label

# draw graphs
for (i in 1:timemax) {
tiff(gname[i],width=480)
plot(gdata$Temps[right[i]:left[i]],gdata$RH_Xacc[right[i]:left[i]],col="red",type="l",ylim=c(-100,200),xlim=c(right[i],left[i]),xaxt="n",ylab="",xlab="time")
axis(1,at=seq(from=rightlab[i],to=leftlab[i],by=12))
lines(gdata$Temps[right[i]:i],gdata$RH_Xacc[right[i]:i])
dev.off(dev.cur())
}

 # call FFMPEG and make the video
 shell("C:/Users/victo/Downloads/ffmpeg/ffmpeg/bin/ffmpeg.exe -codecs -i g%d.tif -b:v 2048k gdata.mpg",mustWork=FALSE)
</code>```

My code seems to work until the shell function. I don't get an error. The code just never stops running. I am not able to get the video with all the data. Can someone tell me where is the problem ? How can I get the video or if there is an other to get the same result ? I've tried the library gganimate but i didn't succeed either... I am doing this in Rstudio and using sweave.

Thanks a lot

答:
Actually, the first thing you should do is probably run the command :
C:/Users/victo/Downloads/ffmpeg/ffmpeg/bin/ffmpeg.exe -codecs -i g%d.tif -b:v 2048k gdata.mpg directly and not with a calling shell from RStudio. You would have a more verbose output.

Original post

Do you have any CPU performance profiling tool ? I suspect that the shell command might take a lot of time to run on your computer since in your example : timemax<-151737 whereas the example has a shorter timemax timemax<-1000

Try your program with a low value of timemax (=1000) and time the execution of the code. I guess you could extrapolate the total time needed to execute multiplying by 150 (I am not an expert of ffmpeg, it might actually be longer)

Body:
I need to do exactly the graph that has been made on this page (the second one)
http://www.animatedgraphs.co.uk/line.html

Here is my actual code :

timemax<-151737 # number of frames (and observations - so no interpolation needed)
setwd("C:/Users/victo/Downloads/ffmpeg/ffmpeg/bin/")
vis<-100 # how many time points are on the screen at one time
gdata<-data.frame('Temps'= data$time,'RH_Xacc'= data$RH_Xacc)

gname<-paste("g",1:timemax,".tif", sep="") # holds the names of the picture files
right<-(((1:timemax)<=vis)*100)+(((1:timemax)>vis)*1:timemax) # rightmost time on screen
left<- right-vis+2 # leftmost time on screen
leftlab<-200*ceiling((left-1)/200) # leftmost x label
rightlab<-200*floor(right/200) # rightmost x label

# draw graphs
for (i in 1:timemax) {
tiff(gname[i],width=480)
plot(gdata$Temps[right[i]:left[i]],gdata$RH_Xacc[right[i]:left[i]],col="red",type="l",ylim=c(-100,200),xlim=c(right[i],left[i]),xaxt="n",ylab="",xlab="time")
axis(1,at=seq(from=rightlab[i],to=leftlab[i],by=12))
lines(gdata$Temps[right[i]:i],gdata$RH_Xacc[right[i]:i])
dev.off(dev.cur())
}

 # call FFMPEG and make the video
 shell("C:/Users/victo/Downloads/ffmpeg/ffmpeg/bin/ffmpeg.exe -codecs -i g%d.tif -b:v 2048k gdata.mpg",mustWork=FALSE)

My code seems to work until the shell function. I don't get an error. The code just never stops running. I am not able to get the video with all the data. Can someone tell me where is the problem ? How can I get the video or if there is an other to get the same result ? I've tried the library gganimate but i didn't succeed either... I am doing this in Rstudio and using sweave.

Thanks a lot


答: If you are on top of your branch, just saying git rebase beta or git rebase B2 will do. The difference is that by using --onto you can control more tricky situations..... like the opposite: want to move beta branch on top of my branch. If you are on top of beta and run git rebase my-branch you would end up with M1--M2--M3--A3'--A4'--A5'--B1'--B2' (because from the point where the branches diverged (A2) revisions A3 to A5 (both inclusive) would also have to be included in a simple rebase. In that case you would have to run: git rebase --onto my-branch alpha-branch beta-branch. Hope that clears it up

Title: git rebase to a different branch


问:
How do you create an oval with border-radius in CSS?
I need an oval instead of a rectangle with rounded edges.

Here's the code I'm using.

```<code>div {
  position: fixed;
  border-radius: 25px;
  background: rgba(0,0,0,.5)
  width: 100px;
  height: 50px;
  top: calc(50% - 25px);
  right: calc(50% - 50px);
}
</code>```

答:
Try this link
which will explain all the different shapes you need. </p>

<p>Following is an example on how you can achieve it. </p>

```<code>   #round {
      position: relative;
      width: 100px;
      height: 100px;
      margin: 20px 0;
      background: orange;
      border-radius: 48% / 25%;
      color: white;
    }
    #round:before {
      content: '';
      position: absolute;
      top: 10%;
      bottom: 11%;
      right: -5%;
      left: -5%;
      background: inherit;
      border-radius: 21% / 68%;
    }

    <div id="round"></div>
</code>```

Body:
I need an oval instead of a rectangle with rounded edges.

Here's the code I'm using.

div {
  position: fixed;
  border-radius: 25px;
  background: rgba(0,0,0,.5)
  width: 100px;
  height: 50px;
  top: calc(50% - 25px);
  right: calc(50% - 50px);
}

Body:
Try this link
which will explain all the different shapes you need.

Following is an example on how you can achieve it.

   #round {
      position: relative;
      width: 100px;
      height: 100px;
      margin: 20px 0;
      background: orange;
      border-radius: 48% / 25%;
      color: white;
    }
    #round:before {
      content: '';
      position: absolute;
      top: 10%;
      bottom: 11%;
      right: -5%;
      left: -5%;
      background: inherit;
      border-radius: 21% / 68%;
    }

    <div id="round"></div>


问:
Align center isn't working
I'm trying to align the text inside my div both horizontally and vertically, but it's only aligning horizontally. Everything I try doesn't work...
here's my css code:

```<code>#loading > h1 {
  text-align: center;
  font-size: 21px;
  animation: fadeUpIn 3s;
  -webkit-animation: fadeUpIn 3s; /* Safari and Chrome */
}

@-webkit-keyframes fadeUpIn /* Safari and Chrome */
{
  from { opacity:0; top:150px; }
  to { opacity:1; top: 70px; }
}
#loading{
  position: absolute; top: 0; left: 0;
  width:100%;
  height: 100%;
  background-color: gray;
  color: white;
  opacity: 1;
  transition: 1s;
  visibility: visible;
}
#loading.hidden{
  opacity: 0;
  visibility: hidden;
}
</code>```

My html code:

```<code><div id="loading">
<h1>Creative. Simple.</h1>
</div>
</code>```

JS fiddle of the whole website:
https://jsfiddle.net/sjyoqdqy/

答:
```<code>#loading {
   ...
   display: table;
 }
#loading h1 {
   ...
   display: table-cell;
   vertical-align: middle;
}
</code>```

Title: Align center isn't working

Body:
I'm trying to align the text inside my div both horizontally and vertically, but it's only aligning horizontally. Everything I try doesn't work...
here's my css code:

#loading > h1 {
  text-align: center;
  font-size: 21px;
  animation: fadeUpIn 3s;
  -webkit-animation: fadeUpIn 3s; /* Safari and Chrome */
}

@-webkit-keyframes fadeUpIn /* Safari and Chrome */
{
  from { opacity:0; top:150px; }
  to { opacity:1; top: 70px; }
}
#loading{
  position: absolute; top: 0; left: 0;
  width:100%;
  height: 100%;
  background-color: gray;
  color: white;
  opacity: 1;
  transition: 1s;
  visibility: visible;
}
#loading.hidden{
  opacity: 0;
  visibility: hidden;
}

My html code:

Creative. Simple.

JS fiddle of the whole website:
https://jsfiddle.net/sjyoqdqy/


问:
How do I add the iPhone SDK 3 to the latest version of Xcode?
I just upgraded Xcode, but now I don't have any 3.x SDK for Simulator. How do I add it for testing purposes?</p>

答: You can goto Project->Edit Project Settings, and from there edit the "Base SDK" to what ever version you have.  From here when you build and run you should be running whatever sdk simulator or device you picked.</p>


问:
How can I find a specific node in my XML?
I have to read the xml node "name" from the following XML, but I don't know how to do it.

Here is the XML:

```<code><?xml version="1.0" standalone="yes" ?>
  <games>
    <game>
      <name>Google Pacman</name>
      <url>http:\\www.google.de</url>
    </game>
  </games>
</code>```

Code:

```<code>using System.Xml;

namespace SRCDSGUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + @"\games.xml");

            XmlElement root = doc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("//games");

            foreach (XmlNode node in nodes)
            {
                listBox1.Items.Add(node["game"].InnerText);
            }

        }
    }
}
</code>```

答:
Here is an example of simple function that finds and fetches two particular nodes from XML file and returns them as string array</p>

```<code>private static string[] ReadSettings(string settingsFile)
    {
        string[] a = new string[2];
        try
        {
            XmlTextReader xmlReader = new XmlTextReader(settingsFile);
            while (xmlReader.Read())
            {
                switch (xmlReader.Name)
                {
                    case "system":
                        break;
                    case "login":
                        a[0] = xmlReader.ReadString();
                        break;
                    case "password":
                        a[1] = xmlReader.ReadString();
                        break;
                }

            }
            return a;
        }
        catch (Exception ex)
        {
            return a;
        }
    }
</code>```

Body:
I have to read the xml node "name" from the following XML, but I don't know how to do it.

Here is the XML:

<?xml version="1.0" standalone="yes" ?>
  <games>
    <game>
      <name>Google Pacman</name>
      <url>http:\\www.google.de</url>
    </game>
  </games>

Code:

using System.Xml;

namespace SRCDSGUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + @"\games.xml");

            XmlElement root = doc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("//games");

            foreach (XmlNode node in nodes)
            {
                listBox1.Items.Add(node["game"].InnerText);
            }

        }
    }
}

Body:
Here is an example of simple function that finds and fetches two particular nodes from XML file and returns them as string array

private static string[] ReadSettings(string settingsFile)
    {
        string[] a = new string[2];
        try
        {
            XmlTextReader xmlReader = new XmlTextReader(settingsFile);
            while (xmlReader.Read())
            {
                switch (xmlReader.Name)
                {
                    case "system":
                        break;
                    case "login":
                        a[0] = xmlReader.ReadString();
                        break;
                    case "password":
                        a[1] = xmlReader.ReadString();
                        break;
                }

            }
            return a;
        }
        catch (Exception ex)
        {
            return a;
        }
    }


答:
Simply use border-radius: 50% instead :)

div {
  border-radius: 50%;
  background-color: rgba(0,0,0,0.5);
  width: 100px;
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Title: How do you create an oval with border-radius in CSS?

Body:
Simply use border-radius: 50% instead :)

div {
  border-radius: 50%;
  background-color: rgba(0,0,0,0.5);
  width: 100px;
  height: 50px;
}

<div></div>


问:
TYPO3 Extbase - The configuration file "ext_emconf.php" seems to be invalid
I try to upload my extension but I get Please check your uploaded extension "my_download_plugin". The configuration file "ext_emconf.php" seems to be invalid.
What is supposed to be wrong with this configuration file?

```<code><?php

/***************************************************************
 * Extension Manager/Repository config file for ext: "my_download_plugin"
 *
 * Auto generated by Extension Builder 2017-01-30
 *
 * Manual updates:
 * Only the data in the array - anything else is removed by next write.
 * "version" and "dependencies" must not be touched!
 ***************************************************************/

$EM_CONF[$_EXTKEY] = array(
    'title' => 'my_download_plugin',
    'description' => 'Downloadlist for my Donwloadcenter',
    'category' => 'plugin',
    'author' => 'Edward Black',
    'author_email' => 'my.name@mycompany.de',
    'state' => 'beta',
    'createDirs' => '',
    'uploadfolder' => false,
    'clearCacheOnLoad' => false,
    'version' => '2.0.0',
    'constraints' => array(
        'depends' => array(
            'typo3' => '6.2.0-6.3.0',
            'static_info_tables' => '6.3.9'
        ),
        'conflicts' => array(),
        'suggests' => array()
    )
);
</code>```

I was reading the official documentation but could not find anything wrong.

答:
I would prefer to set the version for "static_info_tables" to all for developing purposes.

Next you can add "sjbr/static-info-tables" => "*" to your composer.json.

Install the new dependency.

Now take the package version from the composer.lock-file and add it to your composer.json and now u can fix the version in your ext_emconf.php

Body:
I try to upload my extension but I get Please check your uploaded extension "my_download_plugin". The configuration file "ext_emconf.php" seems to be invalid.
What is supposed to be wrong with this configuration file?

<?php

/***************************************************************
 * Extension Manager/Repository config file for ext: "my_download_plugin"
 *
 * Auto generated by Extension Builder 2017-01-30
 *
 * Manual updates:
 * Only the data in the array - anything else is removed by next write.
 * "version" and "dependencies" must not be touched!
 ***************************************************************/

$EM_CONF[$_EXTKEY] = array(
    'title' => 'my_download_plugin',
    'description' => 'Downloadlist for my Donwloadcenter',
    'category' => 'plugin',
    'author' => 'Edward Black',
    'author_email' => 'my.name@mycompany.de',
    'state' => 'beta',
    'createDirs' => '',
    'uploadfolder' => false,
    'clearCacheOnLoad' => false,
    'version' => '2.0.0',
    'constraints' => array(
        'depends' => array(
            'typo3' => '6.2.0-6.3.0',
            'static_info_tables' => '6.3.9'
        ),
        'conflicts' => array(),
        'suggests' => array()
    )
);

I was reading the official documentation but could not find anything wrong.


问:
Exporting HTML canvas from inside of Chrome extension
I'm writing a Chrome extension where a canvas is modified, and I want to have the option to save the canvas data as an image. Is there any way for me (using JavaScript) to save directly to the file system (ideal) or at least prompt the user with a download menu so they can save it themselves?</p>

答:
There seems to be no way to do this except for these ideas:

Online backend written in PHP or something

An iframe to show the online website which would have the canvas on it

Tell the user to right click and save the canvas image


问:
how to always upload an unique image name to aws S3?
How can I ensure that I always upload a unique filename to aws S3?
Current solution:  image name with timestamp.</p>

答: Enable Version when you create the bucket.


问:
Get JSON from Web Service Using JavaScript
I get this error when I click the button in HTML to use my JavaScript.

```<code>myapp.azurewebsites.net/:1 Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
</code>```

JS:

```<code>function ajaxFunction() {
    console.log("ajaxFunction()");
    var ajaxRequest;
    try {
        ajaxRequest = new XMLHttpRequest();
    } catch(e) {
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                alert("Broken");
                return false;
            }
        }
    }

    ajaxRequest.onreadystatechange = function () {
        if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {

            var form = document.getElementById("myform");
            var titleParagraph = document.getElementById("home_title");
            titleParagraph.innerHTML = ajaxRequest.responseText;

            form.style.display = "none";

        }
    }

    var value1 = document.getElementById("field1").value;
    var value2 = document.getElementById("field2").value;
    var url = "https://webapp.azurewebsites.net/users/" + value1 + "/" + value2;
    console.log(url);

    // Call sign in web service

    ajaxRequest.open("GET", url, true);
    ajaxRequest.send(null);
    var jsonResponse = JSON.parse(ajaxRequest.responseText);
    console.log("RESPONSE:");
    console.log(jsonResponse);
}
</code>```

This JSON is what I get when I go to https://webapp.azurewebsites.net/users/value1/value2

```<code>[{"ID":1,"UserName":"username","FirstName":"first","LastName":"last","email":"example@example.com"}]
</code>```

答:
```<code>ajaxRequest.open("GET", url, false);
</code>```

Third parameter says if the request is asynchronous or not. So by looking at your code it should be synchronous.

Body:
I get this error when I click the button in HTML to use my JavaScript.

myapp.azurewebsites.net/:1 Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)

JS:

function ajaxFunction() {
    console.log("ajaxFunction()");
    var ajaxRequest;
    try {
        ajaxRequest = new XMLHttpRequest();
    } catch(e) {
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                alert("Broken");
                return false;
            }
        }
    }

    ajaxRequest.onreadystatechange = function () {
        if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {

            var form = document.getElementById("myform");
            var titleParagraph = document.getElementById("home_title");
            titleParagraph.innerHTML = ajaxRequest.responseText;

            form.style.display = "none";

        }
    }

    var value1 = document.getElementById("field1").value;
    var value2 = document.getElementById("field2").value;
    var url = "https://webapp.azurewebsites.net/users/" + value1 + "/" + value2;
    console.log(url);

    // Call sign in web service

    ajaxRequest.open("GET", url, true);
    ajaxRequest.send(null);
    var jsonResponse = JSON.parse(ajaxRequest.responseText);
    console.log("RESPONSE:");
    console.log(jsonResponse);
}

This JSON is what I get when I go to https://webapp.azurewebsites.net/users/value1/value2

[{"ID":1,"UserName":"username","FirstName":"first","LastName":"last","email":"example@example.com"}]

Body:
ajaxRequest.open("GET", url, false);

Third parameter says if the request is asynchronous or not. So by looking at your code it should be synchronous.


问:
Zoom listener for PhotoView
I'm using Chris Bane's PhotoView to display ImageViews in a ViewPager. I want to disable the ViewPager's scrolling when the user has zoomed into an image. I already found this Hacky ViewPager which can be used to enable/disable scrolling by calling toggleLock().

```<code>public class HackyViewPager extends ViewPager {

    private boolean isLocked;

    public HackyViewPager(Context context) {
        super(context);
        isLocked = false;
    }

    public HackyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        isLocked = false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (!isLocked) {
            try {
                return super.onInterceptTouchEvent(ev);
            }
            catch (IllegalArgumentException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return !isLocked && super.onTouchEvent(event);
    }

    public void toggleLock() {
        isLocked = !isLocked;
    }

    public void setLocked(boolean isLocked) {
        this.isLocked = isLocked;
    }

    public boolean isLocked() {
        return isLocked;
    }

}
</code>```

So my problem here is that I'm not sure at which point I have to call toogleLock(). I guess I have to implement a listener, but I'm not sure which one would be the best. Thanks in advance for helping me out!

EDIT: I figured it out on my own!

```<code>photoview.setOnMatrixChangeListener(new PhotoViewAttacher.OnMatrixChangedListener() {
            @Override
            public void onMatrixChanged(RectF rectF) {
                if (photoview.getScale() > 1) {
                    sPager.setLocked(true);
                } else {
                    sPager.setLocked(false);
                }
            }
        });
</code>```

答:
Instead of using HackyViewPager I set photoview.setAllowParentInterceptOnEdge(true) , when photo Scale = 1.</p>

```<code>photoView.setOnMatrixChangeListener(new PhotoViewAttacher.OnMatrixChangedListener() {
  @Override
  public void onMatrixChanged(RectF rect) {
    photoView.setAllowParentInterceptOnEdge(photoView.getScale() == 1);
  }
});
</code>```

Title: Zoom listener for PhotoView

Body:
I'm using Chris Bane's PhotoView to display ImageViews in a ViewPager. I want to disable the ViewPager's scrolling when the user has zoomed into an image. I already found this Hacky ViewPager which can be used to enable/disable scrolling by calling toggleLock().

public class HackyViewPager extends ViewPager {

    private boolean isLocked;

    public HackyViewPager(Context context) {
        super(context);
        isLocked = false;
    }

    public HackyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        isLocked = false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (!isLocked) {
            try {
                return super.onInterceptTouchEvent(ev);
            }
            catch (IllegalArgumentException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return !isLocked && super.onTouchEvent(event);
    }

    public void toggleLock() {
        isLocked = !isLocked;
    }

    public void setLocked(boolean isLocked) {
        this.isLocked = isLocked;
    }

    public boolean isLocked() {
        return isLocked;
    }

}

So my problem here is that I'm not sure at which point I have to call toogleLock(). I guess I have to implement a listener, but I'm not sure which one would be the best. Thanks in advance for helping me out!

EDIT: I figured it out on my own!

photoview.setOnMatrixChangeListener(new PhotoViewAttacher.OnMatrixChangedListener() {
            @Override
            public void onMatrixChanged(RectF rectF) {
                if (photoview.getScale() > 1) {
                    sPager.setLocked(true);
                } else {
                    sPager.setLocked(false);
                }
            }
        });

Body:
Instead of using HackyViewPager I set photoview.setAllowParentInterceptOnEdge(true) , when photo Scale = 1.

photoView.setOnMatrixChangeListener(new PhotoViewAttacher.OnMatrixChangedListener() {
  @Override
  public void onMatrixChanged(RectF rect) {
    photoView.setAllowParentInterceptOnEdge(photoView.getScale() == 1);
  }
});


问:
Cant use a return value from another function/python file
I am new to python-ish and trying to user the value held in the server variable that is returned at the bottom of select_target_server_type in another program. The first set of code is my menu.py and its just an input/decision tree.

My second code is rest_engine.py which calls menu.start_program() and that works great but when I want to retrieve the value of a function in one of the menu functions I cant get it to work it seems.

```<code>def start_program():
    select_target_server_type()

def select_target_server_type():
    # SUPPORTED SERVERS FOR API CALLS
    # DISPLAYS A LIST TO USER TO CHOOSE FROM

    print("\nWelcome!\nThese are the supported systems, please select a value by entering the corresponding "
          "numbered value\n")

    while True:
        try:
            print("1. APIC-EM")
            print("2. ISE")
            print("3. CSR")
            print("4. Quit")
            server = int(input("\nPlease select a SYSTEM TYPE to continue:   "))

            if 0 >= server or server >= 5:
                print("\n***Incorrect Selection***\n\n")
                pass
            else:
                break

        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)

    while True:
        try:
            if server == 1:
                print("\nYou have selected APIC-EM \n")
                api_top_menu()
            elif server == 2:
                print("\nYou have selected ISE \n")
                api_top_menu()
            elif server == 3:
                print("\nYou have selected CSR \n")
                api_top_menu()
            elif server == 4:
                print("\nQUITTING APPLICATION\n")
                sys.exit(0)
        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)
        return server
</code>```

Second program rest_engine.py (calls the first)

```<code>#!/usr/bin/python3

import json
import requests
import menu

menu.start_program()

name = menu.select_target_server_type()
print(name)
</code>```

Functioning Code Output:

```<code>> /usr/bin/python3.5 /home/danield/PycharmProjects/YODA/rest_engine.py
>
> Welcome! These are the supported systems, please select a value by
> entering the corresponding numbered value
>
> 1. APIC-EM
> 2. ISE
> 3. CSR
> 4. Quit
>
> Please select a SYSTEM TYPE to continue:   1
>
> You have selected APIC-EM
>
> 1. GET
> 2. PUT
> 3. DELETE
> 4. quit Please select a function to continue:   1
>
> You chose to use GET
>
> 1. INVENTORY
> 2. NETWORK DISCOVERY
> 3. TBD
> 4. Quit Please select the FUNCTION category:   1
>
> You chose Inventory
>
>
>
> ***oops***
>
> Process finished with exit code 1
</code>```

答:
I think this is your problem:

Post all your code! We cannot see the code that displays the other lists (i.e. the function and FUNCTION) lists. How can we help with a partial problem? Update your post!

menu.start_program() is called, and in menu.py it calls select_target_server_type() within it. However, select_target_server_type() is set to return server, so it will return sever to the calling function start_program(). However, the start_program() function isn't coded to receive a return from its function call to select_target_server_type(). However, before it can even return server an error is being caught somewhere. But we cant see api_top_menu() so we can't help you there unless you update your post.

Try these changes:

rest_engine.py

```<code>#!/usr/bin/python3

import json
import requests
import menu

name = menu.start_program()

print (name)
</code>```

menu.py

```<code>def start_program():
    server = select_target_server_type()

def select_target_server_type():
    # SUPPORTED SERVERS FOR API CALLS
    # DISPLAYS A LIST TO USER TO CHOOSE FROM

    print("\nWelcome!\nThese are the supported systems, please select a value by entering the corresponding "
          "numbered value\n")

    while True:
        try:
            print("1. APIC-EM")
            print("2. ISE")
            print("3. CSR")
            print("4. Quit")
            server = int(input("\nPlease select a SYSTEM TYPE to continue:   "))

            if 0 >= server or server >= 5:
                print("\n***Incorrect Selection***\n\n")
                pass
            else:
                break

        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)

    while True:
        try:
            if server == 1:
                print("\nYou have selected APIC-EM \n")
                api_top_menu() # we need to see this code too!
            elif server == 2:
                print("\nYou have selected ISE \n")
                api_top_menu()
            elif server == 3:
                print("\nYou have selected CSR \n")
                api_top_menu()
            elif server == 4:
                print("\nQUITTING APPLICATION\n")
                sys.exit(0)
            return server # will end the infinite try here
        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)
</code>```

Body:
I am new to python-ish and trying to user the value held in the server variable that is returned at the bottom of select_target_server_type in another program. The first set of code is my menu.py and its just an input/decision tree.

My second code is rest_engine.py which calls menu.start_program() and that works great but when I want to retrieve the value of a function in one of the menu functions I cant get it to work it seems.

def start_program():
    select_target_server_type()

def select_target_server_type():
    # SUPPORTED SERVERS FOR API CALLS
    # DISPLAYS A LIST TO USER TO CHOOSE FROM

    print("\nWelcome!\nThese are the supported systems, please select a value by entering the corresponding "
          "numbered value\n")

    while True:
        try:
            print("1. APIC-EM")
            print("2. ISE")
            print("3. CSR")
            print("4. Quit")
            server = int(input("\nPlease select a SYSTEM TYPE to continue:   "))

            if 0 >= server or server >= 5:
                print("\n***Incorrect Selection***\n\n")
                pass
            else:
                break

        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)

    while True:
        try:
            if server == 1:
                print("\nYou have selected APIC-EM \n")
                api_top_menu()
            elif server == 2:
                print("\nYou have selected ISE \n")
                api_top_menu()
            elif server == 3:
                print("\nYou have selected CSR \n")
                api_top_menu()
            elif server == 4:
                print("\nQUITTING APPLICATION\n")
                sys.exit(0)
        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)
        return server

Second program rest_engine.py (calls the first)

#!/usr/bin/python3

import json
import requests
import menu

menu.start_program()

name = menu.select_target_server_type()
print(name)

Functioning Code Output:

> /usr/bin/python3.5 /home/danield/PycharmProjects/YODA/rest_engine.py
>
> Welcome! These are the supported systems, please select a value by
> entering the corresponding numbered value
>
> 1. APIC-EM
> 2. ISE
> 3. CSR
> 4. Quit
>
> Please select a SYSTEM TYPE to continue:   1
>
> You have selected APIC-EM
>
> 1. GET
> 2. PUT
> 3. DELETE
> 4. quit Please select a function to continue:   1
>
> You chose to use GET
>
> 1. INVENTORY
> 2. NETWORK DISCOVERY
> 3. TBD
> 4. Quit Please select the FUNCTION category:   1
>
> You chose Inventory
>
>
>
> ***oops***
>
> Process finished with exit code 1

Body:
I think this is your problem:

Post all your code! We cannot see the code that displays the other lists (i.e. the function and FUNCTION) lists. How can we help with a partial problem? Update your post!

menu.start_program() is called, and in menu.py it calls select_target_server_type() within it. However, select_target_server_type() is set to return server, so it will return sever to the calling function start_program(). However, the start_program() function isn't coded to receive a return from its function call to select_target_server_type(). However, before it can even return server an error is being caught somewhere. But we cant see api_top_menu() so we can't help you there unless you update your post.

Try these changes:

rest_engine.py

#!/usr/bin/python3

import json
import requests
import menu

name = menu.start_program()

print (name)

menu.py

def start_program():
    server = select_target_server_type()

def select_target_server_type():
    # SUPPORTED SERVERS FOR API CALLS
    # DISPLAYS A LIST TO USER TO CHOOSE FROM

    print("\nWelcome!\nThese are the supported systems, please select a value by entering the corresponding "
          "numbered value\n")

    while True:
        try:
            print("1. APIC-EM")
            print("2. ISE")
            print("3. CSR")
            print("4. Quit")
            server = int(input("\nPlease select a SYSTEM TYPE to continue:   "))

            if 0 >= server or server >= 5:
                print("\n***Incorrect Selection***\n\n")
                pass
            else:
                break

        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)

    while True:
        try:
            if server == 1:
                print("\nYou have selected APIC-EM \n")
                api_top_menu() # we need to see this code too!
            elif server == 2:
                print("\nYou have selected ISE \n")
                api_top_menu()
            elif server == 3:
                print("\nYou have selected CSR \n")
                api_top_menu()
            elif server == 4:
                print("\nQUITTING APPLICATION\n")
                sys.exit(0)
            return server # will end the infinite try here
        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)


答:
Set border-radius as a percentage.

```<code>div {
  position: fixed;
  width: 100px;
  height: 50px;
  background: rgba(0,0,0,.5);
  border-radius: 50%;
}
</code>```

Body:
Set border-radius as a percentage.

div {
  position: fixed;
  width: 100px;
  height: 50px;
  background: rgba(0,0,0,.5);
  border-radius: 50%;
}


问:
Convert time in seconds from the Epoch to day of the year?
I have a file filled with data, one column of which is seconds from the Epoch. For reference, an example value looks like this:

1498493536984926976

I need to convert it into a day of the year. What I have so far is this piece of code, which uses this reference to convert the date into a normal readable struct and then strftime to pull the day of the year from the struct:

```<code>time_t rawtime = stol(exploded_line[2]);
std::cout << rawtime << std::endl;
struct tm date;
date = *localtime( &rawtime );
char *buffer;
std::cout << 2 << std::endl;
strftime (buffer,sizeof(buffer),"%j",&date);
</code>```

However, this code SegFaults on the strftime line! I have no idea what is causing this. I have tried initializing buffer as

```<code>char buffer[80];
</code>```

and various other declarations but nothing seems to work. I've also tried ditching the buffer entirely and just using a std::string; that hasn't worked either.

Also, I am not partial to this method. If anyone else has a better method of getting the day of the year from an Epoch time, I will totally implement it.

Any help would be appreciated!

答:
And here it is using Howard Hinnant's free, open source date/time library:

```<code>#include "date.h"
#include <iostream>
#include <sstream>

int
main()
{
    using namespace std::chrono;
    using namespace date;
    std::istringstream file{"1498493536984926976"};
    std::int64_t i;
    file >> i;
    std::cout << format("%j\n", sys_time<nanoseconds>{nanoseconds{i}});
}
</code>```

Output:

```<code>177
</code>```

Notes:

You don't specify, but I assumed "seconds from the Epoch" meant UTC.  Once you start calling things like localtime, you are bringing your computer's local time zone offset into the computation.  My code above keeps everything in UTC.

Once the int is parsed from the file, the formatting is a one-liner, with no explicit conversion factors.

If you need the day of the year as an int, instead of streamed out, that is also easily accomplished:

>

```<code>#include "date.h"
#include <iostream>
#include <sstream>

int
main()
{
    using namespace std::chrono;
    using namespace date;
    std::istringstream file{"1498493536984926976"};
    std::int64_t i;
    file >> i;
    auto sd = floor<days>(sys_time<nanoseconds>{nanoseconds{i}});
    auto y = year_month_day{sd}.year();
    int doy = (sd - sys_days{y/jan/1}).count() + 1;
    std::cout << doy << '\n';
}
</code>```

In this latter case, the nanoseconds-precision time_point is truncated to a time_point with a precision of days.  That truncated time_point is then converted to a year_month_day object for the purpose of extracting the current year (using UTC).  And finally the first day of that year is subtracted from the truncated time_point, resulting in a chrono::duration with a precision of days.  1 is added to the result because %j specifies that Jan 1 is day 1.

The output is again:

```<code>177
</code>```

Body:
I have a file filled with data, one column of which is seconds from the Epoch. For reference, an example value looks like this:

1498493536984926976

I need to convert it into a day of the year. What I have so far is this piece of code, which uses this reference to convert the date into a normal readable struct and then strftime to pull the day of the year from the struct:

time_t rawtime = stol(exploded_line[2]);
std::cout << rawtime << std::endl;
struct tm date;
date = *localtime( &rawtime );
char *buffer;
std::cout << 2 << std::endl;
strftime (buffer,sizeof(buffer),"%j",&date);

However, this code SegFaults on the strftime line! I have no idea what is causing this. I have tried initializing buffer as

char buffer[80];

and various other declarations but nothing seems to work. I've also tried ditching the buffer entirely and just using a std::string; that hasn't worked either.

Also, I am not partial to this method. If anyone else has a better method of getting the day of the year from an Epoch time, I will totally implement it.

Any help would be appreciated!

Body:
And here it is using Howard Hinnant's free, open source date/time library:

#include "date.h"
#include <iostream>
#include <sstream>

int
main()
{
    using namespace std::chrono;
    using namespace date;
    std::istringstream file{"1498493536984926976"};
    std::int64_t i;
    file >> i;
    std::cout << format("%j\n", sys_time<nanoseconds>{nanoseconds{i}});
}

Output:

177

Notes:

You don't specify, but I assumed "seconds from the Epoch" meant UTC.  Once you start calling things like localtime, you are bringing your computer's local time zone offset into the computation.  My code above keeps everything in UTC.

Once the int is parsed from the file, the formatting is a one-liner, with no explicit conversion factors.

If you need the day of the year as an int, instead of streamed out, that is also easily accomplished:

>

#include "date.h"
#include <iostream>
#include <sstream>

int
main()
{
    using namespace std::chrono;
    using namespace date;
    std::istringstream file{"1498493536984926976"};
    std::int64_t i;
    file >> i;
    auto sd = floor<days>(sys_time<nanoseconds>{nanoseconds{i}});
    auto y = year_month_day{sd}.year();
    int doy = (sd - sys_days{y/jan/1}).count() + 1;
    std::cout << doy << '\n';
}

In this latter case, the nanoseconds-precision time_point is truncated to a time_point with a precision of days.  That truncated time_point is then converted to a year_month_day object for the purpose of extracting the current year (using UTC).  And finally the first day of that year is subtracted from the truncated time_point, resulting in a chrono::duration with a precision of days.  1 is added to the result because %j specifies that Jan 1 is day 1.

The output is again:

177


问:
Using Excel's FIND Function to search for wildcard characters
I would like to extract a substring to the right of a ** by using the FIND function. However, when I use the following formula,

=RIGHT(A2, FIND("~**", A2))

I receive the #VALUE error message. My understanding is that to search for wildcard characters in Excel strings, you must precede the wild-card with a ~ so I don't get why this formula does not work. Please see the attached image for the string and substring (intended) fields.String and Substring fields

答:
Use the following:

```<code>=TRIM(RIGHT(A2,LEN(A2)- FIND("**", A2)-1))
</code>```

You have to subtract Find() from the length of the string -1

Find will give the position of the first *

Right will count from end of string

It means you have to count tne number of character from the last to before *

Body:
Use the following:

=TRIM(RIGHT(A2,LEN(A2)- FIND("**", A2)-1))

You have to subtract Find() from the length of the string -1

Find will give the position of the first *

Right will count from end of string

It means you have to count tne number of character from the last to before *


问:
Basic Flow Control in JavaScript
Could you, please, explain to me, how to write really basic flow control in JavaScript? Thank you.</p>

```<code>flow([

  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback();  }

], function() {

  alert("Done.");

});
</code>```

答:
I recommend reading about continuation-passing style.  It seems your goal is, given an array of functions which take a continuation argument, chain them together such that the continuation proceeds to the next function in the array.

Here is an implementation of such a function:

```<code>function flow(funcArr, funcDone) {
    function proceed(i) {
        if (i < funcArr.length) {
            return function() {
                funcArr[i](proceed(i+1));
            }
        } else {
            return funcDone;
        }
    }

    proceed(0)();
}
</code>```

Edit: Anon.'s answer is shorter and simpler.

Here's how it works: proceed(i) returns a callback which calls the ith function (or, funcDone, if none are left in the array).  Because proceed(i) returns a callback rather than doing it, we can use proceed(i+1) as the contiunation function.

Sample usage:

```<code>flow([

    function(cb) { print("Thing one");   cb(); },
    function(cb) { print("Thing two");   cb(); },
    function(cb) { print("Thing three"); cb(); },
    function(cb) { print("Thing four");  cb(); },

], function() {

    print("Done.");

});
</code>```

Now try removing one of the cb(); calls.  It will break the chain, which is probably exactly what you want.  Another cool thing is, you can take cb, shove it in a global variable, and call it later on to resume the flow.

Bear in mind there is a drawback to this approach: many (if not all) JavaScript interpreters don't optimize tail recursion.  If the funcArr is too long, you may get a stack overflow.  This is a cross borne by any use of continuation-passing style in JavaScript.

Title: Basic Flow Control in JavaScript

Body:
Could you, please, explain to me, how to write really basic flow control in JavaScript? Thank you.

flow([

  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback();  }

], function() {

  alert("Done.");

});

Body:
I recommend reading about continuation-passing style.  It seems your goal is, given an array of functions which take a continuation argument, chain them together such that the continuation proceeds to the next function in the array.

Here is an implementation of such a function:

function flow(funcArr, funcDone) {
    function proceed(i) {
        if (i < funcArr.length) {
            return function() {
                funcArr[i](proceed(i+1));
            }
        } else {
            return funcDone;
        }
    }

    proceed(0)();
}

Edit: Anon.'s answer is shorter and simpler.

Here's how it works: proceed(i) returns a callback which calls the ith function (or, funcDone, if none are left in the array).  Because proceed(i) returns a callback rather than doing it, we can use proceed(i+1) as the contiunation function.

Sample usage:

flow([

    function(cb) { print("Thing one");   cb(); },
    function(cb) { print("Thing two");   cb(); },
    function(cb) { print("Thing three"); cb(); },
    function(cb) { print("Thing four");  cb(); },

], function() {

    print("Done.");

});

Now try removing one of the cb(); calls.  It will break the chain, which is probably exactly what you want.  Another cool thing is, you can take cb, shove it in a global variable, and call it later on to resume the flow.

Bear in mind there is a drawback to this approach: many (if not all) JavaScript interpreters don't optimize tail recursion.  If the funcArr is too long, you may get a stack overflow.  This is a cross borne by any use of continuation-passing style in JavaScript.


问:
Amazon Kinesis dynamically stream resize
I am working on Amazon Kinesis Api and Kinesis Client library, I have created one producer to put data into stream and have multiple consumer applications to read data from that stream.

I have scenario to increase and decrease size of stream dynamically as per input stream size and output stream size and also using count of Consumer application.

I found some useful source to count number of shard from amazon website but don't get how to calculate . Source URL is :
http://docs.aws.amazon.com/kinesis/latest/dev/how-do-i-size-a-stream.html

Need some understanding on this.

Thanks

答:
I have created npm module which helps in auto scaling kinesis stream.

You can find detailed information at Amazon Kinesis Scaling

This is npm module which scale amazon kinesis as per current traffic needs. This module continuously monitor traffic in kinesis stream and split and merge shards as needed.
  E.g. if your application needs to handle 5000 req/sec then you need to have 5 shards. Since traffic on your application can varies a lot so does number of shards.
  If your application needs to handle 20000 req/sec at peak time then you need to have 20 shards but when at other time you may required only 5 shards.


问:
Cannot Get Function to Execute Properly
I'm trying to test some code I wrote out but I can't get the function "jungleSoundOff" to actually log what I'm asking it to. I've tried moving it from the very bottom to just under the prompt but it still does not log anything from the other animal functions I created. Am I going about this the wrong way? Or am I just missing something very basic?

    var soundOff = prompt("Would you like to perform a jungle sound off?");
  if(soundOff === "yes" || soundOff === "Yes"){
      jungleSoundOff();
  }else if(soundOff === "no" || soundOff === "No"){
    console.log("Maybe another time.");
  }else{
    console.log("I don't understand your response.");
}

function tigerActivity(){
  var energy = 0;
  tigerFood = ["meat", "bugs", "fish"];
  tigerEat = Math.floor(Math.random(tigerFood) + energy + 5);
  tigerSleep = energy + 5;
  var tigerSound = "roar";

function monkeyActivity(){
  var energy = 0;
  monkeyFood = ["meat", "bugs", "grain", "fish"];
  monkeyPlay = energy - 8;
  monkeyEat = Math.floor(Math.random(monkeyFood) + energy + 2);
  var monkeySound = "oooo oooo";

function snakeActivity(){
  var energy = 0;
  snakeFood = ["meat", "bugs", "grain", "fish"];
  snakeEat = Math.floor(Math.random(snakeFood) + energy + 5);
  var snakeSound = "hiss";

 function jungleSoundOff(){
  console.log(tigerSound, energy);
  console.log(monkeySound, energy);
  console.log(snakeSound, energy);
 }
}
}
}```

What the program should do:

energy levels:
-3 for making sound
+5 for eating food
+10 for sleeping

jungle can sound off, animals make sound and report energy level.

tigers get +5 energy for sleeping.
monkeys get +2 energy for eating and -4 energy for making a sound

only monkeys can play when they do they say "oooo ooooo ooooo" and get -8 energy, if they don't have enough energy they say "Monkeys is too tired."

tigers can't eat grain because they have sensitive stomachs.

jungle can have each animal perform a random activity of the ones possible for that animal.

答:
I tried to change your code step by step until it did what you described. Unfortunately, I ended up with something far away. I hope you can get something out of my approach to the problem. I decided to not implement the Tiger so you could implement it yourself.

// We define how each animal by default would behave here and then we change specific behaviour later on.
class Animal {
  constructor() {
    this.energy = 0;
    this.sound = "Default sound";
    // Declare all actvities that animals are able to do
    // bind this on the function so we can call them
    this.activities = [
      // bind the food bugs so they aren't eating air
      this.eat.bind(this, "bugs"),
      this.makeSound.bind(this),
      this.sleep.bind(this)
    ];
  }

  eat(food) {
    // Eating increases energy by 5
    this.energy += 5;
    console.log("Eating", food)
  }

  makeSound() {
    // Make sound decreases energy by 3
    this.energy -= 3;
    console.log(this.sound, "and my energy is", this.energy)
  }
  sleep() {
    // Sleeping increases energy by 10
    this.energy += 10;
    console.log("Sleep")
  }

  doRandomActivity(){
    // We generate a random number between the number of activites
    var actvityIndex = Math.floor(Math.random() * this.activities.length);
    // get the random activity
    var activity = this.activities[actvityIndex];
    // call the activity
    activity();
  }
}

// We extend from the general animal so we can do all of the basic animal things
class Monkey extends Animal{
  constructor() {
    super();
    this.sound = "oooo oooo";
    // add the play activity to actvities, so it can done by a random action
    this.activities.push(this.play.bind(this));
  }

  eat(food) {
    // Since monkeys gain different amount of energy
    this.energy += 2;
    console.log("Eating", food)
  }

  makeSound() {
    // Since monkeys make sounds differently than other animals we override the function
    this.energy -= 4;
    console.log(this.sound, "and my energy is", this.energy)
  }

  play() {
    // Added the new play ability for the monkey
    if (this.energy >= 8) {
      console.log("oooo ooooo ooooo")
      this.energy -= 8;
    } else {
      console.log("Monkeys is too tired");
    }
  }

}

// Snake extends animal so it can do all the animal things
// since the only special thing about the snake we only change its sound
class Snake extends Animal{
  constructor(){
    super();
    this.sound = "hiss";
  }
}

class Jungle {
  constructor() {
    // initialize animals array that contains all animals in the jungle
    this.animals = [];
  }

  addAnimal(animal){
    // add an animal
    this.animals.push(animal);
  }

  soundOff(){
    for(var i = 0; i < this.animals.length; i++) {
      // go through all animals in the jungle and makeSound
      this.animals[i].makeSound();
    }
  }
}

// create a the jungle jungle
var jungle = new Jungle();

// add our animals to the jungle
jungle.addAnimal(new Snake());
jungle.addAnimal(new Monkey());

var soundOff = prompt("Would you like to perform a jungle sound off?").toLowerCase();
  if(soundOff === "yes"){
    jungle.soundOff();
  }else if(soundOff === "no"){
    console.log("Maybe another time.");
  }else{
    console.log("I don't understand your response.");
}```

Title: Cannot Get Function to Execute Properly

Body:
I'm trying to test some code I wrote out but I can't get the function "jungleSoundOff" to actually log what I'm asking it to. I've tried moving it from the very bottom to just under the prompt but it still does not log anything from the other animal functions I created. Am I going about this the wrong way? Or am I just missing something very basic?

    var soundOff = prompt("Would you like to perform a jungle sound off?");
  if(soundOff === "yes" || soundOff === "Yes"){
      jungleSoundOff();
  }else if(soundOff === "no" || soundOff === "No"){
    console.log("Maybe another time.");
  }else{
    console.log("I don't understand your response.");
}

function tigerActivity(){
  var energy = 0;
  tigerFood = ["meat", "bugs", "fish"];
  tigerEat = Math.floor(Math.random(tigerFood) + energy + 5);
  tigerSleep = energy + 5;
  var tigerSound = "roar";

function monkeyActivity(){
  var energy = 0;
  monkeyFood = ["meat", "bugs", "grain", "fish"];
  monkeyPlay = energy - 8;
  monkeyEat = Math.floor(Math.random(monkeyFood) + energy + 2);
  var monkeySound = "oooo oooo";

function snakeActivity(){
  var energy = 0;
  snakeFood = ["meat", "bugs", "grain", "fish"];
  snakeEat = Math.floor(Math.random(snakeFood) + energy + 5);
  var snakeSound = "hiss";

 function jungleSoundOff(){
  console.log(tigerSound, energy);
  console.log(monkeySound, energy);
  console.log(snakeSound, energy);
 }
}
}
}

What the program should do:

energy levels:
-3 for making sound
+5 for eating food
+10 for sleeping

jungle can sound off, animals make sound and report energy level.

tigers get +5 energy for sleeping.
monkeys get +2 energy for eating and -4 energy for making a sound

only monkeys can play when they do they say "oooo ooooo ooooo" and get -8 energy, if they don't have enough energy they say "Monkeys is too tired."

tigers can't eat grain because they have sensitive stomachs.

jungle can have each animal perform a random activity of the ones possible for that animal.


问:
Replace multiple strings in PHP
I want to replace multiple words in my docx-file. I used the words from the input-elements and I pass them through the 'POST'-method. I already replaced the '$bedrijfsnaam' but I want to add more str replacements. I created '$newContents2' but as I thought, it didn't work. How can I solve this? Do I have to add another 'oldContents' like 'oldContents2'? </p>

```<code>$bedrijfsnaam = $_POST['bedrijfsnaam'];
$offertenummer = $_POST['offertenummer'];
$naam = $_POST['naam'];

$zip = new ZipArchive;
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$wordDoc = "Document.docx";
$newFile = $offertenummer . ".docx";

copy("Document.docx", $newFile);

if ($zip->open($newFile) === TRUE) {

    $oldContents = $zip->getFromName($fileToModify);

    $newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents);

    $newContents2 = str_replace('$naam', $naam, $oldContents);

    $zip->deleteName($fileToModify);

    $zip->addFromString($fileToModify, $newContents);

    $return =$zip->close();
    If ($return==TRUE){
        echo "Success!";
    }
} else {
    echo 'failed';
}

$newFilePath = 'offerte/' . $newFile;

$fileMoved = rename($newFile, $newFilePath);
</code>```

答:
You're going to want to keep editing the same content.

```<code>$newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents);
</code>```

The result of the first replacement is in $newContents, so if you want to build upon that, you need to replace the second string in $newContents and store the result in $newContents, which now contains the result of both string replacements.

```<code>$newContents = str_replace('$naam', $naam, $newContents);
</code>```

Edit: Better yet, you can just use arrays and do it all in one line

```<code>$newContent = str_replace(
    ['$bedrijfsnaam', '$naam'],
    [ $bedrijfsnaam, $naam],
    $oldContents
);
</code>```

Title: Replace multiple strings in PHP

Body:
I want to replace multiple words in my docx-file. I used the words from the input-elements and I pass them through the 'POST'-method. I already replaced the '$bedrijfsnaam' but I want to add more str replacements. I created '$newContents2' but as I thought, it didn't work. How can I solve this? Do I have to add another 'oldContents' like 'oldContents2'?

$bedrijfsnaam = $_POST['bedrijfsnaam'];
$offertenummer = $_POST['offertenummer'];
$naam = $_POST['naam'];

$zip = new ZipArchive;
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$wordDoc = "Document.docx";
$newFile = $offertenummer . ".docx";

copy("Document.docx", $newFile);

if ($zip->open($newFile) === TRUE) {

    $oldContents = $zip->getFromName($fileToModify);

    $newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents);

    $newContents2 = str_replace('$naam', $naam, $oldContents);

    $zip->deleteName($fileToModify);

    $zip->addFromString($fileToModify, $newContents);

    $return =$zip->close();
    If ($return==TRUE){
        echo "Success!";
    }
} else {
    echo 'failed';
}

$newFilePath = 'offerte/' . $newFile;

$fileMoved = rename($newFile, $newFilePath);

Body:
You're going to want to keep editing the same content.

$newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents);

The result of the first replacement is in $newContents, so if you want to build upon that, you need to replace the second string in $newContents and store the result in $newContents, which now contains the result of both string replacements.

$newContents = str_replace('$naam', $naam, $newContents);

Edit: Better yet, you can just use arrays and do it all in one line

$newContent = str_replace(
    ['$bedrijfsnaam', '$naam'],
    [ $bedrijfsnaam, $naam],
    $oldContents
);


问:
adding css and js file in view for application based on play framework
Adding reverse routing in view file is causing error. Following is the snippet:

```<code>@main(title = "index")  {
<head>
    <link rel="stylesheet" type="text/css" href='@routes.Assets.at("/Content/Site.css")' />
    <script  type="text/javascript" src='@routes.Assets.at("Scripts/bootstrap.js")'></script>

</head>
<body>
</body>
}
</code>```

I have added the css and js file in public folder

```<code>  [error] C:\myproject\app\views\index.scala.html:5: value at is not a member of controllers.ReverseAssets
  [error]     <link rel="stylesheet" type="text/css" href='@routes.Assets.at("/Content/Site.css")' />
  [error]                                                                     ^
  [error] C:\myproject\app\views\index1.scala.html:6: value at is not a member of controllers.ReverseAssets
  [error]     <script  type="text/javascript" src='@routes.Assets.at("Scripts/bootstrap.js")'></script>
</code>```

Any help is appreciated.

答:
I have to use following syntax for getting rid of error</p>

```<code> <link rel="stylesheet" type="text/css" href='@routes.Assets.versioned("stylesheets/Content/bootstrap.css")'
</code>```

Body:
Adding reverse routing in view file is causing error. Following is the snippet:

@main(title = "index")  {

    <link rel="stylesheet" type="text/css" href='@routes.Assets.at("/Content/Site.css")' />

}

I have added the css and js file in public folder

  [error] C:\myproject\app\views\index.scala.html:5: value at is not a member of controllers.ReverseAssets
  [error]     <link rel="stylesheet" type="text/css" href='@routes.Assets.at("/Content/Site.css")' />
  [error]                                                                     ^
  [error] C:\myproject\app\views\index1.scala.html:6: value at is not a member of controllers.ReverseAssets
  [error]

Any help is appreciated.

Body:
I have to use following syntax for getting rid of error

 <link rel="stylesheet" type="text/css" href='@routes.Assets.versioned("stylesheets/Content/bootstrap.css")'


问:
Jenkins not accessible with http://<hostname>:8080 in Windows server 2012
I have installed Jenkins in Windows server 2012 64-bit machine and want to make it available in internal network.

I have added --httpListenAddress to 0.0.0.0 and restarted Jenkins and tried to access it with http://hostname:8080 but no page shows up(though It showing Jenkins icon in URL bar). However http://localhost:8080 works fine.

Further I checked the firewall inbound rule for the Jenkins but seems it has no issues.

I tried to catch the listening ports with "netstat -aon | find /i "8080" and found <host ip address>:8080 FIN_WAIT_2 which sign towards that the request is stuck(May be I am wrong).

I am clueless what exactly is blocking to use hostname with jenkins. Please share your solution if you already fixed this issue.

答:
On the server open a new command prompt and type
    ipconfig

You should get a list of ips. Open a browser and type each up followed by 8080 for e.g.
    http://202.123.2.1:8080

If Jenkins opens up, from another computer ping the ip and see if you can get a ping reply
    ping 202.123.2.1

If you get a ping reply, you can access jenkins from any pc on the network by typing in the ip and port number.

Now to get to the hostname,you need to edit your host file

c:\Windows\System32\Drivers\etc\hosts

Type in the ip followed by the hostname
    202.123.2.1 jenkins

If you can't get through, you need to open port 8080. See https://www.vultr.com/docs/how-to-open-a-port-in-windows-firewall-on-windows-server-2012


问:
Entity Framework Migrations - Enable AutoMigrations along with added migration
I'm utilizing Entity Framework 4.3 Migrations in my project.  I would like to use Automatic migrations so that when I make modifications to my domain objects and my context class, my database automatically updates when I run the project.  I have this working so far.

I would also like to use some Added Migrations in addition to the automatic migrations, and I would like the application to automatically jump to the latest version (based on my added migrations) when I run the application.

In order to do this I have placed this in the global.asax file...

```<code>Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Core.Migrations.Configuration>());
</code>```

Now this works, but when I do this it no longer automatically updates the database based on my domain objects.

I would like to be able to completely delete the database and then run the application and have all the automatic migrations run and then have my explicit migrations run and bring the database up to the latest version.

I know I've had this working in a previous project, but I'm not sure what I'm doing wrong in this instance.

Thanks

答:
You just need to do</p>

```<code>    private static void InitializeDataStore()
    {
        System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<GalleryDb, GalleryDbMigrationConfiguration>());
        System.Data.Entity.Database.Initialize(false);
    }
</code>```

Body:
I'm utilizing Entity Framework 4.3 Migrations in my project.  I would like to use Automatic migrations so that when I make modifications to my domain objects and my context class, my database automatically updates when I run the project.  I have this working so far.

I would also like to use some Added Migrations in addition to the automatic migrations, and I would like the application to automatically jump to the latest version (based on my added migrations) when I run the application.

In order to do this I have placed this in the global.asax file...

Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Core.Migrations.Configuration>());

Now this works, but when I do this it no longer automatically updates the database based on my domain objects.

I would like to be able to completely delete the database and then run the application and have all the automatic migrations run and then have my explicit migrations run and bring the database up to the latest version.

I know I've had this working in a previous project, but I'm not sure what I'm doing wrong in this instance.

Thanks

Body:
You just need to do

    private static void InitializeDataStore()
    {
        System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<GalleryDb, GalleryDbMigrationConfiguration>());
        System.Data.Entity.Database.Initialize(false);
    }


问:
Angular 2 - Getting length of Pipe in calling component
I have a simple custom pipe in Angular2 to filter an array based on type ID and year arrays, I define it as such:

```<code>@Pipe({name: 'highlightedWorksFilter', pure: false})
export class HighlightedWorksFilterPipe implements PipeTransform {
transform(works: IHighlightedWork[], activityTypeIds: any[], activityYears: any[]){
    if (works && works.length) {
        return works.filter(work => {
            if(activityTypeIds.findIndex(i => i.id === work.activityTypeId && i.checked) === -1) {
                return false;
            }
            if (activityYears.findIndex(i => i.year === work.activityYear && i.checked) === -1) {
                return false;
            }
            return true;
        });
    }
    else {
        return works;
    }
}
}
</code>```

Here's where it's used from a calling component:

```<code><div>FILTERED COUNT / {{highlightedWorks.length}}</div>
<div *ngFor="let work of highlightedWorks | highlightedWorksFilter: myActivityTypeIds:myActivityYears">
 {{work.Title}}
</div>
</code>```

The filter works perfectly and gets updated based on the 2 checkbox list arrays for type and year (using arrays to filter, hence the the "pure: false" on the pipe).

My question is, how can I get that FILTERED COUNT outside of the ngFor to display the pipe's filtered results count?  I have the highlightedWorks.length as the total results count, but want to also display how many results I currently have filtered with the pipes.

答:
I'd suggest performing the filtering in the component code instead of in a pipe for the reasons stated here: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

Then you'd have access to the filtered list as a property of the component class so can more easily get its length.

Here is an example

```<code>import { Component, OnInit } from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {

    _listFilter: string;
    get listFilter(): string {
        return this._listFilter;
    }
    set listFilter(value: string) {
        this._listFilter = value;
        this.filteredProducts = this.listFilter ? this.performFilter(this.listFilter) : this.products;
    }

    filteredProducts: IProduct[];
    products: IProduct[] = [];

    constructor(private _productService: ProductService) {

    }

    performFilter(filterBy: string): IProduct[] {
        filterBy = filterBy.toLocaleLowerCase();
        return this.products.filter((product: IProduct) =>
              product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => {
                    this.products = products;
                    this.filteredProducts = this.products;
                },
                    error => this.errorMessage = <any>error);
    }
}
</code>```

Body:
I have a simple custom pipe in Angular2 to filter an array based on type ID and year arrays, I define it as such:

@Pipe({name: 'highlightedWorksFilter', pure: false})
export class HighlightedWorksFilterPipe implements PipeTransform {
transform(works: IHighlightedWork[], activityTypeIds: any[], activityYears: any[]){
    if (works && works.length) {
        return works.filter(work => {
            if(activityTypeIds.findIndex(i => i.id === work.activityTypeId && i.checked) === -1) {
                return false;
            }
            if (activityYears.findIndex(i => i.year === work.activityYear && i.checked) === -1) {
                return false;
            }
            return true;
        });
    }
    else {
        return works;
    }
}
}

Here's where it's used from a calling component:

FILTERED COUNT / {{highlightedWorks.length}}

 {{work.Title}}

The filter works perfectly and gets updated based on the 2 checkbox list arrays for type and year (using arrays to filter, hence the the "pure: false" on the pipe).

My question is, how can I get that FILTERED COUNT outside of the ngFor to display the pipe's filtered results count?  I have the highlightedWorks.length as the total results count, but want to also display how many results I currently have filtered with the pipes.

Body:
I'd suggest performing the filtering in the component code instead of in a pipe for the reasons stated here: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

Then you'd have access to the filtered list as a property of the component class so can more easily get its length.

Here is an example

import { Component, OnInit } from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {

    _listFilter: string;
    get listFilter(): string {
        return this._listFilter;
    }
    set listFilter(value: string) {
        this._listFilter = value;
        this.filteredProducts = this.listFilter ? this.performFilter(this.listFilter) : this.products;
    }

    filteredProducts: IProduct[];
    products: IProduct[] = [];

    constructor(private _productService: ProductService) {

    }

    performFilter(filterBy: string): IProduct[] {
        filterBy = filterBy.toLocaleLowerCase();
        return this.products.filter((product: IProduct) =>
              product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => {
                    this.products = products;
                    this.filteredProducts = this.products;
                },
                    error => this.errorMessage = <any>error);
    }
}


问:
Issue storing AVRO Kafka streams to File System
I want to store my AVRO kafka streams to file system using my spark streaming API with the following scala code in delimited format, but facing some challenges in achieving this

```<code>record.write.mode(SaveMode.Append).csv("/Users/Documents/kafka-poc/consumer-out/)
</code>```

Since, record(generic record) is not a DF or RDD, I am not sure how to proceed with this?

Code

```<code>       val messages = SparkUtilsScala.createCustomDirectKafkaStreamAvro(ssc, kafkaParams, zookeeper_host, kafkaOffsetZookeeperNode, topicsSet)
       val requestLines = messages.map(_._2)
       requestLines.foreachRDD((rdd, time: Time) => {
       rdd.foreachPartition { partitionOfRecords => {
       val recordInjection = SparkUtilsJava.getRecordInjection(topicsSet.last)
       for (avroLine <- partitionOfRecords) {
       val record = recordInjection.invert(avroLine).get
       println("Consumer output...."+record)
       println("Consumer output schema...."+record.getSchema)
       }}}}
</code>```

following is the output & schema

```<code>{"username": "Str 1-0", "tweet": "Str 2-0", "timestamp": 0}
{"type":"record","name":"twitter_schema","fields":[{"name":"username","type":"string"},{"name":"tweet","type":"string"},{"name":"timestamp","type":"int"}]}
</code>```

Thanks in advance and appreciate your help

答:
I found a solution for this. </p>

```<code>val jsonStrings: RDD[String] = sc.parallelize(Seq(record.toString()));
val result = sqlContext.read.json(jsonStrings).toDF();
result.write.mode("Append").csv("/Users/Documents/kafka-poc/consumer-out/");
</code>```

Body:
I want to store my AVRO kafka streams to file system using my spark streaming API with the following scala code in delimited format, but facing some challenges in achieving this

record.write.mode(SaveMode.Append).csv("/Users/Documents/kafka-poc/consumer-out/)

Since, record(generic record) is not a DF or RDD, I am not sure how to proceed with this?

Code

       val messages = SparkUtilsScala.createCustomDirectKafkaStreamAvro(ssc, kafkaParams, zookeeper_host, kafkaOffsetZookeeperNode, topicsSet)
       val requestLines = messages.map(_._2)
       requestLines.foreachRDD((rdd, time: Time) => {
       rdd.foreachPartition { partitionOfRecords => {
       val recordInjection = SparkUtilsJava.getRecordInjection(topicsSet.last)
       for (avroLine <- partitionOfRecords) {
       val record = recordInjection.invert(avroLine).get
       println("Consumer output...."+record)
       println("Consumer output schema...."+record.getSchema)
       }}}}

following is the output & schema

{"username": "Str 1-0", "tweet": "Str 2-0", "timestamp": 0}
{"type":"record","name":"twitter_schema","fields":[{"name":"username","type":"string"},{"name":"tweet","type":"string"},{"name":"timestamp","type":"int"}]}

Thanks in advance and appreciate your help

Body:
I found a solution for this.

val jsonStrings: RDD[String] = sc.parallelize(Seq(record.toString()));
val result = sqlContext.read.json(jsonStrings).toDF();
result.write.mode("Append").csv("/Users/Documents/kafka-poc/consumer-out/");


问:
Detect which position on tab layout
I want to know or someone to give me an idea to detect which position I am on a tab layout, i got a tab layout and i cant seem to figure out where i should do what i want, i tried doing it here at an extended FragmentPagerAdapter:

```<code>@Override
public CharSequence getPageTitle(int position) {
    // Generate title based on item position

    return tabTitles[position];
}
</code>```

Basically i check if im at position 1 and do what ever and then do something else but it doesnt work, only calls the code once and neva again
ANd here at an extended fragment

```<code> @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = null;

    switch (p) {
        case 1:
            view = RenderFactory.getClass("Page1", inflater, container).displayContent();
            break;
        case 2:
            view = RenderFactory.getClass("Page2", inflater, container).displayContent();
            break;
        case 3:

            view = RenderFactory.getClass("Page3", inflater, container).displayContent();
            break;

    }
    return view;
}
</code>```

here i just put the code within each case and the code doesnt get called more then once. Any ideas ??

答:
Try to with addOnTabSelectedListener. This event handler gives you the position of the chosen tab.

Example:

```<code>tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
</code>```

Title: Detect which position on tab layout

Body:
I want to know or someone to give me an idea to detect which position I am on a tab layout, i got a tab layout and i cant seem to figure out where i should do what i want, i tried doing it here at an extended FragmentPagerAdapter:

@Override
public CharSequence getPageTitle(int position) {
    // Generate title based on item position

    return tabTitles[position];
}

Basically i check if im at position 1 and do what ever and then do something else but it doesnt work, only calls the code once and neva again
ANd here at an extended fragment

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = null;

    switch (p) {
        case 1:
            view = RenderFactory.getClass("Page1", inflater, container).displayContent();
            break;
        case 2:
            view = RenderFactory.getClass("Page2", inflater, container).displayContent();
            break;
        case 3:

            view = RenderFactory.getClass("Page3", inflater, container).displayContent();
            break;

    }
    return view;
}

here i just put the code within each case and the code doesnt get called more then once. Any ideas ??

Body:
Try to with addOnTabSelectedListener. This event handler gives you the position of the chosen tab.

Example:

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


问:
How to implement "class versioning" (using different version of the same class)
Here is the problem : our main class (say : Contract) change every year. Some properties are added, other are removed. We don't know how it will look next year. It may change a lot or not at all.

On the other hand, we now (new requirement...) have to keep an historic of every contracts. Each time the user update a contract, the whole object must be stored in a backup (e.g. - serialized in a table).

Of course, we must be able to read it back... One option (brutal) is to have a new Contract class every year (Contract2008, Contract2009, ...).

But it would be very cumbersome (and ugly) since a lot of classes depend on Contract - in facts, we would have to create a bunch of new classes every year.

Ever have this kind of problem ? Any suggestion ?

Thanks in advance !

(We're using C# 2.0.)

ADDED : Thank for your answers. We're now asking ourself how we could use a dictionary / an XML file to implement versioning without breaking all the code. Dictionary seems very sexy in this context :o)

答:
First thing I can think off the to of my head. Implement a sort of "Capabilities" document. A list (or an XML document) detailing the contact version and what properties it contains.

Each function that operates on Contract should check if particular properties ("capabilities") are supported.

For example:

```<code>Contract2008 Capabilities
-----
has Name
has Stipulations
can DoMagic
-----
>
>     Contract2009 Capabilities
>     -----
>     has Name
>     has Stipulations
>     can DoMagic
>     -----
</code>```

The contract class would store the capabilities document and some generic getters setters.

```<code>Contract
  GetCapabilities()
  Set(field, value)
  Get(field, value)
</code>```

The set and get would check if the field is supported in the capabilities before setting or getting the value.

(This must be a pattern or something, anyone?)

OwnerDisplayName: Sylvain Rodrigue

LastEditorDisplayName: Sylvain Rodrigue

Body:
First thing I can think off the to of my head. Implement a sort of "Capabilities" document. A list (or an XML document) detailing the contact version and what properties it contains.

Each function that operates on Contract should check if particular properties ("capabilities") are supported.

For example:

Contract2008 Capabilities
-----
has Name
has Stipulations
can DoMagic
-----
>
>     Contract2009 Capabilities
>     -----
>     has Name
>     has Stipulations
>     can DoMagic
>     -----

The contract class would store the capabilities document and some generic getters setters.

Contract
  GetCapabilities()
  Set(field, value)
  Get(field, value)

The set and get would check if the field is supported in the capabilities before setting or getting the value.

(This must be a pattern or something, anyone?)

OwnerDisplayName: moogs

LastEditorDisplayName: moogs


问:
How to translate whole website by google transltion?
This is my code :

```<code><div id="wrap">
 ⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯
 ⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯
</div>

<script type="text/javascript">
  google.load("language", "1");
  google.setOnLoadCallback(submitChange);
  var wrap_text = '';
  function submitChange(){
   wrap_text = document.getElementById('wrap').innerHTML;
   google.language.translate(wrap_text, 'zh-CN', 'zh-TW', function(result) {
    var resultBody = document.getElementById('wrap');
    alert(result.translation);
    if (result.translation){
     resultBody.innerHTML = result.translation;
   }
    else {
    resultBody.innerHTML = wrap_text；

    }
   });
   return false;
  }

</script>
</code>```

it does not work, if I replace wrap_text to some words, it works.

who can help me, thanks!

答: I find a good solution http://translate.google.com/translate_tools?hl=en</p>

Body:
This is my code :

 ⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯
 ⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯

it does not work, if I replace wrap_text to some words, it works.

who can help me, thanks!


问:
python-sphinx automodule generates docs even for methods from third party modules
I used automodule to generate documentation from docstrings, like the following:

```<code>.. automodule:: cdbus.csdb.chemnavi.db.schema
    :members:
</code>```

But when using :members: it also generated documentation and example code for sqlalchemy, which is not in my module.  I just imported sqlalchemy to write my module.

Screenshot of documentation

And this documentation is repeated every time I use the members keyword. How can I remove those additional docs and examples from sqlalchemy?

答:
automodule has an option exclude-members:

```<code>.. automodule:: cdbus.csdb.chemnavi.db.schema
    :members:
    :exclude-members: this, that, other
</code>```

Body:
I used automodule to generate documentation from docstrings, like the following:

.. automodule:: cdbus.csdb.chemnavi.db.schema
    :members:

But when using :members: it also generated documentation and example code for sqlalchemy, which is not in my module.  I just imported sqlalchemy to write my module.

Screenshot of documentation

And this documentation is repeated every time I use the members keyword. How can I remove those additional docs and examples from sqlalchemy?

Body:
automodule has an option exclude-members:

.. automodule:: cdbus.csdb.chemnavi.db.schema
    :members:
    :exclude-members: this, that, other