问:
How to configure HTTPS on more than one port on JBoss Fuse 6.3
Im trying to enable HTTPS on more than one port in JBoss Fuse 6.3
How can i achieve this.

I have follow the below tutorial to enable HTTPS on 8443.
https://fusemiddleware.wordpress.com/2015/04/12/generate-self-signed-certificate-using-java-keytool/

Need to enable the HTTPS on 8443 and 9192 port on JBoss Fuse 6.3

Is there any other way to achieve this. I need to enable https on 8443 and also on 9192 port.

Im using Apache Camel, Apache CXF and JBoss Fuse 6.3

答:
I would say that's not possible to use OSGi managed(OSGi http service) ssl port, only one(by default 8443) is possible here. However if it's CXF endpoint you can use httpj:engine-factory[1] to configure an embedded jetty server with any SSL port you wanna use, though this is not recommended way in OSGi container, in OSGi you should always use OSGi http service IMO.

[1]http://cxf.apache.org/docs/jetty-configuration.html


来源: stackexchange

问:
changing bounds property of UIView doesn't affect its content
I am new to iPhone programming and I am trying to understand how frame and bounds properties work. In the Interface builder, I created UIView where I put UIImageView as a child.
I made UIImageView bigger than parent view. and set 'clip subview' property to true for parent UIView and to false for child UIImageView.

When I change frame.origin property of the child UIImageView programmatically. but when I change bounds.origin property of the parent UIView I see nothing. Probably I wrongly understand the purpose of bounds.

What should I do to get the behavior described in the iPhone Application programming guide:

You can change the bounds origin without changing the other two properties. When you do, the view displays the portion of the underlying image that you have identified. InFigure2-4 (page 56), the original bounds origin is set to(0.0,0.0). In Figure2-5, that origin is moved to (8.0,24.0).As a result, a different portion of the underlying image is displayed by the view. Because the frame rectangle did not change, however, the new content is displayed in the same location inside the parent view as before.

Thanks in advance.
Andrew

答:
First of all, make sure you have a proper reference to the image view before you try changing its bounds. Check that it is not nil.

Second, you may need to change the rectangle and then set it again in a separate statement, like this:

```<code>CGRect rect = imageView.bounds;
rect.origin = CGPointMake(whatever, whatever);
imageView.bounds = rect;
</code>```

Bounds might not even be what you want. I don't know where you got that quote, but it doesn't sound right. Try using the image view's frame to position it in its superview.

OwnerDisplayName: Andrew Tver

ContentLicense: CC BY-SA 3.0

Body:
First of all, make sure you have a proper reference to the image view before you try changing its bounds. Check that it is not nil.

Second, you may need to change the rectangle and then set it again in a separate statement, like this:

CGRect rect = imageView.bounds;
rect.origin = CGPointMake(whatever, whatever);
imageView.bounds = rect;

Bounds might not even be what you want. I don't know where you got that quote, but it doesn't sound right. Try using the image view's frame to position it in its superview.

OwnerDisplayName: jtbandes

ContentLicense: CC BY-SA 2.5


问:
How to read properties file in Unix script where key is in another user input variable
I have below property file in same directory.

cancellation.properties

Content:

```<code>TestData=My Name
</code>```

My unix script is abc.sh

Content:

```<code>#!/bin/ksh
. ./cancellation.properties

echo  "Please enter data to read"

read data

echo $data
</code>```

While running I give the value TestData.

I am getting output as "TestData".

But I want output as "My Name".  What changes needs to be done here because key will be entered by user.

答:
When you don't need to store the variables, and only want to display the value, you can do like this:</p>

```<code>read -p "Please enter data to read: " data
grep "^${data}=" ./cancellation.properties | cut -d"=" -f2-
</code>```

Body:
I have below property file in same directory.

cancellation.properties

Content:

TestData=My Name

My unix script is abc.sh

Content:

#!/bin/ksh
. ./cancellation.properties

echo  "Please enter data to read"

read data

echo $data

While running I give the value TestData.

I am getting output as "TestData".

But I want output as "My Name".  What changes needs to be done here because key will be entered by user.

Body:
When you don't need to store the variables, and only want to display the value, you can do like this:

read -p "Please enter data to read: " data
grep "^${data}=" ./cancellation.properties | cut -d"=" -f2-


问:
Why and how does this piece of Javascript Code print 6 five times on execution?
This is the piece of code,which on execution gives 6,five times in one second intervals. Can someone please explain this to me in detail? </p>

```<code>for (var i=1; i<=5; i++) {
    setTimeout( function timer(){
        console.log( i );
        }, i*1000 );
}
</code>```

答:
The variable i is part of the closure of the timer function.
When the timer function is executed,
it will print the value of i at that time.
By the time that happens, the loop has already completed,
and so the value of i is 6.
For all 5 executions of timer,
so you see 6 printed 5 times.
What else would you expect?

If you want to print a count from 1, 2, ..., 5 with timeouts in between,
then pass the current concrete value of i into the closure,
using an immediately evaluated function expression:

```<code>for (var i = 1; i <= 5; i++) {
  setTimeout(function (value) {
    return function timer() {
      console.log(value);
    }
  }(i), i*1000);
}
</code>```

Another equivalent variation:

```<code>for (var i = 1; i <= 5; i++) {
  (function () {
    var value = i;
    setTimeout(function timer() {
      console.log(value);
    }, i*1000);
  })()
}
</code>```

Notice in both examples that the variable value is defined in the closure of the inner function, and a different instance of value is created in every iteration of the for loop,
with the value of i at the time of the iteration.
This is the crucial difference from the code in the question.

Body:
This is the piece of code,which on execution gives 6,five times in one second intervals. Can someone please explain this to me in detail?

for (var i=1; i<=5; i++) {
    setTimeout( function timer(){
        console.log( i );
        }, i*1000 );
}

Body:
The variable i is part of the closure of the timer function.
When the timer function is executed,
it will print the value of i at that time.
By the time that happens, the loop has already completed,
and so the value of i is 6.
For all 5 executions of timer,
so you see 6 printed 5 times.
What else would you expect?

If you want to print a count from 1, 2, ..., 5 with timeouts in between,
then pass the current concrete value of i into the closure,
using an immediately evaluated function expression:

for (var i = 1; i <= 5; i++) {
  setTimeout(function (value) {
    return function timer() {
      console.log(value);
    }
  }(i), i*1000);
}

Another equivalent variation:

for (var i = 1; i <= 5; i++) {
  (function () {
    var value = i;
    setTimeout(function timer() {
      console.log(value);
    }, i*1000);
  })()
}

Notice in both examples that the variable value is defined in the closure of the inner function, and a different instance of value is created in every iteration of the for loop,
with the value of i at the time of the iteration.
This is the crucial difference from the code in the question.


问:
Trying to draw a line with Kivy and threading

I am making a Kivy application right now, and in one part of it, I am getting data as an array of floating point numbers and I want to draw a line in Kivy using the data.
The problem is, I want it to constantly run, so I used threading, but Kivy would not draw the line. here is a stripped down version of the code that illustrates the problem:

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line
from threading import Thread

class MyWidget(Widget):
   def Draw(self):
       with self.canvas:
           Line(points=[100, 200, 300, 400])
class MainApp(App):

    def build(self):
        return MyWidget()

Thread(target=MyWidget().Draw).start()
MainApp().run()
</code>```

I want this code to draw a line with points 100, 200, 300, 400.

but instead, the app opens and does nothing, help will be appreciated!

答:
I modified your example a bit.

Try start the thread in the init method instead. Because when you do MyWidget().Draw, you do that with a new MyWidget object, and not the one you returned in your build method. So that line will never be drawn. But the line in another widget which is not on the screen.

Try like this:

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line, InstructionGroup
from threading import Thread
from random import randint
import time

class MyWidget(Widget):

    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)

        self.ig = InstructionGroup()
        self.line = Line(points=[100, 200, 300, 400])
        self.ig.add(self.line)
        self.canvas.add(self.ig)

        Thread(target=self.draw).start()

    def draw(self):
        while True:
            self.line.points = [randint(0,400) for i in range(4)]
            time.sleep(0.5)

class MainApp(App):

    def build(self):
        return MyWidget()

MainApp().run()
</code>```

Body:
I am making a Kivy application right now, and in one part of it, I am getting data as an array of floating point numbers and I want to draw a line in Kivy using the data.
The problem is, I want it to constantly run, so I used threading, but Kivy would not draw the line. here is a stripped down version of the code that illustrates the problem:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line
from threading import Thread

class MyWidget(Widget):
   def Draw(self):
       with self.canvas:
           Line(points=[100, 200, 300, 400])
class MainApp(App):

    def build(self):
        return MyWidget()

Thread(target=MyWidget().Draw).start()
MainApp().run()

I want this code to draw a line with points 100, 200, 300, 400.

but instead, the app opens and does nothing, help will be appreciated!

Body:
I modified your example a bit.

Try start the thread in the init method instead. Because when you do MyWidget().Draw, you do that with a new MyWidget object, and not the one you returned in your build method. So that line will never be drawn. But the line in another widget which is not on the screen.

Try like this:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line, InstructionGroup
from threading import Thread
from random import randint
import time

class MyWidget(Widget):

    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)

        self.ig = InstructionGroup()
        self.line = Line(points=[100, 200, 300, 400])
        self.ig.add(self.line)
        self.canvas.add(self.ig)

        Thread(target=self.draw).start()

    def draw(self):
        while True:
            self.line.points = [randint(0,400) for i in range(4)]
            time.sleep(0.5)

class MainApp(App):

    def build(self):
        return MyWidget()

MainApp().run()


问:
Is there a way to retrieve an existing NSUrlSession/cancel its task?
I am creating an NSUrlSession for a background upload using a unique identifier.
Is there a way, say after closing and reopening the app, to retrieve that NSUrlSession and cancel the upload task in case it has not been processed yet?

I tried simply recreating the NSUrlSession using the same identifier to check whether it still contains the upload task, however it does not even allow me to create this session, throwing an exception like "A background URLSession with identifier ... already exists", which is unsurprising as documentation explicitly says that a session identifier must be unique.

