问:
How to change TimePicker's timePickerMode spinner without xml?
I'm making a project which is used dynamic time picker. I created my time picker but it is default clock mode. Just I want to change it with spinner mode. How can I change it in my activity class?

Here is the my code:

```<code>TimePicker timePicker = new TimePicker(this);
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1_);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ll.addView(timePicker, lp);
</code>```

答:
Use this

```<code>    String laterTime;
</code>```

Call this method any where you want

```<code>    private void openTimePicker() {
    Calendar mcurrentTime = Calendar.getInstance();
    int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
    int minute = mcurrentTime.get(Calendar.MINUTE);
    TimePickerDialog mTimePicker;
    mTimePicker = new TimePickerDialog(LabCheckOutActivity.this, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
            //  seheduleTimeTV.setText( selectedHour + ":" + selectedMinute);
            laterTime = selectedHour + ":" + selectedMinute;
            Log.e("TIME",""+laterTime);

        }
    }, hour, minute, true);//Yes 24 hour time
    mTimePicker.setTitle("Sehedule Time");

    mTimePicker.show();
}
</code>```

Body:
I'm making a project which is used dynamic time picker. I created my time picker but it is default clock mode. Just I want to change it with spinner mode. How can I change it in my activity class?

Here is the my code:

TimePicker timePicker = new TimePicker(this);
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1_);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ll.addView(timePicker, lp);

Body:
Use this

    String laterTime;

Call this method any where you want

    private void openTimePicker() {
    Calendar mcurrentTime = Calendar.getInstance();
    int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
    int minute = mcurrentTime.get(Calendar.MINUTE);
    TimePickerDialog mTimePicker;
    mTimePicker = new TimePickerDialog(LabCheckOutActivity.this, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
            //  seheduleTimeTV.setText( selectedHour + ":" + selectedMinute);
            laterTime = selectedHour + ":" + selectedMinute;
            Log.e("TIME",""+laterTime);

        }
    }, hour, minute, true);//Yes 24 hour time
    mTimePicker.setTitle("Sehedule Time");

    mTimePicker.show();
}


来源: stackexchange

问:
What is the maximum (practical) number of nodes in an Erlang system
I wish to create a platform as a service in the financial markets using Erlang/Elixir. I will provide AWS lambda-style functions in financial markets, but rather than being accessible via web/rest/http, I plan to distribute my own ARM-based hardware terminals to clients (Nvidia Jetson TX2-based or similar, so decent hardware). They will access the functions from these terminals. I want said terminals to be full nodes in the system. So they will use the actor model to message pass to my central servers, and indeed, the terminals might message pass amongst each other if terminal users decide to put their own functions online.

Is this a viable model? Could I run 1000 terminals like this? 100 000? What kinds of limitations might I start bumping into? Is Erlang message routing scalable enough to imagine such a network still being performant if we had soft-real time financial markets streaming data flowing around? (mostly from central servers to terminals, but a good proportion possible moving directly around from terminal to terminal). We could have a system where up to 100k or more different "subscription" data channel processes were available, many of them taking input and producing output every second.

Basically I'd like a canonical guide to the scalability capabilities of an Erlang system something like the above. Ideally I'd also like some guide to the security implications of such a system ie. would global routing tables or any other part of the system be compromisable by a rogue terminal user, or can edge nodes be partly "sealed off" from sensitive parts of the rest of the Erlang network?

Note that I'd want to make heavy use of ports/NIFs for high-compute processes.

答:
I would not pursue this avenue for various reasons, all of which hark back to the sort of systems that Erlang's distribution mechanism was developed for - a set of boards on a passive backplane: "free" local bandwidth and the whole machine sits in the same security domain. The Erlang distribution protocol is probably too chatty to work well on widely spread and large networks, and it is certainly too insecure. Unless you want nodes to be able to execute :os.cmd("rm -rf /") on each other, of course.

Use the Erlang distribution protocol in your central system to your heart's content, and have these terminals talk something that's data-only-over-SSL to that system and each other. On top of that, you can quite simply build a sort of overlay network to do whatever you want.

ContentLicense: CC BY-SA 3.0


问:
Set item to higher highlight priority on vim
I want to non ascii characters to show as discussed here, but the syntax highlight disappears when the non ascii character are inside a comment. Investigating a little the problem, I've discovered at the vim-manual that an item that starts earlier has higher priority (3rd item). From help :syn-priority:

When several syntax items may match, these rules are used:

When multiple Match or Region items start in the same position, the item    defined last has priority.

A Keyword has priority over Match and Region items.

An item that starts in an earlier position has priority over items that     start in later positions.

I am currently using this:

```<code>syntax match nonascii "[^\x00-\x7F]"
highlight nonascii cterm=underline ctermfg=red ctermbg=none term=underline
</code>```

I tried to give higher priority to nonascii match item using the options nextgroup:

```<code>syntax match nonascii "[^\x00-\x7F]" nextgroup=Comment
</code>```

and contains options:

```<code>syntax match nonascii "[^\x00-\x7F]" contains=ALL
</code>```

but it didn't work. I also tried to disable comments temporarily (highlight clear Comment) without the desired effect (my comments got without highlight, but the nonascii continued unhighlighted). What I am missing?

答:
Someone already have answered the question. However, for others that are still having problems, here is another solution to highlight non-ascii characters in comments (or any group in the matter). It's not the best, but it's a temporary fix.

One may try:

```<code>:syntax match nonascii "[^\u0000-\u007F]" containedin=ALL contained |
            \ highlight nonascii ctermfg=yellow guifg=yellow
</code>```

It's very close to the original implementation and other solution. You may even remove contained, but, from documentation, there may be potential problem of recursing itself (as I understand). To view other defined patterns,  syn-contains section would contain it.

```<code>:help syn-containedin
:help syn-contains
</code>```

Body:
I want to non ascii characters to show as discussed here, but the syntax highlight disappears when the non ascii character are inside a comment. Investigating a little the problem, I've discovered at the vim-manual that an item that starts earlier has higher priority (3rd item). From help :syn-priority:

When several syntax items may match, these rules are used:

When multiple Match or Region items start in the same position, the item    defined last has priority.

A Keyword has priority over Match and Region items.

An item that starts in an earlier position has priority over items that     start in later positions.

I am currently using this:

syntax match nonascii "[^\x00-\x7F]"
highlight nonascii cterm=underline ctermfg=red ctermbg=none term=underline

I tried to give higher priority to nonascii match item using the options nextgroup:

syntax match nonascii "[^\x00-\x7F]" nextgroup=Comment

and contains options:

syntax match nonascii "[^\x00-\x7F]" contains=ALL

but it didn't work. I also tried to disable comments temporarily (highlight clear Comment) without the desired effect (my comments got without highlight, but the nonascii continued unhighlighted). What I am missing?

Body:
Someone already have answered the question. However, for others that are still having problems, here is another solution to highlight non-ascii characters in comments (or any group in the matter). It's not the best, but it's a temporary fix.

One may try:

:syntax match nonascii "[^\u0000-\u007F]" containedin=ALL contained |
            \ highlight nonascii ctermfg=yellow guifg=yellow

It's very close to the original implementation and other solution. You may even remove contained, but, from documentation, there may be potential problem of recursing itself (as I understand). To view other defined patterns,  syn-contains section would contain it.

:help syn-containedin
:help syn-contains


问:
on click the control's size changes
I have an input type as below with me for the Date of Birth.

```<code><div class="input-div spanicon">
   <input placeholder="Enter Date of Birth" class="textbox-n" type="text" id="txtDOB">
   <i class="fa fa-calendar" id="triggerCal" aria-hidden="true"></i>
</div>
</code>```

Here's the fiddle for the same.

On click of the icon, field's size changes, Can someone help on this.

