问:
how i can remove  link which have specific class and title and also rmove the next span
I am working on a third part web application. and inside the Breadcrumb navigation i will get something as follow:-

now i want to remove the link which have title = KB and also the next span which contain >

so my breadcrumb will look something as follow:-

```<code>Info Hub > Home
</code>```

instead of

```<code>Info Hub > kb > Home
</code>```

so can anyone adivce how i can achieve this using CSS at first place, if not possible to do it using javascript ?

答:
.your-breadcrumb-wrapper span:nth-child(2),
.your-breadcrumb-wrapper span:nth-child(3) {
   display: none;
}```

Title: how i can remove <a> link which have specific class and title and also rmove the next span

Body:
I am working on a third part web application. and inside the Breadcrumb navigation i will get something as follow:-

now i want to remove the link which have title = KB and also the next span which contain >

so my breadcrumb will look something as follow:-

Info Hub > Home

instead of

Info Hub > kb > Home

so can anyone adivce how i can achieve this using CSS at first place, if not possible to do it using javascript ?


来源: stackexchange

问:
How to compare current item with the next item in foreach asp.net
I have a question.

I have model, and I show in the page this model thanks to foreach. And in the model I have column (vPeriod) and I need to compare current item (e.g vPeriod = 2016) with next item (e.g. vPeriod = 2017) and I don't know how to compare!

```<code>foreach(var item in Model)
{
if(current.vPeriod == next.vPeriod)
{
//do something
}
else
{
//do something
}
}
</code>```

If I use for, it's the easy way. But how do I do this with foreach?

Code view:

```<code> <tr class="line2">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td style="color: #5f6877;">2016</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

@foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2016")
                {
                    <tr class="line3">
                        <td>@itemData.vAddress</td>
                        <td>@itemData.vCreateDate</td>
                        <td>@itemData.iCountOfFloors</td>
                        <td>@itemData.iCountOfRooms</td>
                        <td>@itemData.iAreaOfRooms</td>
                        <td>@itemData.vLastRepairs</td>
                        <td>@itemData.vType</td>
                        <td>@itemData.vBelonging</td>
                        <td>@itemData.vPlanRepairs</td>
                    </tr>
                }
            }

            <tr class="line2">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td style="color: #5f6877;">2017</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

            @foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2017")
                {
                    <tr class="line3">
                        <td>@itemData.vAddress</td>
                        <td>@itemData.vCreateDate</td>
                        <td>@itemData.iCountOfFloors</td>
                        <td>@itemData.iCountOfRooms</td>
                        <td>@itemData.iAreaOfRooms</td>
                        <td>@itemData.vLastRepairs</td>
                        <td>@itemData.vType</td>
                        <td>@itemData.vBelonging</td>
                        <td>@itemData.vPlanRepairs</td>
                    </tr>
                }
            }
</code>```

It's like really awful! I can have many different years and all the time need to create a block with data and a `foreach block for year.

答:
Solution with for:

```<code>var array = Model.ToArray();
for (int i = 0; i < array.Length - 1; i++)
{
    if(array[i].vPeriod == array[i + 1].vPeriod)
    {
        //do something
    }
    else
    {
        //do something
    }
}
</code>```

Solution with foreach, adjust prev type to your needs:

```<code>    string prev = string.Empty;
    bool first = true;
    foreach (var item in Model)
    {
        if (first)
        {
            first = false;
        }
        else if (prev == item)
        {
            //do something
        }
        else
        {
            //do something
        }

        prev = item;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a question.

I have model, and I show in the page this model thanks to foreach. And in the model I have column (vPeriod) and I need to compare current item (e.g vPeriod = 2016) with next item (e.g. vPeriod = 2017) and I don't know how to compare!

foreach(var item in Model)
{
if(current.vPeriod == next.vPeriod)
{
//do something
}
else
{
//do something
}
}

If I use for, it's the easy way. But how do I do this with foreach?

Code view:

                2016

@foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2016")
                {

                        @itemData.vAddress
                        @itemData.vCreateDate
                        @itemData.iCountOfFloors
                        @itemData.iCountOfRooms
                        @itemData.iAreaOfRooms
                        @itemData.vLastRepairs
                        @itemData.vType
                        @itemData.vBelonging
                        @itemData.vPlanRepairs

                }
            }

                2017

            @foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2017")
                {

                        @itemData.vAddress
                        @itemData.vCreateDate
                        @itemData.iCountOfFloors
                        @itemData.iCountOfRooms
                        @itemData.iAreaOfRooms
                        @itemData.vLastRepairs
                        @itemData.vType
                        @itemData.vBelonging
                        @itemData.vPlanRepairs

                }
            }

It's like really awful! I can have many different years and all the time need to create a block with data and a `foreach block for year.

Body:
Solution with for:

var array = Model.ToArray();
for (int i = 0; i < array.Length - 1; i++)
{
    if(array[i].vPeriod == array[i + 1].vPeriod)
    {
        //do something
    }
    else
    {
        //do something
    }
}

Solution with foreach, adjust prev type to your needs:

    string prev = string.Empty;
    bool first = true;
    foreach (var item in Model)
    {
        if (first)
        {
            first = false;
        }
        else if (prev == item)
        {
            //do something
        }
        else
        {
            //do something
        }

        prev = item;
    }


问:
How do I insert random characters into a sql database column?
I want to populate a column of my database table with 253 lines of 'M' and 'F' randomly placed in the column, is this possible?

Example of what it may look like:

```<code>Gender:
M
M
F
M
F
F
M
F
M
</code>```

答:
Try this so you can decrease "0.5" to improve the chances of being picked if you want the "M" to be more dominant. </p>

```<code> SELECT CASE WHEN (RAND() > 0.5) THEN 'M' ELSE 'F' END
</code>```

Body:
I want to populate a column of my database table with 253 lines of 'M' and 'F' randomly placed in the column, is this possible?

Example of what it may look like:

Gender:
M
M
F
M
F
F
M
F
M

Body:
Try this so you can decrease "0.5" to improve the chances of being picked if you want the "M" to be more dominant.

 SELECT CASE WHEN (RAND() > 0.5) THEN 'M' ELSE 'F' END


问:
Java getTime() error on netbean
I can't run my project, just because of the lines with getTime() / 1000 below. Keep getting errors. It is code for a hotel booking system.

```<code>private void bookingObjectCreation() {
        booking = new Booking();
        roomsToRoomObjectList(tf_rooms.getText());
        booking.setBookingType((String) combo_reservationType.getSelectedItem());
        booking.setPerson(Integer.parseInt(tf_guestNo.getText()));
        ***booking.setCheckInDateTime(date_checkIn.getDate().getTime() / 1000);***
        booking.setBookingType((String) combo_reservationType.getSelectedItem());
        if (date_checkOut.getDate() != null) {
            ***booking.setCheckOutDateTime(date_checkOut.getDate().getTime() / 1000);***
        }
</code>```

I have been write this hotel management system software for almost a week now, and I only get that same particular error from the control panel.

答:
This: date_checkOut.getDate().getTime() / 1000 will return a double value so you can set it.
I don't know why you are dividing by 1000 but you can solve you problem doing:

```<code>booking.setCheckOutDateTime(Math.round(new Date().getTime() / 1000));
</code>```

Title: Java getTime() error on netbean

Body:
I can't run my project, just because of the lines with getTime() / 1000 below. Keep getting errors. It is code for a hotel booking system.

