问:
search a structure element in map
i am new to C++(also english).
i want to search {1,2,3} in the map and if it exists , print TRUE on screen
but i can not
my code comes below
can you help me?</p>

```<code>#include <iostream>
#include <map>
#include <iterator>
#define PKT_UNIT_MAX_LEN  10000
using namespace std;

struct PKT_UNIT
{
int len;
unsigned int checksum;
unsigned char data[PKT_UNIT_MAX_LEN];

};

int main()
{
 map<int,PKT_UNIT> maharan;
 maharan.insert(pair<int,PKT_UNIT>(1,{1,2,3}));

 map<int,PKT_UNIT> ::iterator it;
 it=maharan.begin();

 for(it=maharan.begin(); it != maharan.end(); it++ )
 {

  if (maharan.find(it)!=maharan.end())
  {
   if (it->second.len==1 && it->second.checksum==2 && it->second.data==3)
   cout<<"TRUE"<<endl;

  }

return 0;
}
</code>```

答:
You should overload the equality operator for PKT_UNIT. Then you should just use std::map::find to find what you are looking for.

```<code>bool operator==(const PKT_UNIT& lhs, const PKT_UNIT& rhs)
{
    return (lhs.len == rhs.len) &&
           (lhs.checksum == rhs.checksum) &&
           std::equal(lhs.data,lhs.data + PKT_UNIT_MAX_LEN,rhs.data);
}
</code>```

The  you can do something like this:

```<code>PKT_UNIT goal {1,2,3};
for (const auto& e : maharan)
{
    if (e.second == goal)
    {
        std::cout << "TRUE\n";
        break;
    }
}
</code>```

Also, as it seems you don't need the key, maybe you want to use std::set and use a search algorithm, or std::unordered_set, in which case you wouldn't need a search algorithm at all.

Title: search a structure element in map

Body:
i am new to C++(also english).
i want to search {1,2,3} in the map and if it exists , print TRUE on screen
but i can not
my code comes below
can you help me?

#include <iostream>
#include <map>
#include <iterator>
#define PKT_UNIT_MAX_LEN  10000
using namespace std;

struct PKT_UNIT
{
int len;
unsigned int checksum;
unsigned char data[PKT_UNIT_MAX_LEN];

};

int main()
{
 map<int,PKT_UNIT> maharan;
 maharan.insert(pair<int,PKT_UNIT>(1,{1,2,3}));

 map<int,PKT_UNIT> ::iterator it;
 it=maharan.begin();

 for(it=maharan.begin(); it != maharan.end(); it++ )
 {

  if (maharan.find(it)!=maharan.end())
  {
   if (it->second.len==1 && it->second.checksum==2 && it->second.data==3)
   cout<<"TRUE"<<endl;

  }

return 0;
}

Body:
You should overload the equality operator for PKT_UNIT. Then you should just use std::map::find to find what you are looking for.

bool operator==(const PKT_UNIT& lhs, const PKT_UNIT& rhs)
{
    return (lhs.len == rhs.len) &&
           (lhs.checksum == rhs.checksum) &&
           std::equal(lhs.data,lhs.data + PKT_UNIT_MAX_LEN,rhs.data);
}

The  you can do something like this:

PKT_UNIT goal {1,2,3};
for (const auto& e : maharan)
{
    if (e.second == goal)
    {
        std::cout << "TRUE\n";
        break;
    }
}

Also, as it seems you don't need the key, maybe you want to use std::set and use a search algorithm, or std::unordered_set, in which case you wouldn't need a search algorithm at all.


来源: stackexchange

问:
Spring bean scope for "one object per test method"
I have a test utility for with I need to have a fresh instance per test method (to prevent that state leaks between tests). So far, I was using the scope "prototype", but now I want to be able to wire the utility into another test utility, and the wired instances shall be the same per test.

This appears to be a standard problem, so I was wondering if there is a "test method" scope or something similar?

This is the structure of the test class and test utilities:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {

    @Autowired
    private TestDriver driver;

    @Autowired
    private TestStateProvider state;

    // ... state
    // ... methods
}
```

<pre class="lang-java prettyprint-override"><code>@Component
@Scope("prototype") // not right because MyTest and TestStateProvider get separate instances
public class TestDriver {
    // ...
}
</code>```

@Component
public class TestStateProvider {

    @Autowired
    private TestDriver driver;

    // ...
}
```

I'm aware that I could use @Scope("singleton") and @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) but this refreshes more than I need – a new TestDriver instance for each test would be enough. Also, this approach is error-prone because all tests using the TestDriver would need to know that they also need the @DirtiesContext annotation. So I'm looking for a better solution.

答:
I ran into the same problem some time ago and came to this solution:

Use Mocks

I wrote some methods to create specific mockito settings to add behavior to each mock.

So create a TestConfiguration class with following methods and bean definition.

```<code>    private MockSettings createResetAfterMockSettings() {
        return MockReset.withSettings(MockReset.AFTER);
    }

    private <T> T mockClass(Class<T> classToMock) {
        return mock(classToMock, createResetAfterMockSettings());
    }
</code>```

and your bean definition will look like:

```<code>@Bean
public TestDriver testDriver() {
    return mockClass(TestDriver .class);
}
</code>```

MockReset.AFTER is used to reset the mock after the test method is run.

And finally add a TestExecutionListeners to your Test class:

```<code>@TestExecutionListeners({ResetMocksTestExecutionListener.class})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a test utility for with I need to have a fresh instance per test method (to prevent that state leaks between tests). So far, I was using the scope "prototype", but now I want to be able to wire the utility into another test utility, and the wired instances shall be the same per test.

This appears to be a standard problem, so I was wondering if there is a "test method" scope or something similar?

This is the structure of the test class and test utilities:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {

    @Autowired
    private TestDriver driver;

    @Autowired
    private TestStateProvider state;

    // ... state
    // ... methods
}

@Component
@Scope("prototype") // not right because MyTest and TestStateProvider get separate instances
public class TestDriver {
    // ...
}

@Component
public class TestStateProvider {

    @Autowired
    private TestDriver driver;

    // ...
}

I'm aware that I could use @Scope("singleton") and @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) but this refreshes more than I need – a new TestDriver instance for each test would be enough. Also, this approach is error-prone because all tests using the TestDriver would need to know that they also need the @DirtiesContext annotation. So I'm looking for a better solution.

Body:
I ran into the same problem some time ago and came to this solution:

Use Mocks

I wrote some methods to create specific mockito settings to add behavior to each mock.

So create a TestConfiguration class with following methods and bean definition.

    private MockSettings createResetAfterMockSettings() {
        return MockReset.withSettings(MockReset.AFTER);
    }

    private <T> T mockClass(Class<T> classToMock) {
        return mock(classToMock, createResetAfterMockSettings());
    }

and your bean definition will look like:

@Bean
public TestDriver testDriver() {
    return mockClass(TestDriver .class);
}

MockReset.AFTER is used to reset the mock after the test method is run.

And finally add a TestExecutionListeners to your Test class:

@TestExecutionListeners({ResetMocksTestExecutionListener.class})


问:
Create JSON from SQL Query using PHP
I am attempting to output JSON in the following format:

```<code>[{
  "category": "cONTIME",
  "value": 155,
  "color": "#0f9b0f"
},{
  "category": "cLATE",
  "value": 244,
  "color": "#dd1818"
},{
  "category": "cTOTAL",
  "value": 399,
  "color": "#0575E6"
},{
  "category": "ONTIME",
  "value": 60,
  "color": "#0f9b0f"
},{
  "category": "LATE",
  "value": 58,
  "color": "#dd1818"
},{
  "category": "TOTAL",
  "value": 118,
  "color": "#0f9b0f"
}]
</code>```

The stored procedure I am executing returns the following table - This is SQL SERVER - I have greyed over the columns that are not of interest

I have attempted this by using

```<code>$categories = [
    'cONTIME' => $row['cONTIME'],
    'cLATE' => [],
    'cTOTAL' => [],
];
$colors = [
    'ONTIME' => "#0f9b0f",
    'LATE' => "#dd1818",
    'TOTAL' => "#0575E6",
];

$json = array();

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
        $json['category'] = $categories;
        $json['value'] = $row;
        $json['color'] = $colors;
}
echo json_encode($json);
</code>```

Returning this:

```<code>{
   "category":{
      "cONTIME":null,
      "cLATE":[

      ],
      "cTOTAL":[

      ]
   },
   "value":{
      "cTOTAL":399,
      "cONTIME":155,
      "cLATE":244,
      "cPERCENTS":38,
      "TOTAL":118,
      "ONTIME":60,
      "LATE":58,
      "PERCENTS":50,
      "KPI":"UP"
   },
   "color":{
      "ONTIME":"#0f9b0f",
      "LATE":"#dd1818",
      "TOTAL":"#0575E6"
   }
}
</code>```

I have also attempted this:

```<code>$json = array();

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
        $json[] = $row;
}
echo json_encode($json);
</code>```

Returning:

```<code>[
   {
      "cTOTAL":399,
      "cONTIME":155,
      "cLATE":244,
      "cPERCENTS":38,
      "TOTAL":118,
      "ONTIME":60,
      "LATE":58,
      "PERCENTS":50,
      "KPI":"UP"
   }
]
</code>```

As well as the above I have tried numerous other methods & examples but can't seem to achieve the format I need. I am fully aware of PDO, Prepared Statements, Injection etc!, I just need to format the JSON first, but thanks in advance for the advice

Any help would be greatly appreciated - PHP Noob

答:
Something like this should work:</p>

```<code>$json = array();

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
    foreach ($row as $fieldName => $fieldValue) {
        if (in_array($fieldName, ['cTOTAL', 'cONTIME', 'cLATE', 'TOTAL' ,'ONTIME', 'LATE'])) {
            $json[] = [
                "category" => $fieldName,
                "value" => $fieldValue,
                "color" => getColorByFieldName($fieldName),
            ];
        }
    }
}
echo json_encode($json);

function getColorByFieldName($fieldName)
{
    if ($fieldName === 'ONTIME' || $fieldName === 'cONTIME') {
        return '#0f9b0f';
    }
    if ($fieldName === 'LATE' || $fieldName === 'cLATE') {
        return '#dd1818';
    }
    if ($fieldName === 'TOTAL' || $fieldName === 'cTOTAL') {
        return '#0575E6';
    }
}
</code>```

Title: Create JSON from SQL Query using PHP

Body:
I am attempting to output JSON in the following format:

[{
  "category": "cONTIME",
  "value": 155,
  "color": "#0f9b0f"
},{
  "category": "cLATE",
  "value": 244,
  "color": "#dd1818"
},{
  "category": "cTOTAL",
  "value": 399,
  "color": "#0575E6"
},{
  "category": "ONTIME",
  "value": 60,
  "color": "#0f9b0f"
},{
  "category": "LATE",
  "value": 58,
  "color": "#dd1818"
},{
  "category": "TOTAL",
  "value": 118,
  "color": "#0f9b0f"
}]

The stored procedure I am executing returns the following table - This is SQL SERVER - I have greyed over the columns that are not of interest

I have attempted this by using

$categories = [
    'cONTIME' => $row['cONTIME'],
    'cLATE' => [],
    'cTOTAL' => [],
];
$colors = [
    'ONTIME' => "#0f9b0f",
    'LATE' => "#dd1818",
    'TOTAL' => "#0575E6",
];

$json = array();

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
        $json['category'] = $categories;
        $json['value'] = $row;
        $json['color'] = $colors;
}
echo json_encode($json);