I am trying to do this with Xamarin.Forms 2.3.4.270 in an iOS platform project.

答:
Turns out I was on the right track. The error message "A background URLSession with identifier ... already exists" actually seems to be more of a warning, but there is not actually an exception thrown (the exception I had did not actually come from duplicate session creation).

So, you can in fact reattach to an existing NSUrlSession and will find the contained tasks still present, even after restarting the app. Just create a new configuration with the same identifier, use that to create a new session, ignore the warning that's printed out, and go on from there.

I am not sure if this is recommended for production use, but it works fine for my needs.

```<code>private async Task EnqueueUploadInternal(string uploadId)
{
    NSUrlSessionConfiguration configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(uploadId);
    INSUrlSessionDelegate urlSessionDelegate = (...);
    NSUrlSession session = NSUrlSession.FromConfiguration(configuration, urlSessionDelegate, new NSOperationQueue());

    NSUrlSessionUploadTask uploadTask = await (...);
    uploadTask.Resume();
}

private async Task CancelUploadInternal(string uploadId)
{
    NSUrlSessionConfiguration configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(uploadId);
    NSUrlSession session = NSUrlSession.FromConfiguration(configuration); // this will print a warning

    NSUrlSessionTask[] tasks = await session.GetAllTasksAsync();
    foreach (NSUrlSessionTask task in tasks)
        task.Cancel();
}
</code>```

Body:
Turns out I was on the right track. The error message "A background URLSession with identifier ... already exists" actually seems to be more of a warning, but there is not actually an exception thrown (the exception I had did not actually come from duplicate session creation).

So, you can in fact reattach to an existing NSUrlSession and will find the contained tasks still present, even after restarting the app. Just create a new configuration with the same identifier, use that to create a new session, ignore the warning that's printed out, and go on from there.

I am not sure if this is recommended for production use, but it works fine for my needs.

private async Task EnqueueUploadInternal(string uploadId)
{
    NSUrlSessionConfiguration configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(uploadId);
    INSUrlSessionDelegate urlSessionDelegate = (...);
    NSUrlSession session = NSUrlSession.FromConfiguration(configuration, urlSessionDelegate, new NSOperationQueue());

    NSUrlSessionUploadTask uploadTask = await (...);
    uploadTask.Resume();
}

private async Task CancelUploadInternal(string uploadId)
{
    NSUrlSessionConfiguration configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(uploadId);
    NSUrlSession session = NSUrlSession.FromConfiguration(configuration); // this will print a warning

    NSUrlSessionTask[] tasks = await session.GetAllTasksAsync();
    foreach (NSUrlSessionTask task in tasks)
        task.Cancel();
}


问:
How to search a item from a list?
Could anyone tell me why this code cannot work, please? </p>

```<code>list=[5,9,2,5,13]
item=input("Please enter the search item.")
found=false
for search = 0 to list.length -1
if item==list[search]:
found= True
next search
if found==True:
print("The item is in the list.")
else:
    print("The item is not in the list.")
</code>```

答:
You should at least write in a better way, like:</p>

```<code>lst=[5,9,2,5,13]
item = int(input("Please enter the search item."))
found = False
for search in range(len(lst)):
    if item == (lst[search]):
        found = True
if found:
    print('{} is in the list'.format(item))
else:
    print('{} is not in the list'.format(item))
</code>```

Title: How to search a item from a list?

Body:
Could anyone tell me why this code cannot work, please?

list=[5,9,2,5,13]
item=input("Please enter the search item.")
found=false
for search = 0 to list.length -1
if item==list[search]:
found= True
next search
if found==True:
print("The item is in the list.")
else:
    print("The item is not in the list.")

Body:
You should at least write in a better way, like:

lst=[5,9,2,5,13]
item = int(input("Please enter the search item."))
found = False
for search in range(len(lst)):
    if item == (lst[search]):
        found = True
if found:
    print('{} is in the list'.format(item))
else:
    print('{} is not in the list'.format(item))


问:
Question about bounds/frame of custom class derived from UIView
I have a class derived from UIView, it represents a square area(280x280) over which objects will be drawn, but somehow only the upper portion(280x187) was drawn.

I checked the bounds and frame within the initWithCoder and drawRect of the custom view class, the results are:

initWithCoder-->bounds:(280x280); frame:(280x280)

drawRect------->bounds:(280x187); frame:(280x187)

What could possible happen between initWithCoder and drawRect methods that changed both the bounds and frame?

Thanks for the information.

答: Inside InterfaceBuilder, I turned off the autoresize of view and took out the springs and struts, then the view displayed properly.</p>


答:
I am not sure about the syntax and if that is indeed python. I recommend you look up  a tutorial first.

However, this is how you can search for an element in your list:

```<code>list=[5,9,2,5,13]
element = raw_input("Please enter the desired element")

if int(element) in list:  #note i've put int() because your list is made out of numbers rather than strings.
    print element + " is in the list"
else:
    print element + " is not in the list"
</code>```

Title: How to search a item from a list?

Body:
I am not sure about the syntax and if that is indeed python. I recommend you look up  a tutorial first.

However, this is how you can search for an element in your list:

list=[5,9,2,5,13]
element = raw_input("Please enter the desired element")

if int(element) in list:  #note i've put int() because your list is made out of numbers rather than strings.
    print element + " is in the list"
else:
    print element + " is not in the list"


问:
Undefined offset: 2 inserting two files in a single row
I'm getting trouble inserting multiple files using Array in PHP.</p>

```<code>$applications=$_FILES['applications']['name'];

for($i = 0; $i < count($applications); $i++)
{
    $tmp_name=$_FILES['applications']['tmp_name'][$i];
    move_uploaded_file($tmp_name, "ujuri_admin/uploads/applications/$applications[$i]");
}

$send_data="INSERT INTO table (application[],date_now) VALUES ('$applications[$i]', NOW())";
</code>```

答:
You have to run your query inside the for loop with the current correct value of $applications[$i]. Your code should look something like this:

```<code>$stmt = $db->prepare('INSERT INTO table (application, date_now) VALUES (?, NOW())');
for($i = 0; $i < count($applications); $i++)
{
    $tmp_name=$_FILES['applications']['tmp_name'][$i];
    move_uploaded_file($tmp_name, "ujuri_admin/uploads/applications/$applications[$i]");
    $stmt->execute(array($applications[$i]));
}
$stmt->close();
</code>```

(Assuming $db is a PDO instance)

Body:
I'm getting trouble inserting multiple files using Array in PHP.

$applications=$_FILES['applications']['name'];

for($i = 0; $i < count($applications); $i++)
{
    $tmp_name=$_FILES['applications']['tmp_name'][$i];
    move_uploaded_file($tmp_name, "ujuri_admin/uploads/applications/$applications[$i]");
}

$send_data="INSERT INTO table (application[],date_now) VALUES ('$applications[$i]', NOW())";

Body:
You have to run your query inside the for loop with the current correct value of $applications[$i]. Your code should look something like this:

$stmt = $db->prepare('INSERT INTO table (application, date_now) VALUES (?, NOW())');
for($i = 0; $i < count($applications); $i++)
{
    $tmp_name=$_FILES['applications']['tmp_name'][$i];
    move_uploaded_file($tmp_name, "ujuri_admin/uploads/applications/$applications[$i]");
    $stmt->execute(array($applications[$i]));
}
$stmt->close();

(Assuming $db is a PDO instance)


问:
Spider not following links - scrapy
I am trying to build a spider which follows through 3 pages before getting to the page it scrapes. I have tested the responses in the shell, however, together it doesn't seem to work and I am not sure why.

My code below:

```<code># -*- coding: utf-8 -*-
import scrapy

class CollegiateSpider(scrapy.Spider):
    name = 'Collegiate'
    allowed_domains = ['collegiate-ac.com/uk-student-accommodation']
    start_urls = ['http://collegiate-ac.com/uk-student-accommodation/']

    # Step 1 - Get the area links

    def parse(self, response):
        for city in response.xpath('//*[@id="top"]/div[1]/div/div[1]/div/ul/li/a/text').extract():
            yield scrapy.Request(response.urljoin("/" + city), callback = self.parse_area_page)

    # Step 2 - Get the block links

    def parse_area_page(self, response):
        for url in response.xpath('//div[3]/div/div/div/a/@href').extract():
            yield scrapy.Request(response.urljoin(url), callback=self.parse_unitpage)

    # Step 3 Get the room links

    def parse_unitpage(self, response):
        for url in response.xpath('//*[@id="subnav"]/div/div[2]/ul/li[5]/a/@href').extract():
            yield scrapy.Request(response.urljoin(final), callback=self.parse_final)

    # Step 4 - Scrape the data

    def parse_final(self, response):
        pass
</code>```

I have tried changing to Crawlspider as per this answer, but that didn't seem to help.

I am currently looking into how to debug spiders, however, struggling with that so thought it would be beneficial to get opinions on here as well.

答:
You forgot () in text() in '//*[@id="top"]/div[1]/div/div[1]/div/ul/li/a/text()'

But instead of text() I use @href to get url.

Joining urljoin('/' + city) creates wrong url because / skips /uk-student-accommodation - you have to use urljoin(city)

There was problem with allowed_domains - it blocked most of urls.

Working example. You can run it without project and it saves final urls in output.csv

```<code>import scrapy

class CollegiateSpider(scrapy.Spider):

    name = 'Collegiate'

    allowed_domains = ['collegiate-ac.com']

    start_urls = ['https://collegiate-ac.com/uk-student-accommodation/']

    # Step 1 - Get the area links

    def parse(self, response):
        for url in response.xpath('//*[@id="top"]/div[1]/div/div[1]/div/ul/li/a/@href').extract():
            url = response.urljoin(url)
            #print('>>>', url)
            yield scrapy.Request(url, callback=self.parse_area_page)

    # Step 2 - Get the block links

    def parse_area_page(self, response):
        for url in response.xpath('//div[3]/div/div/div/a/@href').extract():
            url = response.urljoin(url)
            yield scrapy.Request(response.urljoin(url), callback=self.parse_unitpage)

    # Step 3 Get the room links

    def parse_unitpage(self, response):
        for url in response.xpath('//*[@id="subnav"]/div/div[2]/ul/li[5]/a/@href').extract():
            url = response.urljoin(url)
            yield scrapy.Request(url, callback=self.parse_final)

    # Step 4 - Scrape the data

    def parse_final(self, response):
        # show some information for test
        print('>>> parse_final:', response.url)
        # send url as item so it can save it in file
        yield {'final_url': response.url}

# --- run it without project ---

import scrapy.crawler

c = scrapy.crawler.CrawlerProcess({
    "FEED_FORMAT": 'csv',
    "FEED_URI": 'output.csv'
})
c.crawl(CollegiateSpider)
c.start()
</code>```