private void bookingObjectCreation() {
        booking = new Booking();
        roomsToRoomObjectList(tf_rooms.getText());
        booking.setBookingType((String) combo_reservationType.getSelectedItem());
        booking.setPerson(Integer.parseInt(tf_guestNo.getText()));
        ***booking.setCheckInDateTime(date_checkIn.getDate().getTime() / 1000);***
        booking.setBookingType((String) combo_reservationType.getSelectedItem());
        if (date_checkOut.getDate() != null) {
            ***booking.setCheckOutDateTime(date_checkOut.getDate().getTime() / 1000);***
        }

I have been write this hotel management system software for almost a week now, and I only get that same particular error from the control panel.

Body:
This: date_checkOut.getDate().getTime() / 1000 will return a double value so you can set it.
I don't know why you are dividing by 1000 but you can solve you problem doing:

booking.setCheckOutDateTime(Math.round(new Date().getTime() / 1000));


问:
background change after alert
Why on this page:

https://jsfiddle.net/eddnhc5f/

When I press the key c on Firefox and Microsoft edge, the background is changed before the alert, but in Opera and Chrome, after I press confirm alert.

function getKeyup(key) {
  if (key == null) {
    keycode = event.keyCode;
    // To Mozilla
  } else {
    keycode = key.keyCode;
  }
}

function TEST() {
  document.body.style.backgroundColor = "BLACK";
  alert('Hello');
  return false;
}

function getKey(key) {
  if (key == null) {
    keycode = event.keyCode;
    // To Mozilla
  } else {
    keycode = key.keyCode;
  }
  if (keycode == 67) {
    //alert(condcheck);

    TEST();
    return false;
  }
}
$(document).ready(function() {
  $(document).keydown(function(eventObj) {
    getKey(eventObj);
  });
  $(document).keyup(function(eventObj) {
    getKeyup(eventObj);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
TEST</code>```

答:
check out this     demo

I did change in TEST() function.

```<code>function getKeyup(key){
    if ( key == null ) {
        keycode = event.keyCode;
    // To Mozilla
    } else {
        keycode = key.keyCode;
    }
}
function TEST()
{
//document.body.style.backgroundColor = "BLACK";
alert('Hello');
document.body.style.backgroundColor = "BLACK";
return false;
}
function getKey(key){
    if ( key == null ) {
        keycode = event.keyCode;
    // To Mozilla
    } else {
        keycode = key.keyCode;
    }
    if (keycode == 67){
        //alert(condcheck);

        TEST();
        return false;
    }
}
$(document).ready( function (){
    $(document).keydown(function (eventObj){
        getKey(eventObj);
    });
    $(document).keyup(function (eventObj){
        getKeyup(eventObj);
    });
});
</code>```

Title: background change after alert

Body:
Why on this page:

https://jsfiddle.net/eddnhc5f/

When I press the key c on Firefox and Microsoft edge, the background is changed before the alert, but in Opera and Chrome, after I press confirm alert.

function getKeyup(key) {
  if (key == null) {
    keycode = event.keyCode;
    // To Mozilla
  } else {
    keycode = key.keyCode;
  }
}

function TEST() {
  document.body.style.backgroundColor = "BLACK";
  alert('Hello');
  return false;
}

function getKey(key) {
  if (key == null) {
    keycode = event.keyCode;
    // To Mozilla
  } else {
    keycode = key.keyCode;
  }
  if (keycode == 67) {
    //alert(condcheck);

    TEST();
    return false;
  }
}
$(document).ready(function() {
  $(document).keydown(function(eventObj) {
    getKey(eventObj);
  });
  $(document).keyup(function(eventObj) {
    getKeyup(eventObj);
  });
});

TEST

Body:
check out this     demo

I did change in TEST() function.

function getKeyup(key){
    if ( key == null ) {
        keycode = event.keyCode;
    // To Mozilla
    } else {
        keycode = key.keyCode;
    }
}
function TEST()
{
//document.body.style.backgroundColor = "BLACK";
alert('Hello');
document.body.style.backgroundColor = "BLACK";
return false;
}
function getKey(key){
    if ( key == null ) {
        keycode = event.keyCode;
    // To Mozilla
    } else {
        keycode = key.keyCode;
    }
    if (keycode == 67){
        //alert(condcheck);

        TEST();
        return false;
    }
}
$(document).ready( function (){
    $(document).keydown(function (eventObj){
        getKey(eventObj);
    });
    $(document).keyup(function (eventObj){
        getKeyup(eventObj);
    });
});


问:
How do I add a language keyword in Boo to let 'when' behave as an 'if'
I cannot seem to figure out how I can add the 'when' keyword to BOO which should behave as an 'if'. I figure I could make a method, but then I cannot move the when around like I can with if. Any pointers would be appreciated.

-Mark

答:
This would be a job for a macro.  From the page you linked to, it seems that Boo has syntactic macros.

As an aside note, why do you need an exact duplicate of an existing functionality?

LastEditorDisplayName: Paul Dixon

OwnerDisplayName: Harleqin

ContentLicense: CC BY-SA 2.5


问:
How to display a day from the Date
Using SQL Server 2005

Table1

```<code>Date

19-12-2009
20-12-2010
.....
</code>```

Date Column datatype is DATETIME.

Expected Output

```<code>Monday
Tuesday
</code>```

How to make a query for getting the day...

答:
As @Lamak suggested, you can use the DATENAME function if you're on SQL Server 2005 or later:

```<code>SELECT DATENAME(dw, DateField) FROM Table
</code>```

On earlier versions, the closest you could get was the DATEPART function with dw as the interval, but you needed a CASE to convert the number returned to the day name, as seen here.

```<code>SELECT CASE DATEPART(dw, DateField)
       WHEN 1 THEN 'Sunday'
       WHEN 2 THEN 'Monday'
       WHEN 3 THEN 'Tuesday'
       WHEN 4 THEN 'Wednesday'
       WHEN 5 THEN 'Thursday'
       WHEN 6 THEN 'Friday'
       WHEN 7 THEN 'Saturday'
       END AS DayOfWeek
FROM Table
</code>```

Also note the remarks on the MSDN documentation for those date functions, for information about specifying which day of the week is considered the first day (depends on the DATEFORMAT setting of your SQL environment).

Title: How to display a day from the Date

Body:
Using SQL Server 2005

Table1

Date

19-12-2009
20-12-2010
.....

Date Column datatype is DATETIME.

Expected Output

Monday
Tuesday

How to make a query for getting the day...

Body:
As @Lamak suggested, you can use the DATENAME function if you're on SQL Server 2005 or later:

SELECT DATENAME(dw, DateField) FROM Table

On earlier versions, the closest you could get was the DATEPART function with dw as the interval, but you needed a CASE to convert the number returned to the day name, as seen here.

SELECT CASE DATEPART(dw, DateField)
       WHEN 1 THEN 'Sunday'
       WHEN 2 THEN 'Monday'
       WHEN 3 THEN 'Tuesday'
       WHEN 4 THEN 'Wednesday'
       WHEN 5 THEN 'Thursday'
       WHEN 6 THEN 'Friday'
       WHEN 7 THEN 'Saturday'
       END AS DayOfWeek
FROM Table

Also note the remarks on the MSDN documentation for those date functions, for information about specifying which day of the week is considered the first day (depends on the DATEFORMAT setting of your SQL environment).


问:
How to correctly perform all-VS-all row-by-row comparisons between series in two pandas dataframes?
I have two pandas dataframes, df1 and df2. Both contain time series data.

df1

```<code>Event   Number  Timestamp_A
A       1       7:00
A       2       8:00
A       3       9:00
</code>```

df2

```<code>Event   Number  Timestamp_B
B       1       9:01
B       2       8:01
B       3       7:01
</code>```

Basically, I want to determine the Event B which is closest to Event A, and assign this correctly.

Therefore, I need to substract (1) every Timestamp_B in df2 from ever Timestamp_A in df1, row by row. This results in a series of values, of which I want to take the minumum and put it to a new column in df1.

```<code>Event   Number  Timestamp_A Closest_Timestamp_B
A       1       7:00        7:01
A       2       8:00        8:01
A       3       9:00        9:01
</code>```

I am not familiar with row-by-row operations in pandas.
When I am doing:

```<code>for index, row in df1.iterrows():
    s = df1.Timestamp_A.values - df2["Timestamp_B"][:]
    Closest_Timestamp_B = s.min()
</code>```

The result I get is a ValueError:

```<code>ValueError: operands could not be broadcast together with shapes(3,) (4,)
</code>```

How to correctly perform row-by-row comparisons between two pandas dataframes?

答:
Your best bet is to use the underlying numpy data structure to create a matrix of Timestamp_A by Timestamp_B.  Since you need to compare every event in A to every event in B, this is an O(N^2) calculation, well suited for a matrix.

```<code>import pandas as pd
import numpy as np

df1 = pd.DataFrame([['A',1,'7:00'],
    ['A',2,'8:00'],
    ['A',3,'9:00']], columns=['Event', 'Number', 'Timestamp_A'])

df2 = pd.DataFrame([['B',1,'9:01'],
    ['B',2,'8:01'],
    ['B',3,'7:01']], columns=['Event', 'Number', 'Timestamp_B'])

df1.Timestamp_A = pd.to_datetime(df1.Timestamp_A)
df2.Timestamp_B = pd.to_datetime(df2.Timestamp_B)

# create a matrix with the index of df1 as the row index, and the index
# of df2 as the column index
M = df1.Timestamp_A.values.reshape((len(df1),1)) - df2.Timestamp_B.values

# use argmin to find the index of the lowest value (after abs())
index_of_B = np.abs(M).argmin(axis=0)

df1['Closest_timestamp_B'] = df2.Timestamp_B[index_of_B]

df1
# returns:
  Event  Number         Timestamp_A  Closest_timestamp_B
0     A       1 2017-07-05 07:00:00  2017-07-05 09:01:00
1     A       2 2017-07-05 08:00:00  2017-07-05 08:01:00
2     A       3 2017-07-05 09:00:00  2017-07-05 07:01:00
</code>```

If you want to return to the original formatting for the timestamps, you can use:

```<code>df1.Timestamp_A = df1.Timestamp_A.dt.strftime('%H:%M').str.replace(r'^0','')
df1.Closest_timestamp_B = df1.Closest_timestamp_B.dt.strftime('%H:%M').str.replace(r'^0','')

df1
# returns:
  Event  Number Timestamp_A Closest_timestamp_B
0     A       1        7:00                9:01
1     A       2        8:00                8:01
2     A       3        9:00                7:01
</code>```

Body:
I have two pandas dataframes, df1 and df2. Both contain time series data.

df1

Event   Number  Timestamp_A
A       1       7:00
A       2       8:00
A       3       9:00

df2

Event   Number  Timestamp_B
B       1       9:01
B       2       8:01
B       3       7:01

Basically, I want to determine the Event B which is closest to Event A, and assign this correctly.

Therefore, I need to substract (1) every Timestamp_B in df2 from ever Timestamp_A in df1, row by row. This results in a series of values, of which I want to take the minumum and put it to a new column in df1.

Event   Number  Timestamp_A Closest_Timestamp_B
A       1       7:00        7:01
A       2       8:00        8:01
A       3       9:00        9:01

I am not familiar with row-by-row operations in pandas.
When I am doing:

for index, row in df1.iterrows():
    s = df1.Timestamp_A.values - df2["Timestamp_B"][:]
    Closest_Timestamp_B = s.min()

The result I get is a ValueError:

ValueError: operands could not be broadcast together with shapes(3,) (4,)

How to correctly perform row-by-row comparisons between two pandas dataframes?

Body:
Your best bet is to use the underlying numpy data structure to create a matrix of Timestamp_A by Timestamp_B.  Since you need to compare every event in A to every event in B, this is an O(N^2) calculation, well suited for a matrix.

import pandas as pd
import numpy as np

df1 = pd.DataFrame([['A',1,'7:00'],
    ['A',2,'8:00'],
    ['A',3,'9:00']], columns=['Event', 'Number', 'Timestamp_A'])

df2 = pd.DataFrame([['B',1,'9:01'],
    ['B',2,'8:01'],
    ['B',3,'7:01']], columns=['Event', 'Number', 'Timestamp_B'])

df1.Timestamp_A = pd.to_datetime(df1.Timestamp_A)
df2.Timestamp_B = pd.to_datetime(df2.Timestamp_B)

# create a matrix with the index of df1 as the row index, and the index
# of df2 as the column index
M = df1.Timestamp_A.values.reshape((len(df1),1)) - df2.Timestamp_B.values

# use argmin to find the index of the lowest value (after abs())
index_of_B = np.abs(M).argmin(axis=0)

df1['Closest_timestamp_B'] = df2.Timestamp_B[index_of_B]

df1
# returns:
  Event  Number         Timestamp_A  Closest_timestamp_B
0     A       1 2017-07-05 07:00:00  2017-07-05 09:01:00
1     A       2 2017-07-05 08:00:00  2017-07-05 08:01:00
2     A       3 2017-07-05 09:00:00  2017-07-05 07:01:00

If you want to return to the original formatting for the timestamps, you can use:

df1.Timestamp_A = df1.Timestamp_A.dt.strftime('%H:%M').str.replace(r'^0','')
df1.Closest_timestamp_B = df1.Closest_timestamp_B.dt.strftime('%H:%M').str.replace(r'^0','')

df1
# returns:
  Event  Number Timestamp_A Closest_timestamp_B
0     A       1        7:00                9:01
1     A       2        8:00                8:01
2     A       3        9:00                7:01


问:
zfcuser - whitelist routes and all childroutes
I'am using ZfcUser module in my application to protect access to /admin route. As I want to block all childroutes of /admin, except for /login, /register etc.

In order to do so, I've added a code from accepted answer here - Zend Framework 2 - Global check for authentication with ZFCUser

```<code>protected $whitelist = array('zfcuser/login', 'default');

  public function onBootstrap($e)
  {
      $app = $e->getApplication();
      $em  = $app->getEventManager();
      $sm  = $app->getServiceManager();

      $list = $this->whitelist;
      $auth = $sm->get('zfcuser_auth_service');

      $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
          $match = $e->getRouteMatch();

          // No route match, this is a 404
          if (!$match instanceof RouteMatch) {
              return;
          }

          // Route is whitelisted
          $name = $match->getMatchedRouteName();
          if (in_array($name, $list)) {
              return;
          }

          // User is authenticated
          if ($auth->hasIdentity()) {
              return;
          }

          // Redirect to the user login page, as an example
          $router   = $e->getRouter();
          $url      = $router->assemble(array(), array(
              'name' => 'zfcuser/login'
          ));

          $response = $e->getResponse();
          $response->getHeaders()->addHeaderLine('Location', $url);
          $response->setStatusCode(302);

          return $response;
      }, -100);
  }
</code>```

It works, however it also block access to root routes - and as there is plenty of them, I do not really want to add every single route to whitelist. Is there any way to restrict access only to /admin routes?

答:
Is there any way to restrict access only to /admin routes?

That would really mean that rather than a whitelist you would need a blacklist or change the logic of the conditional check.

Depending on your requirements, you could check just part of the route, something like this.

```<code>$this->whitelist = [
    'zfcuser/login',
    'default'
];

// Route is whitelisted
$currentRoute = $match->getMatchedRouteName();

foreach($this->whitelist as $route) {
    if (0 === strpos($currentRoute, $route)) {
        // we matched the start of the route,
        // e.g every route under 'default' would match this
        return;
    }
}
</code>```

Body:
I'am using ZfcUser module in my application to protect access to /admin route. As I want to block all childroutes of /admin, except for /login, /register etc.

In order to do so, I've added a code from accepted answer here - Zend Framework 2 - Global check for authentication with ZFCUser

protected $whitelist = array('zfcuser/login', 'default');

  public function onBootstrap($e)
  {
      $app = $e->getApplication();
      $em  = $app->getEventManager();
      $sm  = $app->getServiceManager();

      $list = $this->whitelist;
      $auth = $sm->get('zfcuser_auth_service');

      $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
          $match = $e->getRouteMatch();

          // No route match, this is a 404
          if (!$match instanceof RouteMatch) {
              return;
          }

          // Route is whitelisted
          $name = $match->getMatchedRouteName();
          if (in_array($name, $list)) {
              return;
          }

          // User is authenticated
          if ($auth->hasIdentity()) {
              return;
          }

          // Redirect to the user login page, as an example
          $router   = $e->getRouter();
          $url      = $router->assemble(array(), array(
              'name' => 'zfcuser/login'
          ));

          $response = $e->getResponse();
          $response->getHeaders()->addHeaderLine('Location', $url);
          $response->setStatusCode(302);

          return $response;
      }, -100);
  }

It works, however it also block access to root routes - and as there is plenty of them, I do not really want to add every single route to whitelist. Is there any way to restrict access only to /admin routes?

Body:
Is there any way to restrict access only to /admin routes?

That would really mean that rather than a whitelist you would need a blacklist or change the logic of the conditional check.

Depending on your requirements, you could check just part of the route, something like this.

$this->whitelist = [
    'zfcuser/login',
    'default'
];

// Route is whitelisted
$currentRoute = $match->getMatchedRouteName();

foreach($this->whitelist as $route) {
    if (0 === strpos($currentRoute, $route)) {
        // we matched the start of the route,
        // e.g every route under 'default' would match this
        return;
    }
}


问:
Prestashop installation in test directory giving internal server error 500
today after finishing my localhost prestashop work, trying to install prestashop on my server to make my site online.
Follow the step right after below

uploaded prestashop_1.6.1.6.zip in test directory.

trying to run installation in /test directory from firefox.

But gave following

`Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at webmaster@mysite.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request. `

please Help. i really appreciate it.

答:
Remove www.yourdomain.com/prestashop_path/cache/class_index.php
it works for me!


问:
Checking for a loop in an un-directed tree graph python
I am trying to develop a python program to check if there is a loop in the graph when a new line is added.

I am storing different lines in a list ordered by shortest length first, and the lines are a class:

```<code>class Line():
def __init__(self,node1,node2,length):
    self.node1 = node1
    self.node2 = node2
    self.length = int(length)
    self.drawn = False
</code>```

And the nodes are stored in a list:

```<code>nodes = ["A","B","C","D","E","F"]
</code>```

When my program has run it stores the route as a list:

```<code>route = [class(Line),class(Line)...]
</code>```

What i want it to do is to check that when a new line is added that it does not form a cycle. I plan to use a method inside of a bigger class:

something like:

```<code>def check_loop(new_line,graphs):
    add new line to graph
    if there is a loop in graphs:
        return False
    else:
        return True
</code>```

(sorry this is one of my first posts so the format is rubbish)

答: To identify if a cycle is created in a tree is pretty simple, all you need to do is pick a node and then breadth first search the entire tree from that node. If any node has been visited before by the time you reach it, then you know that there is a cycle because there was an alternative path that reached that node beside the one that you have taken.</p>

Body:
I am trying to develop a python program to check if there is a loop in the graph when a new line is added.

I am storing different lines in a list ordered by shortest length first, and the lines are a class:

class Line():
def __init__(self,node1,node2,length):
    self.node1 = node1
    self.node2 = node2
    self.length = int(length)
    self.drawn = False

And the nodes are stored in a list:

nodes = ["A","B","C","D","E","F"]

When my program has run it stores the route as a list:

route = [class(Line),class(Line)...]

What i want it to do is to check that when a new line is added that it does not form a cycle. I plan to use a method inside of a bigger class:

something like:

def check_loop(new_line,graphs):
    add new line to graph
    if there is a loop in graphs:
        return False
    else:
        return True

(sorry this is one of my first posts so the format is rubbish)


问:
Laravel: Auth::user()->role_id in app.blade.php display Trying to get property of non-object
In my users table I add role_id column where 1 is admin and 2 is user. So, when I want to his page in header in my app.blade.php file like this:

```<code><ul class="nav navbar-nav">
   @if(Auth::user()->role_id == 1)
    <li><a href="{!! url('/admin/users'); !!}">Users</a></li>
   @endif
</ul>
</code>```

error appear:
(3/3) ErrorException
The use statement with non-compound name 'Auth' has no effect (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php) (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php)

index() method in AdminUsersController looks like this:

```<code><?php

namespace App\Http\Controllers;

use App\User;
use App\Role;
use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Auth;

class AdminUsersController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::paginate(5);

        if(Auth::user()->role_id !== 1) {
            return redirect('/home');
        }

        return view('admin.users.index', compact('users'));
    }
</code>```

When I use check() instead of user()->role_id == 1, It works but then all users can see except one that not login, but I want to see only admin.

I cannot find the answer in similar topics...

答:
you use

```<code><ul class="nav navbar-nav">
   @if(Auth::user()->role_id == 1)
    <li><a href="{!! url('/admin/users'); !!}">Users</a></li>
   @endif
</ul>
</code>```

but you are not sure the user logged in or not

I mean maybe user is guest and not logged in

you should use

```<code>@if(Auth::check() && Auth::user()->role_id == 1)
</code>```

this condition check user is looged in then check user role_id

so replace code with:

```<code><ul class="nav navbar-nav">
   @if(Auth::check() && Auth::user()->role_id == 1)
    <li><a href="{!! url('/admin/users'); !!}">Users</a></li>
   @endif
</ul>
</code>```

Body:
In my users table I add role_id column where 1 is admin and 2 is user. So, when I want to his page in header in my app.blade.php file like this:

   @if(Auth::user()->role_id == 1)

Users

   @endif

error appear:
(3/3) ErrorException
The use statement with non-compound name 'Auth' has no effect (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php) (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php)

index() method in AdminUsersController looks like this:

<?php

namespace App\Http\Controllers;

use App\User;
use App\Role;
use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Auth;

class AdminUsersController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::paginate(5);

        if(Auth::user()->role_id !== 1) {
            return redirect('/home');
        }

        return view('admin.users.index', compact('users'));
    }

When I use check() instead of user()->role_id == 1, It works but then all users can see except one that not login, but I want to see only admin.

I cannot find the answer in similar topics...

Body:
you use

<ul class="nav navbar-nav">
   @if(Auth::user()->role_id == 1)
    <li><a href="{!! url('/admin/users'); !!}">Users</a></li>
   @endif
</ul>

but you are not sure the user logged in or not

I mean maybe user is guest and not logged in

you should use

@if(Auth::check() && Auth::user()->role_id == 1)

this condition check user is looged in then check user role_id

so replace code with:

<ul class="nav navbar-nav">
   @if(Auth::check() && Auth::user()->role_id == 1)
    <li><a href="{!! url('/admin/users'); !!}">Users</a></li>
   @endif
</ul>


问:
What is the 'open' keyword in Swift?
The ObjectiveC.swift file from the standard library contains the following few lines of code around line 228:

```<code>extension NSObject : Equatable, Hashable {
  /// ...
  open var hashValue: Int {
    return hash
  }
}
</code>```

What does open var mean in this context, or what is the open keyword in general?

答:
Open is an access level, was introduced to impose limitations on class inheritance on Swift.

This means that the open access level can only be applied to classes and class members.

In Classes

An open class can be subclassed in the module it is defined in and in modules that import the module in which the class is defined.

In Class members

The same applies to class members. An open method can be overridden by subclasses in the module it is defined in and in modules that import the module in which the method is defined.

THE NEED FOR THIS UPDATE

Some classes of libraries and frameworks are not designed to be subclassed and doing so may result in unexpected behavior. Native Apple library also won't allow overriding the same methods and classes,

So after this addition they will apply public and private access levels accordingly.

For more details have look at Apple Documentation on Access Control

Title: What is the 'open' keyword in Swift?

Body:
The ObjectiveC.swift file from the standard library contains the following few lines of code around line 228:

extension NSObject : Equatable, Hashable {
  /// ...
  open var hashValue: Int {
    return hash
  }
}

What does open var mean in this context, or what is the open keyword in general?


问:
javascript if a html element text equal with 0, addClass to an element
I have an element that contains the discount of a product

0
        %

```

I want, if the element with id="mydiscouttext" equal to 0, addClass "hide".

I am looking for a solution with javascript.

Any idea?

答:
there, in plain Javascript,

var discount = document.getElementById('ammount').innerHTML;
console.log(discount);
if(parseInt(discount) <= 0 ) {
  document.getElementsByClassName('discount_discountAmount')[0].classList.add("hide");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="discount_discountAmount">
    <div id="mydiscouttext" class="discouttext"><span id="ammount">0</span>
        <span class="price_percent">%</span>
    </div>
</div></code>```

Also, i added a span to isolate the percentage amount. it's easy to deal with it then.

Body:
I have an element that contains the discount of a product

0
        %

I want, if the element with id="mydiscouttext" equal to 0, addClass "hide".

I am looking for a solution with javascript.

Any idea?

Body:
there, in plain Javascript,

var discount = document.getElementById('ammount').innerHTML;
console.log(discount);
if(parseInt(discount) <= 0 ) {
  document.getElementsByClassName('discount_discountAmount')[0].classList.add("hide");
}

<div class="discount_discountAmount">
    <div id="mydiscouttext" class="discouttext"><span id="ammount">0</span>
        <span class="price_percent">%</span>
    </div>
</div>

Also, i added a span to isolate the percentage amount. it's easy to deal with it then.


问:
Having a variable in the middle of an alias?
I currently have a commonly used grep command:

```<code>    grep -r -w <SEARCH> --include \*.c --include \*.cpp --include \*.h
</code>```

Want to have this as an alias (say, grepc) but be able to change the SEARCH in the middle. Is it possible to have this as a variable, and if so how would I do this / call it?

答:
No need to pass argument for this use case

```<code>alias xyz="grep -r --include='*.'{c,h,cpp} -w"
xyz 'whatever'
</code>```

When arguments are needed to be passed, use functions instead. See this Q&A on unix stackexchange for discussion between alias and functions

Body:
I currently have a commonly used grep command:

    grep -r -w <SEARCH> --include \*.c --include \*.cpp --include \*.h

Want to have this as an alias (say, grepc) but be able to change the SEARCH in the middle. Is it possible to have this as a variable, and if so how would I do this / call it?

Body:
No need to pass argument for this use case

alias xyz="grep -r --include='*.'{c,h,cpp} -w"
xyz 'whatever'

When arguments are needed to be passed, use functions instead. See this Q&A on unix stackexchange for discussion between alias and functions


问:
Deleted ssh keys from security page Digital Oceans, but still i am allowed to ssh
I have created a ssh key for my droplet at digital oceans. After few days I have deleted the key from security page and still I am able to ssh using putty with that key. Is it necessary to delete the key from authorized_keys file. If so, then what is the use of adding/deleting ssh keys to droplet on their above mentioned security page?

Question at digital ocean -  https://www.digitalocean.com/community/questions/how-to-remove-ssh-keys-for-the-droplet

答:
As the digital tutorial page says
"You can create new DigitalOcean droplets with an SSH key already set up on them by adding your computer’s SSH key to the control panel.".

To setup a ssh key for the droplet it is needed to add your newly created key to the droplet's control panel.

You are able to access the droplet even after you deleted the ssh from security page because now the ssh also resides inside your droplet's ~/.ssh/ folder(remote machine).

To authenticate using SSH keys, a user must have an SSH key pair on their local computer. On the remote server, the public key must be copied to a file within the user's home directory at ~/.ssh/authorized_keys. This file contains a list of public keys, one-per-line, that are authorized to log into this account.
When a client connects to the host, wishing to use SSH key authentication, it will inform the server of this intent and will tell the server which public key to use. The server then check its authorized_keys file for the public key, generate a random string and encrypts it using the public key.
So, it necessary to delete the key from authorized_keys file to stop ssh access to the remote machine.

After the droplet creation security page lists the keys just to show what all ssh keys you used for all your droplets.Deleting them from security page will not prohibit you from accessing your droplet.


问:
Insert multiple rows in database with single database call from WSO2 DSS
We started using WSO2 recently as an integration layer to communicate with different systems but we hit a problem while calling an existing stored procedure present in SQL server database. This stored procedure takes a user defined table type (UDTT) and single SP call can pass thousands of rows in the UDTT.
We've tried enabling batch requests but when the DSS API is tried with multiple rows, multiple database calls are being made once for each row defeating the purpose of having a UDTT as input, so we would like to know if it's really possible to pass multiple rows using a single database call.</p>

答:
We reached out to WSO2 support and we've been informed that it's not possible as of now.

But it would be really nice to have this feature as WSO2 is used for enterprise level systems and usually the data is huge and can't be sent row by row to database, therefore increasing traffic to database server. Really wish we had this feature, now we have to search for alternatives.


问:
Is there anyway i can give id to each recycler view which i created dynamically?
I have a integer counter which sets the number of recycler view to be created. Is there a way i can associate an id with each of the recycler view created?</p>

答: put one textview in your recycler view  and make it as visibility gone and set value to that textview in adapter. If you want that value then retrieve and use as you need.</p>


问:
VBA EXCEL error 91 object variable or with block variable not set
Hi I have this weird problem where I get error 91 ("object variable or with block variable not set"). I do not always get the error when I run the script, only now and then (random). I have tried to do as much as I can without success.

I am scraping a site to get the most recent prices of some pc components.

In order to do that I made a script and call the script sequentially multiple times for different parts. The error is not related to a specific part. I get the error randomly on all the parts. Sometimes I can do all the calls without any errors.

The script (not the full script, only what you need):

```<code>Sub ImportUrlData(url As String)

    Dim ie As InternetExplorer
    Dim html As HTMLDocument
    Dim varListingIDElement As IHTMLElement
    Dim varShopName As String
    varShopName = ""

    Set ie = New InternetExplorer
    ie.Visible = False
    ie.navigate url

    Do While ie.readyState <> READYSTATE_COMPLETE
        DoEvents
    Loop

    Set html = ie.document

    Set varListingIDElement = html.getElementById("listing")
    varShopName = getXPathElement("/table/tbody/tr[1]/td[1]/p/a", varListingIDElement).innerText
</code>```

I always get the error on this last line:

```<code>varShopName = getXPathElement("/table/tbody/tr[" & count & "]/td[1]/p/a", varListingIDElement).innerText
</code>```

(The error is not occurring inside the 'getXPathElement' function, so no need to show that too. If you do want to take a look at it just ask and I'll post it here in an edit.)

When I debug from start to end with F8 I never get the error. Is it possible that the next call already starts before the previous one isn't finished yet?

Thanks in advance!

(Sorry if there are some dutch words I have overseen.)

答:
There are some cases where you can encounter an issue like this (where F8 always works, but a normal run doesn't) if the object return, in whatever way, isn't fully connected. It is difficult to say for certain if this is the case, and I have only encountered this when I am setting an object to something that has it's own process for initializing, and when this process is outside of the control of the VBA routine.

For your problem, specifically, there are a couple of approaches you can take:

```<code>Set varListingIDElement = html.getElementById("listing")
If Not varListingIDEElement is Nothing Then
    varShopName = getXPathElement("/table/tbody/tr[1]/td[1]/p/a", varListingIDElement).innerText
End If
</code>```

The above approach should prevent the error entirely, but it also means varShopName may not be set.

On the other hand:

```<code>Set varListingIDElement = html.getElementById("listing")

Application.Wait(Now + TimeValue("00:00:03"))

varShopName = getXPathElement("/table/tbody/tr[1]/td[1]/p/a", varListingIDElement).innerText
</code>```

This will force the application to wait three seconds between the initial setting of the variable, and the final calling of the variable. You could use this approach if it is indeed an issue of the prior process not finishing before the new one begins. You could also combine this approach with the first to get the best of both.

Good luck!

Body:
Hi I have this weird problem where I get error 91 ("object variable or with block variable not set"). I do not always get the error when I run the script, only now and then (random). I have tried to do as much as I can without success.

I am scraping a site to get the most recent prices of some pc components.

In order to do that I made a script and call the script sequentially multiple times for different parts. The error is not related to a specific part. I get the error randomly on all the parts. Sometimes I can do all the calls without any errors.

The script (not the full script, only what you need):

Sub ImportUrlData(url As String)

    Dim ie As InternetExplorer
    Dim html As HTMLDocument
    Dim varListingIDElement As IHTMLElement
    Dim varShopName As String
    varShopName = ""

    Set ie = New InternetExplorer
    ie.Visible = False
    ie.navigate url

    Do While ie.readyState <> READYSTATE_COMPLETE
        DoEvents
    Loop

    Set html = ie.document

    Set varListingIDElement = html.getElementById("listing")
    varShopName = getXPathElement("/table/tbody/tr[1]/td[1]/p/a", varListingIDElement).innerText

I always get the error on this last line:

varShopName = getXPathElement("/table/tbody/tr[" & count & "]/td[1]/p/a", varListingIDElement).innerText

(The error is not occurring inside the 'getXPathElement' function, so no need to show that too. If you do want to take a look at it just ask and I'll post it here in an edit.)

When I debug from start to end with F8 I never get the error. Is it possible that the next call already starts before the previous one isn't finished yet?

Thanks in advance!

(Sorry if there are some dutch words I have overseen.)

Body:
There are some cases where you can encounter an issue like this (where F8 always works, but a normal run doesn't) if the object return, in whatever way, isn't fully connected. It is difficult to say for certain if this is the case, and I have only encountered this when I am setting an object to something that has it's own process for initializing, and when this process is outside of the control of the VBA routine.

For your problem, specifically, there are a couple of approaches you can take:

Set varListingIDElement = html.getElementById("listing")
If Not varListingIDEElement is Nothing Then
    varShopName = getXPathElement("/table/tbody/tr[1]/td[1]/p/a", varListingIDElement).innerText
End If

The above approach should prevent the error entirely, but it also means varShopName may not be set.

On the other hand:

Set varListingIDElement = html.getElementById("listing")

Application.Wait(Now + TimeValue("00:00:03"))

varShopName = getXPathElement("/table/tbody/tr[1]/td[1]/p/a", varListingIDElement).innerText

This will force the application to wait three seconds between the initial setting of the variable, and the final calling of the variable. You could use this approach if it is indeed an issue of the prior process not finishing before the new one begins. You could also combine this approach with the first to get the best of both.

Good luck!


问:
Averaging and decreasing the array (vector) C++
I've got an array (actually std::vector) size ~ 7k elements.
If you draw this data, there will be a diagram of the combustion of the fuel. But I want to minimize this vector from 7k elements to 721 (every 0.5 degree) elements or ~ 1200 (every 0.3 degree). Of course I want save diagram the same. How can I do it?
Now I am getting every 9 element from big vector to new and cutting other evenly from front and back of vector to get 721 size.

```<code>QVector <double> newVMTVector;
for(QVector <double>::iterator itv = oldVmtDataVector.begin(); itv < oldVmtDataVector.end() - 9; itv+=9){
    newVMTVector.push_back(*itv);
}
auto useless = newVMTVector.size() - 721;
if(useless%2 == 0){
    newVMTVector.erase(newVMTVector.begin(), newVMTVector.begin() + useless/2);
    newVMTVector.erase(newVMTVector.end() - useless/2, newVMTVector.end());
}
else{
    newVMTVector.erase(newVMTVector.begin(), newVMTVector.begin() + useless/2+1);
    newVMTVector.erase(newVMTVector.end() - useless/2, newVMTVector.end());
}
newVMTVector.squeeze();
oldVmtDataVector.clear();
oldVmtDataVector = newVMTVector;
</code>```

I can swear there is an algorithm that averages and reduces the array.

答:
The way I understand it you want to pick the elements [0, k, 2k, 3k ... ] where n is 10 or n is 6.

Here's a simple take:

```<code>template <typename It>
It strided_inplace_reduce(It it, It const last, size_t stride) {
    It out = it;
    if (stride < 1) return last;

    while (it < last)
    {
        *out++ = *it;
        std::advance(it, stride);
    }

    return out;
}
</code>```

Generalizing a bit for non-random-access iterators:

Live On Coliru

```<code>#include <iterator>

namespace detail {
    // version for random access iterators
    template <typename It>
    It strided_inplace_reduce(It it, It const last, size_t stride, std::random_access_iterator_tag) {
        It out = it;
        if (stride < 1) return last;

        while (it < last)
        {
            *out++ = *it;
            std::advance(it, stride);
        }

        return out;
    }

    // other iterator categories
    template <typename It>
    It strided_inplace_reduce(It it, It const last, size_t stride, ...) {
        It out = it;
        if (stride < 1) return last;

        while (it != last) {
            *out++ = *it;
            for (size_t n = stride; n && it != last; --n)
            {
                it = std::next(it);
            }
        }

        return out;
    }
}

template <typename Range>
auto strided_inplace_reduce(Range& range, size_t stride) {
    using std::begin;
    using std::end;

    using It = decltype(begin(range));
    It it = begin(range), last = end(range);

    return detail::strided_inplace_reduce(it, last, stride, typename std::iterator_traits<It>::iterator_category{});
}

#include <vector>
#include <list>
#include <iostream>

int main() {
    {
        std::vector<int> v { 1,2,3,4,5,6,7,8,9 };
        v.erase(strided_inplace_reduce(v, 2), v.end());

        std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout << "\nv: ", " "));
    }
    {
        std::list<int> l { 1,2,3,4,5,6,7,8,9 };
        l.erase(strided_inplace_reduce(l, 4), l.end());

        std::copy(l.begin(), l.end(), std::ostream_iterator<int>(std::cout << "\nl: ", " "));
    }
}
</code>```

Prints

```<code>v: 1 3 5 7 9
l: 1 5 9
</code>```

Body:
I've got an array (actually std::vector) size ~ 7k elements.
If you draw this data, there will be a diagram of the combustion of the fuel. But I want to minimize this vector from 7k elements to 721 (every 0.5 degree) elements or ~ 1200 (every 0.3 degree). Of course I want save diagram the same. How can I do it?
Now I am getting every 9 element from big vector to new and cutting other evenly from front and back of vector to get 721 size.

QVector <double> newVMTVector;
for(QVector <double>::iterator itv = oldVmtDataVector.begin(); itv < oldVmtDataVector.end() - 9; itv+=9){
    newVMTVector.push_back(*itv);
}
auto useless = newVMTVector.size() - 721;
if(useless%2 == 0){
    newVMTVector.erase(newVMTVector.begin(), newVMTVector.begin() + useless/2);
    newVMTVector.erase(newVMTVector.end() - useless/2, newVMTVector.end());
}
else{
    newVMTVector.erase(newVMTVector.begin(), newVMTVector.begin() + useless/2+1);
    newVMTVector.erase(newVMTVector.end() - useless/2, newVMTVector.end());
}
newVMTVector.squeeze();
oldVmtDataVector.clear();
oldVmtDataVector = newVMTVector;

I can swear there is an algorithm that averages and reduces the array.

Body:
The way I understand it you want to pick the elements [0, k, 2k, 3k ... ] where n is 10 or n is 6.

Here's a simple take:

template <typename It>
It strided_inplace_reduce(It it, It const last, size_t stride) {
    It out = it;
    if (stride < 1) return last;

    while (it < last)
    {
        *out++ = *it;
        std::advance(it, stride);
    }

    return out;
}

Generalizing a bit for non-random-access iterators:

Live On Coliru

#include <iterator>

namespace detail {
    // version for random access iterators
    template <typename It>
    It strided_inplace_reduce(It it, It const last, size_t stride, std::random_access_iterator_tag) {
        It out = it;
        if (stride < 1) return last;

        while (it < last)
        {
            *out++ = *it;
            std::advance(it, stride);
        }

        return out;
    }

    // other iterator categories
    template <typename It>
    It strided_inplace_reduce(It it, It const last, size_t stride, ...) {
        It out = it;
        if (stride < 1) return last;

        while (it != last) {
            *out++ = *it;
            for (size_t n = stride; n && it != last; --n)
            {
                it = std::next(it);
            }
        }

        return out;
    }
}

template <typename Range>
auto strided_inplace_reduce(Range& range, size_t stride) {
    using std::begin;
    using std::end;

    using It = decltype(begin(range));
    It it = begin(range), last = end(range);

    return detail::strided_inplace_reduce(it, last, stride, typename std::iterator_traits<It>::iterator_category{});
}

#include <vector>
#include <list>
#include <iostream>

int main() {
    {
        std::vector<int> v { 1,2,3,4,5,6,7,8,9 };
        v.erase(strided_inplace_reduce(v, 2), v.end());

        std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout << "\nv: ", " "));
    }
    {
        std::list<int> l { 1,2,3,4,5,6,7,8,9 };
        l.erase(strided_inplace_reduce(l, 4), l.end());

        std::copy(l.begin(), l.end(), std::ostream_iterator<int>(std::cout << "\nl: ", " "));
    }
}

Prints

v: 1 3 5 7 9
l: 1 5 9


问:
How to reset the value of counter everytime when window closes in local storage in angular?
I made an app named counter app which counts the value on how many times click on the button. I am successful in storing the value when the page loads but my counter value is not reset when I close my window. Can someone suggest me something?

```<code>var app = angular.module('counter', [])
    app.controller("myCtrl", ["$scope", function($scope) {
        $scope.counter = localStorage.getItem('counter');
        $scope.increment = function() {
            $scope.counter = parseInt($scope.counter )+ 1;
        localStorage.setItem('counter', $scope.counter);
        };
        $scope.decrement = function () {
            $scope.counter = $scope.counter - 1;
            localStorage.setItem('counter', $scope.counter);
        }
        $scope.reset = function() {
            $scope.counter = $scope.counter = 0;
            localStorage.setItem('counter', $scope.counter);
        }
        console.log(localStorage.getItem('counter'));
    }]);
</code>```

I changed the code to session storage from local storage but still I won't be able to reset my counter value.

答:
so if you wants to reset the values of your browser storage, on closing of the window. Then prefer way is to use sessionstorage instead of localstorage. Session storage persist value till the point window is not closed, as Window is closed, sessionStorage is lost. and localStorage persist the data  till the things are not cleared from browser itself.

Not much just replace:
localStorage with sessionStorage

Body:
I made an app named counter app which counts the value on how many times click on the button. I am successful in storing the value when the page loads but my counter value is not reset when I close my window. Can someone suggest me something?

var app = angular.module('counter', [])
    app.controller("myCtrl", ["$scope", function($scope) {
        $scope.counter = localStorage.getItem('counter');
        $scope.increment = function() {
            $scope.counter = parseInt($scope.counter )+ 1;
        localStorage.setItem('counter', $scope.counter);
        };
        $scope.decrement = function () {
            $scope.counter = $scope.counter - 1;
            localStorage.setItem('counter', $scope.counter);
        }
        $scope.reset = function() {
            $scope.counter = $scope.counter = 0;
            localStorage.setItem('counter', $scope.counter);
        }
        console.log(localStorage.getItem('counter'));
    }]);

I changed the code to session storage from local storage but still I won't be able to reset my counter value.


问:
How to upload file by PHP cURL using ftp connection?
I am using this script to upload myfile by curl function and ftp connection.

In local it works fine but in my server file is appeared uploaded but it have zero file size.

what is wrong? Thank You.

```<code>$ch = curl_init();
$localfile = (dirname(__FILE__).'/asset/myfile.zip');
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, "ftp://$user_name:$user_pass@$server/".'myfile.zip');
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
curl_close ($ch);
</code>```

and also how can I upload multiple files in this script like:

```<code>$localfile1 = (dirname(__FILE__).'/asset/myfile1.zip');
$localfile2 = (dirname(__FILE__).'/asset/myfile2.zip');
$localfile3 = (dirname(__FILE__).'/asset/myfile3.zip');
</code>```

答:
To upload the file in curl you can use the curl_file_create.Try the below one:</p>

```<code>$localfile = (dirname(__FILE__).'/asset/myfile.zip');
$curl_file = curl_file_create($localfile,'zip');
$params = ['file' => $curl_file];