答:
Give a static width to input

 // Event to trigger the calendar in the signup page
 $("#triggerCal").click(function() {
   $("#txtDOB").attr("type", "date");
   $("#txtDOB").focus();
   $("#txtDOB").click();
 });

 // Focus out event of the textbox
 $("body").on("focusout", "#txtDOB", function() {
   $("#txtDOB").attr("type", "text");
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body.signup-page .login-form form input {
  padding: 0 20px;
}

style.css:841 .input-div.spanicon input {
  float: left;
  position: relative;
  width: 85%;
}

style.css:275 .login-form form input {
  background-color: #ebf7fa;
  border: 0px;
  font-size: 14px;
  color: #000;
  outline: none;
  border-radius: 5px;
  height: 40px;
  line-height: 15px;
  margin-bottom: 10px;
  padding: 0 5px 0 45px;
  width: 100%;
  display: block;
  -webkit-box-shadow: 0px 2px 2px 0px rgba(50, 50, 50, 0.28);
  -moz-box-shadow: 0px 2px 2px 0px rgba(50, 50, 50, 0.28);
  box-shadow: 0px 2px 2px 0px rgba(50, 50, 50, 0.28);
}
.textbox-n{
  width:180px;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

  <input placeholder="Enter Date of Birth" class="textbox-n" type="text" id="txtDOB">

```

Title: on click the control's size changes

Body:
I have an input type as below with me for the Date of Birth.

   <input placeholder="Enter Date of Birth" class="textbox-n" type="text" id="txtDOB">

Here's the fiddle for the same.

On click of the icon, field's size changes, Can someone help on this.

Body:
Give a static width to input

 // Event to trigger the calendar in the signup page
 $("#triggerCal").click(function() {
   $("#txtDOB").attr("type", "date");
   $("#txtDOB").focus();
   $("#txtDOB").click();
 });

 // Focus out event of the textbox
 $("body").on("focusout", "#txtDOB", function() {
   $("#txtDOB").attr("type", "text");
 });

body.signup-page .login-form form input {
  padding: 0 20px;
}

style.css:841 .input-div.spanicon input {
  float: left;
  position: relative;
  width: 85%;
}

style.css:275 .login-form form input {
  background-color: #ebf7fa;
  border: 0px;
  font-size: 14px;
  color: #000;
  outline: none;
  border-radius: 5px;
  height: 40px;
  line-height: 15px;
  margin-bottom: 10px;
  padding: 0 5px 0 45px;
  width: 100%;
  display: block;
  -webkit-box-shadow: 0px 2px 2px 0px rgba(50, 50, 50, 0.28);
  -moz-box-shadow: 0px 2px 2px 0px rgba(50, 50, 50, 0.28);
  box-shadow: 0px 2px 2px 0px rgba(50, 50, 50, 0.28);
}
.textbox-n{
  width:180px;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="input-div spanicon">
  <input placeholder="Enter Date of Birth" class="textbox-n" type="text" id="txtDOB">
  <i class="fa fa-calendar" id="triggerCal" aria-hidden="true"></i></div>


问:
When using Bootstrap 3 and 4, what is a proper way to set a maximum width for the page content?
The reason of doing this is so that when the window is too wide, and the layout is that the information on the page will be too loose if it is spread out beyond a width of 1000px.

I could think of

```<code>body { max-width: 1000px }
</code>```

but what if you can have footer that can span the whole width? So what about if the main content part of the page is inside

```<code><div id="root">

</div>
</code>```

or

```<code><main id="main">

</main>
</code>```

then just use

```<code>#root { max-width: 1000px }
</code>```

or

```<code>main { max-width: 1000px }
</code>```

Is it a good way to do it together with the styling rules of Bootstrap 3 and 4?

答:
There's not a defined proper way. The Bootstrap way is to use a container (defined width), or container-fluid (full width). If you want a page width other than container, define a custom "wrapper" class, and use a container-fluid inside it...

```<code>.wrapper {
   max-width: 1000px;
   margin: 0 auto;
}

<div class="wrapper">
  <div class="container-fluid">
  </div>
</div>
<footer></footer>
</code>```

On 2nd thought, it would be better to customize container since you want the content centered like the container.

```<code>@media (min-width: 1200px) {
    .container.container-custom {
        max-width: 1000px;
    }
}
</code>```

Demo: http://www.codeply.com/go/k5QtAfRysh

It's really a custom approach either way, and there's no "proper way"

Body:
The reason of doing this is so that when the window is too wide, and the layout is that the information on the page will be too loose if it is spread out beyond a width of 1000px.

I could think of

body { max-width: 1000px }

but what if you can have footer that can span the whole width? So what about if the main content part of the page is inside

or

then just use

#root { max-width: 1000px }

or

main { max-width: 1000px }

Is it a good way to do it together with the styling rules of Bootstrap 3 and 4?

Body:
There's not a defined proper way. The Bootstrap way is to use a container (defined width), or container-fluid (full width). If you want a page width other than container, define a custom "wrapper" class, and use a container-fluid inside it...

.wrapper {
   max-width: 1000px;
   margin: 0 auto;
}

<div class="wrapper">
  <div class="container-fluid">
  </div>
</div>
<footer></footer>

On 2nd thought, it would be better to customize container since you want the content centered like the container.

@media (min-width: 1200px) {
    .container.container-custom {
        max-width: 1000px;
    }
}

Demo: http://www.codeply.com/go/k5QtAfRysh

It's really a custom approach either way, and there's no "proper way"


问:
Drop down menu list problems
I am trying to make the drop down menu lists display inline(horizontally) but end up vertically. If I set the ul_dropdown width to 600px or so, it'll do the result I want. However, I want it to do it without me setting the width. Here's my simplified html/css:</p>

```<code><style type="text/css">
#menu {
 list-style:none;
}

#menu .item{
 display:inline;
 position:relative;
 float:left;
 width:100px;
 height:20px;
 text-align:center;
}

#menu .item .ul_dropdown{
    position:absolute;
 float:left;
    left:-999em;
 list-style:none;
 margin:0px;
 padding:0px;
 border:2px solid red;

}

#menu .item .ul_dropdown li h3{
 margin:0px;
 padding:0px;
}

#menu .item .ul_dropdown li{
 display:inline;
 position:relative;
 float:left;
 list-style:none;
 margin-right:1px;
}

#menu .item .ul_dropdown li ul{
 display:inline!important;
 position:relative;
 float:left;
 padding:0px;
 margin:0px;
 width:200px;
}

#menu .item .ul_dropdown li ul li{
 border:1px solid blue;
 width:200px;
 height:22px;
}

#menu .item:hover{
 background-color:red;
}

#menu .item:hover .ul_dropdown {
 left:0px;
 top:auto;
}

#menu .item:hover .ul_dropdown li
{
 display:inline;
 width:200px;
}

</style>
<ul id="menu">
 <li class="item">Main
    <ul class="ul_dropdown">
     <li><h3>Sales</h3>
         <ul>
             <li>Sales Sample 1</li>
                <li>Sales Sample 2</li>
                <li>Sales Sample 3</li>
            </ul>
        </li>
     <li><h3>Invoice</h3>
         <ul>
             <li>Invoice Sample 1</li>
                <li>Invoice Sample 2</li>
            </ul>
     </li>
     <li><h3>Deal</h3>
         <ul>
             <li>Deal Sample 1</li>
                <li>Deal Sample 2</li>
                <li>Deal Sample 3</li>
            </ul>
     </li>
    </ul>

    <li class="item">1st Menu
    </li>

    <li class="item">2nd Menu
    </li>

    <li class="item">3rd Menu
    </li>
</ul>
</code>```

答: Use display:inline-block; and/or float:left; for your li's. Has to work!

ContentLicense: CC BY-SA 2.5

Title: Drop down menu list problems

Body:
I am trying to make the drop down menu lists display inline(horizontally) but end up vertically. If I set the ul_dropdown width to 600px or so, it'll do the result I want. However, I want it to do it without me setting the width. Here's my simplified html/css:

Main

Sales

Sales Sample 1

Sales Sample 2

Sales Sample 3

Invoice

Invoice Sample 1

Invoice Sample 2

Deal

Deal Sample 1

Deal Sample 2

Deal Sample 3

1st Menu

2nd Menu

3rd Menu


问:
How can I add a Mongo Query inside one Document and insert it in a Collection?
This a sample document. I wish to insert a MongoDB query in the field "condition".

So how to insert it?

```<code>{
    "_id": 9000001,
    "GeoId": 111002,
    "collection": "Age",
    "condition": "{ db.age.find({"Fields.FieldValue" : ""})}",
    "alertMessageTemplate": "The age is #<20#  & #>100# ",
}
</code>```

答:
My best approach will be collection name and condition is separate fields:

```<code>"collection": "Age",
"condition": {"Fields.FieldValue" : ""},
</code>```

This way you can save condition as a JSON object.

Then you can format on find: db.getCollection('+collection+').find('+condition+');

Body:
This a sample document. I wish to insert a MongoDB query in the field "condition".

So how to insert it?

{
    "_id": 9000001,
    "GeoId": 111002,
    "collection": "Age",
    "condition": "{ db.age.find({"Fields.FieldValue" : ""})}",
    "alertMessageTemplate": "The age is #<20#  & #>100# ",
}

Body:
My best approach will be collection name and condition is separate fields:

"collection": "Age",
"condition": {"Fields.FieldValue" : ""},

This way you can save condition as a JSON object.

Then you can format on find: db.getCollection('+collection+').find('+condition+');


问:
How to use href correcly with Angular routing?
Here, how I have configured the routing

```<code>var config = function (rp) {
    rp.when(
        '/docs',
        {
            templateUrl: 'Docs.htm'
        }
    );
};
config.$inject = ['$routeProvider'];
app.config(config);
</code>```

then I added

```<code><a href="#docs">Docs</a>
</code>```

to my htm page.

when the link is clicked, URL is changed to

my_pagename.htm#!#docs

and it does not load the template.

but when I manually type the URL in location as

my_pagename.htm#!/docs (replaced hash symbol with '/')

it loads fine.

Can you please tell me the error here?

what is the proper way of specifying the href attribute, in order to work with angular routing?
My angular version is 1.6.3

答:
I don't know the consequences, but I changed the hrefs to

```<code>    #!/<link>

Ex: #!/docs
    #!/contacts