Title: Spider not following links - scrapy

Body:
I am trying to build a spider which follows through 3 pages before getting to the page it scrapes. I have tested the responses in the shell, however, together it doesn't seem to work and I am not sure why.

My code below:

# -*- coding: utf-8 -*-
import scrapy

class CollegiateSpider(scrapy.Spider):
    name = 'Collegiate'
    allowed_domains = ['collegiate-ac.com/uk-student-accommodation']
    start_urls = ['http://collegiate-ac.com/uk-student-accommodation/']

    # Step 1 - Get the area links

    def parse(self, response):
        for city in response.xpath('//*[@id="top"]/div[1]/div/div[1]/div/ul/li/a/text').extract():
            yield scrapy.Request(response.urljoin("/" + city), callback = self.parse_area_page)

    # Step 2 - Get the block links

    def parse_area_page(self, response):
        for url in response.xpath('//div[3]/div/div/div/a/@href').extract():
            yield scrapy.Request(response.urljoin(url), callback=self.parse_unitpage)

    # Step 3 Get the room links

    def parse_unitpage(self, response):
        for url in response.xpath('//*[@id="subnav"]/div/div[2]/ul/li[5]/a/@href').extract():
            yield scrapy.Request(response.urljoin(final), callback=self.parse_final)

    # Step 4 - Scrape the data

    def parse_final(self, response):
        pass

I have tried changing to Crawlspider as per this answer, but that didn't seem to help.

I am currently looking into how to debug spiders, however, struggling with that so thought it would be beneficial to get opinions on here as well.

Body:
You forgot () in text() in '//*[@id="top"]/div[1]/div/div[1]/div/ul/li/a/text()'

But instead of text() I use @href to get url.

Joining urljoin('/' + city) creates wrong url because / skips /uk-student-accommodation - you have to use urljoin(city)

There was problem with allowed_domains - it blocked most of urls.

Working example. You can run it without project and it saves final urls in output.csv

import scrapy

class CollegiateSpider(scrapy.Spider):

    name = 'Collegiate'

    allowed_domains = ['collegiate-ac.com']

    start_urls = ['https://collegiate-ac.com/uk-student-accommodation/']

    # Step 1 - Get the area links

    def parse(self, response):
        for url in response.xpath('//*[@id="top"]/div[1]/div/div[1]/div/ul/li/a/@href').extract():
            url = response.urljoin(url)
            #print('>>>', url)
            yield scrapy.Request(url, callback=self.parse_area_page)

    # Step 2 - Get the block links

    def parse_area_page(self, response):
        for url in response.xpath('//div[3]/div/div/div/a/@href').extract():
            url = response.urljoin(url)
            yield scrapy.Request(response.urljoin(url), callback=self.parse_unitpage)

    # Step 3 Get the room links

    def parse_unitpage(self, response):
        for url in response.xpath('//*[@id="subnav"]/div/div[2]/ul/li[5]/a/@href').extract():
            url = response.urljoin(url)
            yield scrapy.Request(url, callback=self.parse_final)

    # Step 4 - Scrape the data

    def parse_final(self, response):
        # show some information for test
        print('>>> parse_final:', response.url)
        # send url as item so it can save it in file
        yield {'final_url': response.url}

# --- run it without project ---

import scrapy.crawler

c = scrapy.crawler.CrawlerProcess({
    "FEED_FORMAT": 'csv',
    "FEED_URI": 'output.csv'
})
c.crawl(CollegiateSpider)
c.start()


问:
What is the spring boot dependency for JMS?
The spring-boot guide https://spring.io/guides/gs/messaging-jms/ uses spring-boot-starter-activemq and that in turn refers to spring-jms. If I want to use a different message broker and spring doesn't provide a starter jar for that particular message broker, how do I go about including the spring-jms in dependencies? Can I just include spring-jms or is there a better way to do this?</p>

答:
That’s correct: you need to include spring-jms and
Vendor-specific dependency.

More info is in the Reference Manual.


问:
Problem opening mysql connection in php class
I am trying to create my own class to handle mysql interactions on a test site I'm making.  I can't get the mysqli_connect() to work within the class declaration.  Every time I try to use the class in a script I get this syntax error:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\xampp\htdocs\autoshop\classes\class_db.inc.php on line 7

Here is the code I have so far:

```<code><?php
class Db{
    private $host = 'localhost';
    private $db_user = 'username';
    private $db_pass = 'password';
    private $db_name = 'dbname';
    private $con = mysqli_connect($this->host, $this->db_user, $this->db_pass, $this->db_name) or die('failed to connect');

    public function valid_login($login_user, $login_pass){

        if(isset($login_user) && isset($login_pass) && ($login_user !== "") && ($login_pass !== "")){
            include('./includes/functions.php');

            $clean_lu = mysqli_real_escape_string($this->con, $login_user);
            $clean_lp = mysqli_real_escape_string($this->con, $login_pass);

            $login_query = "SELECT hash FROM users WHERE user_name='$clean_lu'";
            $login_results = mysqli_query($this->con, $login_query) or die('bad query');
            $login_hash = mysqli_fetch_array($login_results);

            if(isset($login_hash[0])){
                if(check_hash($clean_lp, $login_hash[0])){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }
    }

    mysqli_close($this->con);
}
?>
</code>```

I keep looking at that line and I can't find any bad syntax.

I apologize if this is a really simple solution that's right in front of my face, I'm pretty new at this whole developer thing.

答:
You cannot initialize object's member with result of function call. Perform this in your constructor instead.

```<code>class Db
{
    private $con;

    public function __construct()
    {
        $this->con = mysqli_connect($this->host, $this->db_user, $this->db_pass, $this->db_name) or die('failed to connect');
    }
    ...
}
</code>```

Also, where is mysqli_close($this->con); located? It doesn't belong to any of methods.

Btw, any reason to close connection manually at all?

Body:
I am trying to create my own class to handle mysql interactions on a test site I'm making.  I can't get the mysqli_connect() to work within the class declaration.  Every time I try to use the class in a script I get this syntax error:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\xampp\htdocs\autoshop\classes\class_db.inc.php on line 7

Here is the code I have so far:

<?php
class Db{
    private $host = 'localhost';
    private $db_user = 'username';
    private $db_pass = 'password';
    private $db_name = 'dbname';
    private $con = mysqli_connect($this->host, $this->db_user, $this->db_pass, $this->db_name) or die('failed to connect');

    public function valid_login($login_user, $login_pass){

        if(isset($login_user) && isset($login_pass) && ($login_user !== "") && ($login_pass !== "")){
            include('./includes/functions.php');

            $clean_lu = mysqli_real_escape_string($this->con, $login_user);
            $clean_lp = mysqli_real_escape_string($this->con, $login_pass);

            $login_query = "SELECT hash FROM users WHERE user_name='$clean_lu'";
            $login_results = mysqli_query($this->con, $login_query) or die('bad query');
            $login_hash = mysqli_fetch_array($login_results);

            if(isset($login_hash[0])){
                if(check_hash($clean_lp, $login_hash[0])){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }
    }

    mysqli_close($this->con);
}
?>

I keep looking at that line and I can't find any bad syntax.

I apologize if this is a really simple solution that's right in front of my face, I'm pretty new at this whole developer thing.

Body:
You cannot initialize object's member with result of function call. Perform this in your constructor instead.

class Db
{
    private $con;

    public function __construct()
    {
        $this->con = mysqli_connect($this->host, $this->db_user, $this->db_pass, $this->db_name) or die('failed to connect');
    }
    ...
}

Also, where is mysqli_close($this->con); located? It doesn't belong to any of methods.

Btw, any reason to close connection manually at all?


问:
Facebook OAuth "The domain of this URL isn't included in the app's domain"
Let me first start with saying I've searched for an answer to this question for quite some time...

I'm trying to setup Facebook OAuth to work with my application that is being developed locally on my machine.  Everything was working perfect with Facebook authorization UNTIL I moved from using localhost to another domain name (still local to my machine.)  Now I'm getting the following error.

Can't Load URL: The domain of this URL isn't included in the app's
domains. To be able to load this URL, add all domains and subdomains
of your app to the App Domains field in your app settings.

My hosts file contains 127.0.0.1   domain.dev  (works perfect)

My redirect in my app (using Socialite) is http://domain.dev/auth/facebook/callback

In my Facebook App Settings...

my App Domain is domain.dev

my Site URL is http://domain.dev/

my Valid OAuth redirect URIs is
http://domain.dev/auth/facebook/callback

The URL at the time of the error message is..

https://www.facebook.com/v2.5/dialog/oauth?client_id=XXXXXXXXXXXXXXX&redirect_uri=http%3A%2F%2Fdomain.dev%2Fauth%2Ffacebook%2Fcallback&scope=email&response_type=code&state=0ztcKhmWwFLtj72TWE8uOKTcf65JmePtG95MZLDD

I'm at a loss of what the problem is...

Screen Shot 1

Screen Shot 2

答:
Using my own local server.

Simply adding http://localhost/my-site as a URL in:

https://developers.facebook.com/apps/YOUR-APP-ID/fb-login/

worked for me.

ContentLicense: CC BY-SA 4.0


问:
How to prevent conflicts while multiple python scripts accessing MySQL DB at once ?
I have MySQL DB/table with column "name" containing one value. Multiple python scripts are accessing the same DB/table and the same column. There are also two more columns called "locked" and "locked_by", each script is reading the table and selects 10 entries from "name" where "locked" is false and update the locked value to True so other script can't take them and do the same work again. At least that is the solution I have for multiple script accessing one column and not tripping all over each other.. BUT!

I'm worried that between time when one script is updating the "locked" status other script takes that value and try to update it and so on.. ending in mess

Is there some solution to this or am I just worried about non exitant issue ?

答: Looks like SQLs: SELECT ... FOR UPDATE would lock the selected row and other processes can't read/update it until I commit changes.. if I understand correctly


问:
How to move map under a marker? android
I want to implement the drag effect of a map. When we drag the map the marker should show the current position or latitude and longitude. Its done in Uber application see below:

In this marker shows the current location as the map is dragged. How can I achieve this???

ChooseFromMapActivity

```<code>    public class ChooseFromMapActivity extends AppCompatActivity implements GoogleMap.OnCameraChangeListener {

    TextView textShowAddress;
    private GoogleMap mMap;
    LatLng latLng;
    double latitude = 17.385044;
    double longitude = 78.486671;
    float zoom;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_from_map);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mMap = mapFragment.getMap();
        mMap.setMyLocationEnabled(true);
        LatLng center = mMap.getCameraPosition().target;
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setRotateGesturesEnabled(true);
        mMap.getUiSettings().setScrollGesturesEnabled(true);
        latLng = new LatLng(-34, 151);

     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        textShowAddress = (TextView) findViewById(R.id.textShowAddress);
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(false)
                .title("sent location :)"))
        .setDraggable(false);
        }
    }
}
</code>```

答:
The answer is good but, setOnCameraChangeListener has depreciated. Use setOnCameraIdleListener.

Here some example to get camera position of map.

```<code>    mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
        @Override
        public void onCameraIdle() {
            LatLng midLatLng = mMap.getCameraPosition().target;
            getAddress(midLatLng.latitude, midLatLng.longitude);
        }
    });
</code>```

Now, getAddress returns to centered position of address.

Title: How to move map under a marker? android

Body:
I want to implement the drag effect of a map. When we drag the map the marker should show the current position or latitude and longitude. Its done in Uber application see below:

In this marker shows the current location as the map is dragged. How can I achieve this???

ChooseFromMapActivity

    public class ChooseFromMapActivity extends AppCompatActivity implements GoogleMap.OnCameraChangeListener {

    TextView textShowAddress;
    private GoogleMap mMap;
    LatLng latLng;
    double latitude = 17.385044;
    double longitude = 78.486671;
    float zoom;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_from_map);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mMap = mapFragment.getMap();
        mMap.setMyLocationEnabled(true);
        LatLng center = mMap.getCameraPosition().target;
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setRotateGesturesEnabled(true);
        mMap.getUiSettings().setScrollGesturesEnabled(true);
        latLng = new LatLng(-34, 151);

     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        textShowAddress = (TextView) findViewById(R.id.textShowAddress);
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(false)
                .title("sent location :)"))
        .setDraggable(false);
        }
    }
}

