问:
Optimised search using Ajax and keypress
I have the following code that I want to use to search a database as a user is typing into a textbox. The code below works fine but it seems a little inefficient, as if a user is typing really fast. I am potentially doing many more searches than necessary. So if a user is typing in "sailing", I am searching on "sail", "saili", "sailin", and "sailing".

I wanted to see if there was a way to detect any particular time between keypresses so only search if user stops typing for 500 milliseconds or something like this.

Is there a best practice for something like this?

```<code>$('#searchString').keypress(function(e) {

    if (e.keyCode == 13) {

        var url = '/Tracker/Search/' + $("#searchString").val();
        $.get(url, function(data) {
            $('div#results').html(data);
            $('#results').show();
        });
    }
    else {

        var existingString = $("#searchString").val();
        if (existingString.length > 2) {
            var url = '/Tracker/Search/' + existingString;
            $.get(url, function(data) {
                $('div#results').html(data);
                $('#results').show();
            });
        }
    }
</code>```

答:
I just want to add some more points to the question.
Throttling and debounce concepts are related to this topics.

Throttling :
It will make you to execute the function in a specified interval.

Debounce :
It will make you to execute the function when user has stopped typing.

You can achieve this two by setimeout , cleartimeout functions.Check this link will give you a clear walk-through of it.

LINK

Body:
I have the following code that I want to use to search a database as a user is typing into a textbox. The code below works fine but it seems a little inefficient, as if a user is typing really fast. I am potentially doing many more searches than necessary. So if a user is typing in "sailing", I am searching on "sail", "saili", "sailin", and "sailing".

I wanted to see if there was a way to detect any particular time between keypresses so only search if user stops typing for 500 milliseconds or something like this.

Is there a best practice for something like this?

$('#searchString').keypress(function(e) {

    if (e.keyCode == 13) {

        var url = '/Tracker/Search/' + $("#searchString").val();
        $.get(url, function(data) {
            $('div#results').html(data);
            $('#results').show();
        });
    }
    else {

        var existingString = $("#searchString").val();
        if (existingString.length > 2) {
            var url = '/Tracker/Search/' + existingString;
            $.get(url, function(data) {
                $('div#results').html(data);
                $('#results').show();
            });
        }
    }


来源: stackexchange

问:
GOJS, how do you bind data to the group property?
I have a GOJS application up and running and i'm trying to bind a parameter in my data to the group property.

If I manually set the group property in the data then it works exactly as I would expect and the nodes appear as part of the group, but if the group is set using binding then no group connection seems to be made.

What am I missing?

example showing the group being set within the data

```<code>var nodes = []
var nodeObj ={
    key:"groupObject",
    text:"group",
    isGroup:true
  }
  nodes.push(nodeObj)

  nodeObj = {
    key:"node1",
    text:"node1",
    group:"groupObject"
  }
  nodes.push(nodeObj)

  nodeObj = {
    key:"node2",
    text:"node2",
    group:"groupObject"
  }
  nodes.push(nodeObj)
}

const initDiagram = () => {
    const $ = go.GraphObject.make;
    const diagram =
      $(go.Diagram,
        {
          'undoManager.isEnabled': true,
          'clickCreatingTool.archetypeNodeData': { text: 'new node', color: 'lightblue' },
          model: $(go.GraphLinksModel,
            {
              linkKeyProperty: 'key'
            })
      });

    diagram.nodeTemplate =
        $(go.Node, 'Auto',
            $(go.Shape, 'RoundedRectangle',
            { name: 'SHAPE', fill: 'white', strokeWidth: 0 },
            new go.Binding('fill', 'color')),
            $(go.TextBlock,
            { margin: 8, editable: true, stroke:"black" },
            new go.Binding('text').makeTwoWay()
            )
        );

    diagram.groupTemplate =
      $(go.Group, "Vertical", $(go.GridLayout,{wrappingColumn:1}),
        $(go.TextBlock,         // group title
          { alignment: go.Spot.Center, font: "Bold 15pt Sans-Serif" },
          new go.Binding("text")),
        $(go.Panel, "Auto",
          $(go.Shape, "RoundedRectangle",  // surrounds the Placeholder
            {fill: "lightblue" }),
          $(go.Placeholder,
            { padding: 5}),
        )
    );
    return diagram;
  }
</code>```

This works ^^^

Now if I set the group parameter in the data to "groupName" instead of group, then bind group to groupName in the init function, the nodes no longer appear as part of the group

```<code>var nodes = []
var nodeObj ={
    key:"groupObject",
    text:"group",
    isGroup:true
  }
  nodes.push(nodeObj)

  nodeObj = {
    key:"node1",
    text:"node1",
    groupName:"groupObject"      //this line has changed
  }
  nodes.push(nodeObj)

  nodeObj = {
    key:"node2",
    text:"node2",
    groupName:"groupObject"      //This line has changed
  }
  nodes.push(nodeObj)
}

const initDiagram = () => {
    const $ = go.GraphObject.make;
    const diagram =
      $(go.Diagram,
        {
          'undoManager.isEnabled': true,
          'clickCreatingTool.archetypeNodeData': { text: 'new node', color: 'lightblue' },
          model: $(go.GraphLinksModel,
            {
              linkKeyProperty: 'key'
            })
      });

    diagram.nodeTemplate =
        $(go.Node, 'Auto',
            new go.Binding('group','groupName'),      //this line has changed
            $(go.Shape, 'RoundedRectangle',
            { name: 'SHAPE', fill: 'white', strokeWidth: 0 },
            new go.Binding('fill', 'color')),
            $(go.TextBlock,
            { margin: 8, editable: true, stroke:"black" },
            new go.Binding('text').makeTwoWay()
            )
        );

    diagram.groupTemplate =
      $(go.Group, "Vertical", $(go.GridLayout,{wrappingColumn:1}),
        $(go.TextBlock,         // group title
          { alignment: go.Spot.Center, font: "Bold 15pt Sans-Serif" },
          new go.Binding("text")),
        $(go.Panel, "Auto",
          $(go.Shape, "RoundedRectangle",
            {fill: "lightblue" }),
          $(go.Placeholder,
            { padding: 5}),
        )
    );
    return diagram;
  }
</code>```

答:
Bindings are used to keep the properties of the GraphObjects of one Part up-to-date with properties on that Part's model data.  Bindings are not used for maintaining relationships between Parts.  Only models know how to interpret and maintain relationships.

If you want to use the data property "groupName" instead of "group" to refer to the node's containing group, set GraphLinksModel.nodeGroupKeyProperty to "groupName".  Preferably before you set Model.nodeDataArray.

Also, please read https://gojs.net/latest/intro/dataBinding.html#ChangingGraphStructure.

ContentLicense: CC BY-SA 4.0

Body:
I have a GOJS application up and running and i'm trying to bind a parameter in my data to the group property.

If I manually set the group property in the data then it works exactly as I would expect and the nodes appear as part of the group, but if the group is set using binding then no group connection seems to be made.

What am I missing?

example showing the group being set within the data

var nodes = []
var nodeObj ={
    key:"groupObject",
    text:"group",
    isGroup:true
  }
  nodes.push(nodeObj)

  nodeObj = {
    key:"node1",
    text:"node1",
    group:"groupObject"
  }
  nodes.push(nodeObj)

  nodeObj = {
    key:"node2",
    text:"node2",
    group:"groupObject"
  }
  nodes.push(nodeObj)
}

const initDiagram = () => {
    const $ = go.GraphObject.make;
    const diagram =
      $(go.Diagram,
        {
          'undoManager.isEnabled': true,
          'clickCreatingTool.archetypeNodeData': { text: 'new node', color: 'lightblue' },
          model: $(go.GraphLinksModel,
            {
              linkKeyProperty: 'key'
            })
      });

    diagram.nodeTemplate =
        $(go.Node, 'Auto',
            $(go.Shape, 'RoundedRectangle',
            { name: 'SHAPE', fill: 'white', strokeWidth: 0 },
            new go.Binding('fill', 'color')),
            $(go.TextBlock,
            { margin: 8, editable: true, stroke:"black" },
            new go.Binding('text').makeTwoWay()
            )
        );

    diagram.groupTemplate =
      $(go.Group, "Vertical", $(go.GridLayout,{wrappingColumn:1}),
        $(go.TextBlock,         // group title
          { alignment: go.Spot.Center, font: "Bold 15pt Sans-Serif" },
          new go.Binding("text")),
        $(go.Panel, "Auto",
          $(go.Shape, "RoundedRectangle",  // surrounds the Placeholder
            {fill: "lightblue" }),
          $(go.Placeholder,
            { padding: 5}),
        )
    );
    return diagram;
  }

This works ^^^

Now if I set the group parameter in the data to "groupName" instead of group, then bind group to groupName in the init function, the nodes no longer appear as part of the group

var nodes = []
var nodeObj ={
    key:"groupObject",
    text:"group",
    isGroup:true
  }
  nodes.push(nodeObj)

  nodeObj = {
    key:"node1",
    text:"node1",
    groupName:"groupObject"      //this line has changed
  }
  nodes.push(nodeObj)

  nodeObj = {
    key:"node2",
    text:"node2",
    groupName:"groupObject"      //This line has changed
  }
  nodes.push(nodeObj)
}

const initDiagram = () => {
    const $ = go.GraphObject.make;
    const diagram =
      $(go.Diagram,
        {
          'undoManager.isEnabled': true,
          'clickCreatingTool.archetypeNodeData': { text: 'new node', color: 'lightblue' },
          model: $(go.GraphLinksModel,
            {
              linkKeyProperty: 'key'
            })
      });

    diagram.nodeTemplate =
        $(go.Node, 'Auto',
            new go.Binding('group','groupName'),      //this line has changed
            $(go.Shape, 'RoundedRectangle',
            { name: 'SHAPE', fill: 'white', strokeWidth: 0 },
            new go.Binding('fill', 'color')),
            $(go.TextBlock,
            { margin: 8, editable: true, stroke:"black" },
            new go.Binding('text').makeTwoWay()
            )
        );

    diagram.groupTemplate =
      $(go.Group, "Vertical", $(go.GridLayout,{wrappingColumn:1}),
        $(go.TextBlock,         // group title
          { alignment: go.Spot.Center, font: "Bold 15pt Sans-Serif" },
          new go.Binding("text")),
        $(go.Panel, "Auto",
          $(go.Shape, "RoundedRectangle",
            {fill: "lightblue" }),
          $(go.Placeholder,
            { padding: 5}),
        )
    );
    return diagram;
  }


问:
Getting generic class from Kotlin Generic
I have the following class signature:

```<code>abstract class BaseActivity<E : ViewModel> : AppCompatActivity() {

    protected lateinit var viewModel: E

}
</code>```

Now I want to initialize my viewModel in a generic way using ViewModelProvider, so:

```<code>   viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(MyViewModel::class)
</code>```

Given that MyViewModel class will be provided in the generic type, I'd say this could potentially be abstracted into the BaseActivity so I dont have to do it for every Activity that extends it.

I tried with:

```<code>inline fun <reified E : ViewModel> getViewModelClass() = E::class.java
</code>```

But then when doing:

```<code>viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(getViewModelClass())
</code>```

I get Cannot use E as reified type paramter. Use class instead

Is there a solution to this?

答:
https://stackoverflow.com/a/52107111/8832537

You should check this guy's solution. The only downside of his approach is he uses Reflection API to get the generic parameter. I researched a lot but didn't find a solution that doesn't use reflection. If you did find it, let me know. That would be more convenient.

Body:
I have the following class signature:

abstract class BaseActivity<E : ViewModel> : AppCompatActivity() {

    protected lateinit var viewModel: E

}

