问:
Wordpress loop for static front page template not working
I have a static wordpress front page. I want the code that works on my regular blog template to work on the homepage too.
Currently, it only shows one post. The code in the main index.php is this...

```<code><?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() );
?>
<?php endwhile; ?>
<?php wp_pagenavi(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
</code>```

content.php calls this....

```<code><div class="col-md-4">
<?php the_excerpt(); ?>
</div><!-- /col-md-4 -->
</code>```

This works great while on the blog page. But i can't get this exact same content on to the static home page. I know I need a different query for homepage but no idea what that is. Any help appreciated!

答:
Your code looks right to me, you can try to reset the loop and query the posts again.</p>

```<code><?php
    rewind_posts();
    query_posts( $args );
    while ( have_posts() ) : the_post();
?>

    <!-- Do stuff... -->

<?php endwhile; ?>
</code>```

Body:
I have a static wordpress front page. I want the code that works on my regular blog template to work on the homepage too.
Currently, it only shows one post. The code in the main index.php is this...

<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() );
?>
<?php endwhile; ?>
<?php wp_pagenavi(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>

content.php calls this....

<?php the_excerpt(); ?>

This works great while on the blog page. But i can't get this exact same content on to the static home page. I know I need a different query for homepage but no idea what that is. Any help appreciated!

Body:
Your code looks right to me, you can try to reset the loop and query the posts again.

<?php
    rewind_posts();
    query_posts( $args );
    while ( have_posts() ) : the_post();
?>

    <!-- Do stuff... -->

<?php endwhile; ?>


来源: stackexchange

问:
panic: Error while trying to create dir if missing: mkdir /var/hyperledger: permission denied
I'm following this guide
https://github.com/ITPeople-Blockchain/auction
after the make native command, I execute the next command ./orderer but I received the following error:

panic: Error while trying to create dir if missing: mkdir /var/hyperledger: permission denied

shell log:

2017-07-06 14:50:11.556 CEST [orderer/main] main -> INFO 001 Starting orderer:
   Version: 1.0.0-rc2-snapshot-a0afe19a
   Go version: go1.8.3
   OS/Arch: linux/amd64
     panic: Error while trying to create dir if missing: mkdir /var/hyperledger: permission denied

goroutine 1 [running]:
  github.com/hyperledger/fabric/common/ledger/util/leveldbhelper.(*DB).Open(0xc42034b480)
      /home/user/work/src/github.com/hyperledger/fabric/common/ledger/util/leveldbhelper/leveldb_helper.go:84 +0x315
  github.com/hyperledger/fabric/common/ledger/util/leveldbhelper.NewProvider(0xc4203583c0, 0xc4203583c0)
      /home/user/work/src/github.com/hyperledger/fabric/common/ledger/util/leveldbhelper/leveldb_provider.go:40 +0x11b
  github.com/hyperledger/fabric/common/ledger/blkstorage/fsblkstorage.NewProvider(0xc420355da0, 0xc420355dc0, 0xc4203583a0, 0xc420167c50)
      /home/user/work/src/github.com/hyperledger/fabric/common/ledger/blkstorage/fsblkstorage/fs_blockstore_provider.go:34 +0x85
  github.com/hyperledger/fabric/orderer/ledger/file.New(0xc4201ee480, 0x23, 0x2, 0x2)
      /home/user/work/src/github.com/hyperledger/fabric/orderer/ledger/file/factory.go:75 +0xf7
  main.createLedgerFactory(0xc4201c06c0, 0x870ad0, 0xc4200ec8c0, 0xc42033e6c0, 0x0)
      /home/user/work/src/github.com/hyperledger/fabric/orderer/util.go:42 +0x2c3
  main.initializeMultiChainManager(0xc4201c06c0, 0x11a18a0, 0x11f2e40, 0xc4201d45d0, 0x1)
      /home/user/work/src/github.com/hyperledger/fabric/orderer/main.go:207 +0x43
  main.main()
      /home/user/work/src/github.com/hyperledger/fabric/orderer/main.go:75 +0x37f

答:
try:</p>

```<code>sudo mkdir -p /var/hyperledger/production
sudo chown -R $(whoami):$(whoami) /var/hyperledger
</code>```

ContentLicense: CC BY-SA 4.0

Body:
try:

sudo mkdir -p /var/hyperledger/production
sudo chown -R $(whoami):$(whoami) /var/hyperledger

ContentLicense: CC BY-SA 3.0


问:
How can I generate a Git patch for a specific commit?
I need to write a script that creates patches for a list of SHA-1 commit numbers.

I tried using git format-patch <the SHA1>, but that generated a patch for each commit since that SHA-1 value. After a few hundred patches were generated, I had to kill the process.

Is there a way to generate a patch only for the specific SHA-1 value?

答:
git format-patch commit_Id~1..commit_Id
git apply patch-file-name
```

Fast and simple solution.

Body:
git format-patch commit_Id~1..commit_Id
git apply patch-file-name

Fast and simple solution.


问:
Visual Studio breaking without a breakpoint in a VB project?
Running a particular project in Debug, Visual Studio is always stopping at the Public Sub New() line in my main form (it's an older project, so the code is within a autogenerated region in the .vb file rather than a .designer.vb file). No idea why this is happening and it's becoming a headache. It doesn't happen in any of my other VB projects (or running under Release). I can just hit F5 and it continues as normal.

Things I have tried:

Debug > Delete all breakpoints

Deleting the .suo file

I should note that both before and after doing the above, there is no breakpoint symbol next to the line. The execution just pauses and the line gets highlighted with a yellow arrow, as with a normal breakpoint line.

Why would VS be breaking at this opening line even without any breakpoints? I'm pretty sure I deleted the relevant files, so I would guess there's a VS setting I can't seem to find (but if it's a setting, wouldn't it affect other projects as well?).

Also, there are multiple developers working on this project. I am the only one this happens to.

答:
The issue was that "Enable Just My Code" was turned off in my debug settings.

I'm still not entirely sure why that caused it to break at this particular line without a breakpoint attached (other projects don't break here, even my fellow developer didn't have this issue after matching his settings with mine and debugging the same project...), but after checking this option, it no longer breaks at that first line.


问:
Getting error while using GroupBy and Pagination in Eloquent
I'm trying to use eloquent to get me a grouped by response and at the same time give me a Pagination response (The one that gives me the link to the second page).
I'm trying to do this:

```<code>App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) {
     return Carbon\Carbon::parse($row->created_at)->format('Y-m-d');
})->paginate(25);
</code>```

But, I'm getting this error when running it in the Tinker:

```<code>PHP warning:  strtolower() expects parameter 1 to be string, object given in D:\Folder\vendor\laravel\framework\src\Illuminate\Database\Grammar.php on line 58
</code>```

without the groupBy, I'm getting the correct result:

```<code>>>> App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->paginate(25)->toArray();
=> [
     "total" => 1,
     "per_page" => 25,
     "current_page" => 1,
     "last_page" => 1,
     "next_page_url" => null,
     "prev_page_url" => null,
     "from" => 1,
     "to" => 3,
     "data" => [
       [
         "id" => 5,
         "status" => "Comeu Bem",
         "created_at" => "2017-07-05 13:55:25",
         "updated_at" => "2017-07-05 13:55:25",
       ],
     ],
   ]
</code>```

BUT, when I remove the pagination, I do get the error but only because I added the get():

```<code>>>>  App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) {
...                          return Carbon\Carbon::parse($row->created_at)->format('Y-m-d');
...                      })->get();
PHP warning:  strtolower() expects parameter 1 to be string, object given in D:\Joao\git\F1Softwares\Code\Server\F1Softwares\vendor\laravel\framework\src\Illuminate\Database\Grammar.php on line 58
>>>
>>>
>>>  App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) {
...                          return Carbon\Carbon::parse($row->created_at)->format('Y-m-d');
...                      });
=> Illuminate\Database\Eloquent\Builder {#855}
</code>```

Any idea what I could be doing wrong? I do need to have the orderBy AND the pagination, to make it easier for the app to show the results(It is a RestFul call).

Thanks,
João

答:
You must call the groupBy() method on a collection, but it seems this won't work with paginate(). You could try using the forPage() method on the collection:

```<code>App\Eating::where('student_id', 2)->orderBy('created_at', 'DESC')
    ->get()->groupBy(function ($eating) {
         return $eating->created_at->format('Y-m-d');
    })->forPage(1, 25);
</code>```

Also, just a note, you don't need to use Carbon to parse the date, Eloquent does this for you.

Alternatively, you could try to manually create your paginator once you have the collection grouped using Illuminate\Pagination\LengthAwarePaginator.

```<code>$eatings = App\Eating::where('student_id', 2)->orderBy('created_at', 'DESC')
               ->get()->groupBy(function ($eating) {
                   return $eating->created_at->format('Y-m-d');
               });
$paginatedEatings = new LengthAwarePaginator($eatings, $eatings->count(), 25);

return $paginatedEatings->toArray();
</code>```

Body:
I'm trying to use eloquent to get me a grouped by response and at the same time give me a Pagination response (The one that gives me the link to the second page).
I'm trying to do this:

App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) {
     return Carbon\Carbon::parse($row->created_at)->format('Y-m-d');
})->paginate(25);

But, I'm getting this error when running it in the Tinker:

PHP warning:  strtolower() expects parameter 1 to be string, object given in D:\Folder\vendor\laravel\framework\src\Illuminate\Database\Grammar.php on line 58

without the groupBy, I'm getting the correct result:

>>> App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->paginate(25)->toArray();
=> [
     "total" => 1,
     "per_page" => 25,
     "current_page" => 1,
     "last_page" => 1,
     "next_page_url" => null,
     "prev_page_url" => null,
     "from" => 1,
     "to" => 3,
     "data" => [
       [
         "id" => 5,
         "status" => "Comeu Bem",
         "created_at" => "2017-07-05 13:55:25",
         "updated_at" => "2017-07-05 13:55:25",
       ],
     ],
   ]

BUT, when I remove the pagination, I do get the error but only because I added the get():

>>>  App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) {
...                          return Carbon\Carbon::parse($row->created_at)->format('Y-m-d');
...                      })->get();
PHP warning:  strtolower() expects parameter 1 to be string, object given in D:\Joao\git\F1Softwares\Code\Server\F1Softwares\vendor\laravel\framework\src\Illuminate\Database\Grammar.php on line 58
>>>
>>>
>>>  App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) {
...                          return Carbon\Carbon::parse($row->created_at)->format('Y-m-d');
...                      });
=> Illuminate\Database\Eloquent\Builder {#855}

Any idea what I could be doing wrong? I do need to have the orderBy AND the pagination, to make it easier for the app to show the results(It is a RestFul call).

Thanks,
João

Body:
You must call the groupBy() method on a collection, but it seems this won't work with paginate(). You could try using the forPage() method on the collection:

App\Eating::where('student_id', 2)->orderBy('created_at', 'DESC')
    ->get()->groupBy(function ($eating) {
         return $eating->created_at->format('Y-m-d');
    })->forPage(1, 25);

Also, just a note, you don't need to use Carbon to parse the date, Eloquent does this for you.

Alternatively, you could try to manually create your paginator once you have the collection grouped using Illuminate\Pagination\LengthAwarePaginator.

$eatings = App\Eating::where('student_id', 2)->orderBy('created_at', 'DESC')
               ->get()->groupBy(function ($eating) {
                   return $eating->created_at->format('Y-m-d');
               });
$paginatedEatings = new LengthAwarePaginator($eatings, $eatings->count(), 25);

return $paginatedEatings->toArray();


问:
Set variables values whose name is passed by string in C#
I'm searching a method for setting dynamically the values of a list of variables whose names and values are readed from a database.

I've found a lot of code for getting the variable name and value, but nothing that works for setting the value.

I'll try to explain myself better.
Think to have a database that contains two columns, say "name" and "value".
Say for example that you have two records:

1)  Name="string1", Value="message1"
2)  Name="string2", Value="message2"

I have the code to read the two records, what i want is a way to take dinamically the names of the variables from the records and assign to them the corresponding values.

The code is this:

```<code>SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    var v1 = dr["Name"].ToString();
    var v2 = dr[lng].ToString();

    //Something here to assign the value stored in v2 to the variable whose name is stored in v1

}
</code>```

Thank you all

答:
I don't know why you would want to do this but why not just use a dictionary?

```<code>SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
SqlDataReader dr = cmd.ExecuteReader();
var variables = new Dictionary<string, string>();
while (dr.Read())
{
    var v1 = dr["Name"].ToString();
    var v2 = dr[lng].ToString();
    variables.Add(v1, v2);
}
</code>```

Then to use them:

```<code>var x= variables[v1];
</code>```

Update:

I see you added a note saying you need to refer to objects. You could change the Dictionary to hold objects instead. You didn't mention the type so for argument sake I will assume they are all text boxes:

```<code>SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
    SqlDataReader dr = cmd.ExecuteReader();
    var variables = new Dictionary<string, object>();
    while (dr.Read())
    {
        var v1 = dr["Name"].ToString();
        var v2 = dr[lng].ToString();
        var textbox = new TextBox() { Text = v2 };
        variables.Add(v1, textbox);
    }