Body:
The answer is good but, setOnCameraChangeListener has depreciated. Use setOnCameraIdleListener.

Here some example to get camera position of map.

    mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
        @Override
        public void onCameraIdle() {
            LatLng midLatLng = mMap.getCameraPosition().target;
            getAddress(midLatLng.latitude, midLatLng.longitude);
        }
    });

Now, getAddress returns to centered position of address.


问:
How to update an ImageField in Django
I am making a website and would like to make it possible for each user to upload and update his own profile picture.

The update-profile template loads perfectly fine. I can update all the other fields, except for the image field. It can only be updated from the /admin page, but not from the update-profile page.

This is my image field in the Profile model:

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    dob = models.DateField(default=datetime.date(1989, 12, 25))
    gender = models.CharField(max_length=12, choices=GENDER_CHOICES, default='Unspecified')
    city = models.CharField(max_length=100, default='Braşov')
    image = models.ImageField(upload_to='profilepics', blank=True)
</code>```

Here is my ProfileForm:

```<code>class ProfileForm(forms.ModelForm):
class Meta:
    model = Profile
    fields = ('dob', 'gender', 'city', 'image')
</code>```

This is the html template:

```<code>{% block body %}
<form method="post">
<div class="container">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<button type="submit">Update</button>
<a href="myprofile" class="btn btn-info" role="button">Cancel</a>
</form>
</div>
{% endblock %}
</code>```

And this is the update_profile view:

```<code>@login_required
@transaction.atomic
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, ('Your profile was successfully updated!'))
            return redirect('myprofile')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(request, 'filter/updateprofile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })
</code>```

Thank you very much for reading!

答:
Add the attribute enctype to your form tag in your html document enctype="multipart/form-data"

See this question
Django ModelForm Imagefield Upload

And as is documented in w3schools
https://www.w3schools.com/tags/att_form_enctype.asp

Title: How to update an ImageField in Django

Body:
I am making a website and would like to make it possible for each user to upload and update his own profile picture.

The update-profile template loads perfectly fine. I can update all the other fields, except for the image field. It can only be updated from the /admin page, but not from the update-profile page.

This is my image field in the Profile model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    dob = models.DateField(default=datetime.date(1989, 12, 25))
    gender = models.CharField(max_length=12, choices=GENDER_CHOICES, default='Unspecified')
    city = models.CharField(max_length=100, default='Braşov')
    image = models.ImageField(upload_to='profilepics', blank=True)

Here is my ProfileForm:

class ProfileForm(forms.ModelForm):
class Meta:
    model = Profile
    fields = ('dob', 'gender', 'city', 'image')

This is the html template:

{% block body %}
<form method="post">

{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<button type="submit">Update</button>
Cancel
</form>

{% endblock %}

And this is the update_profile view:

@login_required
@transaction.atomic
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, ('Your profile was successfully updated!'))
            return redirect('myprofile')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(request, 'filter/updateprofile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

Thank you very much for reading!


问:
Ignore git submodule without read permission
The situation:

I have a repository that has a submodule.

Normal people (like me) don't have read permissions for this submodule which isn't really a problem as it isn't required to run the project.

My problem is that every time I check something out I get errors telling me that the submodule update failed because the submodule remote couldn't be read:

```<code>fatal: Needed a single revision
Unable to find current revision in submodule path
</code>```

no surprise ...

I tried to remove it manually from .gitmodules and then use

```<code>git update-index --assume-unchanged .gitmodules
</code>```

but this only works until the next checkout as submodules seem to get special treatment.

I tried putting .gitmodules into .gitignore or .git/info/exclude but git ignored that, reported .gitmodules as changed and gave me the original one again at checkout.

My question:

How do I suppress these errors and completely ignore the existence of this submodule locally... including all further remote changes that try to reintroduce it?

Note: Please assume that the solution has to stay on my end and requires no changes on the remote side... as they will not happen (already tried talking to the repo admin)

答:
It's a bit difficult to replicate this situation, but as per discussion in comments

```<code>git submodule deinit -f .
</code>```

helped. If someone stumbles here, from documentation one might find out that during init, actual git pull is done on submodule. So If You had no permissions to access remote submodule repository, locally git had no master branch, no commits to checkout, and that was the meaning behind error message.

Update: if you are using a gui like SourceTree or SmartGit, check the repository settings and disable the auto-update of submodules.

Depending on your setup only disabling "Initialize new submodules" may already fix the problem:

Body:
The situation:

I have a repository that has a submodule.

Normal people (like me) don't have read permissions for this submodule which isn't really a problem as it isn't required to run the project.

My problem is that every time I check something out I get errors telling me that the submodule update failed because the submodule remote couldn't be read:

fatal: Needed a single revision
Unable to find current revision in submodule path

no surprise ...

I tried to remove it manually from .gitmodules and then use

git update-index --assume-unchanged .gitmodules

but this only works until the next checkout as submodules seem to get special treatment.

I tried putting .gitmodules into .gitignore or .git/info/exclude but git ignored that, reported .gitmodules as changed and gave me the original one again at checkout.

My question:

How do I suppress these errors and completely ignore the existence of this submodule locally... including all further remote changes that try to reintroduce it?

Note: Please assume that the solution has to stay on my end and requires no changes on the remote side... as they will not happen (already tried talking to the repo admin)

Body:
It's a bit difficult to replicate this situation, but as per discussion in comments

git submodule deinit -f .

helped. If someone stumbles here, from documentation one might find out that during init, actual git pull is done on submodule. So If You had no permissions to access remote submodule repository, locally git had no master branch, no commits to checkout, and that was the meaning behind error message.

Update: if you are using a gui like SourceTree or SmartGit, check the repository settings and disable the auto-update of submodules.

Depending on your setup only disabling "Initialize new submodules" may already fix the problem:


问:
Why the difference between int a[5] = {0} and int a[5]={1} (Missing Feature)
When we initialize an array like this int a[5] = {0}, the compiler makes all 5 elements 0. That is really good, compact-initialization and useful feature.

But I wonder why the compiler doesn't initialize int a[5]={1} similarly? Why does it not make all 5 elements 1? Why the Standard doesn't mandate it? Would it not been an awesome feature? Isn't it missing?

Also, if the number of elements in the initializer is less than the size of the array, then the compile could initialize the remaining elements with the last element in the initializer. Means, int a[5]={1,2,3} is equivalent to int a[5]={1,2,3,3,3}. And similarly, int a[10]={1,2,3,0} is equivalent to int a[10]={1,2,3,0,0,0,0,0,0,0};.

Would it all not be an awesome feature if the Standard mandates it? Or is there any good reasons for this missing feature?

And there is something called designated initializer in C99, which is used like:

Designated initializers can be
  combined with regular initializers, as
  in the following example:

int a[10] = {2, 4, [8]=9, 10}

In this
  example, a[0] is initialized to 2,
  a1 is initialized to 4, a[2] to a[7]
  are initialized to 0, and a[9] is
  initialized to 10.

Quite interesting. But even this feature is not in C++.

答:
I personally find more "logical" (i.e. simple) having a fixed default initializer instead of another rule of repeating last one just for arrays. That may appear "practical" (i.e. useful) but it's IMO more logically complex.

That said however I think you're making a big mistake in trying to apply logic to a language like C++.

C++ is a complex language whose rules are the result of a long evolution history, and its current form is the result of the work of many people and even of formal committees (the last part alone could explain anything).

A language like C++ cannot be inferred by logic, it must be studied like history. Unless you're Hari Seldon there's really no way you can infer history using logical reasoning.

There are places of C++ where you're going to suffer a lot if you try to use logic instead of studying. Just to name a few...

Why is default dispatch static (i.e. wrong)?

Why there's no keyword for the null pointer?

Why the difference of two unsigned is unsigned?

Why a sum between a signed and an unsigned is unsigned?

If unsigned means "element of Z_{2^n}" then why sizes are unsigned?

Why std::string s; s=3.141592654; is perfectly valid C++?

Why in C++0X i = i++ + 1; is undefined behavior and i = ++i + 1; is valid?

Why double x=3.14; int y(int(x)); doesn't mean y will be 3?


问:
UIBarButtonItem position different when placed via storyboard vs. programmatically
In my app, I have a toolbar with UIBarButtonItems.

In most circumstances, the UIBarButtonItems are set via storyboard, and look as follows:

In a special case, I have to replace one UIBarButtonItem programmatically. This is done with the following code:

```<code>let rotatingButton = UIButton(type: .custom)
rotatingButton.setImage(UIImage(named: "LocalizationInUseNoFix"), for: .normal)
rotatingButton.addTarget(self, action: #selector(localizationButtonTapped), for: .touchUpInside)
rotatingButton.rotateStart()
let barButtonItem = UIBarButtonItem(customView: rotatingButton)
leftBarButtonItems![2] = barButtonItem
</code>```

When the rotatingButton is displayed in the toolbar, it placed at a different position. It is shifted to the right, as you can see here:

How can I achieve to place both UIBarButtonItems at the same position?

EDIT:

By now I realized that the horizontal shift of the programmatically created UIBarButtonItem is not always the same, without any changes to the code: Sometimes it is shifted left, and not right:

EDIT 2:

I found a workaround:

If I set a width constrain to my button like

```<code>rotatingButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
</code>```

then the button is apparently always correctly placed. But I hate to hard-code constraints like this.

Is there a more elegant way to do it?

答: When you set the image on UIBarButton programmatically, the contentmode of the leftBarButtonItems becomes 'left' and rightBarButtonItems become 'right'. But from storyboard, it is centered. Set the image and adjust the contentMode as required.</p>

Body:
In my app, I have a toolbar with UIBarButtonItems.

In most circumstances, the UIBarButtonItems are set via storyboard, and look as follows:

In a special case, I have to replace one UIBarButtonItem programmatically. This is done with the following code:

let rotatingButton = UIButton(type: .custom)
rotatingButton.setImage(UIImage(named: "LocalizationInUseNoFix"), for: .normal)
rotatingButton.addTarget(self, action: #selector(localizationButtonTapped), for: .touchUpInside)
rotatingButton.rotateStart()
let barButtonItem = UIBarButtonItem(customView: rotatingButton)
leftBarButtonItems![2] = barButtonItem

When the rotatingButton is displayed in the toolbar, it placed at a different position. It is shifted to the right, as you can see here:

How can I achieve to place both UIBarButtonItems at the same position?

EDIT:

By now I realized that the horizontal shift of the programmatically created UIBarButtonItem is not always the same, without any changes to the code: Sometimes it is shifted left, and not right:

EDIT 2:

I found a workaround:

If I set a width constrain to my button like

rotatingButton.widthAnchor.constraint(equalToConstant: 40).isActive = true

then the button is apparently always correctly placed. But I hate to hard-code constraints like this.

Is there a more elegant way to do it?


问:
Shell script to count no of character,word,line in a file
```<code>#!/bin/bash

clear
character=0
word=0
line=`echo -e "\n"`
space=`echo -e " "`

if [ $# -eq 0 ]
then
    echo "You haven't entered any line"
elif [ $# -eq 1 ]
then
    filename=$1
    while read -n1 newline
    do
        if [ '$newline' == '$line' ]
        then
            ((line++))
        elif [ '$newline' == '$space' ]
        then
            ((word++))
        else
            ((character++))
        fi
    done < $filename
    echo "No of line =$line"
    echo "No of word =$word"
    echo "No of character =$character"
fi
</code>```

答:
Double quotes around a variable are OK, but don't put single quotes around each variable as was done here:

```<code>    if [ '$newline' == '$line' ]
</code>```

To see why that fails, look at the following code, where the pale blue text is code, and the pink text is output:

```<code>a=3
echo $a
</code>```

3

```<code>echo '$a'
</code>```

$a

```<code>if [ '$a' == 3 ] ; then echo true ; else echo false ; fi
</code>```

false

```<code>if [ $a == 3 ] ; then echo true ; else echo false ; fi
</code>```

true

Body:
Double quotes around a variable are OK, but don't put single quotes around each variable as was done here:

    if [ '$newline' == '$line' ]

To see why that fails, look at the following code, where the pale blue text is code, and the pink text is output:

a=3
echo $a

3

echo '$a'

$a

if [ '$a' == 3 ] ; then echo true ; else echo false ; fi

false

if [ $a == 3 ] ; then echo true ; else echo false ; fi

true


问:
Scroll down to show header and hide when scroll up
I tried to make a header animation like this website: https://www.templatemonster.com/demo/57969.html
And here are my code:

HTML

```<code><div id="header-part" class="container-fluid fixed-nav">  </div>
</code>```

CSS

```<code>#header-part.container-fluid {
background-color: #1f2324;
padding: 32px 0 22px 0;
display: flex;
height: 100px;
 width: 100%;
padding: 0;
}

#header-part.fixed-nav {
position: fixed;
top: -100px;
border-bottom: 0px solid #5f6a6d;
z-index: 4;
}
</code>```

JS

```<code>$(window).scroll( function(){
 var top_of_window = $(window).scrollTop();
 if( top_of_window > 100 ){
  $(".fixed-nav").animate({top:'0'}, 800);
  }
});
</code>```

My idea is used top:-100px to hide it and show it when scrolling down to 100px. It runs smoothly but when I add else {$(".fixed-nav").animate({top:'-100px'}, 800);} to hide it when scroll up above 100px, it hide my header as by default and maybe if is ignored to run else.

Try it, then remove comment of else in file js to see problem
https://github.com/dothuan96/Animation-HTML-basic/tree/master/cinema%20header

答:
try this</p>

```<code>if( top_of_window > 100 ){
  $(".fixed-nav").animate({height: 'toggle'}, 800);
  }
else{
$(".fixed-nav").animate({
            height: 'toggle',
        800
        });
}
</code>```

Body:
I tried to make a header animation like this website: https://www.templatemonster.com/demo/57969.html
And here are my code:

HTML

CSS

#header-part.container-fluid {
background-color: #1f2324;
padding: 32px 0 22px 0;
display: flex;
height: 100px;
 width: 100%;
padding: 0;
}

#header-part.fixed-nav {
position: fixed;
top: -100px;
border-bottom: 0px solid #5f6a6d;
z-index: 4;
}

JS

$(window).scroll( function(){
 var top_of_window = $(window).scrollTop();
 if( top_of_window > 100 ){
  $(".fixed-nav").animate({top:'0'}, 800);
  }
});

My idea is used top:-100px to hide it and show it when scrolling down to 100px. It runs smoothly but when I add else {$(".fixed-nav").animate({top:'-100px'}, 800);} to hide it when scroll up above 100px, it hide my header as by default and maybe if is ignored to run else.

Try it, then remove comment of else in file js to see problem
https://github.com/dothuan96/Animation-HTML-basic/tree/master/cinema%20header

Body:
try this

if( top_of_window > 100 ){
  $(".fixed-nav").animate({height: 'toggle'}, 800);
  }
else{
$(".fixed-nav").animate({
            height: 'toggle',
        800
        });
}


问:
Creating a CLI (Shell?) in Python
I am very newbie in Python but I have to implement for school a command line interpreter in Python language, but I am kinda lost in how to do that.

I have already read some tutorials and created a simple file called functions.py where i include some simple functions like this:

```<code>def delete(loc):
    if os.path.exists(loc) == True:
        os.remove(loc)
        print "Removed"
    else:
        print "File not exists"
</code>```

Now.. here is the thing.. in order to use this I must import it inside the python command interpreter, like...

```<code>import functions
functions.delete("file to delete")
</code>```

How can I make a Shell/CLI so instead of have to write all of this I can just write like:

```<code>delete file_name
</code>```

Thanks!

答:
I think you should now to use simple argparse module to get command line arguments

```
<code>
import argparse

from functions import delete

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file')

args = parser.parse_args()

delete(args.file)
</code>
```

Hope this should work for you

Sultan

Title: Creating a CLI (Shell?) in Python

Body:
I am very newbie in Python but I have to implement for school a command line interpreter in Python language, but I am kinda lost in how to do that.

I have already read some tutorials and created a simple file called functions.py where i include some simple functions like this:

def delete(loc):
    if os.path.exists(loc) == True:
        os.remove(loc)
        print "Removed"
    else:
        print "File not exists"

Now.. here is the thing.. in order to use this I must import it inside the python command interpreter, like...

import functions
functions.delete("file to delete")

How can I make a Shell/CLI so instead of have to write all of this I can just write like:

delete file_name

Thanks!

Body:
I think you should now to use simple argparse module to get command line arguments

import argparse

from functions import delete

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file')

args = parser.parse_args()

delete(args.file)

Hope this should work for you

Sultan


问:
How to redirect MongoDB logs in a Java application?
I am using a Mongo database in a Java application.
The stdout is filled with logs of type:

```<code>dec. 09, 2017 9:45:21 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:225, serverValue:225}] to localhost:27017
dec. 09, 2017 9:45:21 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 4, 10]}, minWireVersion=0, maxWireVersion=5, maxDocumentSize=16777216, roundTripTimeNanos=189205}
</code>```

I would like these logs to be redirected to a text file. I tried several options mentioned in other SO answers without success, such as using java.util.logging.Logger, but I don't seem to get it to work.
Help appreciated.

A sample of my code is the following:

```<code>MongoClient m = new MongoClient("localhost",27017);
// Do something with the DBs
m.close();
</code>```

答:
Try this:</p>

```<code>// get mongo db logger
Logger logger = Logger.getLogger("org.mongodb.driver");
// stop upstream log propagation
logger.setUseParentHandlers(false)
// set up handler for output to file
FileHandler fh = new FileHandler("S:/ome/path/to/your/file.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
</code>```

Body:
I am using a Mongo database in a Java application.
The stdout is filled with logs of type:

dec. 09, 2017 9:45:21 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:225, serverValue:225}] to localhost:27017
dec. 09, 2017 9:45:21 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 4, 10]}, minWireVersion=0, maxWireVersion=5, maxDocumentSize=16777216, roundTripTimeNanos=189205}

I would like these logs to be redirected to a text file. I tried several options mentioned in other SO answers without success, such as using java.util.logging.Logger, but I don't seem to get it to work.
Help appreciated.

A sample of my code is the following:

MongoClient m = new MongoClient("localhost",27017);
// Do something with the DBs
m.close();

Body:
Try this:

// get mongo db logger
Logger logger = Logger.getLogger("org.mongodb.driver");
// stop upstream log propagation
logger.setUseParentHandlers(false)
// set up handler for output to file
FileHandler fh = new FileHandler("S:/ome/path/to/your/file.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);


问:
How to search a item from a list?
Could anyone tell me why this code cannot work, please? </p>

```<code>list=[5,9,2,5,13]
item=input("Please enter the search item.")
found=false
for search = 0 to list.length -1
if item==list[search]:
found= True
next search
if found==True:
print("The item is in the list.")
else:
    print("The item is not in the list.")
</code>```

答:
That's what you're asking for: </p>

```<code>value = int(input('Please enter a value to search: '))

if value in [5, 9, 2, 5, 13]:
    print('Item found.')
else:
    print('Item not found.')
</code>```

Title: How to search a item from a list?

Body:
Could anyone tell me why this code cannot work, please?

list=[5,9,2,5,13]
item=input("Please enter the search item.")
found=false
for search = 0 to list.length -1
if item==list[search]:
found= True
next search
if found==True:
print("The item is in the list.")
else:
    print("The item is not in the list.")

Body:
That's what you're asking for:

value = int(input('Please enter a value to search: '))

if value in [5, 9, 2, 5, 13]:
    print('Item found.')
else:
    print('Item not found.')


问:
Data from WebService is not retained in page history
Here is my scenario:

I am using a web service to pass back search results. To do this I am using ToolkitScriptManager with a ServiceReference to my web service and calling the web service up with javascript. The javascript call looks something like this:

```<code>WebService.GetResults("search term", OnSuccessGetData, OnFail);
</code>```

If the request is successful the "OnSuccessGetData" function is fired and the results are inserted into a DIV tag. Because the resulting search results can be large I wrote the service to only pass back the first 20 results on the first trip. After that I make calls again to the service to return the next 5 results and continue to do this until all the results are loaded. This all works wonderful.

You can see it in action at www.lsbio.com and use the search term "human mouse". My problem is that when the user clicks on a product and then hits the 'Back' button, the search results have to be fetched again from the webservice.

Is there a way to keep the search results in the DIV tag to remain as part of the page so when the user navigates away from the search page and uses the 'Back' button to navigate back, the search results are still there without having to hit the webservice again?

If I did not make myself clear enough on what I am trying to do, please test the site www.lsbio.com, use the search terms human mouse, click on a product, and then hit the back button.

答: Maybe you can store the result somewhere, i.e. in a hidden field? Than on page load you first test if the result is in the hidden field, if so you insert it in the result area, if not you use the webservice. </p>

Body:
Here is my scenario:

I am using a web service to pass back search results. To do this I am using ToolkitScriptManager with a ServiceReference to my web service and calling the web service up with javascript. The javascript call looks something like this:

WebService.GetResults("search term", OnSuccessGetData, OnFail);

If the request is successful the "OnSuccessGetData" function is fired and the results are inserted into a DIV tag. Because the resulting search results can be large I wrote the service to only pass back the first 20 results on the first trip. After that I make calls again to the service to return the next 5 results and continue to do this until all the results are loaded. This all works wonderful.

You can see it in action at www.lsbio.com and use the search term "human mouse". My problem is that when the user clicks on a product and then hits the 'Back' button, the search results have to be fetched again from the webservice.

Is there a way to keep the search results in the DIV tag to remain as part of the page so when the user navigates away from the search page and uses the 'Back' button to navigate back, the search results are still there without having to hit the webservice again?

If I did not make myself clear enough on what I am trying to do, please test the site www.lsbio.com, use the search terms human mouse, click on a product, and then hit the back button.


问:
Parse date with moment.js with locales
I am getting an "Invalid date" error when I translate my dates from Spanish to English with moment.js (with locales). The weird thing here, is that only fails with some dates.

I have a list of dates, apparently of the same format (they were parsed before using the same library). Then when I parsed it again after change the moment.js locale (To translate my dates to the desired language) I get this:

```<code>Enero 13º 2017, 6:00:02 Am --> Invalid date
Abril 17º 2017, 7:36:03 Pm --> Invalid date
Abril 17º 2017, 6:00:01 Am --> Invalid date
Mayo 12º 2017, 2:04:19 Pm   --> May 12th 2017, 2:04:19 Pm
Abril 17º 2017, 11:47:17 Pm --> Invalid date
</code>```

Parse Method (format is initialized here because in other moments it can get other values):

```<code>format = 'MMMM Do YYYY, h:mm:ss a';
$(".videoDate").each(function(){
    var _text = $(this).text();//Extract initial date
    var _date = moment(_text, format).format('MMMM Do YYYY, h:mm:ss a');//format
    $(this).text(_date);//new date setting
});
</code>```

http://jsfiddle.net/gr1zdtag/

Maybe I am missing something but I don't find the reason yet. Can any help me with this problem?

答:
You can specify locale when parsing non-english input. You can use moment(String, String, String):

As of version 2.0.0, a locale key can be passed as the third parameter to moment() and moment.utc().

You can use locale() function to change locale of a given moment object (while moment.locale() changes locale globally).

Here a working sample:

var format = 'MMMM Do YYYY, h:mm:ss a';
$(".videoDate").each(function(){
    var _text = $(this).text();//Extract initial date
    //Parse in spanish and convert it in english
    var _date = moment(_text, format, 'es')
                  .locale('en')
                  .format('MMMM Do YYYY, h:mm:ss a');//format
    $(this).text(_date);//new date setting
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment-with-locales.min.js"></script>

<ul>
  <li class="videoDate">Enero 13º 2017, 6:00:02 Am</li>
  <li class="videoDate">Abril 17º 2017, 7:36:03 Pm</li>
  <li class="videoDate">Abril 17º 2017, 6:00:01 Am</li>
  <li class="videoDate">Mayo 12º 2017, 2:04:19 Pm</li>
  <li class="videoDate">Abril 17º 2017, 11:47:1</li>
</ul></code>```

Mayo 12º 2017, 2:04:19 Pm is recognized beacuse by default moment parses strings using english locale and Moment's parser is very forgiving. Mayo contains May so it is considered a valid month name (using forgiving mode).

Title: Parse date with moment.js with locales

Body:
I am getting an "Invalid date" error when I translate my dates from Spanish to English with moment.js (with locales). The weird thing here, is that only fails with some dates.

I have a list of dates, apparently of the same format (they were parsed before using the same library). Then when I parsed it again after change the moment.js locale (To translate my dates to the desired language) I get this:

Enero 13º 2017, 6:00:02 Am --> Invalid date
Abril 17º 2017, 7:36:03 Pm --> Invalid date
Abril 17º 2017, 6:00:01 Am --> Invalid date
Mayo 12º 2017, 2:04:19 Pm   --> May 12th 2017, 2:04:19 Pm
Abril 17º 2017, 11:47:17 Pm --> Invalid date

Parse Method (format is initialized here because in other moments it can get other values):

format = 'MMMM Do YYYY, h:mm:ss a';
$(".videoDate").each(function(){
    var _text = $(this).text();//Extract initial date
    var _date = moment(_text, format).format('MMMM Do YYYY, h:mm:ss a');//format
    $(this).text(_date);//new date setting
});

http://jsfiddle.net/gr1zdtag/

Maybe I am missing something but I don't find the reason yet. Can any help me with this problem?

Body:
You can specify locale when parsing non-english input. You can use moment(String, String, String):

As of version 2.0.0, a locale key can be passed as the third parameter to moment() and moment.utc().

You can use locale() function to change locale of a given moment object (while moment.locale() changes locale globally).

Here a working sample:

var format = 'MMMM Do YYYY, h:mm:ss a';
$(".videoDate").each(function(){
    var _text = $(this).text();//Extract initial date
    //Parse in spanish and convert it in english
    var _date = moment(_text, format, 'es')
                  .locale('en')
                  .format('MMMM Do YYYY, h:mm:ss a');//format
    $(this).text(_date);//new date setting
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment-with-locales.min.js"></script>

<ul>
  <li class="videoDate">Enero 13º 2017, 6:00:02 Am</li>
  <li class="videoDate">Abril 17º 2017, 7:36:03 Pm</li>
  <li class="videoDate">Abril 17º 2017, 6:00:01 Am</li>
  <li class="videoDate">Mayo 12º 2017, 2:04:19 Pm</li>
  <li class="videoDate">Abril 17º 2017, 11:47:1</li>
</ul>

Mayo 12º 2017, 2:04:19 Pm is recognized beacuse by default moment parses strings using english locale and Moment's parser is very forgiving. Mayo contains May so it is considered a valid month name (using forgiving mode).


问:
how to integrate facebook "App-to-User Notifications" into wordpress post comments
Facebook re activated the App-to-User Notifications again.

i am trying to find a way to make my wordpress website send a notification to my user when someone writes a comment to his post on my website.

my users are registered using their Facebook accounts.

Facebook just mentioned that Apps can generate notifications by issuing a HTTP POST request to the /user_id/notifications using

```<code>POST /{recipient_userid}/notifications?access_token=... &template=...&href=...
</code>```

How to integrate this API call into wordpress?

Thanks

答:
Well, your question is too wide because it seems like you are asking the whole guide on how to implement this API call in Wordpress.

So let me just give you the direction:

Get the Facebook PHP SDK from git here: Facebook SDK for PHP (v5)

Implement Wordpress HOOK either in your theme or in the plugin, so that you can handle things when comment is posted. Wordpress Comment Post Hook Document

So in Wordpress side, you will need to create a function which takes the facebook user token who made a post, make an API call, and then link this function to comment_post hook.

Hope this will give you an idea.

Body:
Facebook re activated the App-to-User Notifications again.

i am trying to find a way to make my wordpress website send a notification to my user when someone writes a comment to his post on my website.

my users are registered using their Facebook accounts.

Facebook just mentioned that Apps can generate notifications by issuing a HTTP POST request to the /user_id/notifications using

POST /{recipient_userid}/notifications?access_token=... &template=...&href=...

How to integrate this API call into wordpress?

Thanks


问:
How do programs like mathematica draw graphs and how can I make such a program?
I've been wondering how programs like mathematica and mathlab, and so on, plot graphs of functions so gracefully and fast. Can anyone explain to me how they do this and, furthermore, how I can do this? Is it related to an aspect or course in Computer Programming or Math? Which then?</p>

答:
Basically most programs that plot any type of graph (particularly any graphs of reasonable complexity) will use some type of third party libraries.

The specific library used would depend on the programming language that is being used.
For example:

For a .Net application you might use Crystal reports. http://en.wikipedia.org/wiki/Crystal_Reports

For Java you might use JFreeChart. http://www.jfree.org/jfreechart/
And so on...

You will likely find numerious libraries for whatever language you decide to code in.

If you want to accomplish this functionality in your specific project I suggest using a library especially if you are a beginner. The internal complexities of how these graph libraries are implemented would be significant because of many issues such as cross platform compatibility, graphic rendering optimizations (ie: making sure the graphics render quickly and ‘prettily’), the maths associated with the positioning of elements on the graph and so forth.

Lastly I doubt you will find specific courses in this subject (or require them) as again excluding VERY specific cases programmers will always use libraries that already exist.

Why code it yourself when someone has
  already solved the problem for you?


问:
How to allow only integer value in input field for mobile application
I am using meteor+blaze for application development and need to allow only integer value in number input field for user details form.

I tried to use keypress/keyup events for input type nuber but not able to get the event for decimal point, android mobile number keypad return same keycode 229 for .,- keys and when i return false for keycode 229, it's not working. But events are working fine with number value keys on mobile.

code:

```<code>'keyup #weight': function (event, instance) {
        event.preventDefault();
        if (event.keyCode < 48 || event.keyCode > 57) {
            console.log(this, "Integer values only");
            return false;  // stop processing
        }
    }
</code>```

Please advise, how can I prevent the user from entering a decimal value in the input field?

答:
I guess android:inputType="number" at the xml attributes.

OR

```<code><EditText
android:id="@+id/myNumber"
android:digits="0123456789"
android:inputType="number"/>
</code>```

Hope this helps you.

Body:
I am using meteor+blaze for application development and need to allow only integer value in number input field for user details form.

I tried to use keypress/keyup events for input type nuber but not able to get the event for decimal point, android mobile number keypad return same keycode 229 for .,- keys and when i return false for keycode 229, it's not working. But events are working fine with number value keys on mobile.

code:

'keyup #weight': function (event, instance) {
        event.preventDefault();
        if (event.keyCode < 48 || event.keyCode > 57) {
            console.log(this, "Integer values only");
            return false;  // stop processing
        }
    }

Please advise, how can I prevent the user from entering a decimal value in the input field?

Body:
I guess android:inputType="number" at the xml attributes.

OR

<EditText
android:id="@+id/myNumber"
android:digits="0123456789"
android:inputType="number"/>

Hope this helps you.


问:
Issue forEach JS array
Here is my code JS :

```<code>var items = [255, 255, 255, 255];
items.forEach(function(item) {
    if (item = 255) {
        item = 0;
    };
});
console.log(items)
</code>```

In console.log I get [255, 255, 255, 255], why it doesn't change to [0, 0, 0, 0]? What am I doing wrong?

答:
You want to use .map.

.forEach doesn't return anything, it is used to run a function with each item. .map returns a value for each iteration it runs.

```<code>var items = [255, 255, 255, 255]
items = items.map(item => item === 255 ? 0 : item)

console.log(items) // [0, 0, 0, 0]
</code>```

Title: Issue forEach JS array

Body:
Here is my code JS :

var items = [255, 255, 255, 255];
items.forEach(function(item) {
    if (item = 255) {
        item = 0;
    };
});
console.log(items)

In console.log I get [255, 255, 255, 255], why it doesn't change to [0, 0, 0, 0]? What am I doing wrong?

Body:
You want to use .map.

.forEach doesn't return anything, it is used to run a function with each item. .map returns a value for each iteration it runs.

var items = [255, 255, 255, 255]
items = items.map(item => item === 255 ? 0 : item)

console.log(items) // [0, 0, 0, 0]


答:
Well, you are just changing the value type argument, nothing will happen with the items in the array. You can just change it to use map instead and create a new array

```<code>items = items.map( item => item === 255 ? 0 : item );
</code>```

As remarked in the comments, in the original code, you also used an assignment operator instead of a compare operator

When you do:

```<code>if (item = 255)
</code>```

You will assign item with 255 (which will be truthy, and then go into the if statement where you are assigning it with 0)

Title: Issue forEach JS array

Body:
Well, you are just changing the value type argument, nothing will happen with the items in the array. You can just change it to use map instead and create a new array

items = items.map( item => item === 255 ? 0 : item );

As remarked in the comments, in the original code, you also used an assignment operator instead of a compare operator

When you do:

if (item = 255)

You will assign item with 255 (which will be truthy, and then go into the if statement where you are assigning it with 0)


问:
Need to track unwanted file downloads
I'm looking to track how many people on the web have made my software program file available for download without my permission.

I've thought of searching for my product name and file size to catch possible thieves.

Do you think a web search API is the best way forward?

EDIT: I plan to use the detection data for survey purposes.

答:
There are web analytics companies which could probably help you more than a roll-your-own solution. Consider the companies that big music and film vendors use, or check with the Business Software Alliance.

Ultimately, you are chasing your tail if you are looking to thwart piracy with the results of this kind of activity. However, if you are steadfast that you must try to understand what is going on, you need professional (web analytic) help. There are so many variations out there that you need someone experienced in tracking this kind of information, since you could easily get a false sense of security, or an inflated sense of activity.

Title: Need to track unwanted file downloads


问:
Printing a Class
Hi I'm trying to print 4 band members details using a class, however I'm only able to print one, ill give samples to give you an understanding below, this is my whole code

```<code>class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)
        return '{} {} \n{} {} {}'.format(paul._firstname, paul._surname,     paul.d, paul.m, paul.y)
        return '{} {} \n{} {} {}'.format(george._firstname,     george._surname, george.d, george.m, george.y)
        return '{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d, ringo.m, ringo.y)

john = Person('John','Lennon','8th','October','1940')
paul = Person('Paul','McCartney','18th','June','1942')
george = Person('George','Harrison','25th','February','1943')
ringo = Person('Ringo','Starr','7th','July','1940')

john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'

paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._d = '18th'
paul._m = 'June'
paul._y = '1942'

george._firstname = 'George'
george._surname = 'Harrison'
george._d = '25th'
george._m = 'February'
george._y = '1943'

ringo._firstname = 'Ringo'
ringo._surname = 'Starr'
ringo._d = '7th'
ringo._m = 'July'
ringo._y = '1940'

print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y))
print('{} {} \n{} {} {}'.format(paul._firstname, paul._surname, paul.d,     paul.m, paul.y))
print('{} {} \n{} {} {}'.format(george._firstname, george._surname,         george.d, george.m, george.y))
print('{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d,     ringo.m, ringo.y))
</code>```

I receive, the correct output, which is this:

```<code>John Lennon
8th October 1940
Paul McCartney
18th June 1942
George Harrison
25th February 1943
Ringo Starr
7th July 1940
</code>```

I want to be able to type:

```<code>print(john)
print(george)
print(paul)
print(ringo)
</code>```

To get the same output, however when i type this and remove the bottom 4 print lines, i get this

```<code>John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940
</code>```

My understanding up until now is that the __repr__(self) can only read one line of code, which would be john, but that's where my knowledge stops.

ANY help is more than appreciated! if you need more info please ask, I'm quite new to this as I'm in my first year at university so I appreciate your patience and help!:)

答:
Any return command will simply exit the function, so having multiple return commands at the same level would never work in Python.

The issue with your code is that you should be using the key word self within your __repr__ definition, that way you can access it with all four instances that you create with

```<code>john = Person('John','Lennon','8th','October','1940')
paul = Person('Paul','McCartney','18th','June','1942')
george = Person('George','Harrison','25th','February','1943')
ringo = Person('Ringo','Starr','7th','July','1940')
</code>```

Those creations of instances of the class Person will also automatically store all the information that you enter, so no need to specify by hand values for john._firstname etc.

To give a clear answer:

```<code>class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(self._firstname,
                                         self._surname,
                                         self.d,
                                         self.m,
                                         self..y)

john = Person('John','Lennon','8th','October','1940')
paul = Person('Paul','McCartney','18th','June','1942')
george = Person('George','Harrison','25th','February','1943')
ringo = Person('Ringo','Starr','7th','July','1940')

print(john)
print(paul)
print(george)
print(ringo)
</code>```

Title: Printing a Class

Body:
Hi I'm trying to print 4 band members details using a class, however I'm only able to print one, ill give samples to give you an understanding below, this is my whole code

class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)
        return '{} {} \n{} {} {}'.format(paul._firstname, paul._surname,     paul.d, paul.m, paul.y)
        return '{} {} \n{} {} {}'.format(george._firstname,     george._surname, george.d, george.m, george.y)
        return '{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d, ringo.m, ringo.y)

john = Person('John','Lennon','8th','October','1940')
paul = Person('Paul','McCartney','18th','June','1942')
george = Person('George','Harrison','25th','February','1943')
ringo = Person('Ringo','Starr','7th','July','1940')

john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'

paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._d = '18th'
paul._m = 'June'
paul._y = '1942'

george._firstname = 'George'
george._surname = 'Harrison'
george._d = '25th'
george._m = 'February'
george._y = '1943'

ringo._firstname = 'Ringo'
ringo._surname = 'Starr'
ringo._d = '7th'
ringo._m = 'July'
ringo._y = '1940'

print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y))
print('{} {} \n{} {} {}'.format(paul._firstname, paul._surname, paul.d,     paul.m, paul.y))
print('{} {} \n{} {} {}'.format(george._firstname, george._surname,         george.d, george.m, george.y))
print('{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d,     ringo.m, ringo.y))

I receive, the correct output, which is this:

John Lennon
8th October 1940
Paul McCartney
18th June 1942
George Harrison
25th February 1943
Ringo Starr
7th July 1940

I want to be able to type:

print(john)
print(george)
print(paul)
print(ringo)

To get the same output, however when i type this and remove the bottom 4 print lines, i get this

John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940

My understanding up until now is that the __repr__(self) can only read one line of code, which would be john, but that's where my knowledge stops.

ANY help is more than appreciated! if you need more info please ask, I'm quite new to this as I'm in my first year at university so I appreciate your patience and help!:)