Returning this:

{
   "category":{
      "cONTIME":null,
      "cLATE":[

      ],
      "cTOTAL":[

      ]
   },
   "value":{
      "cTOTAL":399,
      "cONTIME":155,
      "cLATE":244,
      "cPERCENTS":38,
      "TOTAL":118,
      "ONTIME":60,
      "LATE":58,
      "PERCENTS":50,
      "KPI":"UP"
   },
   "color":{
      "ONTIME":"#0f9b0f",
      "LATE":"#dd1818",
      "TOTAL":"#0575E6"
   }
}

I have also attempted this:

$json = array();

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
        $json[] = $row;
}
echo json_encode($json);

Returning:

[
   {
      "cTOTAL":399,
      "cONTIME":155,
      "cLATE":244,
      "cPERCENTS":38,
      "TOTAL":118,
      "ONTIME":60,
      "LATE":58,
      "PERCENTS":50,
      "KPI":"UP"
   }
]

As well as the above I have tried numerous other methods & examples but can't seem to achieve the format I need. I am fully aware of PDO, Prepared Statements, Injection etc!, I just need to format the JSON first, but thanks in advance for the advice

Any help would be greatly appreciated - PHP Noob

Body:
Something like this should work:

$json = array();

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
    foreach ($row as $fieldName => $fieldValue) {
        if (in_array($fieldName, ['cTOTAL', 'cONTIME', 'cLATE', 'TOTAL' ,'ONTIME', 'LATE'])) {
            $json[] = [
                "category" => $fieldName,
                "value" => $fieldValue,
                "color" => getColorByFieldName($fieldName),
            ];
        }
    }
}
echo json_encode($json);

function getColorByFieldName($fieldName)
{
    if ($fieldName === 'ONTIME' || $fieldName === 'cONTIME') {
        return '#0f9b0f';
    }
    if ($fieldName === 'LATE' || $fieldName === 'cLATE') {
        return '#dd1818';
    }
    if ($fieldName === 'TOTAL' || $fieldName === 'cTOTAL') {
        return '#0575E6';
    }
}


问:
How to sort an array starting from the middle?
Considering, I have an array like this [..., n-2, n-1, n, n+1, n+2, ...]. I would like to sort it in this way [n, n+1, n-1, n+2, n-2,...] with n equals to the middle of my array.

For example:

Input:

```<code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

Output:

```<code>[5, 6, 4, 7, 3, 8, 2, 9, 1, 0]
</code>```

let arrayNotSorted = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let positionMiddleArray = Math.trunc(arrayNotSorted.length / 2);

let arraySorted = [arrayNotSorted[positionMiddleArray]];

for(let i=1; i <= positionMiddleArray; i++){
 if(arrayNotSorted[positionMiddleArray + i] !== undefined){
  arraySorted.push(arrayNotSorted[positionMiddleArray + i]);
  }
  if(arrayNotSorted[positionMiddleArray - i] !== undefined){
   arraySorted.push(arrayNotSorted[positionMiddleArray - i]);
  }
}

console.log('Not_Sorted', arrayNotSorted);
console.log('Sorted', arraySorted);```

What I have done works properly, but I would like to know if there is a better way or a more efficient way to do so ?

答:
You can do that in following steps:

Create an empty array for result.

Start the loop. Initialize i to the half of the length.

Loop backwards means decrease i by 1 each loop.

push() the element at current index to the result array first and the other corresponding value to the array.

function sortFromMid(arr){
  let res = [];
  for(let i = Math.ceil(arr.length/2);i>=0;i--){
    res.push(arr[i]);
    res.push(arr[arr.length - i + 1])
  }
  return res.filter(x => x !== undefined);
}

console.log(sortFromMid([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

[5, 6, 4, 7, 3, 8, 2, 9, 1, 0]```

Body:
Considering, I have an array like this [..., n-2, n-1, n, n+1, n+2, ...]. I would like to sort it in this way [n, n+1, n-1, n+2, n-2,...] with n equals to the middle of my array.

For example:

Input:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Output:

[5, 6, 4, 7, 3, 8, 2, 9, 1, 0]

let arrayNotSorted = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let positionMiddleArray = Math.trunc(arrayNotSorted.length / 2);

let arraySorted = [arrayNotSorted[positionMiddleArray]];

for(let i=1; i <= positionMiddleArray; i++){
 if(arrayNotSorted[positionMiddleArray + i] !== undefined){
  arraySorted.push(arrayNotSorted[positionMiddleArray + i]);
  }
  if(arrayNotSorted[positionMiddleArray - i] !== undefined){
   arraySorted.push(arrayNotSorted[positionMiddleArray - i]);
  }
}

console.log('Not_Sorted', arrayNotSorted);
console.log('Sorted', arraySorted);

What I have done works properly, but I would like to know if there is a better way or a more efficient way to do so ?


问:
How can I add a class to leaflet layer groups?
I am making a game map with different layer groups. Everything works fine, but is it possible to add a class to the Layer groups as shown below?

The reason why is because I would like for example to place the second layer group on top of the first layer group. I know it is possible to  add a class and then changing the z-index, but I have no idea how to do this.

This is how I have set up the Layer groups currently.

```<code>// Layer Groups
var lg_locat = L.layerGroup([locat_001, locat_002, locat_003,
locat_004]).addTo(map);
var lg_quests = L.layerGroup([quest_001, quest_002, quest_003,
quest_004, quest_005, quest_006, quest_007]).addTo(map);
var lg_noticeboards = L.layerGroup([noticeboard_001,
noticeboard_002, noticeboard_003]).addTo(map);
var lg_treasures = L.layerGroup([treasure_001, treasure_002,
treasure_003, treasure_004, treasure_005]).addTo(map);
</code>```

Example of the map: http://www.droogjeproductions.nl/leaflet-map-test/index.html

答:
You can call the setZIndex() method on the layer groupe which is setting the z-index of each layer of the layer group

For exemple if lg_noticeboards are above quests which are above treasures which are above locat :

```<code> var lg_locat = L.layerGroup([locat_001, locat_002, locat_003,
locat_004]).addTo(map).setZIndex(1);
var lg_quests = L.layerGroup([quest_001, quest_002, quest_003,
quest_004, quest_005, quest_006, quest_007]).addTo(map).setZIndex(3);
var lg_noticeboards = L.layerGroup([noticeboard_001,
noticeboard_002, noticeboard_003]).addTo(map).setZIndex(4);
var lg_treasures = L.layerGroup([treasure_001, treasure_002,
treasure_003, treasure_004, treasure_005]).addTo(map).setZIndex(2);
</code>```

Something like that may work I think, if it doesn't try this:

```<code>lg_locat.setZIndex(1);
lg_quests.setZIndex(3);
lg_noticeboards.setZIndex(4);
lg_treasures.setZIndex(2);
</code>```

Body:
I am making a game map with different layer groups. Everything works fine, but is it possible to add a class to the Layer groups as shown below?

The reason why is because I would like for example to place the second layer group on top of the first layer group. I know it is possible to  add a class and then changing the z-index, but I have no idea how to do this.

This is how I have set up the Layer groups currently.

// Layer Groups
var lg_locat = L.layerGroup([locat_001, locat_002, locat_003,
locat_004]).addTo(map);
var lg_quests = L.layerGroup([quest_001, quest_002, quest_003,
quest_004, quest_005, quest_006, quest_007]).addTo(map);
var lg_noticeboards = L.layerGroup([noticeboard_001,
noticeboard_002, noticeboard_003]).addTo(map);
var lg_treasures = L.layerGroup([treasure_001, treasure_002,
treasure_003, treasure_004, treasure_005]).addTo(map);

Example of the map: http://www.droogjeproductions.nl/leaflet-map-test/index.html

Body:
You can call the setZIndex() method on the layer groupe which is setting the z-index of each layer of the layer group

For exemple if lg_noticeboards are above quests which are above treasures which are above locat :

 var lg_locat = L.layerGroup([locat_001, locat_002, locat_003,
locat_004]).addTo(map).setZIndex(1);
var lg_quests = L.layerGroup([quest_001, quest_002, quest_003,
quest_004, quest_005, quest_006, quest_007]).addTo(map).setZIndex(3);
var lg_noticeboards = L.layerGroup([noticeboard_001,
noticeboard_002, noticeboard_003]).addTo(map).setZIndex(4);
var lg_treasures = L.layerGroup([treasure_001, treasure_002,
treasure_003, treasure_004, treasure_005]).addTo(map).setZIndex(2);

Something like that may work I think, if it doesn't try this:

lg_locat.setZIndex(1);
lg_quests.setZIndex(3);
lg_noticeboards.setZIndex(4);
lg_treasures.setZIndex(2);


问:
Assert called with argument of specific type
I want to check in my test if a function is called with an argument of a specific class.

```<code>class Foo:
...
</code>```

I found mock.ANY, but there I cannot pass any class. What is want is:

```<code>test_mock.assert_called_with("expected string", ANY(spec=Foo))
</code>```

答:
Use a different test. The call_args attribute contains the arguments passed to the call; you can extract the desired argument, then check its type.

```<code># E.g. test_mock(1,"foo", bar=9) gives
# test_mock.call_args == ((1, "foo"), {"bar": 9})
assert isinstance(test_mock.call_args[1][1], Foo)
</code>```

Body:
I want to check in my test if a function is called with an argument of a specific class.

class Foo:
...

I found mock.ANY, but there I cannot pass any class. What is want is:

test_mock.assert_called_with("expected string", ANY(spec=Foo))

Body:
Use a different test. The call_args attribute contains the arguments passed to the call; you can extract the desired argument, then check its type.

# E.g. test_mock(1,"foo", bar=9) gives
# test_mock.call_args == ((1, "foo"), {"bar": 9})
assert isinstance(test_mock.call_args[1][1], Foo)


问:
T SQL Cursor is only updating row with same value
I'm using MS SQL Server and I have the below table 'tmp_AVG_Weekly_Sales':

```<code>RowID   SKU   Shop  Week   Avg_Value   LAMBDA    PMF      Value
  1     ABC   200    2       1          2        0.13     NULL
  2     DEF   250    2       2          4        0.018    NULL
  3     XYZ   300    3       3          6        0.0024   NULL
</code>```

I need to work out the Value field based on the below logic - I am using a Cursor and Loop:

```<code>DECLARE @CUMULATIVE AS FLOAT = 0;
DECLARE @COUNT AS INT = 0;
DECLARE @LAMBDA AS FLOAT;
DECLARE @RowID AS INT;
DECLARE @PoissonCursor AS CURSOR;
DECLARE @THRESHOLD AS FLOAT = 0.99;
DECLARE @PMF AS FLOAT --= EXP(-@LAMBDA)

SET @PoissonCursor = CURSOR FOR

SELECT RowID
FROM
[tmp_AVG_Weekly_Sales]

OPEN @PoissonCursor;

FETCH NEXT FROM @PoissonCursor INTO @RowID;

WHILE @@FETCH_STATUS = 0

BEGIN

    SELECT @LAMBDA = LAMBDA FROM [tmp_AVG_Weekly_Sales] WHERE RowID = @RowID

    SELECT @PMF = PMF FROM [tmp_AVG_Weekly_Sales] WHERE RowID = @RowID

    WHILE (@CUMULATIVE < @Threshold)

    BEGIN
        SET @CUMULATIVE += @PMF
        SET @COUNT += 1
        SET @PMF = @PMF * (@LAMBDA / @COUNT)

        END

        UPDATE [tmp_AVG_Weekly_Sales] SET [Value] = @COUNT - 1 WHERE RowID = @RowID

    FETCH NEXT FROM @PoissonCursor  INTO @RowID;

END
</code>```

However, the above is just populating the Value field with the same value:

```<code>RowID   SKU   Shop  Week   Avg_Value   LAMBDA    PMF      Value
  1     ABC   200    2       1          2        0.13     6
  2     DEF   250    2       2          4        0.018    6
  3     XYZ   300    3       3          6        0.0024   6
</code>```

When I am expecting the below:

```<code>RowID   SKU   Shop  Week   Avg_Value   LAMBDA    PMF      Value
  1     ABC   200    2       1          2        0.13     6
  2     DEF   250    2       2          4        0.018    9
  3     XYZ   300    3       3          6        0.0024   12
</code>```

Where am I going wrong?

答: You never reset @CUMULATIVE or increase @Threshold, so the block of SET calls are only executed the first go through and each subsequent UPDATE just uses those original values.

Body:
I'm using MS SQL Server and I have the below table 'tmp_AVG_Weekly_Sales':

RowID   SKU   Shop  Week   Avg_Value   LAMBDA    PMF      Value
  1     ABC   200    2       1          2        0.13     NULL
  2     DEF   250    2       2          4        0.018    NULL
  3     XYZ   300    3       3          6        0.0024   NULL

I need to work out the Value field based on the below logic - I am using a Cursor and Loop:

DECLARE @CUMULATIVE AS FLOAT = 0;
DECLARE @COUNT AS INT = 0;
DECLARE @LAMBDA AS FLOAT;
DECLARE @RowID AS INT;
DECLARE @PoissonCursor AS CURSOR;
DECLARE @THRESHOLD AS FLOAT = 0.99;
DECLARE @PMF AS FLOAT --= EXP(-@LAMBDA)

SET @PoissonCursor = CURSOR FOR

SELECT RowID
FROM
[tmp_AVG_Weekly_Sales]

OPEN @PoissonCursor;

FETCH NEXT FROM @PoissonCursor INTO @RowID;

WHILE @@FETCH_STATUS = 0

BEGIN

    SELECT @LAMBDA = LAMBDA FROM [tmp_AVG_Weekly_Sales] WHERE RowID = @RowID

    SELECT @PMF = PMF FROM [tmp_AVG_Weekly_Sales] WHERE RowID = @RowID

    WHILE (@CUMULATIVE < @Threshold)

    BEGIN
        SET @CUMULATIVE += @PMF
        SET @COUNT += 1
        SET @PMF = @PMF * (@LAMBDA / @COUNT)

        END

        UPDATE [tmp_AVG_Weekly_Sales] SET [Value] = @COUNT - 1 WHERE RowID = @RowID

    FETCH NEXT FROM @PoissonCursor  INTO @RowID;

END

However, the above is just populating the Value field with the same value:

RowID   SKU   Shop  Week   Avg_Value   LAMBDA    PMF      Value
  1     ABC   200    2       1          2        0.13     6
  2     DEF   250    2       2          4        0.018    6
  3     XYZ   300    3       3          6        0.0024   6

When I am expecting the below:

RowID   SKU   Shop  Week   Avg_Value   LAMBDA    PMF      Value
  1     ABC   200    2       1          2        0.13     6
  2     DEF   250    2       2          4        0.018    9
  3     XYZ   300    3       3          6        0.0024   12

Where am I going wrong?


问:
Run a macro when a pivot table changes
Is there any way to detect when a pivot table changes, filters are set, in VBA?

I have a macro I would like to automatically run when the user changes the filters of the pivot table.

答:
Try:</p>

```<code>Option Explicit

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)

    'Check if is the right pivot changed
    If Target.Name = "PivotTable1" Then
        ' some code here
    End If

End Sub
</code>```

Title: Run a macro when a pivot table changes

Body:
Try:

Option Explicit

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)

    'Check if is the right pivot changed
    If Target.Name = "PivotTable1" Then
        ' some code here
    End If

End Sub


问:
How to create notifyIcon without Form?
I added notifyIcon to the container and set Visible = true option, but no icon appeared.</p>

```<code>private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
            this.SuspendLayout();
            //
            // notifyIcon1
            //
            this.notifyIcon1.Text = "Manager";
            this.notifyIcon1.Visible = true;
            //
            // Form1
            //
            this.ClientSize = new System.Drawing.Size(0, 0);
            this.ShowInTaskbar = false;
            this.Visible = false;

        }
</code>```

答:
notify Icon is shown when form is minimize. Try this</p>

```<code> this.WindowState = FormWindowState.Minimized;
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to create notifyIcon without Form?

Body:
I added notifyIcon to the container and set Visible = true option, but no icon appeared.

private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
            this.SuspendLayout();
            //
            // notifyIcon1
            //
            this.notifyIcon1.Text = "Manager";
            this.notifyIcon1.Visible = true;
            //
            // Form1
            //
            this.ClientSize = new System.Drawing.Size(0, 0);
            this.ShowInTaskbar = false;
            this.Visible = false;

        }