</code>```

Then to use them by name:

```<code>var textbox= variables[v1];
</code>```

Body:
I'm searching a method for setting dynamically the values of a list of variables whose names and values are readed from a database.

I've found a lot of code for getting the variable name and value, but nothing that works for setting the value.

I'll try to explain myself better.
Think to have a database that contains two columns, say "name" and "value".
Say for example that you have two records:

1)  Name="string1", Value="message1"
2)  Name="string2", Value="message2"

I have the code to read the two records, what i want is a way to take dinamically the names of the variables from the records and assign to them the corresponding values.

The code is this:

SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    var v1 = dr["Name"].ToString();
    var v2 = dr[lng].ToString();

    //Something here to assign the value stored in v2 to the variable whose name is stored in v1

}

Thank you all

Body:
I don't know why you would want to do this but why not just use a dictionary?

SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
SqlDataReader dr = cmd.ExecuteReader();
var variables = new Dictionary<string, string>();
while (dr.Read())
{
    var v1 = dr["Name"].ToString();
    var v2 = dr[lng].ToString();
    variables.Add(v1, v2);
}

Then to use them:

var x= variables[v1];

Update:

I see you added a note saying you need to refer to objects. You could change the Dictionary to hold objects instead. You didn't mention the type so for argument sake I will assume they are all text boxes:

SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
    SqlDataReader dr = cmd.ExecuteReader();
    var variables = new Dictionary<string, object>();
    while (dr.Read())
    {
        var v1 = dr["Name"].ToString();
        var v2 = dr[lng].ToString();
        var textbox = new TextBox() { Text = v2 };
        variables.Add(v1, textbox);
    }

Then to use them by name:

var textbox= variables[v1];


问:
Python: Tkinter pausing a while loop
So i'm trying to create a program that displays the cpu usage of your computer in real time. I wanted to use tkinter to add some buttons to the program. I decided to add a stop button that closes the program and a pause button that stops the cpu usage from updating. I was able to create the stop button but when I started the pause button I realized that I was unable to pause the while loop I using. Does anyone know what i'm doing wrong?</p>

```<code>from tkinter import *
import psutil
from time import sleep

root = Tk()
var = StringVar()

label = Label( root, textvariable=var, relief=GROOVE, height=3, width=6, bd=4)
f = Frame(root, height=100, width=180)
f.pack_propagate(0)
f.pack()
stop=0
def pause1():
    stop=1
    print('It works')
def findcpu():
    if stop==0:
        root.update()
        sleep(0.001)
        cpu = psutil.cpu_percent(interval=1, percpu=False)
        var.set(cpu)
        label.pack()
        root.update()
    elif stop==1:
        print('It really works')
        loop=1

class pauseButton(Button):
    def __init__(self, parent):
        Button.__init__(self, parent)
        self['text']= 'pause'
        self['bg']='orange'
        self['height']=3
        self['width']=6
        self['bd']=4
        self['relief']=GROOVE
        self.button=Button(self)
        self['command']=pause1
        self.pack(side=LEFT)
class quitButton(Button):
    def __init__(self, parent):
        Button.__init__(self, parent)
        self['text'] = 'End'
        self['bg']='red'
        self['height']=3
        self['width']=6
        self['bd']=4
        self['padx']=0
        self['pady']=0
        self['relief']=GROOVE
        self['activebackground']='brown'
        self.button = Button(self)
        self['command'] = parent.destroy
        self.pack(side=RIGHT)
quitButton(root)
pauseButton(root)
loop=0
stop=0
num1=0
num2=1

while loop==0:
    findcpu()

root.mainloop()
print('Done')
</code>```

答:
The scenario is I create a pop-up GUI – OK button

Then I want to wait on the user to click OK to continue

Problem: I create a loop in python alone this “locks out” the GUI part from updating.

In fact the even though I instruct Tk to create a Button pop-up, it never pops-up.

The solution I found is to

1) force-refresh the TK using “update”
                    while (self.wait_for_operator.get()):

```<code>                   root.update()
                   root.update_idletasks()
</code>```

2) I use a special TK variable called an IntVar

“There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.”

This value is set when the user presses the the OK button

The combinations of 1) and 2) means I am successfully able to create a user-controlled loop from a GUI.

The relevant code sections are

```<code>self.wait_for_operator.set(1)

self.button = Button(self.top, text="OK", command= self._handle_start_key_and_serial_input)
self.button.pack()

while (self.wait_for_operator.get()):

   root.update()
   root.update_idletasks()
</code>```

```<code>def _handle_start_key_and_serial_input(self):
  self.wait_for_operator.set(0)
  self.top.destroy()
</code>```

Title: Python: Tkinter pausing a while loop

Body:
So i'm trying to create a program that displays the cpu usage of your computer in real time. I wanted to use tkinter to add some buttons to the program. I decided to add a stop button that closes the program and a pause button that stops the cpu usage from updating. I was able to create the stop button but when I started the pause button I realized that I was unable to pause the while loop I using. Does anyone know what i'm doing wrong?

from tkinter import *
import psutil
from time import sleep

root = Tk()
var = StringVar()

label = Label( root, textvariable=var, relief=GROOVE, height=3, width=6, bd=4)
f = Frame(root, height=100, width=180)
f.pack_propagate(0)
f.pack()
stop=0
def pause1():
    stop=1
    print('It works')
def findcpu():
    if stop==0:
        root.update()
        sleep(0.001)
        cpu = psutil.cpu_percent(interval=1, percpu=False)
        var.set(cpu)
        label.pack()
        root.update()
    elif stop==1:
        print('It really works')
        loop=1

class pauseButton(Button):
    def __init__(self, parent):
        Button.__init__(self, parent)
        self['text']= 'pause'
        self['bg']='orange'
        self['height']=3
        self['width']=6
        self['bd']=4
        self['relief']=GROOVE
        self.button=Button(self)
        self['command']=pause1
        self.pack(side=LEFT)
class quitButton(Button):
    def __init__(self, parent):
        Button.__init__(self, parent)
        self['text'] = 'End'
        self['bg']='red'
        self['height']=3
        self['width']=6
        self['bd']=4
        self['padx']=0
        self['pady']=0
        self['relief']=GROOVE
        self['activebackground']='brown'
        self.button = Button(self)
        self['command'] = parent.destroy
        self.pack(side=RIGHT)
quitButton(root)
pauseButton(root)
loop=0
stop=0
num1=0
num2=1

while loop==0:
    findcpu()

root.mainloop()
print('Done')

Body:
The scenario is I create a pop-up GUI – OK button

Then I want to wait on the user to click OK to continue

Problem: I create a loop in python alone this “locks out” the GUI part from updating.

In fact the even though I instruct Tk to create a Button pop-up, it never pops-up.

The solution I found is to

1) force-refresh the TK using “update”
                    while (self.wait_for_operator.get()):

                   root.update()
                   root.update_idletasks()

2) I use a special TK variable called an IntVar

“There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.”

This value is set when the user presses the the OK button

The combinations of 1) and 2) means I am successfully able to create a user-controlled loop from a GUI.

The relevant code sections are

self.wait_for_operator.set(1)

self.button = Button(self.top, text="OK", command= self._handle_start_key_and_serial_input)
self.button.pack()

while (self.wait_for_operator.get()):

   root.update()
   root.update_idletasks()

def _handle_start_key_and_serial_input(self):
  self.wait_for_operator.set(0)
  self.top.destroy()


问:
How do I click 1 of 2 links with same name, no id and same class. selenium java
I'm trying to get selenium to click the select button but I can't use by.linkText() because there are two buttons with the same name.
I'm using this xpath ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a[text()='Select']"; to find the button but it can't find it.

I've also tried ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a";.
I've looked over the Selenium documentation and can't seem to find a solution.

Here is the section of website code:

...

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

<p>for reference, the second Select button has this code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="view-something_111111_2A3B5DF2_0" class="coverage-wrap collapse" aria-expanded="false" style="height: 30px;">...</div>
<div class="btn-raplace">
  Select</code>```

which is why I am using the id in my xpath.

Thanks.

答:
Here is the Answer to your Question:

Use this xpath:

```<code>//div[@class='btn-raplace']/a[@class='btn-beer']
</code>```

Let me know if this Answers your Question.

Body:
I'm trying to get selenium to click the select button but I can't use by.linkText() because there are two buttons with the same name.
I'm using this xpath ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a[text()='Select']"; to find the button but it can't find it.

