问:
In C python, accessing the bytecode evaluation stack
Given a C Python frame pointer, how do I look at arbitrary evaluation stack entries? (Some specific stack entries can be found via locals(), I'm talking about other stack entries.)

I asked a broader question like this a while ago:

getting the C python exec argument string or accessing the evaluation stack

but here I want to focus on being able to read CPython stack entries at runtime.

I'll take a solution that works on CPython 2.7 or any Python later than Python 3.3. However if you have things that work outside of that, share that and, if there is no better solution I'll accept that.

I'd prefer not modifying the C Python code. In Ruby, I have in fact done this to get what I want. I can speak from experience that this is probably not the way we want to work. But again, if there's no better solution, I'll take that. (My understanding wrt to SO points is that I lose it in the bounty either way. So I'm happy go see it go to the person who has shown the most good spirit and willingness to look at this, assuming it works.)

update: See the comment by user2357112 tldr; Basically this is hard-to-impossible to do. (Still, if you think you have the gumption to try, by all means do so.)

So instead, let me narrow the scope to this simpler problem which I think is doable:

Given a python stack frame, like inspect.currentframe(), find the beginning of the evaluation stack. In the C version of the structure, this is f_valuestack. From that we then need a way in Python to read off the Python values/objects from there.

update 2 well the time period for a bounty is over and no one (including my own summary answer) has offered concrete code. I feel this is a good start though and I now understand the situation much more than I had. In the obligatory "describe why you think there should be a bounty" I had listed one of the proffered choices "to draw more attention to this problem" and to that extent where there had been something  less than a dozen views of the prior incarnation of the problem, as I type this it has been viewed a little under 190 times. So this is a success. However...

If someone in the future decides to carry this further, contact me and I'll set up another bounty.

Thanks all.

答:
This is sometimes possible, with ctypes for direct C struct member access, but it gets messy fast.

First off, there's no public API for this, on the C side or the Python side, so that's out. We'll have to dig into the undocumented insides of the C implementation. I'll be focusing on the CPython 3.8 implementation; the details should be similar, though likely different, in other versions.

A PyFrameObject struct has an f_valuestack member that points to the bottom of its evaluation stack. It also has an f_stacktop member that points to the top of its evaluation stack... sometimes. During execution of a frame, Python actually keeps track of the top of the stack using a stack_pointer local variable in _PyEval_EvalFrameDefault:

```<code>stack_pointer = f->f_stacktop;
assert(stack_pointer != NULL);
f->f_stacktop = NULL;       /* remains NULL unless yield suspends frame */
</code>```

There are two cases in which f_stacktop is restored. One is if the frame is suspended by a yield (or yield from, or any of the multiple constructs that suspend coroutines through the same mechanism). The other is right before calling a trace function for a 'line' or 'opcode' trace event. f_stacktop is cleared again when the frame unsuspends, or after the trace function finishes.

That means that if

you're looking at a suspended generator or coroutine frame, or

you're currently in a trace function for a 'line' or 'opcode' event for a frame

then you can access the f_valuestack and f_stacktop pointers with ctypes to find the lower and upper bounds of the frame's evaluation stack and access the PyObject * pointers stored in that range. You can even get a superset of the stack contents without ctypes with gc.get_referents(frame_object), although this will contain other referents that aren't on the frame's stack.

Debuggers use trace functions, so this gets you value stack entries for the top stack frame while debugging, most of the time. It does not get you value stack entries for any other stack frames on the call stack, and it doesn't get you value stack entries while tracing an 'exception' event or any other trace events.

When f_stacktop is NULL, determining the frame's stack contents is close to impossible. You can still see where the stack begins with f_valuestack, but you can't see where it ends. The stack top is stored in a C-level stack_pointer local variable that's really hard to access.

There's the frame's code object's co_stacksize, which gives an upper bound on the stack size, but it doesn't give the actual stack size.

You can't tell where the stack ends by examining the stack itself, because Python doesn't null out the pointers on the stack when it pops entries.