$ch = curl_init();
$localfile = (dirname(__FILE__).'/asset/myfile.zip');
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, "ftp://$user_name:$user_pass@$server/".'myfile.zip');
curl_setopt($ch, CURLOPT_UPLOAD, 1);
//curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
curl_close ($ch);
</code>```

Body:
I am using this script to upload myfile by curl function and ftp connection.

In local it works fine but in my server file is appeared uploaded but it have zero file size.

what is wrong? Thank You.

$ch = curl_init();
$localfile = (dirname(__FILE__).'/asset/myfile.zip');
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, "ftp://$user_name:$user_pass@$server/".'myfile.zip');
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
curl_close ($ch);

and also how can I upload multiple files in this script like:

$localfile1 = (dirname(__FILE__).'/asset/myfile1.zip');
$localfile2 = (dirname(__FILE__).'/asset/myfile2.zip');
$localfile3 = (dirname(__FILE__).'/asset/myfile3.zip');

Body:
To upload the file in curl you can use the curl_file_create.Try the below one:

$localfile = (dirname(__FILE__).'/asset/myfile.zip');
$curl_file = curl_file_create($localfile,'zip');
$params = ['file' => $curl_file];

$ch = curl_init();
$localfile = (dirname(__FILE__).'/asset/myfile.zip');
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, "ftp://$user_name:$user_pass@$server/".'myfile.zip');
curl_setopt($ch, CURLOPT_UPLOAD, 1);
//curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
curl_close ($ch);


问:
Securing file uploads inside the document root PHP
After reading several threads and articles about securing file uploads I want to check if I have sufficiently secured my uploads. Please notice that I do only have limited admin rights, which makes it difficult to upload/access/manage files outside of the document root.

My uploads folder is in /html/uploads.

For now, I have done the following:

I removed the public rights to read, write or execute from the uploads folder

I removed the group rights to read, write or execute from the uploads folder

I have inserted accept="image/*,.doc, .docx,.pdf" into the <input/> tag.

I check on errors, the max size and the extension via

```<code>foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
    $break = "yes";
    continue; // Skip file if any error found
}
</code>```

and following with checks on max-size and extension

The max number of files uploaded has been limited to 6 by the server

I rename the files after being uploaded

Now since I have read lots about saving files outside of the document root and being unexperienced with uploads, I am not sure if this is enough to make the uploads of the page "safe". Is it ok like this or is it simply not possible to make it "safe" when saving it not outside the document root?

答:
The best thing you can do (if you can't do anything outside your document root) is add a .htaccess file to your uploads folder:

```<code>deny from all
</code>```

This will prevent any access to the files over the internet, which is basically as good as having them outside the document root. This way, even if someone finds a loophole around your upload validation, they can't access the files directly online. In particular, this means they can't upload a PHP file and trick your server into executing it.

Body:
After reading several threads and articles about securing file uploads I want to check if I have sufficiently secured my uploads. Please notice that I do only have limited admin rights, which makes it difficult to upload/access/manage files outside of the document root.

My uploads folder is in /html/uploads.

For now, I have done the following:

I removed the public rights to read, write or execute from the uploads folder

I removed the group rights to read, write or execute from the uploads folder

I have inserted accept="image/*,.doc, .docx,.pdf" into the <input/> tag.

I check on errors, the max size and the extension via

foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
    $break = "yes";
    continue; // Skip file if any error found
}

and following with checks on max-size and extension

The max number of files uploaded has been limited to 6 by the server

I rename the files after being uploaded

Now since I have read lots about saving files outside of the document root and being unexperienced with uploads, I am not sure if this is enough to make the uploads of the page "safe". Is it ok like this or is it simply not possible to make it "safe" when saving it not outside the document root?

Body:
The best thing you can do (if you can't do anything outside your document root) is add a .htaccess file to your uploads folder:

deny from all

This will prevent any access to the files over the internet, which is basically as good as having them outside the document root. This way, even if someone finds a loophole around your upload validation, they can't access the files directly online. In particular, this means they can't upload a PHP file and trick your server into executing it.


问:
Error while defining map in clojure
I am new clojure and am not able to understand exact issue while running this code

```<code>(def my-map {name "Srini" empid "10000"})
</code>```

Receving this error:

CompilerException java.lang.RuntimeException: Unable to resolve symbol: empid in this context, compiling:(/Users/srini/Downloads/clojureexample/my-stugg/src/my_stugg/corecomponents.clj:95:1)

```<code>(def my-map {name "Srini" :empid "10000"})
</code>```

Running successfully.

What wrong I am doing in the first line?

```<code>(def my-map {name "Srini" empid "10000"})
</code>```

答:
Clojure is trying to resolve empid and can't, so it returns an error.

Clojure allows you to define maps with most anything as a key. This includes keywords and strings, which are very common, but also symbols, functions, numbers, data structures such as vectors and other maps, and more.

Your example contains one valid mapping, that is, the function bound to name which maps to the string "Srini". However, the other mapping is invalid because empid is not bound to anything.

The most common case is to use keywords for your keys, which have a particular advantage of allowing the values to be accessed via the keywords in a safe (non-NullPointerException-causing) way:

```<code>(:name {:name "Srini" :empid 10000})
=> "Srini"
</code>```

So, while there may be a case where you'd want to map a function to something, this is clearly not the right way for you here. (as an aside, strings as keywords are particularly useful when reading from a file or database where the data is already a string and there's no advantage to converting to and from a keyword.

Title: Error while defining map in clojure

Body:
I am new clojure and am not able to understand exact issue while running this code

(def my-map {name "Srini" empid "10000"})

Receving this error:

CompilerException java.lang.RuntimeException: Unable to resolve symbol: empid in this context, compiling:(/Users/srini/Downloads/clojureexample/my-stugg/src/my_stugg/corecomponents.clj:95:1)

(def my-map {name "Srini" :empid "10000"})

Running successfully.

What wrong I am doing in the first line?

(def my-map {name "Srini" empid "10000"})

Body:
Clojure is trying to resolve empid and can't, so it returns an error.

Clojure allows you to define maps with most anything as a key. This includes keywords and strings, which are very common, but also symbols, functions, numbers, data structures such as vectors and other maps, and more.

Your example contains one valid mapping, that is, the function bound to name which maps to the string "Srini". However, the other mapping is invalid because empid is not bound to anything.

The most common case is to use keywords for your keys, which have a particular advantage of allowing the values to be accessed via the keywords in a safe (non-NullPointerException-causing) way:

(:name {:name "Srini" :empid 10000})
=> "Srini"

So, while there may be a case where you'd want to map a function to something, this is clearly not the right way for you here. (as an aside, strings as keywords are particularly useful when reading from a file or database where the data is already a string and there's no advantage to converting to and from a keyword.


问:
How can I call a method within mutation method using VueJS 2?
I got a problem here. I don't know how to call a method within mutation method, I've tried this.show() but it doesn't work, is there's a way like actions in vuex that you can call a method within the action using dispatch ?

```<code>// Mutation
export default {
    show(state, payload) {
       // execute code
    },
    hide(state, payload) {
       // how to call show method?
    }
}
</code>```

I want mutation look like this

```<code>// Action
export default {
    show({ state }, payload) {
       // execute code
    },
    hide({ dispatch, state }, payload) {
      // how to call show method look like this in mutation?
      // Is this possible for mutation?
      return dispatch('show', payload)
    }
}
</code>```

答: In VueJS 2 you should use $emit instead of $broadcast as described in documentation - https://v2.vuejs.org/v2/guide/migration.html#dispatch-and-broadcast-replaced

Body:
I got a problem here. I don't know how to call a method within mutation method, I've tried this.show() but it doesn't work, is there's a way like actions in vuex that you can call a method within the action using dispatch ?

// Mutation
export default {
    show(state, payload) {
       // execute code
    },
    hide(state, payload) {
       // how to call show method?
    }
}

I want mutation look like this

// Action
export default {
    show({ state }, payload) {
       // execute code
    },
    hide({ dispatch, state }, payload) {
      // how to call show method look like this in mutation?
      // Is this possible for mutation?
      return dispatch('show', payload)
    }
}

ContentLicense: CC BY-SA 4.0


问:
purpose of $q service in angular?
I am not able to understand the use of $q service in angular js. Can some one please give elaboration on this topic that

what is the $q service in angularjs? How can we use that

答:
I think article i wrote about $q might help you.

Introduction to $q

$q is an angular define a service. It’s same as new Promise(). But $q takes things to the next level by enhancing additional feature that developers can use to perform complex tasks more simply.

This is a sample for creating promise using $q

```<code>angular.module("app",[])
.controller("ctrl",function($scope,$q){
  var work = "resolve";
  var promise = $q(function(resolve, reject) {
    if (work === "resolve") {
        resolve('response 1!');
    } else {
        reject('Oops... something went wrong');
    }
  });
  promise.then(function(data) {
    alert(data)

  })
})
</code>```

$q.defer()

$q.defer() return the instance of the promise constructor. Once you create a defer object there are following methods and properties that you can access from that object

resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.

reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.

notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.

promise – {Promise} – promise object associated with this deferred

Conclusion

Use $q for constructing promises from non-promise Objects/callbacks, and utilize $q.all() and $q.race() to work with existing promises.

Title: purpose of $q service in angular?

Body:
I think article i wrote about $q might help you.

Introduction to $q

$q is an angular define a service. It’s same as new Promise(). But $q takes things to the next level by enhancing additional feature that developers can use to perform complex tasks more simply.

This is a sample for creating promise using $q

angular.module("app",[])
.controller("ctrl",function($scope,$q){
  var work = "resolve";
  var promise = $q(function(resolve, reject) {
    if (work === "resolve") {
        resolve('response 1!');
    } else {
        reject('Oops... something went wrong');
    }
  });
  promise.then(function(data) {
    alert(data)

  })
})

$q.defer()

$q.defer() return the instance of the promise constructor. Once you create a defer object there are following methods and properties that you can access from that object

resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.

reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.

notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.

promise – {Promise} – promise object associated with this deferred

Conclusion

Use $q for constructing promises from non-promise Objects/callbacks, and utilize $q.all() and $q.race() to work with existing promises.


问:
How to Add Views to the Scroll View in Android?
I create the following code to create the Bar Chart and Pie Chart using Canvas.

Here is my code

```<code>public class ChartDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //ScrollView sv = new ScrollView(this);

    LinearLayout llay = new LinearLayout(this);
    llay.setOrientation(LinearLayout.VERTICAL);

    float[] values = { 50, 100, 50, 20, 30, 60, 100, 90 };

    // Bar Chart
    BarGraph BarChart = new BarGraph(this, values);
    llay.addView(BarChart);

    //Pie Chart
    PieChartView Pie = new PieChartView(this, values);
    llay.addView(Pie);

    //sv.addView(llay);

    setContentView(llay);
    //setContentView(sv);
   }
 }