I've also tried ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a";.
I've looked over the Selenium documentation and can't seem to find a solution.

Here is the section of website code:

...

  Select

for reference, the second Select button has this code:

...

  Select

which is why I am using the id in my xpath.

Thanks.

Body:
Here is the Answer to your Question:

Use this xpath:

//div[@class='btn-raplace']/a[@class='btn-beer']

Let me know if this Answers your Question.


问:
Determine when image finished loading with JavaScript or jQuery:
How can I detect with JavaScript or jQuery when an image has finished loading, be it from the server or the browser cache?
I want to load various images in the same  tag and detect when the loading of a new images has finished.

答: For a more thorough image load detection, including images loaded from cache, try this: https://github.com/paulirish/jquery.imgloaded</p>

ContentLicense: CC BY-SA 2.5


问:
Stretch the
 to the full height of the parent

There are many div blocks. One parent, the second inside the left (for the menu), the second inside the right (for the text). How it is possible to stretch the right inner block (it is possible with the left one) to the entire height of the parent block. The parent block it has min-height:1100px

Here's the code:

```<code><div id="wrapctr">
    <div id="leftmenu"></div>
    <div class="rightcontent">
        //common div
        <div style="padding: 10px; width: 100%; overflow: hidden; display: flex; flex-wrap: wrap; justify-content: space-between; background:white">
            // img div
            <div style="float: left; padding: 10px; text-align: center; width: 257px;"><img src="../img/1625.jpg" width="200"></div>
        </div>
    </div>
</div>
</code>```

CSS

```<code>#wrapctr {
    width:80%;
    min-width: 700px;
    max-width: 1200px;
    background:#FFF;
    margin:0 auto;
    min-height:1100px;
    z-index:2;
}

#leftmenu {
    background: #FFF;
    float: left;
    width: 250px;
    list-style: none;
}
.rightcontent {
    background: #FFF;
    margin-left: 255px;
}
</code>```

One page show 12 images are issued in three in a row. If i added position:relative and absolute with height:100% my div with style comes out of rightcontent div

答:
You should give wrapctr position relative
and position absolute to your common div
and then you can give height 100% to the common div </p>

Title: Stretch the <div> to the full height of the parent <div>

Body:
There are many div blocks. One parent, the second inside the left (for the menu), the second inside the right (for the text). How it is possible to stretch the right inner block (it is possible with the left one) to the entire height of the parent block. The parent block it has min-height:1100px

Here's the code:

        //common div

            // img div

CSS

#wrapctr {
    width:80%;
    min-width: 700px;
    max-width: 1200px;
    background:#FFF;
    margin:0 auto;
    min-height:1100px;
    z-index:2;
}

#leftmenu {
    background: #FFF;
    float: left;
    width: 250px;
    list-style: none;
}
.rightcontent {
    background: #FFF;
    margin-left: 255px;
}

One page show 12 images are issued in three in a row. If i added position:relative and absolute with height:100% my div with style comes out of rightcontent div


问:
C++, g++, conditional compilation based on host name?
I have come across the following problem:

Our testing environment is not able to fully simulate a certain hardware part of the production environment, and therefore some code needs excluding when testing the application.

I therefore need something in the way of

```<code> #IFNDEF testing_env
 //code to exclude
 #ENDIF
</code>```

This works just fine if i include a #DEFINE testing_env, but like this i need to manually comment/uncomment this define every time i switch environments.

I'm looking for a way to do this based on the host name or a similar feature. I have tried to look for conditional compilation based on environment variables, but apparently this is not possible.

答:
Your Makefile can determine the hostname and set the specific vars with -D for your build:

Example:

```<code>HOSTNAME=$(shell hostname)

ifeq ($(HOSTNAME), localhost1.localdomain)
    ANY_VAR=COMPILE_VERSION_1
else
    ANY_VAR=COMPILE_VERSION_2
endif

$(info $(HOSTNAME))
$(info $(ANY_VAR))

%.o: %.cpp
    g++ -D$(ANY_VAR) $< -c

OBJECTS=main.o

go: $(OBJECTS)
    g++ $^ -o go

clean:
    rm -f *.o
    rm -f go
</code>```

Your C/C++ can use this vars with something like that:

```<code>#include <iostream>

#ifdef COMPILE_VERSION_1
std::string x="Version1";
#endif

#ifdef COMPILE_VERSION_2
std::string x="Version2";
#endif

int main()
{
    std::cout << x << std::endl;
}
</code>```

Body:
I have come across the following problem:

Our testing environment is not able to fully simulate a certain hardware part of the production environment, and therefore some code needs excluding when testing the application.

I therefore need something in the way of

 #IFNDEF testing_env
 //code to exclude
 #ENDIF

This works just fine if i include a #DEFINE testing_env, but like this i need to manually comment/uncomment this define every time i switch environments.

I'm looking for a way to do this based on the host name or a similar feature. I have tried to look for conditional compilation based on environment variables, but apparently this is not possible.

Body:
Your Makefile can determine the hostname and set the specific vars with -D for your build:

Example:

HOSTNAME=$(shell hostname)

ifeq ($(HOSTNAME), localhost1.localdomain)
    ANY_VAR=COMPILE_VERSION_1
else
    ANY_VAR=COMPILE_VERSION_2
endif

$(info $(HOSTNAME))
$(info $(ANY_VAR))

%.o: %.cpp
    g++ -D$(ANY_VAR) $< -c

OBJECTS=main.o

go: $(OBJECTS)
    g++ $^ -o go

clean:
    rm -f *.o
    rm -f go

Your C/C++ can use this vars with something like that:

#include <iostream>

#ifdef COMPILE_VERSION_1
std::string x="Version1";
#endif

#ifdef COMPILE_VERSION_2
std::string x="Version2";
#endif

int main()
{
    std::cout << x << std::endl;
}


问:
Sum 2 counts from same table at end of row
I am using the query below to generate the table below that, what I would like is to get the total for each row at the end

```<code>SELECT
    FreeText,
    COUNT(case Status WHEN 'BOOKING' then 1 else null end) AS Bookings,
    COUNT(case Status WHEN 'QUOTE' then 1 else null end) AS Quotes
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    OrderDate <= CURDATE()
AND OrderDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
AND FreeText IN ('user1','user2','user3')
AND STATUS IN ('BOOKING', 'QUOTE')
GROUP BY
    FreeText
</code>```

The above produces this table:

```<code>FreeText | Bookings | Quote
User1    | 23       |11
User2    | 11       |17
User3    | 8        |4
</code>```

What I would like the query to produce:

```<code>FreeText | Bookings | Quote | Total
User1    | 23       |11     |34
User2    | 11       |17     |28
User3    | 8        |4      |12
</code>```

Help much appreciated

答:
Add COUNT(*) to the query.

```<code>SELECT
    FreeText,
    COUNT(case Status WHEN 'BOOKING' then 1 else null end) AS Bookings,
    COUNT(case Status WHEN 'QUOTE' then 1 else null end) AS Quotes,
    COUNT(*) AS Total
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    OrderDate <= CURDATE()
AND OrderDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
AND FreeText IN ('user1','user2','user3')
AND STATUS IN ('BOOKING', 'QUOTE')
GROUP BY
    FreeText
</code>```

Body:
I am using the query below to generate the table below that, what I would like is to get the total for each row at the end

SELECT
    FreeText,
    COUNT(case Status WHEN 'BOOKING' then 1 else null end) AS Bookings,
    COUNT(case Status WHEN 'QUOTE' then 1 else null end) AS Quotes
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    OrderDate <= CURDATE()
AND OrderDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
AND FreeText IN ('user1','user2','user3')
AND STATUS IN ('BOOKING', 'QUOTE')
GROUP BY
    FreeText

The above produces this table:

FreeText | Bookings | Quote
User1    | 23       |11
User2    | 11       |17
User3    | 8        |4

What I would like the query to produce:

FreeText | Bookings | Quote | Total
User1    | 23       |11     |34
User2    | 11       |17     |28
User3    | 8        |4      |12

Help much appreciated

Body:
Add COUNT(*) to the query.

SELECT
    FreeText,
    COUNT(case Status WHEN 'BOOKING' then 1 else null end) AS Bookings,
    COUNT(case Status WHEN 'QUOTE' then 1 else null end) AS Quotes,
    COUNT(*) AS Total
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    OrderDate <= CURDATE()
AND OrderDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
AND FreeText IN ('user1','user2','user3')
AND STATUS IN ('BOOKING', 'QUOTE')
GROUP BY
    FreeText


问:
Magento 404 error page frontend
I noticed that Magento throw back a 404 error when trying to access the website from other locations. This only happenes on frontend. Backend can be accessible from all over the world. I don't know what's wrong.
I can access the website just normally without any problems! I can access the website even at home without no issues!
The Website is: borika.de
No restrictions have been noticed. Does anyone have an idea how to solve this issue?
Thanks</p>

答: I recently deactivated other languages. This was the problem! This is the only solution that worked for me: Magento returns 404 error on all browsers except Firefox. </p>

Title: Magento 404 error page frontend


问:
Ui-Path: How to handle dynamic web elements
I am new to UIPath tool. please accept my apologizes if it's a poor question.

I need to click\sendKeys a web element, which is totally a dynamic element.
ID will keep change for everytime when loading the page.

```<code>Login 1: <span id="x58Sn0-cnt" class="z-tab-text" uipath_custom_id="8">Update</span>

Login 2: <span id="nT9Tn0-cnt" class="z-tab-text">Update</span>

Note:
Also we can't relay on class "z-tab-text" because so many other elements are sharing the same class.
</code>```

thanks in advance. :)

答:
I've managed this usecase by using idx

I know it's not recommended for failing cases i'll go with image. Now it's fail free.

Body:
I am new to UIPath tool. please accept my apologizes if it's a poor question.

I need to click\sendKeys a web element, which is totally a dynamic element.
ID will keep change for everytime when loading the page.

Login 1: Update

Login 2: Update

Note:
Also we can't relay on class "z-tab-text" because so many other elements are sharing the same class.

thanks in advance. :)


问:
do I need multiple tables or single?
I developing a tool which may got more than a million data to fill in.

current i have designed single table with 36 coloumns. my question is do I need to divide these into multiple tables or single??

If single what is the advantage and disadvantage

if multiple then what is the advantage and disadvantage

and what will be the engine to use for speed...

my concern is a large database which will have atleast 50000 queries perday..

any help??

答:
It depends!

Does that one table contain a single 'entity'? i.e. Are all 36 columns attributes a single thing, or are there several 'things' mixed together?

If mixed, then you should normalise (separate into distinct entities with relationships between them). You should aim for at least Third Normal Form (3NF).

A best practice is to normalise as much as you can; if you later identify a performance problem, then denormalise as little as you can.

Title: do I need multiple tables or single?