Now I want to initialize my viewModel in a generic way using ViewModelProvider, so:

   viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(MyViewModel::class)

Given that MyViewModel class will be provided in the generic type, I'd say this could potentially be abstracted into the BaseActivity so I dont have to do it for every Activity that extends it.

I tried with:

inline fun <reified E : ViewModel> getViewModelClass() = E::class.java

But then when doing:

viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(getViewModelClass())

I get Cannot use E as reified type paramter. Use class instead

Is there a solution to this?


问:
How to make a hover effect stay after unhovering the image?
I made a JS Fiddle https://jsfiddle.net/t3zaskum/ to show it better, I am trying to use jscript to make the items go up a bit when hovered but it just aint working.

Javascript:

```<code>$('.cover-img').mouseover(function() {
    if ($(this).hasClass('active')) return;
    $('.active').removeClass('active');
    $(this).addClass('active');
});
</code>```

CSS:

```<code>.top-section-hover {
    display: flex;
    padding-top: 10em;
    justify-content: center;
    flex-grow: 2;
    text-align: center;
    text-transform: uppercase;
    font-weight: bold;
    max-width: 96%;
}

.top-section-hover img {
    position: relative;
    top: 0;
    transition: top ease 0.5s;
    left: 0;
}

.active {
    top: -30px;
    transition: all 0.5s ease
}

.cover-title {
    font-weight: bold;
}

.hover-cover-middle:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}

.hover-cover-left:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}

.hover-cover-right:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}
</code>```

Thanks in advance

答:
HTML is fine, JS is fine, only thing is:

.top-section-hover img - is more specific than .active. So we always see a styles of .top-section-hover img.

changing .active to .top-section-hover img.active making that block more specific, so it's rules is applied

$('.cover-img').mouseover(function() {
    if ($(this).hasClass('active')) return;
    $('.active').removeClass('active');
    $(this).addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.top-section-hover {
    display: flex;
    padding-top: 10em;
    justify-content: center;
    flex-grow: 2;
    text-align: center;
    text-transform: uppercase;
    font-weight: bold;
    max-width: 96%;
}

.top-section-hover img {
    position: relative;
    top: 0;
    transition: top ease 0.5s;
    left: 0;
}

.top-section-hover img.active {
    top: -30px;
    transition: all 0.5s ease
}

.cover-title {
    font-weight: bold;
}

.hover-cover-middle:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}

.hover-cover-left:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}

.hover-cover-right:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}</code>```

                    Office

                    Home

                    Events

```

Body:
I made a JS Fiddle https://jsfiddle.net/t3zaskum/ to show it better, I am trying to use jscript to make the items go up a bit when hovered but it just aint working.

Javascript:

$('.cover-img').mouseover(function() {
    if ($(this).hasClass('active')) return;
    $('.active').removeClass('active');
    $(this).addClass('active');
});

CSS:

.top-section-hover {
    display: flex;
    padding-top: 10em;
    justify-content: center;
    flex-grow: 2;
    text-align: center;
    text-transform: uppercase;
    font-weight: bold;
    max-width: 96%;
}

.top-section-hover img {
    position: relative;
    top: 0;
    transition: top ease 0.5s;
    left: 0;
}

.active {
    top: -30px;
    transition: all 0.5s ease
}

.cover-title {
    font-weight: bold;
}

.hover-cover-middle:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}

.hover-cover-left:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}

.hover-cover-right:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}

Thanks in advance

Body:
HTML is fine, JS is fine, only thing is:

.top-section-hover img - is more specific than .active. So we always see a styles of .top-section-hover img.

changing .active to .top-section-hover img.active making that block more specific, so it's rules is applied

$('.cover-img').mouseover(function() {
    if ($(this).hasClass('active')) return;
    $('.active').removeClass('active');
    $(this).addClass('active');
});

.top-section-hover {
    display: flex;
    padding-top: 10em;
    justify-content: center;
    flex-grow: 2;
    text-align: center;
    text-transform: uppercase;
    font-weight: bold;
    max-width: 96%;
}

.top-section-hover img {
    position: relative;
    top: 0;
    transition: top ease 0.5s;
    left: 0;
}

.top-section-hover img.active {
    top: -30px;
    transition: all 0.5s ease
}

.cover-title {
    font-weight: bold;
}

.hover-cover-middle:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}

.hover-cover-left:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}