</code>```

and now they work fine.

note that I didn't change route paths in js file.

Body:
Here, how I have configured the routing

var config = function (rp) {
    rp.when(
        '/docs',
        {
            templateUrl: 'Docs.htm'
        }
    );
};
config.$inject = ['$routeProvider'];
app.config(config);

then I added

Docs

to my htm page.

when the link is clicked, URL is changed to

my_pagename.htm#!#docs

and it does not load the template.

but when I manually type the URL in location as

my_pagename.htm#!/docs (replaced hash symbol with '/')

it loads fine.

Can you please tell me the error here?

what is the proper way of specifying the href attribute, in order to work with angular routing?
My angular version is 1.6.3

Body:
I don't know the consequences, but I changed the hrefs to

    #!/<link>

Ex: #!/docs
    #!/contacts

and now they work fine.

note that I didn't change route paths in js file.


问:
What would be an ideal data structure to represent an image matrix?
As I'm doing a computer vision library, I wondered what would be the ideal data structure to save an image's data.

Someone told me that doing an std::vector imbrication is pretty bad since data contiguity isn't guaranteed, thus a simple one is more efficient.

Problem is, the vector's content has to be colorspace-dependant. Plus, for size issues it would be best to have an unsigned char per channel, though I'd be better off having floats to perform operations.

To handle colorspaces, should I increase the size of the vector (like tripling it to handle RGB), so I could access data like this:

```<code>data[0] => pixel 1, Red
data[1] => pixel 1, Green
data[2] => pixel 1, Blue
data[3] => pixel 2, Red
data[4] => pixel 2, Green
... etc
</code>```

Or is it possible to do this more efficiently (like using a long int or a float to keep all channel's values into one single variable) and if so, how? How could I make this generic to handle 1, 2, 3 or 4 channels so that I can change colorspace (relatively) easily?

The question is not about the container (I am using a single std::vector already), but the content itself.

EDIT: Since this question has been marked as primarily opinion-based, I will try to make it clearer.

At the moment, I'm storing an image's data in a std::vector<float>. The problem here is that I don't know how many items to store (e.g. 3 times the size to handle RGB/HSV, or implementing a 4-items struct (RGBA) even when I'm only using one (grayscale)?) in order to efficiently change colorspace or perform operations on matrices when I need to. As this is meant to be integrated in a computer vision library, it is highly likely to happen at least once every frame.

I'm asking for something efficient in my case here, which has nothing (or very little) to do with opinion. There could be several good answers and chosing among them relies on opinion, but this is supposed to be my call.

答:
What is the "best" data structure for an image data highly depends on what kind of operations you want to perform on the image, and mostly on what operations you want to have optimized performances.

Usually a std::vector of bytes can be enough (for the whole image, not a vector for each single line); a vector guarantees that data is stored in a contiguous block of memory, which may or may not fit your use cases (i.e. it doesn't if you need to manage strides longer than scanlines).

If you need more fine-grained access to the pixelformat information (i.e. single color components), you may want to use a custom defined structure for pixel representation.

Also, data structure may be more complex depending on which kind of images you need to manage.
I.e. are you limited to 1 or a few pixelformats?
Are you limited to "packed" images (sequential color components in 1 "plane") or do you need to manage also "planar" images (multiple "planes", one for each color component)?

You may also look at some available graphics libraries on the web.

One that (in my opinion) has an interesting pixel components management (with custom iterators and other facilities) is Boost GIL

Body:
As I'm doing a computer vision library, I wondered what would be the ideal data structure to save an image's data.

Someone told me that doing an std::vector imbrication is pretty bad since data contiguity isn't guaranteed, thus a simple one is more efficient.

Problem is, the vector's content has to be colorspace-dependant. Plus, for size issues it would be best to have an unsigned char per channel, though I'd be better off having floats to perform operations.

To handle colorspaces, should I increase the size of the vector (like tripling it to handle RGB), so I could access data like this:

data[0] => pixel 1, Red
data[1] => pixel 1, Green
data[2] => pixel 1, Blue
data[3] => pixel 2, Red
data[4] => pixel 2, Green
... etc

Or is it possible to do this more efficiently (like using a long int or a float to keep all channel's values into one single variable) and if so, how? How could I make this generic to handle 1, 2, 3 or 4 channels so that I can change colorspace (relatively) easily?

The question is not about the container (I am using a single std::vector already), but the content itself.

EDIT: Since this question has been marked as primarily opinion-based, I will try to make it clearer.

At the moment, I'm storing an image's data in a std::vector<float>. The problem here is that I don't know how many items to store (e.g. 3 times the size to handle RGB/HSV, or implementing a 4-items struct (RGBA) even when I'm only using one (grayscale)?) in order to efficiently change colorspace or perform operations on matrices when I need to. As this is meant to be integrated in a computer vision library, it is highly likely to happen at least once every frame.

I'm asking for something efficient in my case here, which has nothing (or very little) to do with opinion. There could be several good answers and chosing among them relies on opinion, but this is supposed to be my call.


问:
PHP TeeChart memory consumption
I've been testing creating charts in teechart for PHP using a while loop to create multiple charts via a function:

```<code>while () {
    create_my_chart();
}
</code>```

After 14 iterations of this I'm getting the following error:

"Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 800 bytes) in tchart\sources\GraphicsGD.php on line 602"

This implies that teeChart is not freeing memory correctly but I wondered if there is anything I can do about it?

答:
Your allowed memory useage seems to be only 64MB. This is very small!
Change it in the php.ini or do ini_set('memory_limit','1G') in the script to allow 1 GB memory. And test again.

http://php.net/manual/en/ini.core.php#ini.memory-limit

Title: PHP TeeChart memory consumption

Body:
I've been testing creating charts in teechart for PHP using a while loop to create multiple charts via a function:

while () {
    create_my_chart();
}

After 14 iterations of this I'm getting the following error:

"Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 800 bytes) in tchart\sources\GraphicsGD.php on line 602"

This implies that teeChart is not freeing memory correctly but I wondered if there is anything I can do about it?


问:
Python format default rounding when formatting float number
I'm trying to solve some floating-point problems in my code in Python 2.7.10. When testing I've encountered a strange behaviour with the format method:

```<code>print "{}".format(0.3000000000004) # 13 decimals
</code>```

Prints: 0.3

But:

```<code>print "{}".format(0.300000000004) # 12 decimals
</code>```

Prints: 0.300000000004

Since I'm not specifying the format, why does it round the first number? Is there a default number of allowed decimal places?

答:
This is just the way python (and many other languages) deal with float point inaccuracy. So internally this number is actually equals 0.3. There's a website dedicated to this problem in many languages: http://0.30000000000000004.com/

To this specific print, you can simply quote the number (make it a string), and the compiler will not try to round the number:

```<code>print "{}".format("0.3000000000004")
</code>```

But then you also wouldn't need to use the format:

```<code>print "0.3000000000004"
</code>```

Body:
I'm trying to solve some floating-point problems in my code in Python 2.7.10. When testing I've encountered a strange behaviour with the format method:

print "{}".format(0.3000000000004) # 13 decimals

Prints: 0.3

But:

print "{}".format(0.300000000004) # 12 decimals

Prints: 0.300000000004

Since I'm not specifying the format, why does it round the first number? Is there a default number of allowed decimal places?

Body:
This is just the way python (and many other languages) deal with float point inaccuracy. So internally this number is actually equals 0.3. There's a website dedicated to this problem in many languages: http://0.30000000000000004.com/

To this specific print, you can simply quote the number (make it a string), and the compiler will not try to round the number:

print "{}".format("0.3000000000004")

But then you also wouldn't need to use the format:

print "0.3000000000004"


问:
Android 7.1.1 Wifi Direct can't creat group
After update Huawei Nexus 6P to Android 7.1.1 I can't create a group.

When I call createGroup() or removeGroup() the system invokes callback onFailure(int reason) with message "2" (busy)

Before the updated all worked well.

答:
It's the system error of the android 7.1.1.

Some devices have been updated to Android 7.1.2 where this error was fixed, another ones now have rollback to the previous version.

Unfortunately it`s impossible to use WIfi direct correctly with Android 7.1.1


问:
Filesystems content of docker container on host
I've read quite a lot about how docker works using cgroups and namespaces. If that's correct the host should be able to see all the processes and filesystem tree that is used by the docker container. However I seem to be unable to figure it out.

Could someone show it with docker v1.12.6 and a running "nginx" container?

Optional: Is it possible to still access the files of already exited containers the same way?

PS, GraphDriver looks like this:

```<code>"GraphDriver" : {
  "Name" : "aufs",
  "Data" : null
},
</code>```

答:
When running on the host that the docker daemon runs on, you can run (as root);

Start an nginx container

```<code>docker run -d nginx
</code>```

View all processes that are running, hierarchically

```<code>ps auxf
</code>```

which shows all processes, including the nginx container you just started;