问:
Angular 2 Root module merge
I created a multi App application with several root ngModule's that works perfectly as separate apps.
I'm using Angular 4 with ng-cli.
Now I want to achieve the same but i'm thiking in a way to merge the root ngModules of each app into one to launch all the separated apps integrated.

Any clues on how to achieve this?

答:
take a look to angular docs: https://angular.io/guide/ngmodule#feature-modules

Feature modules and lazy loading I think is exactly what you are looking for.

Title: Angular 2 Root module merge


问:
Ignore inline model when saving
I've been looking on the documentation and stackoverflow/forums for a way to ignore the inline children of a model when I save it in django admin. I've been searching for a few days and I can't seem to find an answer.

I have a normal tabularinline object:

```<code>class UserOrdersAdmin(admin.TabularInline):
    model = Order
    classes = ['collapse']
</code>```

And a normal User admin registration:

```<code>class UserAdmin(BaseUserAdmin):
    inlines = (UserOrdersAdmin, UserSettingsAdmin)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)
</code>```

What I simply want is when I press save within the User "change view", it will ignore the inline "UserOrderAdmin" which is inline to UserAdmin.

答:
From your response on my comment I am getting the idea you want to show some extra information in the admin, that is not editable. This can be achieved using readonly_fields in the Inline, for completeness you should also set the max_num to 0, because otherwise you can add empty inlines.

You could enter all fields manually or use something like given in this answer: https://stackoverflow.com/a/42877484/2354734

The end result would look something like this.

```<code>class UserOrdersAdmin(admin.TabularInline):
    model = Order
    classes = ['collapse']
    max_num = 0

    def get_readonly_fields(self, request, obj=None):
        return list(set(
            [field.name for field in self.opts.local_fields] +
            [field.name for field in self.opts.local_many_to_many]
        ))
</code>```

For completeness of the answer also a link to the documentation

Title: Ignore inline model when saving

Body:
I've been looking on the documentation and stackoverflow/forums for a way to ignore the inline children of a model when I save it in django admin. I've been searching for a few days and I can't seem to find an answer.

I have a normal tabularinline object:

class UserOrdersAdmin(admin.TabularInline):
    model = Order
    classes = ['collapse']

And a normal User admin registration:

class UserAdmin(BaseUserAdmin):
    inlines = (UserOrdersAdmin, UserSettingsAdmin)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

What I simply want is when I press save within the User "change view", it will ignore the inline "UserOrderAdmin" which is inline to UserAdmin.

Body:
From your response on my comment I am getting the idea you want to show some extra information in the admin, that is not editable. This can be achieved using readonly_fields in the Inline, for completeness you should also set the max_num to 0, because otherwise you can add empty inlines.

You could enter all fields manually or use something like given in this answer: https://stackoverflow.com/a/42877484/2354734

The end result would look something like this.

class UserOrdersAdmin(admin.TabularInline):
    model = Order
    classes = ['collapse']
    max_num = 0

    def get_readonly_fields(self, request, obj=None):
        return list(set(
            [field.name for field in self.opts.local_fields] +
            [field.name for field in self.opts.local_many_to_many]
        ))

For completeness of the answer also a link to the documentation


问:
PHP 7 install on Ubuntu 14.04 now fails due to libssl dependency that can't be resolved?
I am using shippable to build my project and part of it requires PHP.

The build script is this:

```<code>apt-get update
apt-get install -y software-properties-common python-software-properties language-pack-en-base
LC_ALL=en_US.UTF-8 add-apt-repository ppa:ondrej/php
apt-get update
apt-get install -y php7.0 php7.0-bcmath
</code>```

Today the build failed while installing PHP with the following error:

```<code>apt-get install -y php7.0 php7.0-bcmath

Reading package lists...
Building dependency tree...
Reading state information...
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 php7.0 : Depends: libapache2-mod-php7.0 but it is not going to be installed or
                   php7.0-fpm but it is not going to be installed or
                   php7.0-cgi but it is not going to be installed
          Depends: php7.0-common but it is not going to be installed
 php7.0-bcmath : Depends: php7.0-common but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

So i started up a local docker container to see if something wierd was happening at shippable - with the following command:

```<code>docker run -i -t ubuntu:14.04 /bin/bash
</code>```

And ran the 5 build lines listed above, and i get the same error. The next thing i did was install aptitude to see if i could get a better error, and ran this aptitude install -y php7.0 php7.0-bcmath - this was the aptitude output:

```<code>aptitude install -y php7.0 php7.0-bcmath
The following NEW packages will be installed:
  apache2{a} apache2-bin{a} apache2-data{a} libapache2-mod-php7.0{ab}
  libapr1{a} libaprutil1{a} libaprutil1-dbd-sqlite3{a} libaprutil1-ldap{a}
  libedit2{a} php-common{a} php7.0 php7.0-bcmath php7.0-cli{ab}
  php7.0-common{ab} php7.0-json{a} php7.0-opcache{a} php7.0-readline{a}
  psmisc{a} ssl-cert{a}
0 packages upgraded, 19 newly installed, 0 to remove and 7 not upgraded.
Need to get 4950 kB of archives. After unpacking 20.2 MB will be used.
The following packages have unmet dependencies:
 php7.0-cli : Depends: libssl1.1 (>= 1.1.0) which is a virtual package.
 php7.0-common : Depends: libssl1.1 (>= 1.1.0) which is a virtual package.
 libapache2-mod-php7.0 : Depends: libssl1.1 (>= 1.1.0) which is a virtual package.
The following actions will resolve these dependencies:

     Keep the following packages at their current version:
1)     libapache2-mod-php7.0 [Not Installed]
2)     php7.0 [Not Installed]
3)     php7.0-bcmath [Not Installed]
4)     php7.0-cli [Not Installed]
5)     php7.0-common [Not Installed]
6)     php7.0-json [Not Installed]
7)     php7.0-opcache [Not Installed]
8)     php7.0-readline [Not Installed]

The following NEW packages will be installed:
  psmisc{a}
0 packages upgraded, 1 newly installed, 0 to remove and 7 not upgraded.
Need to get 53.2 kB of archives. After unpacking 229 kB will be used.
Get: 1 http://archive.ubuntu.com/ubuntu/ trusty/main psmisc amd64 22.20-1ubuntu2 [53.2 kB]
Fetched 53.2 kB in 0s (911 kB/s)
Selecting previously unselected package psmisc.
(Reading database ... 14894 files and directories currently installed.)
Preparing to unpack .../psmisc_22.20-1ubuntu2_amd64.deb ...
Unpacking psmisc (22.20-1ubuntu2) ...
Setting up psmisc (22.20-1ubuntu2) ...
</code>```

I have a couple of questions:

1) How do i fix this? I have done some looking but can't work out how to update libssl

2) Why has this happened all of a sudden, this was never a problem for PHP7.0 before?

Some additional info:

```<code>openssl version -a
OpenSSL 1.0.1f 6 Jan 2014
built on: Mon Jan 30 20:38:38 UTC 2017
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/usr/lib/ssl"

uname -a
Linux b5cbe94d7da8 4.9.13-moby #1 SMP Sat Mar 25 02:48:44 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
</code>```

答:
The PPA maintainer has 'fixed' this, according to a GitHub issue.

To answer your questions:

1) How do i fix this? I have done some looking but can't work out how to update libssl

The PPA has been already fixed, but next time, please, fill an issue at appropriate place - e.g. the issue tracker.

2) Why has this happened all of a sudden, this was never a problem for PHP7.0 before?

The packages in ppa:ondrej/php build-depends on ppa:ondrej/apache2 that has been recently updated to OpenSSL 1.1.0 libraries, and those were picked up by latest build of PHP.  The ppa:ondrej/php had to be updated with OpenSSL 1.1.0 libraries as well as a consequence of this move.

A bug or two occasionally happens, and it is fixed as soon as the bug is filled at appropriate place.

It is perfectly safe to mix more versions of OpenSSL even in the same binary becase OpenSSL uses proper SONAMEs and all the symbols in the shared library are versioned.

Body:
I am using shippable to build my project and part of it requires PHP.

The build script is this:

apt-get update
apt-get install -y software-properties-common python-software-properties language-pack-en-base
LC_ALL=en_US.UTF-8 add-apt-repository ppa:ondrej/php
apt-get update
apt-get install -y php7.0 php7.0-bcmath

Today the build failed while installing PHP with the following error:

apt-get install -y php7.0 php7.0-bcmath

Reading package lists...
Building dependency tree...
Reading state information...
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 php7.0 : Depends: libapache2-mod-php7.0 but it is not going to be installed or
                   php7.0-fpm but it is not going to be installed or
                   php7.0-cgi but it is not going to be installed
          Depends: php7.0-common but it is not going to be installed
 php7.0-bcmath : Depends: php7.0-common but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

So i started up a local docker container to see if something wierd was happening at shippable - with the following command:

docker run -i -t ubuntu:14.04 /bin/bash

And ran the 5 build lines listed above, and i get the same error. The next thing i did was install aptitude to see if i could get a better error, and ran this aptitude install -y php7.0 php7.0-bcmath - this was the aptitude output:

aptitude install -y php7.0 php7.0-bcmath
The following NEW packages will be installed:
  apache2{a} apache2-bin{a} apache2-data{a} libapache2-mod-php7.0{ab}
  libapr1{a} libaprutil1{a} libaprutil1-dbd-sqlite3{a} libaprutil1-ldap{a}
  libedit2{a} php-common{a} php7.0 php7.0-bcmath php7.0-cli{ab}
  php7.0-common{ab} php7.0-json{a} php7.0-opcache{a} php7.0-readline{a}
  psmisc{a} ssl-cert{a}
0 packages upgraded, 19 newly installed, 0 to remove and 7 not upgraded.
Need to get 4950 kB of archives. After unpacking 20.2 MB will be used.
The following packages have unmet dependencies:
 php7.0-cli : Depends: libssl1.1 (>= 1.1.0) which is a virtual package.
 php7.0-common : Depends: libssl1.1 (>= 1.1.0) which is a virtual package.
 libapache2-mod-php7.0 : Depends: libssl1.1 (>= 1.1.0) which is a virtual package.
The following actions will resolve these dependencies:

     Keep the following packages at their current version:
1)     libapache2-mod-php7.0 [Not Installed]
2)     php7.0 [Not Installed]
3)     php7.0-bcmath [Not Installed]
4)     php7.0-cli [Not Installed]
5)     php7.0-common [Not Installed]
6)     php7.0-json [Not Installed]
7)     php7.0-opcache [Not Installed]
8)     php7.0-readline [Not Installed]

The following NEW packages will be installed:
  psmisc{a}
0 packages upgraded, 1 newly installed, 0 to remove and 7 not upgraded.
Need to get 53.2 kB of archives. After unpacking 229 kB will be used.
Get: 1 http://archive.ubuntu.com/ubuntu/ trusty/main psmisc amd64 22.20-1ubuntu2 [53.2 kB]
Fetched 53.2 kB in 0s (911 kB/s)
Selecting previously unselected package psmisc.
(Reading database ... 14894 files and directories currently installed.)
Preparing to unpack .../psmisc_22.20-1ubuntu2_amd64.deb ...
Unpacking psmisc (22.20-1ubuntu2) ...
Setting up psmisc (22.20-1ubuntu2) ...

I have a couple of questions:

1) How do i fix this? I have done some looking but can't work out how to update libssl

2) Why has this happened all of a sudden, this was never a problem for PHP7.0 before?

Some additional info:

openssl version -a
OpenSSL 1.0.1f 6 Jan 2014
built on: Mon Jan 30 20:38:38 UTC 2017
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/usr/lib/ssl"

uname -a
Linux b5cbe94d7da8 4.9.13-moby #1 SMP Sat Mar 25 02:48:44 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux


问:
Angular 2 - Checked property of radio button on load when it is binded by ngModel
I want to check a radio button on load of the page, which is also two-way binded. It is only happening when the ngModel is removed.</p>

```<code><input [(ngModel)] = "field.value" name="{{field.label}}" type="radio"
             [checked]="option.isDefaultOption=='true'?'true':null"/>
