问:
When is the best place to use Task.Result instead of awaiting Task
Whilst I've been using async code in .NET for a while, I've only recently started to research it and understand what's going on.  I've just been going through my code and trying to alter it so if a task can be done in parallel to some work, then it is. So for example:

```<code>var user = await _userRepo.GetByUsername(User.Identity.Name);

//Some minor work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

return user;
</code>```

Now becomes:

```<code>var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(userTask.Result, DateTime.Now);

return user;
</code>```

My understand is that the user object is now being fetched from the database WHILST some unrelated work is going on. However, things I've seen posted imply that result should be used rarely and await is preferred but I don't understand why I'd want to wait for my user object to be fetched if I can be performing some other independant logic at the same time?

答:
Async await does not mean that several threads will be running your code.

However, it will lower the time your thread will be waiting idly for processes to finish, thus finishing earlier.

Whenever the thread normally would have to wait idly for something to finish, like waiting for a web page to download, a database query to finish, a disk write to finish, the async-await thread will not be waiting idly until the data is written / fetched, but looks around if it can do other things instead, and come back later after the awaitable task is finished.

This has been described with a cook analogy in this inverview with Eric Lippert. Search somewhere in the middle for async await.

Eric Lippert compares async-await with one(!) cook who has to make breakfast. After he starts toasting the bread he could wait idly until the bread is toasted before putting on the kettle for tea, wait until the water boils before putting the tea leaves in the teapot, etc.

An async-await cook, wouldn't wait for the toasted bread, but put on the kettle, and while the water is heating up he would put the tea leaves in the teapot.

Whenever the cook has to wait idly for something, he looks around to see if he can do something else instead.

A thread in an async function will do something similar. Because the function is async, you know there is somewhere an await in the function. In fact, if you forget to program the await, your compiler will warn you.

When your thread meets the await, it goes up its call stack to see if it can do something else, until it sees an await, goes up the call stack again, etc. Once everyone is waiting, he goes down the call stack and starts waiting idly until the first awaitable process is finished.

After the awaitable process is finished the thread will continue processing the statements after the await until he sees an await again.

It might be that another thread will continue processing the statements that come after the await (you can see this in the debugger by checking the thread ID). However this other thread has the context of the original thread, so it can act as if it was the original thread. No need for mutexes, semaphores, IsInvokeRequired (in winforms) etc. For you it seems as if there is one thread.

Sometimes your cook has to do something that takes up some time without idly waiting, like slicing tomatoes. In that case it might be wise to hire a different cook and order him to do the slicing. In the mean time your cook can continue with the eggs that just finished boiling and needed peeling.

In computer terms this would be if you had some big calculations without waiting for other processes. Note the difference with for instance writing data to disk. Once your thread has ordered that the data needs to be written to disk, it normally would wait idly until the data has been written. This is not the case when doing big calculations.

You can hire the extra cook using Task.Run

```<code>async Task<DateTime> CalculateSunSet()
{
    // start fetching sunset data. however don't wait for the result yet
    // you've got better things to do:
    Task<SunsetData> taskFetchData = FetchSunsetData();

    // because you are not awaiting your thread will do the following:
    Location location = FetchLocation();

    // now you need the sunset data, start awaiting for the Task:
    SunsetData sunsetData = await taskFetchData;

    // some big calculations are needed, that take 33 seconds,
    // you want to keep your caller responsive, so start a Task
    // this Task will be run by a different thread:
    Task<DateTime> taskBigCalculations = Taks.Run( () => BigCalculations(sunsetData, location);

    // again no await: you are still free to do other things
    ...
    // before returning you need the result of the big calculations.
    // wait until big calculations are finished, keep caller responsive:
    DateTime result = await taskBigCalculations;
    return result;
}
</code>```

Body:
Whilst I've been using async code in .NET for a while, I've only recently started to research it and understand what's going on.  I've just been going through my code and trying to alter it so if a task can be done in parallel to some work, then it is. So for example:

var user = await _userRepo.GetByUsername(User.Identity.Name);

//Some minor work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

return user;

Now becomes:

var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(userTask.Result, DateTime.Now);

return user;

My understand is that the user object is now being fetched from the database WHILST some unrelated work is going on. However, things I've seen posted imply that result should be used rarely and await is preferred but I don't understand why I'd want to wait for my user object to be fetched if I can be performing some other independant logic at the same time?

Body:
Async await does not mean that several threads will be running your code.

However, it will lower the time your thread will be waiting idly for processes to finish, thus finishing earlier.

Whenever the thread normally would have to wait idly for something to finish, like waiting for a web page to download, a database query to finish, a disk write to finish, the async-await thread will not be waiting idly until the data is written / fetched, but looks around if it can do other things instead, and come back later after the awaitable task is finished.

This has been described with a cook analogy in this inverview with Eric Lippert. Search somewhere in the middle for async await.

Eric Lippert compares async-await with one(!) cook who has to make breakfast. After he starts toasting the bread he could wait idly until the bread is toasted before putting on the kettle for tea, wait until the water boils before putting the tea leaves in the teapot, etc.

An async-await cook, wouldn't wait for the toasted bread, but put on the kettle, and while the water is heating up he would put the tea leaves in the teapot.

Whenever the cook has to wait idly for something, he looks around to see if he can do something else instead.

A thread in an async function will do something similar. Because the function is async, you know there is somewhere an await in the function. In fact, if you forget to program the await, your compiler will warn you.

When your thread meets the await, it goes up its call stack to see if it can do something else, until it sees an await, goes up the call stack again, etc. Once everyone is waiting, he goes down the call stack and starts waiting idly until the first awaitable process is finished.

After the awaitable process is finished the thread will continue processing the statements after the await until he sees an await again.

It might be that another thread will continue processing the statements that come after the await (you can see this in the debugger by checking the thread ID). However this other thread has the context of the original thread, so it can act as if it was the original thread. No need for mutexes, semaphores, IsInvokeRequired (in winforms) etc. For you it seems as if there is one thread.

Sometimes your cook has to do something that takes up some time without idly waiting, like slicing tomatoes. In that case it might be wise to hire a different cook and order him to do the slicing. In the mean time your cook can continue with the eggs that just finished boiling and needed peeling.

In computer terms this would be if you had some big calculations without waiting for other processes. Note the difference with for instance writing data to disk. Once your thread has ordered that the data needs to be written to disk, it normally would wait idly until the data has been written. This is not the case when doing big calculations.

You can hire the extra cook using Task.Run