```<code>root      3810  0.9  3.2 387460 67308 ?        Ssl  11:31   0:12 /usr/bin/dockerd -H fd://
root      3819  0.1  0.6 291624 14028 ?        Ssl  11:31   0:01  \_ docker-containerd -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containerd --shim docker-containerd-shim --runtime docker-runc
root      4241  0.0  0.3 143872  6652 ?        Sl   11:49   0:00      \_ docker-containerd-shim 1d3a6c65ac59e61c165d1f0119915a43e4d0387fd8432723f16b1ef2aa966522 /var/run/docker/libcontainerd/1d3a6c65ac59e61c165d1f0119915a43e4d0387fd8432723f16b1ef2aa966522 docker-runc
root      4277  0.0  0.2  31872  5280 ?        Ss   11:49   0:00          \_ nginx: master process nginx -g daemon off;
syslog    4304  0.0  0.1  32260  2904 ?        S    11:49   0:00              \_ nginx: worker process
</code>```

container's filesystem

The storage location for container filesystems depend on the storage driver you're using. In your case the layers of images, and (writable) layers of containers are kept in /var/lib/docker/aufs. However, those files should not be messed with directly. You can use

docker cp to copy files from/to a container (even an exited container)

docker export to export the container's filesystem to a tar archive

docker commit a container to an image

Body:
I've read quite a lot about how docker works using cgroups and namespaces. If that's correct the host should be able to see all the processes and filesystem tree that is used by the docker container. However I seem to be unable to figure it out.

Could someone show it with docker v1.12.6 and a running "nginx" container?

Optional: Is it possible to still access the files of already exited containers the same way?

PS, GraphDriver looks like this:

"GraphDriver" : {
  "Name" : "aufs",
  "Data" : null
},

Body:
When running on the host that the docker daemon runs on, you can run (as root);

Start an nginx container

docker run -d nginx

View all processes that are running, hierarchically

ps auxf

which shows all processes, including the nginx container you just started;

root      3810  0.9  3.2 387460 67308 ?        Ssl  11:31   0:12 /usr/bin/dockerd -H fd://
root      3819  0.1  0.6 291624 14028 ?        Ssl  11:31   0:01  \_ docker-containerd -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containerd --shim docker-containerd-shim --runtime docker-runc
root      4241  0.0  0.3 143872  6652 ?        Sl   11:49   0:00      \_ docker-containerd-shim 1d3a6c65ac59e61c165d1f0119915a43e4d0387fd8432723f16b1ef2aa966522 /var/run/docker/libcontainerd/1d3a6c65ac59e61c165d1f0119915a43e4d0387fd8432723f16b1ef2aa966522 docker-runc
root      4277  0.0  0.2  31872  5280 ?        Ss   11:49   0:00          \_ nginx: master process nginx -g daemon off;
syslog    4304  0.0  0.1  32260  2904 ?        S    11:49   0:00              \_ nginx: worker process

container's filesystem

The storage location for container filesystems depend on the storage driver you're using. In your case the layers of images, and (writable) layers of containers are kept in /var/lib/docker/aufs. However, those files should not be messed with directly. You can use

docker cp to copy files from/to a container (even an exited container)

docker export to export the container's filesystem to a tar archive

docker commit a container to an image


问:
Connect to oracle database in ionic2
Since i am new to ionic2, Can you please give me the solution that how to connect Oracle database using Ionic2.

I have tried using API rest, But in that we are able to connect with MongoDB only.

Am using Visual code source IDE for Developing application, Please help me guys..

答: You need to develop Restful API where it interacts with the Oracle Database and use that API to fetch and put data (CRUD) from your Ionic2 app.

Title: Connect to oracle database in ionic2


问:
Draw line in canvas with another dashed line next to it
For an app I am working on I am drawing a line on a canvas using given coordinates. The problem is that I need to draw a dashed line next to it. Since the coordinates are coming from the API I only can use those coordinates for the dashed line. Is there any way to accomplish this? I really can't figure it out.

What I want:

The way I draw my current line:

```<code>Path line = new Path();
boolean first = true;
for (CircleArea circle : mCircles) {

    canv.drawCircle(circle.getDrawX(), circle.getDrawY(), mCircleRadius, mCirclePaint);
    if(!first) {
        line.lineTo(circle.getDrawX(), circle.getDrawY());
    } else {
        line.moveTo(circle.getDrawX(), circle.getDrawY());
    }

    first = false;
}
canv.drawPath(line, mLinePaint);
</code>```

Sample coordinates:

50,50

75,75

100,75

150,10

170,10

170,75

160,75

答:
Use following code:

```<code>if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        Paint p1 = new Paint();
        p1.setARGB(255,0,0,0);
        p1.setStyle(Paint.Style.FILL_AND_STROKE);

        p1.setStrokeWidth(10);
        canvas.drawLine(0,50,500,550,p1);
        p1.setPathEffect(new DashPathEffect(new float[] {20,20},0));
        canvas.drawLine(0,0,500,500,p1);
</code>```

Above code is an example to create line over dotted line if x and y both are changing. Combining it with GingerHead's logic, you will get you desired path. Just loop above code and add GingerHead's logic

Body:
For an app I am working on I am drawing a line on a canvas using given coordinates. The problem is that I need to draw a dashed line next to it. Since the coordinates are coming from the API I only can use those coordinates for the dashed line. Is there any way to accomplish this? I really can't figure it out.

What I want:

The way I draw my current line:

Path line = new Path();
boolean first = true;
for (CircleArea circle : mCircles) {

    canv.drawCircle(circle.getDrawX(), circle.getDrawY(), mCircleRadius, mCirclePaint);
    if(!first) {
        line.lineTo(circle.getDrawX(), circle.getDrawY());
    } else {
        line.moveTo(circle.getDrawX(), circle.getDrawY());
    }

    first = false;
}
canv.drawPath(line, mLinePaint);

Sample coordinates:

50,50

75,75

100,75

150,10

170,10

170,75

160,75

Body:
Use following code:

if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        Paint p1 = new Paint();
        p1.setARGB(255,0,0,0);
        p1.setStyle(Paint.Style.FILL_AND_STROKE);

        p1.setStrokeWidth(10);
        canvas.drawLine(0,50,500,550,p1);
        p1.setPathEffect(new DashPathEffect(new float[] {20,20},0));
        canvas.drawLine(0,0,500,500,p1);

Above code is an example to create line over dotted line if x and y both are changing. Combining it with GingerHead's logic, you will get you desired path. Just loop above code and add GingerHead's logic


问:
How to delete an record from Django model
I have an Django model as follows:

```<code>class Calculations(models.Model):
    category = models.CharField(max_length=127)
    make = models.CharField(max_length=127)
    model = models.CharField(max_length=127)
    customer = models.ForeignKey(to=Customer, null=True, blank=True)
    data = models.TextField(null=True, blank=True)
</code>```

and customer model as follows:

```<code>class Customer(models.Model):
    title = models.CharField(max_length=4, null=True)
    firstname = models.CharField(max_length=30)
    lastname = models.CharField(max_length=30)
    email = models.EmailField(null=True)
    address = models.CharField(max_length=80)
</code>```

I want to delete one record from the customer. I do it as follows:

```<code>Customer.objects.filter(id=some_id).delete()
</code>```

But that deletes customer and also calculation.

I should probably use on_delete, thus something like:

```<code>customer = models.ForeignKey(to=Customer, null=True, blank=True, on_delete=models....)
</code>```

But, what I want is:

if I delete calculation then I want to delete also the customer,

but if I delete an record from customer I want only that the customer is deleted and that the customer_id from calculations is deleted, thus not the whole calculation record.

Any idea how to do that?

答:
To delete the customer when you delete a calculation:

```<code>def delete(self, *args, **kwargs):
    self.customer.delete()
    super(Calculations, self).delete(*args, **kwargs)
</code>```

To avoid deleting the calculation when you delete a customer:

```<code>customer = models.ForeignKey(to=Customer, null=True, blank=True, on_delete=models.SET_NULL)
</code>```

Body:
I have an Django model as follows:

class Calculations(models.Model):
    category = models.CharField(max_length=127)
    make = models.CharField(max_length=127)
    model = models.CharField(max_length=127)
    customer = models.ForeignKey(to=Customer, null=True, blank=True)
    data = models.TextField(null=True, blank=True)

and customer model as follows:

class Customer(models.Model):
    title = models.CharField(max_length=4, null=True)
    firstname = models.CharField(max_length=30)
    lastname = models.CharField(max_length=30)
    email = models.EmailField(null=True)
    address = models.CharField(max_length=80)

I want to delete one record from the customer. I do it as follows:

Customer.objects.filter(id=some_id).delete()

But that deletes customer and also calculation.

I should probably use on_delete, thus something like:

customer = models.ForeignKey(to=Customer, null=True, blank=True, on_delete=models....)

But, what I want is:

if I delete calculation then I want to delete also the customer,

but if I delete an record from customer I want only that the customer is deleted and that the customer_id from calculations is deleted, thus not the whole calculation record.

Any idea how to do that?

Body:
To delete the customer when you delete a calculation:

def delete(self, *args, **kwargs):
    self.customer.delete()
    super(Calculations, self).delete(*args, **kwargs)

To avoid deleting the calculation when you delete a customer:

customer = models.ForeignKey(to=Customer, null=True, blank=True, on_delete=models.SET_NULL)