Body:
notify Icon is shown when form is minimize. Try this

 this.WindowState = FormWindowState.Minimized;


问:
I need to add a carousel that works as a slideshow
So I am trying to add a carousel but images will come one by one on top of each other

I have tried the bootstrap.com/carousels

```<code><div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="ninjago3.jpg" class="d-block w-100" alt="...">
    </div>
    <div class="carousel-item">
      <img src="..." class="d-block w-100" alt="...">
    </div>
    <div class="carousel-item">
      <img src="..." class="d-block w-100" alt="...">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
</code>```

Images come one by one.

答:
You might have missed to include Bootstrap dependency CSS, JS and Jquery files.

Replace image source with images you needed for your carousel.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    Previous

    Next

```

Body:
So I am trying to add a carousel but images will come one by one on top of each other

I have tried the bootstrap.com/carousels

    Previous

    Next

Images come one by one.

Body:
You might have missed to include Bootstrap dependency CSS, JS and Jquery files.

Replace image source with images you needed for your carousel.

<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="https://www.gstatic.com/webp/gallery/1.jpg" class="d-block w-100" alt="...">
    </div>
    <div class="carousel-item">
      <img src="https://www.gstatic.com/webp/gallery/2.jpg" class="d-block w-100" alt="...">
    </div>
    <div class="carousel-item">
      <img src="https://www.gstatic.com/webp/gallery/4.jpg" class="d-block w-100" alt="...">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
</body>
</html>


问:
Using the SUMMARIZE function in a MAXX calculation

I am trying to aggregate the following values (NHS, Social Care and Both B) by the  reasons for delays column so i can find the reason with the highest value (from the 3 combined values named above).

I have tried using summarize to create a table with just the reasons for delays ,NHS, Social Care and Both B columns. By doing this i hoped i could create a column named totals which adds the NHS, Social Care and Both B Columns together in this summarized table thus giving me the total values for each reason for delay.

Though when i tried to run a maxx function around my totals column it seems to give me the wrong values.

I have tried wrapping my table with the distinct function so it aggregates all the columns in my summarize together, but this did not help either.

```<code>Max Delays =
MAXX (
    SUMMARIZE (
        csv,
        csv[Reason For Delay],
        csv[NHS],
        csv[Social Care],
        csv[Both B],
        "totals", CALCULATE ( SUM ( csv[NHS] ) + SUM ( csv[Both B] ) + SUM ( csv[Social Care] ) )
    ),
    [totals]
)
</code>```

The smaller table (which should represent the summarized table) in the above picture with the total column shows the values i expect to carry my max calculation over, where i expect the max value to be 277.

The max value i am getting instead is 182. This is the max value in the unsummarized table below where i have multiple duplicates of my reasons for delay column and 182 is the highest value.

I have uploaded a sample of the pbix file i am working on if it may be of help;https://www.zeta-uploader.com/en/1184250523

答:
First, create a measure for total reasons:

```<code>Total Reasons = SUM(csv[NHS]) + SUM(csv[Both B]) + SUM(csv[Social Care])
</code>```

Second, create a measure for the max reason:

```<code>Max Reason = MAXX( VALUES(csv[Reason For Delay]), [Total Reasons])
</code>```

Result:

How it works:

The first measure is for convenience. You can re-use it in other formulas, making code cleaner;

In the second measure, we create a list of distinct reasons using VALUES. Then MAXX iterates this list, calculates total for each reason, and then finds the largest of them.

Body:
I am trying to aggregate the following values (NHS, Social Care and Both B) by the  reasons for delays column so i can find the reason with the highest value (from the 3 combined values named above).

I have tried using summarize to create a table with just the reasons for delays ,NHS, Social Care and Both B columns. By doing this i hoped i could create a column named totals which adds the NHS, Social Care and Both B Columns together in this summarized table thus giving me the total values for each reason for delay.

Though when i tried to run a maxx function around my totals column it seems to give me the wrong values.

I have tried wrapping my table with the distinct function so it aggregates all the columns in my summarize together, but this did not help either.

Max Delays =
MAXX (
    SUMMARIZE (
        csv,
        csv[Reason For Delay],
        csv[NHS],
        csv[Social Care],
        csv[Both B],
        "totals", CALCULATE ( SUM ( csv[NHS] ) + SUM ( csv[Both B] ) + SUM ( csv[Social Care] ) )
    ),
    [totals]
)

The smaller table (which should represent the summarized table) in the above picture with the total column shows the values i expect to carry my max calculation over, where i expect the max value to be 277.

The max value i am getting instead is 182. This is the max value in the unsummarized table below where i have multiple duplicates of my reasons for delay column and 182 is the highest value.

I have uploaded a sample of the pbix file i am working on if it may be of help;https://www.zeta-uploader.com/en/1184250523

Body:
First, create a measure for total reasons:

Total Reasons = SUM(csv[NHS]) + SUM(csv[Both B]) + SUM(csv[Social Care])

Second, create a measure for the max reason:

Max Reason = MAXX( VALUES(csv[Reason For Delay]), [Total Reasons])

Result:

How it works:

The first measure is for convenience. You can re-use it in other formulas, making code cleaner;

In the second measure, we create a list of distinct reasons using VALUES. Then MAXX iterates this list, calculates total for each reason, and then finds the largest of them.


问:
How to get Glue development endpoint URL inside CloudFormation template?
I'm trying to write a CloudFormation template that creates:

Glue development endpoint (type AWS::Glue::DevEndpoint); and

EC2 instance with Zeppelin notebook connected to the created endpoint.

The second resource requires endpoint URL. AWS::Glue::DevEndpoint provides endpoint name in the output, but it's not clear how to fetch the URL.

The only solution I found so far is to introduce aws glue get-dev-endpoint command and parse its output at some point of instance initialization process.

答:
As of May 2019, Cloudformation does not support retrieving the public address out of a AWS::Glue::DevEndpoint resource.

As you suggested in the question, you can get the dev endpoint name from CF and pass that to an AWS CLI command in the user data of an EC2 instance which is probably the best way to retrieve that.

I think the model error you are getting with the glue CLI may be resolved if you ensure you are using the latest version of the AWS CLI before you run the command.  This error makes it sound like there is some sort of config issue with the glue service in the CLI.

```<code>Resources:
   MyDevEndpoint:
      Type: AWS::Glue::DevEndpoint
      Properties:
         ...

   MyInstance:
      Type: AWS::EC2::Instance
      Properties:
         ...
         UserData:
            Fn::Base64: !Sub |
               aws --version
               yes | pip3 install awscli --upgrade --user
               aws --version
               ENDPOINT_NAME=${MyDevEndpoint}
               aws glue get-dev-endpoint --endpoint-name $ENDPOINT_NAME
               ...

