问:
httpd local virtualhost example
-- Original post ---

I'd like to setup a dev env to play with some apache features. I'm running httpd on fedora.

I added to hosts local redirects

```<code># cat /etc/hosts
127.0.0.1 example1.com
127.0.0.1 example2.com

# cmkdir /var/www/example1;      echo "Hello from /var/www/example1/index.html" > /var/www/example1/index.html
# cmkdir /var/www/example2;      echo "Hello from /var/www/example2/index.html" > /var/www/example2/index.html
# cmkdir /var/www/example2/sub ; echo "Hello from /var/www/example2/sub/index.html" > /var/www/example2/sub/index.html

# cvi /etc/httpd/conf/httpd.conf
<VirtualHost _default_:80>
    DocumentRoot "/var//www/html"
</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example1"
    ServerName example1.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2"
    ServerName example2.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2/sub"
    ServerName sub.example2.com
    ServerPath "/sub/"
    RewriteEngine On
    RewriteRule "^(/sub/.*)" "/var/www/example2$1"

</VirtualHost>

# capachectl -t ; apachectl restart

# curl localhost
Hello from /var/www/html/index.html
# curl example1.com
Hello from /var/www/example1/index.html
# curl example2.com
Hello from /var/www/example2/index.html
# curl sub.example2.com
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
... ( lots of stuff different from the one i echoed) ...
</code>```

If I do the same thing in local firefox - localhost works as expected, example1.com works as expected, but sub.example2.com redirects me to example2.com.

Can you please help me to figure out how to configure a local sub-domain? What is missing? Based on https://httpd.apache.org/docs/2.4/vhosts/examples.html I believe what I did is correct.

-- Edit / Update ---

If I follow the advice below from Newbie and change only the rewrite rule, without making any other changes from the setup above:

```<code>    <VirtualHost 127.0.0.1:80>
        DocumentRoot "/var/www/example2/sub"
        ServerName sub.example2.com
        ServerPath "/sub/"
#        RewriteEngine On
#        RewriteRule "^(/sub/.*)" "/var/www/example2$1"

    </VirtualHost>
</code>```

I get :

```<code># curl sub.example2.com
curl: (6) Could not resolve host: sub.example2.com
</code>```

If I

```<code># cat /etc/hosts | grep sub
127.0.0.1 example2.com sub.example2.com
</code>```

It works as expected

```<code>#curl example2.com
Hello from /var/www/example2/index.html
# curl sub.example2.com
Hello from /var/www/example2/sub/index.html
</code>```

Still this seems to be strange setup. I don't want to create /etc/hosts record for each sub-domain... Shouldn't it be possible to handle this situation only via the httpd VirtualHost setting, without changing the DNS settings locally or even worse - adding C records in the DNS of a domain(if not localhost)?  Any hint what I'm doing wrong? How can I get sub.example1.com to work without modifying the dns settings?

Regards,
Pavel

答:
Let me know if you run into problems.This dns would be able to work with your regular browsing since for all names it can't resolve it would check with googles dns and save it into its file.</p>

```<code>    install bind
apt-get install bind9 -y

cd /etc/bind

vim named.conf.options

And uncomment forwarders and two rows bellow and instead of 0.0.0.0 enter google's dns IP (8.8.8.8).

service bind9 restart

vim named.conf.options

zone "YOURDOMAIN NAME" {
        type master;
        file "db.site.com";
        notify yes;
        };

cp db.local /var/cache/bind/db.site.com
cd /var/cache/bind/
vim db.site.com

$TTL    604800
@       IN      SOA     admin. admin.itlink.edu. (
                              2         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
        IN NS ns.YOURDOMAINNAMEHERE.
        IN      A       192.168.1.10 replace this with the IP of your PC that has apache installed
ns      A       192.168.1.10 replace this with the IP of your PC that has apache installed
www     A       192.168.1.10 replace this with the IP of your PC that has

service bind9 restart
</code>```

Title: httpd local virtualhost example

Body:
-- Original post ---

I'd like to setup a dev env to play with some apache features. I'm running httpd on fedora.

I added to hosts local redirects

# cat /etc/hosts
127.0.0.1 example1.com
127.0.0.1 example2.com

# cmkdir /var/www/example1;      echo "Hello from /var/www/example1/index.html" > /var/www/example1/index.html
# cmkdir /var/www/example2;      echo "Hello from /var/www/example2/index.html" > /var/www/example2/index.html
# cmkdir /var/www/example2/sub ; echo "Hello from /var/www/example2/sub/index.html" > /var/www/example2/sub/index.html

# cvi /etc/httpd/conf/httpd.conf
<VirtualHost _default_:80>
    DocumentRoot "/var//www/html"
</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example1"
    ServerName example1.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2"
    ServerName example2.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2/sub"
    ServerName sub.example2.com
    ServerPath "/sub/"
    RewriteEngine On
    RewriteRule "^(/sub/.*)" "/var/www/example2$1"

</VirtualHost>

# capachectl -t ; apachectl restart

# curl localhost
Hello from /var/www/html/index.html
# curl example1.com
Hello from /var/www/example1/index.html
# curl example2.com
Hello from /var/www/example2/index.html
# curl sub.example2.com
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">

Body:
Let me know if you run into problems.This dns would be able to work with your regular browsing since for all names it can't resolve it would check with googles dns and save it into its file.

    install bind
apt-get install bind9 -y

cd /etc/bind

vim named.conf.options

And uncomment forwarders and two rows bellow and instead of 0.0.0.0 enter google's dns IP (8.8.8.8).

service bind9 restart

vim named.conf.options

zone "YOURDOMAIN NAME" {
        type master;
        file "db.site.com";
        notify yes;
        };

cp db.local /var/cache/bind/db.site.com
cd /var/cache/bind/
vim db.site.com

$TTL    604800
@       IN      SOA     admin. admin.itlink.edu. (
                              2         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
        IN NS ns.YOURDOMAINNAMEHERE.
        IN      A       192.168.1.10 replace this with the IP of your PC that has apache installed
ns      A       192.168.1.10 replace this with the IP of your PC that has apache installed
www     A       192.168.1.10 replace this with the IP of your PC that has

service bind9 restart


来源: stackexchange

问:
How to automatically handle DialogBoxShowing event in Python(Revit Dynamo)?
How do I subscribe to Revit events in Python (Dynamo)?

Specifically DialogBoxShowing so I can see if it is "Export with Temporary Hide/Isolate" warning and select "Leave the Temporary Isolate Mode on and Export"?

It is done in C# here:

http://thebuildingcoder.typepad.com/blog/2013/03/export-wall-parts-individually-to-dxf.html

See sub-heading: Handling and Dismissing a Warning Message

Thanks!

答:
(sorry not enough reputation to add this as comment to the response by PRMoureu...)

To expand on handling Dialogs a little...

Subscribing to DialogBoxShowing is hugely powerful, we have just rolled out a Dialog Suppressor to silence the ever-frustrating 'Would you like to join walls to the floor you just made' and 'Would you like to attach these walls to the roof'. It can also be used to see what errors users are commonly getting etc.

To investigate a Dialogs message text: event.Message

To reply 'Cancel' to the Dialog: event.OverrideResult(0)

To reply 'Yes' to the Dialog: event.OverrideResult(1)

To reply 'OK' to the Dialog: event.OverrideResult(6)

ContentLicense: CC BY-SA 3.0


问:
Using regex/search to find a string and isolate the column
Hi so what I am trying to achieve is to locate the column in my csv file (converted to a dataframe) that contains the word 'outbound' and isolate that column, and the two columns next to it. So far I have tried the following snippets of code to no avail.

```<code>    mask = np.column_stack([NB_2c17_newburden[col].str.contains(r"outbound", na=False) for col in NB_2c17_newburden])
</code>```

as well as using search

```<code>    for line in NB_2c17_newburden:
       if re.search('outbound', line):
         print (line)
</code>```

I was just using print line to see if it would work. Any help would be appreciated.

In R it has been achieved with the following code:

```<code>  i <- grep('outbound',NB_2c17_newburden)
  i <- i:(i+2)
</code>```

But I am not sure how to convert that to python

答:
```<code>df=pd.DataFrame({"col1":["one","two","three"],"col2":["four","five","six"],"col3":["seven","outbound","nine"],"col4":["ten","eleven","twelve"]})

for i in range(len(df.columns)):
    if pd.Series.any(df.iloc[:,i].str.contains(pat="outbound")):
        new_list=pd.DataFrame({df.columns[i-1]:df.iloc[:,i-1],df.columns[i]:df.iloc[:,i],df.columns[i+1]:df.iloc[:,i+1]})

print(new_list)

  col2      col3    col4
0  four     seven     ten
1  five  outbound  eleven
2   six      nine  twelve
</code>```

Body:
Hi so what I am trying to achieve is to locate the column in my csv file (converted to a dataframe) that contains the word 'outbound' and isolate that column, and the two columns next to it. So far I have tried the following snippets of code to no avail.

    mask = np.column_stack([NB_2c17_newburden[col].str.contains(r"outbound", na=False) for col in NB_2c17_newburden])

as well as using search

    for line in NB_2c17_newburden:
       if re.search('outbound', line):
         print (line)

I was just using print line to see if it would work. Any help would be appreciated.

In R it has been achieved with the following code:

  i <- grep('outbound',NB_2c17_newburden)
  i <- i:(i+2)

But I am not sure how to convert that to python


问:
Algorithm - How to delete duplicate elements in a Haskell list
I'm having a problem creating an function similar to the nub function.

I need this func to remove duplicated elements form a list.
An element is duplicated when 2 elements have the same email, and it should keep the newer one (is closer to the end of the list).

```<code>type Regist = [name,email,,...,date]
type ListRe = [Regist]

rmDup ListRe -> ListRe
rmDup [] = []
rmDup [a] = [a]
rmDup (h:t) | isDup h (head t) = rmDup t
            | otherwise = h : rmDup t

isDup :: Regist -> Regist -> Bool
isDup (a:b:c:xs) (d:e:f:ts) = b==e
</code>```

The problem is that the function doesn't delete duplicated elements unless they are together in the list.

答:
(Assuming you want to figure out an answer, not just call a library function that does this job for you.)

You get what you ask for.  What if h is not equal to head t but is instead equal to the 3rd element of t?  You need to write an algorithm that compares h with every element of t, not just the first element.

Body:
I'm having a problem creating an function similar to the nub function.

I need this func to remove duplicated elements form a list.
An element is duplicated when 2 elements have the same email, and it should keep the newer one (is closer to the end of the list).

type Regist = [name,email,,...,date]
type ListRe = [Regist]

rmDup ListRe -> ListRe
rmDup [] = []
rmDup [a] = [a]
rmDup (h:t) | isDup h (head t) = rmDup t
            | otherwise = h : rmDup t

isDup :: Regist -> Regist -> Bool
isDup (a:b:c:xs) (d:e:f:ts) = b==e

The problem is that the function doesn't delete duplicated elements unless they are together in the list.

ContentLicense: CC BY-SA 2.5


问:
Excel 2011 - How to change output of textJoin from value of cell, to the cell name, so I can put it in Sum() to add those values
I'm using the textJoin UDF listed below to combine values from various rows into a single cell; it displays each value. However, I want to know if I can manipulate the output of this UDF so that instead of simply displaying the values I can add the values and get the sum of the values. Or ideally, if I can just modify variables to instruct it to ADD the values. Does anyone know if this UDF (which I didn't create) can be instructed to output the Cell names (A2, B2, C2), and if so can I put that output within the Sum() function so that it will add A2+B2+C2?