async Task<DateTime> CalculateSunSet()
{
    // start fetching sunset data. however don't wait for the result yet
    // you've got better things to do:
    Task<SunsetData> taskFetchData = FetchSunsetData();

    // because you are not awaiting your thread will do the following:
    Location location = FetchLocation();

    // now you need the sunset data, start awaiting for the Task:
    SunsetData sunsetData = await taskFetchData;

    // some big calculations are needed, that take 33 seconds,
    // you want to keep your caller responsive, so start a Task
    // this Task will be run by a different thread:
    Task<DateTime> taskBigCalculations = Taks.Run( () => BigCalculations(sunsetData, location);

    // again no await: you are still free to do other things
    ...
    // before returning you need the result of the big calculations.
    // wait until big calculations are finished, keep caller responsive:
    DateTime result = await taskBigCalculations;
    return result;
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Can't open Firefox-based Browser
I tried to open modified FireFox browser using Selenium WebDriver.
(This Firefox-based browser as same as original Firefox, just with additional functionality.)

This Browser opens and then I got Error:

["OpenQA.Selenium.WebDriverException" in WebDriver.dll]
  TypeError: Given browserName [object String] "firefox", but my name is [object String] "anotherbrowser"

My code[C#]:

```<code>var path = new FirefoxBinary(@"C:\FireFox_BasedBrowser\anotherbrowser.exe");
IWebDriver driver = new FirefoxDriver(path, null); //here's error
</code>```

After searching I found this advice on Java:

```<code>String bname = "Browser name";
FirefoxOptions options = new FirefoxOptions();
options.setBinary("Path to browser binary");
options.setCapability("browserName", bname);
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);
</code>```

I tried to rewrite it into C#:

```<code>DesiredCapabilities cap = DesiredCapabilities.Firefox();
cap.SetCapability("browserName", "anotherbrowser");
cap.SetCapability("firefox_binary", @"C:\FireFox_BasedBrowser\anotherbrowser.exe");
IWebDriver driver = new FirefoxDriver(cap); //here's error
</code>```

But I also got an error:

["System.ArgumentException" in WebDriver.dll] There is already an option for the browserName capability. Please use
  the  instead.

Please, help me, I can't find any solutions.

P.s. I can't use original Firefox browser, because it doesn't have same advantages as this modified Firefox.

答:
Use FirefoxDriverService.CreateDefaultService(...) to define another path for Firefox:

var service = FirefoxDriverService.CreateDefaultService(@"C:\drivers", "geckodriver.exe");
service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
var driver = new FirefoxDriver(service);
```

ContentLicense: CC BY-SA 3.0

Title: Can't open Firefox-based Browser

Body:
I tried to open modified FireFox browser using Selenium WebDriver.
(This Firefox-based browser as same as original Firefox, just with additional functionality.)

This Browser opens and then I got Error:

["OpenQA.Selenium.WebDriverException" in WebDriver.dll]
  TypeError: Given browserName [object String] "firefox", but my name is [object String] "anotherbrowser"

My code[C#]:

var path = new FirefoxBinary(@"C:\FireFox_BasedBrowser\anotherbrowser.exe");
IWebDriver driver = new FirefoxDriver(path, null); //here's error

After searching I found this advice on Java:

String bname = "Browser name";
FirefoxOptions options = new FirefoxOptions();
options.setBinary("Path to browser binary");
options.setCapability("browserName", bname);
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);

I tried to rewrite it into C#:

DesiredCapabilities cap = DesiredCapabilities.Firefox();
cap.SetCapability("browserName", "anotherbrowser");
cap.SetCapability("firefox_binary", @"C:\FireFox_BasedBrowser\anotherbrowser.exe");
IWebDriver driver = new FirefoxDriver(cap); //here's error

But I also got an error:

["System.ArgumentException" in WebDriver.dll] There is already an option for the browserName capability. Please use
  the  instead.

Please, help me, I can't find any solutions.

P.s. I can't use original Firefox browser, because it doesn't have same advantages as this modified Firefox.


问:
When programming for iphone how do you use data for multiple views?
I am a objective-c newbie and I was wondering how do you use data obtained from one view in another? For example I ask a user for a text input, and this text input then changes a label when a button is hit. I want this information for another label in a different view. how would I get it?
Thanks</p>

答: There are many ways to share data across views (or classes) in objective-c.  One common method is to create a Singleton object that functions as a global object for your application.  Here's a great tutorial about using Singletons in objective-c for global data.</p>

ContentLicense: CC BY-SA 2.5


问:
error: anachronistic old-style base class initializer [-fpermissive]
I have this constructor which give an error on compilation :-

```<code>Time::Time(short y,short m,short d,short h,short mi,short s):
        (*this).y(y);
        (*this).m(m);
        (*this).d(d);
        (*this).h(h);
        (*this).mi(mi);
        (*this).s(s);   {};
</code>```

here is full error:-

```<code>Time.cpp: In constructor ‘Time::Time(short int, short int, short int, short int, short int, short int)’:
Time.cpp:22:2: error: anachronistic old-style base class initializer [-fpermissive]
  (*this).y(y);
  ^
Time.cpp:21:61: error: unnamed initializer for ‘Time’, which has no base classes
 Time::Time(short y,short m,short d,short h,short mi,short s):
                                                             ^
Time.cpp:22:9: error: expected ‘{’ before ‘.’ token
  (*this).y(y);
         ^
Time.cpp: At global scope:
Time.cpp:22:9: error: expected unqualified-id before ‘.’ token
Time.cpp:23:4: error: expected unqualified-id before ‘this’
  (*this).m(m);
    ^~~~
Time.cpp:23:4: error: expected ‘)’ before ‘this’
Time.cpp:24:4: error: expected unqualified-id before ‘this’
  (*this).d(d);
    ^~~~
Time.cpp:24:4: error: expected ‘)’ before ‘this’
Time.cpp:25:4: error: expected unqualified-id before ‘this’
  (*this).h(h);
    ^~~~
Time.cpp:25:4: error: expected ‘)’ before ‘this’
Time.cpp:26:4: error: expected unqualified-id before ‘this’
  (*this).mi(mi);
    ^~~~
Time.cpp:26:4: error: expected ‘)’ before ‘this’
Time.cpp:27:4: error: expected unqualified-id before ‘this’
  (*this).s(s);  {};
    ^~~~
Time.cpp:27:4: error: expected ‘)’ before ‘this’
Time.cpp:27:17: error: expected unqualified-id before ‘{’ token
  (*this).s(s);  {};
                 ^
</code>```

As a noob I have no idea what is going on. On googling ,I only find one stackoverflow link which also doesn't help.

答:
When initialising using an initializer list, you need to seperate it by ,, not ;. And ditch the this

```<code>Time::Time(short _y,short _m,short _d,short _h,short _mi,short _s):
    y(_y),
    m(_m),
    d(_d),
    h(_h),
    mi(_mi),
    s(_s)
{
}
</code>```

I would agree that it's not a great error message, in this case.

Body:
I have this constructor which give an error on compilation :-

Time::Time(short y,short m,short d,short h,short mi,short s):
        (*this).y(y);
        (*this).m(m);
        (*this).d(d);
        (*this).h(h);
        (*this).mi(mi);
        (*this).s(s);   {};

here is full error:-

Time.cpp: In constructor ‘Time::Time(short int, short int, short int, short int, short int, short int)’:
Time.cpp:22:2: error: anachronistic old-style base class initializer [-fpermissive]
  (*this).y(y);
  ^
Time.cpp:21:61: error: unnamed initializer for ‘Time’, which has no base classes
 Time::Time(short y,short m,short d,short h,short mi,short s):
                                                             ^
Time.cpp:22:9: error: expected ‘{’ before ‘.’ token
  (*this).y(y);
         ^
Time.cpp: At global scope:
Time.cpp:22:9: error: expected unqualified-id before ‘.’ token
Time.cpp:23:4: error: expected unqualified-id before ‘this’
  (*this).m(m);
    ^~~~
Time.cpp:23:4: error: expected ‘)’ before ‘this’
Time.cpp:24:4: error: expected unqualified-id before ‘this’
  (*this).d(d);
    ^~~~
Time.cpp:24:4: error: expected ‘)’ before ‘this’
Time.cpp:25:4: error: expected unqualified-id before ‘this’
  (*this).h(h);
    ^~~~
Time.cpp:25:4: error: expected ‘)’ before ‘this’
Time.cpp:26:4: error: expected unqualified-id before ‘this’
  (*this).mi(mi);
    ^~~~
Time.cpp:26:4: error: expected ‘)’ before ‘this’
Time.cpp:27:4: error: expected unqualified-id before ‘this’
  (*this).s(s);  {};
    ^~~~
Time.cpp:27:4: error: expected ‘)’ before ‘this’
Time.cpp:27:17: error: expected unqualified-id before ‘{’ token
  (*this).s(s);  {};
                 ^

As a noob I have no idea what is going on. On googling ,I only find one stackoverflow link which also doesn't help.

Body:
When initialising using an initializer list, you need to seperate it by ,, not ;. And ditch the this

Time::Time(short _y,short _m,short _d,short _h,short _mi,short _s):
    y(_y),
    m(_m),
    d(_d),
    h(_h),
    mi(_mi),
    s(_s)
{
}

I would agree that it's not a great error message, in this case.


问:
How do I segue to a new view controller after a short timeout?
I want to show the user a title screen of the app name firstly and then, after about 2 seconds, the view should proceed to a new view controller.

So far, I have a segue with an identifier. I see a lot of tutorials use IBActions/IBOutlets but I'm not sure if I would use one here since there's no single item that would trigger the segue aside from the timeout.

答:
Just use DispatchQueue.main.asyncAfter(deadline:) in viewDidLoad. This code triggers the segue with the given identifier after a 2 seconds delay:

```<code>DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
    self.performSegue(withIdentifier: "your segue's identifier", sender: self)
}
</code>```

Body:
Just use DispatchQueue.main.asyncAfter(deadline:) in viewDidLoad. This code triggers the segue with the given identifier after a 2 seconds delay:

DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
    self.performSegue(withIdentifier: "your segue's identifier", sender: self)
}


问:
If clause optimization
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

```<code>if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}
</code>```

Is there a cleaner way to write this condition?

Thanks.

答:
In any case, you need to separate the action from the test:

```<code>if (shouldPerform()) {
    perform_action_and_exit();
}
</code>```

Sometimes, early exits make the code clear:

```<code>boolean shouldPerform() {
    if (group != G1) {
        return true;
    }
    if (role != R1) {
        return false;
    }
    if (level > 2) {
        return false;
    }
    if (class == C1) {
        return true;
    }
    if (level != 1) {
        return false;
    }
    return class == C2 || class == C3;
}
</code>```

Sometimes, they don't. Just look at this and decide if you can understand it at first glance. You may have been told something like

The only privileged group is G1, others are unrestricted.

Only R1 can do a privileged action...

...

and then this early exits map exactly to the description.

In no case I'd recommend a complicated boolean expression. Anything spanning more than a line or two is too hard to understand. Using methods or variables with simple expressions can lead to much more readable code.

Don't be bothered with efficiency here. It's quite possible that all your versions of the condition will lead to equally fast code as the JVM inlines methods and transforms expression aggressively. So don't needlessly micro-optimize, that's what the machine is for.

Moreover, I'd bet that the execution of perform_action_and_exit takes at least four orders of magnitude longer than the test. The test may take some tens of nanoseconds (pessimistically assuming branch mispredictions), while the action probably accesses a database which means some milliseconds.

Title: If clause optimization

Body:
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}

Is there a cleaner way to write this condition?

Thanks.

Body:
In any case, you need to separate the action from the test:

if (shouldPerform()) {
    perform_action_and_exit();
}

Sometimes, early exits make the code clear:

boolean shouldPerform() {
    if (group != G1) {
        return true;
    }
    if (role != R1) {
        return false;
    }
    if (level > 2) {
        return false;
    }
    if (class == C1) {
        return true;
    }
    if (level != 1) {
        return false;
    }
    return class == C2 || class == C3;
}

Sometimes, they don't. Just look at this and decide if you can understand it at first glance. You may have been told something like

The only privileged group is G1, others are unrestricted.

Only R1 can do a privileged action...

...

and then this early exits map exactly to the description.

In no case I'd recommend a complicated boolean expression. Anything spanning more than a line or two is too hard to understand. Using methods or variables with simple expressions can lead to much more readable code.

Don't be bothered with efficiency here. It's quite possible that all your versions of the condition will lead to equally fast code as the JVM inlines methods and transforms expression aggressively. So don't needlessly micro-optimize, that's what the machine is for.

Moreover, I'd bet that the execution of perform_action_and_exit takes at least four orders of magnitude longer than the test. The test may take some tens of nanoseconds (pessimistically assuming branch mispredictions), while the action probably accesses a database which means some milliseconds.


问:
Include Image src to LinkExtractor Scrapy CrawlSpider
Im working on crawling on a site and Im using LinkExtractor from scrapy to crawl links and determine their response status. </p>

<p>Moreover, I also want to use the Link Extractor to get image src's from the site. I have a code and it works well with the sites urls but i cant seem to get the images. since it wont log on the console. </p>

```<code>handle_httpstatus_list = [404,502]
# allowed_domains = [''mydomain']