</code>```

Body:
As of May 2019, Cloudformation does not support retrieving the public address out of a AWS::Glue::DevEndpoint resource.

As you suggested in the question, you can get the dev endpoint name from CF and pass that to an AWS CLI command in the user data of an EC2 instance which is probably the best way to retrieve that.

I think the model error you are getting with the glue CLI may be resolved if you ensure you are using the latest version of the AWS CLI before you run the command.  This error makes it sound like there is some sort of config issue with the glue service in the CLI.

Resources:
   MyDevEndpoint:
      Type: AWS::Glue::DevEndpoint
      Properties:
         ...

   MyInstance:
      Type: AWS::EC2::Instance
      Properties:
         ...
         UserData:
            Fn::Base64: !Sub |
               aws --version
               yes | pip3 install awscli --upgrade --user
               aws --version
               ENDPOINT_NAME=${MyDevEndpoint}
               aws glue get-dev-endpoint --endpoint-name $ENDPOINT_NAME
               ...


问:
How to use $arrayElemAt operator in Spring Data MongoDB
$arrayElemAt new in MongoDB version 3.2.

```<code>db.users.aggregate([
{
 $project:
  {
     name: 1,
     first: { $arrayElemAt: [ "$favorites", 0 ] },
     last: { $arrayElemAt: [ "$favorites", -1 ] }
  }
}
</code>```

])

答:
Even more concise, you can even use $arrayElementAt as follows:

```<code>project("name")
  .and("favorites").arrayElementAt(0).as("first")
  .and("favorites").arrayElementAt(-1).as("last")
</code>```

Body:
$arrayElemAt new in MongoDB version 3.2.

db.users.aggregate([
{
 $project:
  {
     name: 1,
     first: { $arrayElemAt: [ "$favorites", 0 ] },
     last: { $arrayElemAt: [ "$favorites", -1 ] }
  }
}

])

Body:
Even more concise, you can even use $arrayElementAt as follows:

project("name")
  .and("favorites").arrayElementAt(0).as("first")
  .and("favorites").arrayElementAt(-1).as("last")


问:
For fingerprint use in api<28 ...what should i use...Fingerprint Manager otlr BiometricPrompt?
I tried to add biometric prompt but that's not working
It shows that BiometricPrompt can't be instantiated...because its not public class.
I m using java in android studio</p>

答:
Declare permission in Manifest </p>

```<code> <uses-permission android:name="android.permission.USE_BIOMETRIC"/>
</code>```

<p> </p>

Body:
Declare permission in Manifest

 <uses-permission android:name="android.permission.USE_BIOMETRIC"/>


问:
How to echo a function in php using button?
I am making an event calendar.I want to echo a function in php using button.

My actual code:

Calendar.php

```<code><?php include_once('functions.php'); ?>
<?php echo getCalender(); ?>
</code>```

functions.php

```<code><?php

if(isset($_POST['func']) && !empty($_POST['func'])){
    switch($_POST['func']){
        case 'getCalender':
            getCalender($_POST['year'],$_POST['month']);
            break;
        case 'getEvents':
            getEvents($_POST['date']);
            break;
        default:
            break;
    }
}
//Get calendar full HTML
function getCalender($year = '',$month = '')
{
    $dateYear = ($year != '')?$year:date("Y");
    $dateMonth = ($month != '')?$month:date("m");
    $date = $dateYear.'-'.$dateMonth.'-01';
    $currentMonthFirstDay = date("N",strtotime($date));
    $totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
    $totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
    $boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
?>
    <div id="calender_section">
    //
}
 <script type="text/javascript">
    function getCalendar(target_div,year,month){
        $.ajax({
            type:'POST',
            url:'functions.php',
            data:'func=getCalender&year='+year+'&month='+month,
            success:function(html){
                $('#'+target_div).html(html);
            }
        });
    }

function getEvents(date){
        $.ajax({
            type:'POST',
            url:'functions.php',
            data:'func=getEvents&date='+date,
            success:function(html){
                $('#event_list').html(html);
                $('#event_add').slideUp('slow');
                $('#event_list').slideDown('slow');
            }
        });
    }
</code>```

Now I want to use button to call the getcalendar function. I've tried this:

Calendar.php

```<code> <form class="" action="" method="post">
               <input type="button" value="Dhaka" onclick="<?php echo getCalender(); ?>"/>
              </form>
</code>```

Now this is not waitiing for button click. When I refresh the page it is showing the calendat even if i didn't click the button.
How can I solve this?

答:
Here is the code for functions.php. You mentioned getCalender instead of getCalendar

```<code><?php include_once('functions.php'); ?>
<form class="" action="" method="post">
<input type="button" value="Dhaka" onclick="getCalendar()"/>
</form>
</code>```

Also, close the script tag in the functions.php file after the getEvents function.

Body:
I am making an event calendar.I want to echo a function in php using button.

My actual code:

Calendar.php

<?php include_once('functions.php'); ?>
<?php echo getCalender(); ?>

functions.php

<?php

if(isset($_POST['func']) && !empty($_POST['func'])){
    switch($_POST['func']){
        case 'getCalender':
            getCalender($_POST['year'],$_POST['month']);
            break;
        case 'getEvents':
            getEvents($_POST['date']);
            break;
        default:
            break;
    }
}
//Get calendar full HTML
function getCalender($year = '',$month = '')
{
    $dateYear = ($year != '')?$year:date("Y");
    $dateMonth = ($month != '')?$month:date("m");
    $date = $dateYear.'-'.$dateMonth.'-01';
    $currentMonthFirstDay = date("N",strtotime($date));
    $totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
    $totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
    $boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
?>

    //
}

Body:
Here is the code for functions.php. You mentioned getCalender instead of getCalendar

<?php include_once('functions.php'); ?>
<form class="" action="" method="post">
<input type="button" value="Dhaka" onclick="getCalendar()"/>
</form>

Also, close the script tag in the functions.php file after the getEvents function.


问:
Convert TSV to CSV, where TSV field has commas in it
I have a TSV with fields that look like:

```<code>name   location   1,2,3,4,5
</code>```

When I use sed 's/\w/,/g'
i end up with a csv where 1,2,3,4 and 5 are considered seperate entrys.
I would like it to be '1 2 3 4 5'
I've tried converting commas to white space before running the above command using

```<code>sed 's/,/\w/g'
</code>```

however when converting the whitespace back to commas it includes single white spaces as well as the tabs, so what is the regex for just a single whitespace character?

Desired output:

```<code>name, location,1 2 3 4 5,
</code>```

答:
Either replace tabs with "," and enclose lines between double quotes, or replace commas with spaces and tabs with commas. In both cases you'll get valid CSV.

```<code>$ cat file
name    location        1,2,3,4,5
$
$ sed 's/\t/","/g; s/^\|$/"/g' file
"name","location","1,2,3,4,5"
$
$ sed 's/,/ /g; s/\t/,/g' file
name,location,1 2 3 4 5
</code>```

Body:
I have a TSV with fields that look like:

name   location   1,2,3,4,5

When I use sed 's/\w/,/g'
i end up with a csv where 1,2,3,4 and 5 are considered seperate entrys.
I would like it to be '1 2 3 4 5'
I've tried converting commas to white space before running the above command using

sed 's/,/\w/g'

however when converting the whitespace back to commas it includes single white spaces as well as the tabs, so what is the regex for just a single whitespace character?

Desired output:

name, location,1 2 3 4 5,

Body:
Either replace tabs with "," and enclose lines between double quotes, or replace commas with spaces and tabs with commas. In both cases you'll get valid CSV.

$ cat file
name    location        1,2,3,4,5
$
$ sed 's/\t/","/g; s/^\|$/"/g' file
"name","location","1,2,3,4,5"
$
$ sed 's/,/ /g; s/\t/,/g' file
name,location,1 2 3 4 5


问:
Segmenting a df based on condition shows nan values in jupyter
Using df[columns][df[colums]<0.5] to segment a DataFrame in Pandas usually only showed me the rows matching this condition.

Just recently I end up getting NaN - Values shown:

Was there an update I'm missing or what is causing this behaviour usually?

Dropping all NaN with .dropna() is obviously a fast solution to this issue, but doesn't explain the change in "behaviour".

Fix: Don't put columns in double brackets..

答:
If need compare by one column and filter by multiple columns use DataFrame.loc with boolean indexing:

```<code>df.loc[df['district-heating'] < 0.5, ['id','district-heating']]
</code>```

Body:
If need compare by one column and filter by multiple columns use DataFrame.loc with boolean indexing:

df.loc[df['district-heating'] < 0.5, ['id','district-heating']]


问:
Unable to fetch page properties in the head script
I am trying to get a page property in the head of my page basically to make it universally available so that the front end developers can use it in their scripts as they will.

This is on AEM 6.3. And I've already tried to include a script in the head.html but it can't read the page properties in a script tag.

```<code><script>
    window.myAppEndpoint = {
        baseURL: "${properties.myappendpoint}"
    };
</script>
</code>```

I expect the window object to populate with my endpoint value be able to use it anywhere in the application.

答:
You can create a global object in js and include that js in the clientlib at the template level.
Or use the global objects available in HTL. Please have a look here.</p>

Body:
I am trying to get a page property in the head of my page basically to make it universally available so that the front end developers can use it in their scripts as they will.

This is on AEM 6.3. And I've already tried to include a script in the head.html but it can't read the page properties in a script tag.

I expect the window object to populate with my endpoint value be able to use it anywhere in the application.


问:
Sharing data types from multiple Web References
Say a vendor has provided two separate webservices, which both share the same data types and same namespace.

e.g.
The following webservices both contain similar objects, such as a TestCredentials object:

TestWebservice/Testwebservice1.asmx

TestWebservice/Testwebservice2.asmx

Including these into Visual Studio using web references I end up with:

Testwebservice1.TestCredentials

Testwebservice2.TestCredentials

When what I really want is:

Testwebservice.TestCredentials

Is there any way in Visual Studio, when dealing with the web references, to link these two webservices together so that the proxy classes that are generated are the same (and within the same namespace)?

答:
You can create a simple .disco file that references all the web services. It is just a simple contractRef for each web service.

Visual studio will share the types as long as they are using the same xml namespace.

OwnerDisplayName: cheezdog

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Freddy Rios


问:
Hibernate first level caching
I want to know how load and get works with first level caching.

If I have a select query with in the same session with first retrieving using getmethod and then using load method. Will the 2nd load method use the query cache or will make a new query on retrieval of properties?

答:
The cache is primary used when:

calling session.get

calling session.load

when (lazy) loading many-to-one and one-to-one relations

If there isn't a hit, get performs a query, load creates a proxy.

When performing any kind of query (HQL, criteria), the query is translated to SQL and performed on the database. If the resulting objects are found in the cache, the query will return them.

Title: Hibernate first level caching


问:
Element available for more groups than one
For example I have the button in my template that is available only for stuff:

```<code>{% if request.user.is_staff %}
<a href="{% url 'unosZanraKnjige' %}" class="button">Add new</a>
{% endif %}
</code>```

I have group created in http://127.0.0.1:8000/admin/ called "Djelatnici".

Is it possible to make some element (button in this case) available only for specific groups with "OR" (||) condition, something like:

```<code>{% if request.user.is_staff %} || {% if request.user.is_djelatnici %}
<a href="{% url 'unosZanraKnjige' %}" class="button">Add new</a>
{% endif %}
</code>```

答:
You can do that using Django Custom Template tags

Something like this:

my_custom_tag.py

@register.filter(name='is_my_custom_group')
def is_my_custom_group(user, group_name):
    return user.groups.filter(name=group_name).exists()
```

<p>Then on your template you import this tag and use like this:</p>

<p><strong>template.html</strong></p>

<pre class="lang-html prettyprint-override"><code>{% load is_my_custom_group %}

{% if request.user.is_staff or request.user|is_my_custom_group:'Djelatnici' %}
    Add new
{% endif %}

</code>```

Body:
For example I have the button in my template that is available only for stuff:

{% if request.user.is_staff %}
Add new
{% endif %}

I have group created in http://127.0.0.1:8000/admin/ called "Djelatnici".

Is it possible to make some element (button in this case) available only for specific groups with "OR" (||) condition, something like:

{% if request.user.is_staff %} || {% if request.user.is_djelatnici %}
Add new
{% endif %}

Body:
You can do that using Django Custom Template tags

Something like this:

my_custom_tag.py

@register.filter(name='is_my_custom_group')
def is_my_custom_group(user, group_name):
    return user.groups.filter(name=group_name).exists()

Then on your template you import this tag and use like this:

template.html

{% load is_my_custom_group %}

{% if request.user.is_staff or request.user|is_my_custom_group:'Djelatnici' %}
    <a href="{% url 'unosZanraKnjige' %}" class="button">Add new</a>
{% endif %}


问:
Code signing with signtool fails due to private key filter
While trying to sign some installer created by the company I am working for I encountered an error, which I have not been able to solve. I am using the same certificate which has been used on another machine (Win7) successfully in the same way for signing quasi the same installer. Anyway, on our Windows Server 2008 which is running CruiseControl.net I tried to sign an installer with signtool.exe and it fails with the following error:

```<code>The following certificates were considered:
    Issued to: <our company>
    Issued by: <some ca>
    Expires:   <is valid>
    SHA1 hash: <...>

    Issued to: <...>
    Issued by: <...>
    Expires:   <...>
    SHA1 hash: <...>

After EKU filter, 1 certs were left.
After expiry filter, 1 certs were left.
After Subject Name filter, 1 certs were left.
After Private Key filter, 0 certs were left.
SignTool Error: No certificates were found that met all the given criteria.
</code>```

I tried installing the certificate to different certificate stores, tried different versions of signtool.exe and tried to use the .cer file directly, but it made no difference. I am receiving the error mentioned above in all of the cases. I tried the following command line commands

```<code>signtool.exe sign /debug /n "MyCompany" C:\my\installer.exe
signtool.exe sign /debug /f C:\path\to\my\certificate.cer C:\my\installer.exe
</code>```

but I left the /debug away in some cases. Is there anything I am doing wrong or missing?

答:
I had same problem as mentioned. This is what I did - assuming you have setup the rest of the pre-requisites for code signing.

Closed the solution and closed the VS IDE

Launched the Visual Studio IDE with Run as Administrator privileges

Open the solution and rebuild it

This time the signing process was successful.

I presume you have the right cert file and private key for signing and also imported the cert to the Trusted store.

If not, you can continue to read more.

Import the pfx file - "xyz.pfx" :: Open command prompt (launch - Run
as Administrator privileges) and run the following command

certutil.exe -p mypassword -importpfx xyz.pfx

An output from the command is shown below as example:

Certificate "CN=Name of the Cert, O=BLAH, OU=BLAH, E=john.doe@yourorg.com" added to
  store.
  CertUtil: -importPFX command completed successfully.

Add the certificate to the Trusted Root Certification Authorities by using the following command. There are many ways to do but I used this. Open command prompt (launch - Run as Administrator privileges) and run the following command

certmgr.exe -add -c mycertificate.cer -s -r localMachine root

You will see an output message like this

CertMgr Succeeded

Sign the assembly. Simple process from Visual Studio IDE.

Right click the Project in your solution and open its properties.

Open Signing section and click on Sign the Assembly check box (Enable it)

Choose the pfx file using Browse option and enter the password

```you can also create a new one but you need a cert file that match to this pfx file, otherwise your signing will fail.```

Save the changes

Now, Click on Build Events section and click Edit Post-Build to open the editor for post build events. Enter the following command.

"C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64\signtool.exe" sign /v /sm "$(TargetPath)"

Path of the signtool.exe depends on where/whether you have installed the Windows SDK.

Now build the solution, your solution should build successfully and your binaries signed. Ensure to run the VS IDE with Administrator privileges.

Body:
While trying to sign some installer created by the company I am working for I encountered an error, which I have not been able to solve. I am using the same certificate which has been used on another machine (Win7) successfully in the same way for signing quasi the same installer. Anyway, on our Windows Server 2008 which is running CruiseControl.net I tried to sign an installer with signtool.exe and it fails with the following error:

The following certificates were considered:
    Issued to: <our company>
    Issued by: <some ca>
    Expires:   <is valid>
    SHA1 hash: <...>

    Issued to: <...>
    Issued by: <...>
    Expires:   <...>
    SHA1 hash: <...>

After EKU filter, 1 certs were left.
After expiry filter, 1 certs were left.
After Subject Name filter, 1 certs were left.
After Private Key filter, 0 certs were left.
SignTool Error: No certificates were found that met all the given criteria.

I tried installing the certificate to different certificate stores, tried different versions of signtool.exe and tried to use the .cer file directly, but it made no difference. I am receiving the error mentioned above in all of the cases. I tried the following command line commands

signtool.exe sign /debug /n "MyCompany" C:\my\installer.exe
signtool.exe sign /debug /f C:\path\to\my\certificate.cer C:\my\installer.exe

but I left the /debug away in some cases. Is there anything I am doing wrong or missing?

Body:
I had same problem as mentioned. This is what I did - assuming you have setup the rest of the pre-requisites for code signing.

Closed the solution and closed the VS IDE

Launched the Visual Studio IDE with Run as Administrator privileges

Open the solution and rebuild it

This time the signing process was successful.

I presume you have the right cert file and private key for signing and also imported the cert to the Trusted store.

If not, you can continue to read more.

Import the pfx file - "xyz.pfx" :: Open command prompt (launch - Run
as Administrator privileges) and run the following command

certutil.exe -p mypassword -importpfx xyz.pfx

An output from the command is shown below as example:

Certificate "CN=Name of the Cert, O=BLAH, OU=BLAH, E=john.doe@yourorg.com" added to
  store.
  CertUtil: -importPFX command completed successfully.

Add the certificate to the Trusted Root Certification Authorities by using the following command. There are many ways to do but I used this. Open command prompt (launch - Run as Administrator privileges) and run the following command

certmgr.exe -add -c mycertificate.cer -s -r localMachine root

You will see an output message like this

CertMgr Succeeded

Sign the assembly. Simple process from Visual Studio IDE.

Right click the Project in your solution and open its properties.

Open Signing section and click on Sign the Assembly check box (Enable it)

Choose the pfx file using Browse option and enter the password

you can also create a new one but you need a cert file that match to this pfx file, otherwise your signing will fail.

Save the changes

Now, Click on Build Events section and click Edit Post-Build to open the editor for post build events. Enter the following command.

"C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64\signtool.exe" sign /v /sm "$(TargetPath)"

Path of the signtool.exe depends on where/whether you have installed the Windows SDK.

Now build the solution, your solution should build successfully and your binaries signed. Ensure to run the VS IDE with Administrator privileges.


问:
Materialize v1.0.0 hide-on-med-and-down not working in chrome
hide-on-med-and-down works fine in firefox 68.0b1 and safari 12.1 which means that with a screen width <= 992px my ul with the class .hide-on-med-and-down is not shown and when > 992px, it is shown as expected. As this menu appears in chrome with another code, it is seems not related to the chrome browser.

BUT on chrome only, when the screen is > 992px, the content of the ul keep not showing! But with another

I have tried the replace the class hide-on-med-and-down with show-on-large but the result is also unexpected (the ul keep showing on small screen).

```<code><nav class="teal">
    <div class="container">
      <div class="nav-wrapper">
       <a href="#home" class="brand-logo">AMV</a>
       <a href="#" data-target="mobile-nav" class="sidenav-trigger>
          <i class="material-icons">menu</i>
        </a>
        <ul class="right hide-on-med-and-down">
          <li>
            <a href="<?php echo URLROOT; ?>">Home</a>
          </li>
          <li>
            <a href="<?php echo URLROOT; ?>/pages/about">About</a>
          </li>
          <li>
            <a href="<?php echo URLROOT; ?>pages/contact">Contact</a>
          </li>
        </ul>
        </div>
    </div>
  </nav>

        <ul class="sidenav " id="mobile-nav">
          <li>
            <a href="<?php echo URLROOT; ?>">Home</a>
          </li>
          <li>
            <a href="<?php echo URLROOT; ?>/pages/about">About</a>
          </li>

          <li>
            <a href="<?php echo URLROOT; ?>/pages/contact">Contact</a>
          </li>
        </ul>

    <script type="text/javascript" src="js/materialize.js">
    $(document).ready(function(){
    $('.sidenav').sidenav();
    });
    </script>
</code>```

答: The issue was related to the screen who was magnified and I did not care about this parameter. As I reset the zoom to 100%, the menu was showie as expected.</p>

Body:
hide-on-med-and-down works fine in firefox 68.0b1 and safari 12.1 which means that with a screen width <= 992px my ul with the class .hide-on-med-and-down is not shown and when > 992px, it is shown as expected. As this menu appears in chrome with another code, it is seems not related to the chrome browser.

BUT on chrome only, when the screen is > 992px, the content of the ul keep not showing! But with another

I have tried the replace the class hide-on-med-and-down with show-on-large but the result is also unexpected (the ul keep showing on small screen).

       AMV

          menu

            <a href="<?php echo URLROOT; ?>">Home

            <a href="<?php echo URLROOT; ?>/pages/about">About

            <a href="<?php echo URLROOT; ?>pages/contact">Contact

            <a href="<?php echo URLROOT; ?>">Home

            <a href="<?php echo URLROOT; ?>/pages/about">About

            <a href="<?php echo URLROOT; ?>/pages/contact">Contact


问:
FormData key does not go through
I use external class for making object variable into FormData variable. All of the keys go through, all but One for File object.

Here is that external class: https://github.com/therealparmesh/object-to-formdata

This is how I create objects and make them into FormData

```<code>var _documents = [];

for (var i = 0; i < arrayOfFiles.length; i++) {

  var document = {
     File: arrayOfFiles[i].file.nativeFile,
     DocumentId: arrayOfFiles[i].documentId,
     DocumentType: arrayOfFiles[i].documentName
  };

  _documents.push(document);
}

var uploadedInformation = {
       LoanID: 1452465,
       documents: _documents
};

var options = {
   indices: true,
   nulls: true
};

var a = objectToFormData(uploadedInformation, options);

for (var pair of a.entries()) {
     console.log(pair[0] + ', ' + pair[1]);
}

jQuery.ajaxSettings.traditional = true;
$.ajax({
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    url:  '@Url.Action("UploadFile", "Home")',
    data: a
});
</code>```

Code for controller:

[HttpPost]
        [ActionName("UploadFile")]
        public ActionResult UploadFile(UploadedInformation uploadedInformation)
        {
            _ = Request.Form;
            return View();
        }
```

<p>UploadedFile class:</p>

<pre class="lang-cs prettyprint-override"><code>public class UploadedInformation
    {

        public long LoanID { get; set; }
        public IEnumerable<Document> Documents { get; set; }

    }
</code>```

Document class:

public class Document
{

      public HttpPostedFileBase File { get; set;}
      public string DocumentId { get; set;}
      public string DocumentType { get; set; }
}
```

<p>All of the items bind perfectly, except for <code>File</code>.
In browser debugger keys and values are:</p>

```LoanID, 1452465
documents[0][File], [object File]
documents[0][DocumentId], 1
documents[0][DocumentType], Passport
```

<p><code>_=Request.Form</code> also displays only 3 keys without <code>documents[0][File]</code></p>

<p><strong>Update:</strong>
I changed controller to </p>

<pre class="lang-cs prettyprint-override"><code>public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> file, IEnumerable<string> documentType, IEnumerable<string>documentId, long loanId){...}
</code>```

and _=Request.Form still shows nothing with file, however file list is populated

Another update:
Apparently, this time file items shows only in _=Request.File

答:
Due to the way that the controller is handling the file upload parts of the request, I suspect you may need to make some adjustments to your process and allow for the fact that the files are being separated from the main object.

I've included some adjustments to your code below (note, this is untested so you may need to experiment a little), assuming that the files come through in the same order as you Documents, then just run a match up process before running your own process.

Code for controller:

[HttpPost]
        [ActionName("UploadFile")]
        public ActionResult UploadFile(List<HttpPostedFileBase> myFiles, UploadedInformation uploadedInformation)
        {
            for (var i = 0; i <uploadedInformation.Documents.Length; i++)
            {
                uploadedInformation.Documents[i].File = myFiles[i];
            }

            // Do stuff

            return View();
        }
```

<p>In the event that the order of the files cannot be assumed, you can add the filename to the data to aid with matching on the server side</p>

<p>Javascript</p>

```var _documents = [];

for (var i = 0; i < arrayOfFiles.length; i++) {

  var document = {
     File: arrayOfFiles[i].file.nativeFile,
     FileName: arrayOfFiles[i].file.name,
     DocumentId: arrayOfFiles[i].documentId,
     DocumentType: arrayOfFiles[i].documentName
  };

  _documents.push(document);
}
```

Title: FormData key does not go through

Body:
I use external class for making object variable into FormData variable. All of the keys go through, all but One for File object.

Here is that external class: https://github.com/therealparmesh/object-to-formdata

This is how I create objects and make them into FormData

var _documents = [];

for (var i = 0; i < arrayOfFiles.length; i++) {

  var document = {
     File: arrayOfFiles[i].file.nativeFile,
     DocumentId: arrayOfFiles[i].documentId,
     DocumentType: arrayOfFiles[i].documentName
  };

  _documents.push(document);
}

var uploadedInformation = {
       LoanID: 1452465,
       documents: _documents
};

var options = {
   indices: true,
   nulls: true
};

var a = objectToFormData(uploadedInformation, options);

for (var pair of a.entries()) {
     console.log(pair[0] + ', ' + pair[1]);
}

jQuery.ajaxSettings.traditional = true;
$.ajax({
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    url:  '@Url.Action("UploadFile", "Home")',
    data: a
});

Code for controller:

[HttpPost]
        [ActionName("UploadFile")]
        public ActionResult UploadFile(UploadedInformation uploadedInformation)
        {
            _ = Request.Form;
            return View();
        }

UploadedFile class:

public class UploadedInformation
    {

        public long LoanID { get; set; }
        public IEnumerable<Document> Documents { get; set; }

    }

Document class:

public class Document
{

      public HttpPostedFileBase File { get; set;}
      public string DocumentId { get; set;}
      public string DocumentType { get; set; }
}

All of the items bind perfectly, except for File.
In browser debugger keys and values are:

LoanID, 1452465
documents[0][File], [object File]
documents[0][DocumentId], 1
documents[0][DocumentType], Passport

_=Request.Form also displays only 3 keys without documents[0][File]

Update:
I changed controller to

public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> file, IEnumerable<string> documentType, IEnumerable<string>documentId, long loanId){...}