</code>```

The above code show the BarChart only.
I change my code like the following it gives the Black(blank)Screen only.With out no error and exception

```<code>  public class ChartDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ScrollView sv = new ScrollView(this);

    LinearLayout llay = new LinearLayout(this);
    llay.setOrientation(LinearLayout.VERTICAL);

    float[] values = { 50, 100, 50, 20, 30, 60, 100, 90 };

    // Bar Chart
    BarGraph BarChart = new BarGraph(this, values);
    llay.addView(BarChart);

    //Pie Chart
    PieChartView Pie = new PieChartView(this, values);
    llay.addView(Pie);

    sv.addView(llay);

    setContentView(sv);
   }
 }
</code>```

And i create my Chart Views like the following

```<code>public class PieChartView extends View {

private float[] Values;

public PieChartView(Context context, float[] Values) {
    super(context);

    this.Values = Values;

}

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

               .......
               .........

        }

}
</code>```

I need to add both chart in Single Screen with Scroll View . But i am not able to add Both in the single Activity.How to do this ??

答:
when you add programmatically views to some layout, like LinearLayout or ScrollView (which derives from FrameLayout), you should set layout parameters on your views, something like this (just an example):

```<code>BarGraph BarChart = new BarGraph(this, values);
// be sure to use correct layout params for your layout
LinearLayout.LayoutParams llp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.weight = 1.0f;
BarChart.setLayoutParams(llp);
llay.addView(BarChart);