```<code>Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
    Dim d As Long
    Dim c As Long
    Dim arr2()
    Dim t As Long, y As Long
    t = -1
    y = -1
    If TypeName(arr) = "Range" Then
        arr2 = arr.Value
    Else
        arr2 = arr
    End If
    On Error Resume Next
    t = UBound(arr2, 2)
    y = UBound(arr2, 1)
    On Error GoTo 0

    If t >= 0 And y >= 0 Then
        For c = LBound(arr2, 1) To UBound(arr2, 1)
            For d = LBound(arr2, 1) To UBound(arr2, 2)
                If arr2(c, d) <> "" Or Not skipblank Then
                    TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
                End If
            Next d
        Next c
    Else
        For c = LBound(arr2) To UBound(arr2)
            If arr2(c) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c) & delim
            End If
        Next c
    End If
        TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
    End Function
</code>```

It seems like there should be a way to convert the output from the value of the cell to the cell name (i.e. C2, C3, C4, etc), then put the whole thing within the Sum() function so that it simply adds the cells together. Alternatively, is there a function that ads the values placed within the function instead of using cell names?

I want to add the highlighted cell (G2). I have the value of 10 and 20. It seems like I should be able to use =Sum(textJoin(...))  if I can get textJoin to output the cell names (i.e. C2, C3).

答:
if you want it to just total the values then you can add something like this to the end of the UDF

```<code>    Dim total As Long
    Dim txtPart
    For Each txtPart In Split(TEXTJOIN, delim)
        total = total + CLng(txtPart)
    Next txtPart
    TEXTJOIN = total
</code>```

example

```<code>Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
Dim d As Long
Dim c As Long
Dim arr2()
Dim t As Long, y As Long
t = -1
y = -1
If TypeName(arr) = "Range" Then
    arr2 = arr.Value
Else
    arr2 = arr
End If
On Error Resume Next
t = UBound(arr2, 2)
y = UBound(arr2, 1)
On Error GoTo 0

If t >= 0 And y >= 0 Then
    For c = LBound(arr2, 1) To UBound(arr2, 1)
        For d = LBound(arr2, 1) To UBound(arr2, 2)
            If arr2(c, d) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
            End If
        Next d
    Next c
Else
    For c = LBound(arr2) To UBound(arr2)
        If arr2(c) <> "" Or Not skipblank Then
            TEXTJOIN = TEXTJOIN & arr2(c) & delim
        End If
    Next c
End If
    TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
    'add the below loop to add each number together
    Dim total As Long
    Dim txtPart
    For Each txtPart In Split(TEXTJOIN, delim)
        total = total + CLng(txtPart)

    Next txtPart
    TEXTJOIN = total
End Function
</code>```

Body:
I'm using the textJoin UDF listed below to combine values from various rows into a single cell; it displays each value. However, I want to know if I can manipulate the output of this UDF so that instead of simply displaying the values I can add the values and get the sum of the values. Or ideally, if I can just modify variables to instruct it to ADD the values. Does anyone know if this UDF (which I didn't create) can be instructed to output the Cell names (A2, B2, C2), and if so can I put that output within the Sum() function so that it will add A2+B2+C2?

Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
    Dim d As Long
    Dim c As Long
    Dim arr2()
    Dim t As Long, y As Long
    t = -1
    y = -1
    If TypeName(arr) = "Range" Then
        arr2 = arr.Value
    Else
        arr2 = arr
    End If
    On Error Resume Next
    t = UBound(arr2, 2)
    y = UBound(arr2, 1)
    On Error GoTo 0

    If t >= 0 And y >= 0 Then
        For c = LBound(arr2, 1) To UBound(arr2, 1)
            For d = LBound(arr2, 1) To UBound(arr2, 2)
                If arr2(c, d) <> "" Or Not skipblank Then
                    TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
                End If
            Next d
        Next c
    Else
        For c = LBound(arr2) To UBound(arr2)
            If arr2(c) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c) & delim
            End If
        Next c
    End If
        TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
    End Function

It seems like there should be a way to convert the output from the value of the cell to the cell name (i.e. C2, C3, C4, etc), then put the whole thing within the Sum() function so that it simply adds the cells together. Alternatively, is there a function that ads the values placed within the function instead of using cell names?

I want to add the highlighted cell (G2). I have the value of 10 and 20. It seems like I should be able to use =Sum(textJoin(...))  if I can get textJoin to output the cell names (i.e. C2, C3).

Body:
if you want it to just total the values then you can add something like this to the end of the UDF

    Dim total As Long
    Dim txtPart
    For Each txtPart In Split(TEXTJOIN, delim)
        total = total + CLng(txtPart)
    Next txtPart
    TEXTJOIN = total

example

Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
Dim d As Long
Dim c As Long
Dim arr2()
Dim t As Long, y As Long
t = -1
y = -1
If TypeName(arr) = "Range" Then
    arr2 = arr.Value
Else
    arr2 = arr
End If
On Error Resume Next
t = UBound(arr2, 2)
y = UBound(arr2, 1)
On Error GoTo 0

If t >= 0 And y >= 0 Then
    For c = LBound(arr2, 1) To UBound(arr2, 1)
        For d = LBound(arr2, 1) To UBound(arr2, 2)
            If arr2(c, d) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
            End If
        Next d
    Next c
Else
    For c = LBound(arr2) To UBound(arr2)
        If arr2(c) <> "" Or Not skipblank Then
            TEXTJOIN = TEXTJOIN & arr2(c) & delim
        End If
    Next c
End If
    TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
    'add the below loop to add each number together
    Dim total As Long
    Dim txtPart
    For Each txtPart In Split(TEXTJOIN, delim)
        total = total + CLng(txtPart)

    Next txtPart
    TEXTJOIN = total
End Function


问:
Load json into javascript
So I have a json html link that like below

```<code>www.pretendJsonLink.com/getData
</code>```

and the data i receive is below:

```<code>{"Items":[{"date":1498850140373,"displayId":"003","sentId":"121213",
"customer":"ME"}, {"date":1452870140571,"displayId":"007","sentId":"152713",
"customer":"YOU"}],"Count":2,"ScannedCount":2}
</code>```

I need to load this into a js file  so i can then call them as needed in a html file in an id="" tag

Like Items.date and Items.customer or something like it

Any help would be great and I understand that this should be a simple task, but i can also forward my search history as well :) i have been looking for solutions that work, but just cant seem to find anything that fits my needs

答: Use JSON.parse() function. Here is the link to documentation

Title: Load json into javascript

Body:
So I have a json html link that like below

www.pretendJsonLink.com/getData

and the data i receive is below:

{"Items":[{"date":1498850140373,"displayId":"003","sentId":"121213",
"customer":"ME"}, {"date":1452870140571,"displayId":"007","sentId":"152713",
"customer":"YOU"}],"Count":2,"ScannedCount":2}

I need to load this into a js file  so i can then call them as needed in a html file in an id="" tag

Like Items.date and Items.customer or something like it

Any help would be great and I understand that this should be a simple task, but i can also forward my search history as well :) i have been looking for solutions that work, but just cant seem to find anything that fits my needs


问:
Can git store or control directory user, group or permissions
I have developed a few git repositories for a web application.  As part of the deployment process, a few of the folders need to be writable by Apache for file uploads.  Does git have any control over this for either the user or group, or the respective permissions?

答:
git can only set this for the entire repository, not for a subdirectory. Run in the root of your repo:</p>

```<code>sudo chgrp -R apache .
sudo chmod -R ug+rwX *
git config core.sharedRepository group
</code>```

Body:
git can only set this for the entire repository, not for a subdirectory. Run in the root of your repo:

sudo chgrp -R apache .
sudo chmod -R ug+rwX *
git config core.sharedRepository group


问:
Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Auth\UserInterface, null given open:
I have a Facebook login I am performing with OAuth2, and then I am using Laravel 4's built in Authentication system to log the user back in on revisit.  For the majority of users, I see no issues with what I have, but for one user, he is seeing the following error appear on login:

```<code>ErrorException
Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Auth\UserInterface, null given
open: */nfs/c09/h04/mnt/139243/domains/crowdsets.com/vendor/laravel/framework/src/Illuminate/Auth/Guard.php
*        /**
        * Log a user into the application.
        *
        * @param  \Illuminate\Auth\UserInterface  $user
        * @param  bool  $remember
        * @return void
        */
       public function login(UserInterface $user, $remember = false)
       {
               $id = $user->getAuthIdentifier();
</code>```

Here is the relevant login/authentication code in the controller:

```<code>$check = Fan::where('fbid', '=', $user['uid'])->first();

                if(is_null($check)) {

                  $fan = new Fan;

                  $fan->fbid = $user['uid'];
                  $fan->email = $user['email'];
                  $fan->first_name = $user['first_name'];
                  $fan->last_name = $user['last_name'];
                  $fan->gender = $user['gender'];
                  $fan->birthday = $user['birthday'];
                  $fan->age = $age;
                  $fan->city = $city;
                  $fan->state = $state_abbrev;
                  $fan->image = $user['image'];
                  $fan->friend_ids_url = $user['friends'];
                  $fan->friend_ids_unpacked = $friend_ids;

                  $fan->save();

                  $new = Fan::where('fbid', '=', $user['uid'])->first();

                  Auth::login($new);
                  return Redirect::to('fans/home');

                }

               else {

                  Auth::login($check);

                  $fan = Fan::find(Auth::user()->id);
                  $fan->image = $user['image'];
                  $fan->save();

                  return Redirect::to('fans/home');
                  var_dump($user);

               }
</code>```

This is my code in the model for the table I am using to keep user information, called "Fans":

```<code><?php

use Illuminate\Auth\UserInterface;

class Fan extends Eloquent implements UserInterface {
    protected $guarded = array();

    public static $rules = array();

    public function getAuthIdentifier()
{
return $this->getKey();
}

public function getAuthPassword()
{
return $this->password;
}
</code>```

This is very perplexing because this login works for all of the other profiles I have tried.  It is only with this friend's profile that it is throwing this error.  I will also add, that on login (or retries) it will create multiple entries for this user in the database/table.  This authentication system is supposed to be set up to prevent exactly this.  Is there anything I'm missing?

答:
I had the same issue and I managed to resolve it by checking few things:

Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Auth\UserInterface, null given open:

As you can see, null given means that the $user you want to Auth::login($user) is null. Check if the variable it set.

Don't put any var_dump() between the Auth::login and the final redirect(). It may stop the Authentification.

Hope it helps

Body:
I have a Facebook login I am performing with OAuth2, and then I am using Laravel 4's built in Authentication system to log the user back in on revisit.  For the majority of users, I see no issues with what I have, but for one user, he is seeing the following error appear on login:

ErrorException
Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Auth\UserInterface, null given
open: */nfs/c09/h04/mnt/139243/domains/crowdsets.com/vendor/laravel/framework/src/Illuminate/Auth/Guard.php
*        /**
        * Log a user into the application.
        *
        * @param  \Illuminate\Auth\UserInterface  $user
        * @param  bool  $remember
        * @return void
        */
       public function login(UserInterface $user, $remember = false)
       {
               $id = $user->getAuthIdentifier();

Here is the relevant login/authentication code in the controller:

$check = Fan::where('fbid', '=', $user['uid'])->first();

                if(is_null($check)) {

                  $fan = new Fan;

                  $fan->fbid = $user['uid'];
                  $fan->email = $user['email'];
                  $fan->first_name = $user['first_name'];
                  $fan->last_name = $user['last_name'];
                  $fan->gender = $user['gender'];
                  $fan->birthday = $user['birthday'];
                  $fan->age = $age;
                  $fan->city = $city;
                  $fan->state = $state_abbrev;
                  $fan->image = $user['image'];
                  $fan->friend_ids_url = $user['friends'];
                  $fan->friend_ids_unpacked = $friend_ids;

                  $fan->save();

                  $new = Fan::where('fbid', '=', $user['uid'])->first();

                  Auth::login($new);
                  return Redirect::to('fans/home');

                }

               else {

                  Auth::login($check);

                  $fan = Fan::find(Auth::user()->id);
                  $fan->image = $user['image'];
                  $fan->save();

                  return Redirect::to('fans/home');
                  var_dump($user);

               }

This is my code in the model for the table I am using to keep user information, called "Fans":

<?php

use Illuminate\Auth\UserInterface;

class Fan extends Eloquent implements UserInterface {
    protected $guarded = array();

    public static $rules = array();

    public function getAuthIdentifier()
{
return $this->getKey();
}

public function getAuthPassword()
{
return $this->password;
}

This is very perplexing because this login works for all of the other profiles I have tried.  It is only with this friend's profile that it is throwing this error.  I will also add, that on login (or retries) it will create multiple entries for this user in the database/table.  This authentication system is supposed to be set up to prevent exactly this.  Is there anything I'm missing?


问:
Select Max And Inner Join
I have SQL Server 2012 database, I need to query database and get results relevant to MAX(Rule_ID) AND MAX(CI_ID)

But i cant get results relevant to MAX(CI_ID) all CI_ID versions are in results.

```<code>USE CM_T01
SELECT Max_id, MAX(CIVersion), Netbios_Name0, RuleName, RuleDescription, prereifiedvalue, complianceState
FROM v_CI_CurrentComplianceStatus
INNER JOIN
(
SELECT CI_ID,Rule_ID, Rulename,  RuleDescription,criteria, MAX(Rule_ID) OVER(PARTITION BY Rulename) AS Max_id
from v_cirules
where rulename like '%Account lockout duration%' AND RuleDescription like '%applicable%'
group by Rule_ID,RuleName, RuleDescription,CI_ID,Criteria) as v_CIRules
ON v_CIRules.CI_ID = v_CI_CurrentComplianceStatus.CI_ID
INNER JOIN v_R_System
ON v_R_System.ResourceID = v_CI_CurrentComplianceStatus.ItemKey
LEFT JOIN v_CICurrentRuleDetail
ON v_CICurrentRuleDetail.CurrentComplianceStatusID = v_CI_CurrentComplianceStatus.CI_CurrentComplianceStatusID
where netbios_name0='TRISTSCCM-PS'
GROUP BY Netbios_Name0, RuleName, RuleDescription, prereifiedvalue, complianceState,v_cirules.CI_ID,v_CIRules.Max_id,Criteria
</code>```

RESULTS

```<code>Max_id  (No column name)    Netbios_Name0   RuleName    RuleDescription prereifiedvalue complianceState
16780130    4   TRISTSCCM-PS    OS Hardening: Account Lockout Policy - Account lockout duration Applicable /Account lockout duration Must equal to 10   NULL    1
16780130    8   TRISTSCCM-PS    OS Hardening: Account Lockout Policy - Account lockout duration Applicable /Account lockout duration Must equal to 10   NULL    1
16780130    12  TRISTSCCM-PS    OS Hardening: Account Lockout Policy - Account lockout duration Applicable /Account lockout duration Must equal to 10   NULL    1
</code>```

答:
```<code>USE CM_T01
SELECT Max_id, CIVersion, Netbios_Name0, RuleName, RuleDescription, Criteria, prereifiedvalue, complianceState
FROM v_CI_CurrentComplianceStatus
INNER JOIN
(
SELECT CI_ID,Rule_ID, Rulename,  RuleDescription, MAX(Rule_ID) OVER(PARTITION BY Rulename) AS Max_id
from v_cirules
where rulename like '%Account lockout duration%'
group by Rule_ID,RuleName, RuleDescription) as v_CIRules
ON v_CIRules.CI_ID = v_CI_CurrentComplianceStatus.CI_ID
INNER JOIN v_R_System
ON v_R_System.ResourceID = v_CI_CurrentComplianceStatus.ItemKey
LEFT JOIN v_CICurrentRuleDetail
ON v_CICurrentRuleDetail.CurrentComplianceStatusID = v_CI_CurrentComplianceStatus.CI_CurrentComplianceStatusID
GROUP BY CIVersion, Netbios_Name0, RuleName, RuleDescription, Criteria, prereifiedvalue, complianceState
</code>```

Title: Select Max And Inner Join

Body:
I have SQL Server 2012 database, I need to query database and get results relevant to MAX(Rule_ID) AND MAX(CI_ID)

But i cant get results relevant to MAX(CI_ID) all CI_ID versions are in results.

USE CM_T01
SELECT Max_id, MAX(CIVersion), Netbios_Name0, RuleName, RuleDescription, prereifiedvalue, complianceState
FROM v_CI_CurrentComplianceStatus
INNER JOIN
(
SELECT CI_ID,Rule_ID, Rulename,  RuleDescription,criteria, MAX(Rule_ID) OVER(PARTITION BY Rulename) AS Max_id
from v_cirules
where rulename like '%Account lockout duration%' AND RuleDescription like '%applicable%'
group by Rule_ID,RuleName, RuleDescription,CI_ID,Criteria) as v_CIRules
ON v_CIRules.CI_ID = v_CI_CurrentComplianceStatus.CI_ID
INNER JOIN v_R_System
ON v_R_System.ResourceID = v_CI_CurrentComplianceStatus.ItemKey
LEFT JOIN v_CICurrentRuleDetail
ON v_CICurrentRuleDetail.CurrentComplianceStatusID = v_CI_CurrentComplianceStatus.CI_CurrentComplianceStatusID
where netbios_name0='TRISTSCCM-PS'
GROUP BY Netbios_Name0, RuleName, RuleDescription, prereifiedvalue, complianceState,v_cirules.CI_ID,v_CIRules.Max_id,Criteria

RESULTS

Max_id  (No column name)    Netbios_Name0   RuleName    RuleDescription prereifiedvalue complianceState
16780130    4   TRISTSCCM-PS    OS Hardening: Account Lockout Policy - Account lockout duration Applicable /Account lockout duration Must equal to 10   NULL    1
16780130    8   TRISTSCCM-PS    OS Hardening: Account Lockout Policy - Account lockout duration Applicable /Account lockout duration Must equal to 10   NULL    1
16780130    12  TRISTSCCM-PS    OS Hardening: Account Lockout Policy - Account lockout duration Applicable /Account lockout duration Must equal to 10   NULL    1


问:
SSRS - Prevent pagebreak in the middle of a row group
I have an SSRS report that gets exported to PDF and then printed on to paper. The problem I am having is that I am getting page breaks in the middle of a group.

I have MetricGroup - MetricSubGroup and Details. Those are my Row Groups.

I have several different MetricGroups in the report.

I need to make it so that my report will not break in the middle of a MetricGroup.

So right now I get lets say 2 metric groups and half of the 3rd metric group on page 1. Page 2 contains the second half of the 3rd metric group and so on.

I need SSRS to push a metric group to the next page if the metric group does not fit entirely on the current page.

Is this possible to accomplish?

答:
To elaborate a little more on the previous answer, specifying KeepTogether = true for any given tablix member will try to keep all elements of that tablix member together.

So if you specify KeepTogether on your MetricGroup tablix member, SSRS will try to keep all elements of that tablix group together, and when it fails because the report spans multiple pages, it will page break where it likes, resulting in groups breaking up over pages.

If, however, you specify KeepTogether on your MetricSubGroup tablix member, SSRS will try to keep all of the subgroups within a MetricGroup together, which will result in the parent MetricGroup trying not to break on a page if that were possible.

I'm spelling this out explicitly because there's a common degenerate case here - a report without any groupings but with a complex details tablix that generates with multiple rows per data record. Trying to specify KeepTogether on the details tablix will try to keep all of the details together, introducing unexpected page breaks.

In this case you'll need to generate a details group as the immediate parent of the details tablix and group by whatever the report identity is. Then you can specify KeepTogether on the details tablix and it will keep together only the members for one single data record.


问:
TYPO3 7.6 - cooluri redirects everything to root page
Like the headline says, I installed cooluri and each link redirects to the root page. But the URL is rewritten correctly!

e.g. '/index.php?id=4' is rewritten to '/Products', but the Page shown is the root page which should be just '/'

my /typo3/.htaccess:

```<code><IfModule mod_rewrite.c>

# Enable URL rewriting
RewriteEngine On

# Store the current location in an environment variable CWD to use
# mod_rewrite in .htaccess files without knowing the RewriteBase
RewriteCond $0#%{REQUEST_URI} ([^#]*)#(.*)\1$
RewriteRule ^.*$ - [E=CWD:%2]

# Rules to set ApplicationContext based on hostname
#RewriteCond %{HTTP_HOST} ^dev\.example\.com$
#RewriteRule .? - [E=TYPO3_CONTEXT:Development]
#RewriteCond %{HTTP_HOST} ^staging\.example\.com$
#RewriteRule .? - [E=TYPO3_CONTEXT:Production/Staging]
#RewriteCond %{HTTP_HOST} ^www\.example\.com$
#RewriteRule .? - [E=TYPO3_CONTEXT:Production]

# Rule for versioned static files, configured through:
# - $GLOBALS['TYPO3_CONF_VARS']['BE']['versionNumberInFilename']
# - $GLOBALS['TYPO3_CONF_VARS']['FE']['versionNumberInFilename']
# IMPORTANT: This rule has to be the very first RewriteCond in order to work!
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)\.(\d+)\.(php|js|css|png|jpg|gif|gzip)$ %{ENV:CWD}$1.$3 [L]

# Access block for folders
RewriteRule _(?:recycler|temp)_/ - [F]
RewriteRule fileadmin/templates/.*\.(?:txt|ts)$ - [F]
RewriteRule ^(?:vendor|typo3_src|typo3temp/logs) - [F]
RewriteRule (?:typo3conf/ext|typo3/sysext|typo3/ext)/[^/]+/(?:Configuration|Resources/Private|Tests?|Documentation|docs?)/ - [F]

# Block access to all hidden files and directories with the exception of
# the visible content from within the `/.well-known/` hidden directory (RFC 5785).
RewriteCond %{REQUEST_URI} "!(^|/)\.well-known/([^./]+./?)+$" [NC]
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule (?:^|/)\. - [F]

# Stop rewrite processing, if we are in the typo3/ directory or any other known directory
# NOTE: Add your additional local storages here
RewriteRule ^(?:typo3/|fileadmin/|typo3conf/|typo3temp/|uploads/|favicon\.ico) - [L]

# If the file/symlink/directory does not exist => Redirect to index.php.
# For httpd.conf, you need to prefix each '%{REQUEST_FILENAME}' with '%{DOCUMENT_ROOT}'.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.*$ %{ENV:CWD}index.php [QSA,L]
</code>```

my root TS:

```<code>config {
  simulateStaticDocuments = 1
  simulateStaticDocuments_noTypeIfNoTitle = 1
  tx_cooluri_enable = 1
  redirectOldLinksToNew = 1
  typolinkCheckRootline= 0

  baseURL = {$baseURL}
  doctype = html5
  language = de
}
</code>```

答:
I personally would prefer to use realurl for url-rewriting.

Realurl gives you a pretty well working default configuration and there is a good documentation & support for this extension.

Speaking URLs for TYPO3 - typo3.org

Body:
Like the headline says, I installed cooluri and each link redirects to the root page. But the URL is rewritten correctly!

e.g. '/index.php?id=4' is rewritten to '/Products', but the Page shown is the root page which should be just '/'

my /typo3/.htaccess:

<IfModule mod_rewrite.c>

# Enable URL rewriting
RewriteEngine On

# Store the current location in an environment variable CWD to use
# mod_rewrite in .htaccess files without knowing the RewriteBase
RewriteCond $0#%{REQUEST_URI} ([^#]*)#(.*)\1$
RewriteRule ^.*$ - [E=CWD:%2]

# Rules to set ApplicationContext based on hostname
#RewriteCond %{HTTP_HOST} ^dev\.example\.com$
#RewriteRule .? - [E=TYPO3_CONTEXT:Development]
#RewriteCond %{HTTP_HOST} ^staging\.example\.com$
#RewriteRule .? - [E=TYPO3_CONTEXT:Production/Staging]
#RewriteCond %{HTTP_HOST} ^www\.example\.com$
#RewriteRule .? - [E=TYPO3_CONTEXT:Production]

# Rule for versioned static files, configured through:
# - $GLOBALS['TYPO3_CONF_VARS']['BE']['versionNumberInFilename']
# - $GLOBALS['TYPO3_CONF_VARS']['FE']['versionNumberInFilename']
# IMPORTANT: This rule has to be the very first RewriteCond in order to work!
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)\.(\d+)\.(php|js|css|png|jpg|gif|gzip)$ %{ENV:CWD}$1.$3 [L]

# Access block for folders
RewriteRule _(?:recycler|temp)_/ - [F]
RewriteRule fileadmin/templates/.*\.(?:txt|ts)$ - [F]
RewriteRule ^(?:vendor|typo3_src|typo3temp/logs) - [F]
RewriteRule (?:typo3conf/ext|typo3/sysext|typo3/ext)/[^/]+/(?:Configuration|Resources/Private|Tests?|Documentation|docs?)/ - [F]

# Block access to all hidden files and directories with the exception of
# the visible content from within the `/.well-known/` hidden directory (RFC 5785).
RewriteCond %{REQUEST_URI} "!(^|/)\.well-known/([^./]+./?)+$" [NC]
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule (?:^|/)\. - [F]

# Stop rewrite processing, if we are in the typo3/ directory or any other known directory
# NOTE: Add your additional local storages here
RewriteRule ^(?:typo3/|fileadmin/|typo3conf/|typo3temp/|uploads/|favicon\.ico) - [L]

# If the file/symlink/directory does not exist => Redirect to index.php.
# For httpd.conf, you need to prefix each '%{REQUEST_FILENAME}' with '%{DOCUMENT_ROOT}'.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.*$ %{ENV:CWD}index.php [QSA,L]

my root TS:

config {
  simulateStaticDocuments = 1
  simulateStaticDocuments_noTypeIfNoTitle = 1
  tx_cooluri_enable = 1
  redirectOldLinksToNew = 1
  typolinkCheckRootline= 0

  baseURL = {$baseURL}
  doctype = html5
  language = de
}


问:
Mikrotik - Using 2 WAN connections with 2 Static IP addresses
I have 2 WAN lines that connect to the Internet: one connects on ether1 interface, the other connect on ether2 interface, using a Mikrotik router.

ether3 connects to LAN.

Each line has Valid IP (static IP) and connect with PPPoE connection:

WAN 1 has 217.219.xx.xx, connecting with pppoe1-WAN

WAN 2 has 89.165.xx.xx connecting with pppoe1-WAN2

In Routing, pppoe1-WAN1 has Distance 1 and pppoe1-WAN2 has Distance 2

When WAN1 is Disabled, I can use 89.165.xx.xx to connect to router from out of office but when WAN1 is enabled I can not connect with 89.165.xx.xx.

Can anyone help me to fix this problem?

答:
this is very good,
for the gateways with ip address like 192.168.xxx.xxx it is good to replace
 "gateway=pppoe-WAN1" with "gateway=192.168.xxx.xxx" on this rule:

```<code>add distance=1 gateway=pppoe-WAN1 routing-mark=RWAN1
</code>```

Body:
this is very good,
for the gateways with ip address like 192.168.xxx.xxx it is good to replace
 "gateway=pppoe-WAN1" with "gateway=192.168.xxx.xxx" on this rule:

add distance=1 gateway=pppoe-WAN1 routing-mark=RWAN1


问:
Interactive plots on local .html via .rmd or Shiny
I'm trying to build a .html file via RStudio in to have following function(simplified).

plot1:a simple time series plot of $y_t$, where user can manually pull/drag each dot to change it's values a each time point.

plot2:a time series dependent on $y_t$, such as $f(y_t)=2*y_t+1$, once the value in plot1 changed, the plot2 will also change accordingly.

I want the .html self contained, not cloud based. I'm thinking of plotly, shininy/knitr, but I'm not sure if I'm in the direction or how to connect the dots. Hope anyone can point me to the right direction.

答:
A self-contained/client-side html report sounds well-suited for flexdashboard.  It's based on R Markdown, and therefore can accommodate Shiny elements.

I don't know if you can modify values with a mouse, but you can certainly modify values with sliders and other inputs, as well as have a second plot react to a first plot.

You may see some more possibilities in the gallery.


问:
sklearn.cross_validation.cross_val_score multiple cpu?
I am trying to get a score for a model through cross validation with sklearn.cross_validation.cross_val_score. According to its documentation, the parameter n_jobs sets the number of cpus that you can utilize. However, when I set it to -1 (or other values not equal to 1), the program complains that:

AttributeError: '_MainProcess' object has no attribute '_daemonic'

Attached below is a minimal example, and the corresponding error message.

```<code>import sklearn.datasets
import sklearn.cross_validation
import sklearn.linear_model
d = sklearn.datasets.load_iris()
X = d.data
y = d.target
sklearn.cross_validation.cross_val_score(sklearn.linear_model.LogisticRegression(), X, y, n_jobs=-1)
</code>```

```<code>AttributeError
Traceback (most recent call last)
<ipython-input-57-3b5f62e97b0d> in <module>()
    ----> 1 sklearn.cross_validation.cross_val_score(gb_clf, train, train_label, n_jobs=2)

/usr/lib/python3.4/site-packages/sklearn/cross_validation.py in cross_val_score(estimator, X, y,     scoring, cv, n_jobs, verbose, fit_params, score_func, pre_dispatch)
   1150         delayed(_cross_val_score)(clone(estimator), X, y, scorer, train, test,
   1151                                   verbose, fit_params)
-> 1152         for train, test in cv)
   1153     return np.array(scores)
   1154

/usr/lib/python3.4/site-packages/sklearn/externals/joblib/parallel.py in __call__(self, iterable)
    468             self._pool = None
    469         else:
--> 470             if multiprocessing.current_process()._daemonic:
    471                 # Daemonic processes cannot have children
    472                 n_jobs = 1

AttributeError: '_MainProcess' object has no attribute '_daemonic'
</code>```

Additional information: I am running this script in IPython notebook mode. It also appears under console mode, or under normal python interpreter (per @larsmans comment).

答:
You will have to protect your code:

```<code>if __name__ == "__main__":
    [Your code]
</code>```

There seems to be issues with joblib.Parallel when it comes to multiple processing (n_jobs > 1). More information about that in the joblib documentation, and there's also a Github thread discussing that problem.

Body:
I am trying to get a score for a model through cross validation with sklearn.cross_validation.cross_val_score. According to its documentation, the parameter n_jobs sets the number of cpus that you can utilize. However, when I set it to -1 (or other values not equal to 1), the program complains that:

AttributeError: '_MainProcess' object has no attribute '_daemonic'

Attached below is a minimal example, and the corresponding error message.

import sklearn.datasets
import sklearn.cross_validation
import sklearn.linear_model
d = sklearn.datasets.load_iris()
X = d.data
y = d.target
sklearn.cross_validation.cross_val_score(sklearn.linear_model.LogisticRegression(), X, y, n_jobs=-1)

AttributeError
Traceback (most recent call last)
<ipython-input-57-3b5f62e97b0d> in <module>()
    ----> 1 sklearn.cross_validation.cross_val_score(gb_clf, train, train_label, n_jobs=2)

/usr/lib/python3.4/site-packages/sklearn/cross_validation.py in cross_val_score(estimator, X, y,     scoring, cv, n_jobs, verbose, fit_params, score_func, pre_dispatch)
   1150         delayed(_cross_val_score)(clone(estimator), X, y, scorer, train, test,
   1151                                   verbose, fit_params)
-> 1152         for train, test in cv)
   1153     return np.array(scores)
   1154