Body:
Any return command will simply exit the function, so having multiple return commands at the same level would never work in Python.

The issue with your code is that you should be using the key word self within your __repr__ definition, that way you can access it with all four instances that you create with

john = Person('John','Lennon','8th','October','1940')
paul = Person('Paul','McCartney','18th','June','1942')
george = Person('George','Harrison','25th','February','1943')
ringo = Person('Ringo','Starr','7th','July','1940')

Those creations of instances of the class Person will also automatically store all the information that you enter, so no need to specify by hand values for john._firstname etc.

To give a clear answer:

class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(self._firstname,
                                         self._surname,
                                         self.d,
                                         self.m,
                                         self..y)

john = Person('John','Lennon','8th','October','1940')
paul = Person('Paul','McCartney','18th','June','1942')
george = Person('George','Harrison','25th','February','1943')
ringo = Person('Ringo','Starr','7th','July','1940')

print(john)
print(paul)
print(george)
print(ringo)


问:
How restore correct state of view after minimize and restore application?
I try to use Mosby. But I have one problem.

I have Activity (view), presenter, model, and viewState.
On activity I have button. When I click on button I call the method from presenter to load data:

```<code>presenter.loadData()
</code>```

Method that load data call 2 methods:

1.view.showProgress

model.getData()

Method model.getData() create ASYNC http request (Retrofit). After request finish than presenter call method from view, view.hideProgress().