</code>```

答:
Try this in component

```<code>ngOnInit() {

   field.value = true;

}
</code>```

and in the template

```<code> <input [(ngModel)] = "field.value" name="{{field.label}}" type="radio"
         [value]="true" />
</code>```

Body:
I want to check a radio button on load of the page, which is also two-way binded. It is only happening when the ngModel is removed.

<input [(ngModel)] = "field.value" name="{{field.label}}" type="radio"
             [checked]="option.isDefaultOption=='true'?'true':null"/>

Body:
Try this in component

ngOnInit() {

   field.value = true;

}

and in the template

 <input [(ngModel)] = "field.value" name="{{field.label}}" type="radio"
         [value]="true" />


问:
Cannot call CREATE SCHEMA through JDBC in SQL Server
I'm using the official SQL Server JDBC driver:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.2.0.jre8</version>
</dependency>
```

<p>To run this code here:</p>

<pre class="lang-java prettyprint-override"><code>try (Connection c = new com.microsoft.sqlserver.jdbc.SQLServerDriver().connect(u, p)) {
    try (PreparedStatement s1 = c.prepareStatement("create schema x");
         PreparedStatement s2 = c.prepareStatement("drop schema x")) {
        System.out.println(s1.execute());
        System.out.println(s2.execute());
    }
}
</code>```

But I'm getting this error:

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'schema'.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:258)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1547)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:528)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:461)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7151)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2689)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:224)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:204)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.execute(SQLServerPreparedStatement.java:445)
```

<p>Obviuosly, the statements are correct and they work as static statements:</p>

```try (Statement s1 = c.createStatement();
     Statement s2 = c.createStatement()) {
    System.out.println(s1.execute("create schema x"));
    System.out.println(s2.execute("drop schema x"));
}
```

Is this intended, or a bug in the JDBC driver?

答:
This seems to be a regression in version 6.2.0. It used to work in version 6.1.0. I've reported this issue to Microsoft: https://github.com/Microsoft/mssql-jdbc/issues/370

The CREATE VIEW statement is also affected:

// Works on both versions 6.2.0 and 6.1.0
try (Statement s1 = c.createStatement();
     Statement s2 = c.createStatement()) {
    System.out.println(s1.execute("create view x as select 1 a"));
    System.out.println(s2.execute("drop view x"));
}

// Works only on version 6.1.0
try (PreparedStatement s1 = c.prepareStatement("create view x as select 1 a");
     PreparedStatement s2 = c.prepareStatement("drop view x")) {
    System.out.println(s1.execute());
    System.out.println(s2.execute());
}
```

(I'm documenting this here on Stack Overflow because several tools that run DDL, including jOOQ, Hibernate, MyBatis, Flyway, etc. might be affected)

Body:
I'm using the official SQL Server JDBC driver:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.2.0.jre8</version>
</dependency>

To run this code here:

try (Connection c = new com.microsoft.sqlserver.jdbc.SQLServerDriver().connect(u, p)) {
    try (PreparedStatement s1 = c.prepareStatement("create schema x");
         PreparedStatement s2 = c.prepareStatement("drop schema x")) {
        System.out.println(s1.execute());
        System.out.println(s2.execute());
    }
}

But I'm getting this error:

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'schema'.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:258)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1547)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:528)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:461)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7151)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2689)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:224)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:204)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.execute(SQLServerPreparedStatement.java:445)

Obviuosly, the statements are correct and they work as static statements:

try (Statement s1 = c.createStatement();
     Statement s2 = c.createStatement()) {
    System.out.println(s1.execute("create schema x"));
    System.out.println(s2.execute("drop schema x"));
}

Is this intended, or a bug in the JDBC driver?

Body:
This seems to be a regression in version 6.2.0. It used to work in version 6.1.0. I've reported this issue to Microsoft: https://github.com/Microsoft/mssql-jdbc/issues/370

The CREATE VIEW statement is also affected:

// Works on both versions 6.2.0 and 6.1.0
try (Statement s1 = c.createStatement();
     Statement s2 = c.createStatement()) {
    System.out.println(s1.execute("create view x as select 1 a"));
    System.out.println(s2.execute("drop view x"));
}

// Works only on version 6.1.0
try (PreparedStatement s1 = c.prepareStatement("create view x as select 1 a");
     PreparedStatement s2 = c.prepareStatement("drop view x")) {
    System.out.println(s1.execute());
    System.out.println(s2.execute());
}

(I'm documenting this here on Stack Overflow because several tools that run DDL, including jOOQ, Hibernate, MyBatis, Flyway, etc. might be affected)


问:
How to export images from word doc to local drive
I wanted to export the images on the word doc to local drive how can I do it from excel using vba.</p>

```<code>Sub gen_Files()

Dim WdApp As Word.Application, Doc As Word.Document, fPath As String
Dim i As Long

fPath = ThisWorkbook.Path & Application.PathSeparator & "Test.docx"
If fPath = "" Or Dir(fPath) = "" Then MsgBox "Invalid file path.": Exit Sub

Set WdApp = New Word.Application
WdApp.Visible = True
Set Doc = WdApp.Documents.Open(fPath)
Doc.SaveAs2 ThisWorkbook.Path & "\New.docx", FileFormat:=12

For i = 1 To Doc.InlineShapes.Count
    'Doc.InlineShapes(i).Range.ExportAsFixedFormat(ThisWorkbook.Path & Application.PathSeparator & i & ".jpg",wdExportFormatXPS,False,,,,,,,,,,)
Next i

'Save the file and done
Doc.Save
Doc.Close
WdApp.Quit

End Sub
</code>```

答:
The code would be like this.</p>

```<code>Sub gen_Files()

Dim WdApp As Word.Application, Doc As Word.Document, fPath As String
Dim i As Long
Dim cht As Chart, obj As ChartObject
Dim Ws As Worksheet
Dim myFn As String
Dim shp As InlineShape

Set Ws = ActiveSheet

fPath = ThisWorkbook.Path & Application.PathSeparator & "Test.docx"
If fPath = "" Or Dir(fPath) = "" Then MsgBox "Invalid file path.": Exit Sub

Set WdApp = New Word.Application
WdApp.Visible = True
Set Doc = WdApp.Documents.Open(fPath)
Doc.SaveAs2 ThisWorkbook.Path & "\New.docx", FileFormat:=12

For i = 1 To Doc.InlineShapes.Count
    Set shp = Doc.InlineShapes(i)
    shp.Range.CopyAsPicture
    Set obj = Ws.ChartObjects.Add(Range("i1").Left, 0, shp.Width, shp.Height)
    myFn = ThisWorkbook.Path & Application.PathSeparator & i & ".jpg"
    With obj.Chart
        .Paste
        .Export myFn
    End With
    obj.Delete
Next i

'Save the file and done
Doc.Save
Doc.Close
WdApp.Quit

End Sub
</code>```

Body:
I wanted to export the images on the word doc to local drive how can I do it from excel using vba.

Sub gen_Files()

Dim WdApp As Word.Application, Doc As Word.Document, fPath As String
Dim i As Long

fPath = ThisWorkbook.Path & Application.PathSeparator & "Test.docx"
If fPath = "" Or Dir(fPath) = "" Then MsgBox "Invalid file path.": Exit Sub

Set WdApp = New Word.Application
WdApp.Visible = True
Set Doc = WdApp.Documents.Open(fPath)
Doc.SaveAs2 ThisWorkbook.Path & "\New.docx", FileFormat:=12

For i = 1 To Doc.InlineShapes.Count
    'Doc.InlineShapes(i).Range.ExportAsFixedFormat(ThisWorkbook.Path & Application.PathSeparator & i & ".jpg",wdExportFormatXPS,False,,,,,,,,,,)
Next i

'Save the file and done
Doc.Save
Doc.Close
WdApp.Quit

End Sub

Body:
The code would be like this.

Sub gen_Files()

Dim WdApp As Word.Application, Doc As Word.Document, fPath As String
Dim i As Long
Dim cht As Chart, obj As ChartObject
Dim Ws As Worksheet
Dim myFn As String
Dim shp As InlineShape

Set Ws = ActiveSheet

fPath = ThisWorkbook.Path & Application.PathSeparator & "Test.docx"
If fPath = "" Or Dir(fPath) = "" Then MsgBox "Invalid file path.": Exit Sub

Set WdApp = New Word.Application
WdApp.Visible = True
Set Doc = WdApp.Documents.Open(fPath)
Doc.SaveAs2 ThisWorkbook.Path & "\New.docx", FileFormat:=12

For i = 1 To Doc.InlineShapes.Count
    Set shp = Doc.InlineShapes(i)
    shp.Range.CopyAsPicture
    Set obj = Ws.ChartObjects.Add(Range("i1").Left, 0, shp.Width, shp.Height)
    myFn = ThisWorkbook.Path & Application.PathSeparator & i & ".jpg"
    With obj.Chart
        .Paste
        .Export myFn
    End With
    obj.Delete
Next i

'Save the file and done
Doc.Save
Doc.Close
WdApp.Quit

End Sub


问:
How to encrypt the fetched data in jmeter using bean shell?
I have a scenario as follows:
A value is extracted from the server response and is to be encrypted and pass to the subsequent request. How can it be done using bean shell. And what are the jar files I have to include to run the script?

答:
Generally if you have decrypt class e.g. Decryptor in jar e.g. x.jar

Click Test Plan, below in Add Library Click Browse and add your x.jar.

Add Beanshell Sampler (or JSR223 Sampler)

Get encrypted variable e.g. paramName

Put in new variable e.g. paramNameDecrypted the decrypt value

Code:

```<code>import package.Decryptor;