.hover-cover-right:hover .cover-title {
    color: white;
    border-bottom: 3px solid white;
    transition: 0.5s all;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="top-section-hover">
            <span class="hover-cover-left">
                <a href="#" class="cover-left-content">
                    <img src="https://via.placeholder.com/150

C/O https://placeholder.com/" alt="" class="cover-img">
                    <span class="cover-title">Office</span>
                </a>
            </span>

            <span class="hover-cover-middle">
                <a href="#" class="cover-left-content">
                    <img src="https://via.placeholder.com/150

C/O https://placeholder.com/" alt="" class="cover-img">
                    <span class="cover-title">Home</span>
                </a>
            </span>

            <span class="hover-cover-right">
                <a href="#" class="cover-left-content">
                    <img src="https://via.placeholder.com/150

C/O https://placeholder.com/" alt="" class="cover-img">
                    <span class="cover-title">Events</span>
                </a>
            </span>
</div>


问:
Python loop through tuple list adding a value from pandas data frame
I am trying to loop through a list of tuples adding a value to the end of each one that corresponds to a value in a column in a pandas data frame.

```<code>df1 = [(1,2),(4,5),(8,9)]

df2 = pd.DataFrame({'Alpha': [2, 4, 8],
                    'Beta': ["a","b","c"]})

df3 = []

for i in df1:
    print(i)

for i,j in df2["Beta"], df1:
    j = j + (i,)
    df3.append(j)

print(df3)
</code>```

I would expect print(df3) to display the following:

```<code>[(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]
</code>```

However, I get an error stating too many values to unpack.

答:
One way using a list comprehension would be:

```<code>[(*i, j) for i, j in zip(df1,  df2.Beta)]
# [(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]
</code>```

Or you could also map with operator.add:

```<code>from operator import add
list(map(add, df1, df2.Beta.map(tuple)))
# [(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]
</code>```

Or working from pandas:

```<code>(pd.Series(df1) + df2.Beta.map(tuple)).values.tolist()
# [(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]
</code>```

Body:
I am trying to loop through a list of tuples adding a value to the end of each one that corresponds to a value in a column in a pandas data frame.

df1 = [(1,2),(4,5),(8,9)]

df2 = pd.DataFrame({'Alpha': [2, 4, 8],
                    'Beta': ["a","b","c"]})

df3 = []

for i in df1:
    print(i)

for i,j in df2["Beta"], df1:
    j = j + (i,)
    df3.append(j)

print(df3)

I would expect print(df3) to display the following:

[(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]

However, I get an error stating too many values to unpack.

Body:
One way using a list comprehension would be:

[(*i, j) for i, j in zip(df1,  df2.Beta)]
# [(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]

Or you could also map with operator.add:

from operator import add
list(map(add, df1, df2.Beta.map(tuple)))
# [(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]

Or working from pandas:

(pd.Series(df1) + df2.Beta.map(tuple)).values.tolist()
# [(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]


问:
Supported file types in Azure File Storage
I am wondering if there is a list of supported file types for uploading to Azure File Storage.

Particularly, what would happen if someone attempted to upload a malicious file (say, an executable) to the File Storage. Would Azure allow it, and if it did, what would happen with the .exe?

I haven't found any documentation on this.

答:
I am wondering if there is a list of supported file types for
  uploading to Azure File Storage.

As such, all kinds of files are supported by Azure File Storage. There's no restriction on the kind of files that can be uploaded/not uploaded there.

There's a threat detection service from Microsoft but is only available for Blob Storage at the time of writing this answer. You can read more about it here: https://learn.microsoft.com/en-us/azure/storage/common/storage-advanced-threat-protection?tabs=azure-portal


问:
Export bitfield to an array
I've declared this bit field. What I am trying to do is to get the whole value of the bitfield in binary and convert it into an array so I can use the index and address every '1' value.

```<code>union{
    struct shape{
        uint8_t p0 : 1;
        uint8_t p1 : 1;
        uint8_t p2 : 1;
        uint8_t p3 : 1;
        uint8_t p4 : 1;
        uint8_t p5 : 1;
        uint8_t p6 : 1;
        uint8_t p7 : 1;
    };
    uint8_t row;
}rows[8*2+4];
</code>```

what I am trying to do is to export the bitfield to have it an array like uint8_t tab[8] = {0,1,1,0,0,1,0,1};

Is that even possible? Any tips?
Thanks in advance

Title: Export bitfield to an array

Body:
I've declared this bit field. What I am trying to do is to get the whole value of the bitfield in binary and convert it into an array so I can use the index and address every '1' value.

union{
    struct shape{
        uint8_t p0 : 1;
        uint8_t p1 : 1;
        uint8_t p2 : 1;
        uint8_t p3 : 1;
        uint8_t p4 : 1;
        uint8_t p5 : 1;
        uint8_t p6 : 1;
        uint8_t p7 : 1;
    };
    uint8_t row;
}rows[8*2+4];

what I am trying to do is to export the bitfield to have it an array like uint8_t tab[8] = {0,1,1,0,0,1,0,1};

Is that even possible? Any tips?
Thanks in advance

Body:
rows[8] = (union row){.p0 = 0,.p1 = 1,.p2 = 1,.p3 = 0,.p4 = 0,.p5= 1,.p6 = 0,.p7 = 1};

or

rows[8].row = {b01100101}; if you define all the bin balues yourself like below or not portable rows[8].row = {0b01100101};

#ifndef __BIN_8BITS__
#define __BIN_8BITS__

#define b00000000 0x0000
#define b00000001 0x0001
#define b00000010 0x0002
#define b00000011 0x0003
#define b00000100 0x0004
#define b00000101 0x0005
#define b00000110 0x0006
#define b00000111 0x0007
#define b00001000 0x0008
#define b00001001 0x0009
#define b00001010 0x000A
#define b00001011 0x000B
#define b00001100 0x000C
#define b00001101 0x000D
#define b00001110 0x000E
#define b00001111 0x000F
#define b00010000 0x0010
#define b00010001 0x0011
#define b00010010 0x0012
#define b00010011 0x0013
#define b00010100 0x0014
#define b00010101 0x0015
#define b00010110 0x0016
#define b00010111 0x0017
#define b00011000 0x0018
#define b00011001 0x0019
#define b00011010 0x001A
#define b00011011 0x001B
#define b00011100 0x001C
#define b00011101 0x001D
#define b00011110 0x001E
#define b00011111 0x001F
#define b00100000 0x0020
#define b00100001 0x0021
#define b00100010 0x0022
#define b00100011 0x0023
#define b00100100 0x0024
#define b00100101 0x0025
#define b00100110 0x0026
#define b00100111 0x0027
#define b00101000 0x0028
#define b00101001 0x0029
#define b00101010 0x002A
#define b00101011 0x002B
#define b00101100 0x002C
#define b00101101 0x002D
#define b00101110 0x002E
#define b00101111 0x002F
#define b00110000 0x0030
#define b00110001 0x0031
#define b00110010 0x0032
#define b00110011 0x0033
#define b00110100 0x0034
#define b00110101 0x0035
#define b00110110 0x0036
#define b00110111 0x0037
#define b00111000 0x0038
#define b00111001 0x0039
#define b00111010 0x003A
#define b00111011 0x003B
#define b00111100 0x003C
#define b00111101 0x003D
#define b00111110 0x003E
#define b00111111 0x003F
#define b01000000 0x0040
#define b01000001 0x0041
#define b01000010 0x0042
#define b01000011 0x0043
#define b01000100 0x0044
#define b01000101 0x0045
#define b01000110 0x0046
#define b01000111 0x0047
#define b01001000 0x0048
#define b01001001 0x0049
#define b01001010 0x004A
#define b01001011 0x004B
#define b01001100 0x004C
#define b01001101 0x004D
#define b01001110 0x004E
#define b01001111 0x004F
#define b01010000 0x0050
#define b01010001 0x0051
#define b01010010 0x0052
#define b01010011 0x0053
#define b01010100 0x0054
#define b01010101 0x0055
#define b01010110 0x0056
#define b01010111 0x0057
#define b01011000 0x0058
#define b01011001 0x0059
#define b01011010 0x005A
#define b01011011 0x005B
#define b01011100 0x005C
#define b01011101 0x005D
#define b01011110 0x005E
#define b01011111 0x005F
#define b01100000 0x0060
#define b01100001 0x0061
#define b01100010 0x0062
#define b01100011 0x0063
#define b01100100 0x0064
#define b01100101 0x0065
#define b01100110 0x0066
#define b01100111 0x0067
#define b01101000 0x0068
#define b01101001 0x0069
#define b01101010 0x006A
#define b01101011 0x006B
#define b01101100 0x006C
#define b01101101 0x006D
#define b01101110 0x006E
#define b01101111 0x006F
#define b01110000 0x0070
#define b01110001 0x0071
#define b01110010 0x0072
#define b01110011 0x0073
#define b01110100 0x0074
#define b01110101 0x0075
#define b01110110 0x0076
#define b01110111 0x0077
#define b01111000 0x0078
#define b01111001 0x0079
#define b01111010 0x007A
#define b01111011 0x007B
#define b01111100 0x007C
#define b01111101 0x007D
#define b01111110 0x007E
#define b01111111 0x007F
#define b10000000 0x0080
#define b10000001 0x0081
#define b10000010 0x0082
#define b10000011 0x0083
#define b10000100 0x0084
#define b10000101 0x0085
#define b10000110 0x0086
#define b10000111 0x0087
#define b10001000 0x0088
#define b10001001 0x0089
#define b10001010 0x008A
#define b10001011 0x008B
#define b10001100 0x008C
#define b10001101 0x008D
#define b10001110 0x008E
#define b10001111 0x008F
#define b10010000 0x0090
#define b10010001 0x0091
#define b10010010 0x0092
#define b10010011 0x0093
#define b10010100 0x0094
#define b10010101 0x0095
#define b10010110 0x0096
#define b10010111 0x0097
#define b10011000 0x0098
#define b10011001 0x0099
#define b10011010 0x009A
#define b10011011 0x009B
#define b10011100 0x009C
#define b10011101 0x009D
#define b10011110 0x009E
#define b10011111 0x009F
#define b10100000 0x00A0
#define b10100001 0x00A1
#define b10100010 0x00A2
#define b10100011 0x00A3
#define b10100100 0x00A4
#define b10100101 0x00A5
#define b10100110 0x00A6
#define b10100111 0x00A7
#define b10101000 0x00A8
#define b10101001 0x00A9
#define b10101010 0x00AA
#define b10101011 0x00AB
#define b10101100 0x00AC
#define b10101101 0x00AD
#define b10101110 0x00AE
#define b10101111 0x00AF
#define b10110000 0x00B0
#define b10110001 0x00B1
#define b10110010 0x00B2
#define b10110011 0x00B3
#define b10110100 0x00B4
#define b10110101 0x00B5
#define b10110110 0x00B6
#define b10110111 0x00B7
#define b10111000 0x00B8
#define b10111001 0x00B9
#define b10111010 0x00BA
#define b10111011 0x00BB
#define b10111100 0x00BC
#define b10111101 0x00BD
#define b10111110 0x00BE
#define b10111111 0x00BF
#define b11000000 0x00C0
#define b11000001 0x00C1
#define b11000010 0x00C2
#define b11000011 0x00C3
#define b11000100 0x00C4
#define b11000101 0x00C5
#define b11000110 0x00C6
#define b11000111 0x00C7
#define b11001000 0x00C8
#define b11001001 0x00C9
#define b11001010 0x00CA
#define b11001011 0x00CB
#define b11001100 0x00CC
#define b11001101 0x00CD
#define b11001110 0x00CE
#define b11001111 0x00CF
#define b11010000 0x00D0
#define b11010001 0x00D1
#define b11010010 0x00D2
#define b11010011 0x00D3
#define b11010100 0x00D4
#define b11010101 0x00D5
#define b11010110 0x00D6
#define b11010111 0x00D7
#define b11011000 0x00D8
#define b11011001 0x00D9
#define b11011010 0x00DA
#define b11011011 0x00DB
#define b11011100 0x00DC
#define b11011101 0x00DD
#define b11011110 0x00DE
#define b11011111 0x00DF
#define b11100000 0x00E0
#define b11100001 0x00E1
#define b11100010 0x00E2
#define b11100011 0x00E3
#define b11100100 0x00E4
#define b11100101 0x00E5
#define b11100110 0x00E6
#define b11100111 0x00E7
#define b11101000 0x00E8
#define b11101001 0x00E9
#define b11101010 0x00EA
#define b11101011 0x00EB
#define b11101100 0x00EC
#define b11101101 0x00ED
#define b11101110 0x00EE
#define b11101111 0x00EF
#define b11110000 0x00F0
#define b11110001 0x00F1
#define b11110010 0x00F2
#define b11110011 0x00F3
#define b11110100 0x00F4
#define b11110101 0x00F5
#define b11110110 0x00F6
#define b11110111 0x00F7
#define b11111000 0x00F8
#define b11111001 0x00F9
#define b11111010 0x00FA
#define b11111011 0x00FB
#define b11111100 0x00FC
#define b11111101 0x00FD
#define b11111110 0x00FE
#define b11111111 0x00FF

#endif


问:
posting an array using JQuery .post()
so I am rather new to the whole .post() experience with jquery.

I have only experience POSTing input values so far. What I want to do is POST an array.

which is a standard array of a list of numbers. The end goal being: performing a query with these values.

Could somebody explain to me very basically how using JQuery .post() I can post my array?

many thanks,

答: Check The jQuery Site and the Docs for jQuery.post()</p>

ContentLicense: CC BY-SA 3.0

Title: posting an array using JQuery .post()


问:
How do I customise Rundeck with a logo?
I've just installed Community Rundeck 3.2.2 with RPM on a RHEL 8.1.

I've tried to customise it with my logo images with no success:

Created user-assets directory in /var/lib/rundeck

Copied the images there (png and jpg)

Defined the settings in /etc/rundeck/rundeck-config.properties

rundeck.gui.logo=logoTNC600x600grey.jpg

rundeck.gui.logoSmall=logoTNC200x200white.png

rundeck.gui.instanceNameLabelColor=#ededed

rundeck.gui.instanceNameLabelTextColor=#000000

rundeck.gui.title=TNC Rundeck

rundeck.gui.staticUserResources.enable=true

rundeck.gui.login.welcome=Welcome to TNC

Restarted Rundeck service to no avail: picture not shown in web browser

What have I missed?

Regards,

Raul Costa

答:
You need to add your assets at /var/lib/rundeck/user-assets path (create if it doesn't exist, remember: the "rundeck" user needs to reach that path). Also, verify the files extensions.

Update: change the order of elements in your configuration. Works in the following order:

```<code># custom logo
rundeck.gui.staticUserResources.enabled=true
rundeck.gui.logo=logo.jpg
rundeck.gui.logoSmall=logosmall.jpg
rundeck.gui.instanceNameLabelColor=#ededed
rundeck.gui.instanceNameLabelTextColor=#000000
rundeck.gui.title=TNC Rundeck
</code>```

Title: How do I customise Rundeck with a logo?

Body:
You need to add your assets at /var/lib/rundeck/user-assets path (create if it doesn't exist, remember: the "rundeck" user needs to reach that path). Also, verify the files extensions.

Update: change the order of elements in your configuration. Works in the following order:

# custom logo
rundeck.gui.staticUserResources.enabled=true
rundeck.gui.logo=logo.jpg
rundeck.gui.logoSmall=logosmall.jpg
rundeck.gui.instanceNameLabelColor=#ededed
rundeck.gui.instanceNameLabelTextColor=#000000
rundeck.gui.title=TNC Rundeck


问:
How should I use Azure Blob Containers?
My current approach is that I have a few containers:

raw (the actual raw files or exports, separated into folders like servicenow-cases, servicenow-users, playvox-evaluations, etc.)

staging (lightly transformed raw data)

analytics (these are Parquet file directories which consolidate and partition the files)

visualization (we use a 3rd party tool which syncs with Azure Blob, but only CSV files currently. This is almost the exact same as the analytics container)

However, it could also make some sense to create more containers and kind of use them like I would use a database schema. For example, one container for ServiceNow data, another for LogMeIn data, another for our telephony system, etc.

Is there any preferred approach?

答:
Based on your description, it seems you are tangled to use a small number of containers to store a large number of blobs or make a large number of containers to store a small number of blobs. If all you think about is parallelism and scalability, you can rest assured,  just you design a storage structure that suits you. Because partitioning in Azure Blob storage is done at the blob level, not the container.

Each of these two approaches has their advantages and disadvantages.

For a small number of containers, it can save the cost of creating containers (the operation of creating containers need you to pay for it). But at the same time, when you try to list the blobs in the container, the objects in it will be listed. If you still have a subset inside, you still need to continue to obtain, in this case the performance is less than the Lots of Container Solution. And at the same time, the security boundary you set will apply to all blobs in this container. This is not necessarily what you want.

For a large number of structured containers, more containers can set more security boundaries (custom access permissions, access control SAS signatures). It is also easy to list blobs, no more messy subsets are needed to catch. But again, its disadvantage is that it will have more consumption in creating containers (in extreme cases, it will increase a lot of costs. In general, it does not matter. a website that calculates costs: https://azure.microsoft.com/en-us/pricing/calculator/?cdn=disable).

Title: How should I use Azure Blob Containers?


问:
Kubernates cluster instance
I have created a Kubernetes cluster and one of instance in the cluster is inactive
I want to review the configured Kubernetes Engine cluster of an inactive configuration by which command should I check?
Should I use this "kubectl config get-contexts"?
or
kubectl config use-context and kubectl config view?

Am beginner to cloud please anyone explains?

答:
The kubectl config get-context will not help you debug why the instance is failing. Basically it will just show you the list ot contexts.  A context  is a group of cluster access parameters. Each context contains a Kubernetes cluster, a user, and a namespace. The current context is the cluster that is currently the default for kubectl . On other hand the kubectl config view will just print you kubeconfig settings.

The best way to start is the Kubernestes official documentation. It provides a good basic steps for troubleshoouting your cluster. Some of the steps can be applied to GKE as well as the Kubeadm or Minikube clusters.

If you're using GKE, then you can read the nodes logs from Stackdriver. This document is excellent start when you want to check the logs directly in the log viewer.

If one of your instaces report NotReady after listing them with kubectl get nodes I suggest to ssh to that instances and check kubernetes components (kubelet and kube-proxy). You can view the GKE nodes from the instances page.

Kube  Proxy logs:

```<code>/var/log/kube-proxy.log
</code>```

If you want to check the kubelet logs, they're a unit in systemd in COS that can be accessed using jorunactl.

Kubelet logs:

```<code>sudo journalctl -u kubelet
</code>```

For further debugging it is worth mentioning that that GKE master is a node inside a Google managed project and it is different from your cluster project.
For the detailed master logs you will have open a google support ticket. Here is more information about how GKE cluster architecture works, in case there's something related to the api-server.

Let me know if that was helpful.

Title: Kubernates cluster instance

Body:
The kubectl config get-context will not help you debug why the instance is failing. Basically it will just show you the list ot contexts.  A context  is a group of cluster access parameters. Each context contains a Kubernetes cluster, a user, and a namespace. The current context is the cluster that is currently the default for kubectl . On other hand the kubectl config view will just print you kubeconfig settings.

The best way to start is the Kubernestes official documentation. It provides a good basic steps for troubleshoouting your cluster. Some of the steps can be applied to GKE as well as the Kubeadm or Minikube clusters.

If you're using GKE, then you can read the nodes logs from Stackdriver. This document is excellent start when you want to check the logs directly in the log viewer.

If one of your instaces report NotReady after listing them with kubectl get nodes I suggest to ssh to that instances and check kubernetes components (kubelet and kube-proxy). You can view the GKE nodes from the instances page.

Kube  Proxy logs:

/var/log/kube-proxy.log

If you want to check the kubelet logs, they're a unit in systemd in COS that can be accessed using jorunactl.

Kubelet logs:

sudo journalctl -u kubelet

For further debugging it is worth mentioning that that GKE master is a node inside a Google managed project and it is different from your cluster project.
For the detailed master logs you will have open a google support ticket. Here is more information about how GKE cluster architecture works, in case there's something related to the api-server.

Let me know if that was helpful.


问:
Prevent Recyclerview from losing focus
I am developping this android TV app which has one activity containing some buttons. After clicking a button, a RecyclerView (in the same activity) gets populated and automatically focused.

The problem is when navigating with DPAD toward the direction of the buttons, the RecyclerView loses focus to the buttons. I want to prevent this behavior, i.e. prevent the RecyclerView from losing focus to anything else on the activity. Later, the only way to select another button is by clicking the back button, this I can do, no problem.

Here is what I have tried, and did not work:

```<code><androidx.recyclerview.widget.RecyclerView
        android:id="@+id/categories_rv"
        android:layout_width="@dimen/categories_list_width"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:nextFocusForward="@id/categories_rv"
        android:nextFocusUp="@id/categories_rv"
        android:nextFocusRight="@id/categories_rv"
        android:nextFocusLeft="@id/categories_rv"
        android:nextFocusDown="@id/categories_rv"
        android:focusableInTouchMode="true" />
</code>```

And this:

```<code> binding.categoriesRv.setOnFocusChangeListener { v, hasFocus ->
     if (!hasFocus)
        v.requestFocus()
  }
</code>```

In the second way, the FocusChangeListener never gets called unless I use android:descendantFocusability="blocksDescendants" in the RecyclerView, but this prevents the items of the RecyclerView of being focused.

答:
First of all i worked for 3 years on AndroidTv fighting against the focus management, it is actually pretty simple, the problem is...there is no documentation!

On Android-TV the right way to manage the Dpad navigation is actually to use the focusSearch method. What does this do?

DPad navigation actually means the focus changes between some Views. So who should decide where the focus should go when you press Dpad-Right? The ViewGroup (the parent) containing the Views does!

A little background: when a view does not know who should get the focus, it asks the ViewGroup to take the decision. So in most cases when you push DpadRight while in focus on a View, focusSearch is called on its container with direction = FOCUS_RIGHT (FOCUS_END) and so on.

The solution for you is then pretty simple. You have 2 ways:

Put the Recyclerview inside a BrowseFrameLayout then you can do the following

BrowseFrameLayout browseFrameLayout = view.findViewById(R.id.recyclerview_container);
RecyclerView recyclerView = view.findViewById(R.id.categories_rv);
theBrowseFrameLayout.setOnFocusSearchListener(new BrowseFrameLayout.OnFocusSearchListener() {
    @Override
    public View onFocusSearch(View focused, int direction) {
        if (recyclerView.hasFocus())
            return focused; // keep focus on recyclerview! DO NOT return recyclerview, but focused, which is a child of the recyclerview
        else
            return null; // someone else will find the next focus
    }
});
```
<ol start="2">
<li>You can create a custom view extending any container you are using for your recyclerview and do the same, here is a little more complex example that we use with an UI having a top menu and various fragments under it : https://gist.github.com/RedLann/bfaffc06eb0f571234c6e46b697d633b</li>
</ol>
<p><strong>NOTE:</strong> Usually in xml we use on recyclerview <code>android:descendantFocusability="afterDescendants"</code></p>
<p><strong>NOTE:</strong> Just so you know, when a View gets focused for the first time, there is a method of that view that is called, which is:</p>
<pre class="lang-java prettyprint-override"><code>protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)
</code>```

NOTE: If you use this approach, the focus management becomes really easy, each Parent view (ViewGroup/Container) will manage the focus for its direct children, when it doesn't know what to do it can delegate to its own parent viewgroup returning super.focusSearch

Title: Prevent Recyclerview from losing focus

Body:
I am developping this android TV app which has one activity containing some buttons. After clicking a button, a RecyclerView (in the same activity) gets populated and automatically focused.

The problem is when navigating with DPAD toward the direction of the buttons, the RecyclerView loses focus to the buttons. I want to prevent this behavior, i.e. prevent the RecyclerView from losing focus to anything else on the activity. Later, the only way to select another button is by clicking the back button, this I can do, no problem.

Here is what I have tried, and did not work:

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/categories_rv"
        android:layout_width="@dimen/categories_list_width"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:nextFocusForward="@id/categories_rv"
        android:nextFocusUp="@id/categories_rv"
        android:nextFocusRight="@id/categories_rv"
        android:nextFocusLeft="@id/categories_rv"
        android:nextFocusDown="@id/categories_rv"
        android:focusableInTouchMode="true" />

And this:

 binding.categoriesRv.setOnFocusChangeListener { v, hasFocus ->
     if (!hasFocus)
        v.requestFocus()
  }

In the second way, the FocusChangeListener never gets called unless I use android:descendantFocusability="blocksDescendants" in the RecyclerView, but this prevents the items of the RecyclerView of being focused.

Body:
First of all i worked for 3 years on AndroidTv fighting against the focus management, it is actually pretty simple, the problem is...there is no documentation!

On Android-TV the right way to manage the Dpad navigation is actually to use the focusSearch method. What does this do?

DPad navigation actually means the focus changes between some Views. So who should decide where the focus should go when you press Dpad-Right? The ViewGroup (the parent) containing the Views does!

A little background: when a view does not know who should get the focus, it asks the ViewGroup to take the decision. So in most cases when you push DpadRight while in focus on a View, focusSearch is called on its container with direction = FOCUS_RIGHT (FOCUS_END) and so on.

The solution for you is then pretty simple. You have 2 ways:

Put the Recyclerview inside a BrowseFrameLayout then you can do the following

BrowseFrameLayout browseFrameLayout = view.findViewById(R.id.recyclerview_container);
RecyclerView recyclerView = view.findViewById(R.id.categories_rv);
theBrowseFrameLayout.setOnFocusSearchListener(new BrowseFrameLayout.OnFocusSearchListener() {
    @Override
    public View onFocusSearch(View focused, int direction) {
        if (recyclerView.hasFocus())
            return focused; // keep focus on recyclerview! DO NOT return recyclerview, but focused, which is a child of the recyclerview
        else
            return null; // someone else will find the next focus
    }
});

You can create a custom view extending any container you are using for your recyclerview and do the same, here is a little more complex example that we use with an UI having a top menu and various fragments under it : https://gist.github.com/RedLann/bfaffc06eb0f571234c6e46b697d633b

NOTE: Usually in xml we use on recyclerview android:descendantFocusability="afterDescendants"

NOTE: Just so you know, when a View gets focused for the first time, there is a method of that view that is called, which is:

protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)

NOTE: If you use this approach, the focus management becomes really easy, each Parent view (ViewGroup/Container) will manage the focus for its direct children, when it doesn't know what to do it can delegate to its own parent viewgroup returning super.focusSearch


问:
How Can I implement in OOP?
```<code>// A is the core class

class A{
   public $lang;
   function sayhi($name){echo "Hi".$name;}
   function speak(){echo "Can Speak".$this->lang;}
}

class B {

  function TODO(){
       echo  " Go to work ";
  }
}
</code>```

I DID for now like this:

```<code>class C extends B {

    function TODO(){
    //more implement here

    $a = new A();// here I created an instance.
        // do  any  actions for A
    $a->sayhi("Newbie");
    }

}
</code>```

BUT I  want to class B have all the construct  of class A?

so when I DO on  class C (just something like this)

```<code>class C extends B {

    function TODO(){
    //more implement here
     // I wish I can
       sayhi("Newbie");
    }

}
</code>```

Anybody could tell me how can implement this?

答:
```<code>class A{
   public $lang;
   function sayhi($name){echo "Hi".$name;}    //here you missed a semicolon
   function speak(){echo "Can Speak".$this->lang;}
}

class B extends A {

  function TODO(){
      echo  " Go to work ";
  }
}

class C extends B {

    function TODO(){
        $this->sayhi("Newbie");
    }

}
</code>```

Title: How Can I implement in OOP?

Body:
// A is the core class

class A{
   public $lang;
   function sayhi($name){echo "Hi".$name;}
   function speak(){echo "Can Speak".$this->lang;}
}

class B {

  function TODO(){
       echo  " Go to work ";
  }
}

I DID for now like this:

class C extends B {

    function TODO(){
    //more implement here

    $a = new A();// here I created an instance.
        // do  any  actions for A
    $a->sayhi("Newbie");
    }

}

BUT I  want to class B have all the construct  of class A?

so when I DO on  class C (just something like this)

class C extends B {

    function TODO(){
    //more implement here
     // I wish I can
       sayhi("Newbie");
    }

}

Anybody could tell me how can implement this?


问:
Can we use Java Spring mvc and Spring Boot at the same time in a project?
Actually I want to implement JWT authentication in existing Spring based project. But all the examples and helping material i found, are in Spring Boot.
Kindly provide any relevant link which helps me in implementing JWT auth or guide me if we use Spring Boot together.
Thanks in advance.</p>

答:
no you can't,
here's an example spring security jwt with spring mvc
https://www.toptal.com/java/rest-security-with-jwt-spring-security-and-java?</p>


问:
Simple array sorting program showing incorrect output
When I run the given program I get the output as:

```<code>-2 -2 -2 -2
</code>```

The code is given below:

```<code>#include<iostream>
using namespace std;

int main(){
int a;
int arr[4]={7,-1,0,-2};
for(int i=0;i<4;i++){
    a=i;
    for(int j=i+1;j<4;j++){
        if(arr[j]<arr[a])
            a=j;
    }
 arr[i] = arr[a];
}
for(int z=0;z<4;z++)
    cout<<arr[z]<<"\t";
return 0;
}
</code>```

Where am I making the mistake?

答:
hi thanks for all the help the corrected code is:

```<code>#include<iostream>
using namespace std;

int main(){
int a;
int arr[6] = {12,-3,45,-2,-2,65};
for(int i=0;i<6;i++){
    a=i;
    for(int j=i+1;j<6;j++){
        if(arr[j]<arr[a])
            a=j;

    }
    swap(arr[a],arr[i]);
}

for(int z=0;z<6;z++)
    cout<<arr[z]<<"\t";
return 0;
}
</code>```

or by using a temporary variable for exchanging :

```<code>#include<iostream>
using namespace std;

int main(){
int a,temp;
int arr[4] = {-6,-3,0,7};
for(int i=0;i<4;i++){
    a=i;
    for(int j=i+1;j<4;j++){
        if(arr[j]<arr[a])
            a=j;

    }
    temp = arr[i];
    arr[i] = arr[a];
    arr[a] = temp;
}

for(int z=0;z<4;z++)
    cout<<arr[z]<<"\t";
return 0;
}
</code>```

Body:
When I run the given program I get the output as:

-2 -2 -2 -2

The code is given below:

#include<iostream>
using namespace std;

int main(){
int a;
int arr[4]={7,-1,0,-2};
for(int i=0;i<4;i++){
    a=i;
    for(int j=i+1;j<4;j++){
        if(arr[j]<arr[a])
            a=j;
    }
 arr[i] = arr[a];
}
for(int z=0;z<4;z++)
    cout<<arr[z]<<"\t";
return 0;
}

Where am I making the mistake?

Body:
hi thanks for all the help the corrected code is:

#include<iostream>
using namespace std;

int main(){
int a;
int arr[6] = {12,-3,45,-2,-2,65};
for(int i=0;i<6;i++){
    a=i;
    for(int j=i+1;j<6;j++){
        if(arr[j]<arr[a])
            a=j;

    }
    swap(arr[a],arr[i]);
}

for(int z=0;z<6;z++)
    cout<<arr[z]<<"\t";
return 0;
}

or by using a temporary variable for exchanging :

#include<iostream>
using namespace std;

int main(){
int a,temp;
int arr[4] = {-6,-3,0,7};
for(int i=0;i<4;i++){
    a=i;
    for(int j=i+1;j<4;j++){
        if(arr[j]<arr[a])
            a=j;

    }
    temp = arr[i];
    arr[i] = arr[a];
    arr[a] = temp;
}

for(int z=0;z<4;z++)
    cout<<arr[z]<<"\t";
return 0;
}


问:
Why can't I connect to my USB Composite Device with HIDSharp?
I'm working on a project that emulates a USB Composite Device consisting of a HID keyboard and HID Mouse using a microprocessor.  I have the device properly enumerating and functioning with both my Windows 7 x64 and Raspbian hosts and it all looks good, but where I'm running into a problem is getting my winforms application (using HidSharp) to open the connected composite device so I can get at the raw data in the keyboard endpoint.

The problem seems to be with the TryOpen() function, in that I can find the connected device by matching VID and PID, I assign the device information and report descriptor, but when I try to open a datastream via TryOpen() it fails, and I don't know why.  Unfortunately the function only returns a bool, so I don't know why it's failing, just that it can't open the datastream.  I'm wondering if maybe there's something funny with opening a composite device that I'm not aware of?  My code for finding the device and opening the datastream is below:

```<code>/*These vars are part of the class*/
byte[] keyboardBuffer;  //EP1
HidSharp.Reports.Input.HidDeviceInputReceiver InputReceiver;
HidSharp.Reports.ReportDescriptor KeyboardRptDescriptor;
HidStream KeyboardStream;
HidDevice KeyboardDevice;

private void FindDevice()
{
    var list = DeviceList.Local;
    var stopwatch = Stopwatch.StartNew();
    var hidDeviceList = list.GetHidDevices().ToArray();

    foreach (HidDevice d in hidDeviceList)
    {

        if (d.VendorID == 0x0000 && d.ProductID == 0xA0A0)
        {
            /*Proper VID and PID Found*/
            if (d.GetProductName() == "Keyboard")
            {
                KeyboardDevice = d;
                KeyboardRptDescriptor = KeyboardDevice.GetReportDescriptor();

            }

        }

    }

    if (KeyboardDevice != null)
    {
        /*Device Found, open the datastream*/
        if (KeyboardDevice.TryOpen(out KeyboardStream))    //PROBLEM LINE - Always False?
        {
            KeyboardReport = KeyboardRptDescriptor.InputReports.FirstOrDefault();
            keyboardBuffer = new byte[KeyboardDevice.GetMaxInputReportLength()];
            InputParser = KeyboardReport.DeviceItem.CreateDeviceItemInputParser();
            InputReceiver = KeyboardRptDescriptor.CreateHidDeviceInputReceiver();
            InputReceiver.Received -= new EventHandler(HidInputReceived);
            InputReceiver.Received += new EventHandler(HidInputReceived);
            InputReceiver.Start(KeyboardStream);
        } else {
            rtb_hidLog.AppendText("Unable to connect to device\r\n");
        }

    }
    else
    {
        rtb_hidLog.AppendText("No Device Found\r\n");
    }

}
</code>```

Right now I'm only attempting to read from the HID Keyboard, and will add the mouse once I sort the keyboard out.  There are seemingly no issues finding the device, but why is opening it giving me such an issue?  My HIDSharp library appears to be v2.0.2.0 (according to the file properties).

Thanks in advance for any suggestions!

答: Yup... couple days of searching... and found your post.  My boss, the wizard, pointed me to a fairly elegant (for low level) solution.   You've got to register windows hooks and catch key strokes.  You have to be creative in determining if it's your input or not, but at least you can capture/eat keystrokes without having focus....</p>

Body:
I'm working on a project that emulates a USB Composite Device consisting of a HID keyboard and HID Mouse using a microprocessor.  I have the device properly enumerating and functioning with both my Windows 7 x64 and Raspbian hosts and it all looks good, but where I'm running into a problem is getting my winforms application (using HidSharp) to open the connected composite device so I can get at the raw data in the keyboard endpoint.

The problem seems to be with the TryOpen() function, in that I can find the connected device by matching VID and PID, I assign the device information and report descriptor, but when I try to open a datastream via TryOpen() it fails, and I don't know why.  Unfortunately the function only returns a bool, so I don't know why it's failing, just that it can't open the datastream.  I'm wondering if maybe there's something funny with opening a composite device that I'm not aware of?  My code for finding the device and opening the datastream is below:

/*These vars are part of the class*/
byte[] keyboardBuffer;  //EP1
HidSharp.Reports.Input.HidDeviceInputReceiver InputReceiver;
HidSharp.Reports.ReportDescriptor KeyboardRptDescriptor;
HidStream KeyboardStream;
HidDevice KeyboardDevice;

private void FindDevice()
{
    var list = DeviceList.Local;
    var stopwatch = Stopwatch.StartNew();
    var hidDeviceList = list.GetHidDevices().ToArray();

    foreach (HidDevice d in hidDeviceList)
    {

        if (d.VendorID == 0x0000 && d.ProductID == 0xA0A0)
        {
            /*Proper VID and PID Found*/
            if (d.GetProductName() == "Keyboard")
            {
                KeyboardDevice = d;
                KeyboardRptDescriptor = KeyboardDevice.GetReportDescriptor();

            }

        }

    }

    if (KeyboardDevice != null)
    {
        /*Device Found, open the datastream*/
        if (KeyboardDevice.TryOpen(out KeyboardStream))    //PROBLEM LINE - Always False?
        {
            KeyboardReport = KeyboardRptDescriptor.InputReports.FirstOrDefault();
            keyboardBuffer = new byte[KeyboardDevice.GetMaxInputReportLength()];
            InputParser = KeyboardReport.DeviceItem.CreateDeviceItemInputParser();
            InputReceiver = KeyboardRptDescriptor.CreateHidDeviceInputReceiver();
            InputReceiver.Received -= new EventHandler(HidInputReceived);
            InputReceiver.Received += new EventHandler(HidInputReceived);
            InputReceiver.Start(KeyboardStream);
        } else {
            rtb_hidLog.AppendText("Unable to connect to device\r\n");
        }

    }
    else
    {
        rtb_hidLog.AppendText("No Device Found\r\n");
    }

}

Right now I'm only attempting to read from the HID Keyboard, and will add the mouse once I sort the keyboard out.  There are seemingly no issues finding the device, but why is opening it giving me such an issue?  My HIDSharp library appears to be v2.0.2.0 (according to the file properties).

Thanks in advance for any suggestions!


问:
countdown from 200 to 0 in multiples of x. X is a value input by the user (python)
I wanted to make a program that counts down from 200 to 0 in multiples of "x". "x" is a number that the user inputs. For example, if the user inputs "5", I want the program to print a list that begins with 200,195,190,185,180... and ends with 0. This is the code I have written so far:

```<code>rows = int(input('What number? '))
i = 1
for i in range(200,-1,rows):
 print (200- i * rows)
i = i + 1
</code>```

Right now it's telling me that "for i in range" can only have one argument, but when I make the argument 0, it doesn't run. When I make the argument 200, the program subtracts "x" from two hundred 200 times. How can I get the program to stop the list at 0?

答:
You don't have to increment i manually in Python.

range(a, b, step) is a range from a inclusive to b exclusive with preset step. Please see.

For your purpose, the following would be suitable:

```<code>print(i) for i in reversed(range(1, 200+1, x))
</code>```

Body:
I wanted to make a program that counts down from 200 to 0 in multiples of "x". "x" is a number that the user inputs. For example, if the user inputs "5", I want the program to print a list that begins with 200,195,190,185,180... and ends with 0. This is the code I have written so far:

rows = int(input('What number? '))
i = 1
for i in range(200,-1,rows):
 print (200- i * rows)
i = i + 1

Right now it's telling me that "for i in range" can only have one argument, but when I make the argument 0, it doesn't run. When I make the argument 200, the program subtracts "x" from two hundred 200 times. How can I get the program to stop the list at 0?

Body:
You don't have to increment i manually in Python.

range(a, b, step) is a range from a inclusive to b exclusive with preset step. Please see.

For your purpose, the following would be suitable:

print(i) for i in reversed(range(1, 200+1, x))


问:
Getting the "name" of XML elements
I have an XML that looks something like this:

```<code><signals>
  <signal name="N$41">
  </signal>
  <signal name="S$80">
  </signal>
</signals>
</code>```

I am wondering how and if it is possible to get the name, i.e. "N$41" from each signal?

答:
using XDocument

```<code>var result = XDocument.Load(filename).Descendants("signal");

foreach (var p in result)
{
    Console.WriteLine(p.Attribute("name"));
}
</code>```

Title: Getting the "name" of XML elements

Body:
I have an XML that looks something like this:

<signals>
  <signal name="N$41">
  </signal>
  <signal name="S$80">
  </signal>
</signals>

I am wondering how and if it is possible to get the name, i.e. "N$41" from each signal?

Body:
using XDocument

var result = XDocument.Load(filename).Descendants("signal");

foreach (var p in result)
{
    Console.WriteLine(p.Attribute("name"));
}


问:
QVariant deserialization gives invalid value
I have the following class I want to serialize and deserialize:

```<code>#include <QObject>
#include <QDataStream>
#include <QVariant>

/**
 * @brief   The type used to store the \ref CComPacket::Cmd enum
 */
using CmdType = quint8;

/**
 * @brief   A smart container for the TCP packets
 */
class CComPacket : public QObject
{
    Q_OBJECT

public:

    /**
     * @brief   Provides the command information for the packet (tells how
     *          the data is supposed to be parsed).
     */
    enum class Cmd: CmdType
    {
        Invalid,
        ReadName,
        GiveName,
    };

    explicit CComPacket(QObject *parent = nullptr);

    /**
     * @brief   The ostream (<<) overloading
     * @param   out: The data stream to which the \p cpp class is going to
     *          be serialized.
     * @param   ccp: the class to be serialized into the \p out.
     * @return  reference to \p out.
     */
    friend QDataStream& operator<<(QDataStream& out, const CComPacket& ccp)
    {
        out << static_cast<CmdType>(ccp.m_cmd) << ccp.m_data;
        return out;
    }

    /**
     * @brief   The istream (>>) overloading
     * @param   in: The serialized data that will be deserialized to the \p cpp
     * @param   ccp: deserialized data goes here.
     * @return  The \p in reference.
     */
    friend QDataStream& operator>>(QDataStream& in, CComPacket& ccp)
    {
        CmdType tmp;
        in >> tmp >> ccp.m_data;
        ccp.m_cmd = static_cast<Cmd>(tmp);

        return in;
    }

    /**
     * @brief   The parsing command
     */
    Cmd m_cmd = Cmd::Invalid;

    /**
     * @brief   The data to be parsed
     */
    QVariant m_data;

};
</code>```

I am trying to test this with this code:

```<code>CComPacket tmp;
tmp.m_cmd = CComPacket::Cmd::GiveName;
tmp.m_data = 5.112233;

QDataStream str;
str << tmp;

CComPacket tmp2;
str >> tmp2;
</code>```

When debugging I see that the m_cmd member of tmp2 is deserialized correctly but the m_data object is still invalid. From the documentation I understand that QVariant support serialization by default. What am I missing here?

答:
In order to make this work, I had to incorporate the QByteArray that had to be used as the parameter for the QDataStream, since a phisical container was needed already. I planned on serializing the data to bytes anyways in the later step, so this just made everything easier. I added the following member functions:

```<code>QByteArray serialize();
static CComPacket deserialize(QByteArray& ba);

QByteArray CComPacket::serialize()
{
    QByteArray ba;
    QDataStream ds(&ba, QIODevice::WriteOnly);

    ds << *this;
    return ba;
}

CComPacket CComPacket::deserialize(QByteArray& ba)
{
    QDataStream ds(&ba, QIODevice::ReadOnly);
    CComPacket cp;

    ds >> cp;
    return cp;
}
</code>```

And this test code now works correctly (tmp is the same as tmp2):

```<code>CComPacket tmp;
tmp.m_cmd = CComPacket::Cmd::GiveName;
tmp.m_data = 5.112233;

QByteArray ba = tmp.serialize();
CComPacket tmp2 = CComPacket::deserialize(ba);
</code>```

Body:
I have the following class I want to serialize and deserialize:

#include <QObject>
#include <QDataStream>
#include <QVariant>

/**
 * @brief   The type used to store the \ref CComPacket::Cmd enum
 */
using CmdType = quint8;

/**
 * @brief   A smart container for the TCP packets
 */
class CComPacket : public QObject
{
    Q_OBJECT

public:

    /**
     * @brief   Provides the command information for the packet (tells how
     *          the data is supposed to be parsed).
     */
    enum class Cmd: CmdType
    {
        Invalid,
        ReadName,
        GiveName,
    };

    explicit CComPacket(QObject *parent = nullptr);

    /**
     * @brief   The ostream (<<) overloading
     * @param   out: The data stream to which the \p cpp class is going to
     *          be serialized.
     * @param   ccp: the class to be serialized into the \p out.
     * @return  reference to \p out.
     */
    friend QDataStream& operator<<(QDataStream& out, const CComPacket& ccp)
    {
        out << static_cast<CmdType>(ccp.m_cmd) << ccp.m_data;
        return out;
    }

    /**
     * @brief   The istream (>>) overloading
     * @param   in: The serialized data that will be deserialized to the \p cpp
     * @param   ccp: deserialized data goes here.
     * @return  The \p in reference.
     */
    friend QDataStream& operator>>(QDataStream& in, CComPacket& ccp)
    {
        CmdType tmp;
        in >> tmp >> ccp.m_data;
        ccp.m_cmd = static_cast<Cmd>(tmp);

        return in;
    }

    /**
     * @brief   The parsing command
     */
    Cmd m_cmd = Cmd::Invalid;

    /**
     * @brief   The data to be parsed
     */
    QVariant m_data;

};

I am trying to test this with this code:

CComPacket tmp;
tmp.m_cmd = CComPacket::Cmd::GiveName;
tmp.m_data = 5.112233;

QDataStream str;
str << tmp;

CComPacket tmp2;
str >> tmp2;

When debugging I see that the m_cmd member of tmp2 is deserialized correctly but the m_data object is still invalid. From the documentation I understand that QVariant support serialization by default. What am I missing here?

Body:
In order to make this work, I had to incorporate the QByteArray that had to be used as the parameter for the QDataStream, since a phisical container was needed already. I planned on serializing the data to bytes anyways in the later step, so this just made everything easier. I added the following member functions:

QByteArray serialize();
static CComPacket deserialize(QByteArray& ba);

QByteArray CComPacket::serialize()
{
    QByteArray ba;
    QDataStream ds(&ba, QIODevice::WriteOnly);

    ds << *this;
    return ba;
}

CComPacket CComPacket::deserialize(QByteArray& ba)
{
    QDataStream ds(&ba, QIODevice::ReadOnly);
    CComPacket cp;

    ds >> cp;
    return cp;
}

And this test code now works correctly (tmp is the same as tmp2):

CComPacket tmp;
tmp.m_cmd = CComPacket::Cmd::GiveName;
tmp.m_data = 5.112233;

QByteArray ba = tmp.serialize();
CComPacket tmp2 = CComPacket::deserialize(ba);


答:
You can use this code</p>

```<code>rows = int(input('What number? '))
i = 1
for i in range(1, int(200/rows)+1):
    print (200- i*rows)
</code>```

Title: countdown from 200 to 0 in multiples of x. X is a value input by the user (python)

Body:
You can use this code

rows = int(input('What number? '))
i = 1
for i in range(1, int(200/rows)+1):
    print (200- i*rows)


问:
How to fit the map in a destination point with MapViewDirections on react native?
How to fit the map in a destination point?
I just need to fit the camera to the destination point, not to both coordinates (initial and destination like today). How do I do this? Another way to fit the coordinates to this?

{destination && (
  <Fragment>
    <Directions
      origin={region}
      destination={destination}
      onReady={result => {
        this.setState({ duration: Math.floor(result.duration) });
        this.mapView.fitToCoordinates(result.coordinates, {
          edgePadding: {
            right: getPixelSize(10),
            left: getPixelSize(10),
            top: getPixelSize(10),
            bottom: getPixelSize(50),
          },
          animated: true,
        });
      }}
    />
    <Marker
      onPress={this.pickLocationHandler}
      coordinate={destination}
      centerOffset={{ x: -18, y: -60 }}
      anchor={{ x: 0, y: 0 }}
    //opacity={0.6}
    >
      <LocationBox>
        <LocationText>{destination.title}</LocationText>
      </LocationBox>
    </Marker>
    <Marker
      coordinate={region}
      anchor={{ x: 0, y: 0 }}
      onPress={this.pickLocationHandler}>
      <LocationBox>
        <LocationTimeBox>
          <LocationTimeText>{duration}</LocationTimeText>
          <LocationTimeTextSmall>
            Tempo de Viagem
          </LocationTimeTextSmall>
        </LocationTimeBox>
        <LocationText>{location}</LocationText>
      </LocationBox>
    </Marker>
  </Fragment>
)}
```

It would be nice if anyone has some code that works together with GooglePlacesAutocomplete.

答:
This is my solution, I remove the method directions and replace for this animation one:

Add this method:

```<code>  getCoordsFromName(loc) {
     this.mapView.animateToRegion({
      ...this.state.region,
      latitude: loc.lat,
      longitude: loc.lng,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA,
    });
    this.setState(prevState => {
      return {
        region: {
          ...prevState.region,
          latitude: loc.lat,
          longitude: loc.lng,
        },
      };
    });
  }
</code>```

accordingly with:

```<code> <MapInput style = {{flex: 1, position : 'absolute'}} notifyChange={loc => this.getCoordsFromName(loc)} />
</code>```

Body:
How to fit the map in a destination point?
I just need to fit the camera to the destination point, not to both coordinates (initial and destination like today). How do I do this? Another way to fit the coordinates to this?

{destination && (
  <Fragment>
    <Directions
      origin={region}
      destination={destination}
      onReady={result => {
        this.setState({ duration: Math.floor(result.duration) });
        this.mapView.fitToCoordinates(result.coordinates, {
          edgePadding: {
            right: getPixelSize(10),
            left: getPixelSize(10),
            top: getPixelSize(10),
            bottom: getPixelSize(50),
          },
          animated: true,
        });
      }}
    />
    <Marker
      onPress={this.pickLocationHandler}
      coordinate={destination}
      centerOffset={{ x: -18, y: -60 }}
      anchor={{ x: 0, y: 0 }}
    //opacity={0.6}
    >
      <LocationBox>
        <LocationText>{destination.title}</LocationText>
      </LocationBox>
    </Marker>
    <Marker
      coordinate={region}
      anchor={{ x: 0, y: 0 }}
      onPress={this.pickLocationHandler}>
      <LocationBox>
        <LocationTimeBox>
          <LocationTimeText>{duration}</LocationTimeText>
          <LocationTimeTextSmall>
            Tempo de Viagem
          </LocationTimeTextSmall>
        </LocationTimeBox>
        <LocationText>{location}</LocationText>
      </LocationBox>
    </Marker>
  </Fragment>
)}

It would be nice if anyone has some code that works together with GooglePlacesAutocomplete.

Body:
This is my solution, I remove the method directions and replace for this animation one:

Add this method:

  getCoordsFromName(loc) {
     this.mapView.animateToRegion({
      ...this.state.region,
      latitude: loc.lat,
      longitude: loc.lng,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA,
    });
    this.setState(prevState => {
      return {
        region: {
          ...prevState.region,
          latitude: loc.lat,
          longitude: loc.lng,
        },
      };
    });
  }

accordingly with:

 <MapInput style = {{flex: 1, position : 'absolute'}} notifyChange={loc => this.getCoordsFromName(loc)} />


问:
Using unique_ptr in a pair
My code:

```<code>template <typename T>//, T value_if_empty>
class AtomicQueue {
    std::mutex m;
    std::queue<T> q;
    T value_if_empty;

public:
    AtomicQueue(const T& emptyval) : value_if_empty(std::move(emptyval)) {};
    void push(const T& t)
    {
        m.lock();
        q.push(std::move(t));
        m.unlock();
    }
    T pop()
    {
        T a = std::move(value_if_empty);
        m.lock();
        if (!q.empty())
        {
            a = std::move(q.front());
            q.pop();
        }
        m.unlock();
        return a;
    }
};

AtomicQueue<int> A(0);
AtomicQueue<std::unique_ptr<Class1>> B(nullptr);
AtomicQueue < std::pair<int, std::unique_ptr<Class1>>> C({ 0,nullptr });
</code>```

This code compiles if I declare just A and B but fails when C is also declared. The error is 'std::pair<int,std::unique_ptr<Class1,std::default_delete<Class1>>>::pair(const std::pair<int,std::unique_ptr<Class1,std::default_delete<Class1>>> &)': attempting to reference a deleted function

The problem seems to be that std::pair<int, std::unique_ptr<Class1>> does not have a copy constructor. But the same is true for std::unique_ptr<Class1>. So why does the declaration for B compile but C does not? Also, where exactly is the copy constructor being used?
Sorry if the answer is trivial. I am new to using unique_ptr and move constructors.

Side Question: Is there a cleaner or better way to use value_if_empty? I do not want anything other than nullptr being passed when unique_ptr is being used.

Edit: B does not compile either. (as mentioned in a comment by NathanOliver). So, the question now is how do I remove this error?

答:
This is because you don't move anything in your function. They recieve const T&, but constants cannot be moved. Calling std::move on a const won't move and does absolutely nothing.

See, move is simply a cast to rvalue. The actual moving happen in the move constructor and move assignment. Such move constructors are declared like this:

```<code>unique_ptr(unique_ptr&& other);
</code>```

As you can see, it's a non const rvalue reference. Since you cannot call the move constructor, it tries to copy instead. That is the source of the error.

How can you fix it then?

Simply add the required overloads and remove the superfluous moves:

```<code>template <typename T>
class AtomicQueue {
    std::mutex m;
    std::queue<T> q;
    T value_if_empty;

public:
    // copy, it's an lvalue
    AtomicQueue(const T& emptyval) : value_if_empty(emptyval) {};

    // move, it's an rvalue
    AtomicQueue(T&& emptyval) : value_if_empty(std::move(emptyval)) {};

    void push(const T& t)
    {
        m.lock();
        q.push(t); // same here
        m.unlock();
    }

    void push(T&& t)
    {
        m.lock();
        q.push(std::move(t)); // same here
        m.unlock();
    }
    T pop()
    {
        T a = std::move(value_if_empty);
        m.lock();
        if (!q.empty())
        {
            a = std::move(q.front());
            q.pop();
        }
        m.unlock();
        return a;
    }
};
</code>```

Live example

Also note that there's a fundamental bug in your class. Look at this line:

```<code>T a = std::move(value_if_empty);
</code>```

If pop is called more than once, value_if_empty will be a moved from value and you return it. Your pop function can only be called one time before returning unspecified values.

You'll need either to copy value_if_empty, default construct it or replace it by a factory function that will return a new value to take if empty.

My favourite solution would be to default construct it.

Here's nonetheless an example with a factory function:

```<code>template <typename T>
class AtomicQueue {
    std::function<T()> make_empty_value;

public:
    T pop()
    {
        T a = make_empty_value();
        // ...
    }
};
</code>```

Then pass it to your class when creating it:

```<code>AtomicQueue<std::unique_ptr<Class1>> B([]{ return std::unique_ptr<Class1>{nullptr}; });
</code>```

If you want to avoid the overhead of std::function, you can replace the member variable by a template parameter of the lambda type.

Title: Using unique_ptr in a pair

Body:
My code:

template <typename T>//, T value_if_empty>
class AtomicQueue {
    std::mutex m;
    std::queue<T> q;
    T value_if_empty;

public:
    AtomicQueue(const T& emptyval) : value_if_empty(std::move(emptyval)) {};
    void push(const T& t)
    {
        m.lock();
        q.push(std::move(t));
        m.unlock();
    }
    T pop()
    {
        T a = std::move(value_if_empty);
        m.lock();
        if (!q.empty())
        {
            a = std::move(q.front());
            q.pop();
        }
        m.unlock();
        return a;
    }
};

AtomicQueue<int> A(0);
AtomicQueue<std::unique_ptr<Class1>> B(nullptr);
AtomicQueue < std::pair<int, std::unique_ptr<Class1>>> C({ 0,nullptr });

This code compiles if I declare just A and B but fails when C is also declared. The error is 'std::pair<int,std::unique_ptr<Class1,std::default_delete<Class1>>>::pair(const std::pair<int,std::unique_ptr<Class1,std::default_delete<Class1>>> &)': attempting to reference a deleted function

The problem seems to be that std::pair<int, std::unique_ptr<Class1>> does not have a copy constructor. But the same is true for std::unique_ptr<Class1>. So why does the declaration for B compile but C does not? Also, where exactly is the copy constructor being used?
Sorry if the answer is trivial. I am new to using unique_ptr and move constructors.

Side Question: Is there a cleaner or better way to use value_if_empty? I do not want anything other than nullptr being passed when unique_ptr is being used.

Edit: B does not compile either. (as mentioned in a comment by NathanOliver). So, the question now is how do I remove this error?

Body:
This is because you don't move anything in your function. They recieve const T&, but constants cannot be moved. Calling std::move on a const won't move and does absolutely nothing.

See, move is simply a cast to rvalue. The actual moving happen in the move constructor and move assignment. Such move constructors are declared like this:

unique_ptr(unique_ptr&& other);

As you can see, it's a non const rvalue reference. Since you cannot call the move constructor, it tries to copy instead. That is the source of the error.

How can you fix it then?

Simply add the required overloads and remove the superfluous moves:

template <typename T>
class AtomicQueue {
    std::mutex m;
    std::queue<T> q;
    T value_if_empty;

public:
    // copy, it's an lvalue
    AtomicQueue(const T& emptyval) : value_if_empty(emptyval) {};

    // move, it's an rvalue
    AtomicQueue(T&& emptyval) : value_if_empty(std::move(emptyval)) {};

    void push(const T& t)
    {
        m.lock();
        q.push(t); // same here
        m.unlock();
    }

    void push(T&& t)
    {
        m.lock();
        q.push(std::move(t)); // same here
        m.unlock();
    }
    T pop()
    {
        T a = std::move(value_if_empty);
        m.lock();
        if (!q.empty())
        {
            a = std::move(q.front());
            q.pop();
        }
        m.unlock();
        return a;
    }
};

Live example

Also note that there's a fundamental bug in your class. Look at this line:

T a = std::move(value_if_empty);

If pop is called more than once, value_if_empty will be a moved from value and you return it. Your pop function can only be called one time before returning unspecified values.

You'll need either to copy value_if_empty, default construct it or replace it by a factory function that will return a new value to take if empty.

My favourite solution would be to default construct it.

Here's nonetheless an example with a factory function:

template <typename T>
class AtomicQueue {
    std::function<T()> make_empty_value;

public:
    T pop()
    {
        T a = make_empty_value();
        // ...
    }
};

Then pass it to your class when creating it:

AtomicQueue<std::unique_ptr<Class1>> B([]{ return std::unique_ptr<Class1>{nullptr}; });

If you want to avoid the overhead of std::function, you can replace the member variable by a template parameter of the lambda type.


问:
Limit number of executions of a python program
Hello
I made a program in python2.6 and converted to exe with py2exe.
I wish that could limit the number of times the
user can use, then this is blocked with a counter or maybe a library.
Any ideas?</p>

答:
A compiled binary can't (easily) modify itself to keep track of something like this. You're going to have to write a counter to the registry or to some web API and check that counter on application (executable) startup.

Keeping in mind, this won't stop someone that determed from bypassing the counter- just a casual user.


问:
Python: create for-loop until two lists match
I am trying to match two lists until they match:

So let's say I have

bought = [12, 10, 5]

sold = [4, 6, 3, 2, 12]

Eventually, I want to create a for-loop over both lists that keeps looping until all numbers match. So it would find all current matches and keeps creating splits for numbers that do not match

In the above example, it would start with 12 being a match for both lists. Then there is 10 which does not match anything but the closest element in the other list is 6, leaving behind 4 which is also a match from the other list.

The above would then eventually become

result = [12, 6, 4, 3, 2]

I was wondering whether there is a Python function such as intersections that can maybe be of help to do this efficiently?

Rules:
1. Sum of two lists is always equal

答:
If I understood well, you need to decompose each element b from bought into elements s1, s2... from sold with the condition b = s1 + s2 .... To achieve this, I suggest to use combinations. I will enumerate every combinations I can do with elements of sold, for example [4], [6,3], [4,2,12]... etc until the sum correspond with an element from bought.

For your example, 12 matched with 12, 10 with 6+4, and 5 with 3+2. If you had 11, it would match with 6+3+2.

```<code>from itertools import combinations

bought = [12, 10, 5]
sold = [4, 6, 3, 2, 12]
sold = sorted(sold, reverse=True)

result = []
for b in bought:
    stop = False
    for i in range(1, len(sold)+1):
        for c in combinations(sold, i):
            if sum(c) == b:
                result += (c)
                stop = True
                break
        if stop:
            break

print(result)
# [12, 6, 4, 3, 2]
</code>```

Body:
If I understood well, you need to decompose each element b from bought into elements s1, s2... from sold with the condition b = s1 + s2 .... To achieve this, I suggest to use combinations. I will enumerate every combinations I can do with elements of sold, for example [4], [6,3], [4,2,12]... etc until the sum correspond with an element from bought.

For your example, 12 matched with 12, 10 with 6+4, and 5 with 3+2. If you had 11, it would match with 6+3+2.

from itertools import combinations

bought = [12, 10, 5]
sold = [4, 6, 3, 2, 12]
sold = sorted(sold, reverse=True)

result = []
for b in bought:
    stop = False
    for i in range(1, len(sold)+1):
        for c in combinations(sold, i):
            if sum(c) == b:
                result += (c)
                stop = True
                break
        if stop:
            break

print(result)
# [12, 6, 4, 3, 2]


问:
Create a vector according to multiple conditions contained in vectors
Imagine I have this data.frame :

```<code>a <- c("Boy","Girl","Dog","Cat","Chair","Table")
b <- c(1:6)
df <- data.frame(a,b)
</code>```

I would like to create a third column groupings elements in the first column according to predefined vectors :

```<code>human <- c("Boy","Girl")
pet <- c("Dog","Cat")
object <- c("Chair","Table")
</code>```

With this wished result :

```<code>df$Type <- c("Human","Human","Animal","Animal","Object","Object")
</code>```

I managed to get it right for 2 groups but I don't know how to include the third one :

```<code>df$Type1 <- ifelse(df$a==human,"Human","Animal")
</code>```

答:
You can keep adding groups like this:

```<code>df$Type <- NA
df$Type <- ifelse(df$a %in% human, "Human", df$Type)
df$Type <- ifelse(df$a %in% pet, "Animal", df$Type)
df$Type <- ifelse(df$a %in% object, "Object", df$Type)
</code>```

Result:

```<code>      a b   Type
1   Boy 1  Human
2  Girl 2  Human
3   Dog 3 Animal
4   Cat 4 Animal
5 Chair 5 Object
6 Table 6 Object
</code>```

Body:
Imagine I have this data.frame :

a <- c("Boy","Girl","Dog","Cat","Chair","Table")
b <- c(1:6)
df <- data.frame(a,b)

I would like to create a third column groupings elements in the first column according to predefined vectors :

human <- c("Boy","Girl")
pet <- c("Dog","Cat")
object <- c("Chair","Table")

With this wished result :

df$Type <- c("Human","Human","Animal","Animal","Object","Object")

I managed to get it right for 2 groups but I don't know how to include the third one :

df$Type1 <- ifelse(df$a==human,"Human","Animal")

Body:
You can keep adding groups like this:

df$Type <- NA
df$Type <- ifelse(df$a %in% human, "Human", df$Type)
df$Type <- ifelse(df$a %in% pet, "Animal", df$Type)
df$Type <- ifelse(df$a %in% object, "Object", df$Type)

Result:

      a b   Type
1   Boy 1  Human
2  Girl 2  Human
3   Dog 3 Animal
4   Cat 4 Animal
5 Chair 5 Object
6 Table 6 Object


答:
You can use nested ifelse() and use %in% instead of ==

```<code>ifelse(df$a %in% human, "Human", ifelse(df$a %in% pet, "Animal", "Object"))
</code>```

Assuming there is nothing else it can be this will work

Title: Create a vector according to multiple conditions contained in vectors

Body:
You can use nested ifelse() and use %in% instead of ==

ifelse(df$a %in% human, "Human", ifelse(df$a %in% pet, "Animal", "Object"))

Assuming there is nothing else it can be this will work


问:
snapshot listener isFromCache() returning false
I am registering snapshot listener on my document reference. For first time, I am getting metadata isfromCache true and rest other time I am getting false. It should be opposite as no document is changing. I checked this value just to be sure that my datas after first time read are getting read from cache. </p>

```<code>DocumentReference basicRef = usersRef.collection(DETAILS).document(BASIC_DETAILS);
ListenerRegistration basicListener = basicRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot snapshot,
                                @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    return;
                }

                if (snapshot != null && snapshot.exists()) {
                    Log.d("debug", "Current data basic: " + snapshot.getMetadata().isFromCache());
                    BasicDetails basicDetails = snapshot.toObject(BasicDetails.class);
                    loadData(basicDetails);
                } else {
                    Log.d("debug", "Current data: null");
                }
            }
        });