FrameLayout.LayoutParams flp = new /* ... */;
llay.setLayoutParams(flp);

sv.addView(llay);
</code>```

if you don't set them, they get default ones depending on the layout, and they might do the job or not depending on the added views.
(btw conventionally in Java variables names begin with lower case)

Body:
I create the following code to create the Bar Chart and Pie Chart using Canvas.

Here is my code

public class ChartDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //ScrollView sv = new ScrollView(this);

    LinearLayout llay = new LinearLayout(this);
    llay.setOrientation(LinearLayout.VERTICAL);

    float[] values = { 50, 100, 50, 20, 30, 60, 100, 90 };

    // Bar Chart
    BarGraph BarChart = new BarGraph(this, values);
    llay.addView(BarChart);

    //Pie Chart
    PieChartView Pie = new PieChartView(this, values);
    llay.addView(Pie);

    //sv.addView(llay);

    setContentView(llay);
    //setContentView(sv);
   }
 }

The above code show the BarChart only.
I change my code like the following it gives the Black(blank)Screen only.With out no error and exception

  public class ChartDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ScrollView sv = new ScrollView(this);

    LinearLayout llay = new LinearLayout(this);
    llay.setOrientation(LinearLayout.VERTICAL);

    float[] values = { 50, 100, 50, 20, 30, 60, 100, 90 };

    // Bar Chart
    BarGraph BarChart = new BarGraph(this, values);
    llay.addView(BarChart);

    //Pie Chart
    PieChartView Pie = new PieChartView(this, values);
    llay.addView(Pie);

    sv.addView(llay);

    setContentView(sv);
   }
 }

And i create my Chart Views like the following

public class PieChartView extends View {

private float[] Values;

public PieChartView(Context context, float[] Values) {
    super(context);

    this.Values = Values;

}

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

               .......
               .........

        }

}

I need to add both chart in Single Screen with Scroll View . But i am not able to add Both in the single Activity.How to do this ??

Body:
when you add programmatically views to some layout, like LinearLayout or ScrollView (which derives from FrameLayout), you should set layout parameters on your views, something like this (just an example):

BarGraph BarChart = new BarGraph(this, values);
// be sure to use correct layout params for your layout
LinearLayout.LayoutParams llp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.weight = 1.0f;
BarChart.setLayoutParams(llp);
llay.addView(BarChart);

FrameLayout.LayoutParams flp = new /* ... */;
llay.setLayoutParams(flp);

sv.addView(llay);

if you don't set them, they get default ones depending on the layout, and they might do the job or not depending on the added views.
(btw conventionally in Java variables names begin with lower case)


问:
how to include external css and javascript in riot tag?
I want to create a tag for a carousel, but I only want to load the CSS and Javascript files when this tag is used on the site, but I can only make it work if I add it to the  of my website.

Is there a way to only load is in the tag?

my tag example (that only works if I move the css and .js files into the website body:

```<code><carousel>
  <div class="row" hide="{$gg.filterApplied || $gg.redeem.redeemInProgress()}">
    <div class="col-sm-12">
      <div class="logos text-center">
        <div class="divider"></div>
        <div data-slick='{"slidesToShow": 4, "slidesToScroll": 4}'>
          <div><h3>1</h3></div>
          <div><h3>2</h3></div>
          <div><h3>3</h3></div>
          <div><h3>4</h3></div>
          <div><h3>5</h3></div>
          <div><h3>6</h3></div>
        </div>
        <div class="divider"></div>
      </div>
    </div>
  </div>

  <style scoped>
    @import url("//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css")
  </style>

  <script src="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js"></script>
  <script>
    var self = this;
    self.mixin(SharedMixin)
  </script>