gc.get_referents doesn't return value stack entries when f_stacktop is null. It doesn't know how to retrieve stack entries safely in this case either (and it doesn't need to, because if f_stacktop is null and stack entries exist, the frame is guaranteed reachable).

You might be able to examine the frame's f_lasti to determine the last bytecode instruction it was on and try to figure out where that instruction would leave the stack, but that would take a lot of intimate knowledge of Python bytecode and the bytecode evaluation loop, and it's still ambiguous sometimes (because the frame might be halfway through an instruction). This would at least give you a lower bound on the current stack size, though, letting you safely inspect at least some of it.

Frame objects have independent value stacks that aren't contiguous with each other, so you can't look at the bottom of one frame's stack to find the top of another. (The value stack is actually allocated within the frame object itself.)

You might be able to hunt down the stack_pointer local variable with some GDB magic or something, but it'd be a mess.

Body:
This is sometimes possible, with ctypes for direct C struct member access, but it gets messy fast.

First off, there's no public API for this, on the C side or the Python side, so that's out. We'll have to dig into the undocumented insides of the C implementation. I'll be focusing on the CPython 3.8 implementation; the details should be similar, though likely different, in other versions.

A PyFrameObject struct has an f_valuestack member that points to the bottom of its evaluation stack. It also has an f_stacktop member that points to the top of its evaluation stack... sometimes. During execution of a frame, Python actually keeps track of the top of the stack using a stack_pointer local variable in _PyEval_EvalFrameDefault:

stack_pointer = f->f_stacktop;
assert(stack_pointer != NULL);
f->f_stacktop = NULL;       /* remains NULL unless yield suspends frame */

There are two cases in which f_stacktop is restored. One is if the frame is suspended by a yield (or yield from, or any of the multiple constructs that suspend coroutines through the same mechanism). The other is right before calling a trace function for a 'line' or 'opcode' trace event. f_stacktop is cleared again when the frame unsuspends, or after the trace function finishes.

That means that if

you're looking at a suspended generator or coroutine frame, or

you're currently in a trace function for a 'line' or 'opcode' event for a frame

then you can access the f_valuestack and f_stacktop pointers with ctypes to find the lower and upper bounds of the frame's evaluation stack and access the PyObject * pointers stored in that range. You can even get a superset of the stack contents without ctypes with gc.get_referents(frame_object), although this will contain other referents that aren't on the frame's stack.

Debuggers use trace functions, so this gets you value stack entries for the top stack frame while debugging, most of the time. It does not get you value stack entries for any other stack frames on the call stack, and it doesn't get you value stack entries while tracing an 'exception' event or any other trace events.

When f_stacktop is NULL, determining the frame's stack contents is close to impossible. You can still see where the stack begins with f_valuestack, but you can't see where it ends. The stack top is stored in a C-level stack_pointer local variable that's really hard to access.

There's the frame's code object's co_stacksize, which gives an upper bound on the stack size, but it doesn't give the actual stack size.

You can't tell where the stack ends by examining the stack itself, because Python doesn't null out the pointers on the stack when it pops entries.

gc.get_referents doesn't return value stack entries when f_stacktop is null. It doesn't know how to retrieve stack entries safely in this case either (and it doesn't need to, because if f_stacktop is null and stack entries exist, the frame is guaranteed reachable).

You might be able to examine the frame's f_lasti to determine the last bytecode instruction it was on and try to figure out where that instruction would leave the stack, but that would take a lot of intimate knowledge of Python bytecode and the bytecode evaluation loop, and it's still ambiguous sometimes (because the frame might be halfway through an instruction). This would at least give you a lower bound on the current stack size, though, letting you safely inspect at least some of it.

Frame objects have independent value stacks that aren't contiguous with each other, so you can't look at the bottom of one frame's stack to find the top of another. (The value stack is actually allocated within the frame object itself.)

You might be able to hunt down the stack_pointer local variable with some GDB magic or something, but it'd be a mess.


来源: stackexchange

问:
How to populate a 2d array?
I have the following code that (nearly) populates a list of lists (I will call it a 2d array) in Python.

Instead of going up from 0-6 and repeating this 3 times, I want it to populate the array with numbers 0 - 20. Please see code below:

```<code>#matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
#print(matrix[1][2])

rows=3
columns=7

for i in range(rows):
  for j in range(columns):
    matrix=[j]
    i=i+1
    print(matrix,end="")
</code>```

The erroneous output is:

```<code>[0][1][2][3][4][5][6][0][1][2][3][4][5][6][0][1][2][3][4][5][6]
</code>```

I want the output to be:

```<code>[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
</code>```

答:
There are fancier ways, but this is the most straightforward:

```<code>>>> rows = 3
>>> columns = 7
>>> n = 1
>>> matrix = []
>>> for _ in range(rows):
...     sub = []
...     for _ in range(columns):
...         sub.append(n)
...         n += 1
...     matrix.append(sub)
...
>>> matrix
[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21]]
</code>```

And for good measure, a fancy way:

```<code>>>> import itertools
>>> counter = itertools.count(1)
>>> rows = 3
>>> columns = 7
>>> matrix = [[n for n, _ in zip(counter, range(columns))] for _ in range(rows)]
>>> matrix
[[1, 2, 3, 4, 5, 6, 7], [9, 10, 11, 12, 13, 14, 15], [17, 18, 19, 20, 21, 22, 23]]
>>>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to populate a 2d array?

Body:
I have the following code that (nearly) populates a list of lists (I will call it a 2d array) in Python.

Instead of going up from 0-6 and repeating this 3 times, I want it to populate the array with numbers 0 - 20. Please see code below:

#matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
#print(matrix[1][2])

rows=3
columns=7

for i in range(rows):
  for j in range(columns):
    matrix=[j]
    i=i+1
    print(matrix,end="")

The erroneous output is:

[0][1][2][3][4][5][6][0][1][2][3][4][5][6][0][1][2][3][4][5][6]

I want the output to be:

[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]

Body:
There are fancier ways, but this is the most straightforward:

>>> rows = 3
>>> columns = 7
>>> n = 1
>>> matrix = []
>>> for _ in range(rows):
...     sub = []
...     for _ in range(columns):
...         sub.append(n)
...         n += 1
...     matrix.append(sub)
...
>>> matrix
[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21]]

And for good measure, a fancy way:

>>> import itertools
>>> counter = itertools.count(1)
>>> rows = 3
>>> columns = 7
>>> matrix = [[n for n, _ in zip(counter, range(columns))] for _ in range(rows)]
>>> matrix
[[1, 2, 3, 4, 5, 6, 7], [9, 10, 11, 12, 13, 14, 15], [17, 18, 19, 20, 21, 22, 23]]
>>>


问:
React Native - Reveal modal with option to show more upon tapping it
I have a form that once completed, a Result component will slide up on the screen showing a score. There will be a TouchableHighlight on this component so that once pressed, the Result component will slide up more to reveal more details about the result. So something like below where completing the form will make my Result component appear with a button to reveal more information.

```<code>Show result
|--------------------------|
|   Result Score: 100   ^  |
|                          |
|--------------------------|
______________________________
Click on arrow to reveal more information
|--------------------------|
|   Result Score: 100      |
|                          |
|   Some more info         |
|--------------------------|
</code>```

At the moment, my result component appears by manipulating styles and changing the flex value, but this results in shrinking my form to fit the results. I was thinking if a better solution was to render a modal as it doesn't matter if form is covered by the results. I'm looking for recommendations to implement this.

答:
You should understand how flex works. Think of it as dividing a whole into portions. When adding content you will need to increase the vertical height of the container.

The simplest way to handle dynamically generated and variable height content is to put the content in a scrollview. You can set contentContainerStyle to something like { alignItems: 'stretch', alignSelf: 'stretch' } and avoid defining flex on the children of scrollview so they take up only as much space as needed and grow as needed.

This may not work well with all use cases though. Sometimes you really don't want a scrollview. I just suggest this method as one of the simplest.

Body:
I have a form that once completed, a Result component will slide up on the screen showing a score. There will be a TouchableHighlight on this component so that once pressed, the Result component will slide up more to reveal more details about the result. So something like below where completing the form will make my Result component appear with a button to reveal more information.

Show result
|--------------------------|
|   Result Score: 100   ^  |
|                          |
|--------------------------|
______________________________
Click on arrow to reveal more information
|--------------------------|
|   Result Score: 100      |
|                          |
|   Some more info         |
|--------------------------|

At the moment, my result component appears by manipulating styles and changing the flex value, but this results in shrinking my form to fit the results. I was thinking if a better solution was to render a modal as it doesn't matter if form is covered by the results. I'm looking for recommendations to implement this.


问:
Implications of Wrapping Delayed Job in Transaction for Rails App
Can anyone explain what would happen in the code below if the delayed_job that's scheduled in two weeks fails?

My understand is that this entire transaction would sit in memory until the transaction runs successfully or exhausts the permitted number of attempts (i.e. transaction doesn't merely guarantee that the job itself is created). Am I correct? If anyone could also elaborate on implications of this structure (i.e. memory leakage, race conditions, performance, etc.) and potential improvements that would be greatly appreciated!

```<code>...

def process
  old_user.transaction(requires_new: true) do
    begin
      update_user_attributes

      TransferUserDataJob.new(old_user, new_user).delay(run_at: 14.days.from_now, queue: 'transfer_user_data_queue').perform

      raise ActiveRecord::Rollback if user.status.nil?
    rescue Exception => e
      raise ActiveRecord::Rollback
    end
end

...
</code>```

答:
No, the transaction will NOT wait two weeks. This is precisely the reason why background jobs exist: do the expensive/heavy stuff later, so that frontend can respond as quickly as possible. If your user transfer process needs to happen in the same transaction, either move everything to the worker, or do everything on the spot, without delaying.

That is, transaction doesn't merely guarantee that the job itself is created?

This is exactly what happens in your code.

Body:
Can anyone explain what would happen in the code below if the delayed_job that's scheduled in two weeks fails?

My understand is that this entire transaction would sit in memory until the transaction runs successfully or exhausts the permitted number of attempts (i.e. transaction doesn't merely guarantee that the job itself is created). Am I correct? If anyone could also elaborate on implications of this structure (i.e. memory leakage, race conditions, performance, etc.) and potential improvements that would be greatly appreciated!

...

def process
  old_user.transaction(requires_new: true) do
    begin
      update_user_attributes

      TransferUserDataJob.new(old_user, new_user).delay(run_at: 14.days.from_now, queue: 'transfer_user_data_queue').perform

      raise ActiveRecord::Rollback if user.status.nil?
    rescue Exception => e
      raise ActiveRecord::Rollback
    end
end

...


问:
libcontainer vs Docker vs OCF vs runc?
I'm trying to understand the Docker world a little better, and can't quite seem to wrap my brain around the differences between these. I believe that OCF is an emerging container standard being endorsed by OpenContainers, and I believe that Docker is set to be the first reference implementation of that standard. But even then, I have concerns that the Google Gods don't seem to be providing answers for:

What exactly is the OCF "standard"? Just a written document? A written API? A compiled C lib?

What are some examples of specific items governed by this standard? I guess without really understanding what a "container" is, its hard for me to understand what a governing standard for containers even addresses.

How/where do runc and libcontainer fit into the Docker/OCF equation?

答: Just in case anyone accidentally finds comes across this old thread like I just did: this specification is no longer called OCF, it is now known as the "Open Container Initiative Runtime Specification", the link above still works though it now sends you to https://github.com/opencontainers/runtime-spec.  There is a different OCF spec around (Open Connectivity Foundation).</p>

Title: libcontainer vs Docker vs OCF vs runc?


问:
Active links jquery superfish
I have a question.
I use jquery superfish menu with the following structure

```<code><div id="menu" class="ge-navigation-item">
  <!-- navigation -->
    <ul id="test" class="sf-menu sf-vertical sf-js-enabled sf-shadow">
      <li><a href="index.html">Home</a></li>
      <li><a href="#">About</a>
        <ul>
          <li><a href="index.html">Index</a></li>
          <li><a href="#">Page</a>
                            <ul>
                                <li><a href="#">menu item</a></li>
                                <li><a href="#">menu item</a></li>
                                <li><a href="proef.html">menu item</a></li>
                                <li><a href="index.html">index</a></li>
                                <li><a href="#">menu item</a></li>
                            </ul>
          </li>
          <li><a href="page-fullwidth.php">Page - Full Width</a></li>
        </ul>
      </li>
      <li><a href="showcase.php">Showcase</a></li>
    </ul>
    <!-- /navigation -->
  </div>
</code>```

what I want is that clicking on a link the menu structure will be visible

So clicking on index.html will set a link on all links with href index.html
But clicking on proef.html will set an active class on href proef.html - Page - About

So far I have tried this but with bad results

```<code>var path = window.location.toString().split("/")
path = path[path.length - 1]
//alert (path);
if (path)
$("#test a[href='" + path + "']").addClass("actief");
$("#test ul li:has(a) a[href='" + path +
     "']").parent().parent().parent().addClass("actief");
</code>```

答:
Welcome to stackoverflow.  Try this:

```<code>var path = window.location.pathname.split('/');
path = path[path.length-1];

if (path !== undefined) {
    $("#menu3").find("a[href='" + path + "']").addClass("actief");

}
</code>```

That should appply the class to any link that matches the last item of the current url.  If you were looking for a different behavior, please elaborate!

UPDATE

Actually, it looks like you need this:

```<code>var path = window.location.pathname.split('/');
path = path[path.length-1];

if (path !== undefined) {
    $("#menu3")
        .find("a[href$='" + path + "']") // gets all links that match the href
        .parents('li')  // gets all list items that are ancestors of the link
        .children('a')  // walks down one level from all selected li's
        .addClass('actief');
}
</code>```

That will put the class on every a element up the chain.

Title: Active links jquery superfish

Body:
I have a question.
I use jquery superfish menu with the following structure

Home

About

Index

Page

menu item

menu item

menu item

index

menu item

Page - Full Width

Showcase

what I want is that clicking on a link the menu structure will be visible

So clicking on index.html will set a link on all links with href index.html
But clicking on proef.html will set an active class on href proef.html - Page - About

So far I have tried this but with bad results

var path = window.location.toString().split("/")
path = path[path.length - 1]
//alert (path);
if (path)
$("#test a[href='" + path + "']").addClass("actief");
$("#test ul li:has(a) a[href='" + path +
     "']").parent().parent().parent().addClass("actief");

Body:
Welcome to stackoverflow.  Try this:

var path = window.location.pathname.split('/');
path = path[path.length-1];

if (path !== undefined) {
    $("#menu3").find("a[href='" + path + "']").addClass("actief");

}

That should appply the class to any link that matches the last item of the current url.  If you were looking for a different behavior, please elaborate!

UPDATE

Actually, it looks like you need this:

var path = window.location.pathname.split('/');
path = path[path.length-1];

if (path !== undefined) {
    $("#menu3")
        .find("a[href$='" + path + "']") // gets all links that match the href
        .parents('li')  // gets all list items that are ancestors of the link
        .children('a')  // walks down one level from all selected li's
        .addClass('actief');
}

That will put the class on every a element up the chain.


问:
Redefining Methods to a Javascript function
So I have a Javascript function i.e

```<code>var object = function(){
    function sayHello(){
       console.log("Hello");
    }
}
</code>```

Is there a way to redefine the object.sayHello method later on in my code such that instead it prints "Bonjour"?

答:
js

```<code>var input = document.getElementById('input').value;
var object = function(){
    function sayHello(input){
       console.log(input);
    }
}
</code>```

and html

```<code><input type="text" name="input" id="input" placeholder="enter greetings">
</code>```

Body:
So I have a Javascript function i.e

var object = function(){
    function sayHello(){
       console.log("Hello");
    }
}

Is there a way to redefine the object.sayHello method later on in my code such that instead it prints "Bonjour"?

Body:
js

var input = document.getElementById('input').value;
var object = function(){
    function sayHello(input){
       console.log(input);
    }
}

and html

<input type="text" name="input" id="input" placeholder="enter greetings">


问:
Javascript : get  src and set as variable?
If the img below is present

```<code><img id="youtubeimg" src="http://i1.ytimg.com/vi/VK4ah66jBvE/0.jpg"/>
</code>```

and the script is

```<code><script>
var youtubeimgsrc = "something here"

document.write(''+youtubeimgsrc+'')
</script>
</code>```

and the result should be http://i1.ytimg.com/vi/VK4ah66jBvE/0.jpg

what can i do to get the image source and set as a variable.

答:
Use JQuery, its easy.

Include the JQuery library into your html file in the head as such:

```<code><head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
</code>```

(Make sure that this script tag goes before your other script tags in your html file)

Target your id in your JavaScript file as such:

```<code><script>
var youtubeimcsrc = $('#youtubeimg').attr('src');

//your var will be the src string that you're looking for

</script>
</code>```

Title: Javascript : get <img> src and set as variable?

Body:
If the img below is present

and the script is

and the result should be http://i1.ytimg.com/vi/VK4ah66jBvE/0.jpg

what can i do to get the image source and set as a variable.

Body:
Use JQuery, its easy.

Include the JQuery library into your html file in the head as such:

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

(Make sure that this script tag goes before your other script tags in your html file)

Target your id in your JavaScript file as such:

<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');

//your var will be the src string that you're looking for

</script>


问:
Javascript Regex 1-10
I am trying to get a regex that can get from 1-10 and i have been having trouble

I have tried :

```<code>/^[1-9]|10$/ //this will matches out 1-9 but not 10
/^10|[1-9]$/ //this will matches 10 but no 1-9 digits
</code>```

I feel weird because i have seen this question before and people said either of these expression should work. Any ideas of another way to get any # from 1-10?

答:
Without knowing your specific use case, I don't see a reason to include ^ and & here, which requires that the number is surrounded by a start and end of line. Even if your inner regex was correct, it wouldn't match the '6' in: 'I have a 6 year old son.'

Instead, surround the inner regex with \b (a word boundary). So, to use Jordan's example, \b([1-9]|10)\b would match all numbers from 1-10. To use regex in javascript, you need to utilize one of several functions that accept it as an argument, or methods that can be called on it:

let regex = /\b([1-9]|10)\b/;

console.log('I have a 6 year old son.'.match(regex)[0]);
console.log('I have a six year old son.'.match(regex));

console.log('I have a 6 year old son.'.replace(regex, 'six'));

console.log(regex.test('I have a 6 year old son.'));
console.log(regex.test('I have a six year old son.'));```

Title: Javascript Regex 1-10

Body:
I am trying to get a regex that can get from 1-10 and i have been having trouble

I have tried :

/^[1-9]|10$/ //this will matches out 1-9 but not 10
/^10|[1-9]$/ //this will matches 10 but no 1-9 digits

I feel weird because i have seen this question before and people said either of these expression should work. Any ideas of another way to get any # from 1-10?


问:
How to implement C# Rhino Security
I am trying to implement Rhino Security, i have managed to find a couple tutorials but they do not give enough information to completely understand it, i was wondering if anyone knows of a good source where to learn about Rhino Security from. Or sugest alternatives for implementing security with NHibernate.

Is there some sort of documentation for any of the methods / classes within Rhino Security?

答: As far as I know there is no centralized documentation for Rhino.Security. The best tutorial I know is this article by Artur Trosin (even though it's slightly outdated by now). Winecellarmanager is a sample app that uses Rhino.Security. There's also a admin UI for Rhino.Security, reading its source code might help. There was also some talk about integrating Rhino.Security to Who Can Help Me, but I don't know if it was finished. There's also an article about integrating Rhino.Security to S#arp projects.</p>

ContentLicense: CC BY-SA 2.5

Title: How to implement C# Rhino Security


问:
SQL case sensitive query with BETWEEN
On SQLServer 2012, why does the query:

```<code>SELECT
   Firstname
FROM
   dbo.CWIndividualGivers
WHERE
   FirstName BETWEEN 'r' COLLATE SQL_Latin1_General_CP1_CS_AS AND 'rzzz' COLLATE SQL_Latin1_General_CP1_CS_AS
</code>```

Return values like 'Ruth' and 'Renee'?

I would expect the names with capital letters in the first position to be excluded.  How does BETWEEN work in case sensitive collation?

答:
You could do something like the following:

```<code>Select LEFT(Firstname, 100)
FROM dbo.CWIndividualGivers
WHERE FirstName like 'r%' COLLATE SQL_Latin1_General_CP1_CS_AS
</code>```

NOTE: 100 is just a number, you can replace this with however long the longest name in your dataset is.

Title: SQL case sensitive query with BETWEEN

Body:
On SQLServer 2012, why does the query:

SELECT
   Firstname
FROM
   dbo.CWIndividualGivers
WHERE
   FirstName BETWEEN 'r' COLLATE SQL_Latin1_General_CP1_CS_AS AND 'rzzz' COLLATE SQL_Latin1_General_CP1_CS_AS

Return values like 'Ruth' and 'Renee'?

I would expect the names with capital letters in the first position to be excluded.  How does BETWEEN work in case sensitive collation?

Body:
You could do something like the following:

Select LEFT(Firstname, 100)
FROM dbo.CWIndividualGivers
WHERE FirstName like 'r%' COLLATE SQL_Latin1_General_CP1_CS_AS

NOTE: 100 is just a number, you can replace this with however long the longest name in your dataset is.


问:
A simple UIPickerView in MonoTouch (Xamarin)?
Can anybody describe how I can create a UIPickerView in monotouch using XCode and populate it with sample data?

I did look at the example here: https://github.com/xamarin/monotouch-samples/blob/master/MonoCatalog-MonoDevelop/PickerViewController.xib.cs but this hasn't been very helpful since I am creating my UIPickerView in the XCode. Here's what I have so far:

```<code>public partial class StatusPickerPopoverView : UIViewController
{
    public StatusPickerPopoverView (IntPtr handle) : base (handle)
    {
        pickerStatus = new UIPickerView();
        pickerStatus.Model = new StatusPickerViewModel();
    }

    public StatusPickerPopoverView (): base ()
    {
    }

    public class StatusPickerViewModel : UIPickerViewModel
    {
        public override int GetComponentCount (UIPickerView picker)
        {
            return 1;
        }

        public override int GetRowsInComponent (UIPickerView picker, int component)
        {
            return 5;
        }

        public override string GetTitle (UIPickerView picker, int row, int component)
        {

            return "Component " + row.ToString();
        }
    }
}
</code>```

答:
I created a blog post, covering it in more detail than the current answers.

Firstly, add a UIPickerView to your Storyboard. Add a name to the UIPicker.

Next, A class implementing UIPickerViewModel is required, which sets the Pickers model which populates it. If you are more familiar with Android development, setting up a Picker for Xamarin iOS can seem weird, you cannot just populate the picker with a list.

Lastly, set the model of the UIPickerView to the class created.

Body:
Can anybody describe how I can create a UIPickerView in monotouch using XCode and populate it with sample data?

I did look at the example here: https://github.com/xamarin/monotouch-samples/blob/master/MonoCatalog-MonoDevelop/PickerViewController.xib.cs but this hasn't been very helpful since I am creating my UIPickerView in the XCode. Here's what I have so far:

public partial class StatusPickerPopoverView : UIViewController
{
    public StatusPickerPopoverView (IntPtr handle) : base (handle)
    {
        pickerStatus = new UIPickerView();
        pickerStatus.Model = new StatusPickerViewModel();
    }

    public StatusPickerPopoverView (): base ()
    {
    }

    public class StatusPickerViewModel : UIPickerViewModel
    {
        public override int GetComponentCount (UIPickerView picker)
        {
            return 1;
        }

        public override int GetRowsInComponent (UIPickerView picker, int component)
        {
            return 5;
        }

        public override string GetTitle (UIPickerView picker, int row, int component)
        {

            return "Component " + row.ToString();
        }
    }
}


问:
BelongsToMany of Laravel 5.4 does not work
I am creating a table where it displays a list of requests, I have a relation between the ID's 'erp_createdid' and 'erp_productid'. To display the name of the products, I created a belongsToMany, in which I specify my two 'ID's'.

Order model

```<code>class Order extends Model
{
    protected $table = 'erp_order';
    protected $fillable = ['erp_createdid'];
    protected $primaryKey = 'erp_orderid';

    public function description()
    {
        return $this->belongsToMany('App\Description','erp_order_product', 'erp_createdid', 'erp_productid');
    }

}
</code>```

Description Model

```<code>class Description extends Model
{
    protected $table = 'erp_product_description';
    protected $primaryKey = 'erp_productid';
    protected $fillable = ['erp_name'];
    public $timestamps = false;

    public function order()
        {
            return $this->belongsToMany('App\Order', 'erp_order_product', 'erp_createdid', 'erp_productid');
        }
</code>```

Table

```<code><td>@foreach($orders->description as $des)
 {{$des->erp_name}}
 @endforeach
 </td>
</code>```

But the values in the table are not displayed, any suggestions?

答:
I think you have the parameters on Order's belongsToMany in an incorrect order.

Try this:

```<code>public function description()
{
    return $this->belongsToMany('App\Description','erp_order_product', 'erp_productid', 'erp_createdid');
}
</code>```

Also try updating your foreach like this:

Oh OK, try this:

```<code>@foreach($orders as $order)
    @foreach($order->description as $description)
        {{ $description->erp_name }}
    @endforeach
@endforeach
</code>```

Body:
I am creating a table where it displays a list of requests, I have a relation between the ID's 'erp_createdid' and 'erp_productid'. To display the name of the products, I created a belongsToMany, in which I specify my two 'ID's'.

Order model

class Order extends Model
{
    protected $table = 'erp_order';
    protected $fillable = ['erp_createdid'];
    protected $primaryKey = 'erp_orderid';

    public function description()
    {
        return $this->belongsToMany('App\Description','erp_order_product', 'erp_createdid', 'erp_productid');
    }

}

Description Model

class Description extends Model
{
    protected $table = 'erp_product_description';
    protected $primaryKey = 'erp_productid';
    protected $fillable = ['erp_name'];
    public $timestamps = false;

    public function order()
        {
            return $this->belongsToMany('App\Order', 'erp_order_product', 'erp_createdid', 'erp_productid');
        }

Table

@foreach($orders->description as $des)
 {{$des->erp_name}}
 @endforeach

But the values in the table are not displayed, any suggestions?

Body:
I think you have the parameters on Order's belongsToMany in an incorrect order.

Try this:

public function description()
{
    return $this->belongsToMany('App\Description','erp_order_product', 'erp_productid', 'erp_createdid');
}

Also try updating your foreach like this:

Oh OK, try this:

@foreach($orders as $order)
    @foreach($order->description as $description)
        {{ $description->erp_name }}
    @endforeach
@endforeach


问:
Restricting time intervals in DateTime Picker
I'm using this to select date and time. The documentation does not mention about time picker, but it works anyhow.

HTML:

```<code><div class="dateTimePicker">
        <input name="start" type="text" value="">
        <span class="add-on"><i class="time-icon"></i></span>
</div>
</code>```

JS:

```<code>$(".dateTimePicker").datetimepicker({
    pickDate: false,
    pickTime: true,
    useSeconds: false,
    format: 'hh:mm'
});
</code>```

This works all fine. It shows a selector with intervals of 1 hour for hours, 3 minutes for minutes and 3 seconds for seconds.

My aim is to change the intervals of minutes from 3 to 15. Currently, the selector for minutes shows: 00 03 06 etc. Can I change it to 00 15 30 45. Is this even possible or are there any other time pickers which give me this flexibility?

答:
```<code>$(".dateTimePicker").datetimepicker({
    step: 15
});
</code>```

This is how sets interval in jquery datetimepicker

Body:
I'm using this to select date and time. The documentation does not mention about time picker, but it works anyhow.

HTML:

        <input name="start" type="text" value="">

JS:

$(".dateTimePicker").datetimepicker({
    pickDate: false,
    pickTime: true,
    useSeconds: false,
    format: 'hh:mm'
});

This works all fine. It shows a selector with intervals of 1 hour for hours, 3 minutes for minutes and 3 seconds for seconds.

My aim is to change the intervals of minutes from 3 to 15. Currently, the selector for minutes shows: 00 03 06 etc. Can I change it to 00 15 30 45. Is this even possible or are there any other time pickers which give me this flexibility?

Body:
$(".dateTimePicker").datetimepicker({
    step: 15
});

This is how sets interval in jquery datetimepicker


问:
Asp.net retrieve content from a Control
I will start by telling I'm not an ASC/C# developer, this is for a homework. (i hope somebody will understand what i want :D, because i dont know exactly the terms)

I have Friends.aspx and Friends.aspx.cs

In Friends.aspx i have something like

     <%@ Reference Control="~/FriendBox.ascx" %>

In Friends.aspx.cs i have this to populate divFriends:

```<code>
foreach (FBUser user in list){
      Control control = LoadControl("FriendBox.ascx");
      FriendBox myControl = (FriendBox)control;
      myControl.user = user;
      divFriends.Controls.Add(myControl);
  }
</code>```

In my page a have a form, and divFriends is inside the form. I have a button in this form. If i just press the button, my page gets submitted and i can retrieve values from selected checkboxes. (Every control contains a checkbox)

Everithing worked fine until i tried to submit the page via Ajax (JQuery).
My problem is that even the checkboxes are on page (i can se them, select them), when i do an ajax submit i cannot access values from checkboxes.
This is the code i use to retrieve values from checkboxes:

```
foreach(Control ctrl in divFriends.Controls) {<br>
      var friendBox = ctrl as FriendBox;
      //i can get here<br>
      if (friendBox != null)
      { //i never get here - because friendBox is allways null }
 }
</code>```

How can i make the content from divFriends accesible when i submit my form with Jquery?
Thanks in advance.

Edit: here is the javascript i use
```<code>
 $(document).ready(function () {
        $('.big').click(function () {
            //.big is my button
            $('.big').attr('disabled', true);</p>

```        var form_form = $(document).find('form');
        $.ajax({
            type: 'POST',
            url: form_form.attr('action'),
            data: form_form.serialize(),
            dataType: 'json',
            success: function (data) {
                console.log('success');
            },
            complete: function (XMLHttpRequest, textStatus) {
                $('.big').attr('disabled', false);
            }
        });
        return false;
    });
```

<p>});```

The javascript is working because i can submit data, and i can receive data back (json), when i look at the data submited i dont have the checkboxes from divFriends.

答:
The problem appears to be asp.net state managment issue. You are only adding FriendBox one time (I'm assuming, probably with an if not page.ispostback sort of thign), and not on each page hit.  Since FriendBox is added dynamically it's not surviving a postback and thus it does not exist when you try to read it.

You should add FriendBox each time the page loads, on Init before viewstate is loaded.  Adding the controls during on init will allow Viewstate to track the values and will probably fix the issue.

Title: Asp.net retrieve content from a Control

Body:
I will start by telling I'm not an ASC/C# developer, this is for a homework. (i hope somebody will understand what i want :D, because i dont know exactly the terms)

I have Friends.aspx and Friends.aspx.cs

In Friends.aspx i have something like

     <%@ Reference Control="~/FriendBox.ascx" %>

In Friends.aspx.cs i have this to populate divFriends:

foreach (FBUser user in list){
      Control control = LoadControl("FriendBox.ascx");
      FriendBox myControl = (FriendBox)control;
      myControl.user = user;
      divFriends.Controls.Add(myControl);
  }

In my page a have a form, and divFriends is inside the form. I have a button in this form. If i just press the button, my page gets submitted and i can retrieve values from selected checkboxes. (Every control contains a checkbox)

Everithing worked fine until i tried to submit the page via Ajax (JQuery).
My problem is that even the checkboxes are on page (i can se them, select them), when i do an ajax submit i cannot access values from checkboxes.
This is the code i use to retrieve values from checkboxes:

foreach(Control ctrl in divFriends.Controls) {

      var friendBox = ctrl as FriendBox;
      //i can get here

      if (friendBox != null)
      { //i never get here - because friendBox is allways null }
 }

How can i make the content from divFriends accesible when i submit my form with Jquery?
Thanks in advance.

Edit: here is the javascript i use

 $(document).ready(function () {
        $('.big').click(function () {
            //.big is my button
            $('.big').attr('disabled', true);

        var form_form = $(document).find('form');
        $.ajax({
            type: 'POST',
            url: form_form.attr('action'),
            data: form_form.serialize(),
            dataType: 'json',
            success: function (data) {
                console.log('success');
            },
            complete: function (XMLHttpRequest, textStatus) {
                $('.big').attr('disabled', false);
            }
        });
        return false;
    });

});

The javascript is working because i can submit data, and i can receive data back (json), when i look at the data submited i dont have the checkboxes from divFriends.


问:
django server not running on host with vagrant
Vagrantfile:

```<code>config.vm.network "forwarded_port", guest: 8080, host: 8080
</code>```

On my virtual machine I am running this command:

```<code>python manage.py runserver 0.0.0.0:8080
</code>```

But when I try to curl on host machine, response is curl: (52) Empty reply from server and on browser it says 127.0.0.1 didn’t send any data.

I looked on stackoverflow for this problem, most of them were able to resolve it by adding 0.0.0.0 to the runserver command. But, I have already added it.

I tried:

Disabling the firewall and allowing all connections to the virtual machine by accepting all input and output in iptables.

I changed the 127.0.0.1 localhost in /etc/hosts to 0.0.0.0 localhost but still the same response.

I ensured that my host machine is not preventing it by disabling the firewall on my host machine too.

Note: I am using ubuntu machine on virtual box and mac OS on host.

答:
While the virtual machine is running, any changes to the Vagrantfile are not properly registered by the machine even if you run vagrant up.

To ensure that all the changes get reflected correctly, the virtual machine should be halted and then run again.

In my case, I had changed the forwarding ports while the vagrant was running. I was doing vagrant up assuming the changes will get reflected but they did not.
Doing vagrant halt followed by vagrant up solved my issue.

Body:
Vagrantfile:

config.vm.network "forwarded_port", guest: 8080, host: 8080

On my virtual machine I am running this command:

python manage.py runserver 0.0.0.0:8080

But when I try to curl on host machine, response is curl: (52) Empty reply from server and on browser it says 127.0.0.1 didn’t send any data.

I looked on stackoverflow for this problem, most of them were able to resolve it by adding 0.0.0.0 to the runserver command. But, I have already added it.

I tried:

Disabling the firewall and allowing all connections to the virtual machine by accepting all input and output in iptables.

I changed the 127.0.0.1 localhost in /etc/hosts to 0.0.0.0 localhost but still the same response.

I ensured that my host machine is not preventing it by disabling the firewall on my host machine too.

Note: I am using ubuntu machine on virtual box and mac OS on host.


问:
Is this the right way to use generics in Java?
```<code>class Matrix<T>{
   private List<Attribute<T>> attributes;

   public Matrix(T type){
      attributes = new ArrayList<Attribute<T>>();
      attributes.add(new Attribute<T>(type));
   }
}
</code>```

I feel like in the constructor, these two lines should be use a specific type, not the generic T:

```<code>attributes = new ArrayList<Attribute<T>>();
      attributes.add(new Attribute<T>(type));
</code>```

But the compiler doesn't complain. So this is the right way to define this class?

答:
Yes, thats the right way. The only thing where you might be wrong is that your Parameter in the constructor should not be namend type, but value. The Type is T.

If you need to, you can say that your Generic has to a childtype of something else. Let's say we have a class which holds an Exception. We could just make a Membervariable of Type Exception. But when getting the Exception from inside this Object, we don't want to cast our Exception to a more specific one.

So we use a Generic which must be a childtype of Exception:

```<code>public class SomeClass<T extends Exception>
{
    private final T value;

    public SomeClass(T value)
    {
        this.value = value;
    }

    public T getValue()
    {
        return this.value;
    }
}
</code>```

Now we can do stuff like this:

```<code>SomeClass<ArrayIndexOutOfBoundsException> obj = new SomeClass<>(new ArrayIndexOutOfBoundsException());
ArrayIndexOutOfBoundsException exc = obj.getValue(); // no cast from Exception to ArrayIndexOutOfBoundsException needed
</code>```

Body:
class Matrix<T>{
   private List<Attribute<T>> attributes;

   public Matrix(T type){
      attributes = new ArrayList<Attribute<T>>();
      attributes.add(new Attribute<T>(type));
   }
}

I feel like in the constructor, these two lines should be use a specific type, not the generic T:

attributes = new ArrayList<Attribute<T>>();
      attributes.add(new Attribute<T>(type));

But the compiler doesn't complain. So this is the right way to define this class?

Body:
Yes, thats the right way. The only thing where you might be wrong is that your Parameter in the constructor should not be namend type, but value. The Type is T.

If you need to, you can say that your Generic has to a childtype of something else. Let's say we have a class which holds an Exception. We could just make a Membervariable of Type Exception. But when getting the Exception from inside this Object, we don't want to cast our Exception to a more specific one.

So we use a Generic which must be a childtype of Exception:

public class SomeClass<T extends Exception>
{
    private final T value;

    public SomeClass(T value)
    {
        this.value = value;
    }

    public T getValue()
    {
        return this.value;
    }
}

Now we can do stuff like this:

SomeClass<ArrayIndexOutOfBoundsException> obj = new SomeClass<>(new ArrayIndexOutOfBoundsException());
ArrayIndexOutOfBoundsException exc = obj.getValue(); // no cast from Exception to ArrayIndexOutOfBoundsException needed


问:
Rails: Normal log doesn't print out after inserting custom middleware
I want to print out all request from client. So I write a custom middleware:

```<code>class Logger
  def initialize(app)
    @app = app
  end

  def call(env)

    headers = env.select {|k,v| k.start_with? 'HTTP_'}
    .map {|pair| [pair[0].sub(/^HTTP_/, ''), pair[1]].join(": ")}
    .sort

    request_params = env['rack.input'].read

    puts "Request: #{env["REQUEST_METHOD"]} #{env["PATH_INFO"]} #{headers} #{request_params}"

    @app.call(env).tap do |response|
      status, headers, body = *response

      puts "Response: #{status}"
      puts "Headers: #{headers}"
      # puts "Response:"

      # body.each do |line|
      #   puts line
      # end
    end
  end
end
</code>```

After that, I insert to application.rb

```<code>config.middleware.insert_before Rails::Rack::Logger, ::Logger
</code>```

Request is printed out fine. The only problem is all other logs (such as activerecord log hasn't existed anymore). Please help me figure out why.

答:
You are naming your class Logger which is already the name of the Ruby standard lib Logger class which is used by the Rails logger i.e. you are overriding the Logger class (the initialize method in particular) and breaking Rails logging.

Name your logger class something else like MyRackLogger.

Body:
I want to print out all request from client. So I write a custom middleware:

class Logger
  def initialize(app)
    @app = app
  end

  def call(env)

    headers = env.select {|k,v| k.start_with? 'HTTP_'}
    .map {|pair| [pair[0].sub(/^HTTP_/, ''), pair[1]].join(": ")}
    .sort

    request_params = env['rack.input'].read

    puts "Request: #{env["REQUEST_METHOD"]} #{env["PATH_INFO"]} #{headers} #{request_params}"

    @app.call(env).tap do |response|
      status, headers, body = *response

      puts "Response: #{status}"
      puts "Headers: #{headers}"
      # puts "Response:"

      # body.each do |line|
      #   puts line
      # end
    end
  end
end

After that, I insert to application.rb

config.middleware.insert_before Rails::Rack::Logger, ::Logger

Request is printed out fine. The only problem is all other logs (such as activerecord log hasn't existed anymore). Please help me figure out why.


问:
how to create a new observable subscription based on existing observable in rxjs?
I need to do something as the following line in my project(from
https://github.com/devyumao/angular2-busy)

```<code>ngOnInit() {
    this.busy = this.http.get('...').subscribe();
}
</code>```

In my project, I am making request based on route change as the following:

```<code>ngOnInit(): void {
    this.activatedRoute
        .params
        .map(params => params['queryString'])
        .flatMap(id => this.http.(''))
        .subscribe(result => this.data = result);
}
</code>```

It seems I need to create a new subscription every time there is a change in route. I am not sure how to do it.

I am looking for rxjs solution only (without using Promise).

Thanks!

derek

答:
Actually, you can subscribe to the ajaxCallObservable in the chain. :)

ngOnInit(): void {
    this.activatedRoute
        .params
        .map(params => params['queryString'])
        .map(id => this.http.(''))
        .do(ajaxCallObservable => { this.busy = ajaxCallObservable.subscribe() })
        .flatMap(ajaxCallObservable => ajaxCallObservable)
        .subscribe(result => this.data = result);
}```

Body:
I need to do something as the following line in my project(from
https://github.com/devyumao/angular2-busy)

ngOnInit() {
    this.busy = this.http.get('...').subscribe();
}

In my project, I am making request based on route change as the following:

ngOnInit(): void {
    this.activatedRoute
        .params
        .map(params => params['queryString'])
        .flatMap(id => this.http.(''))
        .subscribe(result => this.data = result);
}

It seems I need to create a new subscription every time there is a change in route. I am not sure how to do it.

I am looking for rxjs solution only (without using Promise).

Thanks!

derek


问:
udevadm does not show all attributes inside a docker container
When I run docker container and list properties of some device with udevadm inside the container, there are only the basic information about the device. When I do the same thing on host, I can see much more. What can I do to get all the information inside the container?

```<code>host$ udevadm info --query=property /dev/bus/usb/004/008
BUSNUM=004
DEVNAME=/dev/bus/usb/004/008
DEVNUM=008
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1
DEVTYPE=usb_device
DRIVER=usb
ID_BUS=usb
ID_MODEL=MCP2210_USB-to-SPI_Master
ID_MODEL_ENC=MCP2210 USB-to-SPI Master
ID_MODEL_ID=00de
ID_REVISION=0002
ID_SERIAL=Microchip_Technology_Inc._MCP2210_USB-to-SPI_Master_0000267472
ID_SERIAL_SHORT=0000267472
ID_USB_INTERFACES=:030000:
ID_VENDOR=Microchip_Technology_Inc.
ID_VENDOR_ENC=Microchip Technology Inc.
ID_VENDOR_FROM_DATABASE=Microchip Technology, Inc.
ID_VENDOR_ID=04d8
MAJOR=189
MINOR=391
PRODUCT=4d8/de/2
SUBSYSTEM=usb
TYPE=0/0/0
USEC_INITIALIZED=176769529274

host$ docker run -ti -v /dev/bus/usb/:/dev/bus/usb alpine sh
container# apk update
container# apk add eudev
container# udevadm info --query=property /dev/bus/usb/004/008
BUSNUM=004
DEVNAME=/dev/bus/usb/004/008
DEVNUM=008
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1
DEVTYPE=usb_device
DRIVER=usb
MAJOR=189
MINOR=391
PRODUCT=4d8/de/2
SUBSYSTEM=usb
TYPE=0/0/0
</code>```

I have also tried to mount other volumes from host: /sys, /dev. Did not help.

EDIT according to the Alex P.'s answer:

I'm not very experienced with udev. I have copied this

```<code>SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", IMPORT{builtin}="usb_id", IMPORT{builtin}="hwdb --subsystem=usb"
</code>```

to /dev/udev/rules.d/10-local.rules, I have set udev logging to debug, reloaded config with udevadm control --reload. Now I get this:

```<code>calling: info
P: /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2
N: bus/usb/004/016
no db file to read /run/udev/data/c189:399: No such file or directory
E: BUSNUM=004
E: DEVNAME=/dev/bus/usb/004/016
E: DEVNUM=016
E: DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2
E: DEVTYPE=usb_device
E: DRIVER=usb
E: MAJOR=189
E: MINOR=399
E: PRODUCT=4d8/de/2
E: SUBSYSTEM=usb
E: TYPE=0/0/0
</code>```

For now still no luck.
I tried to run the container with --privileged flag, did not help. I have no other rules in /etc/udev/rules.d. I tried to copy all rules from my host, no luck.

```<code>host$ udevadm monitor --environment
    monitor will print the received events for:
UDEV - the event which udev sends out after rule processing
KERNEL - the kernel uevent

KERNEL[183757.837879] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1 (usb)
ACTION=add
BUSNUM=004
DEVNAME=/dev/bus/usb/004/034
DEVNUM=034
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1
DEVTYPE=usb_device
MAJOR=189
MINOR=417
PRODUCT=4d8/de/2
SEQNUM=5985
SUBSYSTEM=usb
TYPE=0/0/0

KERNEL[183757.838467] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0 (usb)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0
DEVTYPE=usb_interface
INTERFACE=3/0/0
MODALIAS=usb:v04D8p00DEd0002dc00dsc00dp00ic03isc00ip00in00
PRODUCT=4d8/de/2
SEQNUM=5986
SUBSYSTEM=usb
TYPE=0/0/0

KERNEL[183757.840044] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F (hid)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=5987
SUBSYSTEM=hid

KERNEL[183757.840586] add      /class/usbmisc (class)
ACTION=add
DEVPATH=/class/usbmisc
SEQNUM=5988
SUBSYSTEM=class

KERNEL[183757.840891] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=add
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=5989
SUBSYSTEM=usbmisc

KERNEL[183757.841219] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0 (hidraw)
ACTION=add
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=5990
SUBSYSTEM=hidraw

UDEV  [183757.842324] add      /class/usbmisc (class)
ACTION=add
DEVPATH=/class/usbmisc
SEQNUM=5988
SUBSYSTEM=class
USEC_INITIALIZED=183757842069

UDEV  [183758.395467] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1 (usb)
ACTION=add
BUSNUM=004
DEVNAME=/dev/bus/usb/004/034
DEVNUM=034
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1
DEVTYPE=usb_device
DRIVER=usb
ID_BUS=usb
ID_MODEL=MCP2210_USB-to-SPI_Master
ID_MODEL_ENC=MCP2210\x20USB-to-SPI\x20Master
ID_MODEL_ID=00de
ID_REVISION=0002
ID_SERIAL=Microchip_Technology_Inc._MCP2210_USB-to-SPI_Master_0000267472
ID_SERIAL_SHORT=0000267472
ID_USB_INTERFACES=:030000:
ID_VENDOR=Microchip_Technology_Inc.
ID_VENDOR_ENC=Microchip\x20Technology\x20Inc.
ID_VENDOR_FROM_DATABASE=Microchip Technology, Inc.
ID_VENDOR_ID=04d8
MAJOR=189
MINOR=417
PRODUCT=4d8/de/2
SEQNUM=5985
SUBSYSTEM=usb
TYPE=0/0/0
USEC_INITIALIZED=183757852027

UDEV  [183758.396989] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0 (usb)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0
DEVTYPE=usb_interface
DRIVER=usbhid
ID_VENDOR_FROM_DATABASE=Microchip Technology, Inc.
INTERFACE=3/0/0
MODALIAS=usb:v04D8p00DEd0002dc00dsc00dp00ic03isc00ip00in00
PRODUCT=4d8/de/2
SEQNUM=5986
SUBSYSTEM=usb
TYPE=0/0/0
USEC_INITIALIZED=183758396448

UDEV  [183758.398096] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=add
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=5989
SUBSYSTEM=usbmisc
USEC_INITIALIZED=183758397905

UDEV  [183758.398728] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F (hid)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=5987
SUBSYSTEM=hid
USEC_INITIALIZED=183758398168

UDEV  [183758.399920] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0 (hidraw)
ACTION=add
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=5990
SUBSYSTEM=hidraw
USEC_INITIALIZED=183758399726

KERNEL[183758.400685] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=remove
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=5991
SUBSYSTEM=usbmisc

KERNEL[183758.400766] remove   /usbmisc (class)
ACTION=remove
DEVPATH=/usbmisc
SEQNUM=5992
SUBSYSTEM=class

KERNEL[183758.400956] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0 (hidraw)
ACTION=remove
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=5993
SUBSYSTEM=hidraw

KERNEL[183758.401068] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F (hid)
ACTION=remove
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=5994
SUBSYSTEM=hid

UDEV  [183758.403532] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=remove
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=5991
SUBSYSTEM=usbmisc
USEC_INITIALIZED=183758400806

UDEV  [183758.404020] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0 (hidraw)
ACTION=remove
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=5993
SUBSYSTEM=hidraw
USEC_INITIALIZED=183758402106

UDEV  [183758.404380] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F (hid)
ACTION=remove
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=5994
SUBSYSTEM=hid
USEC_INITIALIZED=183758402790

UDEV  [183758.405108] remove   /usbmisc (class)
ACTION=remove
DEVPATH=/usbmisc
SEQNUM=5992
SUBSYSTEM=class
USEC_INITIALIZED=183758401553
</code>```

In the container, the ID fields are missing:

```<code>    monitor will print the received events for:
UDEV - the event which udev sends out after rule processing
KERNEL - the kernel uevent

KERNEL[183877.777776] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1 (usb)
ACTION=add
BUSNUM=004
DEVNAME=/dev/bus/usb/004/035
DEVNUM=035
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1
DEVTYPE=usb_device
MAJOR=189
MINOR=418
PRODUCT=4d8/de/2
SEQNUM=5999
SUBSYSTEM=usb
TYPE=0/0/0

KERNEL[183877.778115] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0 (usb)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0
DEVTYPE=usb_interface
INTERFACE=3/0/0
MODALIAS=usb:v04D8p00DEd0002dc00dsc00dp00ic03isc00ip00in00
PRODUCT=4d8/de/2
SEQNUM=6000
SUBSYSTEM=usb
TYPE=0/0/0

KERNEL[183877.779627] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020 (hid)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=6001
SUBSYSTEM=hid

KERNEL[183877.780178] add      /class/usbmisc (class)
ACTION=add
DEVPATH=/class/usbmisc
SEQNUM=6002
SUBSYSTEM=class

KERNEL[183877.780314] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=add
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=6003
SUBSYSTEM=usbmisc

KERNEL[183877.780413] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020/hidraw/hidraw0 (hidraw)
ACTION=add
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=6004
SUBSYSTEM=hidraw

KERNEL[183878.337362] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=remove
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=6005
SUBSYSTEM=usbmisc

KERNEL[183878.337467] remove   /usbmisc (class)
ACTION=remove
DEVPATH=/usbmisc
SEQNUM=6006
SUBSYSTEM=class

KERNEL[183878.337521] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020/hidraw/hidraw0 (hidraw)
ACTION=remove
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=6007
SUBSYSTEM=hidraw

KERNEL[183878.337584] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020 (hid)
ACTION=remove
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=6008
SUBSYSTEM=hid
</code>```

答:
If you only care about getting information from the udev database, then you can mount the host's udev database into the docker container, e.g.,

```<code>-v /run/udev:/run/udev:ro
</code>```

By doing so, you won't need to run a udev daemon inside the docker container, but still get all the ID_ attributes when doing udevadm info. This worked for me for a Debian docker container running on a Debian host.

I also suggest mounting /dev as well so your docker container will know about any changes to the device files.

Body:
When I run docker container and list properties of some device with udevadm inside the container, there are only the basic information about the device. When I do the same thing on host, I can see much more. What can I do to get all the information inside the container?

host$ udevadm info --query=property /dev/bus/usb/004/008
BUSNUM=004
DEVNAME=/dev/bus/usb/004/008
DEVNUM=008
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1
DEVTYPE=usb_device
DRIVER=usb
ID_BUS=usb
ID_MODEL=MCP2210_USB-to-SPI_Master
ID_MODEL_ENC=MCP2210 USB-to-SPI Master
ID_MODEL_ID=00de
ID_REVISION=0002
ID_SERIAL=Microchip_Technology_Inc._MCP2210_USB-to-SPI_Master_0000267472
ID_SERIAL_SHORT=0000267472
ID_USB_INTERFACES=:030000:
ID_VENDOR=Microchip_Technology_Inc.
ID_VENDOR_ENC=Microchip Technology Inc.
ID_VENDOR_FROM_DATABASE=Microchip Technology, Inc.
ID_VENDOR_ID=04d8
MAJOR=189
MINOR=391
PRODUCT=4d8/de/2
SUBSYSTEM=usb
TYPE=0/0/0
USEC_INITIALIZED=176769529274

host$ docker run -ti -v /dev/bus/usb/:/dev/bus/usb alpine sh
container# apk update
container# apk add eudev
container# udevadm info --query=property /dev/bus/usb/004/008
BUSNUM=004
DEVNAME=/dev/bus/usb/004/008
DEVNUM=008
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1
DEVTYPE=usb_device
DRIVER=usb
MAJOR=189
MINOR=391
PRODUCT=4d8/de/2
SUBSYSTEM=usb
TYPE=0/0/0

I have also tried to mount other volumes from host: /sys, /dev. Did not help.

EDIT according to the Alex P.'s answer:

I'm not very experienced with udev. I have copied this

SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", IMPORT{builtin}="usb_id", IMPORT{builtin}="hwdb --subsystem=usb"

to /dev/udev/rules.d/10-local.rules, I have set udev logging to debug, reloaded config with udevadm control --reload. Now I get this:

calling: info
P: /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2
N: bus/usb/004/016
no db file to read /run/udev/data/c189:399: No such file or directory
E: BUSNUM=004
E: DEVNAME=/dev/bus/usb/004/016
E: DEVNUM=016
E: DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2
E: DEVTYPE=usb_device
E: DRIVER=usb
E: MAJOR=189
E: MINOR=399
E: PRODUCT=4d8/de/2
E: SUBSYSTEM=usb
E: TYPE=0/0/0

For now still no luck.
I tried to run the container with --privileged flag, did not help. I have no other rules in /etc/udev/rules.d. I tried to copy all rules from my host, no luck.

host$ udevadm monitor --environment
    monitor will print the received events for:
UDEV - the event which udev sends out after rule processing
KERNEL - the kernel uevent

KERNEL[183757.837879] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1 (usb)
ACTION=add
BUSNUM=004
DEVNAME=/dev/bus/usb/004/034
DEVNUM=034
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1
DEVTYPE=usb_device
MAJOR=189
MINOR=417
PRODUCT=4d8/de/2
SEQNUM=5985
SUBSYSTEM=usb
TYPE=0/0/0

KERNEL[183757.838467] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0 (usb)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0
DEVTYPE=usb_interface
INTERFACE=3/0/0
MODALIAS=usb:v04D8p00DEd0002dc00dsc00dp00ic03isc00ip00in00
PRODUCT=4d8/de/2
SEQNUM=5986
SUBSYSTEM=usb
TYPE=0/0/0

KERNEL[183757.840044] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F (hid)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=5987
SUBSYSTEM=hid

KERNEL[183757.840586] add      /class/usbmisc (class)
ACTION=add
DEVPATH=/class/usbmisc
SEQNUM=5988
SUBSYSTEM=class

KERNEL[183757.840891] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=add
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=5989
SUBSYSTEM=usbmisc

KERNEL[183757.841219] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0 (hidraw)
ACTION=add
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=5990
SUBSYSTEM=hidraw

UDEV  [183757.842324] add      /class/usbmisc (class)
ACTION=add
DEVPATH=/class/usbmisc
SEQNUM=5988
SUBSYSTEM=class
USEC_INITIALIZED=183757842069

UDEV  [183758.395467] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1 (usb)
ACTION=add
BUSNUM=004
DEVNAME=/dev/bus/usb/004/034
DEVNUM=034
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1
DEVTYPE=usb_device
DRIVER=usb
ID_BUS=usb
ID_MODEL=MCP2210_USB-to-SPI_Master
ID_MODEL_ENC=MCP2210\x20USB-to-SPI\x20Master
ID_MODEL_ID=00de
ID_REVISION=0002
ID_SERIAL=Microchip_Technology_Inc._MCP2210_USB-to-SPI_Master_0000267472
ID_SERIAL_SHORT=0000267472
ID_USB_INTERFACES=:030000:
ID_VENDOR=Microchip_Technology_Inc.
ID_VENDOR_ENC=Microchip\x20Technology\x20Inc.
ID_VENDOR_FROM_DATABASE=Microchip Technology, Inc.
ID_VENDOR_ID=04d8
MAJOR=189
MINOR=417
PRODUCT=4d8/de/2
SEQNUM=5985
SUBSYSTEM=usb
TYPE=0/0/0
USEC_INITIALIZED=183757852027

UDEV  [183758.396989] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0 (usb)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0
DEVTYPE=usb_interface
DRIVER=usbhid
ID_VENDOR_FROM_DATABASE=Microchip Technology, Inc.
INTERFACE=3/0/0
MODALIAS=usb:v04D8p00DEd0002dc00dsc00dp00ic03isc00ip00in00
PRODUCT=4d8/de/2
SEQNUM=5986
SUBSYSTEM=usb
TYPE=0/0/0
USEC_INITIALIZED=183758396448

UDEV  [183758.398096] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=add
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=5989
SUBSYSTEM=usbmisc
USEC_INITIALIZED=183758397905

UDEV  [183758.398728] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F (hid)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=5987
SUBSYSTEM=hid
USEC_INITIALIZED=183758398168

UDEV  [183758.399920] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0 (hidraw)
ACTION=add
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=5990
SUBSYSTEM=hidraw
USEC_INITIALIZED=183758399726

KERNEL[183758.400685] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=remove
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=5991
SUBSYSTEM=usbmisc

KERNEL[183758.400766] remove   /usbmisc (class)
ACTION=remove
DEVPATH=/usbmisc
SEQNUM=5992
SUBSYSTEM=class

KERNEL[183758.400956] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0 (hidraw)
ACTION=remove
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=5993
SUBSYSTEM=hidraw

KERNEL[183758.401068] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F (hid)
ACTION=remove
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=5994
SUBSYSTEM=hid

UDEV  [183758.403532] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=remove
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=5991
SUBSYSTEM=usbmisc
USEC_INITIALIZED=183758400806

UDEV  [183758.404020] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0 (hidraw)
ACTION=remove
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=5993
SUBSYSTEM=hidraw
USEC_INITIALIZED=183758402106

UDEV  [183758.404380] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F (hid)
ACTION=remove
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.001F
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=5994
SUBSYSTEM=hid
USEC_INITIALIZED=183758402790

UDEV  [183758.405108] remove   /usbmisc (class)
ACTION=remove
DEVPATH=/usbmisc
SEQNUM=5992
SUBSYSTEM=class
USEC_INITIALIZED=183758401553

In the container, the ID fields are missing:

    monitor will print the received events for:
UDEV - the event which udev sends out after rule processing
KERNEL - the kernel uevent

KERNEL[183877.777776] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1 (usb)
ACTION=add
BUSNUM=004
DEVNAME=/dev/bus/usb/004/035
DEVNUM=035
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1
DEVTYPE=usb_device
MAJOR=189
MINOR=418
PRODUCT=4d8/de/2
SEQNUM=5999
SUBSYSTEM=usb
TYPE=0/0/0

KERNEL[183877.778115] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0 (usb)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0
DEVTYPE=usb_interface
INTERFACE=3/0/0
MODALIAS=usb:v04D8p00DEd0002dc00dsc00dp00ic03isc00ip00in00
PRODUCT=4d8/de/2
SEQNUM=6000
SUBSYSTEM=usb
TYPE=0/0/0

KERNEL[183877.779627] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020 (hid)
ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=6001
SUBSYSTEM=hid

KERNEL[183877.780178] add      /class/usbmisc (class)
ACTION=add
DEVPATH=/class/usbmisc
SEQNUM=6002
SUBSYSTEM=class

KERNEL[183877.780314] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=add
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=6003
SUBSYSTEM=usbmisc

KERNEL[183877.780413] add      /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020/hidraw/hidraw0 (hidraw)
ACTION=add
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=6004
SUBSYSTEM=hidraw

KERNEL[183878.337362] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0 (usbmisc)
ACTION=remove
DEVNAME=/dev/usb/hiddev0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/usbmisc/hiddev0
MAJOR=180
MINOR=0
SEQNUM=6005
SUBSYSTEM=usbmisc

KERNEL[183878.337467] remove   /usbmisc (class)
ACTION=remove
DEVPATH=/usbmisc
SEQNUM=6006
SUBSYSTEM=class

KERNEL[183878.337521] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020/hidraw/hidraw0 (hidraw)
ACTION=remove
DEVNAME=/dev/hidraw0
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020/hidraw/hidraw0
MAJOR=244
MINOR=0
SEQNUM=6007
SUBSYSTEM=hidraw

KERNEL[183878.337584] remove   /devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020 (hid)
ACTION=remove
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.1/4-1.1:1.0/0003:04D8:00DE.0020
HID_ID=0003:000004D8:000000DE
HID_NAME=Microchip Technology Inc. MCP2210 USB-to-SPI Master
HID_PHYS=usb-0000:00:1d.0-1.1/input0
HID_UNIQ=0000267472
MODALIAS=hid:b0003g0001v000004D8p000000DE
SEQNUM=6008
SUBSYSTEM=hid

Body:
If you only care about getting information from the udev database, then you can mount the host's udev database into the docker container, e.g.,

-v /run/udev:/run/udev:ro

By doing so, you won't need to run a udev daemon inside the docker container, but still get all the ID_ attributes when doing udevadm info. This worked for me for a Debian docker container running on a Debian host.

I also suggest mounting /dev as well so your docker container will know about any changes to the device files.


问:
Convert a list of objects to an xml string
Hello I have a list of object i want to convert into an xml. Here is what the final xml should look like.

```<code><ArrayOfTweet>
    <Tweet>
        <Photos>
            <Photo>
                <PhotoHeight>FOO</PhotoHeight>
                <PhotoUri>a/random/ur/path</PhotoUri>
                <PhotoWidth>923</PhotoWidth>
                <SourcePhotoUri>a/random/path</SourcePhotoUri>
            </Photo>
        </Photos>
        <ProfileImage>a/random/path</ProfileImage>
        <ScreenName>FOO</ScreenName>
        <Text>some text</Text>
        <TweetId>1234</TweetId>
        <UserId>1234</UserId>
        <Username>BAR</Username>
    </Tweet>
    <Tweet>
        <Photos>
            <Photo>
                <PhotoHeight>FOO</PhotoHeight>
                <PhotoUri>a/random/ur/path</PhotoUri>
                <PhotoWidth>923</PhotoWidth>
                <SourcePhotoUri>a/random/path</SourcePhotoUri>
            </Photo>
        </Photos>
        <ProfileImage>a/random/path</ProfileImage>
        <ScreenName>FOO</ScreenName>
        <Text>some text</Text>
        <TweetId>1234</TweetId>
        <UserId>1234</UserId>
        <Username>BAR</Username>
    </Tweet>
</ArrayOfTweet>
</code>```

I have converted each of the objects in the list into an xml string like so

```<code>//TweetList is the list of tweet objects

List<string> xmlStringTweetList = new List<string>();
foreach (var tl in TweetList)
{
    xmlStringTweetList.Add(toXML(tl));
}

private string toXML(Tweet t)
{
    var stringwriter = new System.IO.StringWriter();
    var serializer = new XmlSerializer(t.GetType());
    serializer.Serialize(stringwriter, t);
    return stringwriter.ToString();
}
</code>```

I tried converting that list into the format above using

```<code>XElement xmlElements = new XElement("ArrayOfTweet", xmlStringTweetList.Select(i => new XElement("Tweet", i)));
</code>```

But there is the extra <Tweet></Tweet>  That i dont need. Is there a way of doing this?

答:
I made a fiddle here that illustrates a way to serialize your object all at once, instead of piecing strings together.

I suspect your extra <Tweet></Tweet> is because of a null or empty value in the list, because I am not experiencing it in my test above.

Body:
Hello I have a list of object i want to convert into an xml. Here is what the final xml should look like.

<ArrayOfTweet>
    <Tweet>
        <Photos>
            <Photo>
                <PhotoHeight>FOO</PhotoHeight>
                <PhotoUri>a/random/ur/path</PhotoUri>
                <PhotoWidth>923</PhotoWidth>
                <SourcePhotoUri>a/random/path</SourcePhotoUri>
            </Photo>
        </Photos>
        <ProfileImage>a/random/path</ProfileImage>
        <ScreenName>FOO</ScreenName>
        <Text>some text</Text>
        <TweetId>1234</TweetId>
        <UserId>1234</UserId>
        <Username>BAR</Username>
    </Tweet>
    <Tweet>
        <Photos>
            <Photo>
                <PhotoHeight>FOO</PhotoHeight>
                <PhotoUri>a/random/ur/path</PhotoUri>
                <PhotoWidth>923</PhotoWidth>
                <SourcePhotoUri>a/random/path</SourcePhotoUri>
            </Photo>
        </Photos>
        <ProfileImage>a/random/path</ProfileImage>
        <ScreenName>FOO</ScreenName>
        <Text>some text</Text>
        <TweetId>1234</TweetId>
        <UserId>1234</UserId>
        <Username>BAR</Username>
    </Tweet>
</ArrayOfTweet>

I have converted each of the objects in the list into an xml string like so

//TweetList is the list of tweet objects

List<string> xmlStringTweetList = new List<string>();
foreach (var tl in TweetList)
{
    xmlStringTweetList.Add(toXML(tl));
}

private string toXML(Tweet t)
{
    var stringwriter = new System.IO.StringWriter();
    var serializer = new XmlSerializer(t.GetType());
    serializer.Serialize(stringwriter, t);
    return stringwriter.ToString();
}

I tried converting that list into the format above using

XElement xmlElements = new XElement("ArrayOfTweet", xmlStringTweetList.Select(i => new XElement("Tweet", i)));

But there is the extra <Tweet></Tweet>  That i dont need. Is there a way of doing this?


问:
PyCharm is not responding on Ctrl key shortcuts
```<code>Environment: XUbuntu 13.04, Java: Oracle 7 u40
PyCharm 3.0 Community Edition
</code>```

Any shortcut which involves Ctrl key is not working.
For example, I can Copy-Paste text using mouse or middle-button, but not via Ctrl+C/Ctrl+V.
When I hover mouse in menu, I can see shortcut tooltip and Settings confirm that shortcut is correct. But it is not working.

Shortcuts with Alt, like Alt+F7 work normally.

Other apps, for example, Aptana studio - which is Java and Eclipse-based works normally. All system applications work with Ctrl button OK.

答: I entered to File-Settings-Keymap and then I changed keymap version from existing to VisualStudio and it started to work correctly.</p>

Body:
Environment: XUbuntu 13.04, Java: Oracle 7 u40
PyCharm 3.0 Community Edition

Any shortcut which involves Ctrl key is not working.
For example, I can Copy-Paste text using mouse or middle-button, but not via Ctrl+C/Ctrl+V.
When I hover mouse in menu, I can see shortcut tooltip and Settings confirm that shortcut is correct. But it is not working.

Shortcuts with Alt, like Alt+F7 work normally.

Other apps, for example, Aptana studio - which is Java and Eclipse-based works normally. All system applications work with Ctrl button OK.


问:
Returning a image with ServletContext
I am trying to return a image with ServletContext but I get a 500 error and the console says:

java.lang.NullPointerException: null
        at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2146)
        at org.apache.commons.io.IOUtils.copy(IOUtils.java:2102)
        at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2123)
        at org.apache.commons.io.IOUtils.copy(IOUtils.java:2078)
        at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:721)

Configuration:

```<code>@Configuration
public class ImageConfiguration {

    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(byteArrayHttpMessageConverter());
    }

    @Bean
    public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
        ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
        arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
        return arrayHttpMessageConverter;
    }

    private List<MediaType> getSupportedMediaTypes() {
        List<MediaType> list = new ArrayList<MediaType>();
        list.add(MediaType.IMAGE_JPEG);
        list.add(MediaType.IMAGE_PNG);
        list.add(MediaType.APPLICATION_OCTET_STREAM);
        return list;
    }
}
</code>```

Service:

```<code>@Service
public class ImageService {

    @Autowired
    ServletContext servletContext;

    public byte[] getRankImage (String id) throws IOException {

        byte[] b;

            InputStream in;

        if (id.equals("0")) {
            in = servletContext.getResourceAsStream("images/level-0.png");
            return IOUtils.toByteArray(in);
</code>```

restful service:

```<code>@RequestMapping(value = "/level/{id}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> getImage(@PathVariable("id") String id) {
        byte[] imageBytes;

        try {
            imageBytes = imageService.getRankImage(id);
            return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
</code>```

The images are located in resources -> images -> {image_name} when I look in the war file I confirm that they are in there. I am not sure if I am doing this wrong or I need to handle the path differently.

---------Update 1-------

I took the war file and deployed it manually in apache and this is the output:

答:
In ImageService class, you autowired ServletContext instance.

Spring container will not autowire servletContext as it is not a spring bean. ServletContext is from javax.servlet package.

You can inject the instance using setter method as shown below.

```<code>@Service
public class ImageService implements ServletContextAware{

     private ServletContext context;

     public void setServletContext(ServletContext servletContext) {
        this.context = servletContext;
     }

     // use `context` object to get the image and pass to IOUtils.toByteArray method
}
</code>```

By implementing ServletContextAware interface, Spring will inject it for you.

Ideally, we shouldn't be injecting ServletContext instance outside the Controller layer. Here, we are injecting in Service layer which isn't the recommended approach.

Hope this helps!

Title: Returning a image with ServletContext

Body:
I am trying to return a image with ServletContext but I get a 500 error and the console says:

java.lang.NullPointerException: null
        at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2146)
        at org.apache.commons.io.IOUtils.copy(IOUtils.java:2102)
        at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2123)
        at org.apache.commons.io.IOUtils.copy(IOUtils.java:2078)
        at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:721)

Configuration:

@Configuration
public class ImageConfiguration {

    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(byteArrayHttpMessageConverter());
    }

    @Bean
    public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
        ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
        arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
        return arrayHttpMessageConverter;
    }

    private List<MediaType> getSupportedMediaTypes() {
        List<MediaType> list = new ArrayList<MediaType>();
        list.add(MediaType.IMAGE_JPEG);
        list.add(MediaType.IMAGE_PNG);
        list.add(MediaType.APPLICATION_OCTET_STREAM);
        return list;
    }
}

Service:

@Service
public class ImageService {

    @Autowired
    ServletContext servletContext;

    public byte[] getRankImage (String id) throws IOException {

        byte[] b;

            InputStream in;

        if (id.equals("0")) {
            in = servletContext.getResourceAsStream("images/level-0.png");
            return IOUtils.toByteArray(in);

restful service:

@RequestMapping(value = "/level/{id}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> getImage(@PathVariable("id") String id) {
        byte[] imageBytes;

        try {
            imageBytes = imageService.getRankImage(id);
            return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

The images are located in resources -> images -> {image_name} when I look in the war file I confirm that they are in there. I am not sure if I am doing this wrong or I need to handle the path differently.

---------Update 1-------

I took the war file and deployed it manually in apache and this is the output:

Body:
In ImageService class, you autowired ServletContext instance.

Spring container will not autowire servletContext as it is not a spring bean. ServletContext is from javax.servlet package.

You can inject the instance using setter method as shown below.

@Service
public class ImageService implements ServletContextAware{

     private ServletContext context;

     public void setServletContext(ServletContext servletContext) {
        this.context = servletContext;
     }

     // use `context` object to get the image and pass to IOUtils.toByteArray method
}

By implementing ServletContextAware interface, Spring will inject it for you.

Ideally, we shouldn't be injecting ServletContext instance outside the Controller layer. Here, we are injecting in Service layer which isn't the recommended approach.

Hope this helps!


问:
How could I replace a form with text when form is submitted?
I want my form to disappear when someone submits it (and it passes all of the error checking)
and text replaces where it was and says something like "Thank you a confirmation email has been sent"

What are some ways I would be able to do this?

I have the form working and the error checks and everything working, all I would need to do is make it disappear when the user clicks submit..

I am using php, Thanks!

答:
I did NOT test the form on http://www.sligroup.ca/contact_us.php because i do not want to sendthem a pointless message.

All you have to do wrap up the part of you script that outputs the forms html source in an pif block an check if the orm was already submitted correctly. No javascript needed.

Simple example:

```<code>$validFormSubmitted = validateform();
...
if(!$validFormSubmitted){
echo $formText;
}
</code>```

[EDIT: this will reload the page without the form. You said you want a PHP solution but if you do not want to reload the page you will have to use AJAX]

Body:
I did NOT test the form on http://www.sligroup.ca/contact_us.php because i do not want to sendthem a pointless message.

All you have to do wrap up the part of you script that outputs the forms html source in an pif block an check if the orm was already submitted correctly. No javascript needed.

Simple example:

$validFormSubmitted = validateform();
...
if(!$validFormSubmitted){
echo $formText;
}

[EDIT: this will reload the page without the form. You said you want a PHP solution but if you do not want to reload the page you will have to use AJAX]