and _=Request.Form still shows nothing with file, however file list is populated

Another update:
Apparently, this time file items shows only in _=Request.File

Body:
Due to the way that the controller is handling the file upload parts of the request, I suspect you may need to make some adjustments to your process and allow for the fact that the files are being separated from the main object.

I've included some adjustments to your code below (note, this is untested so you may need to experiment a little), assuming that the files come through in the same order as you Documents, then just run a match up process before running your own process.

Code for controller:

[HttpPost]
        [ActionName("UploadFile")]
        public ActionResult UploadFile(List<HttpPostedFileBase> myFiles, UploadedInformation uploadedInformation)
        {
            for (var i = 0; i <uploadedInformation.Documents.Length; i++)
            {
                uploadedInformation.Documents[i].File = myFiles[i];
            }

            // Do stuff

            return View();
        }

In the event that the order of the files cannot be assumed, you can add the filename to the data to aid with matching on the server side

Javascript

var _documents = [];

for (var i = 0; i < arrayOfFiles.length; i++) {

  var document = {
     File: arrayOfFiles[i].file.nativeFile,
     FileName: arrayOfFiles[i].file.name,
     DocumentId: arrayOfFiles[i].documentId,
     DocumentType: arrayOfFiles[i].documentName
  };

  _documents.push(document);
}