/usr/lib/python3.4/site-packages/sklearn/externals/joblib/parallel.py in __call__(self, iterable)
    468             self._pool = None
    469         else:
--> 470             if multiprocessing.current_process()._daemonic:
    471                 # Daemonic processes cannot have children
    472                 n_jobs = 1

AttributeError: '_MainProcess' object has no attribute '_daemonic'

Additional information: I am running this script in IPython notebook mode. It also appears under console mode, or under normal python interpreter (per @larsmans comment).

Body:
You will have to protect your code:

if __name__ == "__main__":
    [Your code]

There seems to be issues with joblib.Parallel when it comes to multiple processing (n_jobs > 1). More information about that in the joblib documentation, and there's also a Github thread discussing that problem.


问:
Ext.js Editable TreeNodes
Is is possible to make TreeNodes (i.e. folders) editable by the user? I see that there's an option called editable in TreeNode class but I couldn't get it working or find any examples on its usage.

My other quest is to place an input box in nodes so, user can enter numbers for each item. How can I do it?

答:
Adding new Ext.tree.TreeEditor(yourTree); will be enough to make the tree editable.

But you can define much more by using the other 2 contructors parameters:

```<code>var te = new Ext.tree.TreeEditor(tree, new Ext.form.NumberField({
    allowBlank: false,
    blankText: 'A number is required'
}), {
    editDelay: 100,
    revertInvalid: false
});

te.on("complete", function(node) {
    alert(node.startValue + ' -> ' + node.editNode.text);
});
</code>```

There I used a NumberField so you can enter only numbers in there.

And you can restrict edition by using the editable property of every TreeNode (yes, the one you mentioned), or by using the beforestartedit event of the TreeEditor:

```<code>te.on('beforestartedit', function(ed, boundEl, value) {
    if (ed.editNode.leaf)
      return false;
});
</code>```

At jsbin.com/ExtJS-TreeEditor/2 you have a live example I made based on Sencha's Checkbox TreePanel example, the diference is that you can edit the folder nodes on my example.

Just select a folder and then click again on that folder, the editor (a NumberField) should appear above the folder's name.

Title: Ext.js Editable TreeNodes

Body:
Adding new Ext.tree.TreeEditor(yourTree); will be enough to make the tree editable.

But you can define much more by using the other 2 contructors parameters:

var te = new Ext.tree.TreeEditor(tree, new Ext.form.NumberField({
    allowBlank: false,
    blankText: 'A number is required'
}), {
    editDelay: 100,
    revertInvalid: false
});