String decryptValue = Decryptor.decrypt(vars.get("paramName"));

vars.put("paramNameDecrypted", decryptValue)
</code>```

Body:
Generally if you have decrypt class e.g. Decryptor in jar e.g. x.jar

Click Test Plan, below in Add Library Click Browse and add your x.jar.

Add Beanshell Sampler (or JSR223 Sampler)

Get encrypted variable e.g. paramName

Put in new variable e.g. paramNameDecrypted the decrypt value

Code:

import package.Decryptor;

String decryptValue = Decryptor.decrypt(vars.get("paramName"));

vars.put("paramNameDecrypted", decryptValue)


问:
Avoiding an incomplete pattern match
Consider the following code:

```<code>data A
data B

f :: A -> B
f = undefined

data T = TA A | TB B
data ListT = ListTA [A] | ListTB [B]

g :: [T] -> ListT
g l =
  let
    f' :: T -> B
    f' (TA x) = f x
    f' (TB x) = x
    isA :: T -> Bool
    isA TA{} = True
    isA TB{} = False
  in
    case (all isA l) of
      True -> ListTA (map (\(TA x) -> x) l)
      False -> ListTB (map f' l)

main = pure ()
</code>```

The idea behind this is I've got a list of either As or Bs mixed together. I can convert A -> B but not the other way around. Based on this list, I want to make either a list of As or list of Bs, the former if all my original list elements are As, the latter if at least one is a B.

The above code compiles (and I'm guessing will work) but the incomplete pattern match in the map (\(TA x) -> x) l makes me just a little uncomfortable. Is such an incomplete match just a necessity of what I'm doing here? Also, am I reinventing the wheel, is there something that generalises what I'm doing here?

答:
After some help from the other answers, I'm going to answer my own question for the benefit of future viewers. I believe the most suscinct function for g is as follows (and noticed I've generalised to Traversable instead of just lists).

```<code>data ListT t = ListTA (t A) | ListTB (t B)

g :: (Traversable t) => t T -> ListT t
g l =
  let
    f2B :: T -> B
    f2B (TA x) = f x
    f2B (TB x) = x
    f2A :: T -> Maybe A
    f2A (TA x) = Just x
    f2A (TB x) = Nothing
  in
    maybe (ListTB (fmap f2B l)) ListTA (traverse f2A l)

main = pure ()
</code>```

On lists, this should only take space proportional to the number of leading As, which is minimal I believe.

Title: Avoiding an incomplete pattern match

Body:
Consider the following code:

data A
data B

f :: A -> B
f = undefined

data T = TA A | TB B
data ListT = ListTA [A] | ListTB [B]

g :: [T] -> ListT
g l =
  let
    f' :: T -> B
    f' (TA x) = f x
    f' (TB x) = x
    isA :: T -> Bool
    isA TA{} = True
    isA TB{} = False
  in
    case (all isA l) of
      True -> ListTA (map (\(TA x) -> x) l)
      False -> ListTB (map f' l)

main = pure ()

The idea behind this is I've got a list of either As or Bs mixed together. I can convert A -> B but not the other way around. Based on this list, I want to make either a list of As or list of Bs, the former if all my original list elements are As, the latter if at least one is a B.

The above code compiles (and I'm guessing will work) but the incomplete pattern match in the map (\(TA x) -> x) l makes me just a little uncomfortable. Is such an incomplete match just a necessity of what I'm doing here? Also, am I reinventing the wheel, is there something that generalises what I'm doing here?

Body:
After some help from the other answers, I'm going to answer my own question for the benefit of future viewers. I believe the most suscinct function for g is as follows (and noticed I've generalised to Traversable instead of just lists).

data ListT t = ListTA (t A) | ListTB (t B)

g :: (Traversable t) => t T -> ListT t
g l =
  let
    f2B :: T -> B
    f2B (TA x) = f x
    f2B (TB x) = x
    f2A :: T -> Maybe A
    f2A (TA x) = Just x
    f2A (TB x) = Nothing
  in
    maybe (ListTB (fmap f2B l)) ListTA (traverse f2A l)

main = pure ()

On lists, this should only take space proportional to the number of leading As, which is minimal I believe.


问:
How can I find out a screen device's power failure : xamarin
Is there an events or way to find out a screen device's power failure.
I need to flag on a remote device if all the parts are working.
I found ways for most off the elements but for the screen I could only find events that tells if screen is on sleep or active but nothings to detect if a screen is powerless or broken. Could not find any code sample to workaround. As a beginner I do not know how to resolve. Anny hints would be welcome.

I haven't started coding this up yet. This is more investigative than anything at this point.

答:
Although I have never tried to detect an error with the screen, it doesn't look like there is much on this. If the screen is broken, the low-level device driver plumbing may not even give you any information or incorrect information. You might check out
DisplayManager as it contains a DisplayListener which may notify you when a display such as the main device display is disconnected but it sounds like it is more for external displays you are connecting to the device. Closest I could find.


问:
How to bind checkBox to a boolean property?
I started using vaadin framework recently.

I have a Form which contains some textFields and a checkbox, my problem is all fields are binding with their properties expect checkbox ??.

This is the form :

```<code>public class ContactForm extends FormLayout {

private Button save = new Button("Save", this::save);
private Button delete = new Button("Delete", this::delete);
private Button cancel = new Button("Cancel", this::cancel);
private TextField firstName = new TextField("First name");
private TextField lastName = new TextField("Last name");
private TextField phone = new TextField("Phone");
private TextField email = new TextField("Email");
private DateField birthDate = new DateField("Birth date");
private CheckBox bookMarks = new CheckBox("BookMarks");

private Contact contact;

// Easily bind forms to beans and manage validation and buffering
private BeanFieldGroup<Contact> formFieldBindings;

public ContactForm() {
    configureComponents();
    buildLayout();
}

private void configureComponents() {...}

private void buildLayout() {...}

void edit(Contact contact) {

    this.contact = contact;
    if (contact != null) {
        // Bind the properties of the contact POJO to fields in this form
        formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this);

        delete.setVisible(contact.getId() != null);
    }

    setVisible(contact != null);
}

@Override
public AddressbookUI getUI() {
    return (AddressbookUI) super.getUI();
}}
</code>```

This is My class Contact :

```<code>public class Contact implements Serializable, Cloneable {

private Long id;

private String firstName = "";
private String lastName = "";
private String phone = "";
private String email = "";
private Date birthDate;
private Boolean bookMarks;

// getters and setters
...
}
</code>```

What am i doing wrong? Should I bind the checkbox field manually ?

答:
You can get the value of check box value onlistenter and set the object explicitly.

```<code>bookMarks.addListener(new ValueChangeListener() {
    public void valueChange(ValueChangeEvent event) {

        contact.setBookMarks(checkbox1.getValue());
    }
});
</code>```

To Know more about checkbox check this link

Body:
I started using vaadin framework recently.

I have a Form which contains some textFields and a checkbox, my problem is all fields are binding with their properties expect checkbox ??.

This is the form :

public class ContactForm extends FormLayout {

private Button save = new Button("Save", this::save);
private Button delete = new Button("Delete", this::delete);
private Button cancel = new Button("Cancel", this::cancel);
private TextField firstName = new TextField("First name");
private TextField lastName = new TextField("Last name");
private TextField phone = new TextField("Phone");
private TextField email = new TextField("Email");
private DateField birthDate = new DateField("Birth date");
private CheckBox bookMarks = new CheckBox("BookMarks");

private Contact contact;

// Easily bind forms to beans and manage validation and buffering
private BeanFieldGroup<Contact> formFieldBindings;

public ContactForm() {
    configureComponents();
    buildLayout();
}

private void configureComponents() {...}

private void buildLayout() {...}

void edit(Contact contact) {

    this.contact = contact;
    if (contact != null) {
        // Bind the properties of the contact POJO to fields in this form
        formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this);

        delete.setVisible(contact.getId() != null);
    }

    setVisible(contact != null);
}

@Override
public AddressbookUI getUI() {
    return (AddressbookUI) super.getUI();
}}

This is My class Contact :

public class Contact implements Serializable, Cloneable {

private Long id;

private String firstName = "";
private String lastName = "";
private String phone = "";
private String email = "";
private Date birthDate;
private Boolean bookMarks;

// getters and setters
...
}

What am i doing wrong? Should I bind the checkbox field manually ?

Body:
You can get the value of check box value onlistenter and set the object explicitly.

bookMarks.addListener(new ValueChangeListener() {
    public void valueChange(ValueChangeEvent event) {

        contact.setBookMarks(checkbox1.getValue());
    }
});

To Know more about checkbox check this link


问:
Change hash without triggering a hashchange event
I'm using the hash to load content dynamically. To make the back button work I am capturing hash changes. However sometimes I need to change the hash without triggering the hash changed function (eg, when the page was redirected server side and I need to update the hash once the content has returned.)

The best solution I have come up with is to unbind the hashchange event, make the change and then rebind it. However, as this happens asynchronously, I am finding that it rebinds too quickly and still catches the hash change.

My solution at the moment is very poor: Rebinding in a setTimeout. Does anyone have a better idea?

```<code>    $(window).unbind( 'hashchange', hashChanged);
    window.location.hash  = "!" + url;
    setTimeout(function(){
        $(window).bind( 'hashchange', hashChanged);
    }, 100);
</code>```

Edit:

Amir Raminfar's suggestion prompted me to a solution that does not require a timeout.
I added a class variable

```<code>_ignoreHashChange = false;
</code>```

When I want to change the hash silently I do this:

```<code>_ignoreHashChange = true;
window.location.hash  = "!" + url;
</code>```

and the hash changed event does this :

```<code>function hashChanged(event){
    if(_ignoreHashChange === false){
        url = window.location.hash.slice(2);
        fetchContent(url);
    }
    _ignoreHashChange = false;
}
</code>```

答:
You could use history.replaceState and append the hash, to replace the current URI without triggering the hashchange event:

```<code>var newHash = 'test';