问:
How to replace a list comprehension with a numpy command?
Is there a way to replace the following python list comprehension with a numpy function that doesn't work with loops?

a = np.array([0, 1, 1, 1, 0, 3])

bins = np.bincount(a)
>>> bins: [2 3 0 1]

a_counts = [bins[val] for val in y_true]
>>> a_counts: [2, 3, 3, 3, 2, 1]
```

So the basic idea is to generate an array where the actual values are replaced by the number of occurrences of that specific value in the array.

I want to do this calculation in a custom keras loss function which, to my knowledge, doesn't work with loops or list comprehensions.

答:
If you want to avoid loops, you may use pandas library:

```<code>import pandas as pd
import numpy as np
a = np.array([0, 1, 1, 1, 0, 3])
a_counts = pd.value_counts(a)[a].values
>>> a_counts: array([2, 3, 3, 3, 2, 1], dtype=int64)
</code>```

Body:
Is there a way to replace the following python list comprehension with a numpy function that doesn't work with loops?

a = np.array([0, 1, 1, 1, 0, 3])

bins = np.bincount(a)
>>> bins: [2 3 0 1]

a_counts = [bins[val] for val in y_true]
>>> a_counts: [2, 3, 3, 3, 2, 1]

So the basic idea is to generate an array where the actual values are replaced by the number of occurrences of that specific value in the array.

I want to do this calculation in a custom keras loss function which, to my knowledge, doesn't work with loops or list comprehensions.

Body:
If you want to avoid loops, you may use pandas library:

import pandas as pd
import numpy as np
a = np.array([0, 1, 1, 1, 0, 3])
a_counts = pd.value_counts(a)[a].values
>>> a_counts: array([2, 3, 3, 3, 2, 1], dtype=int64)


问:
Autocomplete search
hi every one i need simple auto suggest code i have tried with  jquery.autocomplete.js am not getting what i need to do
code :- index.jsp

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

 <html>

 <head>

     <link rel="stylesheet" type="text/css" href="style.css" />

     <script type="text/javascript" src="jquery-1.3.2.min.js"></script>

     <script type="text/javascript" src="jquery.autocomplete.js"></script>

 </head>

 <body>

     <div style="width: 300px; margin: 50px auto;">

         <b>Country</b>   : <input type="text" id="country" name="country" class="input_text"/>

     </div>

 </body>

 <script>

     jQuery(function(){

         $("#country").autocomplete("list.jsp");

     });

 </script>

 </html>

and list.jsp
<%@page import="java.util.Iterator"%>

 <%@page import="java.util.List"%>

 <%@page import="java.util.ArrayList"%>

 <%

    String countries[] = {

                             "Afghanistan",

                            "Albania",

                             "Algeria",

                            "Andorra",

                             "Angola",

                             "Antigua and Barbuda",

                             "Argentina",

                             "Armenia",

                             "Yemen",

                             "Zambia",

                             "Zimbabwe"

                             };

     String query = (String)request.getParameter("q");

     System.out.println("1"+request.getParameterNames().nextElement());

     response.setHeader("Content-Type", "text/html");

     int cnt=1;

     for(int i=0;i<countries.length;i++)

     {

         if(countries[i].toUpperCase().startsWith(query.toUpperCase()))

        {

            out.print(countries[i]+"\n");

             if(cnt>=10)
                break;

             cnt++;

         }

     }

 %>
</code>```