问:
How to use $_GET variable (index.php?cat=about)
I know there must already has this question been asked but I didn't find the answer cause I don't know how to search exactly what I want.

So, I wanna make such a link http://example.com/index.php?cat=about where I should insert some about info. But I don't know how to make a page with this URL containing ? symbol and other stuff, or how to edit that page then, where to edit and etc.

```<code><a href="index.php?cat=about">About Us</a>
</code>```

I've also made cat.php file but what next?

答:
@Lasha Palelashvili let suppose below example:

above you are sending only one input parameter cat through url to the index.php file at server side so when you send this data from url it will send by get method by default, if you want to get this url info(input parameter) at the php side so $_GET will help you to fetch that info $_GET is actually an array which stores your input parameter as key and input parameter's value as value for your case("index.php?cat=about") $_GET array will contain value like below:

$_GET = array("cat" => "about")

now at the server side you can easily get the value like:

```<code>//index.php
<?php
 $cat = $_GET["cat"];
 echo $cat;
?>
</code>```

Body:
I know there must already has this question been asked but I didn't find the answer cause I don't know how to search exactly what I want.

So, I wanna make such a link http://example.com/index.php?cat=about where I should insert some about info. But I don't know how to make a page with this URL containing ? symbol and other stuff, or how to edit that page then, where to edit and etc.

About Us

I've also made cat.php file but what next?

Body:
@Lasha Palelashvili let suppose below example:

above you are sending only one input parameter cat through url to the index.php file at server side so when you send this data from url it will send by get method by default, if you want to get this url info(input parameter) at the php side so $_GET will help you to fetch that info $_GET is actually an array which stores your input parameter as key and input parameter's value as value for your case("index.php?cat=about") $_GET array will contain value like below:

$_GET = array("cat" => "about")

now at the server side you can easily get the value like:

//index.php
<?php
 $cat = $_GET["cat"];
 echo $cat;
?>


问:
Validate user per every request and response in spring
Since I am new to Spring and i have an issue with user service. I have admin panel and customer blog. When the Customer is logged into browser, the admin has been changed the status to Active from InActive in Table of Customer. But the user session is active. So that he can able to do process after the status is changed.

I need one common method that should be in common place. This method should be access the table and validate the user per every request. I have one controller and that should invoke the common method. Because I cannot edit code to every class. In JSP & Servlet I have handled this using doFilter. How to achieve this in Spring..

AppInitializer.java

```<code>import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { AppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
    registration.setMultipartConfig(getMultipartConfigElement());
}

private MultipartConfigElement getMultipartConfigElement() {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement( LOCATION, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD);
    return multipartConfigElement;
}

private static final String LOCATION = "C:/temp/"; // Temporary location where files will be stored

private static final long MAX_FILE_SIZE = 5242880; // 5MB : Max file size.
                                                    // Beyond that size spring will throw exception.
private static final long MAX_REQUEST_SIZE = 20971520; // 20MB : Total request size containing Multi part.

private static final int FILE_SIZE_THRESHOLD = 0;

}
</code>```

AppConfig.java

```<code>import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { AppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
    registration.setMultipartConfig(getMultipartConfigElement());
}

private MultipartConfigElement getMultipartConfigElement() {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement( LOCATION, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD);
    return multipartConfigElement;
}

private static final String LOCATION = "C:/temp/"; // Temporary location where files will be stored

private static final long MAX_FILE_SIZE = 5242880; // 5MB : Max file size.
                                                    // Beyond that size spring will throw exception.
private static final long MAX_REQUEST_SIZE = 20971520; // 20MB : Total request size containing Multi part.

private static final int FILE_SIZE_THRESHOLD = 0;

}
</code>```

HibernateConfiguration.java

```<code>import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.ppts.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.ppts.model" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
 }

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    return properties;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
   HibernateTransactionManager txManager = new HibernateTransactionManager();
   txManager.setSessionFactory(s);
   return txManager;
}
}
</code>```

AppController.java

```<code>package com.sample.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.sample.handler.FileHandler;
import com.sample.model.Address;
import com.sample.model.Employee;
import com.sample.model.EmployeeDocument;
import com.sample.model.EmployeeSalary;
import com.sample.model.FileBucket;
import com.sample.model.User;
import com.sample.model.UserProfile;
import com.sample.service.EmployeeDocumentService;
import com.sample.service.EmployeeSalaryService;
import com.sample.service.EmployeeService;
import com.sample.service.UserProfileService;
import com.sample.service.UserService;
import com.sample.validators.FileValidator;

@Controller
@RequestMapping("/")
@SessionAttributes("roles")
public class AppController {

@Autowired
UserService userService;

@Autowired
EmployeeService employeeService;

@Autowired
EmployeeSalaryService employeeSalaryService;

@Autowired
UserProfileService userProfileService;

@Autowired
EmployeeDocumentService employeeDocumentService;

@Autowired
FileValidator fileValidator;

@InitBinder("fileBucket")
protected void initBinderFileBucket(WebDataBinder binder) {
    binder.setValidator(fileValidator);
}

@Autowired
MessageSource messageSource;

@Autowired
PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices;

@Autowired
AuthenticationTrustResolver authenticationTrustResolver;

@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String adminPage(ModelMap model) {
    model.addAttribute("home",true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "home";
}

@RequestMapping(value = { "/userList" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {
    List<User> users = userService.findAllUsers();
    model.addAttribute("users", users);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userslist";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.GET)
public String newUser(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("edit", false);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result,
        ModelMap model) {
    if (result.hasErrors()) {
        return "registration";
    }
    if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){
        FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
        result.addError(ssoError);
        return "registration";
    }
    userService.saveUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " registered successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.GET)
public String editUser(@PathVariable String ssoId, ModelMap model) {
    User user = userService.findBySSO(ssoId);
    model.addAttribute("user", user);
    model.addAttribute("edit", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}

@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.POST)
public String updateUser(@Valid User user, BindingResult result,
        ModelMap model, @PathVariable String ssoId) {
    if (result.hasErrors()) {
        return "registration";
    }
    userService.updateUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

//Update User and Employee By Id
@RequestMapping(value = { "/getUserById" }, method = RequestMethod.GET)
public String getUserSSOId(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("edit", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userview";
}

@RequestMapping(value = { "/updateByUserId" }, method = RequestMethod.GET)
public String getByUserId( @ModelAttribute User userDetails,ModelMap model,BindingResult result) {
    User user =userService.findBySSO(userDetails.getSsoId());
    if(user!=null){
        model.addAttribute("user", user);
        model.addAttribute("edit", true);
        model.addAttribute("loggedinuser", getPrincipal());
        return "registration";
    }else{
        FieldError referenceIdError =new FieldError("user","ssoId",messageSource.getMessage("non.empty.userid.notexist", new String[]{userDetails.getSsoId()}, Locale.getDefault()));
        result.addError(referenceIdError);
        model.addAttribute("loggedinuser", getPrincipal());
        return "userview";
    }
}

@RequestMapping(value = { "/updateByUserId" }, method = RequestMethod.POST)
public String updateUserById(@Valid User user, BindingResult result,
        ModelMap model) {
    if (result.hasErrors()) {
        return "registration";
    }
    userService.updateUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/deleteByUserId" }, method = RequestMethod.GET)
public String deleteUserById(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("delete", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userview";
}

@RequestMapping(value = { "/deleteUserById" }, method = RequestMethod.GET)
public String deleteByuserId( @ModelAttribute User userDetails,ModelMap model,BindingResult result) {
    User user=userService.findBySSO(userDetails.getSsoId());
    if(user!=null){
        userService.deleteUserBySSO(userDetails.getSsoId());
        model.addAttribute("loggedinuser", getPrincipal());
        model.addAttribute("employeeSuccess", "Employee " + user.getFirstName() + " deleted successfully");
        return "registrationsuccess";
    }else{
        FieldError referenceIdError =new FieldError("employee","employeeReferenceId",messageSource.getMessage("non.empty.userid.notexist", new String[]{userDetails.getSsoId()}, Locale.getDefault()));
        model.addAttribute("loggedinuser", getPrincipal());
        result.addError(referenceIdError);
        return "userview";
    }

}
}
</code>```

答:
You can make create a class implementing Spring's HandlerInterceptor interface. Its preHandle method will be called for every request before request is processed by the Controller method.

Since you just want to process validation check for each request before it is handled, you can create a class extending the HandlerInterceptorAdapter class which provides convenient defaults for all methods in the HandlerInterceptor interface.

You only need to provide implementation as per your business rule for the following method

```<code>preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
</code>```

Sample code below

```<code>import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class TransactionInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        // Your business logic goes here

        // return true or false depending on whether you want the controller to handle the request or terminate request processing.
    }
}
</code>```

You would need to register the interceptor in Spring Config as below

```<code>@EnableWebMvc
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {

    .....
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new YourNewInterceptor());
    }
    .....

}
</code>```

Body:
Since I am new to Spring and i have an issue with user service. I have admin panel and customer blog. When the Customer is logged into browser, the admin has been changed the status to Active from InActive in Table of Customer. But the user session is active. So that he can able to do process after the status is changed.