te.on("complete", function(node) {
    alert(node.startValue + ' -> ' + node.editNode.text);
});

There I used a NumberField so you can enter only numbers in there.

And you can restrict edition by using the editable property of every TreeNode (yes, the one you mentioned), or by using the beforestartedit event of the TreeEditor:

te.on('beforestartedit', function(ed, boundEl, value) {
    if (ed.editNode.leaf)
      return false;
});

At jsbin.com/ExtJS-TreeEditor/2 you have a live example I made based on Sencha's Checkbox TreePanel example, the diference is that you can edit the folder nodes on my example.

Just select a folder and then click again on that folder, the editor (a NumberField) should appear above the folder's name.


问:
Javascript AJAX SyntaxError: Unexpected token E in JSON at position 0
I am using AJAX to make HTTP requests to my node.js server. However, my AJAX requests keep returning the error SyntaxError: Unexpected token E in JSON at position 0 (there's no error returned on the server side).

While browsing other SO questions, I found the solution is to use JSON.stringify() on my data object.. but I still get the same error:

```<code>var postData = {
  company_id: 'cid',
  credentials:
   { first_name: 'van',
     last_name: 'jones',
     phone_number: '1035191043',
     email: 'van.jones@gmail.com'},
  company:
   { company_name: 'cnn',
     company_email: 'info@cnn.com',
     company_phone_number: '2800231374',
     company_notes: '' },
  shipping_address:
   { addr_1: 'addr1',
     addr_2: 'addr2',
     city: 'city',
     state: 'state',
     zip: 'zip' },
  billing_address:
   { addr_1: 'addr1',
     addr_2: 'addr2',
     city: 'city',
     state: 'state',
     zip: 'zip' },
  some_bool: true,
  another_bool: true,
  hostname: 'localhost'
}

$.ajax({
  type: "POST",
  url: 'some_url',
  data: JSON.stringify(postData),
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data, status) {
    console.log('success')
  },
  error: function(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
    // returns SyntaxError: Unexpected token E in JSON at position 0
  }
});
</code>```

Does anyone know what I might be missing?

Thank you.

答:
From my experience such information always ment some trouble server-side (I know you say there isn't, but still..), e.g. SQL query error. Try incorporating similar code to your error handling function. It may help you solve your problem.</p>

```<code>error: function(xhr) {
  try {
    var response = JSON.parse(xhr.responseText);
    console.log('Success');
    console.log(response);
  }
  catch (e) {
    var response = xhr.responseText;
    console.log(
      'There was an error: \n -> '
      + e + '\n'
      + 'Complete server response: \n -->'
      + response
    );
  }
}
</code>```

Body:
I am using AJAX to make HTTP requests to my node.js server. However, my AJAX requests keep returning the error SyntaxError: Unexpected token E in JSON at position 0 (there's no error returned on the server side).

While browsing other SO questions, I found the solution is to use JSON.stringify() on my data object.. but I still get the same error:

var postData = {
  company_id: 'cid',
  credentials:
   { first_name: 'van',
     last_name: 'jones',
     phone_number: '1035191043',
     email: 'van.jones@gmail.com'},
  company:
   { company_name: 'cnn',
     company_email: 'info@cnn.com',
     company_phone_number: '2800231374',
     company_notes: '' },
  shipping_address:
   { addr_1: 'addr1',
     addr_2: 'addr2',
     city: 'city',
     state: 'state',
     zip: 'zip' },
  billing_address:
   { addr_1: 'addr1',
     addr_2: 'addr2',
     city: 'city',
     state: 'state',
     zip: 'zip' },
  some_bool: true,
  another_bool: true,
  hostname: 'localhost'
}

$.ajax({
  type: "POST",
  url: 'some_url',
  data: JSON.stringify(postData),
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data, status) {
    console.log('success')
  },
  error: function(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
    // returns SyntaxError: Unexpected token E in JSON at position 0
  }
});

Does anyone know what I might be missing?

Thank you.

Body:
From my experience such information always ment some trouble server-side (I know you say there isn't, but still..), e.g. SQL query error. Try incorporating similar code to your error handling function. It may help you solve your problem.

error: function(xhr) {
  try {
    var response = JSON.parse(xhr.responseText);
    console.log('Success');
    console.log(response);
  }
  catch (e) {
    var response = xhr.responseText;
    console.log(
      'There was an error: \n -> '
      + e + '\n'
      + 'Complete server response: \n -->'
      + response
    );
  }
}


问:
PMCreateSession not creating print session
Trying to get printable rect for OS X app. Seems to involve creating a session, then a page format, validating the format, etc. Code compiles, but getting a status of -50 from PMCreateSession. Am I declaring printSession improperly? Normally don't have to deal so much with UnsafeMutablePointers.

Thanks!

```<code>    let printSession: UnsafeMutablePointer<PMPrintSession> = nil
    let pmPageFormat: UnsafeMutablePointer<PMPageFormat> = nil
    var status = PMCreateSession(printSession)
    status = PMCreatePageFormat(pmPageFormat)
    status = PMSessionDefaultPageFormat(printSession.memory, pmPageFormat.memory)
    let changed: UnsafeMutablePointer<DarwinBoolean> = nil
    status = PMSessionValidatePageFormat(printSession.memory, pmPageFormat.memory, changed)
    changed.destroy()
    var pRect = PMRect()
    status = PMGetAdjustedPageRect(pmPageFormat.memory, &pRect)

    Swift.print("pRect \(pRect)")

    status = PMRelease(pmPageFormat)
    status = PMRelease(printSession)
</code>```

答:
Am I declaring printSession improperly?

One could acquire a PMPrintSession as follows:

// create a C Null pointer of type PMPrintSession
let printSession = unsafeBitCast(0, to: PMPrintSession.self)
// pass by & converts PMPrintSession to UnsafeMutablePointer<PMPrintSession>
PMCreateSession(&printSession)
…
// recast printSession to release memory
PMRelease( PMObject(printSession) )
```

<p>Alternately, a <code>PMPrintSession</code> can be accessed from the Cocoa <code>NSPrintInfo</code>:</p>

<pre class="lang-swift prettyprint-override"><code>let printInfo = NSPrintInfo.shared()
let printSession = PMPrintSession(printInfo.pmPrintSession())
</code>```

Normally don't have to deal so much with UnsafeMutablePointers

For information more information on using an UnsafeMutablePointer see StackOverflow "How to use UnsafeMutablePointer in Swift?"

For a complete example of using Core Printing with Swift see 004.42Apple_CorePrintingExample on GitHub.

Body:
Trying to get printable rect for OS X app. Seems to involve creating a session, then a page format, validating the format, etc. Code compiles, but getting a status of -50 from PMCreateSession. Am I declaring printSession improperly? Normally don't have to deal so much with UnsafeMutablePointers.

Thanks!

    let printSession: UnsafeMutablePointer<PMPrintSession> = nil
    let pmPageFormat: UnsafeMutablePointer<PMPageFormat> = nil
    var status = PMCreateSession(printSession)
    status = PMCreatePageFormat(pmPageFormat)
    status = PMSessionDefaultPageFormat(printSession.memory, pmPageFormat.memory)
    let changed: UnsafeMutablePointer<DarwinBoolean> = nil
    status = PMSessionValidatePageFormat(printSession.memory, pmPageFormat.memory, changed)
    changed.destroy()
    var pRect = PMRect()
    status = PMGetAdjustedPageRect(pmPageFormat.memory, &pRect)

    Swift.print("pRect \(pRect)")

    status = PMRelease(pmPageFormat)
    status = PMRelease(printSession)

Body:
Am I declaring printSession improperly?

One could acquire a PMPrintSession as follows:

// create a C Null pointer of type PMPrintSession
let printSession = unsafeBitCast(0, to: PMPrintSession.self)
// pass by & converts PMPrintSession to UnsafeMutablePointer<PMPrintSession>
PMCreateSession(&printSession)
…
// recast printSession to release memory
PMRelease( PMObject(printSession) )

Alternately, a PMPrintSession can be accessed from the Cocoa NSPrintInfo:

let printInfo = NSPrintInfo.shared()
let printSession = PMPrintSession(printInfo.pmPrintSession())

Normally don't have to deal so much with UnsafeMutablePointers

For information more information on using an UnsafeMutablePointer see StackOverflow "How to use UnsafeMutablePointer in Swift?"

For a complete example of using Core Printing with Swift see 004.42Apple_CorePrintingExample on GitHub.


问:
Monitor a process
Is there a way I a process can be monitor and if it were to die, can a script be called which in turn will bring the process back up ?</p>

答: systemd is a sophisticated process manager available on most major Linux distributions.</p>

Title: Monitor a process


问:
zsh alias to remove all docker containers returns command not found
I have this alias in my .zshrc file:

```<code>alias rmcons="docker rm -f $(docker ps -aq)"
</code>```

But after trying to execute it, it removes only one container and then it prints

```<code>$rmcons
ef8197f147fb
zsh: command not found: c2ea2673f9e4
zsh: command not found: 4603059f1618
zsh: command not found: 40ad60328595
</code>```

How can I remove all containers that docker ps -aq shows?

答:
Warning: untested. I  don't use/have docker.

I think you should serialize the output first "escaping" the new lines.

You might also use the for loop, trying:

```<code>for id in `docker ps -aq`; do docker rm -f $id; done
</code>```

Note the backquotes to parse the command's output.

You can also directly use $() instead of its shortcut backquote.

I recommend to test with echo first instead of removing with rm:

```<code>for id in `docker -ps -aq`; do echo rm -f $id; done
</code>```

, and to use the rm with its -i switch to prompt for confirmation before deleting.

I hope docker's rm subcommand has one.

Body:
I have this alias in my .zshrc file:

alias rmcons="docker rm -f $(docker ps -aq)"

But after trying to execute it, it removes only one container and then it prints

$rmcons
ef8197f147fb
zsh: command not found: c2ea2673f9e4
zsh: command not found: 4603059f1618
zsh: command not found: 40ad60328595

How can I remove all containers that docker ps -aq shows?

Body:
Warning: untested. I  don't use/have docker.

I think you should serialize the output first "escaping" the new lines.

You might also use the for loop, trying:

for id in `docker ps -aq`; do docker rm -f $id; done

Note the backquotes to parse the command's output.

You can also directly use $() instead of its shortcut backquote.

I recommend to test with echo first instead of removing with rm:

for id in `docker -ps -aq`; do echo rm -f $id; done

, and to use the rm with its -i switch to prompt for confirmation before deleting.

I hope docker's rm subcommand has one.


问:
ASP.NET DataList - defining "columns/rows" when repeating horizontal and using flow layout
Here is my DataList:

```<code><asp:DataList id="DataList" Visible="false" RepeatDirection="Horizontal" Width="100%" HorizontalAlign="Justify" RepeatLayout="Flow" runat="server">
        [Contents Removed]
</asp:DataList>
</code>```

This generates markup that has each item wrapped in a span. From there, I'd like to break each of these spans out into rows of three columns. Ideally I would like something like this:

```<code><div>
 <span>Item 1</span>
 <span>Item 2</span>
 <span>Item 3</span>
</div>
<div>
 <span>Item 4</span>
 <span>Item 5</span>
 <span>Item 6</span>
</div>
[etc]
</code>```

The closest I can get to this is to set RepeatColumns to "3" and then a
 is inserted after every three items in the DataList.

```<code> <span>Item 1</span>
 <span>Item 2</span>
 <span>Item 3</span>
<br>
 <span>Item 4</span>
 <span>Item 5</span>
 <span>Item 6</span>
<br>
</code>```

This gets me kind of close, but really doesn't do the trick - I still can't control the layout the way I'd like to be able to.

Can anyone suggest a way to make this better? If I could implement the above example - that would be perfect, however I'd accept a less elegant solution as well - as long as its more flexible than
 (such as inserting a  instead of
).

答:
You can achieve your desired layout using CSS without altering the original generated markup.  Since span tags are displayed inline by default, switching to inline-block and specifying a width of 33% on those spans should do the trick.

Or more specifically, set the CssClass property of your DataList control to a value such as "threecolumns".

Define the following css style:

```<code><style type="text/css">
.threecolumns span
{
    display: inline-block;
    width: 33%;
}
</style>
</code>```

VS2008 might tell you that inline-block isn't a valid setting for the display property.  I wouldn't worry about that too much since almost every browser supports it.

OwnerDisplayName: irobinson

Body:
Here is my DataList:

<asp:DataList id="DataList" Visible="false" RepeatDirection="Horizontal" Width="100%" HorizontalAlign="Justify" RepeatLayout="Flow" runat="server">
        [Contents Removed]
</asp:DataList>

This generates markup that has each item wrapped in a span. From there, I'd like to break each of these spans out into rows of three columns. Ideally I would like something like this:

 Item 1
 Item 2
 Item 3

 Item 4
 Item 5
 Item 6

[etc]

The closest I can get to this is to set RepeatColumns to "3" and then a
 is inserted after every three items in the DataList.

 Item 1
 Item 2
 Item 3

 Item 4
 Item 5
 Item 6

This gets me kind of close, but really doesn't do the trick - I still can't control the layout the way I'd like to be able to.

Can anyone suggest a way to make this better? If I could implement the above example - that would be perfect, however I'd accept a less elegant solution as well - as long as its more flexible than
 (such as inserting a  instead of
).

LastEditorDisplayName: bdukes

Body:
You can achieve your desired layout using CSS without altering the original generated markup.  Since span tags are displayed inline by default, switching to inline-block and specifying a width of 33% on those spans should do the trick.

Or more specifically, set the CssClass property of your DataList control to a value such as "threecolumns".

Define the following css style:

<style type="text/css">
.threecolumns span
{
    display: inline-block;
    width: 33%;
}
</style>

VS2008 might tell you that inline-block isn't a valid setting for the display property.  I wouldn't worry about that too much since almost every browser supports it.


问:
Need to abstract collections of objects (C#)
In the following simplified example, I need to abstract Collection classes in such a way that PrintFruitsAndEaters(oranges, orangeEaters); or PrintFruitsAndEaters(apples, appleEaters);
becomes possible:

```<code>abstract class Fruit
abstract class FruitEater

class Apple : Fruit
class AppleEater : FruitEater
class Orange : Fruit
class OrangeEater : FruitEater

class AppleCollection : List<Apple>
class OrangeCollection : List<Orange>
class AppleEaterCollection : List<AppleEater>
class OrangeEaterCollection : List<OrangeEater>
</code>```

I've tried templatizing the method and collection classes, but i need to access methods specific to Fruit and FruitEater classes:

```<code>class FruitCollection<T> : List<T>
class FruitEaterCollection<T> : List<T>

void PrintFruitsAndEaters<T, S>(FruitCollection<T> fruits, FruitEaterCollection<S> eaters)
</code>```

答:
Then you want this:

```<code>void PrintFruitsAndEaters<T, S>(
    FruitCollection<T> fruits,
    FruitEaterCollection<S> eaters)
        where T : Fruit
        where S : FruitEater
{
    // ...
}
</code>```

This will constrain the T and S types as you require; calling the method with a FruitCollection<T>, where the T cannot be guaranteed to be Fruit or a subtype, will result in a compile-time error.  Same with S and FruitEater.

Because of the constraint, when working with a value of type T you will be able to access members of the Fruit class, and when working with a value of type S you will be able to access members of the FruitEater class.

Note that, as per Brian's (deleted) answer, you might want to add constraints to the collection types too:

```<code>class FruitCollection<T> : List<T> where T : Fruit { }
class FruitEaterCollection<T> : List<T> where T : FruitEater { }
</code>```

But this will still not allow you to omit the constraints on the method.

(Also, inheriting List<T> is an evil thing to do, instead use IList<T>)

Body:
In the following simplified example, I need to abstract Collection classes in such a way that PrintFruitsAndEaters(oranges, orangeEaters); or PrintFruitsAndEaters(apples, appleEaters);
becomes possible:

abstract class Fruit
abstract class FruitEater

class Apple : Fruit
class AppleEater : FruitEater
class Orange : Fruit
class OrangeEater : FruitEater

class AppleCollection : List<Apple>
class OrangeCollection : List<Orange>
class AppleEaterCollection : List<AppleEater>
class OrangeEaterCollection : List<OrangeEater>

I've tried templatizing the method and collection classes, but i need to access methods specific to Fruit and FruitEater classes:

class FruitCollection<T> : List<T>
class FruitEaterCollection<T> : List<T>

void PrintFruitsAndEaters<T, S>(FruitCollection<T> fruits, FruitEaterCollection<S> eaters)

Body:
Then you want this:

void PrintFruitsAndEaters<T, S>(
    FruitCollection<T> fruits,
    FruitEaterCollection<S> eaters)
        where T : Fruit
        where S : FruitEater
{
    // ...
}

This will constrain the T and S types as you require; calling the method with a FruitCollection<T>, where the T cannot be guaranteed to be Fruit or a subtype, will result in a compile-time error.  Same with S and FruitEater.

Because of the constraint, when working with a value of type T you will be able to access members of the Fruit class, and when working with a value of type S you will be able to access members of the FruitEater class.

Note that, as per Brian's (deleted) answer, you might want to add constraints to the collection types too:

class FruitCollection<T> : List<T> where T : Fruit { }
class FruitEaterCollection<T> : List<T> where T : FruitEater { }

But this will still not allow you to omit the constraints on the method.

(Also, inheriting List<T> is an evil thing to do, instead use IList<T>)


问:
C++ Concatenate containers of polymorphic objects
Assume I have a virtual base class and some derived concrete classes:

```<code>class Base { ... }
class DerivedA : public Base { ... }
class DerivedB : public Base { ... }
class DerivedC : public Base { ... }
</code>```

And somewhere I have vectors of objects of each derived class:

```<code>std::vector<DerivedA> my_a;
std::vector<DerivedB> my_b;
std::vector<DerivedC> my_c;
</code>```

Now, quite often I need to iterate over all elements in all three vectors and exercise the base class interface. I could write three for-loops, doing exactly the same in each. But obviously that's a far from optimal solution.

Is there a clever way to concatenate the vectors into a common container with base-class pointers/references, such that I need to iterate only once? Or any other idea how to solve this elegantly?

答:
There's no need for polymorphism in your current situation. You could simply use a variadic template + higher-order function to iterate over the vectors. Here's a C++17 solution using a fold expression:

```<code>template <typename F, typename... Vectors>
void for_all_vectors(F&& f, Vectors&&... vs)
{
    (std::for_each(std::forward<Vectors>(vs).begin(),
                   std::forward<Vectors>(vs).end(),
                   f), ...);
}
</code>```

Usage:

```<code>int main()
{
    std::vector<A> my_a;
    std::vector<B> my_b;
    std::vector<C> my_c;

    for_all_vectors([](const auto& x){ something(x); }, my_a, my_b, my_c);
}
</code>```

live example on wandbox

In C++11/14 you can replace the fold expression with for_each_argument:

```<code>template <typename TF, typename... Ts>
void for_each_argument(TF&& f, Ts&&... xs)
{
    return (void)std::initializer_list<int>{
        (f(std::forward<Ts>(xs)), 0)...};
}

template <typename F, typename... Vectors>
void for_all_vectors(F&& f, Vectors&&... vs)
{
    for_each_argument([&f](auto&& v)
    {
        std::for_each(v.begin(), v.end(), f);
    }, std::forward<Vectors>(vs)...);
}
</code>```

live example on wandbox

I explain the idea behind this snippet and expand upon it in this CppCon 2015 talk: "for_each_argument explained and expanded".

Body:
Assume I have a virtual base class and some derived concrete classes:

class Base { ... }
class DerivedA : public Base { ... }
class DerivedB : public Base { ... }
class DerivedC : public Base { ... }

And somewhere I have vectors of objects of each derived class:

std::vector<DerivedA> my_a;
std::vector<DerivedB> my_b;
std::vector<DerivedC> my_c;

Now, quite often I need to iterate over all elements in all three vectors and exercise the base class interface. I could write three for-loops, doing exactly the same in each. But obviously that's a far from optimal solution.

Is there a clever way to concatenate the vectors into a common container with base-class pointers/references, such that I need to iterate only once? Or any other idea how to solve this elegantly?

Body:
There's no need for polymorphism in your current situation. You could simply use a variadic template + higher-order function to iterate over the vectors. Here's a C++17 solution using a fold expression:

template <typename F, typename... Vectors>
void for_all_vectors(F&& f, Vectors&&... vs)
{
    (std::for_each(std::forward<Vectors>(vs).begin(),
                   std::forward<Vectors>(vs).end(),
                   f), ...);
}

Usage:

int main()
{
    std::vector<A> my_a;
    std::vector<B> my_b;
    std::vector<C> my_c;

    for_all_vectors([](const auto& x){ something(x); }, my_a, my_b, my_c);
}

live example on wandbox

In C++11/14 you can replace the fold expression with for_each_argument:

template <typename TF, typename... Ts>
void for_each_argument(TF&& f, Ts&&... xs)
{
    return (void)std::initializer_list<int>{
        (f(std::forward<Ts>(xs)), 0)...};
}

template <typename F, typename... Vectors>
void for_all_vectors(F&& f, Vectors&&... vs)
{
    for_each_argument([&f](auto&& v)
    {
        std::for_each(v.begin(), v.end(), f);
    }, std::forward<Vectors>(vs)...);
}

live example on wandbox

I explain the idea behind this snippet and expand upon it in this CppCon 2015 talk: "for_each_argument explained and expanded".


问:
implementing authentication and authorization using JWT token
I am just confuse to use UseJwtBearerAuthentication or JWT with OAUTH 2 for implementing authentication and authorization in .Net Core Web API.</p>

答:
JSON Web Token (JWT) is an implementation of OAUTH 2.

ASP.NET Core and Angular 2 by Valerio De Sanctis explains very detail on how to implement JWT provider in ASP.NET Core. Here is the sample code -

```<code>public void Configure(IApplicationBuilder app...)
{
     ...
    // Add a custom Jwt Provider to generate Tokens
    app.UseJwtProvider();

    // Add the Jwt Bearer Header Authentication to validate Tokens
    app.UseJwtBearerAuthentication(new JwtBearerOptions()
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        RequireHttpsMetadata = false,
        TokenValidationParameters = new TokenValidationParameters()
        {
            IssuerSigningKey = JwtProvider.SecurityKey,
            ValidateIssuerSigningKey = true,
            ValidIssuer = JwtProvider.Issuer,
            ValidateIssuer = false,
            ValidateAudience = false
        }
    });
    ...
}
</code>```

Unfortunately, the sample code is written in previous version of ASP.NET Core which used project.json. I convert the project to csproj at GitHub.

Body:
JSON Web Token (JWT) is an implementation of OAUTH 2.

ASP.NET Core and Angular 2 by Valerio De Sanctis explains very detail on how to implement JWT provider in ASP.NET Core. Here is the sample code -

public void Configure(IApplicationBuilder app...)
{
     ...
    // Add a custom Jwt Provider to generate Tokens
    app.UseJwtProvider();

    // Add the Jwt Bearer Header Authentication to validate Tokens
    app.UseJwtBearerAuthentication(new JwtBearerOptions()
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        RequireHttpsMetadata = false,
        TokenValidationParameters = new TokenValidationParameters()
        {
            IssuerSigningKey = JwtProvider.SecurityKey,
            ValidateIssuerSigningKey = true,
            ValidIssuer = JwtProvider.Issuer,
            ValidateIssuer = false,
            ValidateAudience = false
        }
    });
    ...
}

Unfortunately, the sample code is written in previous version of ASP.NET Core which used project.json. I convert the project to csproj at GitHub.


问:
How to modify this kind of file by Ruby
I have a file like:

```<code>Fruit.Store={
    #order:123, order:345, order:456
    #order:789
    "customer-id:12345,item:store/apple" = 10;
    "customer-id:23456,item:store/banana" = 10;
    "customer-id:23456,item:store/watermelon" = 10;
    #order:987
    "customer-id:67890,item:store/pear" = 10;
}
</code>```

Except the comments, each line has the same format: customer-id and item:store/ are fixed, and customer-id is a 5-digit number. There are about 1000 unique lines in the file.

When a new order is placed based on same customer-id and fruit type with different quantity, I want the order id be added in the comment line above and update the quantity, like if a new order 001 is placed with information "customer-id:23456,item:store/watermelon" = 5;  than we should have a new file:

```<code>Fruit.Store={
    #order:123, order:345, order:456
    #order:789, order:000
    "customer-id:12345,item:store/apple" = 10;
    "customer-id:23456,item:store/banana" = 10;
    "customer-id:23456,item:store/watermelon" = 5;
    #order:987
    "customer-id:67890,item:store/pear" = 10;
}
</code>```

Is it possible to do so in an efficient way? Because file has to be read and written line by line, how could we detect the matched information and go back to previous line to do modification? Thank you.

答:
In short: no, it is not possible to do so in an efficient way. Your best bet is to open separate files for reading and writing, but even then you'll effectively be rewriting the entire file over and over.

Ultimately, you should be using some sort of referential database, like SQL. Those databases were practically invented for this exact use-case.

I really don't like to tell people that the only solution is to do something entirely different from what they're doing, but in this case I can't stress enough how poorly text files scale for managing data.

Title: How to modify this kind of file by Ruby

Body:
I have a file like:

Fruit.Store={
    #order:123, order:345, order:456
    #order:789
    "customer-id:12345,item:store/apple" = 10;
    "customer-id:23456,item:store/banana" = 10;
    "customer-id:23456,item:store/watermelon" = 10;
    #order:987
    "customer-id:67890,item:store/pear" = 10;
}

Except the comments, each line has the same format: customer-id and item:store/ are fixed, and customer-id is a 5-digit number. There are about 1000 unique lines in the file.

When a new order is placed based on same customer-id and fruit type with different quantity, I want the order id be added in the comment line above and update the quantity, like if a new order 001 is placed with information "customer-id:23456,item:store/watermelon" = 5;  than we should have a new file:

Fruit.Store={
    #order:123, order:345, order:456
    #order:789, order:000
    "customer-id:12345,item:store/apple" = 10;
    "customer-id:23456,item:store/banana" = 10;
    "customer-id:23456,item:store/watermelon" = 5;
    #order:987
    "customer-id:67890,item:store/pear" = 10;
}

Is it possible to do so in an efficient way? Because file has to be read and written line by line, how could we detect the matched information and go back to previous line to do modification? Thank you.


答:
Using a command that you specify in a simple configuration file, Supervisor can start, monitor, and restart a process that unexpectedly dies.

Consider the following Supervisor configuration file fragment in /etc/supervisor/conf.d/forever.conf which displays the date and time every second:

```<code>[program:forever]
command=/bin/bash -c 'while true; do echo "Current time is `date`"; sleep 1; done;'
</code>```

Program forever starts with PID 15474:

```<code>derek@derek-lubuntu:~/Projects/fire$ sudo supervisorctl status forever
forever                          RUNNING   pid 15474, uptime 0:00:17
derek@derek-lubuntu:~/Projects/fire$ sudo supervisorctl tail forever
Current time is Fri Jul  7 17:11:10 EDT 2017
Current time is Fri Jul  7 17:11:11 EDT 2017
Current time is Fri Jul  7 17:11:12 EDT 2017
Current time is Fri Jul  7 17:11:13 EDT 2017
Current time is Fri Jul  7 17:11:14 EDT 2017
Current time is Fri Jul  7 17:11:15 EDT 2017
Current time is Fri Jul  7 17:11:16 EDT 2017
Current time is Fri Jul  7 17:11:17 EDT 2017
Current time is Fri Jul  7 17:11:18 EDT 2017
Current time is Fri Jul  7 17:11:19 EDT 2017
Current time is Fri Jul  7 17:11:20 EDT 2017
Current time is Fri Jul  7 17:11:21 EDT 2017
Current time is Fri Jul  7 17:11:22 EDT 2017
Current time is Fri Jul  7 17:11:23 EDT 2017
Current time is Fri Jul  7 17:11:24 EDT 2017
Current time is Fri Jul  7 17:11:25 EDT 2017
</code>```

Kill the forever process and Supervisor restarts it automatically with new process ID 15760:

```<code>derek@derek-lubuntu:~/Projects/fire$ sudo kill 15474
derek@derek-lubuntu:~/Projects/fire$ sudo supervisorctl status forever
forever                          RUNNING   pid 15760, uptime 0:00:02
derek@derek-lubuntu:~/Projects/fire$ sudo supervisorctl tail forever
Current time is Fri Jul  7 17:11:21 EDT 2017
Current time is Fri Jul  7 17:11:22 EDT 2017
Current time is Fri Jul  7 17:11:23 EDT 2017
Current time is Fri Jul  7 17:11:24 EDT 2017
Current time is Fri Jul  7 17:11:25 EDT 2017
Current time is Fri Jul  7 17:11:26 EDT 2017
Current time is Fri Jul  7 17:11:27 EDT 2017
Current time is Fri Jul  7 17:11:28 EDT 2017
Current time is Fri Jul  7 17:11:29 EDT 2017
Current time is Fri Jul  7 17:11:30 EDT 2017
Current time is Fri Jul  7 17:11:31 EDT 2017
Current time is Fri Jul  7 17:11:32 EDT 2017
Current time is Fri Jul  7 17:11:33 EDT 2017
Current time is Fri Jul  7 17:11:34 EDT 2017
Current time is Fri Jul  7 17:11:35 EDT 2017
Current time is Fri Jul  7 17:11:36 EDT 2017
</code>```

Title: Monitor a process

Body: Is there a way I a process can be monitor and if it were to die, can a script be called which in turn will bring the process back up ?

Body:
Using a command that you specify in a simple configuration file, Supervisor can start, monitor, and restart a process that unexpectedly dies.

Consider the following Supervisor configuration file fragment in /etc/supervisor/conf.d/forever.conf which displays the date and time every second:

[program:forever]
command=/bin/bash -c 'while true; do echo "Current time is `date`"; sleep 1; done;'

Program forever starts with PID 15474:

derek@derek-lubuntu:~/Projects/fire$ sudo supervisorctl status forever
forever                          RUNNING   pid 15474, uptime 0:00:17
derek@derek-lubuntu:~/Projects/fire$ sudo supervisorctl tail forever
Current time is Fri Jul  7 17:11:10 EDT 2017
Current time is Fri Jul  7 17:11:11 EDT 2017
Current time is Fri Jul  7 17:11:12 EDT 2017
Current time is Fri Jul  7 17:11:13 EDT 2017
Current time is Fri Jul  7 17:11:14 EDT 2017
Current time is Fri Jul  7 17:11:15 EDT 2017
Current time is Fri Jul  7 17:11:16 EDT 2017
Current time is Fri Jul  7 17:11:17 EDT 2017
Current time is Fri Jul  7 17:11:18 EDT 2017
Current time is Fri Jul  7 17:11:19 EDT 2017
Current time is Fri Jul  7 17:11:20 EDT 2017
Current time is Fri Jul  7 17:11:21 EDT 2017
Current time is Fri Jul  7 17:11:22 EDT 2017
Current time is Fri Jul  7 17:11:23 EDT 2017
Current time is Fri Jul  7 17:11:24 EDT 2017
Current time is Fri Jul  7 17:11:25 EDT 2017

Kill the forever process and Supervisor restarts it automatically with new process ID 15760:

derek@derek-lubuntu:~/Projects/fire$ sudo kill 15474
derek@derek-lubuntu:~/Projects/fire$ sudo supervisorctl status forever
forever                          RUNNING   pid 15760, uptime 0:00:02
derek@derek-lubuntu:~/Projects/fire$ sudo supervisorctl tail forever
Current time is Fri Jul  7 17:11:21 EDT 2017
Current time is Fri Jul  7 17:11:22 EDT 2017
Current time is Fri Jul  7 17:11:23 EDT 2017
Current time is Fri Jul  7 17:11:24 EDT 2017
Current time is Fri Jul  7 17:11:25 EDT 2017
Current time is Fri Jul  7 17:11:26 EDT 2017
Current time is Fri Jul  7 17:11:27 EDT 2017
Current time is Fri Jul  7 17:11:28 EDT 2017
Current time is Fri Jul  7 17:11:29 EDT 2017
Current time is Fri Jul  7 17:11:30 EDT 2017
Current time is Fri Jul  7 17:11:31 EDT 2017
Current time is Fri Jul  7 17:11:32 EDT 2017
Current time is Fri Jul  7 17:11:33 EDT 2017
Current time is Fri Jul  7 17:11:34 EDT 2017
Current time is Fri Jul  7 17:11:35 EDT 2017
Current time is Fri Jul  7 17:11:36 EDT 2017


问:
.find() triggers run-time error 91 even though all variables are set VBA possibly due to bad references
I am writing code to create a template. This code populates a tab named "fullDistribution" from user-input on different tabs in the same wb. I have a working section of code that I wrote in a separate module (for testing) away from my master module. The code runs properly and executes completely when it is separate. When I pasted this section of code into my master module and ran it, I began receiving "Run-time error 91: object variable or with block variable not set" at the start of the newly-pasted code. I am not using any with blocks, and all of my variables are set. I made no changes in my code when I transferred it to my master module, and I carried over the new variables I created.

This is the selection of code that I wrote in a separate module:

```<code>Worksheets("bls2016").Activate
tcount = WorksheetFunction.CountA(Worksheets("detailedEntity").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row))
acount = WorksheetFunction.CountA(Worksheets("detailedEntity").Range("K2:K7"))
Application.ScreenUpdating = False

Dim h As Integer
Dim f As Integer
Dim blstate As Range
Dim bl As Range
Dim state As Range
Dim deat As Range
Dim agje As Range
Dim e As Integer
Dim r As Integer
Dim ii As Integer

Set blstate = Worksheets("bls2016").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row)
Set state = Worksheets("detailedEntity").Range("Q1")
Set deat = Worksheets("detailedEntity").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row)
Set agje = Worksheets("detailedEntity").Range("L2:M" & Cells(Rows.Count, "M").End(xlUp).Row)

h = Activecolumn
f = Activerow
r = 2

x = 120
    For e = 1 To (acount * acount)
        blstate.Find(state).Select
        For ii = 1 To x
        'ccnt = acst.Offset(0, 1)
            ccgv = ActiveCell.Offset(0, 2)
            acem = ActiveCell.Offset(0, 5)
            Do While True
            vl1 = Application.IfNa(Application.VLookup(Worksheets("fullDistribution").Cells(r, 2), deat, 1, False), 0)
                If vl1 = 0 Then
                    Worksheets("fullDistribution").Cells(r, 4) = 0
                Else:
                    vl2 = Application.IfNa(Application.VLookup(Worksheets("fullDistribution").Cells(r, 1), agje, 2, False), 0)
                    If ActiveCell.Offset(0, 1).Value = "Unknown Or Undefined" Then
                        Exit Do
                    Else:
                        If vl2 = ccgv Then
                            Worksheets("fullDistribution").Cells(r, 4) = acem
                        ElseIf vl2 <> ccgv Then
                            Worksheets("fullDistribution").Cells(r, 4) = ActiveCell.Offset(x + 1, 5)
                        Else:
                            End If
                        End If
                    End If
                Exit Do
            Loop
            ActiveCell.Offset(f + 1, h).Select
        r = r + 1
        Next ii
    Next e
</code>```

The error triggers at the line "blstate.find(state).select" which tells excel to look in a dynamic range that contains the names of states and select the first instance of the state to use as the Activecell. Again, this works when it's run outside of the main module.

I believe this has something to do with a reference area. When this runs alone and finishes, I have to have a specific worksheet activated for it to run properly. If my excel workbook is open to a different tab, it will not run. My main module too only executes properly if it is run on a specific worksheet/tab.

If need be, I can edit my post and provide my whole master code.

答:
It may be a problem of not fully referencing sheets, eg amend your blstate line to

```<code>with Worksheets("bls2016")
 Set blstate = .Range("D2:D" & .Cells(.Rows.Count, "D").End(xlUp).Row)
end with
</code>```

Then it might find the value and not error. You should look up how to use the Find method as your way is destined to cause you headaches.

Body:
I am writing code to create a template. This code populates a tab named "fullDistribution" from user-input on different tabs in the same wb. I have a working section of code that I wrote in a separate module (for testing) away from my master module. The code runs properly and executes completely when it is separate. When I pasted this section of code into my master module and ran it, I began receiving "Run-time error 91: object variable or with block variable not set" at the start of the newly-pasted code. I am not using any with blocks, and all of my variables are set. I made no changes in my code when I transferred it to my master module, and I carried over the new variables I created.

This is the selection of code that I wrote in a separate module:

Worksheets("bls2016").Activate
tcount = WorksheetFunction.CountA(Worksheets("detailedEntity").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row))
acount = WorksheetFunction.CountA(Worksheets("detailedEntity").Range("K2:K7"))
Application.ScreenUpdating = False

Dim h As Integer
Dim f As Integer
Dim blstate As Range
Dim bl As Range
Dim state As Range
Dim deat As Range
Dim agje As Range
Dim e As Integer
Dim r As Integer
Dim ii As Integer

Set blstate = Worksheets("bls2016").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row)
Set state = Worksheets("detailedEntity").Range("Q1")
Set deat = Worksheets("detailedEntity").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row)
Set agje = Worksheets("detailedEntity").Range("L2:M" & Cells(Rows.Count, "M").End(xlUp).Row)