start_urls = ['somedomain.com/']

http_user = '###'
http_pass = '#####'

rules = (
    Rule(LinkExtractor(allow=('domain.com',),canonicalize = True, unique = True), process_links='filter_links', follow = False, callback='parse_local_link'),
    Rule(LinkExtractor(allow=('cdn.domain.com'),tags = ('img',),attrs=('src',),canonicalize = True, unique = True), follow = False, callback='parse_image_link'),
)

def filter_links(self,links):
    for link in

def parse_local_link(self, response):
    if response.status != 200:
        item = LinkcheckerItem()
        item['url'] = response.url
        item['status'] = response.status
        item['link_type'] = 'local'
        item['referer'] = response.request.headers.get('Referer',None)
        yield item

def parse_image_link(self, response):
    print "Got image link"
    if response.status != 200:
        item = LinkcheckerItem()
        item['url'] = response.url
        item['status'] = response.status
        item['link_type'] = 'img'
        item['referer'] = response.request.headers.get('Referer',None)
        yield item
</code>```

答:
I have been using Scarpy for over 2 years and I always use start_requests() method for start scraping URLs instead of start_urls and LinkExtractor

Instead of getting confused by above, simply use this

```<code>class MySpider(scrapy.Spider):
    name = "myspider"

    def start_requests(self):

        urls_to_scrape = ["abc.com", "abc.com2"]

        for url in urls_to_scrape:

            yield Request(url=url, callback=self.my_callback)

    def my_callback(self, response):

        for img in response.css("img"):

            image_here = img.css("::attr(src)").extract_first()