history.replaceState(null, null, document.location.pathname + '#' + newHash);
</code>```

JSFiddle example

Body:
I'm using the hash to load content dynamically. To make the back button work I am capturing hash changes. However sometimes I need to change the hash without triggering the hash changed function (eg, when the page was redirected server side and I need to update the hash once the content has returned.)

The best solution I have come up with is to unbind the hashchange event, make the change and then rebind it. However, as this happens asynchronously, I am finding that it rebinds too quickly and still catches the hash change.

My solution at the moment is very poor: Rebinding in a setTimeout. Does anyone have a better idea?

    $(window).unbind( 'hashchange', hashChanged);
    window.location.hash  = "!" + url;
    setTimeout(function(){
        $(window).bind( 'hashchange', hashChanged);
    }, 100);

Edit:

Amir Raminfar's suggestion prompted me to a solution that does not require a timeout.
I added a class variable

_ignoreHashChange = false;

When I want to change the hash silently I do this:

_ignoreHashChange = true;
window.location.hash  = "!" + url;

and the hash changed event does this :

function hashChanged(event){
    if(_ignoreHashChange === false){
        url = window.location.hash.slice(2);
        fetchContent(url);
    }
    _ignoreHashChange = false;
}

Body:
You could use history.replaceState and append the hash, to replace the current URI without triggering the hashchange event:

var newHash = 'test';

history.replaceState(null, null, document.location.pathname + '#' + newHash);

JSFiddle example


答:
```<code>SELECT
    FreeText,
    COUNT(case Status WHEN 'BOOKING' then 1 else null end) AS Bookings,
    COUNT(case Status WHEN 'QUOTE' then 1 else null end) AS Quotes,COUNT(1) AS TOTAL
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    OrderDate <= CURDATE()
AND OrderDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
AND FreeText IN ('user1','user2','user3')
AND STATUS IN ('BOOKING', 'QUOTE')
GROUP BY
    FreeText
</code>```

Try above query.

Title: Sum 2 counts from same table at end of row

Body:
I am using the query below to generate the table below that, what I would like is to get the total for each row at the end

SELECT
    FreeText,
    COUNT(case Status WHEN 'BOOKING' then 1 else null end) AS Bookings,
    COUNT(case Status WHEN 'QUOTE' then 1 else null end) AS Quotes
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    OrderDate <= CURDATE()
AND OrderDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
AND FreeText IN ('user1','user2','user3')
AND STATUS IN ('BOOKING', 'QUOTE')
GROUP BY
    FreeText

The above produces this table:

FreeText | Bookings | Quote
User1    | 23       |11
User2    | 11       |17
User3    | 8        |4

What I would like the query to produce:

FreeText | Bookings | Quote | Total
User1    | 23       |11     |34
User2    | 11       |17     |28
User3    | 8        |4      |12

Help much appreciated

Body:
SELECT
    FreeText,
    COUNT(case Status WHEN 'BOOKING' then 1 else null end) AS Bookings,
    COUNT(case Status WHEN 'QUOTE' then 1 else null end) AS Quotes,COUNT(1) AS TOTAL
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    OrderDate <= CURDATE()
AND OrderDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
AND FreeText IN ('user1','user2','user3')
AND STATUS IN ('BOOKING', 'QUOTE')
GROUP BY
    FreeText

Try above query.


答: First and foremost ask yourself are you repeating fields or attributes of fields.  Does your one table contain relationships or attributes that should be separated.  Follow third normal form...we need more info to help but generally speaking one table with thirty six columns smells like a db fart.</p>

Title: do I need multiple tables or single?

Body:
I developing a tool which may got more than a million data to fill in.

current i have designed single table with 36 coloumns. my question is do I need to divide these into multiple tables or single??

If single what is the advantage and disadvantage

if multiple then what is the advantage and disadvantage

and what will be the engine to use for speed...

my concern is a large database which will have atleast 50000 queries perday..

any help??


问:
pymysql incorrect writes to the database the Russian text
I had the following problem: is There a site encoded in windows-1251. I'm using the library BeautifulSoup to get the data you need in Russian language. For testing recorded the values in the file, they are displayed correctly. Then I tried to record this data to the database, but got this error: Warning: (1366, "Incorrect string value: '\\x98\\xD0\\xBD\\xD1\\x82\\xD0...' for column 'description' at row 1")
The database encoding is utf-8.
Below code demonstrates how to read html file:

```<code>def get_html(url):
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
response = urllib.request.urlopen(req)
return response.read()
</code>```

The code below demonstrates how to write values to the database:

```<code>def write_to_db(chars, desc):
    conn = pymysql.connect(host='localhost',
        port=3307,
        user='****',
        password='****',
        db='****',
        charset='utf8',
        cursorclass=pymysql.cursors.DictCursor)

global _id
with conn.cursor() as cursor:
    sql = "INSERT INTO `articles` (`id_cat`, `characteristics`, `description`) VALUES (%s, %s, %s)"
    cursor.execute(sql, (_id, chars, desc))
conn.commit()
</code>```

In the end we get in the database the following characters:РњРѕРґРµР»СЊ

How can I overcome this problem?

答:
Try changing the database encoding to cp1251_general_ci.

On this link you can check the Cyrillic Character Sets and collations.

Body:
I had the following problem: is There a site encoded in windows-1251. I'm using the library BeautifulSoup to get the data you need in Russian language. For testing recorded the values in the file, they are displayed correctly. Then I tried to record this data to the database, but got this error: Warning: (1366, "Incorrect string value: '\\x98\\xD0\\xBD\\xD1\\x82\\xD0...' for column 'description' at row 1")
The database encoding is utf-8.
Below code demonstrates how to read html file:

def get_html(url):
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
response = urllib.request.urlopen(req)
return response.read()

The code below demonstrates how to write values to the database:

def write_to_db(chars, desc):
    conn = pymysql.connect(host='localhost',
        port=3307,
        user='****',
        password='****',
        db='****',
        charset='utf8',
        cursorclass=pymysql.cursors.DictCursor)

global _id
with conn.cursor() as cursor:
    sql = "INSERT INTO `articles` (`id_cat`, `characteristics`, `description`) VALUES (%s, %s, %s)"
    cursor.execute(sql, (_id, chars, desc))
conn.commit()

In the end we get in the database the following characters:РњРѕРґРµР»СЊ

How can I overcome this problem?


问:
Metadata file '.dll' could not be found
I am working on a WPF, C# 3.0 project, and I get this error:

```<code>Error 1 Metadata file
'WORK=- \Tools\VersionManagementSystem\BusinessLogicLayer\bin\Debug
\BusinessLogicLayer.dll' could not be found C:\-=WORK=- \Tools
\VersionManagementSystem\VersionManagementSystem\CSC VersionManagementSystem
</code>```

This is how I reference my usercontrols:

```<code>xmlns:vms="clr-namespace:VersionManagementSystem"
<vms:SignOffProjectListing Margin="5"/>
</code>```

It happens after every failed build. The only way I can get the solution to compile is to comment out all my user controls and re-build the project, and then I uncomment the usercontrols and everything is fine.

I have checked build orders and dependencies configurations.

As you can see, it seems to have truncated the DLL file's absolute path... I have read that there is a bug with the length. Is this a possible problem?

It's very annoying and having to comment, build, and uncomment, the build is becoming extremely tiresome.

答:
I started having this problem after changing the solution a lot, shelving the changes and undoing it.

Only way to solve it was removing and adding again the mapping from TFS to my local folder.

Title: Metadata file '.dll' could not be found

Body:
I am working on a WPF, C# 3.0 project, and I get this error:

Error 1 Metadata file
'WORK=- \Tools\VersionManagementSystem\BusinessLogicLayer\bin\Debug
\BusinessLogicLayer.dll' could not be found C:\-=WORK=- \Tools
\VersionManagementSystem\VersionManagementSystem\CSC VersionManagementSystem

This is how I reference my usercontrols:

xmlns:vms="clr-namespace:VersionManagementSystem"
<vms:SignOffProjectListing Margin="5"/>

It happens after every failed build. The only way I can get the solution to compile is to comment out all my user controls and re-build the project, and then I uncomment the usercontrols and everything is fine.

I have checked build orders and dependencies configurations.

As you can see, it seems to have truncated the DLL file's absolute path... I have read that there is a bug with the length. Is this a possible problem?

It's very annoying and having to comment, build, and uncomment, the build is becoming extremely tiresome.


问:
HTML entity encoding (convert '<' to '<') on iPhone in objective-c
I'm developing an application for the iPhone that has inApp-mail sending capabilities. So far so good, but now I want to avoid html-injections as some parts of the mail are user-generated texts.

Basically I search for something like this:

```<code>// inits
NSString *sourceString = [NSString stringWithString:@"Hello world! Grüße dich Welt <-- This is in German."];

//                                          -----   THAT'S WHAT I'M LOOKING FOR
// pseudo-code                              |
//                                          V
NSString *htmlEncodedString = [sourceString htmlEncode];

// log
NSLog(@"source string: %@", sourceString);
NSLog(@"encoded string: %@", htmlEncodedString);
</code>```

Expected output

source string: Hello world! Grüße dich Welt <-- This is in German.

encoded string: Hello world! Grüße dich Welt <-- This is in German.

I already googled and looked through several of SO's questions and answers, but all of them seem to be related to URL-encoding and that's not what I really need (I tried stringByAddingPercentEscapesUsingEncoding with no luck - it creates %C3%BC out of an 'ü' that should be an ü).

A code sample would be really great (correcting mine?)...

--

Thanks in advance,

Markus

答:
I'm expanding @Markus answer, because my case is i'm sending JSON string, so i need to added some escape, these are my function :

note :
the exception reference from w3schools. https://www.w3schools.com/tags/ref_urlencode.asp

```<code>- (NSString*)convertStringToHTMLEscape:(NSString*)stringContent
{
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"{" withString:@"%7B"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"}" withString:@"%7D"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"[" withString:@"%5B"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"]" withString:@"%5D"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"\"" withString:@"%22"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"\\" withString:@"%5C"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"/" withString:@"%2F"];

    return stringContent;
}
</code>```

Body:
I'm developing an application for the iPhone that has inApp-mail sending capabilities. So far so good, but now I want to avoid html-injections as some parts of the mail are user-generated texts.

Basically I search for something like this:

// inits
NSString *sourceString = [NSString stringWithString:@"Hello world! Grüße dich Welt <-- This is in German."];

//                                          -----   THAT'S WHAT I'M LOOKING FOR
// pseudo-code                              |
//                                          V
NSString *htmlEncodedString = [sourceString htmlEncode];

// log
NSLog(@"source string: %@", sourceString);
NSLog(@"encoded string: %@", htmlEncodedString);

Expected output

source string: Hello world! Grüße dich Welt <-- This is in German.

encoded string: Hello world! Grüße dich Welt <-- This is in German.

I already googled and looked through several of SO's questions and answers, but all of them seem to be related to URL-encoding and that's not what I really need (I tried stringByAddingPercentEscapesUsingEncoding with no luck - it creates %C3%BC out of an 'ü' that should be an ü).

A code sample would be really great (correcting mine?)...

--

Thanks in advance,

Markus

Body:
I'm expanding @Markus answer, because my case is i'm sending JSON string, so i need to added some escape, these are my function :

note :
the exception reference from w3schools. https://www.w3schools.com/tags/ref_urlencode.asp

- (NSString*)convertStringToHTMLEscape:(NSString*)stringContent
{
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"{" withString:@"%7B"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"}" withString:@"%7D"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"[" withString:@"%5B"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"]" withString:@"%5D"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"\"" withString:@"%22"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"\\" withString:@"%5C"];
    stringContent = [stringContent stringByReplacingOccurrencesOfString:@"/" withString:@"%2F"];

    return stringContent;
}


问:
Multiple prepared statements on same page MYSQLI
I have some issues with my code. It seems like I'm not able to have multiple prepared statements which seems a little unusual to me.

I would be glad if you can spot an error or help me because I can't figure out the issue.

My error:

Fatal error: Call to a member function bind_param() on boolean in /Applications/XAMPP/xamppfiles/htdocs/platform/creating_user.php on line 37

I am trying to check if the users email already exists in the database and then register the user.

The code works fine when i dont execute the $check.

```<code>$check->execute();
</code>```

I would also like some response on my workflow (the way my code is built up). is it okay?

Thanks!

```<code><?php