there is one more style.css is there but it is not showing anything while execution
note all source file is present in same folder please tell me where am lacking

答:
```<code><%
 String countries[] = {"Afghanistan","Albania","Algeria","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Yemen","Zambia","Zimbabwe"};
 String query = (String)request.getParameter("q");
 response.setHeader("Content-Type","text/html");
 String javascriptContent = new String ("");
 int cnt = countries.length;
 if(cnt > 10)
 {
  cnt = 10;
 }
 for(int i=0;i<cnt;i++)
 {
    if(countries[i].toUpperCase().startsWith(query.toUpperCase()))
    {
        javascriptContent.concat(countries.get(i));
        if (i < (cnt -1))
        {
            javascriptContent.concat(",");
        }
    }
}
%>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/demo/main.css" type="text/css" />
    <link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.css" type="text/css" />
    <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/lib/jquery.bgiframe.min.js"></script>
    <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/lib/jquery.dimensions.js"></script>
    <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            var data = "<%=  javascriptContent %>".split(",");
            $("#country").autocomplete(data);
        });
    </script>
</head>
<body>
    <b>Country</b>   : <input type="text" id="country" name="country" class="input_text"/></div>
</body>
</html>
</code>```

Here they are and have fun. I copied athe html source code from the mainpage of autocomplete. Please check the java syntax first.

Title: Autocomplete search

Body:
hi every one i need simple auto suggest code i have tried with  jquery.autocomplete.js am not getting what i need to do
code :- index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

     <link rel="stylesheet" type="text/css" href="style.css" />

         Country   : <input type="text" id="country" name="country" class="input_text"/>

and list.jsp
<%@page import="java.util.Iterator"%>

 <%@page import="java.util.List"%>

 <%@page import="java.util.ArrayList"%>

 <%

    String countries[] = {

                             "Afghanistan",

                            "Albania",

                             "Algeria",

                            "Andorra",

                             "Angola",

                             "Antigua and Barbuda",

                             "Argentina",

                             "Armenia",

                             "Yemen",

                             "Zambia",

                             "Zimbabwe"

                             };

     String query = (String)request.getParameter("q");

     System.out.println("1"+request.getParameterNames().nextElement());

     response.setHeader("Content-Type", "text/html");

     int cnt=1;

     for(int i=0;i<countries.length;i++)

     {

         if(countries[i].toUpperCase().startsWith(query.toUpperCase()))

        {

            out.print(countries[i]+"\n");

             if(cnt>=10)
                break;

             cnt++;

         }

     }

 %>

there is one more style.css is there but it is not showing anything while execution
note all source file is present in same folder please tell me where am lacking

Body:
<%
 String countries[] = {"Afghanistan","Albania","Algeria","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Yemen","Zambia","Zimbabwe"};
 String query = (String)request.getParameter("q");
 response.setHeader("Content-Type","text/html");
 String javascriptContent = new String ("");
 int cnt = countries.length;
 if(cnt > 10)
 {
  cnt = 10;
 }
 for(int i=0;i<cnt;i++)
 {
    if(countries[i].toUpperCase().startsWith(query.toUpperCase()))
    {
        javascriptContent.concat(countries.get(i));
        if (i < (cnt -1))
        {
            javascriptContent.concat(",");
        }
    }
}
%>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/demo/main.css" type="text/css" />
    <link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.css" type="text/css" />
    <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/lib/jquery.bgiframe.min.js"></script>
    <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/lib/jquery.dimensions.js"></script>
    <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            var data = "<%=  javascriptContent %>".split(",");
            $("#country").autocomplete(data);
        });
    </script>
</head>
<body>
    <b>Country</b>   : <input type="text" id="country" name="country" class="input_text"/></div>
</body>
</html>

Here they are and have fun. I copied athe html source code from the mainpage of autocomplete. Please check the java syntax first.


问:
Is there a better way to write my item/weapon unlock system?
I'm really struggling with creating a weapon/item unlock system via an in-game shop. The player should only be able to select weapons at indexes that have been unlocked or bought.

I've wasted two days on the best way to achieve this and I'm still not anywhere near a solution.

Currently this is what I have:

I have a WeaponUnlock script that handles a dictionary of weapons and another WeaponSwitcher script that access vales from that script to check if it is unlocked or not.

```<code>public class WeaponUnlockSystem : MonoBehaviour
{

    private Dictionary<string, bool> weaponUnlockState;

    void Start()
    {
        // Seeding with some data for example purposes
        weaponUnlockState = new Dictionary<string, bool>();
        weaponUnlockState.Add("Shotgun", true);
        weaponUnlockState.Add("Rifle", true);
        weaponUnlockState.Add("FireballGun", false);
        weaponUnlockState.Add("LaserGun", false);
        weaponUnlockState.Add("FlamethrowerGun", false);
        weaponUnlockState.Add("SuperGun", false);
    }

    public bool IsWeaponUnlocked(string weapon_)
    {
        if (weaponUnlockState.ContainsKey(weapon_))
            return weaponUnlockState[weapon_];              // this will return either true or false if the weapon is unlocked or not
        else
            return false;
    }

    public void UnlockWeapon(string weapon_)            //this will be called by the button..
    {
        if (weaponUnlockState.ContainsKey(weapon_))
            weaponUnlockState[weapon_] = true;
    }
}
</code>```

The WeaponSwitchergets the name of the weapon from the nested children every time the nextWeapon button is pressed:

```<code>weaponName = this.gameObject.transform.GetChild(weaponIdx).name.ToString();     //get the name of the child at current index

        if (weaponUnlock.IsWeaponUnlocked(weaponName))      //ask weaponUnlockSystem if this name weapon is unlocked or not, only enable the transform if true is returned
            selectedWeapon = weaponIdx;
</code>```

This...... works..... but I know is not practical. As the script sits on a game object and at every time it is called the Start() is called that will reset all the unlocked values. Also will I have to make it persistent via DontDestroyOnLOad() through scenes?

I can get use PlayerPrefs and set a value for every weapon, but that is also not ideal and also to avoid it being reset every time someone opens my game I would have to perform a checks of PlayerPrefs.HasKey() for every weapon. Also not practical.

There must be a better way of doing this. Its funny that I cannot find much help online for this and dont know how everyone is getting around this.

Thanks

答:
I had a Unity project recently where we needed to hold and manipulate some simple data between scenes. We just made a static class that doesn't extend monobehaviour.
Also, if you're looking for efficiency, why not just maintain an array of unlocked weapons?

All in all, why not try something like this:

```<code>public static class WeaponUnlockSystem
{

    private static string[] unlockedWeapons = InitialWeapons();

    private static string[] InitialWeapons(){
        string w = new string[]{
            "Shotgun",
            "Rifle",
        }
    }

    public static bool IsWeaponUnlocked(string name)
    {
        int i = 0;
        bool found = false;
        while(i < unlockedWeapons.Length && !found){
            if (string.Equals(unlockedWeapons[i],name)){
                found = true;
            }
            i++;
        }
        return found;
    }

    public static void UnlockWeapon(string name)
    {
        string[] weapons = new string[unlockedWeapons.Length+1];
        int i = 0;
        bool found = false;
        while(i < unlockedWeapons.Length && !found){
            if (string.Equals(unlockedWeapons[i],name)){
                found = true;
            } else {
                weapons[i] = unlockedWeapons[i];
            }
        }
        if(!found){
            weapons[unlockedWeapons.Length] = name;
            unlockedWeapons = weapons;
        }
}
</code>```

I'm not running my c# IDE, so I apologise if there's any syntax errors. Should be efficient, simple and - as it's static - you shouldn't need to put it on an empty GameObject to have it work.

Body:
I'm really struggling with creating a weapon/item unlock system via an in-game shop. The player should only be able to select weapons at indexes that have been unlocked or bought.

I've wasted two days on the best way to achieve this and I'm still not anywhere near a solution.

Currently this is what I have:

I have a WeaponUnlock script that handles a dictionary of weapons and another WeaponSwitcher script that access vales from that script to check if it is unlocked or not.

public class WeaponUnlockSystem : MonoBehaviour
{

    private Dictionary<string, bool> weaponUnlockState;

    void Start()
    {
        // Seeding with some data for example purposes
        weaponUnlockState = new Dictionary<string, bool>();
        weaponUnlockState.Add("Shotgun", true);
        weaponUnlockState.Add("Rifle", true);
        weaponUnlockState.Add("FireballGun", false);
        weaponUnlockState.Add("LaserGun", false);
        weaponUnlockState.Add("FlamethrowerGun", false);
        weaponUnlockState.Add("SuperGun", false);
    }

    public bool IsWeaponUnlocked(string weapon_)
    {
        if (weaponUnlockState.ContainsKey(weapon_))
            return weaponUnlockState[weapon_];              // this will return either true or false if the weapon is unlocked or not
        else
            return false;
    }

    public void UnlockWeapon(string weapon_)            //this will be called by the button..
    {
        if (weaponUnlockState.ContainsKey(weapon_))
            weaponUnlockState[weapon_] = true;
    }
}

The WeaponSwitchergets the name of the weapon from the nested children every time the nextWeapon button is pressed:

weaponName = this.gameObject.transform.GetChild(weaponIdx).name.ToString();     //get the name of the child at current index

        if (weaponUnlock.IsWeaponUnlocked(weaponName))      //ask weaponUnlockSystem if this name weapon is unlocked or not, only enable the transform if true is returned
            selectedWeapon = weaponIdx;

This...... works..... but I know is not practical. As the script sits on a game object and at every time it is called the Start() is called that will reset all the unlocked values. Also will I have to make it persistent via DontDestroyOnLOad() through scenes?

I can get use PlayerPrefs and set a value for every weapon, but that is also not ideal and also to avoid it being reset every time someone opens my game I would have to perform a checks of PlayerPrefs.HasKey() for every weapon. Also not practical.

There must be a better way of doing this. Its funny that I cannot find much help online for this and dont know how everyone is getting around this.

Thanks

Body:
I had a Unity project recently where we needed to hold and manipulate some simple data between scenes. We just made a static class that doesn't extend monobehaviour.
Also, if you're looking for efficiency, why not just maintain an array of unlocked weapons?