</code>```

Body:
Im working on crawling on a site and Im using LinkExtractor from scrapy to crawl links and determine their response status.

Moreover, I also want to use the Link Extractor to get image src's from the site. I have a code and it works well with the sites urls but i cant seem to get the images. since it wont log on the console.

handle_httpstatus_list = [404,502]
# allowed_domains = [''mydomain']

start_urls = ['somedomain.com/']

http_user = '###'
http_pass = '#####'

rules = (
    Rule(LinkExtractor(allow=('domain.com',),canonicalize = True, unique = True), process_links='filter_links', follow = False, callback='parse_local_link'),
    Rule(LinkExtractor(allow=('cdn.domain.com'),tags = ('img',),attrs=('src',),canonicalize = True, unique = True), follow = False, callback='parse_image_link'),
)

def filter_links(self,links):
    for link in

def parse_local_link(self, response):
    if response.status != 200:
        item = LinkcheckerItem()
        item['url'] = response.url
        item['status'] = response.status
        item['link_type'] = 'local'
        item['referer'] = response.request.headers.get('Referer',None)
        yield item

def parse_image_link(self, response):
    print "Got image link"
    if response.status != 200:
        item = LinkcheckerItem()
        item['url'] = response.url
        item['status'] = response.status
        item['link_type'] = 'img'
        item['referer'] = response.request.headers.get('Referer',None)
        yield item

Body:
I have been using Scarpy for over 2 years and I always use start_requests() method for start scraping URLs instead of start_urls and LinkExtractor

Instead of getting confused by above, simply use this

class MySpider(scrapy.Spider):
    name = "myspider"

    def start_requests(self):

        urls_to_scrape = ["abc.com", "abc.com2"]

        for url in urls_to_scrape:

            yield Request(url=url, callback=self.my_callback)

    def my_callback(self, response):

        for img in response.css("img"):

            image_here = img.css("::attr(src)").extract_first()


问:
Query speed based on order of columns
Does the order of the column types in your database have any affect on the query time?

For example, would a table with mixed ordering (INT, TEXT, VARCHAR, INT, TEXT) be slower to query than a table with consecutive types (INT, INT, VARCHAR, TEXT, TEXT)?

答:
I would suggest that there is absolutely no [significant] difference no matter how you order the columns.

PostgreSQL: http://social.msdn.microsoft.com/Forums/en-US/sqldatabaseengine/thread/a7ce8a90-22fc-456d-9f56-4956c42a78b0

SQL Server:
http://social.msdn.microsoft.com/Forums/en/sqldatabaseengine/thread/36713a82-315d-45ef-b74e-5f342e0f22fa

I suspect the same for MySQL.

All data is read in pages, so if your data fits into a single page it does not matter how you order the columns.  If a disk block size is 2K, 4K, it will take in multiple to satisfy the "8K page request".  If the disk block size is 64K (for large DB systems), you would already be buffering other data.

Not only that, if a record is requested, it will normally retrieve all pages for the record, including the overflow to pages 2 and 3 if the data spans multiple pages.  The columns are then worked out from the data retrieved.  SQL Server has a limit on in-page data, which is about 8060 bytes.  Anything larger is stored off the main data page, similar to TOAST for PostgreSQL and is not retrieved if the column is not used.  It still does not matter where the column is in the order.

In SQL Server for example, multiple bit fields are stored together in a bit patterned mask - this is irrespective of whether you put the columns next to each other.  I would suspect MySQL and PostgreSQL to do much the same to optimize space.

Note: [significant] - the only reason for this qualification is that, possibly, when extracting a particular column from a data page, having it in the beginning helps because the low-level assembly calls do not have to seek far in the memory block.

Title: Query speed based on order of columns


问:
Compile and link 32-bit program from Visual Studio 2008
I asked this same basic question yesterday, but had not got far enough to get a clear idea of the issue. Basically, this is the error I now get when building my app:

.\Debug\HotSync.obj : fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

I assume this means that I'm compiling 64-bit object modules and then trying to link a 32-bit executable. So is this a matter of the compiler itself, or of an option given to the compiler? This project was previously a VC++ 2003 project, so has always been 32-bit.

I might mention that the only versions of cl.exe that I can find are in the amd64 and x86-amd64 subdirectories of VC\bin. I have to manually add one of these paths to the "VC++ Directories" list, but the results are the same for either.

My hosting PC is AMD running Windows 7 64-bit, but I would hope that I can still build programs that will run on XP. Anyone know how to do this?

答:
A default installation of Visual Studio 2008 should have put an x86 cl.exe and associated compiler binaries in:

```<code>C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\
</code>```

on a Win7 x64 system.

If you don't have a cl.exe there (ie., 'above' the amd64 or x86_amd64 directories), then you might want to consider reinstalling Visual Studio.

Note that the compiler in the amd64 directory targets x64 systems and is itself built to run on x64 systems.  The compiler in the x86_amd64 directory also targets x64 systems, but is itself an x86 binary (ie., it cross compiles to x64 from a x86 32-bit system).

You should also have a short-cut in the Visual Studio 2008 program group (or whatever that might be called in Win7):

```<code>"Microsoft Visual Studio 2008" | "Visual Studio Tools" | "Visual Studio 2008 Command Prompt"
</code>```

that opens a command window that initially says:

```<code>Setting environment for using Microsoft Visual Studio 2008 x86 tools.
</code>```

And running the cl command there with no options should say something like:

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86

Again - if none of this is there for you, you need a reinstall.

Also, make sure that the project configurations for all of your projects involved in the build are set to Win32 and not x64.

Body:
A default installation of Visual Studio 2008 should have put an x86 cl.exe and associated compiler binaries in:

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\

on a Win7 x64 system.

If you don't have a cl.exe there (ie., 'above' the amd64 or x86_amd64 directories), then you might want to consider reinstalling Visual Studio.

Note that the compiler in the amd64 directory targets x64 systems and is itself built to run on x64 systems.  The compiler in the x86_amd64 directory also targets x64 systems, but is itself an x86 binary (ie., it cross compiles to x64 from a x86 32-bit system).

You should also have a short-cut in the Visual Studio 2008 program group (or whatever that might be called in Win7):

"Microsoft Visual Studio 2008" | "Visual Studio Tools" | "Visual Studio 2008 Command Prompt"

that opens a command window that initially says:

Setting environment for using Microsoft Visual Studio 2008 x86 tools.

And running the cl command there with no options should say something like:

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86

Again - if none of this is there for you, you need a reinstall.

Also, make sure that the project configurations for all of your projects involved in the build are set to Win32 and not x64.


问:
PHP Search filter sort results alphabetically
I'm working on a little webcatalog with a search function. I'm using the software Eshop in Joomla. There is a filter function for manufacturers, but these results aren't displayed alphabetically.

I've looked around for solutions, but I can't get it working. This is the code:

```<code><?php
if (!empty($filterData['manufacturer_ids'])){
    $manufacturerIds = $filterData['manufacturer_ids'];
}
else{
    $manufacturerIds = array();
}

foreach ($manufacturers as $manufacturer){?>
    <li>
        <label class="checkbox">
            <input class="manufacturer" onclick="eshop_ajax_products_filter('manufacturer');" type="checkbox" name="manufacturer_ids[]" value="<?php echo $manufacturer->manufacturer_id; ?>" <?php if (in_array($manufacturer->manufacturer_id, $manufacturerIds)) echo 'checked="checked"'; ?>>
            <?php echo $manufacturer->manufacturer_name; ?><span class="badge badge-info"><?php echo $manufacturer->number_products;?></span>
        </label>
    </li>
<?php }?>
</code>```

Can anyone help me?

This is the current view

答:
You can use the sort function and I would suggest using the SORT_STRING optional parameter to give you the following.

```<code>$manufacturers = sort($manufacturers, SORT_STRING);
</code>```

This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

...

SORT_STRING - compare items as strings

Edit:

After confirming the data structure, this is an array of objects and requires a custom sorting function. Therefore, you should use usort().

This function will sort an array by its values using a user-supplied
  comparison function. If the array you wish to sort needs to be sorted
  by some non-trivial criteria, you should use this function.

So you first define the function that compares the strings for the manufacturer_name property.

```<code>function cmp($a, $b)
{
    return strcmp($a->manufacturer_name, $b->manufacturer_name);
}

usort($manufacturers , "cmp");
</code>```

Body:
I'm working on a little webcatalog with a search function. I'm using the software Eshop in Joomla. There is a filter function for manufacturers, but these results aren't displayed alphabetically.

I've looked around for solutions, but I can't get it working. This is the code:

<?php
if (!empty($filterData['manufacturer_ids'])){
    $manufacturerIds = $filterData['manufacturer_ids'];
}
else{
    $manufacturerIds = array();
}

foreach ($manufacturers as $manufacturer){?>

            <input class="manufacturer" onclick="eshop_ajax_products_filter('manufacturer');" type="checkbox" name="manufacturer_ids[]" value="<?php echo $manufacturer->manufacturer_id; ?>" <?php if (in_array($manufacturer->manufacturer_id, $manufacturerIds)) echo 'checked="checked"'; ?>>
            <?php echo $manufacturer->manufacturer_name; ?><?php echo $manufacturer->number_products;?>

<?php }?>

Can anyone help me?

This is the current view

Body:
You can use the sort function and I would suggest using the SORT_STRING optional parameter to give you the following.

$manufacturers = sort($manufacturers, SORT_STRING);

This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

...

SORT_STRING - compare items as strings

Edit:

After confirming the data structure, this is an array of objects and requires a custom sorting function. Therefore, you should use usort().

This function will sort an array by its values using a user-supplied
  comparison function. If the array you wish to sort needs to be sorted
  by some non-trivial criteria, you should use this function.

So you first define the function that compares the strings for the manufacturer_name property.

function cmp($a, $b)
{
    return strcmp($a->manufacturer_name, $b->manufacturer_name);
}

usort($manufacturers , "cmp");


问:
Yobit c#, jsonconvert.deserialize
From https://yobit.net/api/3/depth/btc_usd?limit=5 i have

```<code>    string response = { "btc_usd":{ "asks":[[6657,0.06689384],[6680.47685546,0.001],[6680.47690546,0.00526334],[6697,0.05],[6698,0.05]],"bids":[[6656,0.02371773],[6640.00000001,0.0297727],[6640,0.34752146],[6637.46352566,0.0011574],[6634,0.00424518]]}}
</code>```

I want to deserialize this.
I created some classes

```<code>public class Orderbook
{
    [JsonProperty("asks")]
    public List<BidAsk> asks { get; set; }

    [JsonProperty("bids")]
    public List<BidAsk> bids { get; set; }
}

public class BidAsk
{
    public decimal price { get; set; }
    public decimal volume { get; set; }
}

var jsonResponse = JsonConvert.DeserializeObject<Orderbook>(response);
</code>```

After this operation i got:
jsonResponse.asks = null
jsonResponse.bids = null

What I've done wrong in deserialization?

答:
There's an extra level for the currency. Try something like:

```<code>public class Orderbook
{
    [JsonProperty("btc_usd")]
    public Currency BTCToUSD{ get; set; }
}

public class Currency
{
    [JsonProperty("asks")]
    public double[][] asks { get; set; }

    [JsonProperty("bids")]
    public double[][] bids { get; set; }
}