OK. This scheme works fine.

But I have one problem.
Steps:

1.Click button on view

2.presenter.loadData()

3.In presenter call view.showProgress() and start async http request

4.Minimize application

5.Activity is destroy

6.As result on viewState call method saveInstanceState() to save current state of view (progress is show)

7.After 5 seconds the network request was finished and presenter try to call view.hideProgress()

8.But Activity does not exist and as result, nothing happened.

9.User return to application

As result call method in viewState restoreInstanceState()

And as result progress show again, because this state saved on viewState (see item 6).

The problem is that the progress must be hidden because network request was successfully finished when application was minimized (not visible for the user).

How can I fix problem?

答:
When you receive HTTP response you should store it somewhere, for example, it can be repository which stores in memory, or maybe some local storage. Then when you call model.getData() you should check if data is already saved, return this data from the model (and if needed send one more HTTP request to get fresher data) if there is no saved data - send HTTP request.
So now, when activity opens you invoke presenter.getData(), it calls view.showProgress() inside and model.getData(), model returns some cached data (if available) and presented calls view.hideProgress()

Body:
I try to use Mosby. But I have one problem.

I have Activity (view), presenter, model, and viewState.
On activity I have button. When I click on button I call the method from presenter to load data:

presenter.loadData()

Method that load data call 2 methods:

1.view.showProgress

model.getData()

Method model.getData() create ASYNC http request (Retrofit). After request finish than presenter call method from view, view.hideProgress().

OK. This scheme works fine.

But I have one problem.
Steps:

1.Click button on view

2.presenter.loadData()

3.In presenter call view.showProgress() and start async http request

4.Minimize application

5.Activity is destroy

6.As result on viewState call method saveInstanceState() to save current state of view (progress is show)

7.After 5 seconds the network request was finished and presenter try to call view.hideProgress()

8.But Activity does not exist and as result, nothing happened.

9.User return to application

As result call method in viewState restoreInstanceState()

And as result progress show again, because this state saved on viewState (see item 6).

The problem is that the progress must be hidden because network request was successfully finished when application was minimized (not visible for the user).

How can I fix problem?


问:
Database architecture for asp.net mvc websites builder system
I want to create the design of a SQL database that will hold the data entered from a dynamic created websites (something like http://www.wufoo.com).
Users of the system will create forms by dragging controls into the form and then they will use the created forms to build a website by including the forms in some pages.
What would be the options that I have when I create the architecture of the database.</p>

答:
Since you do not know what you will get in your DB, how the object will look like; I would suggest using NoSql.

Otherwise you need to create some very abstract table, let's say Form, and then make in inheritable by other tables (ye, you can do that in EF)


答:
Your code contains two bugs.

= is assignment, not comparison. Your function is equivalent to:

```<code>function (item) {
    item = 255;
    item = 0;
}
</code>```

item is a function parameter, i.e. a local variable in the anonymous function. Assigning to item has no effect on the items array:

```<code>var x = 255;
(function (y) { y = 0; })(x);
console.log(x);
// 255
</code>```

Title: Issue forEach JS array

Body:
Your code contains two bugs.

= is assignment, not comparison. Your function is equivalent to:

function (item) {
    item = 255;
    item = 0;
}

item is a function parameter, i.e. a local variable in the anonymous function. Assigning to item has no effect on the items array:

var x = 255;
(function (y) { y = 0; })(x);
console.log(x);
// 255


问:
How to get the latitude and longitude from a Google Map marker in order to update in a form?
I want to make a form that auto-updates the coordinates of a marker.
Here's my part of the script:

```<code>google.maps.event.addListener(map, "click", function(event) {
  marker = new google.maps.Marker({
    position: event.latLng,
    map: map,
  });
  var x = document.getElementById("coordinates");
  if (x.style.display === "none") {
    x.style.display = "block";
  };
  var lati, longi;
  lati = event.latLng;
  longi = event.latLng;
  $("#lat").val(lati);
  $("#lng").val(longi);
});
</code>```

And here's the form:

```<code><div id="coordinates" class="container" style="margin-top: 10px; display: none;">
  <div class="col-sm-5 col-md-5 col-lg-5">
    <input class="form-control" id="lat" name="lat" placeholder="Latitude" type="text" required>
  </div>
  <div class="col-sm-5 col-md-5 col-lg-5">
    <input class="form-control" id="lng" name="lng" placeholder="Longitude" type="text" required>
  </div>
</code>```

答:
You need to use the .lat() and .lng() methods of the google.maps.LatLng object to get the individual fields:

```<code>var lati, longi;
lati = event.latLng.lat();
longi = event.latLng.lng();
$("#lat").val(lati);
$("#lng").val(longi);
</code>```

proof of concept fiddle

code snippet:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  google.maps.event.addListener(map, "click", function(event) {
    marker = new google.maps.Marker({
      position: event.latLng,
      map: map,
    });
    var x = document.getElementById("coordinates");
    if (x.style.display === "none") {
      x.style.display = "block";
    };

    var lati, longi;
    lati = event.latLng.lat();
    longi = event.latLng.lng();
    $("#lat").val(lati);
    $("#lng").val(longi);

  });
}
google.maps.event.addDomListener(window, "load", initialize);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
#map_canvas {
  height: 95%;
  width: 100%;
  margin: 0px;
  padding: 0px
}</code>```

    <input class="form-control" id="lat" name="lat" placeholder="Latitude" type="text" required>

    <input class="form-control" id="lng" name="lng" placeholder="Longitude" type="text" required>

```