h = Activecolumn
f = Activerow
r = 2

x = 120
    For e = 1 To (acount * acount)
        blstate.Find(state).Select
        For ii = 1 To x
        'ccnt = acst.Offset(0, 1)
            ccgv = ActiveCell.Offset(0, 2)
            acem = ActiveCell.Offset(0, 5)
            Do While True
            vl1 = Application.IfNa(Application.VLookup(Worksheets("fullDistribution").Cells(r, 2), deat, 1, False), 0)
                If vl1 = 0 Then
                    Worksheets("fullDistribution").Cells(r, 4) = 0
                Else:
                    vl2 = Application.IfNa(Application.VLookup(Worksheets("fullDistribution").Cells(r, 1), agje, 2, False), 0)
                    If ActiveCell.Offset(0, 1).Value = "Unknown Or Undefined" Then
                        Exit Do
                    Else:
                        If vl2 = ccgv Then
                            Worksheets("fullDistribution").Cells(r, 4) = acem
                        ElseIf vl2 <> ccgv Then
                            Worksheets("fullDistribution").Cells(r, 4) = ActiveCell.Offset(x + 1, 5)
                        Else:
                            End If
                        End If
                    End If
                Exit Do
            Loop
            ActiveCell.Offset(f + 1, h).Select
        r = r + 1
        Next ii
    Next e