var jsonResponse = JsonConvert.DeserializeObject<Orderbook>(response);
</code>```

Note I've changed the bid/asks to arrays of arrays of doubles as that's how they are in your example.

You might want to look into decimal too, not sure how Json.NET handles it, but when dealing with finance you probably want to be cautious with floating precision.

Title: Yobit c#, jsonconvert.deserialize

Body:
From https://yobit.net/api/3/depth/btc_usd?limit=5 i have

    string response = { "btc_usd":{ "asks":[[6657,0.06689384],[6680.47685546,0.001],[6680.47690546,0.00526334],[6697,0.05],[6698,0.05]],"bids":[[6656,0.02371773],[6640.00000001,0.0297727],[6640,0.34752146],[6637.46352566,0.0011574],[6634,0.00424518]]}}

I want to deserialize this.
I created some classes

public class Orderbook
{
    [JsonProperty("asks")]
    public List<BidAsk> asks { get; set; }

    [JsonProperty("bids")]
    public List<BidAsk> bids { get; set; }
}

public class BidAsk
{
    public decimal price { get; set; }
    public decimal volume { get; set; }
}

var jsonResponse = JsonConvert.DeserializeObject<Orderbook>(response);

After this operation i got:
jsonResponse.asks = null
jsonResponse.bids = null

What I've done wrong in deserialization?

Body:
There's an extra level for the currency. Try something like:

public class Orderbook
{
    [JsonProperty("btc_usd")]
    public Currency BTCToUSD{ get; set; }
}

public class Currency
{
    [JsonProperty("asks")]
    public double[][] asks { get; set; }

    [JsonProperty("bids")]
    public double[][] bids { get; set; }
}

var jsonResponse = JsonConvert.DeserializeObject<Orderbook>(response);

Note I've changed the bid/asks to arrays of arrays of doubles as that's how they are in your example.

You might want to look into decimal too, not sure how Json.NET handles it, but when dealing with finance you probably want to be cautious with floating precision.


问:
How can i seperate/split part of string messege in node red
I received this message:

```<code> "data: "{"cmd":"gw","seqno":515816,"EUI":"000DB53113683569","ts":1510584501221,"fcnt":1,"port":2,"freq":868100000,"toa":1482,"dr":"SF12 BW125 4/5","ack":false,"gws":[{"rssi":-71,"snr":9.5,"ts":1510584501221,"time":"2017-11-13T14:48:21.218869Z","gweui":"B827EBFFFF6A14DD","lat":50.0751806,"lon":14.4022641}],"bat":255,"data":"0002560000000000000000"}""
</code>```

I need to put away the "data: " and on the end the "

I need just the JSON message if I use JSON node it just writes me an error because of the "data: "

答:
As an alternative you could add the missing  {} and then JSON.parse.

```<code>var string = "{" + msg.payload +"}"
var dataObject = JSON.parse(string)

msg.payload = dataObject.data
return msg
</code>```

Body:
I received this message:

 "data: "{"cmd":"gw","seqno":515816,"EUI":"000DB53113683569","ts":1510584501221,"fcnt":1,"port":2,"freq":868100000,"toa":1482,"dr":"SF12 BW125 4/5","ack":false,"gws":[{"rssi":-71,"snr":9.5,"ts":1510584501221,"time":"2017-11-13T14:48:21.218869Z","gweui":"B827EBFFFF6A14DD","lat":50.0751806,"lon":14.4022641}],"bat":255,"data":"0002560000000000000000"}""

I need to put away the "data: " and on the end the "

I need just the JSON message if I use JSON node it just writes me an error because of the "data: "

Body:
As an alternative you could add the missing  {} and then JSON.parse.

var string = "{" + msg.payload +"}"
var dataObject = JSON.parse(string)

msg.payload = dataObject.data
return msg


问:
Groovy: Method definition not expected here
I'm sure this is a simple fix but I'm new to programming in general and Groovy in particular.

I am trying to follow this guide to enable slack notifications in a Jenkins 2 pipeline job but pasting and customizing the final code block is giving me the following error;

```<code>Method definition not expected here. Please define the method at an appropriate place or perhaps try using a block/Closure instead.
</code>```

This is my code right now, although I've substituted a few bits for security. The error is occurring at the def notifyBuild(String buildStatus = 'STARTED') { line.

```<code>node('on-demand-t2large'){
    stage ('Checkout') {
        checkout( checkout stuff here )
    }

    stage ('Build') {
        try {
            notifyBuild('STARTED')

            dir("place") {
                sh 'script name'
            }
        }
        catch (e) {
            // If there was an exception thrown, the build failed
            currentBuild.result = "FAILED"
            throw e
        }
        finally {
            // Success or failure, always send notifications
            notifyBuild(currentBuild.result)
        }

        def notifyBuild(String buildStatus = 'STARTED') {
            // build status of null means successful
            buildStatus =  buildStatus ?: 'SUCCESSFUL'

            // Default values
            def colorName = 'RED'
            def colorCode = '#FF0000'
            def subject = "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'"
            def summary = "${subject} (${env.BUILD_URL})"
            def details = """<p>STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
            <p>Check console output at "<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>"</p>"""

            // Override default values based on build status
            if (buildStatus == 'STARTED') {
                color = 'YELLOW'
                colorCode = '#FFFF00'
            } else if (buildStatus == 'SUCCESSFUL') {
                color = 'GREEN'
                colorCode = '#00FF00'
            } else {
                color = 'RED'
                colorCode = '#FF0000'
            }

            // Send notifications
            slackSend (channel: '@me', color: colorCode, message: summary)
        }
    }
}
</code>```

I understand from some googling that groovy doesn't accept inner class definition, but as new as I am to programming I don't know how to fix it. Any help (with explanations so I can learn!) would be appreciated.

答:
You can use Closures http://groovy-lang.org/closures.html</p>

```<code>node('on-demand-t2large') {
    def notifyBuild = { String buildStatus ->
        // build status of null means successful
        buildStatus =  buildStatus ?: 'SUCCESSFUL'

        // Default values
        def colorName = 'RED'
        def colorCode = '#FF0000'
        def subject = "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'"
        def summary = "${subject} (${env.BUILD_URL})"
        def details = """<p>STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
        <p>Check console output at "<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>"</p>"""

        // Override default values based on build status
        if (buildStatus == 'STARTED') {
            color = 'YELLOW'
            colorCode = '#FFFF00'
        } else if (buildStatus == 'SUCCESSFUL') {
            color = 'GREEN'
            colorCode = '#00FF00'
        } else {
            color = 'RED'
            colorCode = '#FF0000'
        }

        // Send notifications
        slackSend (channel: '@me', color: colorCode, message: summary)
    }

    stage ('Checkout') {
        checkout( checkout stuff here )
    }

    stage ('Build') {
        try {
            notifyBuild('STARTED')

            dir("place") {
                sh 'script name'
            }
        } catch (e) {
            // If there was an exception thrown, the build failed
            currentBuild.result = "FAILED"
            throw e
        } finally {
            // Success or failure, always send notifications
            notifyBuild(currentBuild.result)
        }
    }
}
</code>```

Body:
I'm sure this is a simple fix but I'm new to programming in general and Groovy in particular.

I am trying to follow this guide to enable slack notifications in a Jenkins 2 pipeline job but pasting and customizing the final code block is giving me the following error;

Method definition not expected here. Please define the method at an appropriate place or perhaps try using a block/Closure instead.

This is my code right now, although I've substituted a few bits for security. The error is occurring at the def notifyBuild(String buildStatus = 'STARTED') { line.

node('on-demand-t2large'){
    stage ('Checkout') {
        checkout( checkout stuff here )
    }

    stage ('Build') {
        try {
            notifyBuild('STARTED')

            dir("place") {
                sh 'script name'
            }
        }
        catch (e) {
            // If there was an exception thrown, the build failed
            currentBuild.result = "FAILED"
            throw e
        }
        finally {
            // Success or failure, always send notifications
            notifyBuild(currentBuild.result)
        }

        def notifyBuild(String buildStatus = 'STARTED') {
            // build status of null means successful
            buildStatus =  buildStatus ?: 'SUCCESSFUL'

            // Default values
            def colorName = 'RED'
            def colorCode = '#FF0000'
            def subject = "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'"
            def summary = "${subject} (${env.BUILD_URL})"
            def details = """
STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':

Check console output at "${env.JOB_NAME} [${env.BUILD_NUMBER}]"
"""

            // Override default values based on build status
            if (buildStatus == 'STARTED') {
                color = 'YELLOW'
                colorCode = '#FFFF00'
            } else if (buildStatus == 'SUCCESSFUL') {
                color = 'GREEN'
                colorCode = '#00FF00'
            } else {
                color = 'RED'
                colorCode = '#FF0000'
            }

            // Send notifications
            slackSend (channel: '@me', color: colorCode, message: summary)
        }
    }
}

I understand from some googling that groovy doesn't accept inner class definition, but as new as I am to programming I don't know how to fix it. Any help (with explanations so I can learn!) would be appreciated.

Body:
You can use Closures http://groovy-lang.org/closures.html

node('on-demand-t2large') {
    def notifyBuild = { String buildStatus ->
        // build status of null means successful
        buildStatus =  buildStatus ?: 'SUCCESSFUL'

        // Default values
        def colorName = 'RED'
        def colorCode = '#FF0000'
        def subject = "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'"
        def summary = "${subject} (${env.BUILD_URL})"
        def details = """<p>STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
        <p>Check console output at &QUOT;<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>&QUOT;</p>"""

        // Override default values based on build status
        if (buildStatus == 'STARTED') {
            color = 'YELLOW'
            colorCode = '#FFFF00'
        } else if (buildStatus == 'SUCCESSFUL') {
            color = 'GREEN'
            colorCode = '#00FF00'
        } else {
            color = 'RED'
            colorCode = '#FF0000'
        }

        // Send notifications
        slackSend (channel: '@me', color: colorCode, message: summary)
    }

    stage ('Checkout') {
        checkout( checkout stuff here )
    }

    stage ('Build') {
        try {
            notifyBuild('STARTED')

            dir("place") {
                sh 'script name'
            }
        } catch (e) {
            // If there was an exception thrown, the build failed
            currentBuild.result = "FAILED"
            throw e
        } finally {
            // Success or failure, always send notifications
            notifyBuild(currentBuild.result)
        }
    }
}


问:
Visual Studio Extensions SDK - can we access FTP functions?
I am trying to build a Visual Studio extension (using VS 2017 Community).

Visual Studio already comes with the ability to publish files via FTP to a remote server (for website projects); so obviously, there must be some sort of FTP library (or class) within Visual Studio.

My Question:

Does anyone know if there is an FTP class within the Visual Studio SDK that allows developers to publish files via FTP?  Currently, I have not found anything within the Visual Studio Extensions SDK documentation -- but I thought I should ask those who may be in the know.

Thanks in advance.

答:
I have used a couple:
For FTPS(Small use case) i used limilabs:
https://www.limilabs.com/ftp (Requires payment, simple ftp as well)

For built in FTP, i programmed using sockets:
System.Net.Sockets.Socket
System.Net.IPEndPoint

https://msdn.microsoft.com/en-us/library/system.net.sockets.socket(v=vs.110).aspx

The code is a bit obtuse but it works, i found a similar program tutorial for you:
http://www.dreamincode.net/forums/topic/35902-create-an-ftp-class-library-in-c%23/


问:
Android How to add ScrollView? ScrollView shits layout
I have a problem with adding ScrollView into my layout. So, when I add ScrollView (match_parent) into my layout, it shifts my layout into right side. Hereby, I see only background picture on the screen of the device. All Buttons, Textviews, and Edittexts shifted into right. By the way, I wrote code for only portrait layout.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rauf.myapplication.Main2Activity"
android:background="@drawable/bii3">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:layout_editor_absoluteY="8dp"
    tools:layout_editor_absoluteX="8dp"
    android:paddingLeft="60dp"
    android:paddingRight="58dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:layout_weight="2"
        android:gravity="center"
        android:orientation="vertical"
        android:paddingTop="42dp">

        <ImageView
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_gravity="center"
            android:src="@drawable/kamera" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:layout_weight="0.5"
        android:paddingTop="35dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/message" />

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:background="#00000000"
                android:hint="email address"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/log"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/usrusr"/>
            <EditText
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:background="#00000000"
                android:hint="username"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/red"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/pswrd"/>
            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:background="#00000000"
                android:hint="password"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/red2"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/pswrd"/>
            <EditText
                android:id="@+id/passwordconf"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:background="#00000000"
                android:hint="password confirm"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/button_background2"
            android:text="SIGN UP"
            android:onClick="clickButton2"
            android:clickable="true"
            android:layout_marginTop="20dp"
            android:textColor="#ffffff"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_marginTop="30dp"
            android:onClick="clickFunction2"
            android:text="Already have an Account ?"
            android:textColor="#000000" />
    </LinearLayout>
</LinearLayout>
</LinearLayout>
</code>```