</code>```

答:
The isFromCache property is documented to be:

true if the snapshot was created from cached data rather than guaranteed up-to-date server data.

So it being false does not necessarily mean the document was read from the server, as much as it means that the document is guaranteed to be up to date with the server.

To know what documents have changed, you can iterate over the documentChanged collection, as shown in the code above.

Also see:

Firebase always reads from internet

Body:
I am registering snapshot listener on my document reference. For first time, I am getting metadata isfromCache true and rest other time I am getting false. It should be opposite as no document is changing. I checked this value just to be sure that my datas after first time read are getting read from cache.

DocumentReference basicRef = usersRef.collection(DETAILS).document(BASIC_DETAILS);
ListenerRegistration basicListener = basicRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot snapshot,
                                @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    return;
                }

                if (snapshot != null && snapshot.exists()) {
                    Log.d("debug", "Current data basic: " + snapshot.getMetadata().isFromCache());
                    BasicDetails basicDetails = snapshot.toObject(BasicDetails.class);
                    loadData(basicDetails);
                } else {
                    Log.d("debug", "Current data: null");
                }
            }
        });


答:
Yes, you can access the global document from a script in your external SVG file.

Your access is via:

```<code>window.top.document.body
</code>```

Title: Access global document from shadow DOM script

Body:
I have the following svg. Of course document.body is always null because it refers to shadow DOM. Is it possible to access global document from this script?

Please don't tell me it doesn't make sense, believe me it does.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="266" height="100" viewBox="0 0 266 100"
    overflow="visible" enable-background="new 0 0 266 100" xml:space="preserve">
    <g><rect fill="#3B5998" width="266" height="100"/></g>
    <g>
        <path fill="#FFFFFF" d="M242.2011719,66.1777344c1.4726562,0,2.6464844,1.2011719,2.6464844,2.7011719
            c0,1.5234375-1.1738281,2.7109375-2.6572266,2.7109375c-1.4755859,0-2.6728516-1.1875-2.6728516-2.7109375
            c0-1.5,1.1972656-2.7011719,2.6728516-2.7011719H242.2011719z M242.1904297,66.5976562
            c-1.1865234,0-2.1582031,1.0214844-2.1582031,2.28125c0,1.2832031,0.9716797,2.2910156,2.1689453,2.2910156
            c1.1982422,0.0117188,2.1552734-1.0078125,2.1552734-2.2792969s-0.9570312-2.2929688-2.1552734-2.2929688H242.1904297z
             M241.6865234,70.4511719h-0.4804688V67.4375c0.2519531-0.0351562,0.4921875-0.0703125,0.8515625-0.0703125
            c0.4560547,0,0.7539062,0.0957031,0.9365234,0.2265625c0.1767578,0.1328125,0.2724609,0.3359375,0.2724609,0.6230469
            c0,0.3984375-0.2617188,0.6367188-0.5849609,0.734375v0.0234375c0.2626953,0.0488281,0.4423828,0.2871094,0.5029297,0.7304688
            c0.0703125,0.46875,0.1425781,0.6484375,0.1904297,0.7460938h-0.5029297
            c-0.0712891-0.0976562-0.1435547-0.3730469-0.2041016-0.7695312c-0.0703125-0.3828125-0.2636719-0.5273438-0.6484375-0.5273438
            h-0.3330078V70.4511719z M241.6865234,68.7832031h0.3476562c0.3935547,0,0.7285156-0.1445312,0.7285156-0.5175781
            c0-0.2636719-0.1904297-0.5273438-0.7285156-0.5273438c-0.1572266,0-0.265625,0.0117188-0.3476562,0.0234375V68.7832031z"/>
    </g>

</svg>

Body:
Yes, you can access the global document from a script in your external SVG file.

Your access is via:

window.top.document.body


答:
Write the number of starts into a file and check it.

If you want a 100% secure and safe way to prevent users from starting your app more than 15 times, then you should not publish it. That's the only working way to make sure the user doesn't start it more than 15 times.

Rationale: Any good hacker will be able to dismantle your protection in a couple of minutes if he cares. The average user won't know where to start. So you can get good (99%) protection with little effort or 99.5% for a whole lot of effort.

Title: Limit number of executions of a python program

Body:
Hello
I made a program in python2.6 and converted to exe with py2exe.
I wish that could limit the number of times the
user can use, then this is blocked with a counter or maybe a library.
Any ideas?


问:
Recursion with array's PHP
I have a function (listarUrls ()) that returns / scans all the urls it finds on a web page.
I need that for each of the urls that the function returns to me, I return to the list / scan all the urls of that page
many times as requested by the user, that is

```<code>        .If the user asks for 1 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
            -$arry[1] www.2.com
            -..... So with all the urls you find in www.a.com

        .If the user asks for 2 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
                -$arry[0][0] www.1-1.com
                -$arry[0][1] www.1-2.com
                -...So with all the urls you find in www.1.com
            -$arry[1] www.2.com
                -$arry[1][0] www.2-1.com
                -$arry[1][1] www.2-2.com
                -...So with all the urls you find in www.2.com
            -...

        .If the user asks for 3 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
                -$arry[0][0] www.1-1.com
                    -$arry[0][0][0] www.1-1-1.com
                    -$arry[0][0][1] www.1-1-2.com
                    -...So with all the urls you find in www.1-1.com
                -$arry[0][1] www.1-2.com
                    -$arry[0][1][0] www.1-2-1.com
                    -$arry[0][1][1] www.1-2-2.com
                    -...So with all the urls you find in www.1-2.com
            -$arry[1] www.2.com
                -$arry[1][0] www.2-1.com
                    -$arry[1][0][0] www.2-1-1.com
                    -$arry[1][0][1] www.2-1-2.com
                    -...So with all the urls you find in www.2-1.com
                -$arry[1][1] www.2-2.com
                    -$arry[1][1][0] www.2-2-1.com
                    -$arry[1][1][1] www.2-2-2.com
                    -...So with all the urls you find in www.2-2.com
        -...