I need one common method that should be in common place. This method should be access the table and validate the user per every request. I have one controller and that should invoke the common method. Because I cannot edit code to every class. In JSP & Servlet I have handled this using doFilter. How to achieve this in Spring..

AppInitializer.java

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { AppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
    registration.setMultipartConfig(getMultipartConfigElement());
}

private MultipartConfigElement getMultipartConfigElement() {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement( LOCATION, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD);
    return multipartConfigElement;
}

private static final String LOCATION = "C:/temp/"; // Temporary location where files will be stored

private static final long MAX_FILE_SIZE = 5242880; // 5MB : Max file size.
                                                    // Beyond that size spring will throw exception.
private static final long MAX_REQUEST_SIZE = 20971520; // 20MB : Total request size containing Multi part.

private static final int FILE_SIZE_THRESHOLD = 0;

}

AppConfig.java

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { AppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
    registration.setMultipartConfig(getMultipartConfigElement());
}

private MultipartConfigElement getMultipartConfigElement() {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement( LOCATION, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD);
    return multipartConfigElement;
}

private static final String LOCATION = "C:/temp/"; // Temporary location where files will be stored

private static final long MAX_FILE_SIZE = 5242880; // 5MB : Max file size.
                                                    // Beyond that size spring will throw exception.
private static final long MAX_REQUEST_SIZE = 20971520; // 20MB : Total request size containing Multi part.

private static final int FILE_SIZE_THRESHOLD = 0;

}

HibernateConfiguration.java

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.ppts.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.ppts.model" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
 }

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    return properties;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
   HibernateTransactionManager txManager = new HibernateTransactionManager();
   txManager.setSessionFactory(s);
   return txManager;
}
}

AppController.java

package com.sample.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.sample.handler.FileHandler;
import com.sample.model.Address;
import com.sample.model.Employee;
import com.sample.model.EmployeeDocument;
import com.sample.model.EmployeeSalary;
import com.sample.model.FileBucket;
import com.sample.model.User;
import com.sample.model.UserProfile;
import com.sample.service.EmployeeDocumentService;
import com.sample.service.EmployeeSalaryService;
import com.sample.service.EmployeeService;
import com.sample.service.UserProfileService;
import com.sample.service.UserService;
import com.sample.validators.FileValidator;