I want ScrollView for this:

But I end up with this:

答:
This needs to be the settings for the top three layouts
You had the last one set to 600dp which was why it was pushing everything further down , change it to wrap_content:)

```<code>  <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:app="http://schemas.android.com/apk/res-auto"
                  xmlns:tools="http://schemas.android.com/tools"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            tools:layout_editor_absoluteY="8dp"
            tools:layout_editor_absoluteX="8dp"
            android:paddingLeft="60dp"
            android:paddingRight="58dp">

            <LinearLayout
                android:id="@+id/CHANGE_THIS_ONE"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" <<<<<<<<<
                android:layout_weight="2"
                android:gravity="center"
                android:orientation="vertical"
                android:paddingTop="42dp">
</code>```

Body:
I have a problem with adding ScrollView into my layout. So, when I add ScrollView (match_parent) into my layout, it shifts my layout into right side. Hereby, I see only background picture on the screen of the device. All Buttons, Textviews, and Edittexts shifted into right. By the way, I wrote code for only portrait layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rauf.myapplication.Main2Activity"
android:background="@drawable/bii3">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:layout_editor_absoluteY="8dp"
    tools:layout_editor_absoluteX="8dp"
    android:paddingLeft="60dp"
    android:paddingRight="58dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:layout_weight="2"
        android:gravity="center"
        android:orientation="vertical"
        android:paddingTop="42dp">

        <ImageView
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_gravity="center"
            android:src="@drawable/kamera" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:layout_weight="0.5"
        android:paddingTop="35dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/message" />

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:background="#00000000"
                android:hint="email address"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/log"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/usrusr"/>
            <EditText
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:background="#00000000"
                android:hint="username"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/red"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/pswrd"/>
            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:background="#00000000"
                android:hint="password"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/red2"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/pswrd"/>
            <EditText
                android:id="@+id/passwordconf"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:background="#00000000"
                android:hint="password confirm"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/button_background2"
            android:text="SIGN UP"
            android:onClick="clickButton2"
            android:clickable="true"
            android:layout_marginTop="20dp"
            android:textColor="#ffffff"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_marginTop="30dp"
            android:onClick="clickFunction2"
            android:text="Already have an Account ?"
            android:textColor="#000000" />
    </LinearLayout>
</LinearLayout>
</LinearLayout>

I want ScrollView for this:

But I end up with this:

Body:
This needs to be the settings for the top three layouts
You had the last one set to 600dp which was why it was pushing everything further down , change it to wrap_content:)

  <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:app="http://schemas.android.com/apk/res-auto"
                  xmlns:tools="http://schemas.android.com/tools"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            tools:layout_editor_absoluteY="8dp"
            tools:layout_editor_absoluteX="8dp"
            android:paddingLeft="60dp"
            android:paddingRight="58dp">

            <LinearLayout
                android:id="@+id/CHANGE_THIS_ONE"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" <<<<<<<<<
                android:layout_weight="2"
                android:gravity="center"
                android:orientation="vertical"
                android:paddingTop="42dp">


问:
ABAP: pass data type to form
I want to pass my own datatype to a form - but it doesn´t work:</p>

```<code>TYPES: BEGIN OF my_type,
     v1 TYPE i,
     v2 TYPE i,
   END OF my_type.

PERFORM calc using ...some parameters... .

FORM calc using ...some parameters... .

DATA values TYPE my_type " <- ERROR type my_type does not exist

...some code...

ENDFORM.
</code>```