All in all, why not try something like this:

public static class WeaponUnlockSystem
{

    private static string[] unlockedWeapons = InitialWeapons();

    private static string[] InitialWeapons(){
        string w = new string[]{
            "Shotgun",
            "Rifle",
        }
    }

    public static bool IsWeaponUnlocked(string name)
    {
        int i = 0;
        bool found = false;
        while(i < unlockedWeapons.Length && !found){
            if (string.Equals(unlockedWeapons[i],name)){
                found = true;
            }
            i++;
        }
        return found;
    }

    public static void UnlockWeapon(string name)
    {
        string[] weapons = new string[unlockedWeapons.Length+1];
        int i = 0;
        bool found = false;
        while(i < unlockedWeapons.Length && !found){
            if (string.Equals(unlockedWeapons[i],name)){
                found = true;
            } else {
                weapons[i] = unlockedWeapons[i];
            }
        }
        if(!found){
            weapons[unlockedWeapons.Length] = name;
            unlockedWeapons = weapons;
        }
}

I'm not running my c# IDE, so I apologise if there's any syntax errors. Should be efficient, simple and - as it's static - you shouldn't need to put it on an empty GameObject to have it work.


问:
How to get attribute wait until the state change in Firefox Selenium, python ,window , version : 67.0(64-bit) + selenium 3.9.0
Want to confirm whether the data downloading is finished .

The target attributes information like below :

```<code><richlistitem  class="download download-state" active="true"
orient="horizontal"
onclick="DownloadsView.onDownloadClick(event);" state="1"
exists="true" selected="true">....<description
class="downloadDetails downloadDetailsHover" crop="end"
value="49.5 KB — xxx.com:8080 — 8:09 PM"/><description
class="downloadDetails downloadDetailsButtonHover"
crop="end"/></vbox></hbox><toolbarseparator/><button
class="downloadButton downloadIconShow"
oncommand="DownloadsView.onDownloadButton(event);"
tooltiptext="Open Containing Folder"/></richlistitem>

# Current script:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

download_CSV =dr.find_element_by_id('xxxx')
download_CSV.click()
NEW_TAB = driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
cur_windows = driver.window_handles # NEW TAB

time.sleep(2)

driver.switch_to.window(cur_windows[1])
driver.get('about:downloads')
# EC.until the download message attribute change script
</code>```

How to get the attribute of state="1" (1 =meaning download finished,0=not yet) or exist="true",need to wait until state="1" changed from "0" / or exist="true" appear ?
(welcome for other method the define the file is already finished download)

Cannot apply this answer to my situation.
Selenium : wait until attribute value changed

答:
I dont know if this will work but maybe you can try with the Expected conditions: presence_of_element_located.

If there is no other element in the website that responds to the Xpath locator

```<code>//richlistitem[@state='1']
</code>```

Maybe this can be the sollution to your problem:

```<code>WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.XPATH, '//richlistitem[@state="1"]')))
</code>```

This code will be looking for the element "//richlistitem[@state='1']" during 10 seconds until the element is located on the DOM otherwise it will return TimeoutException

Body:
Want to confirm whether the data downloading is finished .

The target attributes information like below :

<richlistitem  class="download download-state" active="true"
orient="horizontal"
onclick="DownloadsView.onDownloadClick(event);" state="1"
exists="true" selected="true">....<description
class="downloadDetails downloadDetailsHover" crop="end"
value="49.5 KB — xxx.com:8080 — 8:09 PM"/><description
class="downloadDetails downloadDetailsButtonHover"
crop="end"/></vbox></hbox><toolbarseparator/><button
class="downloadButton downloadIconShow"
oncommand="DownloadsView.onDownloadButton(event);"
tooltiptext="Open Containing Folder"/></richlistitem>

# Current script:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

download_CSV =dr.find_element_by_id('xxxx')
download_CSV.click()
NEW_TAB = driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
cur_windows = driver.window_handles # NEW TAB

time.sleep(2)

driver.switch_to.window(cur_windows[1])
driver.get('about:downloads')
# EC.until the download message attribute change script

How to get the attribute of state="1" (1 =meaning download finished,0=not yet) or exist="true",need to wait until state="1" changed from "0" / or exist="true" appear ?
(welcome for other method the define the file is already finished download)

Cannot apply this answer to my situation.
Selenium : wait until attribute value changed

Body:
I dont know if this will work but maybe you can try with the Expected conditions: presence_of_element_located.

If there is no other element in the website that responds to the Xpath locator

//richlistitem[@state='1']

Maybe this can be the sollution to your problem:

WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.XPATH, '//richlistitem[@state="1"]')))

This code will be looking for the element "//richlistitem[@state='1']" during 10 seconds until the element is located on the DOM otherwise it will return TimeoutException


问:
How to detect phoenix application started from `mix phx.server`?
I have some workers (children) in Application.start. They shouldn't be started if phoenix app running from task other than mix phx.server (for example with mix ecto.reset).

So, how to know in Application.start that it is mix phx.server running the code?

答:
There is no documented way to check if the application was started as a task, e. g. because the application does not have a mix dependency on production.

Typically, that sort of fine tuning is resolved by using :included_applications in project config and loading them manually if needed from Application.start/2 when required with Application.ensure_started/2. For the condition to check one might use an environment variable (optionally via the task alias):

```<code>LOAD_INCLUDED=app1,app2,app3 mix ecto.reset
</code>```

and somewhere in Application.start/2:

```<code>"LOAD_INCLUDED"
|> System.get_env()
|> Enum.split(",")
|> Enum.map(&String.to_atom/1)
|> Application.ensure_started()
</code>```

If these workers are your own workers, it’s even easier: just call Kernel.++/2 with a list of conditional workers based on the environment variable.

Sidenote: in production, the application is started as an OTP release, without mix included and therefore an explicit check for mix phx.server makes zero sense.

Body:
There is no documented way to check if the application was started as a task, e. g. because the application does not have a mix dependency on production.

Typically, that sort of fine tuning is resolved by using :included_applications in project config and loading them manually if needed from Application.start/2 when required with Application.ensure_started/2. For the condition to check one might use an environment variable (optionally via the task alias):

LOAD_INCLUDED=app1,app2,app3 mix ecto.reset

and somewhere in Application.start/2:

"LOAD_INCLUDED"
|> System.get_env()
|> Enum.split(",")
|> Enum.map(&String.to_atom/1)
|> Application.ensure_started()

If these workers are your own workers, it’s even easier: just call Kernel.++/2 with a list of conditional workers based on the environment variable.

Sidenote: in production, the application is started as an OTP release, without mix included and therefore an explicit check for mix phx.server makes zero sense.


问:
Fix date issue in a .csv file with utl_file
I am using utl_file to write in a csv file. The data includes date columns also. The issue here is

For a single digit day 0 gets removed when the data gets inserted in the csv file.
   Eg - date 07-Jun-13 gets inserted as 7-Jun-13, how can I ensure that 0 stays?

I already to_char and concat "" but still I get single digit date only. The csv file being generated is used by a 3rd party system hence no change can be made in the csv.

I am using EBS 12.1.3.

Thanks

PL/SQL code snippet

```<code>   concat(concat('"',lv_proj_start_date),'"')    ||','||
   concat(concat('"',lv_proj_start_date_plus_1),'"')     ||','||
</code>```

I expect the output for date in the csv like 07-Jun-13

but in csv file the o/p is 7-Jun-13.

答:
Assuming both columns are of DATE format, you need to explicitly convert the date into whichever format you desire, e.g.:

```<code>'"' || to_char(lv_proj_start_date, 'dd-Mon-yy', 'nls_date_language=english') || '","'
    || to_char(lv_proj_start_date_plus_1, 'dd-Mon-yy', 'nls_date_language=english') || '",'
</code>```

N.B. I have also converted your CONCAT function calls to use the concatenation operator ||, as this is much easier to read. I've also combined text strings where possible.

I have also used the optional third parameter of to_char() to explicitly set the date language to be English, which makes it NLS independent.

A final note: do you absolutely have to output the dates with 2-digit years? 4-digits are preferred nowawdays, post Y2K!

ETA: Here's an example showing that the output is correct:

```<code>DECLARE
  lv_proj_start_date DATE := to_date('07/07/2019', 'dd/mm/yyyy');
  lv_proj_start_date_plus_1 DATE := lv_proj_start_date + 1;

  v_str VARCHAR2(4000);
BEGIN
  v_str := '"Testing","' || to_char(lv_proj_start_date, 'dd-Mon-yy', 'nls_date_language=english') || '","'
                          || to_char(lv_proj_start_date_plus_1, 'dd-Mon-yy', 'nls_date_language=english') || '"';

  dbms_output.put_line(v_str);
END;
/

"Testing","07-Jul-19","08-Jul-19"
</code>```

Body:
I am using utl_file to write in a csv file. The data includes date columns also. The issue here is

For a single digit day 0 gets removed when the data gets inserted in the csv file.
   Eg - date 07-Jun-13 gets inserted as 7-Jun-13, how can I ensure that 0 stays?

I already to_char and concat "" but still I get single digit date only. The csv file being generated is used by a 3rd party system hence no change can be made in the csv.

I am using EBS 12.1.3.

Thanks

PL/SQL code snippet

   concat(concat('"',lv_proj_start_date),'"')    ||','||
   concat(concat('"',lv_proj_start_date_plus_1),'"')     ||','||

I expect the output for date in the csv like 07-Jun-13

but in csv file the o/p is 7-Jun-13.

Body:
Assuming both columns are of DATE format, you need to explicitly convert the date into whichever format you desire, e.g.:

'"' || to_char(lv_proj_start_date, 'dd-Mon-yy', 'nls_date_language=english') || '","'
    || to_char(lv_proj_start_date_plus_1, 'dd-Mon-yy', 'nls_date_language=english') || '",'

N.B. I have also converted your CONCAT function calls to use the concatenation operator ||, as this is much easier to read. I've also combined text strings where possible.

I have also used the optional third parameter of to_char() to explicitly set the date language to be English, which makes it NLS independent.

A final note: do you absolutely have to output the dates with 2-digit years? 4-digits are preferred nowawdays, post Y2K!

ETA: Here's an example showing that the output is correct:

DECLARE
  lv_proj_start_date DATE := to_date('07/07/2019', 'dd/mm/yyyy');
  lv_proj_start_date_plus_1 DATE := lv_proj_start_date + 1;

  v_str VARCHAR2(4000);
BEGIN
  v_str := '"Testing","' || to_char(lv_proj_start_date, 'dd-Mon-yy', 'nls_date_language=english') || '","'
                          || to_char(lv_proj_start_date_plus_1, 'dd-Mon-yy', 'nls_date_language=english') || '"';

  dbms_output.put_line(v_str);
END;
/

"Testing","07-Jul-19","08-Jul-19"