</code>```

Could someone shed some light on the subject please?

答:
This is web scraping with the option to instruct how much deep to investigate.

We can have a function definition like below:

```<code>function scrapeURLs($url,$steps,&$visited_urls = []);
</code>```

Here, $url is the current URL we are scraping. $steps is which step we are investigating. If $steps == 1 at any point in our recursive function, we stop scraping further. $visited_urls is to make sure we aren't visiting same URL twice for scraping.

Snippet:

```<code><?php
ini_set('max_execution_time','500');
libxml_use_internal_errors(true); // not recommended but fine for debugging. Make sure HTML of the URL follows DOMDocument requirements
function scrapeURLs($url,$steps,&$visited_urls = []){
    $result = [];
    if(preg_match('/^http(s)?:\/\/.+/',$url) === 0){ // if not a proper URL, we stop here, but will have to double check if it's a relative URL and do some modifications to current script
        return $result;
    }

    $dom = new DOMDocument();
    $dom->loadHTMLFile($url);

    // get all script tags
    foreach($dom->getElementsByTagName('script') as $script_tag){
        $script_url = $script_tag->getAttribute('src');
        if(!isset($visited_urls[$script_url])){
            $visited_urls[$script_url] = true;
            $result[$script_url] = $steps === 1 ? [] : scrapeURLs($script_url,$steps - 1,$visited_urls);    // stop or recurse further
        }

    }

    // get all anchor tags
    foreach($dom->getElementsByTagName('a') as $anchor_tag){
        $anchor_url = $anchor_tag->getAttribute('href');
        if(!isset($visited_urls[$anchor_url])){
            $visited_urls[$anchor_url] = true;
            $result[$anchor_url] = $steps === 1 ? [] : scrapeURLs($anchor_url,$steps - 1,$visited_urls);
            // stop or recurse further
        }
    }

    /* Likewise, you can capture several other URLs like CSS stylesheets, image URLs etc*/

    return $result;
}