$db = new mysqli("localhost","root","","database");
session_start();

if (isset($_POST)){
    if(
        !empty($_POST["name"])
      & !empty($_POST["city"])
      & !empty($_POST["zip"])
      & !empty($_POST["email"])
      & !empty($_POST["tel"])
      & !empty($_POST["password"])
    ) {

        $name       = encrypt($_POST["name"]);
        $city       = encrypt($_POST["city"]);
        $zip        = encrypt($_POST["zip"]);
        $email      = encrypt($_POST["email"]);
        $tel        = encrypt($_POST["tel"]);
        $password   = encrypt($_POST["password"]);

        if(!empty($name) && !empty($city) && !empty($zip) && !empty($email) && !empty($tel) && !empty($password)) {

            $check = $db->prepare("SELECT email FROM user WHERE email = ?");
            $check->bind_param('s', $email);
            $check->execute();

            if ($check->num_rows == 1) {
                header("Location: index.php");
                die();
            } else {

            $insert = $db->prepare("INSERT INTO user (name, city, zip, email, tel, password, created) VALUES (?, ?, ?, ?, ?, ?, NOW())");
            $insert->bind_param("ssssss",$name, $city, $zip, $email, $tel, $password);

            if ($insert->execute()){

                $db->close();
                $_SESSION["user"] = $email;
                header("Location: created_user");
                die();

            } else {
                header("Location: create-user");
                die();
            }

        }

        } else {
            header("Location: create-user");
            die();
        }

    } else {
        header("Location: create-user");
        die();
    }
} else {
    header("Location: create-user");
    die();
}

?>
</code>```

答:
On php.net I found this

mysqli::prepare() returns a statement object or FALSE if an error
  occurred.

So this mean something is wrong with your $db object. This could be:

Wrong password

Wrong username

...

Body:
I have some issues with my code. It seems like I'm not able to have multiple prepared statements which seems a little unusual to me.

I would be glad if you can spot an error or help me because I can't figure out the issue.

My error:

Fatal error: Call to a member function bind_param() on boolean in /Applications/XAMPP/xamppfiles/htdocs/platform/creating_user.php on line 37

I am trying to check if the users email already exists in the database and then register the user.

The code works fine when i dont execute the $check.

$check->execute();

I would also like some response on my workflow (the way my code is built up). is it okay?

Thanks!

<?php

$db = new mysqli("localhost","root","","database");
session_start();

if (isset($_POST)){
    if(
        !empty($_POST["name"])
      & !empty($_POST["city"])
      & !empty($_POST["zip"])
      & !empty($_POST["email"])
      & !empty($_POST["tel"])
      & !empty($_POST["password"])
    ) {

        $name       = encrypt($_POST["name"]);
        $city       = encrypt($_POST["city"]);
        $zip        = encrypt($_POST["zip"]);
        $email      = encrypt($_POST["email"]);
        $tel        = encrypt($_POST["tel"]);
        $password   = encrypt($_POST["password"]);

        if(!empty($name) && !empty($city) && !empty($zip) && !empty($email) && !empty($tel) && !empty($password)) {

            $check = $db->prepare("SELECT email FROM user WHERE email = ?");
            $check->bind_param('s', $email);
            $check->execute();

            if ($check->num_rows == 1) {
                header("Location: index.php");
                die();
            } else {

            $insert = $db->prepare("INSERT INTO user (name, city, zip, email, tel, password, created) VALUES (?, ?, ?, ?, ?, ?, NOW())");
            $insert->bind_param("ssssss",$name, $city, $zip, $email, $tel, $password);

            if ($insert->execute()){

                $db->close();
                $_SESSION["user"] = $email;
                header("Location: created_user");
                die();

            } else {
                header("Location: create-user");
                die();
            }

        }

        } else {
            header("Location: create-user");
            die();
        }

    } else {
        header("Location: create-user");
        die();
    }
} else {
    header("Location: create-user");
    die();
}

?>


问:
Make a UITableView "sticky to the bottom"
Say you have a table view T which shows messages,

```<code>T[ message d
T[ message c
T[ message b
T[ most recent message down bottom
</code>```

Say there are 100 messages, with the bottom 4 visible in the example.

So the table view height is 700 say.  You have a typical text entry underneath...

```<code>T[ message d
T[ message c
T[ message b
T[ most recent message down bottom
[enter snapped chat message!] [send]
</code>```

When the keyboard appears, the new height of the visible table view is 400 say.

Of course, that will "cut off the bottom" of the messages - the most recent two will no longer be visible.

```<code>T[ message d
T[ message c
[enter snapped chat message!] [send]
[           iOS keyboard        ]
[           iOS keyboard        ]
</code>```

(So, messages A and B are now "under" the keyboard.)

Naturally what you do is just scroll the table after the keyboard appears, for example.  No problem doing it in an ad-hoc manner.

However, it would be really natural if one could subclass UITableView in such a way that, as the size of the visible area changed, the table view knew to keep the "bottom point" identical.

So, as the bottom of the table moves up and down (due to keyboard appearing - or whatever cause), the table would scroll actually based on the movement of the "base" of the table.

(Apart from anything else this would solve the "match the animation timing" nuisance.)

Could this be achieved elegantly and if so how - indeed this would seem so natural these days, perhaps it's built-in to UITableView as a flag and I just don't know?

once again the question here is

How to modify UITableView so that it moves its own scroll position, as, the view size changes...

(so as to keep the "bottom point the same")

Note that it's trivial to just scroll the table "manually" as it were from the outside.

答:
As far as I know, you have a few choices for doing this:

If you have the indexPath of the row you want to be visible:

```<code>tableView.ScrollToRow(indexPath, UITableViewScrollPosition.Top, true);
</code>```

This will scroll to the cell given by the indexPath. In this case you are  selecting the option to show it on the .Top of the screen.

If you don't have the indexPath, you can use:

```<code>tableView.ScrollRectToVisible(new RectangleF(0, Ydisplacement, tableView.Width, tableView.Height), true);
</code>```

Body:
Say you have a table view T which shows messages,

T[ message d
T[ message c
T[ message b
T[ most recent message down bottom

Say there are 100 messages, with the bottom 4 visible in the example.

So the table view height is 700 say.  You have a typical text entry underneath...

T[ message d
T[ message c
T[ message b
T[ most recent message down bottom
[enter snapped chat message!] [send]

When the keyboard appears, the new height of the visible table view is 400 say.

Of course, that will "cut off the bottom" of the messages - the most recent two will no longer be visible.

T[ message d
T[ message c
[enter snapped chat message!] [send]
[           iOS keyboard        ]
[           iOS keyboard        ]

(So, messages A and B are now "under" the keyboard.)

Naturally what you do is just scroll the table after the keyboard appears, for example.  No problem doing it in an ad-hoc manner.

However, it would be really natural if one could subclass UITableView in such a way that, as the size of the visible area changed, the table view knew to keep the "bottom point" identical.

So, as the bottom of the table moves up and down (due to keyboard appearing - or whatever cause), the table would scroll actually based on the movement of the "base" of the table.

(Apart from anything else this would solve the "match the animation timing" nuisance.)

Could this be achieved elegantly and if so how - indeed this would seem so natural these days, perhaps it's built-in to UITableView as a flag and I just don't know?

once again the question here is

How to modify UITableView so that it moves its own scroll position, as, the view size changes...

(so as to keep the "bottom point the same")

Note that it's trivial to just scroll the table "manually" as it were from the outside.

Body:
As far as I know, you have a few choices for doing this:

If you have the indexPath of the row you want to be visible:

tableView.ScrollToRow(indexPath, UITableViewScrollPosition.Top, true);

This will scroll to the cell given by the indexPath. In this case you are  selecting the option to show it on the .Top of the screen.

If you don't have the indexPath, you can use:

tableView.ScrollRectToVisible(new RectangleF(0, Ydisplacement, tableView.Width, tableView.Height), true);


问:
Cast List<int> to List<string> in .NET 2.0
Can you cast a List<int> to List<string> somehow?

I know I could loop through and .ToString() the thing, but a cast would be awesome.

I'm in C# 2.0 (so no LINQ).

答:
You wouldn't be able to directly cast it as no explicit or implicit cast exists from int to string, it would have to be a method involving .ToString() such as:-

```<code>foreach (int i in intList) stringList.Add(i.ToString());
</code>```

Edit - or as others have pointed out rather brilliantly, use intList.ConvertAll(delegate(int i) { return i.ToString(); });, however clearly you still have to use .ToString() and it's a conversion rather than a cast.

OwnerDisplayName: lomaxx

Body:
You wouldn't be able to directly cast it as no explicit or implicit cast exists from int to string, it would have to be a method involving .ToString() such as:-

foreach (int i in intList) stringList.Add(i.ToString());

Edit - or as others have pointed out rather brilliantly, use intList.ConvertAll(delegate(int i) { return i.ToString(); });, however clearly you still have to use .ToString() and it's a conversion rather than a cast.

OwnerDisplayName: kronoz

LastEditorDisplayName: kronoz


问:
MMORPG protocol encryption
Anyone know what the trend is with MMORPG developers encryption their client/server protocols these days?

The pro's and con's are as follows.

Encrypting protocol:

protects trade secrets regarding client/server protocol to a degree?

Botting isn't stopped, it is only changed because people will create bots which read screen states and trigger mouse+keyboard events will then be developed, merely mitigating the development of bots as opposed to stopping them in anyway. Still though bot development is less in supply somewhat, but the demand is still there, they merely get higher bids on rentacoder.com

Regular plain text:

more advanced bots since the developers are able to inject their own datagrams into the client/server protocol. (ie: running through walls, teleporting... which the server side has to now check, which in turn leads to a development contest between out patching exploits via injection (time consuming)

答: The main reason why developers should add encryption to their protocols is marketing reasons. They simply just need to ensure that their server will be only one (for example if they will (or already) want to make paid membership) and no one will just write his own emulator of server after discovering of protocol and will offer it for free.</p>

OwnerDisplayName: Zombies

Title: MMORPG protocol encryption

OwnerDisplayName: Dmitriy Matveev