</carousel>
</code>```

答:
I had a similar problem and I solved in this way.

I added a method to tags, using a mixin, to load resources at runtime and I call it before-mount is fired, passing a list of css and js files.

It uses the function getScript of jQuery.

```<code>loadResources(css, js, callback){
    for(var i = 0; i < css.length; i++){
        if(css[i] !== ''){
            var link = document.createElement('link');
            link.setAttribute("rel", "stylesheet");
            link.setAttribute("type", "text/css");
            link.setAttribute("href", css[i]);
            document.getElementsByTagName("head")[0].appendChild(link);
        }
    }
    var jsProgress = 0;
    for(var j = 0; j < js.length; j++){
        $.getScript(js[j], function () {
            if (++jsProgress == js.length && typeof callback !== 'undefined') callback();
        });
    }
}
</code>```

Body:
I want to create a tag for a carousel, but I only want to load the CSS and Javascript files when this tag is used on the site, but I can only make it work if I add it to the  of my website.

Is there a way to only load is in the tag?

my tag example (that only works if I move the css and .js files into the website body:

<carousel>

1

2

3

4

5

6

</carousel>

Body:
I had a similar problem and I solved in this way.

I added a method to tags, using a mixin, to load resources at runtime and I call it before-mount is fired, passing a list of css and js files.

It uses the function getScript of jQuery.

loadResources(css, js, callback){
    for(var i = 0; i < css.length; i++){
        if(css[i] !== ''){
            var link = document.createElement('link');
            link.setAttribute("rel", "stylesheet");
            link.setAttribute("type", "text/css");
            link.setAttribute("href", css[i]);
            document.getElementsByTagName("head")[0].appendChild(link);
        }
    }
    var jsProgress = 0;
    for(var j = 0; j < js.length; j++){
        $.getScript(js[j], function () {
            if (++jsProgress == js.length && typeof callback !== 'undefined') callback();
        });
    }
}


问:
what would be a quick way to read a property file in python?
I have a file with the format

```<code>VarName=Value
.
.
</code>```

I want to read it into a hash such that H("VarName") will return the value.

What would be a quick way? (read a set of strings, split all of them where the equality sign is, and then put it into a hash?

I am working with python.

答:
For python2 there is a jproperties https://pypi.python.org/pypi/jproperties/1.0.1

For python2/3 there is javaproperties http://javaproperties.readthedocs.io/en/v0.1.0/

as simple as:

```<code>import os, javaproperties
with open(file, 'rb') as f:
    properties_dict = javaproperties.load(f)