print_r(scrapeURLs('http://yoursite.com/',2));
</code>```

Title: Recursion with array's PHP

Body:
I have a function (listarUrls ()) that returns / scans all the urls it finds on a web page.
I need that for each of the urls that the function returns to me, I return to the list / scan all the urls of that page
many times as requested by the user, that is

        .If the user asks for 1 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
            -$arry[1] www.2.com
            -..... So with all the urls you find in www.a.com

        .If the user asks for 2 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
                -$arry[0][0] www.1-1.com
                -$arry[0][1] www.1-2.com
                -...So with all the urls you find in www.1.com
            -$arry[1] www.2.com
                -$arry[1][0] www.2-1.com
                -$arry[1][1] www.2-2.com
                -...So with all the urls you find in www.2.com
            -...

        .If the user asks for 3 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
                -$arry[0][0] www.1-1.com
                    -$arry[0][0][0] www.1-1-1.com
                    -$arry[0][0][1] www.1-1-2.com
                    -...So with all the urls you find in www.1-1.com
                -$arry[0][1] www.1-2.com
                    -$arry[0][1][0] www.1-2-1.com
                    -$arry[0][1][1] www.1-2-2.com
                    -...So with all the urls you find in www.1-2.com
            -$arry[1] www.2.com
                -$arry[1][0] www.2-1.com
                    -$arry[1][0][0] www.2-1-1.com
                    -$arry[1][0][1] www.2-1-2.com
                    -...So with all the urls you find in www.2-1.com
                -$arry[1][1] www.2-2.com
                    -$arry[1][1][0] www.2-2-1.com
                    -$arry[1][1][1] www.2-2-2.com
                    -...So with all the urls you find in www.2-2.com
        -...

Could someone shed some light on the subject please?

Body:
This is web scraping with the option to instruct how much deep to investigate.

We can have a function definition like below:

function scrapeURLs($url,$steps,&$visited_urls = []);

Here, $url is the current URL we are scraping. $steps is which step we are investigating. If $steps == 1 at any point in our recursive function, we stop scraping further. $visited_urls is to make sure we aren't visiting same URL twice for scraping.

Snippet:

<?php
ini_set('max_execution_time','500');
libxml_use_internal_errors(true); // not recommended but fine for debugging. Make sure HTML of the URL follows DOMDocument requirements
function scrapeURLs($url,$steps,&$visited_urls = []){
    $result = [];
    if(preg_match('/^http(s)?:\/\/.+/',$url) === 0){ // if not a proper URL, we stop here, but will have to double check if it's a relative URL and do some modifications to current script
        return $result;
    }

    $dom = new DOMDocument();
    $dom->loadHTMLFile($url);

    // get all script tags
    foreach($dom->getElementsByTagName('script') as $script_tag){
        $script_url = $script_tag->getAttribute('src');
        if(!isset($visited_urls[$script_url])){
            $visited_urls[$script_url] = true;
            $result[$script_url] = $steps === 1 ? [] : scrapeURLs($script_url,$steps - 1,$visited_urls);    // stop or recurse further
        }

    }

    // get all anchor tags
    foreach($dom->getElementsByTagName('a') as $anchor_tag){
        $anchor_url = $anchor_tag->getAttribute('href');
        if(!isset($visited_urls[$anchor_url])){
            $visited_urls[$anchor_url] = true;
            $result[$anchor_url] = $steps === 1 ? [] : scrapeURLs($anchor_url,$steps - 1,$visited_urls);
            // stop or recurse further
        }
    }

    /* Likewise, you can capture several other URLs like CSS stylesheets, image URLs etc*/

    return $result;
}

print_r(scrapeURLs('http://yoursite.com/',2));