答:
Remark: Based on more information in comments: The code is defined in a function module.

A function module is its own programm (the name is SAPL...function group name...). Each function module is its own include.

If you define a type in a report, a function module can't know the type definition. If you need to share a type definition between a reports and function modules (groups), you should define it as a global type in SE11.

If you run your code only inside a function module, you may define types in the top include of the function group. But you should not use this definition in the function module interfaces.

Title: ABAP: pass data type to form

Body:
I want to pass my own datatype to a form - but it doesn´t work:

TYPES: BEGIN OF my_type,
     v1 TYPE i,
     v2 TYPE i,
   END OF my_type.

PERFORM calc using ...some parameters... .

FORM calc using ...some parameters... .

DATA values TYPE my_type " <- ERROR type my_type does not exist

...some code...

ENDFORM.


问:
Android DownloadManager class: getUriForDownloadedFile return wrong path
i download a .apk file with DownloadManager library, and i have a BroadcastReceiver for download service. here is my code in onRecieve():

```<code>  long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
  DownloadManager dm = (DownloadManager)context.getSystemService(context.DOWNLOAD_SERVICE);

  intent = new Intent(Intent.ACTION_VIEW);
  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  intent.setDataAndType(dm.getUriForDownloadedFile(id), "application/vnd.android.package-archive");
  context.startActivity(intent);
</code>```

the problem here is when i call UriForDownloadedFile(id) somtimes return file:///storage/emulated/0/Download/example.apk
and on another device return
content://downloads/all_downloads/183

and i cant install apk with (content://downloads/all_downloads/183) path

答:
```<code>registerReceiver(
      new BroadcastReceiver() {
          @Override public void onReceive(Context context, Intent intent) {
              final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
              if (downloadId == 0) return;

              final Cursor cursor = downloadManager.query(
                  new DownloadManager.Query().setFilterById(downloadId));

              if (cursor.moveToFirst()) {
                  final String downloadedTo = cursor.getString(
                        cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                  Log.d(TAG, "The file has been downloaded to: " + downloadedTo);

                  context.startActivity(new Intent(Intent.ACTION_VIEW)
                        .setDataAndType(Uri.parse(downloadedTo),
                              "application/pdf"));
              }
          }
      },
      new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
</code>```

Body:
i download a .apk file with DownloadManager library, and i have a BroadcastReceiver for download service. here is my code in onRecieve():

  long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
  DownloadManager dm = (DownloadManager)context.getSystemService(context.DOWNLOAD_SERVICE);

  intent = new Intent(Intent.ACTION_VIEW);
  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  intent.setDataAndType(dm.getUriForDownloadedFile(id), "application/vnd.android.package-archive");
  context.startActivity(intent);

the problem here is when i call UriForDownloadedFile(id) somtimes return file:///storage/emulated/0/Download/example.apk
and on another device return
content://downloads/all_downloads/183

and i cant install apk with (content://downloads/all_downloads/183) path


问:
Only 'Import keras' takes 10GB in GPU
I am using EC2 GPU machine with pre-made AMIs.
I just put 'import keras' and run it.
It takes 11519MiB ( out of 12181MiB).
It's non-sense right?

I did googling it. I guess it might come from the path setting.
I don't know which causes memory leak.

Anyone who know the solution or experience similar with me??

--UPDATE--
It is the LD_LIBRARY_PATH in my company's GPU server
When I used the server at the first time, Only tensorflow was installed, not tensorflow-gpu. So I just did 'pip install --upgrade tensorflow-gpu'

答:
I solved the problem.

It is related to Keras & Tensorflow Memory allocation problem.
My setting automatically allocated all memory in GPU.
I solve it by the below.
Anyway, Thanks all

```<code>import tensorflow as tf
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
from keras import backend as K
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.2
session = tf.Session(config=config)
K.set_session(session)
</code>```

Title: Only 'Import keras' takes 10GB in GPU

Body:
I solved the problem.

It is related to Keras & Tensorflow Memory allocation problem.
My setting automatically allocated all memory in GPU.
I solve it by the below.
Anyway, Thanks all

import tensorflow as tf
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
from keras import backend as K
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.2
session = tf.Session(config=config)
K.set_session(session)


问:
JQuery iterate through string occurrences
I've an HTML like this

blalblala bla  blalba  bla and so on...

Now I would to get the left position of all items of kind myID.
I've tried with this code

```<code>var x = "";
$('.myID').each(function(index) {
    x += " " + $(this).position().left+",";
});
return x;
</code>```

But it's wrong because it does not return anything.
What's wrong?
Thanks

答:
you have multiple identical IDs in your document [fragment]

you are using the class selector, while you have IDs

To quote the freenode#css bot:

Explore the intricacies of HTML and CSS here: http://wsc.opera.com/ , http://www.htmlhelp.com/ , http://css-discuss.incutio.com/ , http://www.brainjar.com/ , http://www.htmldog.com/ , http://css.maxdesign.com.au/

Body:
I've an HTML like this

blalblala bla  blalba  bla and so on...

Now I would to get the left position of all items of kind myID.
I've tried with this code

var x = "";
$('.myID').each(function(index) {
    x += " " + $(this).position().left+",";
});
return x;

But it's wrong because it does not return anything.
What's wrong?
Thanks


问:
ASP .NET Core app and myBB forum on one server?
I want to buy VPS (Debian/Ubuntu) and host my ASP .NET Core app and myBB forum on this machine. How can I configure Apache ( and everything what is needed ) to get something like this:

mydomain.com targets ASP .NET app

mydomain.com/forum or forum.mydomain.com targets myBB forum.

I had never dig into Apache configuration so I don't know how to do this. Any help will be appreciated.

答:
The simplest and most effective approach will be to use IIS. You can host myBB and you ASP.Net app without and issue.

For your Asp.net Core app follow this tutorial and for configuring and installing PHP (for your myBB forum) follow the tutorials here.


问:
How to access a button in toolbar?
I have a custome toolbar in application like below there is a button call logout

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_layout"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@android:color/transparent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="24dp">

        <Button
            android:id="@+id/toolbar_logo_image"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="4dp"
            android:layout_centerVertical="true"
            android:background="@drawable/logo" />

        <EditText
            android:id="@+id/toolbar_search_field"
            android:layout_width="280dp"
            android:layout_height="36dp"
            android:textSize="20dp"
            android:hint="Search"
            android:textColorHint="@color/white"
            android:layout_toEndOf="@+id/toolbar_logo_image"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:background="@android:color/transparent"
            android:drawablePadding="2dp"
            android:drawableStart="@drawable/ic_search_24dp"
            tools:textColor="@android:color/black"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>
</code>```

I have include this toolbar in my main activity like below

```<code><include
        android:id="@+id/main_page_toolbar"
        layout="@layout/app_bar_toolbar">
    </include>
</code>```

in my main activity I have get that toolbar like below

```<code>mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
</code>```

How can I access the button in that toolbar I want to create a onclickevent
how can i do that?

答:
You are not using a toolbar, you using FrameLayout...
use this instead

```<code><android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:layout="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@android:color/white"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    layout:popupTheme="@style/Toolbar.Theme">
    <Button
        android:id="@+id/toolbar_logo_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_centerVertical="true"
        android:layout_marginEnd="4dp"
        android:layout_marginStart="8dp"
        android:background="@drawable/logo"></Button>
</android.support.v7.widget.Toolbar>
</code>```

and you can use this to get the button

```<code> mToolbar = (Toolbar) findViewById(R.id.toolbar);
 Button button = (Button) mToolbar.findViewById(R.id.toolbar_logo_image);
</code>```

Title: How to access a button in toolbar?

Body:
I have a custome toolbar in application like below there is a button call logout

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_layout"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@android:color/transparent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="24dp">

        <Button
            android:id="@+id/toolbar_logo_image"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="4dp"
            android:layout_centerVertical="true"
            android:background="@drawable/logo" />

        <EditText
            android:id="@+id/toolbar_search_field"
            android:layout_width="280dp"
            android:layout_height="36dp"
            android:textSize="20dp"
            android:hint="Search"
            android:textColorHint="@color/white"
            android:layout_toEndOf="@+id/toolbar_logo_image"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:background="@android:color/transparent"
            android:drawablePadding="2dp"
            android:drawableStart="@drawable/ic_search_24dp"
            tools:textColor="@android:color/black"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>

I have include this toolbar in my main activity like below

<include
        android:id="@+id/main_page_toolbar"
        layout="@layout/app_bar_toolbar">
    </include>

in my main activity I have get that toolbar like below

mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);

How can I access the button in that toolbar I want to create a onclickevent
how can i do that?

Body:
You are not using a toolbar, you using FrameLayout...
use this instead

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:layout="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@android:color/white"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    layout:popupTheme="@style/Toolbar.Theme">
    <Button
        android:id="@+id/toolbar_logo_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_centerVertical="true"
        android:layout_marginEnd="4dp"
        android:layout_marginStart="8dp"
        android:background="@drawable/logo"></Button>
</android.support.v7.widget.Toolbar>

and you can use this to get the button

 mToolbar = (Toolbar) findViewById(R.id.toolbar);
 Button button = (Button) mToolbar.findViewById(R.id.toolbar_logo_image);


问:
element-wise multiplication with broadcasting in keras custom layer
I am creating a custom layer with weights that need to be multiplied by element-wise before activation. I can get it to work when the output and input is the same shape. The problem occurs when I have a first order array as input with a second order array as output. tensorflow.multiply supports broadcasting, but when I try to use it in Layer.call(x, self.kernel)
to multiply x by the self.kernel Variable it complains that they are different shapes saying:

```<code>ValueError: Dimensions must be equal, but are 4 and 3 for 'my_layer_1/Mul' (op: 'Mul') with input shapes: [?,4], [4,3].
</code>```

here is my code:

```<code>from keras import backend as K
from keras.engine.topology import Layer
import tensorflow as tf
from keras.models import Sequential
import numpy as np

class MyLayer(Layer):

    def __init__(self, output_dims, **kwargs):
        self.output_dims = output_dims

        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel',
                                      shape=self.output_dims,
                                      initializer='ones',
                                      trainable=True)

        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    def call(self, x):
        #multiply wont work here?
        return K.tf.multiply(x, self.kernel)

    def compute_output_shape(self, input_shape):
        return (self.output_dims)

mInput = np.array([[1,2,3,4]])
inShape = (4,)
net = Sequential()
outShape = (4,3)
l1 = MyLayer(outShape, input_shape= inShape)
net.add(l1)
net.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])
p = net.predict(x=mInput, batch_size=1)
print(p)
</code>```

Edit:
Given input shape (4,) and output shape (4,3) the weight matrix should be the same shape as the output and initialized with ones. So in the above code the input is [1,2,3,4], the weight matrix should be [[1,1,1,1],[1,1,1,1],[1,1,1,1]] and the output should look like [[1,2,3,4],[1,2,3,4],[1,2,3,4]]

答:
Before multiplying, you need to repeat the elements to increase the shape.
You can use K.repeat_elements for that. (import keras.backend as K)

```<code>class MyLayer(Layer):

    #there are some difficulties for different types of shapes
    #let's use a 'repeat_count' instead, increasing only one dimension
    def __init__(self, repeat_count,**kwargs):
        self.repeat_count = repeat_count
        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):

        #first, let's get the output_shape
        output_shape = self.compute_output_shape(input_shape)
        weight_shape = (1,) + output_shape[1:] #replace the batch size by 1

        self.kernel = self.add_weight(name='kernel',
                                      shape=weight_shape,
                                      initializer='ones',
                                      trainable=True)

        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    #here, we need to repeat the elements before multiplying
    def call(self, x):

        if self.repeat_count > 1:

             #we add the extra dimension:
             x = K.expand_dims(x, axis=1)

             #we replicate the elements
             x = K.repeat_elements(x, rep=self.repeat_count, axis=1)

        #multiply
        return x * self.kernel

    #make sure we comput the ouptut shape according to what we did in "call"
    def compute_output_shape(self, input_shape):

        if self.repeat_count > 1:
            return (input_shape[0],self.repeat_count) + input_shape[1:]
        else:
            return input_shape