</code>```

Body:
I have a file with the format

VarName=Value
.
.

I want to read it into a hash such that H("VarName") will return the value.

What would be a quick way? (read a set of strings, split all of them where the equality sign is, and then put it into a hash?

I am working with python.

Body:
For python2 there is a jproperties https://pypi.python.org/pypi/jproperties/1.0.1

For python2/3 there is javaproperties http://javaproperties.readthedocs.io/en/v0.1.0/

as simple as:

import os, javaproperties
with open(file, 'rb') as f:
    properties_dict = javaproperties.load(f)


问:
Drupal update.php white screening
Tried everything..

Permissions, error logs, re-cloning, etc.

Works fine on another workstation so can't be the application code.

Any ideas?

答: Upload some small script containing only phpinfo(); call, find out what php.ini file is used and edit it. Turn on error display. If web server is working it can't return empty screen - there must by some error message if errors are enabled.

Title: Drupal update.php white screening


问:
Disable Bootstrap tab with eventkey in ract.js
I am using React Bootstrap in my react.js page. I want to disable tabs based on a button click and i don't want set default disable attribute.
Is there any way

```<code><Tabs activeKey={this.state.key} onSelect={this.handleSelect} id="uncontrolled-tab-example">
      <Tab eventKey={1} title="Customer" className="studenttab">
      </Tab>
      <Tab eventKey={2} title="Customer" className="admintab">
      </Tab>
     <Tab eventKey={3} title="Customer" className="othertab">
      </Tab>
</Tabs>
</code>```

答:
You could try to pass a boolean prop isAdmin to the parent component that tells, whether the current user is admin and then use it in the component:

<Tabs activeKey={this.state.key} onSelect={this.handleSelect} id="uncontrolled-tab-example">
      <Tab eventKey={1} title="Student" disabled={this.props.isAdmin} className="studenttab" />
      <Tab eventKey={2} title="Admin" className="admintab" />
     <Tab eventKey={3} title="Other" disabled={this.props.isAdmin} className="othertab" />
</Tabs>
```

Body:
I am using React Bootstrap in my react.js page. I want to disable tabs based on a button click and i don't want set default disable attribute.
Is there any way

<Tabs activeKey={this.state.key} onSelect={this.handleSelect} id="uncontrolled-tab-example">
      <Tab eventKey={1} title="Customer" className="studenttab">
      </Tab>
      <Tab eventKey={2} title="Customer" className="admintab">
      </Tab>
     <Tab eventKey={3} title="Customer" className="othertab">
      </Tab>
</Tabs>


问:
Returning sequential numbers
Assume Col contains system name "Apple". Col B has a bunch of ID's associated with system in Col A. These ID's mean something wrt the system. Col C has the timestamp at which these ID's are generated by the system.

This is the query I wrote to obtain the above data:

```<code>SELECT Name, ID, time
FROM Xtable
WHERE (Name='Apple') AND ID in ('1', '2', '3', '4')
GROUP BY Name, ID, time
</code>```

The problem with this query is that it returns rows as long as it contains one of the above numbers (not necessarily in a sequence)

Output of the above query:

```<code>Apple   3    12/1/2010 11:04 AM
Apple   4    12/1/2010 11:58 AM
Apple   1    12/1/2010 11:00 AM
Apple   1    12/1/2010 11:01 AM
Apple   1    12/1/2010 09:05 AM
Apple   2    12/1/2010 09:10 AM
Apple   3    12/1/2010 09:40 AM
Apple   4    12/1/2010 10:00 AM
Apple   2    12/4/2010 03:25 PM
Apple   1    12/4/2010 12:47 PM
.
.
.
.
.
.
</code>```

I want to tweak it such that it returns values in all three columns only when the IDs in Column B occur in a sequence (1,2,3,4). I want this information because the sequential IDs represent a set of events that I'm using to extract some information.

答: It doesn't matter if Event ID 2 occurs before ID 1. All I want is all 4 ID's (1, 2, 3, and 4) to occur in consecutive rows. The IDs mean something only if all them appear together. I mean, if there are any repeating IDs like: 3, 3, 4, 2, 1; I want the first 3 to be excluded from the output.</p>

Title: Returning sequential numbers

Body:
Assume Col contains system name "Apple". Col B has a bunch of ID's associated with system in Col A. These ID's mean something wrt the system. Col C has the timestamp at which these ID's are generated by the system.

This is the query I wrote to obtain the above data:

SELECT Name, ID, time
FROM Xtable
WHERE (Name='Apple') AND ID in ('1', '2', '3', '4')
GROUP BY Name, ID, time

The problem with this query is that it returns rows as long as it contains one of the above numbers (not necessarily in a sequence)

Output of the above query:

Apple   3    12/1/2010 11:04 AM
Apple   4    12/1/2010 11:58 AM
Apple   1    12/1/2010 11:00 AM
Apple   1    12/1/2010 11:01 AM
Apple   1    12/1/2010 09:05 AM
Apple   2    12/1/2010 09:10 AM
Apple   3    12/1/2010 09:40 AM
Apple   4    12/1/2010 10:00 AM
Apple   2    12/4/2010 03:25 PM
Apple   1    12/4/2010 12:47 PM
.
.
.
.
.
.

I want to tweak it such that it returns values in all three columns only when the IDs in Column B occur in a sequence (1,2,3,4). I want this information because the sequential IDs represent a set of events that I'm using to extract some information.


问:
Adding value to column depending on LIKE
I have SSMS 2008 R2. This is my table

```<code>PK | DateOf           | Other Columns | Items
01 | 05/30/2017 15:30 | Blah          | truck, elephant, apple, . . .
02 | 04/15/2012 07:07 | Bluh          | foot, orange, horse, . . .
03 | 11/01/2016 10:30 | Wham          | apple, screen, penny, . . .
</code>```

I am trying to search the Items column for each record and count how many times the fruits occur. Conveniently enough, there will only be a single fruit for each record, but it would be cool if the solution would be able to handle several fruits (maybe even duplicates). The result table would look like this for the above