Body:
I want to make a form that auto-updates the coordinates of a marker.
Here's my part of the script:

google.maps.event.addListener(map, "click", function(event) {
  marker = new google.maps.Marker({
    position: event.latLng,
    map: map,
  });
  var x = document.getElementById("coordinates");
  if (x.style.display === "none") {
    x.style.display = "block";
  };
  var lati, longi;
  lati = event.latLng;
  longi = event.latLng;
  $("#lat").val(lati);
  $("#lng").val(longi);
});

And here's the form:

    <input class="form-control" id="lat" name="lat" placeholder="Latitude" type="text" required>

    <input class="form-control" id="lng" name="lng" placeholder="Longitude" type="text" required>

Body:
You need to use the .lat() and .lng() methods of the google.maps.LatLng object to get the individual fields:

var lati, longi;
lati = event.latLng.lat();
longi = event.latLng.lng();
$("#lat").val(lati);
$("#lng").val(longi);

proof of concept fiddle

code snippet:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  google.maps.event.addListener(map, "click", function(event) {
    marker = new google.maps.Marker({
      position: event.latLng,
      map: map,
    });
    var x = document.getElementById("coordinates");
    if (x.style.display === "none") {
      x.style.display = "block";
    };

    var lati, longi;
    lati = event.latLng.lat();
    longi = event.latLng.lng();
    $("#lat").val(lati);
    $("#lng").val(longi);

  });
}
google.maps.event.addDomListener(window, "load", initialize);

html,
body,
#map_canvas {
  height: 95%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="coordinates" class="container" style="margin-top: 10px; display: none;">
  <div class="col-sm-5 col-md-5 col-lg-5">
    <input class="form-control" id="lat" name="lat" placeholder="Latitude" type="text" required>
  </div>
  <div class="col-sm-5 col-md-5 col-lg-5">
    <input class="form-control" id="lng" name="lng" placeholder="Longitude" type="text" required>
  </div>
</div>
<div id="map_canvas"></div>