The error triggers at the line "blstate.find(state).select" which tells excel to look in a dynamic range that contains the names of states and select the first instance of the state to use as the Activecell. Again, this works when it's run outside of the main module.

I believe this has something to do with a reference area. When this runs alone and finishes, I have to have a specific worksheet activated for it to run properly. If my excel workbook is open to a different tab, it will not run. My main module too only executes properly if it is run on a specific worksheet/tab.

If need be, I can edit my post and provide my whole master code.

Body:
It may be a problem of not fully referencing sheets, eg amend your blstate line to

with Worksheets("bls2016")
 Set blstate = .Range("D2:D" & .Cells(.Rows.Count, "D").End(xlUp).Row)
end with

Then it might find the value and not error. You should look up how to use the Find method as your way is destined to cause you headaches.


问:
Accurately detect page with AJAX load time in Python using Selenium
I'm trying to accurately detect page load times on a company website I'm working on. I've decided to try and do this using python and selenium so I can automate it. However, I've seemed to have hit a wall since I'm unable to get a reliable page load time. The culprit appears to be the fact that we don't consider the page "loaded" until a ~3 second ajax call finishes. Yet, Selenium considers the page loaded when the DOM fully loads before that, which is not the load time we're looking for. I've read online I can use the WebDriverWait function to poll for an element that appears after the ajax executes. I should be able to do this as new elements are created after the ajax call, however, I've noticed online that it has a polling frequency of 500ms, which is far too large for me. I'm trying to very accurately determine page load times and 500ms is a large margin of error. I couldn't find anything online for how to change the default polling frequency in python, just similar stuff in Java that I can't decipher. If you know how to decrease the polling frequency by a lot or have a better idea of how to get the accurate page load time with Ajax with a margin of error around ~50ms please let me know. Thank you.</p>