@Controller
@RequestMapping("/")
@SessionAttributes("roles")
public class AppController {

@Autowired
UserService userService;

@Autowired
EmployeeService employeeService;

@Autowired
EmployeeSalaryService employeeSalaryService;

@Autowired
UserProfileService userProfileService;

@Autowired
EmployeeDocumentService employeeDocumentService;

@Autowired
FileValidator fileValidator;

@InitBinder("fileBucket")
protected void initBinderFileBucket(WebDataBinder binder) {
    binder.setValidator(fileValidator);
}

@Autowired
MessageSource messageSource;

@Autowired
PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices;

@Autowired
AuthenticationTrustResolver authenticationTrustResolver;

@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String adminPage(ModelMap model) {
    model.addAttribute("home",true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "home";
}

@RequestMapping(value = { "/userList" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {
    List<User> users = userService.findAllUsers();
    model.addAttribute("users", users);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userslist";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.GET)
public String newUser(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("edit", false);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result,
        ModelMap model) {
    if (result.hasErrors()) {
        return "registration";
    }
    if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){
        FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
        result.addError(ssoError);
        return "registration";
    }
    userService.saveUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " registered successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.GET)
public String editUser(@PathVariable String ssoId, ModelMap model) {
    User user = userService.findBySSO(ssoId);
    model.addAttribute("user", user);
    model.addAttribute("edit", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}

@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.POST)
public String updateUser(@Valid User user, BindingResult result,
        ModelMap model, @PathVariable String ssoId) {
    if (result.hasErrors()) {
        return "registration";
    }
    userService.updateUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

//Update User and Employee By Id
@RequestMapping(value = { "/getUserById" }, method = RequestMethod.GET)
public String getUserSSOId(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("edit", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userview";
}

@RequestMapping(value = { "/updateByUserId" }, method = RequestMethod.GET)
public String getByUserId( @ModelAttribute User userDetails,ModelMap model,BindingResult result) {
    User user =userService.findBySSO(userDetails.getSsoId());
    if(user!=null){
        model.addAttribute("user", user);
        model.addAttribute("edit", true);
        model.addAttribute("loggedinuser", getPrincipal());
        return "registration";
    }else{
        FieldError referenceIdError =new FieldError("user","ssoId",messageSource.getMessage("non.empty.userid.notexist", new String[]{userDetails.getSsoId()}, Locale.getDefault()));
        result.addError(referenceIdError);
        model.addAttribute("loggedinuser", getPrincipal());
        return "userview";
    }
}

@RequestMapping(value = { "/updateByUserId" }, method = RequestMethod.POST)
public String updateUserById(@Valid User user, BindingResult result,
        ModelMap model) {
    if (result.hasErrors()) {
        return "registration";
    }
    userService.updateUser(user);
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/deleteByUserId" }, method = RequestMethod.GET)
public String deleteUserById(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("delete", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userview";
}

@RequestMapping(value = { "/deleteUserById" }, method = RequestMethod.GET)
public String deleteByuserId( @ModelAttribute User userDetails,ModelMap model,BindingResult result) {
    User user=userService.findBySSO(userDetails.getSsoId());
    if(user!=null){
        userService.deleteUserBySSO(userDetails.getSsoId());
        model.addAttribute("loggedinuser", getPrincipal());
        model.addAttribute("employeeSuccess", "Employee " + user.getFirstName() + " deleted successfully");
        return "registrationsuccess";
    }else{
        FieldError referenceIdError =new FieldError("employee","employeeReferenceId",messageSource.getMessage("non.empty.userid.notexist", new String[]{userDetails.getSsoId()}, Locale.getDefault()));
        model.addAttribute("loggedinuser", getPrincipal());
        result.addError(referenceIdError);
        return "userview";
    }

}
}

Body:
You can make create a class implementing Spring's HandlerInterceptor interface. Its preHandle method will be called for every request before request is processed by the Controller method.

Since you just want to process validation check for each request before it is handled, you can create a class extending the HandlerInterceptorAdapter class which provides convenient defaults for all methods in the HandlerInterceptor interface.

You only need to provide implementation as per your business rule for the following method

preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

Sample code below

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class TransactionInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        // Your business logic goes here

        // return true or false depending on whether you want the controller to handle the request or terminate request processing.
    }
}

You would need to register the interceptor in Spring Config as below

@EnableWebMvc
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {

    .....
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new YourNewInterceptor());
    }
    .....

}


问:
Jenkins integration with Team Services
I am trying to intregate jenkins in visual studio team services as a service hook. The idea is when a code to master branch is pushed, launch a job of jenkins automatically. Everything seems to be configured correctly but when the event occurs, it gives an error:

```<code>"An error occurred while sending the request. Unable to connect to the remote server"
</code>```

The request is the notifyCommit url that if I paste in the browser works and it launches the jenkins job. So, it seems that something is not correctly configured because from team services cannot connect to Jenkins.

```<code>"Error Details
System.Net.Http.HttpRequestException: An error occurred while sending the request. --->
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: A connection attempt failed because the
connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to respond"
</code>```

答: Jenkins was not accessible because is not public outside.</p>

Title: Jenkins integration with Team Services

Body:
I am trying to intregate jenkins in visual studio team services as a service hook. The idea is when a code to master branch is pushed, launch a job of jenkins automatically. Everything seems to be configured correctly but when the event occurs, it gives an error:

"An error occurred while sending the request. Unable to connect to the remote server"

The request is the notifyCommit url that if I paste in the browser works and it launches the jenkins job. So, it seems that something is not correctly configured because from team services cannot connect to Jenkins.

"Error Details
System.Net.Http.HttpRequestException: An error occurred while sending the request. --->
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: A connection attempt failed because the
connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to respond"


问:
Why the image is rotated , by calling CGContextDrawImage
Why the image is rotated , by calling CGContextDrawImage.Thanks for your help.</p>

```<code>// Initialization code
UIImage *img = [UIImage imageNamed:@"logo.png"];
UIImagePNGRepresentation(img);
_image_ref = img.CGImage;

// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect img_rect = CGRectMake(20, 40, 100, 150);
CGContextDrawImage(context, img_rect, _image_ref);
</code>```

答:
Following this explanation. I created solution which allow to draw multiple images with custom rects in one context.

```<code>func foo() -> UIImage? {
    let image = UIImage(named: "back.png")!

    let contextSize = CGSize(width: 500, height: 500)
    UIGraphicsBeginImageContextWithOptions(contextSize, true, image.scale)
    guard let ctx = UIGraphicsGetCurrentContext() else { return nil }
    guard let cgImage = image.cgImage else { return nil}

    //Start code which can by copy/paste
    let imageRect = CGRect(origin: CGPoint(x: 200.0, y: 200.0), size: image.size) //custom rect
    let ty = imageRect.origin.y + imageRect.size.height //calculate translation Y
    let imageRectWithoutOriginY = CGRect(origin: CGPoint(x: imageRect.origin.x, y: 0), size: imageRect.size)
    ctx.translateBy(x: 0.0, y: ty) //prepare context for custom rect
    ctx.scaleBy(x: 1.0, y: -1.0)

    ctx.draw(cgImage, in: imageRectWithoutOriginY) //draw image

    ctx.translateBy(x: 0.0, y:-ty) //restore default context setup (so you can select new area to place another image)
    ctx.scaleBy(x: 1.0, y: -1.0)
    //End code which can by copy/paste

    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return result
}
</code>```

Example with to images:

I know that it can be refactored. I duplicated code for more clarity.

Body:
Why the image is rotated , by calling CGContextDrawImage.Thanks for your help.

// Initialization code
UIImage *img = [UIImage imageNamed:@"logo.png"];
UIImagePNGRepresentation(img);
_image_ref = img.CGImage;

// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect img_rect = CGRectMake(20, 40, 100, 150);
CGContextDrawImage(context, img_rect, _image_ref);

Body:
Following this explanation. I created solution which allow to draw multiple images with custom rects in one context.

func foo() -> UIImage? {
    let image = UIImage(named: "back.png")!

    let contextSize = CGSize(width: 500, height: 500)
    UIGraphicsBeginImageContextWithOptions(contextSize, true, image.scale)
    guard let ctx = UIGraphicsGetCurrentContext() else { return nil }
    guard let cgImage = image.cgImage else { return nil}

    //Start code which can by copy/paste
    let imageRect = CGRect(origin: CGPoint(x: 200.0, y: 200.0), size: image.size) //custom rect
    let ty = imageRect.origin.y + imageRect.size.height //calculate translation Y
    let imageRectWithoutOriginY = CGRect(origin: CGPoint(x: imageRect.origin.x, y: 0), size: imageRect.size)
    ctx.translateBy(x: 0.0, y: ty) //prepare context for custom rect
    ctx.scaleBy(x: 1.0, y: -1.0)

    ctx.draw(cgImage, in: imageRectWithoutOriginY) //draw image

    ctx.translateBy(x: 0.0, y:-ty) //restore default context setup (so you can select new area to place another image)
    ctx.scaleBy(x: 1.0, y: -1.0)
    //End code which can by copy/paste

    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return result
}

Example with to images:

I know that it can be refactored. I duplicated code for more clarity.


问:
Chart js custom single tooltip not working
Hi i would like to set the tooltips of my chart so that only the label and nothing else is displayed. Unfortunately, the x-value is still being displayed as you can see here: https://1drv.ms/i/s!As59C5Mmd0nahr4ENuppEupBDAbqqw

this is the code that is being executed at the beginning when i create the chart:

```<code>tooltips: {
    callbacks: {
        label: function (tooltipItems, data) {
            return data.datasets[tooltipItems.datasetIndex].label;
        }
    }
}
</code>```

答:
Just make font size zero like this:  </p>

```<code>tooltips: {
    titleFontSize: 0
}
</code>```

Body:
Hi i would like to set the tooltips of my chart so that only the label and nothing else is displayed. Unfortunately, the x-value is still being displayed as you can see here: https://1drv.ms/i/s!As59C5Mmd0nahr4ENuppEupBDAbqqw

this is the code that is being executed at the beginning when i create the chart:

tooltips: {
    callbacks: {
        label: function (tooltipItems, data) {
            return data.datasets[tooltipItems.datasetIndex].label;
        }
    }
}

Body:
Just make font size zero like this:

tooltips: {
    titleFontSize: 0
}


问:
QueryList changes subscribe does not work
I have a QueryList in a component. I am adding dynamically other components, that will be present in the QueryList, but if I subscribe to the changes of the QueryList, nothing happens. I thought it is because I subscribed in ngAfterViewInit, but the QueryList is undefined yet in ngOnInit.

Here I have the plunkr.

code:

```<code>@Component({
  ...
})
export class AppComponent {

    @ViewChildren(ControlFactoryDirective) factories:
        QueryList<ControlFactoryDirective>

    ngAfterViewInit() {
      this.factories.changes.subscribe(() => {
        console.log('changed')
      })
    }
}
</code>```

答:
After you make a change to the objects in query list you should call query list to notify on changes.</p>

```<code>update() {
  this.factories.forEach(factory => {
    console.log(factory.componentRef.instance.model.data = "alma")
  //  factory.()
  this.factories.notifyOnChanges();
  })
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a QueryList in a component. I am adding dynamically other components, that will be present in the QueryList, but if I subscribe to the changes of the QueryList, nothing happens. I thought it is because I subscribed in ngAfterViewInit, but the QueryList is undefined yet in ngOnInit.

Here I have the plunkr.

code:

@Component({
  ...
})
export class AppComponent {

    @ViewChildren(ControlFactoryDirective) factories:
        QueryList<ControlFactoryDirective>

    ngAfterViewInit() {
      this.factories.changes.subscribe(() => {
        console.log('changed')
      })
    }
}

Body:
After you make a change to the objects in query list you should call query list to notify on changes.

update() {
  this.factories.forEach(factory => {
    console.log(factory.componentRef.instance.model.data = "alma")
  //  factory.()
  this.factories.notifyOnChanges();
  })
}


问:
MySQL making search function won't work
I am trying to build a search function into my site, which lets you find users based on their name or surname and then it will print all found names. Problem is, that I won't work at all. Can you guys help me?

EDIT: if I try to search something, it will always give me the answer that nothing was found.

The php code:

```<code><?php
    $search = $_POST["search"];
    if(isset($search)) {
        $findname = "SELECT `name` FROM Account WHERE $search = `name`
                    OR SELECT `name` FROM `Account` WHERE $search = `surname`
                    OR SELECT `name` FROM `Account`
                    WHERE $search = `name` . `surname`
                    OR SELECT `name` FROM `Account` WHERE $search = `name` . `surnameprefix` . `surname`";

        $findsurname = "SELECT `surname` from Account WHERE $search = `name`
                        OR SELECT `surname` FROM `Account` WHERE $search = `surname`
                        OR SELECT `surname` FROM `Account` WHERE $search = `name` . `surname`
                        OR SELECT `surname` FROM `Account` WHERE $search = `name` . `surnameprefix` . `surname`";

        $result2 = mysql_query($findsurname);
        $result1 = mysql_query($findname);
            if($result1 == false && $result2 == false) {
                echo '<div id="searchresult"><h1>People found:</h1> <p>No one was found...</p>';
            } else {
                echo '<div id="searchresult">
                        <h1>People found:</h1>
                        <table id="searchtable">
                            while($result = mysql_fetch_array($result1)){
                                <tr id="searchtablerow">
                                    <td> $findname ' . '$findsurname</td>
                                    <td><img src="standard-profile-square.jpg" id="searchpicture"></td>
                                </tr>
                            }
                        </table>
                    </div>';
            }
        }
?>
</code>```

The html form code:

```<code>    <div id="searchform">
        <h1>Search friends:</h1>
        <form name="searchform" method="post" action ="searchlink.php">
            <input type="text" name="search" id="search" autofocus placeholder="e.g. John Smith..."></input> <br>
            <input type="submit" name="submitsearch" value="Search" id="searchbutton"></input>
        </form>
    </div>
</code>```

Thank you guys in advance for helping me!

Yours sincerely,
Unheil

答:
There are a lot of errors in your code. The SQL statements are wrong. The two statements basically do the same thing
except they return a different column.

The SELECTs in the where clause are nonsense. Instead, in the where clause you should just add more qualifiers, not select statements.

In a SQL statement, you use PHP concatenation, which doesn't work in SQL.
The PHP code has many syntax and logic errors. You are using the mysql functions instead of the mysqli functions.
You never open a connection to the database.

The list of problems in the code go on and on.

Here's some code that should work and get you closer to what you want.

```<code><?php
    $host = 'your host name';
    $user = 'your db user name';
    $password = 'your db user name';
    $db_name = 'your db name';
    $search = $_POST["search"];
    if(isset($search)) {
        $db = mysqli_connect($host, $user, $password, $db_name);
        $wild_search = "%".$search."%";
        $findname = "SELECT `name`,`surname`
        FROM `Account`
        WHERE `name` LIKE '".$wild_search."'
            OR `surname` LIKE '".$wild_search."'
            OR CONCAT(`name`, `surname`) LIKE '".$wild_search."'
            OR CONCAT(`name`, `surnameprefix`, `surname`) LIKE '".$wild_search."';";
        $query = mysqli_query($db,$findname);
        $results = mysqli_fetch_all($query);

        if($result) {
            echo "<div id='searchresult'>\n";
            echo "<h1>People Found</h1>\n";
            echo "<table id='searchresult'>\n";
            foreach($result as $rowno => $row) {
                echo "<tr class='searchtablerow'>\n";
                echo "<td>".$row['name'].", ".$row['surname']."</td>\n";
                echo "</tr>\n";
            }
            echo "</table>\n";
        } else {
            echo "<div id='searchresult'><h1>People Found:</h1>\n";
            echo "<p>No one was found.</p>\n";
            echo "</div>\n";
        }
    } else {
    }
?>
</code>```

In phpAdmin, try the following test statement. Substitute a name you know exists in the table for "smith" in the example:

```<code>SELECT `name`,`surname`
    FROM `Account`
    WHERE `name` LIKE '%smith%'
        OR `surname` LIKE '%smith%'
        OR CONCAT(`name`, `surname`) LIKE '%smith%'
        OR CONCAT(`name`, `surnameprefix`, `surname`) LIKE '%smith%';
</code>```

Title: MySQL making search function won't work

Body:
I am trying to build a search function into my site, which lets you find users based on their name or surname and then it will print all found names. Problem is, that I won't work at all. Can you guys help me?

EDIT: if I try to search something, it will always give me the answer that nothing was found.

The php code:

<?php
    $search = $_POST["search"];
    if(isset($search)) {
        $findname = "SELECT `name` FROM Account WHERE $search = `name`
                    OR SELECT `name` FROM `Account` WHERE $search = `surname`
                    OR SELECT `name` FROM `Account`
                    WHERE $search = `name` . `surname`
                    OR SELECT `name` FROM `Account` WHERE $search = `name` . `surnameprefix` . `surname`";

        $findsurname = "SELECT `surname` from Account WHERE $search = `name`
                        OR SELECT `surname` FROM `Account` WHERE $search = `surname`
                        OR SELECT `surname` FROM `Account` WHERE $search = `name` . `surname`
                        OR SELECT `surname` FROM `Account` WHERE $search = `name` . `surnameprefix` . `surname`";

        $result2 = mysql_query($findsurname);
        $result1 = mysql_query($findname);
            if($result1 == false && $result2 == false) {
                echo '

People found:

No one was found...
';
            } else {
                echo '

People found:

                            while($result = mysql_fetch_array($result1)){

                                     $findname ' . '$findsurname

                            }

';
            }
        }
?>

The html form code:

Search friends:

        <form name="searchform" method="post" action ="searchlink.php">
            <input type="text" name="search" id="search" autofocus placeholder="e.g. John Smith..."></input>

            <input type="submit" name="submitsearch" value="Search" id="searchbutton"></input>
        </form>

Thank you guys in advance for helping me!

Yours sincerely,
Unheil

Body:
There are a lot of errors in your code. The SQL statements are wrong. The two statements basically do the same thing
except they return a different column.

The SELECTs in the where clause are nonsense. Instead, in the where clause you should just add more qualifiers, not select statements.

In a SQL statement, you use PHP concatenation, which doesn't work in SQL.
The PHP code has many syntax and logic errors. You are using the mysql functions instead of the mysqli functions.
You never open a connection to the database.

The list of problems in the code go on and on.

Here's some code that should work and get you closer to what you want.

<?php
    $host = 'your host name';
    $user = 'your db user name';
    $password = 'your db user name';
    $db_name = 'your db name';
    $search = $_POST["search"];
    if(isset($search)) {
        $db = mysqli_connect($host, $user, $password, $db_name);
        $wild_search = "%".$search."%";
        $findname = "SELECT `name`,`surname`
        FROM `Account`
        WHERE `name` LIKE '".$wild_search."'
            OR `surname` LIKE '".$wild_search."'
            OR CONCAT(`name`, `surname`) LIKE '".$wild_search."'
            OR CONCAT(`name`, `surnameprefix`, `surname`) LIKE '".$wild_search."';";
        $query = mysqli_query($db,$findname);
        $results = mysqli_fetch_all($query);

        if($result) {
            echo "<div id='searchresult'>\n";
            echo "<h1>People Found</h1>\n";
            echo "<table id='searchresult'>\n";
            foreach($result as $rowno => $row) {
                echo "<tr class='searchtablerow'>\n";
                echo "<td>".$row['name'].", ".$row['surname']."</td>\n";
                echo "</tr>\n";
            }
            echo "</table>\n";
        } else {
            echo "<div id='searchresult'><h1>People Found:</h1>\n";
            echo "<p>No one was found.</p>\n";
            echo "</div>\n";
        }
    } else {
    }
?>

In phpAdmin, try the following test statement. Substitute a name you know exists in the table for "smith" in the example:

SELECT `name`,`surname`
    FROM `Account`
    WHERE `name` LIKE '%smith%'
        OR `surname` LIKE '%smith%'
        OR CONCAT(`name`, `surname`) LIKE '%smith%'
        OR CONCAT(`name`, `surnameprefix`, `surname`) LIKE '%smith%';


问:
Regex for express get file path
Because I am using react router I cannot make specific file path references to every single route with react in Node. In order for their not to be a crash while getting a specific file path, I have to put this code in node.

```<code>app.use(express.static(path.join(__dirname, '/frontend-two')));

app.get('*', function(req,res) {
res.sendFile(path.join(__dirname, './frontend-two/index.html'));
});
</code>```

I do, however, want to place a specific file path in order to send json data back to the client. It would interfere with the app.get('*') unless I can figure out a regex for specifically '/users' to be excluded.

Is there anyone who may know a possible regular expression to accomplish this? I have tried ideas through other questions but was unable to figure it out.

答:
You can do it in two ways:

You can add /users path and then * path:

```<code>app.get('/get', function (req, res) {
    // ...
});

app.get('*', function (req, res) {
    // ...
});
</code>```

The first one matching will be used so the * path will not match the /users as it's the second one.

Or you can use a regex like this: /^(?!\/users)$/ that matches everything but not users. There are many ways in which you can compose the regex - search for a negative look-ahead and look-behind assertions.

Title: Regex for express get file path

Body:
Because I am using react router I cannot make specific file path references to every single route with react in Node. In order for their not to be a crash while getting a specific file path, I have to put this code in node.

app.use(express.static(path.join(__dirname, '/frontend-two')));

app.get('*', function(req,res) {
res.sendFile(path.join(__dirname, './frontend-two/index.html'));
});

I do, however, want to place a specific file path in order to send json data back to the client. It would interfere with the app.get('*') unless I can figure out a regex for specifically '/users' to be excluded.

Is there anyone who may know a possible regular expression to accomplish this? I have tried ideas through other questions but was unable to figure it out.

Body:
You can do it in two ways:

You can add /users path and then * path:

app.get('/get', function (req, res) {
    // ...
});

app.get('*', function (req, res) {
    // ...
});

The first one matching will be used so the * path will not match the /users as it's the second one.

Or you can use a regex like this: /^(?!\/users)$/ that matches everything but not users. There are many ways in which you can compose the regex - search for a negative look-ahead and look-behind assertions.


问:
speex decoding going wrong
I'm using speex to encode some audio data and send it over UDP, and decode it on the other side.
I ran a few tests with speex, and noticed that if I decode a packet straight after I encoded it, the decoded data is in no way close to the original data. Most of the bytes at the start of the buffer are 0.
So when I decode the audio sent over UDP, all I get is noise.
This is how I am encoding the audio:

```<code>bool AudioEncoder::encode( float *raw, char *encoded_bits )
{
    for ( size_t i = 0; i < 256; i++ )
        this->_rfdata[i] = raw[i];
    speex_bits_reset(&this->_bits);
    speex_encode(this->_state, this->_rfdata, &this->_bits);
    int bytesWritten = speex_bits_write(&this->_bits, encoded_bits, 512);
    if (bytesWritten)
        return true;
    return false;
}
</code>```

this is how I am decoding the audio:

```<code>float *f = new float[256];
// recvbuf is the buffer I pass to my recv function on the socket
speex_bits_read_from(&this->_bits, recvbuf, 512);
speex_decode(this->state, &this->_bits, f);
</code>```

I've check out the docs, and most of my code comes from the example encoding/decoding sample from the speex website.
I'm not sure what I'm missing here.

答: I found the reason the encoded data was so different. There is the fact it's a lossy compression as Paulo Scardine said, and also that speex only works with 160 frames, so when getting data from portaudio to speex, it needs to be by "packets" of 160 frames.</p>

Title: speex decoding going wrong

Body:
I'm using speex to encode some audio data and send it over UDP, and decode it on the other side.
I ran a few tests with speex, and noticed that if I decode a packet straight after I encoded it, the decoded data is in no way close to the original data. Most of the bytes at the start of the buffer are 0.
So when I decode the audio sent over UDP, all I get is noise.
This is how I am encoding the audio:

bool AudioEncoder::encode( float *raw, char *encoded_bits )
{
    for ( size_t i = 0; i < 256; i++ )
        this->_rfdata[i] = raw[i];
    speex_bits_reset(&this->_bits);
    speex_encode(this->_state, this->_rfdata, &this->_bits);
    int bytesWritten = speex_bits_write(&this->_bits, encoded_bits, 512);
    if (bytesWritten)
        return true;
    return false;
}

this is how I am decoding the audio:

float *f = new float[256];
// recvbuf is the buffer I pass to my recv function on the socket
speex_bits_read_from(&this->_bits, recvbuf, 512);
speex_decode(this->state, &this->_bits, f);

I've check out the docs, and most of my code comes from the example encoding/decoding sample from the speex website.
I'm not sure what I'm missing here.