```<code>Count | Fruit
2     | Apple
1     | Orange
</code>```

I have a complete list of the "fruits". I was trying to figure out how to make it work with LIKE's.

```<code>SELECT
count(PK) AS [Count]
??? AS [Fruit]
WHERE DateOf >= '2011-01-01 00:00' AND DateOf < '2012-01-01 00:00'
AND Items LIKE '%Apple%' --??(some kind of code that looks for the fruit values??)
</code>```

答:
You can use a simple outer apply to identify fruits if you have table with fruits. Like this:</p>

```<code>drop table if exists dbo.Details;
drop table if exists dbo.Fruits;

create table dbo.Details (
    PK int not null primary key
    , DateOf datetime2(3)
    , Items varchar(100)
);

create table dbo.Fruits (
    Fruit varchar(100) not null primary key
);

insert into dbo.Details (PK, DateOf, Items)
values (1, '20170530 15:30', 'truck, elephant, apple, . . .')
    , (2, '20120415 07:07', 'foot, orange, horse, . . .')
    , (3, '20161101 10:30', 'apple, screen, penny, orange, . . .')

insert into dbo.Fruits (Fruit)
values ('apple'), ('orange');

select
    d.PK, d.DateOf, d.Items, count(*) as CountOfFruit
from dbo.Details d
    outer apply (
            select
            *
            from dbo.Fruits f
            where d.Items like '%' + f.Fruit + '%'
    ) tf
group by d.PK, d.DateOf, d.Items
</code>```

Body:
I have SSMS 2008 R2. This is my table

PK | DateOf           | Other Columns | Items
01 | 05/30/2017 15:30 | Blah          | truck, elephant, apple, . . .
02 | 04/15/2012 07:07 | Bluh          | foot, orange, horse, . . .
03 | 11/01/2016 10:30 | Wham          | apple, screen, penny, . . .

I am trying to search the Items column for each record and count how many times the fruits occur. Conveniently enough, there will only be a single fruit for each record, but it would be cool if the solution would be able to handle several fruits (maybe even duplicates). The result table would look like this for the above

Count | Fruit
2     | Apple
1     | Orange

I have a complete list of the "fruits". I was trying to figure out how to make it work with LIKE's.

SELECT
count(PK) AS [Count]
??? AS [Fruit]
WHERE DateOf >= '2011-01-01 00:00' AND DateOf < '2012-01-01 00:00'
AND Items LIKE '%Apple%' --??(some kind of code that looks for the fruit values??)

Body:
You can use a simple outer apply to identify fruits if you have table with fruits. Like this:

drop table if exists dbo.Details;
drop table if exists dbo.Fruits;

create table dbo.Details (
    PK int not null primary key
    , DateOf datetime2(3)
    , Items varchar(100)
);

create table dbo.Fruits (
    Fruit varchar(100) not null primary key
);

insert into dbo.Details (PK, DateOf, Items)
values (1, '20170530 15:30', 'truck, elephant, apple, . . .')
    , (2, '20120415 07:07', 'foot, orange, horse, . . .')
    , (3, '20161101 10:30', 'apple, screen, penny, orange, . . .')

insert into dbo.Fruits (Fruit)
values ('apple'), ('orange');

select
    d.PK, d.DateOf, d.Items, count(*) as CountOfFruit
from dbo.Details d
    outer apply (
            select
            *
            from dbo.Fruits f
            where d.Items like '%' + f.Fruit + '%'
    ) tf
group by d.PK, d.DateOf, d.Items


问:
How to personalize the display of a ActiveRecord object in console
I have an object that when printed on the rails console looks like:

```<code>> Model.first
MyModel{
    id: 1
  role: 2
status: 5
}
</code>```

What options do I have in order to change the role and status to a more descriptive value? Let's say I have a hash on MyModel to specify what each thing is

```<code> class MyModel < AR
    STATUSES = {0: active, 1: inactive, etc...}
</code>```

How I can customize the output to use those values for printing using only the  rails console? I've tried with inspect without success.

PD. I'm aware that enum is an option, but for other reasons I would really like to customize the output of printing this object in console. I'm prety sure it's possible as AwesomePrint does it. For example, I also would like to hide some fields.

答:
As stated in the comments, you could use enum to get the result you are looking for. I think that is the best option you've got.

To use an enum just add it your model, for example:

```<code>class MyModel < ApplicationRecord
  enum status: { active: 0, inactive: 1, other: 5 }
  enum role: { admin: 0, user: 1, superuser: 2 }
end
</code>```

Notice that the key in the hash is a symbol with the description you want and the value is the data stored in the db.

Example:

pp MyModel.first
#<MyModel:0x007f89e736a600
 id: 4,
 role: "superuser",
 status: "other">
```

Additionally, with enums in place, you have a lot of methods created for you, so you don't need to use the db values again. Check the docs for more info.

Body:
I have an object that when printed on the rails console looks like:

> Model.first
MyModel{
    id: 1
  role: 2
status: 5
}

What options do I have in order to change the role and status to a more descriptive value? Let's say I have a hash on MyModel to specify what each thing is

 class MyModel < AR
    STATUSES = {0: active, 1: inactive, etc...}

How I can customize the output to use those values for printing using only the  rails console? I've tried with inspect without success.

PD. I'm aware that enum is an option, but for other reasons I would really like to customize the output of printing this object in console. I'm prety sure it's possible as AwesomePrint does it. For example, I also would like to hide some fields.

Body:
As stated in the comments, you could use enum to get the result you are looking for. I think that is the best option you've got.

To use an enum just add it your model, for example:

class MyModel < ApplicationRecord
  enum status: { active: 0, inactive: 1, other: 5 }
  enum role: { admin: 0, user: 1, superuser: 2 }
end

Notice that the key in the hash is a symbol with the description you want and the value is the data stored in the db.

Example:

pp MyModel.first
#<MyModel:0x007f89e736a600
 id: 4,
 role: "superuser",
 status: "other">

Additionally, with enums in place, you have a lot of methods created for you, so you don't need to use the db values again. Check the docs for more info.


问:
ECMAScript 6 support in PhpStorm 2016
I recently pulled in the latest Laravel 5.3. In the gulp.js file, there is the newer ES6 arrow function syntax:

```<code>elixir(mix => {
    mix.sass('app.scss')
       .webpack('app.js');
});
</code>```

PhpStorm 2016.2 shows this code error on that:

```<code>Expression statement is not assignment or call.
</code>```

Additionally, the code auto-formatter mucks everything up when it encounters this because it sees it as an error.

How do I get PhpStorm to stop showing that as an error?

答: MacOs: Menu > PhpStorm> Preferences > Languages & Frameworks > JavaScript and change JavaScript language version to ECMAScript 6

Title: ECMAScript 6 support in PhpStorm 2016

Body:
I recently pulled in the latest Laravel 5.3. In the gulp.js file, there is the newer ES6 arrow function syntax:

elixir(mix => {
    mix.sass('app.scss')
       .webpack('app.js');
});

PhpStorm 2016.2 shows this code error on that:

Expression statement is not assignment or call.

Additionally, the code auto-formatter mucks everything up when it encounters this because it sees it as an error.

How do I get PhpStorm to stop showing that as an error?


问:
How to correctly perform all-VS-all row-by-row comparisons between series in two pandas dataframes?
I have two pandas dataframes, df1 and df2. Both contain time series data.

df1

```<code>Event   Number  Timestamp_A
A       1       7:00
A       2       8:00
A       3       9:00
</code>```

df2

```<code>Event   Number  Timestamp_B
B       1       9:01
B       2       8:01
B       3       7:01
</code>```

Basically, I want to determine the Event B which is closest to Event A, and assign this correctly.

Therefore, I need to substract (1) every Timestamp_B in df2 from ever Timestamp_A in df1, row by row. This results in a series of values, of which I want to take the minumum and put it to a new column in df1.

```<code>Event   Number  Timestamp_A Closest_Timestamp_B
A       1       7:00        7:01
A       2       8:00        8:01
A       3       9:00        9:01
</code>```

I am not familiar with row-by-row operations in pandas.
When I am doing:

```<code>for index, row in df1.iterrows():
    s = df1.Timestamp_A.values - df2["Timestamp_B"][:]
    Closest_Timestamp_B = s.min()
</code>```

The result I get is a ValueError:

```<code>ValueError: operands could not be broadcast together with shapes(3,) (4,)
</code>```

How to correctly perform row-by-row comparisons between two pandas dataframes?

答:
Use apply to compare Timestamp_A on each row with all Timestamp_B and get the index of the row with min diff, then extract Timestamp_B using the index.</p>

```<code>df1['Closest_Timestamp_B'] = (
    df1.apply(lambda x: abs(pd.to_datetime(x.Timestamp_A).value -
                            df2.Timestamp_B.apply(lambda x: pd.to_datetime(x).value))
                            .idxmin(),axis=1)
       .apply(lambda x: df2.Timestamp_B.loc[x])
)

df1
Out[271]:
  Event  Number Timestamp_A Closest_Timestamp_B
0     A       1        7:00                7:01
1     A       2        8:00                8:01
2     A       3        9:00                9:01
</code>```

Body:
I have two pandas dataframes, df1 and df2. Both contain time series data.

df1

Event   Number  Timestamp_A
A       1       7:00
A       2       8:00
A       3       9:00

df2

Event   Number  Timestamp_B
B       1       9:01
B       2       8:01
B       3       7:01

Basically, I want to determine the Event B which is closest to Event A, and assign this correctly.

Therefore, I need to substract (1) every Timestamp_B in df2 from ever Timestamp_A in df1, row by row. This results in a series of values, of which I want to take the minumum and put it to a new column in df1.

Event   Number  Timestamp_A Closest_Timestamp_B
A       1       7:00        7:01
A       2       8:00        8:01
A       3       9:00        9:01

I am not familiar with row-by-row operations in pandas.
When I am doing:

for index, row in df1.iterrows():
    s = df1.Timestamp_A.values - df2["Timestamp_B"][:]
    Closest_Timestamp_B = s.min()

The result I get is a ValueError:

ValueError: operands could not be broadcast together with shapes(3,) (4,)

How to correctly perform row-by-row comparisons between two pandas dataframes?

Body:
Use apply to compare Timestamp_A on each row with all Timestamp_B and get the index of the row with min diff, then extract Timestamp_B using the index.

df1['Closest_Timestamp_B'] = (
    df1.apply(lambda x: abs(pd.to_datetime(x.Timestamp_A).value -
                            df2.Timestamp_B.apply(lambda x: pd.to_datetime(x).value))
                            .idxmin(),axis=1)
       .apply(lambda x: df2.Timestamp_B.loc[x])
)

df1
Out[271]:
  Event  Number Timestamp_A Closest_Timestamp_B
0     A       1        7:00                7:01
1     A       2        8:00                8:01
2     A       3        9:00                9:01