答:
In one of my project I wrote such a function:

```<code>def wait_for(condition_function, *args):
    start_time = time.time()
    while time.time() < start_time + 10:
        if condition_function(*args):
            return True
        else:
            time.sleep(0.1)
    raise TimeoutException(
        'Timeout waiting for {}'.format(condition_function.__name__)
    )
</code>```

to later use it like this:

```<code>wait_for(obj_has_gone_stale, login_btn)
</code>```

where login_btn is a Selenium object and obj_has_gone_stale is a function that tries to find object and catches a StaleElementReferenceException. It looks like this:

```<code>def obj_has_gone_stale(obj):
    try:
        # poll the link with an arbitrary call
        obj.find_elements_by_id('doesnt-matter')
        return False
    except StaleElementReferenceException:
        return True
</code>```

With this approach you can set time.sleep() inside wait_for for any time you want. But don't forget to take into consideration that obj.find_elements_by_id('doesnt-matter') may also take some time to execute . No sure if it is much better that Selenium built-in wait for presence as I wrote wait_for for scenarios where the obj has to disappear and not to appear. But you may write something similar to obj_has_gone_stale but  obj_has_rendered. It basically has to try to access obj and see if it has been rendered on the page and return true. Then pass the function to wait_for.

Body:
In one of my project I wrote such a function:

def wait_for(condition_function, *args):
    start_time = time.time()
    while time.time() < start_time + 10:
        if condition_function(*args):
            return True
        else:
            time.sleep(0.1)
    raise TimeoutException(
        'Timeout waiting for {}'.format(condition_function.__name__)
    )

to later use it like this:

wait_for(obj_has_gone_stale, login_btn)

where login_btn is a Selenium object and obj_has_gone_stale is a function that tries to find object and catches a StaleElementReferenceException. It looks like this:

def obj_has_gone_stale(obj):
    try:
        # poll the link with an arbitrary call
        obj.find_elements_by_id('doesnt-matter')
        return False
    except StaleElementReferenceException:
        return True

With this approach you can set time.sleep() inside wait_for for any time you want. But don't forget to take into consideration that obj.find_elements_by_id('doesnt-matter') may also take some time to execute . No sure if it is much better that Selenium built-in wait for presence as I wrote wait_for for scenarios where the obj has to disappear and not to appear. But you may write something similar to obj_has_gone_stale but  obj_has_rendered. It basically has to try to access obj and see if it has been rendered on the page and return true. Then pass the function to wait_for.


问:
How to read contents of a CSV file inside zip file using spark (python)
I have multiple zip files containing two types of files(A.csv & B.csv)

/data/jan.zip --> contains A.csv & B.csv

/data/feb.zip --> contains A.csv & B.csv

I want to read the contents of all the A.csv files inside all the zip files using pyspark.

```<code> textFile = sc.textFile("hdfs://<HDFS loc>/data/*.zip")
</code>```

Can someone tell me how to get the contents of A.csv files into an RDD?

答:
Here you want to read all csv files inside the zip files recursively. </p>

```<code>val files = sc.CSVFiles("file://path/to/files/*.zip")
files.flatMap({case (name, content) =>
  unzip(content)
})

def unzip(content: String): List[String] = {
  ...
}
</code>```

Body:
I have multiple zip files containing two types of files(A.csv & B.csv)

/data/jan.zip --> contains A.csv & B.csv

/data/feb.zip --> contains A.csv & B.csv

I want to read the contents of all the A.csv files inside all the zip files using pyspark.

 textFile = sc.textFile("hdfs://<HDFS loc>/data/*.zip")

Can someone tell me how to get the contents of A.csv files into an RDD?

Body:
Here you want to read all csv files inside the zip files recursively.

val files = sc.CSVFiles("file://path/to/files/*.zip")
files.flatMap({case (name, content) =>
  unzip(content)
})

def unzip(content: String): List[String] = {
  ...
}


问:
python command line programming examples, recipes
There has been a need for python command line utilities at work lately and I have no experience in writing cli's. Regardless, I must still pop them out.

My biggest hurdle is the structure of these programs. Also, the method in getting and verifying input from the user. I have been ending up with very looong while loops and I just dont think that is the most efficient approach.

Could someone provide links to open source cli programs that I may pick to gain a bit of an understanding? Or, books, tutorials, etc that I could get my hands on. I have dug around but have had little success (my google skills must be lacking).

答:
If you can use python 2.7 or 3, or expect a common environment from which it might be accessible, consider argparse instead of optparse.  It gives you the same control optparse does over options with arguments.

I personally don't mind putting the all the parsing in the if __name__ == '__main__' block if it's pretty straightforward.

In your comment to Falmarri's response, you mention extensive user interaction during use of your CLI program - for me, that's starting to edge towards a "line-oriented command interpreter" like the cmd in the standard libary, or the excellent cmd2.  Looping over lines that are different with manually parsed raw_input's is replicating some of the functionality you could get from one of these.  I'd also be interested to see good examples of what you describe.