</code>```

Body:
I am creating a custom layer with weights that need to be multiplied by element-wise before activation. I can get it to work when the output and input is the same shape. The problem occurs when I have a first order array as input with a second order array as output. tensorflow.multiply supports broadcasting, but when I try to use it in Layer.call(x, self.kernel)
to multiply x by the self.kernel Variable it complains that they are different shapes saying:

ValueError: Dimensions must be equal, but are 4 and 3 for 'my_layer_1/Mul' (op: 'Mul') with input shapes: [?,4], [4,3].

here is my code:

from keras import backend as K
from keras.engine.topology import Layer
import tensorflow as tf
from keras.models import Sequential
import numpy as np

class MyLayer(Layer):

    def __init__(self, output_dims, **kwargs):
        self.output_dims = output_dims

        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel',
                                      shape=self.output_dims,
                                      initializer='ones',
                                      trainable=True)

        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    def call(self, x):
        #multiply wont work here?
        return K.tf.multiply(x, self.kernel)

    def compute_output_shape(self, input_shape):
        return (self.output_dims)

mInput = np.array([[1,2,3,4]])
inShape = (4,)
net = Sequential()
outShape = (4,3)
l1 = MyLayer(outShape, input_shape= inShape)
net.add(l1)
net.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])
p = net.predict(x=mInput, batch_size=1)
print(p)

Edit:
Given input shape (4,) and output shape (4,3) the weight matrix should be the same shape as the output and initialized with ones. So in the above code the input is [1,2,3,4], the weight matrix should be [[1,1,1,1],[1,1,1,1],[1,1,1,1]] and the output should look like [[1,2,3,4],[1,2,3,4],[1,2,3,4]]

Body:
Before multiplying, you need to repeat the elements to increase the shape.
You can use K.repeat_elements for that. (import keras.backend as K)

class MyLayer(Layer):

    #there are some difficulties for different types of shapes
    #let's use a 'repeat_count' instead, increasing only one dimension
    def __init__(self, repeat_count,**kwargs):
        self.repeat_count = repeat_count
        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):

        #first, let's get the output_shape
        output_shape = self.compute_output_shape(input_shape)
        weight_shape = (1,) + output_shape[1:] #replace the batch size by 1

        self.kernel = self.add_weight(name='kernel',
                                      shape=weight_shape,
                                      initializer='ones',
                                      trainable=True)

        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    #here, we need to repeat the elements before multiplying
    def call(self, x):

        if self.repeat_count > 1:

             #we add the extra dimension:
             x = K.expand_dims(x, axis=1)

             #we replicate the elements
             x = K.repeat_elements(x, rep=self.repeat_count, axis=1)

        #multiply
        return x * self.kernel

    #make sure we comput the ouptut shape according to what we did in "call"
    def compute_output_shape(self, input_shape):

        if self.repeat_count > 1:
            return (input_shape[0],self.repeat_count) + input_shape[1:]
        else:
            return input_shape


问:
Concat two nodelists
I am trying to concat two nodelists using

```<code>var ul   = document.querySelector("ul");
var down = document.getElementsByClassName("mobile")[0];
var ul_child = Array.prototype.concat.call(ul.children,down.children);
</code>```

But this returns only two nodes from ul nodelist and ignore others. What is the most valid to concat two nodelsits? I would like to avoid brute looping them

答:
Set() ensures items are unique and the ES6 Spread operator makes it neat & tidy:</p>

```<code>var elems = new Set([
    ...document.querySelectorAll(query1),
    ...document.querySelectorAll(query2)
]);
</code>```

Title: Concat two nodelists

Body:
I am trying to concat two nodelists using

var ul   = document.querySelector("ul");
var down = document.getElementsByClassName("mobile")[0];
var ul_child = Array.prototype.concat.call(ul.children,down.children);

But this returns only two nodes from ul nodelist and ignore others. What is the most valid to concat two nodelsits? I would like to avoid brute looping them

Body:
Set() ensures items are unique and the ES6 Spread operator makes it neat & tidy:

var elems = new Set([
    ...document.querySelectorAll(query1),
    ...document.querySelectorAll(query2)
]);