问:
Redirection not working on Safari and Firefox
I'm using express-ntlm for authenticate my users on my app. For Mac OS, browsers ask for username and password and when a user insert a wrong password, it shows a page with a forbidden message. I overwrite forbidden function on my custom library so I can redirect users to the current URL so they can insert username and password again. For some reason this works on Chrome but not on Firefox or Safari, it just keep refreshing the page but doesn't prompt users for username and password. Looks like browser is storing the failed tried of log in and doesn't let you try again.

```<code>forbidden: function(req,res){
    res
      .status(401)
      .send(`<!DOCTYPE html><html><head><body>
      <h2>Login failed, Please try again.</h2></body></head>
      <script>
      window.setTimeout(function() {
        window.location.href = '${req.url}';
      }, 1000);
      </script></html>`)
  }
</code>```

答:
NTLM only makes sense, if you use it for SSO (without manually entering credentials).

In your case I would suggest you to create your own username/password form and then use some Active Directory / LDAP module to authenticate against the Domain Controller. If it succeeds the user will be logged in, otherwise you show an error and the user can try again.

You can also combine them and use express-ntlm if a browser comes along that support NTLM (e.g. IE) and otherwise show a login form. In my opinion this would be the biggest benefit and best UX for your users.

Body:
I'm using express-ntlm for authenticate my users on my app. For Mac OS, browsers ask for username and password and when a user insert a wrong password, it shows a page with a forbidden message. I overwrite forbidden function on my custom library so I can redirect users to the current URL so they can insert username and password again. For some reason this works on Chrome but not on Firefox or Safari, it just keep refreshing the page but doesn't prompt users for username and password. Looks like browser is storing the failed tried of log in and doesn't let you try again.

forbidden: function(req,res){
    res
      .status(401)
      .send(`<!DOCTYPE html>

Login failed, Please try again.

      `)
  }


来源: stackexchange

问:
How to generate an image using C code
The function below simply serves html when it is called, however

```<code>void generateHTML (int socket) {
   char* message;

   // Sends HTTP response header

   message = "HTTP/1.0 200 OK\r\n"
                "Content-Type: text/html\r\n"
                "\r\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = "<HTML><BODY><P>Hello World.</P></BODY></HTML>\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));
}
</code>```

My output on the web browser would by a simple Hello World message. However, I want to change it so that it will display a bitmap image instead. Let's use a 1x1 red pixel as our bmp.

I've modified this function so far by:

```<code>void generateHTML (int socket) {
   char* message;

   // Sends HTTP response header

   message = "HTTP/1.0 200 OK\r\n"
                "Content-Type: image/bmp\r\n"
                "Content-Length: ???WTF???\r\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = "BMF8\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = " "; //bmp file data goes here.
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));
}
</code>```

Quoting from Dan's answer, the data in hex looks like:

```<code>0000000: 424d 3a00 0000 0000 0000 3600 0000 2800  BM:.......6...(.
0000010: 0000 0100 0000 0100 0000 0100 1800 0000  ................
0000020: 0000 0400 0000 130b 0000 130b 0000 0000  ................
0000030: 0000 0000 0000 0000 0000                 ..........
</code>```

However, I simply cannot place that inside the quotation marks. How would I do this?

ContentLicense: CC BY-SA 3.0

Title: How to generate an image using C code

Body:
The function below simply serves html when it is called, however

void generateHTML (int socket) {
   char* message;

   // Sends HTTP response header

   message = "HTTP/1.0 200 OK\r\n"
                "Content-Type: text/html\r\n"
                "\r\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = "
Hello World.
\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));
}

My output on the web browser would by a simple Hello World message. However, I want to change it so that it will display a bitmap image instead. Let's use a 1x1 red pixel as our bmp.

I've modified this function so far by:

void generateHTML (int socket) {
   char* message;

   // Sends HTTP response header

   message = "HTTP/1.0 200 OK\r\n"
                "Content-Type: image/bmp\r\n"
                "Content-Length: ???WTF???\r\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = "BMF8\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = " "; //bmp file data goes here.
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));
}

Quoting from Dan's answer, the data in hex looks like:

0000000: 424d 3a00 0000 0000 0000 3600 0000 2800  BM:.......6...(.
0000010: 0000 0100 0000 0100 0000 0100 1800 0000  ................
0000020: 0000 0400 0000 130b 0000 130b 0000 0000  ................
0000030: 0000 0000 0000 0000 0000                 ..........

However, I simply cannot place that inside the quotation marks. How would I do this?

Body:
this is an xxd dump of a 1x1 black windows bmp image:

0000000: 424d 3a00 0000 0000 0000 3600 0000 2800  BM:.......6...(.
0000010: 0000 0100 0000 0100 0000 0100 1800 0000  ................
0000020: 0000 0400 0000 130b 0000 130b 0000 0000  ................
0000030: 0000 0000 0000 0000 0000                 ..........


问:
How to print over a current line, using the python logging module
I am writing a program with multiple threads, thus for logging information I use the python logging module. However I have parts of application where I would like to display how much is a thread is waiting for execution in the same line which is overwritten each time. I do not want multiple lines to show in the log.

I tried to use the sys.stdout.flush() function. Unfortunately it doesn't work.

My current code:

```<code>def log_flush(message, start, stop):
    import logging, sys
    logging.basicConfig(level=logging.DEBUG,
                        format='(%(threadName)-10s) %(message)s',
                        )
    time = stop - start
    logging.debug((str(message) + str(time)))
    sys.stdout.write('\r')
    sys.stdout.flush()

for i in range(0, 5):
    log_flush("Time taken: ", 0, i)
</code>```

My expected output is (after execution is finished):

```<code>(MainThread) Time taken: 4
</code>```

While currently the script outputs:

```<code>(MainThread) Time taken: 0
(MainThread) Time taken: 1
(MainThread) Time taken: 2
(MainThread) Time taken: 3
(MainThread) Time taken: 4
</code>```

答:
I think you have to clean your console :))

see this question :

clear console in python

ContentLicense: CC BY-SA 4.0

Body:
I am writing a program with multiple threads, thus for logging information I use the python logging module. However I have parts of application where I would like to display how much is a thread is waiting for execution in the same line which is overwritten each time. I do not want multiple lines to show in the log.

I tried to use the sys.stdout.flush() function. Unfortunately it doesn't work.

My current code:

def log_flush(message, start, stop):
    import logging, sys
    logging.basicConfig(level=logging.DEBUG,
                        format='(%(threadName)-10s) %(message)s',
                        )
    time = stop - start
    logging.debug((str(message) + str(time)))
    sys.stdout.write('\r')
    sys.stdout.flush()

for i in range(0, 5):
    log_flush("Time taken: ", 0, i)

My expected output is (after execution is finished):

(MainThread) Time taken: 4

While currently the script outputs:

(MainThread) Time taken: 0
(MainThread) Time taken: 1
(MainThread) Time taken: 2
(MainThread) Time taken: 3
(MainThread) Time taken: 4


问:
Delete a record on clicking multiple checkbox
I want to delete a record which is selected in the checkbox and also deleted a whole record as well.

This is the tab where user can select checkbox for select all.

```<code><button type="checkbox" id="checkall" class="btn btn-default btn-sm checkbox-toggle">
    <i class="fa fa-square-o" ></i>
</button>
<div class="btn-group">
    <button type="submit" class="btn btn-default btn-sm" >
        <i class="fa fa-trash-o"></i>
    </button>
</div>

<!-- /.btn-group -->
<a href="{{ route('home.notificationbox') }}">
    <button type="button" class="btn btn-default btn-sm">
        <i class="fa fa-refresh"></i>
    </button>
</a>
</code>```

This the table structure

```<code><div class="table-responsive mailbox-messages">
    <table id="mailplan" class="table table-hover-row table-striped-row{{ count($admin_notifications) > 0 ? 'datatable' : '' }}" data-page-length="25">
        <tbody>
            @if (count($admin_notifications) > 0)

                <?php $count=1; ?>
                @foreach ($admin_notifications as $admin_notification)

                    @if($admin_notification['is_read'] == 1)
                        <tr class="table-dark-row" data-entry-id="{{ $admin_notification['notification_id'] }}">
                            <td>
                                <a href="">{{ $count++ }}</a>
                            </td>
                            <td>
                                <input type="checkbox" class="checkbox"
                                    onclick="delete_admin_notification({{ $admin_notification['notification_id'] }});"
                                    name = "deleteMultipleMail[]"
                                    value = "{{ $admin_notification['notification_id' ]}}">
                            </td>
                            <td class="mailbox-name">
                                <a href="#" onclick="showInDetail('{{ $admin_notification['message_type'] }}','{{ $admin_notification['message_view_id'] }}','{{ $admin_notification['notification_msg_id'] }}')">
                                    {{ $admin_notification['message_from'] }}
                                </a>
                            </td>
                            <td class="mailbox-subject">
                                <b>{{ $admin_notification['title'] }}</b> - {{ $admin_notification['message'] }}
                            </td>
                            <td class="mailbox-date">
                                {{ $admin_notification['duration'] }}
                            </td>
                        </tr>
                    @else

                        <tr data-entry-id="{{ $admin_notification['notification_id'] }}">
                            <td>
                                <a href="">{{ $count++ }}</a>
                            </td>
                            <td>
                                <input type="checkbox" class="checkbox"
                                    onclick = "delete_admin_notification({{ $admin_notification['notification_id']}});"
                                    value = "{{ $admin_notification['notification_id' ]}}">
                            </td>
                            <td class="mailbox-name">
                                <a href="#" onclick="showInDetail('{{ $admin_notification['message_type'] }}','{{ $admin_notification['message_view_id'] }}','{{ $admin_notification['notification_msg_id'] }}')">
                                    {{ $admin_notification['message_from'] }}
                                </a>
                            </td>
                            <td class="mailbox-subject">
                                <b>{{ $admin_notification['title'] }}</b> - {{ $admin_notification['message'] }}
                            </td>
                            <td class="mailbox-date">
                                {{ $admin_notification['duration'] }}
                            </td>
                        </tr>
                    @endif
                @endforeach
            @else
                <tr>
                    <td colspan="12">No Subscription Plan Available</td>
                </tr>
            @endif
        </tbody>

    </table>
    <!-- /.table -->
</div>
</code>```

Here is the script

```<code>$(function () {

    $('#check_all').on('click', function(e) {

        if($(this).is(':checked',true)) {

            $(".checkbox").prop('checked', true);
        } else {
            $(".checkbox").prop('checked',false);
        }
    });

    $('.checkbox').on('click',function() {

        if($('.checkbox:checked').length == $('.checkbox').length) {
            $('#check_all').prop('checked',true);
        } else {
            $('#check_all').prop('checked',false);
        }
    });

    $('.delete-all').on('click', function(e) {
        var idsArr = [];
        var strIds = idsArr.join(",");
        $.ajax({

            url: "/deleteMultipleMail",
            type: 'POST',
            headers: {'X-CSRF-TOKEN':token},
            data: 'ids='+strIds,
            success: function (data) {
                if(response['success']){
                window.location = response['redirect_url'];
                } else {
                    alert('Whoops Something went wrong!!');
                }
            },
            error: function (data) {
                alert(data.responseText);
            }
        });
    });
});
</code>```

This is deleted, controller.

```<code>public function delete_admin_notification(Request $request)
{
    if(!empty($request)) {

        $adminNotification=AdminNotification::find($request['notification_id'])->delete();
        return redirect()->back();
    } else {
        return false;
    }
}
public function deleteMultipleMail(Request $request)
{
    dd($request);
    $delId = $request->input('deleteMultipleMail');
    AdminNotification::whereIn('notification_id' , $delId)->delete();
    return redirect()->back();
}
</code>```

Route page

```<code>Route::post('/deleteMultipleMail','HomeController@deleteMultipleMail');
</code>```

Delete all record on clicking the checkbox or those who are selected only that would be deleted.

答:
In your js file:

```<code>$('.delete-all').on('click', function(e) {
    var idsArr = [];

    $('.checkbox').each(function(){
        var isChecked = $(this).prop('checked');

        if(isChecked){
            idsArr.push($(this).val());
        }
    });

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        url: "/deleteMultipleMail",
        type: 'POST',
        data:{
            idsArr: idsArr
        },
        success: function (response) {
            if(response.success){
             window.location = response.redirect_url;
            } else {
                alert('Whoops Something went wrong!!');
            }
        },
        error: function (data) {
            alert(data.responseText);
        }
    });
});
</code>```

In your controller:

```<code>public function deleteMultipleMail(Request $request)
{
    $post = $request->all();

    AdminNotification::whereIn('notification_id' , $post['idsArr'])->delete();

    return response()->json(['success' => true, 'redirect_url' => 'your redirect url']);
}
</code>```

Body:
I want to delete a record which is selected in the checkbox and also deleted a whole record as well.

This is the tab where user can select checkbox for select all.

<button type="checkbox" id="checkall" class="btn btn-default btn-sm checkbox-toggle">

</button>

    <button type="submit" class="btn btn-default btn-sm" >

    </button>

    <button type="button" class="btn btn-default btn-sm">

    </button>

This the table structure

 0 ? 'datatable' : '' }}" data-page-length="25">

            @if (count($admin_notifications) > 0)

                <?php $count=1; ?>
                @foreach ($admin_notifications as $admin_notification)

                    @if($admin_notification['is_read'] == 1)

                                {{ $count++ }}

                                <input type="checkbox" class="checkbox"
                                    onclick="delete_admin_notification({{ $admin_notification['notification_id'] }});"
                                    name = "deleteMultipleMail[]"
                                    value = "{{ $admin_notification['notification_id' ]}}">

                                    {{ $admin_notification['message_from'] }}

                                {{ $admin_notification['title'] }} - {{ $admin_notification['message'] }}

                                {{ $admin_notification['duration'] }}

                    @else

                                {{ $count++ }}

                                <input type="checkbox" class="checkbox"
                                    onclick = "delete_admin_notification({{ $admin_notification['notification_id']}});"
                                    value = "{{ $admin_notification['notification_id' ]}}">

                                    {{ $admin_notification['message_from'] }}

                                {{ $admin_notification['title'] }} - {{ $admin_notification['message'] }}

                                {{ $admin_notification['duration'] }}

                    @endif
                @endforeach
            @else

                    No Subscription Plan Available

            @endif

Here is the script

$(function () {

    $('#check_all').on('click', function(e) {

        if($(this).is(':checked',true)) {

            $(".checkbox").prop('checked', true);
        } else {
            $(".checkbox").prop('checked',false);
        }
    });

    $('.checkbox').on('click',function() {

        if($('.checkbox:checked').length == $('.checkbox').length) {
            $('#check_all').prop('checked',true);
        } else {
            $('#check_all').prop('checked',false);
        }
    });

    $('.delete-all').on('click', function(e) {
        var idsArr = [];
        var strIds = idsArr.join(",");
        $.ajax({

            url: "/deleteMultipleMail",
            type: 'POST',
            headers: {'X-CSRF-TOKEN':token},
            data: 'ids='+strIds,
            success: function (data) {
                if(response['success']){
                window.location = response['redirect_url'];
                } else {
                    alert('Whoops Something went wrong!!');
                }
            },
            error: function (data) {
                alert(data.responseText);
            }
        });
    });
});

This is deleted, controller.

public function delete_admin_notification(Request $request)
{
    if(!empty($request)) {

        $adminNotification=AdminNotification::find($request['notification_id'])->delete();
        return redirect()->back();
    } else {
        return false;
    }
}
public function deleteMultipleMail(Request $request)
{
    dd($request);
    $delId = $request->input('deleteMultipleMail');
    AdminNotification::whereIn('notification_id' , $delId)->delete();
    return redirect()->back();
}

Route page

Route::post('/deleteMultipleMail','HomeController@deleteMultipleMail');

Delete all record on clicking the checkbox or those who are selected only that would be deleted.

Body:
In your js file:

$('.delete-all').on('click', function(e) {
    var idsArr = [];

    $('.checkbox').each(function(){
        var isChecked = $(this).prop('checked');

        if(isChecked){
            idsArr.push($(this).val());
        }
    });

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        url: "/deleteMultipleMail",
        type: 'POST',
        data:{
            idsArr: idsArr
        },
        success: function (response) {
            if(response.success){
             window.location = response.redirect_url;
            } else {
                alert('Whoops Something went wrong!!');
            }
        },
        error: function (data) {
            alert(data.responseText);
        }
    });
});

In your controller:

public function deleteMultipleMail(Request $request)
{
    $post = $request->all();

    AdminNotification::whereIn('notification_id' , $post['idsArr'])->delete();

    return response()->json(['success' => true, 'redirect_url' => 'your redirect url']);
}


问:
WSSE Security PHP SoapServer- Header not understood
I have a client call with a WSSE Security Header:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsse:UsernameToken wsu:Id="UsernameToken-7BCCD9337425FBA038149772606059420"><wsse:Username>USERNAME</wsse:Username><wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">PASSWORD</wsse:Password><wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">NONCE</wsse:Nonce><wsu:Created>2017-06-17T19:01:00.594Z</wsu:Created></wsse:UsernameToken></wsse:Security></soapenv:Header>
   <soapenv:Body>
      <ns:FUNCTION/>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

As SoapServer I have a simple one:

```<code>// the SOAP Server options
$options=array(
    'trace' => true
    , 'cache_wsdl' => 0
    , 'soap_version' => SOAP_1_1
    , 'encoding' => 'UTF-8'
);

$wsdl = 'http://localhost/index.php?wsdl';

$server = new \SoapServer($wsdl, $options);
$server->setClass('ServerClass');
$server->handle();
$response = ob_get_clean();
echo $response;
</code>```

As soon the property MustUnderstand = 1, then I become from the server the exception: Header not understood.

How to understand the header?

How to make the WSSE validation on the SoapServer side?

答:
Mutatos' question / answer got me on the right track. I was working outside of a class structure so what worked for me was the following:

```<code>function Security($data)
{
    $username = $data->UsernameToken->Username;
    $password = $data->UsernameToken->Password;
    //check security credentials here
}

$server = new SoapServer("schema/wsdls/FCI_BookingPullService.wsdl", array('soap_version' => SOAP_1_2));
$server->addFunction("Security");
$server->handle();
</code>```

Essentially a function with the same name as the SOAP header "<wsse:Security>" (ignore the namespace) is being defined, then telling the server to use that to process the header with the 'addFunction' method.

Not ideal from a scope point of view, if that's an issue, try the class approach.

Body:
I have a client call with a WSSE Security Header:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsse:UsernameToken wsu:Id="UsernameToken-7BCCD9337425FBA038149772606059420"><wsse:Username>USERNAME</wsse:Username><wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">PASSWORD</wsse:Password><wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">NONCE</wsse:Nonce><wsu:Created>2017-06-17T19:01:00.594Z</wsu:Created></wsse:UsernameToken></wsse:Security></soapenv:Header>
   <soapenv:Body>
      <ns:FUNCTION/>
   </soapenv:Body>
</soapenv:Envelope>

As SoapServer I have a simple one:

// the SOAP Server options
$options=array(
    'trace' => true
    , 'cache_wsdl' => 0
    , 'soap_version' => SOAP_1_1
    , 'encoding' => 'UTF-8'
);

$wsdl = 'http://localhost/index.php?wsdl';

$server = new \SoapServer($wsdl, $options);
$server->setClass('ServerClass');
$server->handle();
$response = ob_get_clean();
echo $response;

As soon the property MustUnderstand = 1, then I become from the server the exception: Header not understood.

How to understand the header?

How to make the WSSE validation on the SoapServer side?

Body:
Mutatos' question / answer got me on the right track. I was working outside of a class structure so what worked for me was the following:

function Security($data)
{
    $username = $data->UsernameToken->Username;
    $password = $data->UsernameToken->Password;
    //check security credentials here
}

$server = new SoapServer("schema/wsdls/FCI_BookingPullService.wsdl", array('soap_version' => SOAP_1_2));
$server->addFunction("Security");
$server->handle();

Essentially a function with the same name as the SOAP header "<wsse:Security>" (ignore the namespace) is being defined, then telling the server to use that to process the header with the 'addFunction' method.

Not ideal from a scope point of view, if that's an issue, try the class approach.


问:
Discard some dictionary items in list during random.choice
I want to get random item from a list, also I don't want some items to be consider while random.choice(). Below is my data structure

```<code>x=[
  { 'id': 1, 'version':0.1, 'ready': True  }
  { 'id': 6, 'version':0.2, 'ready': True }
  { 'id': 4, 'version':0.1, 'ready': False }
  { 'id': 35, 'version':0.1, 'ready': False  }
  { 'id': 45, 'version':0.1, 'ready': False  }
  { 'id': 63, 'version':0.1, 'ready': True   }
  { 'id': 34, 'version':0.1, 'ready': True   }
  { 'id': 33, 'version':0.1, 'ready': True   }
]
</code>```

I can get the random item by using random.choice(x). But is there any way, consider 'ready': True attribute of item while random.choice().

Or any SIMPLE trick to achieve this?

NOTE: I want to use python in-built modules to avoid dependencies like numpy, etc.

答:
Just generate a new list with a list comprehension, selecting those items you want to randomly select from:

```<code>ready_items = [d for in x if d["ready"]]
random.choice(ready_items)
</code>```

You can combine the two into one expression:

```<code>random.choice([d for in x if d["ready"]])
</code>```

but if you are going to use random.choice() more than once then generating ready_items just once is helpful.

Body:
I want to get random item from a list, also I don't want some items to be consider while random.choice(). Below is my data structure

x=[
  { 'id': 1, 'version':0.1, 'ready': True  }
  { 'id': 6, 'version':0.2, 'ready': True }
  { 'id': 4, 'version':0.1, 'ready': False }
  { 'id': 35, 'version':0.1, 'ready': False  }
  { 'id': 45, 'version':0.1, 'ready': False  }
  { 'id': 63, 'version':0.1, 'ready': True   }
  { 'id': 34, 'version':0.1, 'ready': True   }
  { 'id': 33, 'version':0.1, 'ready': True   }
]

I can get the random item by using random.choice(x). But is there any way, consider 'ready': True attribute of item while random.choice().

Or any SIMPLE trick to achieve this?

NOTE: I want to use python in-built modules to avoid dependencies like numpy, etc.

Body:
Just generate a new list with a list comprehension, selecting those items you want to randomly select from:

ready_items = [d for in x if d["ready"]]
random.choice(ready_items)

You can combine the two into one expression:

random.choice([d for in x if d["ready"]])

but if you are going to use random.choice() more than once then generating ready_items just once is helpful.


问:
Angular 6: don't trigger validators setValue
I'm building a CRUD app using Angular 6.

My forms are used for adding and updating items. When the user updates an item, the form is pre-populated from the server. When the server updates the form it triggers the validation.

How can I update the form values without triggering the validation?

Here is the relevant code:

```<code>ngOnInit(){
    this.form = this.fb.group({
        name: ['', [Validators.required], MyAsyncValidator],
        comments: [''],
    });

    this.http.get('/api')
        .subscribe((data: any) => {
            this.form.setValue({ name: data.name, comments: data.comments });
        });
    //How to populate form without triggering validation
}
</code>```

The template:

```<code><form [formGroup]="form">
<div class="form-group row">
    <label class="col-sm-2 col-form-label">Name</label>
    <div class="col-sm-10">
        <input formControlName="name"
            class="form-control"
            [ngClass]="{'is-invalid': isInvalid(form.controls.name)}"
            type="text">
        <small *ngIf="form.get('name').status=='PENDING'" class="form-text text-muted">
            <i class="fa fa-spinner fa-spin"></i> Checking Name...
        </small>
        <small class="invalid-feedback">
            <div *ngIf="form.controls['name'].hasError('required')">Name Required</div>
            <div *ngIf="form.controls['name'].hasError('exists')">Name Exists</div>
        </small>
    </div>
</div>
</code>```

答:
Just faced same problem.

Calling control.markAsTouched() before calling control.setValue(value) worked for my case.

Does this mean validation fails only when the control is touched? hm...

I'm using Angular 7 btw

Body:
I'm building a CRUD app using Angular 6.

My forms are used for adding and updating items. When the user updates an item, the form is pre-populated from the server. When the server updates the form it triggers the validation.

How can I update the form values without triggering the validation?

Here is the relevant code:

ngOnInit(){
    this.form = this.fb.group({
        name: ['', [Validators.required], MyAsyncValidator],
        comments: [''],
    });

    this.http.get('/api')
        .subscribe((data: any) => {
            this.form.setValue({ name: data.name, comments: data.comments });
        });
    //How to populate form without triggering validation
}

The template:

<form [formGroup]="form">

    Name

        <input formControlName="name"
            class="form-control"
            [ngClass]="{'is-invalid': isInvalid(form.controls.name)}"
            type="text">

             Checking Name...

Name Required

Name Exists


问:
What is the highest FlyingSaucer R8 compatible Itext?
The FS distro comes bundled with IText 2.0.8 and given that are many more recent releases in the 2.x.x range i was wondering if anyone had any experiences in more recent releases. I am guesssing there is a chance FS might also be compatible with 3.x.x.x +...

Anybody know/confirm ?

答: I just tried 2.1.7 and it has some class (API) changes which cause Flying Saucer to get linkageerrors...so i n short no it would appear that 2.0.8 is the latest supported version.</p>


问:
amcharts4 - how to escape square bracket character ("[")
I would like to have Spread Value [EUR] as my title axis text so I tried with

valueAxis.title.text = "Spread Value \[EUR\]";
```

<p>because</p>

<pre class="lang-js prettyprint-override"><code>valueAxis.title.text = "Spread Value [EUR]";
</code>```

results in Spread Value.

Any suggestions how to fix?

Note: I could fix it with Spread Value (EUR) but I would like to use square brackets.

答:
You can use valueAxis.title.html instead of valueAxis.title.text:

```<code>valueAxis.title.html = "Spread Value [EUR]";
</code>```

Here is an example code pen.

Alternatively you can use double [[]] with valueAxis.title.text:

```<code>valueAxis.title.text = "Spread Value [[EUR]]";
</code>```

Body:
I would like to have Spread Value [EUR] as my title axis text so I tried with

valueAxis.title.text = "Spread Value \[EUR\]";

because

valueAxis.title.text = "Spread Value [EUR]";

results in Spread Value.

Any suggestions how to fix?

Note: I could fix it with Spread Value (EUR) but I would like to use square brackets.

Body:
You can use valueAxis.title.html instead of valueAxis.title.text:

valueAxis.title.html = "Spread Value [EUR]";

Here is an example code pen.

Alternatively you can use double [[]] with valueAxis.title.text:

valueAxis.title.text = "Spread Value [[EUR]]";


问:
Parameterized query from Excel with IN clause
I have a MS Query connection from Excel 2016 sheet to IBM DB2 database. I use parameterized query and link parameter values to Excel cell. While "singular value" clauses such as = < > like work, I can't get IN clause to work with multiple values but otherwise super simple query.

Here's a simple demo dataset how I produce the parameter values:

Column D formula is =IF(C2>5,A2&",","") which checks column C value for higher than 5 and populates ID in column D if TRUE. I'm expecting to use a helper cell to merge/concat all values in column D which I want to use for IN clause as value (yet to be completed).

How can I use "value1, value2, value3, ..." in a cell to run an IN clause query? Is it possible at all? IN clause works fine when the linked cell holds value 1 however 1, 3 produces error message:
"Bad parameter type. Microsoft Excel is expecting a different kind of value than what was provided".

Using a separate parameter and OR clause for each cell technically looks to work, however in practice the dataset can easily reach 50-100 values which means crazy amount of parameter setup.

Query itself is something as simple as:

```<code>select * from PRODUCTS a
where a.prod_ID in (1,3)
</code>```

or as Excel MS Query alternative:

```<code>select * from PRODUCTS a
where a.prod_ID in ?
</code>```

答:
posting this here for future googlers. So the solution was a bit out of the box for me - although still needs enhancement.

It checks for worksheet change events in range M1:M4 and then populates IN-clause query command text according to the prepared syntax in B1. Really out of the box for me!

Unfortunately it only handles a single Listobject (1) here, although I have more than one which should get the same treatment - but nevertheless, great stuff.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    Dim INvaluesCell As Range
    Dim SQLin As String, parts As Variant
    Dim i As Long, p1 As Long, p2 As Long
    Dim qt As QueryTable

    Set INvaluesCell = Range("B1")

    If Not Intersect(Target, Range(INvaluesCell, "M1:M4")) Is Nothing Then

        SQLin = ""
        parts = Split(INvaluesCell.Value, ",")
        For i = 0 To UBound(parts)
            SQLin = SQLin & "'" & parts(i) & "',"
        Next
        SQLin = " IN (" & Left(SQLin, Len(SQLin) - 1) & ")"

        Set qt = Me.ListObjects(1).QueryTable

        p1 = InStr(1, qt.CommandText, " IN (", vbTextCompare)
        If p1 > 0 Then
            p2 = InStr(p1, qt.CommandText, ")") + 1
            qt.CommandText = Left(qt.CommandText, p1 - 1) & SQLin & Mid(qt.CommandText, p2)
        End If

    End If

End Sub
</code>```

Body:
I have a MS Query connection from Excel 2016 sheet to IBM DB2 database. I use parameterized query and link parameter values to Excel cell. While "singular value" clauses such as = < > like work, I can't get IN clause to work with multiple values but otherwise super simple query.

Here's a simple demo dataset how I produce the parameter values:

Column D formula is =IF(C2>5,A2&",","") which checks column C value for higher than 5 and populates ID in column D if TRUE. I'm expecting to use a helper cell to merge/concat all values in column D which I want to use for IN clause as value (yet to be completed).

How can I use "value1, value2, value3, ..." in a cell to run an IN clause query? Is it possible at all? IN clause works fine when the linked cell holds value 1 however 1, 3 produces error message:
"Bad parameter type. Microsoft Excel is expecting a different kind of value than what was provided".

Using a separate parameter and OR clause for each cell technically looks to work, however in practice the dataset can easily reach 50-100 values which means crazy amount of parameter setup.

Query itself is something as simple as:

select * from PRODUCTS a
where a.prod_ID in (1,3)

or as Excel MS Query alternative:

select * from PRODUCTS a
where a.prod_ID in ?

Body:
posting this here for future googlers. So the solution was a bit out of the box for me - although still needs enhancement.

It checks for worksheet change events in range M1:M4 and then populates IN-clause query command text according to the prepared syntax in B1. Really out of the box for me!

Unfortunately it only handles a single Listobject (1) here, although I have more than one which should get the same treatment - but nevertheless, great stuff.

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim INvaluesCell As Range
    Dim SQLin As String, parts As Variant
    Dim i As Long, p1 As Long, p2 As Long
    Dim qt As QueryTable

    Set INvaluesCell = Range("B1")

    If Not Intersect(Target, Range(INvaluesCell, "M1:M4")) Is Nothing Then

        SQLin = ""
        parts = Split(INvaluesCell.Value, ",")
        For i = 0 To UBound(parts)
            SQLin = SQLin & "'" & parts(i) & "',"
        Next
        SQLin = " IN (" & Left(SQLin, Len(SQLin) - 1) & ")"

        Set qt = Me.ListObjects(1).QueryTable

        p1 = InStr(1, qt.CommandText, " IN (", vbTextCompare)
        If p1 > 0 Then
            p2 = InStr(p1, qt.CommandText, ")") + 1
            qt.CommandText = Left(qt.CommandText, p1 - 1) & SQLin & Mid(qt.CommandText, p2)
        End If

    End If

End Sub


问:
How to set timer to execute at specific time in c#
I have a requirement where i need to execute timer at 00:01:00 A.M every day...But  i am not getting how to achieve this ..If i am taking Systems time,it can be in different format..
Here is my timer code..</p>

```<code>static System.Timers.Timer timer;
timer = new System.Timers.Timer();
timer.Interval = 1000 * 60 * 60 * 24;//set interval of one day
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
start_timer();

static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        // Add timer code here

    }
    private static void start_timer()
    {
        timer.Start();
    }
</code>```

答:
Here is a timer implementation which takes an Interval (just like any other timer) and fires exactly when that interval expires, even the machine goes to sleep mode in between. </p>

```<code>public delegate void TimerCallbackDelegate(object sender, ElapsedEventArgs e);
public class TimerAbsolute : System.Timers.Timer
{
    private DateTime m_dueTime;
    private TimerCallbackDelegate callback;

    public TimerAbsolute(TimerCallbackDelegate cb) : base()
    {
        if (cb == null)
        {
            throw new Exception("Call back is NULL");
        }
        callback = cb;
        this.Elapsed += this.ElapsedAction;
        this.AutoReset = true;
    }

    protected new void Dispose()
    {
        this.Elapsed -= this.ElapsedAction;
        base.Dispose();
    }

    public double TimeLeft
    {
        get
        {
            return (this.m_dueTime - DateTime.Now).TotalMilliseconds;
        }
    }

    public int TimeLeftSeconds
    {
        get
        {
            return (int)(this.m_dueTime - DateTime.Now).TotalSeconds;
        }
    }

    public void Start(double interval)
    {
        if (interval < 10)
        {
            throw new Exception($"Interval ({interval}) is too small");
        }

        DateTime dueTime = DateTime.Now.AddMilliseconds(interval);

        if (dueTime <= DateTime.Now)
        {
            throw new Exception($"Due time ({dueTime}) should be in future. Interval ({interval})");
        }
        this.m_dueTime = dueTime;

        // Timer tick is 1 second
        this.Interval = 1 * 1000;
        base.Start();
    }

    private void ElapsedAction(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (DateTime.Now >= m_dueTime)
        {
            // This means Timer expired
            callback(sender, e);
            base.Stop();
        }
    }
}
</code>```

Body:
I have a requirement where i need to execute timer at 00:01:00 A.M every day...But  i am not getting how to achieve this ..If i am taking Systems time,it can be in different format..
Here is my timer code..

static System.Timers.Timer timer;
timer = new System.Timers.Timer();
timer.Interval = 1000 * 60 * 60 * 24;//set interval of one day
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
start_timer();

static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        // Add timer code here

    }
    private static void start_timer()
    {
        timer.Start();
    }

Body:
Here is a timer implementation which takes an Interval (just like any other timer) and fires exactly when that interval expires, even the machine goes to sleep mode in between.

public delegate void TimerCallbackDelegate(object sender, ElapsedEventArgs e);
public class TimerAbsolute : System.Timers.Timer
{
    private DateTime m_dueTime;
    private TimerCallbackDelegate callback;

    public TimerAbsolute(TimerCallbackDelegate cb) : base()
    {
        if (cb == null)
        {
            throw new Exception("Call back is NULL");
        }
        callback = cb;
        this.Elapsed += this.ElapsedAction;
        this.AutoReset = true;
    }

    protected new void Dispose()
    {
        this.Elapsed -= this.ElapsedAction;
        base.Dispose();
    }

    public double TimeLeft
    {
        get
        {
            return (this.m_dueTime - DateTime.Now).TotalMilliseconds;
        }
    }

    public int TimeLeftSeconds
    {
        get
        {
            return (int)(this.m_dueTime - DateTime.Now).TotalSeconds;
        }
    }

    public void Start(double interval)
    {
        if (interval < 10)
        {
            throw new Exception($"Interval ({interval}) is too small");
        }

        DateTime dueTime = DateTime.Now.AddMilliseconds(interval);

        if (dueTime <= DateTime.Now)
        {
            throw new Exception($"Due time ({dueTime}) should be in future. Interval ({interval})");
        }
        this.m_dueTime = dueTime;

        // Timer tick is 1 second
        this.Interval = 1 * 1000;
        base.Start();
    }

    private void ElapsedAction(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (DateTime.Now >= m_dueTime)
        {
            // This means Timer expired
            callback(sender, e);
            base.Stop();
        }
    }
}


问:
is there any convenient way to get a index of sub section in a page?
it is convenient to use "index-x" to quick locate a sub section in a page.

for instance

```<code>https://docs.python.org/3/library/re.html#index-2
</code>```

gives 3rd sub-section in this page.

when i want to share the location of a sub-section to others, how to get the index in a convenient way?

for instance, how to get the index of {m,n} sub-section without counting from index-0?

答:
With bs4 4.7.1 you can use :has and :contains to target a specific text string and return the index (note that using select_one will return first match. Use a list comprehension and select if want to return all matches

```<code>import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://docs.python.org/3/library/re.html')
soup = bs(r.content, 'lxml')
index = soup.select_one('dl:has(.pre:contains("{m,n}"))')['id']
print(index)
</code>```

Any version: if you want a dictionary that maps special characters to indices. Thanks to @zoe for spotting the error in my dictionary comprehension.

```<code>import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://docs.python.org/3/library/re.html')
soup = bs(r.content, 'lxml')
mappings = dict([(item['id'], [i.text for i in item.select('dt .pre')]) for item in soup.select('[id^="index-"]')])
indices = {i: k for (k, v) in mappings.items() for i in v}
</code>```

Body:
it is convenient to use "index-x" to quick locate a sub section in a page.

for instance

https://docs.python.org/3/library/re.html#index-2

gives 3rd sub-section in this page.

when i want to share the location of a sub-section to others, how to get the index in a convenient way?

for instance, how to get the index of {m,n} sub-section without counting from index-0?

Body:
With bs4 4.7.1 you can use :has and :contains to target a specific text string and return the index (note that using select_one will return first match. Use a list comprehension and select if want to return all matches

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://docs.python.org/3/library/re.html')
soup = bs(r.content, 'lxml')
index = soup.select_one('dl:has(.pre:contains("{m,n}"))')['id']
print(index)

Any version: if you want a dictionary that maps special characters to indices. Thanks to @zoe for spotting the error in my dictionary comprehension.

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://docs.python.org/3/library/re.html')
soup = bs(r.content, 'lxml')
mappings = dict([(item['id'], [i.text for i in item.select('dt .pre')]) for item in soup.select('[id^="index-"]')])
indices = {i: k for (k, v) in mappings.items() for i in v}


问:
Multiple content_for on the same page
I have large block of HTML in my application that I would like to move into a shared template and then use content_for with yields to insert the necessary content. However, if I use it more than once in the same layout file the content_for just appends to the previous making that idea not work so well. Is there a solution to this?

```<code><div class="block side">
    <div class="block_head">
        <div class="bheadl"></div>
        <div class="bheadr"></div>
        <h2><%= yield :block_head %></h2>
    </div>
    <div class="block_content">
        <%= yield :block_content %>
    </div>
    <div class="bendl"></div>
    <div class="bendr"></div>
</div>
</code>```

and I use the following code to set the content for the block

```<code>    <%= overwrite_content_for :block_head do -%>
        My Block
    <% end -%>
    <%= overwrite_content_for :block_content do -%>
        <p>My Block Content</p>
    <% end -%>
    <%= render :file => "shared/_blockside" %>
</code>```

The problem is if I use this multiple times on the same layout the content from the original block is appended to the secondary block

I have tried creating a custom helper method to get around it, however it does not return any content

```<code>  def overwrite_content_for(name, content = nil, &block)
    @_content_for[name] = ""
    content_for(name, content &block)
  end
</code>```

I may also be going about this completely wrong and if there are any better methods for getting content to work like this I would like to know. Thanks.

答:
You can use named content_for and yield blocks like this:

View:

```<code><% content_for :heading do %>
  <h1>Title of post</h1>
<% end %>

<p>Body text</p>

<% content_for :footer do %>
  <cite>By Author Name</cite>
<% end %>
</code>```

Then in a layout:

```<code><%= yield :heading %>
<%= yield %>
<%= yield :footer %>
</code>```

You can of course define those in any order.

Docs: http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html

Title: Multiple content_for on the same page

Body:
I have large block of HTML in my application that I would like to move into a shared template and then use content_for with yields to insert the necessary content. However, if I use it more than once in the same layout file the content_for just appends to the previous making that idea not work so well. Is there a solution to this?

<%= yield :block_head %>

        <%= yield :block_content %>

and I use the following code to set the content for the block

    <%= overwrite_content_for :block_head do -%>
        My Block
    <% end -%>
    <%= overwrite_content_for :block_content do -%>

My Block Content

    <% end -%>
    <%= render :file => "shared/_blockside" %>

The problem is if I use this multiple times on the same layout the content from the original block is appended to the secondary block

I have tried creating a custom helper method to get around it, however it does not return any content

  def overwrite_content_for(name, content = nil, &block)
    @_content_for[name] = ""
    content_for(name, content &block)
  end

I may also be going about this completely wrong and if there are any better methods for getting content to work like this I would like to know. Thanks.

Body:
You can use named content_for and yield blocks like this:

View:

<% content_for :heading do %>
  <h1>Title of post</h1>
<% end %>

<p>Body text</p>

<% content_for :footer do %>
  <cite>By Author Name</cite>
<% end %>

Then in a layout:

<%= yield :heading %>
<%= yield %>
<%= yield :footer %>

You can of course define those in any order.

Docs: http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html


问:
PHP - how to read json file header and other objects and insert in mysql
I am trying to read a json file, which has header, body and footer part and subsequently want to insert in mysql db using PHP code.

I tried to read json file, however the file has few header objects and data object. Data object has many records. I want to read header and data seperately. I tried to read data object, however even print statement didn't work. Please help in parsing the header and data object seperately.

php code

```<code>$json = file_get_contents('./f.json');

$json_data = json_decode($json,true);

print_r($json_data);

foreach ($json_data['data'] as $item => $value) {
    print $item['symbol'];
    print ' - ';
    print $item['ltp'];
    print ' - ';
    print '<br>';
}
</code>```

json file

```<code>{

    "noChg":0,
    "adv":10,
    "dec":3,
    "data":[
        {
            "symbol":"TECHM",
            "open":"749.90",
            "high":"749.90",
            "low":"732.05",
            "ltP":"737.00",
            "ptsC":"-6.30",
            "per":"-0.85"
        },
        {
            "symbol":"HAVELLS",
            "open":"752.85",
            "high":"754.90",
            "low":"739.10",
            "ltP":"745.00",
            "ptsC":"-6.50",
            "per":"-0.86"
        },
        {
            "symbol":"NESTLEIND",
            "open":"10,813.00",
            "high":"10,849.90",
            "low":"10,592.30",
            "ltP":"10,682.40",
            "ptsC":"-114.65",
            "per":"-1.06"
        },
        {
            "symbol":"HEXAWARE",
            "open":"356.30",
            "high":"357.45",
            "low":"349.45",
            "ltP":"352.00",
            "ptsC":"-4.15",
            "per":"-1.17"
        },
        {
            "symbol":"ADANIENT",
            "open":"162.35",
            "high":"163.75",
            "low":"151.85",
            "ltP":"159.15",
            "ptsC":"-1.90",
            "per":"-1.18"
        },
        {
            "symbol":"TORNTPHARM",
            "open":"1,554.80",
            "high":"1,566.90",
            "low":"1,511.20",
            "ltP":"1,530.00",
            "ptsC":"-22.20",
            "per":"-1.43"
        },
        {
            "symbol":"BATAINDIA",
            "open":"1,374.90",
            "high":"1,374.90",
            "low":"1,329.00",
            "ltP":"1,345.00",
            "ptsC":"-20.50",
            "per":"-1.50"
        },
        {
            "symbol":"KAJARIACER",
            "open":"616.05",
            "high":"619.00",
            "low":"595.20",
            "ltP":"603.00",
            "ptsC":"-12.80",
            "per":"-2.08"
        },
        {
            "symbol":"RELINFRA",
            "open":"116.40",
            "high":"116.90",
            "low":"111.05",
            "ltP":"111.85",
            "ptsC":"-2.60",
            "per":"-2.27"
        },
        {
            "symbol":"PVR",
            "open":"1,783.80",
            "high":"1,783.80",
            "low":"1,698.85",
            "ltP":"1,716.00",
            "ptsC":"-50.85",
            "per":"-2.88"
        },
        {
            "symbol":"SUNTV",
            "open":"553.00",
            "high":"561.30",
            "low":"512.00",
            "ltP":"531.70",
            "ptsC":"-16.15",
            "per":"-2.95"
        },
        {
            "symbol":"JETAIRWAYS",
            "open":"146.15",
            "high":"152.90",
            "low":"142.35",
            "ltP":"147.70",
            "ptsC":"-7.75",
            "per":"-4.99"
        },
        {
            "symbol":"JUSTDIAL",
            "open":"744.00",
            "high":"744.00",
            "low":"673.35",
            "ltP":"680.60",
            "ptsC":"-66.35",
            "per":"-8.88"
        }
    ],
    "totQty":"14,259.87",
    "totQtyMil":"1,425.99",
    "totValMil":"353.59",
    "time":"May 24, 2019 16:00:00",
    "totVal":"35,358.82" }
</code>```

I expect to parse and extract values from data objects, but i am getting the following error:

PHP Fatal error:  Cannot use object of type stdClass as array in
  /home/fut/public_html/on.php

答:
You need to pass second parameter True if you want to have JSON decoded as an array.</p>

```<code><?php
$json = file_get_contents('./f.json');

$json_data = json_decode($json, true);

print_r($json_data);

//to see header
$header = array_keys($json_data['data'][0]);
var_export($header);

$header2 = [];
foreach($json_data as $key => $item) {
    if(!is_array($item)) {
        $header2[$key] = $item;
    }
}
//to see the other header
var_export($header2);

foreach ($json_data['data'] as $item => $value) {
print $item['symbol'];
print ' - ';
print $item['ltp'];
print ' - ';
print '<br>';

}
</code>```

Body:
I am trying to read a json file, which has header, body and footer part and subsequently want to insert in mysql db using PHP code.

I tried to read json file, however the file has few header objects and data object. Data object has many records. I want to read header and data seperately. I tried to read data object, however even print statement didn't work. Please help in parsing the header and data object seperately.

php code

$json = file_get_contents('./f.json');

$json_data = json_decode($json,true);

print_r($json_data);

foreach ($json_data['data'] as $item => $value) {
    print $item['symbol'];
    print ' - ';
    print $item['ltp'];
    print ' - ';
    print '
';
}

json file

{

    "noChg":0,
    "adv":10,
    "dec":3,
    "data":[
        {
            "symbol":"TECHM",
            "open":"749.90",
            "high":"749.90",
            "low":"732.05",
            "ltP":"737.00",
            "ptsC":"-6.30",
            "per":"-0.85"
        },
        {
            "symbol":"HAVELLS",
            "open":"752.85",
            "high":"754.90",
            "low":"739.10",
            "ltP":"745.00",
            "ptsC":"-6.50",
            "per":"-0.86"
        },
        {
            "symbol":"NESTLEIND",
            "open":"10,813.00",
            "high":"10,849.90",
            "low":"10,592.30",
            "ltP":"10,682.40",
            "ptsC":"-114.65",
            "per":"-1.06"
        },
        {
            "symbol":"HEXAWARE",
            "open":"356.30",
            "high":"357.45",
            "low":"349.45",
            "ltP":"352.00",
            "ptsC":"-4.15",
            "per":"-1.17"
        },
        {
            "symbol":"ADANIENT",
            "open":"162.35",
            "high":"163.75",
            "low":"151.85",
            "ltP":"159.15",
            "ptsC":"-1.90",
            "per":"-1.18"
        },
        {
            "symbol":"TORNTPHARM",
            "open":"1,554.80",
            "high":"1,566.90",
            "low":"1,511.20",
            "ltP":"1,530.00",
            "ptsC":"-22.20",
            "per":"-1.43"
        },
        {
            "symbol":"BATAINDIA",
            "open":"1,374.90",
            "high":"1,374.90",
            "low":"1,329.00",
            "ltP":"1,345.00",
            "ptsC":"-20.50",
            "per":"-1.50"
        },
        {
            "symbol":"KAJARIACER",
            "open":"616.05",
            "high":"619.00",
            "low":"595.20",
            "ltP":"603.00",
            "ptsC":"-12.80",
            "per":"-2.08"
        },
        {
            "symbol":"RELINFRA",
            "open":"116.40",
            "high":"116.90",
            "low":"111.05",
            "ltP":"111.85",
            "ptsC":"-2.60",
            "per":"-2.27"
        },
        {
            "symbol":"PVR",
            "open":"1,783.80",
            "high":"1,783.80",
            "low":"1,698.85",
            "ltP":"1,716.00",
            "ptsC":"-50.85",
            "per":"-2.88"
        },
        {
            "symbol":"SUNTV",
            "open":"553.00",
            "high":"561.30",
            "low":"512.00",
            "ltP":"531.70",
            "ptsC":"-16.15",
            "per":"-2.95"
        },
        {
            "symbol":"JETAIRWAYS",
            "open":"146.15",
            "high":"152.90",
            "low":"142.35",
            "ltP":"147.70",
            "ptsC":"-7.75",
            "per":"-4.99"
        },
        {
            "symbol":"JUSTDIAL",
            "open":"744.00",
            "high":"744.00",
            "low":"673.35",
            "ltP":"680.60",
            "ptsC":"-66.35",
            "per":"-8.88"
        }
    ],
    "totQty":"14,259.87",
    "totQtyMil":"1,425.99",
    "totValMil":"353.59",
    "time":"May 24, 2019 16:00:00",
    "totVal":"35,358.82" }

I expect to parse and extract values from data objects, but i am getting the following error:

PHP Fatal error:  Cannot use object of type stdClass as array in
  /home/fut/public_html/on.php

Body:
You need to pass second parameter True if you want to have JSON decoded as an array.

<?php
$json = file_get_contents('./f.json');

$json_data = json_decode($json, true);

print_r($json_data);

//to see header
$header = array_keys($json_data['data'][0]);
var_export($header);

$header2 = [];
foreach($json_data as $key => $item) {
    if(!is_array($item)) {
        $header2[$key] = $item;
    }
}
//to see the other header
var_export($header2);

foreach ($json_data['data'] as $item => $value) {
print $item['symbol'];
print ' - ';
print $item['ltp'];
print ' - ';
print '<br>';

}


问:
Language switcher with PHP with a two dimensional array in short syntax
I like to create a language switcher for a website in three languages.
It would be nice to use a multidimensional array in the shorthand syntax.

Unfortunately I'm completely new to PHP, therefor it is difficult to find a script, which I only have to edit for my purpose.

The situation, which is a standard usecase I suppose:
There's a website with 3 languages (for the example I use 3 different pages for each lanuage).

```<code>https://example.tld/de/
https://example.tld/en/
https://example.tld/fr/

https://example.tld/de/zimmer
https://example.tld/en/rooms
https://example.tld/fr/chambres

https://example.tld/de/seminarbereich
https://example.tld/en/seminar-area
https://example.tld/fr/zone-seminaires
</code>```

Can I use the following two dimensional array to solve the task?

```<code>$myarray = [
['de', 'en', 'fr'], //language and as well the first part of the url
['Sprachumschalter', 'Language Switcher', 'Sélecteur de langue'], //aria-label
['Diese Seite auf Deutsch', 'This page in English', 'Cette page en français'], //title
['', '', ''], // page 1, start page of each language
['zimmer', 'rooms', 'chambres'], // page 2
['seminarbereich', 'seminar-area', 'zone-seminaires'] // page 3
]
</code>```

The result in form of HTML5 on each page should be - here in form of the page "rooms":

```<code><nav aria-label="Sprachumschalter">
    <ol>
        <li class="aktiv"><a href="/de/zimmer" lang="de" title="Diese Seite auf Deutsch">de</a></li>
        <li><a href="/en/rooms" lang="en" title="This page in English">en</a></li>
        <li><a href="/fr/chambres" lang="fr" title="Cette page en Français">fr</a></li>
    </ol>
</nav>
</code>```

Can you give me please a hint, where I can find a script which uses a comparable two dimenisional array for such a purpose?

I suppose I need a script which "asks"

"if the first of the url is 'de' than go to the array to position '...' and pick the appropriate content".

If there's someone who likes to help me, I would appreciate it. Thanks in advance.

答:
Try to change your structure like this:

```<code>$array = [
    ["de"] => [
         ["label"] => "Sprachumschalter",
         ["title"] => "Diese Seite auf Deutsch",
         ["page"] => ["", "zimmer", "seminarbereich"]
    ],
    ["en"] => [
         ["label"] => "Language Switcher",
         ["title"] => "This page in English",
         ["page"] => ["", "rooms", "seminar-area"]
    ],
    ["fr"] => [
         ["label"] => "Sélecteur de langue",
         ["title"] => "Cette page en français",
         ["page"] => ["", "chambres", "zone-seminaires"]
    ]
]
</code>```

Get URI Segments in PHP

```<code>https://example.tld/language/

$uriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

echo $uriSegments[1]; //returns language

$language = $uriSegments[1];
</code>```

So in your arra you can access to the information as follows:

```<code>var_dump($array[$language]); // get language data
echo $array[$language]["label"]; //get label
</code>```

So for get your page you can create a counter that started in 0;

```<code>$counterPage = 0;

echo $array[$language]["page"][$counterPage]; //get the page
</code>```

I hope I've helped you with an idea for how to solve it;

Body:
I like to create a language switcher for a website in three languages.
It would be nice to use a multidimensional array in the shorthand syntax.

Unfortunately I'm completely new to PHP, therefor it is difficult to find a script, which I only have to edit for my purpose.

The situation, which is a standard usecase I suppose:
There's a website with 3 languages (for the example I use 3 different pages for each lanuage).

https://example.tld/de/
https://example.tld/en/
https://example.tld/fr/

https://example.tld/de/zimmer
https://example.tld/en/rooms
https://example.tld/fr/chambres

https://example.tld/de/seminarbereich
https://example.tld/en/seminar-area
https://example.tld/fr/zone-seminaires

Can I use the following two dimensional array to solve the task?

$myarray = [
['de', 'en', 'fr'], //language and as well the first part of the url
['Sprachumschalter', 'Language Switcher', 'Sélecteur de langue'], //aria-label
['Diese Seite auf Deutsch', 'This page in English', 'Cette page en français'], //title
['', '', ''], // page 1, start page of each language
['zimmer', 'rooms', 'chambres'], // page 2
['seminarbereich', 'seminar-area', 'zone-seminaires'] // page 3
]

The result in form of HTML5 on each page should be - here in form of the page "rooms":

de

en

fr

Can you give me please a hint, where I can find a script which uses a comparable two dimenisional array for such a purpose?

I suppose I need a script which "asks"

"if the first of the url is 'de' than go to the array to position '...' and pick the appropriate content".

If there's someone who likes to help me, I would appreciate it. Thanks in advance.

Body:
Try to change your structure like this:

$array = [
    ["de"] => [
         ["label"] => "Sprachumschalter",
         ["title"] => "Diese Seite auf Deutsch",
         ["page"] => ["", "zimmer", "seminarbereich"]
    ],
    ["en"] => [
         ["label"] => "Language Switcher",
         ["title"] => "This page in English",
         ["page"] => ["", "rooms", "seminar-area"]
    ],
    ["fr"] => [
         ["label"] => "Sélecteur de langue",
         ["title"] => "Cette page en français",
         ["page"] => ["", "chambres", "zone-seminaires"]
    ]
]

Get URI Segments in PHP

https://example.tld/language/

$uriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

echo $uriSegments[1]; //returns language

$language = $uriSegments[1];

So in your arra you can access to the information as follows:

var_dump($array[$language]); // get language data
echo $array[$language]["label"]; //get label

So for get your page you can create a counter that started in 0;

$counterPage = 0;

echo $array[$language]["page"][$counterPage]; //get the page

I hope I've helped you with an idea for how to solve it;


问:
The public type <<classname>> must be defined in its own file: bad style or nice feature
(Since I got this error in a special situation where it actually makes sense to me.
I would like to share some insights and workarounds not mentioned elsewhere for similar questions here...)

```<code>/* e.g. located in a src/main/java/mypkg/MyKeys.java file */
package mypkg;

public enum EditStatus { ... }
public enum CustomerTypeKey { ... }  // the suggestion of an IDE could be
                                     // to move this one to its own file
// ...
</code>```

Now I want to have those types packed in one file as explained in my answer below...

答: Make sure and check that the class name is the same as the .java file name, that is the reason that I got the error above.  </p>

Body:
(Since I got this error in a special situation where it actually makes sense to me.
I would like to share some insights and workarounds not mentioned elsewhere for similar questions here...)

/* e.g. located in a src/main/java/mypkg/MyKeys.java file */
package mypkg;

public enum EditStatus { ... }
public enum CustomerTypeKey { ... }  // the suggestion of an IDE could be
                                     // to move this one to its own file
// ...

Now I want to have those types packed in one file as explained in my answer below...


问:
How to add a active class that stays activated
Hey there is a relatively strange problem on one part of my website. I included the part that doesn’t work anymore.  Normally the button should stay at the same size and should have a dark blue color if it is clicked. But right now, it just gets a basic html button. That’s strange because a few days ago the code worked perfectly fine and I changed nothing.

var header = document.getElementById("flex-wrapper-zahlung");
var btns = header.getElementsByClassName("accordion-zahlung");
for (var y = 0; y < btns.length; y++) {
  btns[y].addEventListener("click", function() {
    var current = document.getElementsByClassName("activated");
    if (current.length > 0) {
      current[0].className = current[0].className.replace("activated", "");
    }
    this.className += "activated";
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-wrapper-zahlung {
  margin: 0 0 0 0;
  width: 24em;
}

.accordion-zahlung {
  display: flex;
  background-color: #ededed;
  color: black;
  cursor: pointer;
  padding: .75em;
  width: 30em;
  border: none;
  text-align: left;
  outline: none;
  font-size: 1em;
  font-weight: 500;
  transition: 0.4s;
  margin: .5em 0 0 0;
  border-radius: .5em;
}

.activated,
.accordion-zahlung:hover {
  background-color: #092a5e;
  color: white;
}</code>```

  <button class="accordion-zahlung">     Kreditkarte</button>
  <button class="accordion-zahlung">        Lastschrift</button>
  <button class="accordion-zahlung">       PayPal</button>
  <button class="accordion-zahlung">     Rechnung</button>

```

答:
By looking at your code I think that you are simply missing a space when updating the className:
try with this.className += " activated"; instead of this.className += "activated";

With your code the new className of the button would've become <button class="accordion-zahlungactivated">.

Body:
Hey there is a relatively strange problem on one part of my website. I included the part that doesn’t work anymore.  Normally the button should stay at the same size and should have a dark blue color if it is clicked. But right now, it just gets a basic html button. That’s strange because a few days ago the code worked perfectly fine and I changed nothing.

var header = document.getElementById("flex-wrapper-zahlung");
var btns = header.getElementsByClassName("accordion-zahlung");
for (var y = 0; y < btns.length; y++) {
  btns[y].addEventListener("click", function() {
    var current = document.getElementsByClassName("activated");
    if (current.length > 0) {
      current[0].className = current[0].className.replace("activated", "");
    }
    this.className += "activated";
  });
}

.flex-wrapper-zahlung {
  margin: 0 0 0 0;
  width: 24em;
}

.accordion-zahlung {
  display: flex;
  background-color: #ededed;
  color: black;
  cursor: pointer;
  padding: .75em;
  width: 30em;
  border: none;
  text-align: left;
  outline: none;
  font-size: 1em;
  font-weight: 500;
  transition: 0.4s;
  margin: .5em 0 0 0;
  border-radius: .5em;
}

.activated,
.accordion-zahlung:hover {
  background-color: #092a5e;
  color: white;
}

  <button class="accordion-zahlung">     Kreditkarte</button>
  <button class="accordion-zahlung">        Lastschrift</button>
  <button class="accordion-zahlung">       PayPal</button>
  <button class="accordion-zahlung">     Rechnung</button>


答:
In order to add or remove a class you can use classList so that your code changes from:

```<code>this.className += "activated";
</code>```

to:

```<code>this.classList.add("activated");
</code>```

The snippet:

var header = document.getElementById("flex-wrapper-zahlung");
var btns = header.getElementsByClassName("accordion-zahlung");
for (var y = 0; y < btns.length; y++) {
    btns[y].addEventListener("click", function() {
        var current = document.getElementsByClassName("activated");
        if (current.length > 0) {
            current[0].classList.remove('activated')
        }
        this.classList.add("activated");
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-wrapper-zahlung {
    margin: 0 0 0 0;
    width: 24em;
}

.accordion-zahlung {
    display: flex;
    background-color: #ededed;
    color: black;
    cursor: pointer;
    padding: .75em;
    width: 30em;
    border: none;
    text-align: left;
    outline: none;
    font-size: 1em;
    font-weight: 500;
    transition: 0.4s;
    margin: .5em 0 0 0;
    border-radius: .5em;
}

.activated,
.accordion-zahlung:hover {
    background-color: #092a5e;
    color: white;
}</code>```

    <button class="accordion-zahlung">     Kreditkarte</button>

    <button class="accordion-zahlung">        Lastschrift</button>

    <button class="accordion-zahlung">       PayPal</button>

    <button class="accordion-zahlung">     Rechnung</button>

```

Title: How to add a active class that stays activated

Body:
In order to add or remove a class you can use classList so that your code changes from:

this.className += "activated";

to:

this.classList.add("activated");

The snippet:

var header = document.getElementById("flex-wrapper-zahlung");
var btns = header.getElementsByClassName("accordion-zahlung");
for (var y = 0; y < btns.length; y++) {
    btns[y].addEventListener("click", function() {
        var current = document.getElementsByClassName("activated");
        if (current.length > 0) {
            current[0].classList.remove('activated')
        }
        this.classList.add("activated");
    });
}

.flex-wrapper-zahlung {
    margin: 0 0 0 0;
    width: 24em;
}

.accordion-zahlung {
    display: flex;
    background-color: #ededed;
    color: black;
    cursor: pointer;
    padding: .75em;
    width: 30em;
    border: none;
    text-align: left;
    outline: none;
    font-size: 1em;
    font-weight: 500;
    transition: 0.4s;
    margin: .5em 0 0 0;
    border-radius: .5em;
}

.activated,
.accordion-zahlung:hover {
    background-color: #092a5e;
    color: white;
}

<div id="flex-wrapper-zahlung">

    <button class="accordion-zahlung"><i class="far fa-credit-card"></i> &nbsp; &nbsp; Kreditkarte</button>

    <button class="accordion-zahlung"> <i class="fas fa-file-invoice"></i> &nbsp; &nbsp; &nbsp; Lastschrift</button>

    <button class="accordion-zahlung"><i class="fab fa-paypal"></i> &nbsp; &nbsp; &nbsp; PayPal</button>

    <button class="accordion-zahlung"><i class="fas fa-money-check"></i> &nbsp; &nbsp; Rechnung</button>

</div>


问:
Deny access include file not working in nginx conf
Include not taken into account to deny access to certain ip

Nginx 1.12 is configured as a proxy.

I have 2 config files :

```<code>nginx.conf
mydomain.conf
</code>```

I followed a tuto to have a list of deny ip list, all in a 3rd conf file called blockips.conf.
Everyline in that conf file is like :

```<code>deny xxx.xxx.xxx.xxx;
</code>```

now, i tried to include like that in either the http or server section of both nginx.conf and mydomain.conf files (not both at the same time, but tring 1st and then 2n) but either it doesn't block either it crash.

```<code>include blockips.conf;
</code>```

but when i put only the

```<code>deny xxx.xxx.xxx.xxx;
</code>```

directly in the mydomain.conf in the server section then the ip is blocked. of course i could put all my list of ips within mydomain.conf file but it makes mote sense to have it external right ? but then it doesn't work. Of course, i've tried to have my blockips.conf file with only one line (just to make sure it is not a ; missing).

and i have checked the files right and they are all identical 644 under root

Thank you

答:
There was 2 nginx.conf files on my system and i was not modifying the correct one!
Just do a nginx -t just to verify where is the correct file.

now it is working.

Body:
Include not taken into account to deny access to certain ip

Nginx 1.12 is configured as a proxy.

I have 2 config files :

nginx.conf
mydomain.conf

I followed a tuto to have a list of deny ip list, all in a 3rd conf file called blockips.conf.
Everyline in that conf file is like :

deny xxx.xxx.xxx.xxx;

now, i tried to include like that in either the http or server section of both nginx.conf and mydomain.conf files (not both at the same time, but tring 1st and then 2n) but either it doesn't block either it crash.

include blockips.conf;

but when i put only the

deny xxx.xxx.xxx.xxx;

directly in the mydomain.conf in the server section then the ip is blocked. of course i could put all my list of ips within mydomain.conf file but it makes mote sense to have it external right ? but then it doesn't work. Of course, i've tried to have my blockips.conf file with only one line (just to make sure it is not a ; missing).

and i have checked the files right and they are all identical 644 under root

Thank you


问:
How to implement username/password auth with express ntlm?
I am trying to implement username and password auth with Express-ntlm.I have added below code as middleware

```<code>app.use( ntlm({
domain: '<domainname>',
domaincontroller: '<ldap url>',
}));
</code>```

I am not providing any user name password in the request and its automatically adding ntlm header in the request with my loggedin user details. I am getting {Authenticated:true} along with my username and system name in request.ntlm.
How can I provide different username/password in this and authenticate?
Also will this work if I login from linux/mac system?

答:
If you use a supported browser (e.g. IE) NTLM will automatically log the user in using the current session in Windows. express-ntlm will just receive this information and exposes it to the application.

If you want to use other credentials you have to log in using a different user in Windows or use a browser that will show you a prompt for username and password if it gets an NTLM challenge. If I remember correctly Chrome will do it like this.

I never tried it using macOS/Linux, but I'm sure most browser will just provide you a username/password prompt.

Body:
I am trying to implement username and password auth with Express-ntlm.I have added below code as middleware

app.use( ntlm({
domain: '<domainname>',
domaincontroller: '<ldap url>',
}));

I am not providing any user name password in the request and its automatically adding ntlm header in the request with my loggedin user details. I am getting {Authenticated:true} along with my username and system name in request.ntlm.
How can I provide different username/password in this and authenticate?
Also will this work if I login from linux/mac system?


问:
Android Image Loading Speeds
Does anyone out there know what image format results in the fastest loading speeds?
I haven't done any checks, but if someone has, please comment.

I know that the android docs say that it supports: .JPG, .GIF, .PNG, .BMP, .WEBP.
Lets say that I have to load many images very quickly, which format should I use to get the best performance? I am already using low-res and hi-res images. Loading the low-res images is very fast, but if you scroll my screen very fast, sometimes it can't quite keep up (there is a black section).

Also, does the method of loading matter? I'm currently using BitmapFactory.DecodeFile(path) as it is the easiest. I load the images asynchronously, so there is no 'hiccup' in the UI but we sometimes see black sections for a few milliseconds.

I know this also has to do with I/O speeds, but lets live in an ideal world where this speed is negligible.

答:
Surprisingly the IO is not the bottleneck.

1024x1024x32BPP image.

From the native side, I have more flexibility on what I'm loading.

PNG : 109ms
Custom TGA loader : 39ms

Custom RAW loader : 32ms

The profiler shows PNG loader spent an age decompressing, dwarfing file IO.

Title: Android Image Loading Speeds


问:
generics are not supported in -source 1.3
I have a problem while maven packaging. In this code:

```<code>public class LoginDialog extends Dialog {

    private final TextField<String> customer;
                          ^here
    private final TextField<String> login1;
    private final TextField<String> password1;
    private final MainController controller= new MainController();
    private String customerId;
    private String login;
    private String password;
</code>```

I have an error like:

```<code>[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure
...src/main/java/com/messagedna/web/client/widget/LoginDialog.java:[19,27] error: generics are not supported in -source 1.3
</code>```

what may be the reason of this?

答:
If you are not using maven and facing similar issue in Intellij editor, probably worth to check Project Settings.
Even if you define Proper JDK, change the "Project language level" and can configure 5 onward.</p>

Body:
I have a problem while maven packaging. In this code:

public class LoginDialog extends Dialog {

    private final TextField<String> customer;
                          ^here
    private final TextField<String> login1;
    private final TextField<String> password1;
    private final MainController controller= new MainController();
    private String customerId;
    private String login;
    private String password;

I have an error like:

[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure
...src/main/java/com/messagedna/web/client/widget/LoginDialog.java:[19,27] error: generics are not supported in -source 1.3

what may be the reason of this?


问:
What is the correct way to link a button to open an other py file?
I have a big doubt because my script is not performing as it should be. So I have a simple main file with a button that opens a blank grid (codes below). The problem with this code is that it opens reportWindow the first time it executes, but if I close the report and I  try to open it again I receive the error :
NameError: name 'TestFrame' is not defined

I've also removed if __name__ == '__main__' from the last lines of reportWindow.py because the script wasn't working with it. I tried if __name__ == 'main' as it's imported from main.py but it didn't work either.

Please, can someone show me how it should have been done the correct way?

Thank you

main.py

```<code>import wx

class Test(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id, "Frame aka Window", size=(300, 200))
        panel = wx.Panel(self)
        button = wx.Button(panel, label = "Exit", pos=(80, 80), size = (120,30))
        self.Bind(wx.EVT_BUTTON, self.closebutton, button)

    def closebutton(self,event):
        from reportWindow import SimpleGrid
        SimpleGrid(TestFrame, -1)

if __name__ == '__main__':
    app = wx.App()
    frame = Test(parent=None, id=1)
    frame.Show()
    app.MainLoop()
</code>```

reportWindow.py

```<code>import wx
import wx.grid as gridlib

class SimpleGrid(gridlib.Grid): ##, mixins.GridAutoEditMixin):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)

        #[...Some code...]

class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, 0, "Title", size=(1400,800))
        self.grid = SimpleGrid(self, log)

        #[...Some code...]

#if __name__ == '__main__':
import sys
from wx.lib.mixins.inspection import InspectableApp
app = InspectableApp(False)
frame = TestFrame(None, sys.stdout)
frame.Show(True)
#import wx.lib.inspection
#wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
</code>```

答:
Your code has a few of issues.

1) The NameError is occurring because you're not importing TestFrame from reportWindow.

2) Without if __name__ == "__main__" in reportWindow.py your program will create another wx.App and start another MainLoop which will block the first loop from receiving events etc... You should only create 1 App/MainLoop.  It will also create the TestFrame the first time you import reportWindow.

3) It looks like you want SimpleGrid to be a child of TestFrame, but then you try to create it by itself in closebutton.

4) When creating the SimpleGrid you pass the TestFrame class instead of an instance of the TestFrame class.

Here is the modified code

```<code># main.py
import wx, sys

class Test(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Frame aka Window", size=(300, 200))
        panel = wx.Panel(self)
        button = wx.Button(panel, label="Exit", pos=(80, 80), size=(120, 30))
        self.Bind(wx.EVT_BUTTON, self.closebutton, button)

    def closebutton(self, event):
        from reportWindow import TestFrame

        frame = TestFrame(self, sys.stdout)
        frame.Show()

if __name__ == '__main__':
    app = wx.App()
    frame = Test(parent=None, id=1)
    frame.Show()
    app.MainLoop()
</code>```

```<code># reportWindow.py
import wx
import wx.grid as gridlib

class SimpleGrid(gridlib.Grid):  ##, mixins.GridAutoEditMixin):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)

        # [...Some code...]

class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, 0, "Title", size=(1400, 800))
        self.grid = SimpleGrid(self, log)

        # [...Some code...]

if __name__ == '__main__':
    import sys
    from wx.lib.mixins.inspection import InspectableApp

    app = InspectableApp(False)
    frame = TestFrame(None, sys.stdout)
    frame.Show(True)
    import wx.lib.inspection
    wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()
</code>```

Body:
I have a big doubt because my script is not performing as it should be. So I have a simple main file with a button that opens a blank grid (codes below). The problem with this code is that it opens reportWindow the first time it executes, but if I close the report and I  try to open it again I receive the error :
NameError: name 'TestFrame' is not defined

I've also removed if __name__ == '__main__' from the last lines of reportWindow.py because the script wasn't working with it. I tried if __name__ == 'main' as it's imported from main.py but it didn't work either.

Please, can someone show me how it should have been done the correct way?

Thank you

main.py

import wx

class Test(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id, "Frame aka Window", size=(300, 200))
        panel = wx.Panel(self)
        button = wx.Button(panel, label = "Exit", pos=(80, 80), size = (120,30))
        self.Bind(wx.EVT_BUTTON, self.closebutton, button)

    def closebutton(self,event):
        from reportWindow import SimpleGrid
        SimpleGrid(TestFrame, -1)

if __name__ == '__main__':
    app = wx.App()
    frame = Test(parent=None, id=1)
    frame.Show()
    app.MainLoop()

reportWindow.py

import wx
import wx.grid as gridlib

class SimpleGrid(gridlib.Grid): ##, mixins.GridAutoEditMixin):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)

        #[...Some code...]

class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, 0, "Title", size=(1400,800))
        self.grid = SimpleGrid(self, log)

        #[...Some code...]

#if __name__ == '__main__':
import sys
from wx.lib.mixins.inspection import InspectableApp
app = InspectableApp(False)
frame = TestFrame(None, sys.stdout)
frame.Show(True)
#import wx.lib.inspection
#wx.lib.inspection.InspectionTool().Show()
app.MainLoop()

Body:
Your code has a few of issues.

1) The NameError is occurring because you're not importing TestFrame from reportWindow.

2) Without if __name__ == "__main__" in reportWindow.py your program will create another wx.App and start another MainLoop which will block the first loop from receiving events etc... You should only create 1 App/MainLoop.  It will also create the TestFrame the first time you import reportWindow.

3) It looks like you want SimpleGrid to be a child of TestFrame, but then you try to create it by itself in closebutton.

4) When creating the SimpleGrid you pass the TestFrame class instead of an instance of the TestFrame class.

Here is the modified code

# main.py
import wx, sys

class Test(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Frame aka Window", size=(300, 200))
        panel = wx.Panel(self)
        button = wx.Button(panel, label="Exit", pos=(80, 80), size=(120, 30))
        self.Bind(wx.EVT_BUTTON, self.closebutton, button)

    def closebutton(self, event):
        from reportWindow import TestFrame

        frame = TestFrame(self, sys.stdout)
        frame.Show()

if __name__ == '__main__':
    app = wx.App()
    frame = Test(parent=None, id=1)
    frame.Show()
    app.MainLoop()

# reportWindow.py
import wx
import wx.grid as gridlib

class SimpleGrid(gridlib.Grid):  ##, mixins.GridAutoEditMixin):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)

        # [...Some code...]

class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, 0, "Title", size=(1400, 800))
        self.grid = SimpleGrid(self, log)

        # [...Some code...]

if __name__ == '__main__':
    import sys
    from wx.lib.mixins.inspection import InspectableApp

    app = InspectableApp(False)
    frame = TestFrame(None, sys.stdout)
    frame.Show(True)
    import wx.lib.inspection
    wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()


问:
How to change 'No Privileges' for phpMyAdmin online?

I have a website I uploaded online. It works perfectly fine on XAMPP (localhost), but when online, it seems that functions like INSERTING new users to the DB (to register) do not work online, as well as many other INSERT functions. I gave all privileges on DirectAdmin, but on phpMyAdmin I still get "No Privileges".

Does anybody have a fix? and also, is it the phpMyAdmin blocking me from registering new users, or is the problem something else?

答:
There are a few problems here, the most pressing is the lack of information.

phpMyAdmin runs on a web server, but it looks like you are using XAMPP, which is a pre-rolled solution for users that might not necessarily know how to configure phpMyAdmin in Linux/Mac/Windows, setup their own solution, or want something easy to deploy.  There should be a log file you can grab.

I've never used XAMPP, but I have used phpMyAdmin for decades.  Setting up using the default settings XAMPP is installed to "C:\XAMPP".

If I browse to that file I see a directory called "apache" and inside that "logs".  This file, "error", should contain the error that will help us determine why your server is having issues with permissions.

**

Please send the text from the error file in
  "\apache\logs".

**

This might be a bug with XAMPP, phpMyAdmin, your configuration, or something else.  Paste the errors from the log file and I will be happy to look at them.  I can't solve your problem with the information you have provided, but hopefully this will help point you in the right direction.


问:
Discard some dictionary items in list during random.choice
I want to get random item from a list, also I don't want some items to be consider while random.choice(). Below is my data structure

```<code>x=[
  { 'id': 1, 'version':0.1, 'ready': True  }
  { 'id': 6, 'version':0.2, 'ready': True }
  { 'id': 4, 'version':0.1, 'ready': False }
  { 'id': 35, 'version':0.1, 'ready': False  }
  { 'id': 45, 'version':0.1, 'ready': False  }
  { 'id': 63, 'version':0.1, 'ready': True   }
  { 'id': 34, 'version':0.1, 'ready': True   }
  { 'id': 33, 'version':0.1, 'ready': True   }
]
</code>```

I can get the random item by using random.choice(x). But is there any way, consider 'ready': True attribute of item while random.choice().

Or any SIMPLE trick to achieve this?

NOTE: I want to use python in-built modules to avoid dependencies like numpy, etc.

答:
What you want may be List Comprehension .

First, filter the list to the final form you want l = [e for e in x if e["ready"]]

Second, use random.choice on it, ret = random.choice(l)

Body:
I want to get random item from a list, also I don't want some items to be consider while random.choice(). Below is my data structure

x=[
  { 'id': 1, 'version':0.1, 'ready': True  }
  { 'id': 6, 'version':0.2, 'ready': True }
  { 'id': 4, 'version':0.1, 'ready': False }
  { 'id': 35, 'version':0.1, 'ready': False  }
  { 'id': 45, 'version':0.1, 'ready': False  }
  { 'id': 63, 'version':0.1, 'ready': True   }
  { 'id': 34, 'version':0.1, 'ready': True   }
  { 'id': 33, 'version':0.1, 'ready': True   }
]

I can get the random item by using random.choice(x). But is there any way, consider 'ready': True attribute of item while random.choice().

Or any SIMPLE trick to achieve this?

NOTE: I want to use python in-built modules to avoid dependencies like numpy, etc.


问:
Angularjs minlength validation stop characters counter
I'm facing a weird "bug". I have a form with a textarea with a minlength and a maxlength validation on it.

Also, there is a super simple character left counter:

```<code><textarea ng-trim="false" ng-model="form.text" minlength="20" maxlength="240"></textarea>
<p>{{240 - form.text.length}} left</p>
</code>```

I don't know why my counter start working only after the characters reach the minlength value... While typing the counter stuck to 240. After I reach 20 characters the counter jump to 220... What is going wrong here?

Pen example

答:
This is probably because angular isn't saving the the internal state of the textarea to its form.text variable until you hit the minlength. It should be very easy to validate this by changing that
 tag's inner text from form.text.length to form.text.

If at all possible, I would remove the minlength attribute from your textarea and add that as a validation step later on -- Definitely inform the user somehow with a label on-screen though by keeping track of it.

Body:
I'm facing a weird "bug". I have a form with a textarea with a minlength and a maxlength validation on it.

Also, there is a super simple character left counter:

<textarea ng-trim="false" ng-model="form.text" minlength="20" maxlength="240"></textarea>

{{240 - form.text.length}} left

I don't know why my counter start working only after the characters reach the minlength value... While typing the counter stuck to 240. After I reach 20 characters the counter jump to 220... What is going wrong here?

Pen example

Body:
This is probably because angular isn't saving the the internal state of the textarea to its form.text variable until you hit the minlength. It should be very easy to validate this by changing that <p> tag's inner text from form.text.length to form.text.

If at all possible, I would remove the minlength attribute from your textarea and add that as a validation step later on -- Definitely inform the user somehow with a label on-screen though by keeping track of it.


问:
jquery ui autocomplete with database
I fairly new to JQuery and perhaps trying to achieve something that might be abit harder for a beginner.  However I am trying to create an autocomplete that sends the current value to a PHP script and then returns the necessary values.

Here is my Javascript code

```<code>$("#login_name").autocomplete({
    source: function(request, response) {
 $.ajax({
     url: "http://www.myhost.com/myscript.php",
     dataType: "jsonp",

     success: function(data) {
  alert(data);
  response($.map(data, function(item) {
      return {
   label: item.user_login_name,
   value: item.user_id
      }
  }))
     }
 })
    },
    minLength: 2
});
</code>```

And here is the the last half of "myscript.php"

```<code>while($row = $Database->fetch(MYSQLI_ASSOC))
{
    foreach($row as $column=>$val)
    {
        $results[$i][$column] = $val;
    }
    $i++;
}
print json_encode($results);
</code>```

Which produces the following output

```<code>[{"user_id":"2","user_login_name":"Name1"},{"user_id":"3","user_login_name":"Name2"},{"user_id":"4","user_login_name":"Name3"},{"user_id":"5","user_login_name":"Name4"},{"user_id":"6","user_login_name":"Name5"},{"user_id":"7","user_login_name":"Name6"}]
</code>```

Can anyone tell me where I am going wrong please?  Starting to get quite frustrated.  The input box just turns "white" and no options are shown.  The code does work if I specify an array of values.

UPDATE
I have changed the code to and still having no luck.

```<code>$("#login_name").autocomplete({
    source: "/ajax/login_name.php",
    dataType: "json",
    minLength: 2,
    cache: false,
    select: function(event, ui) {
        alert(ui);
    }
});
</code>```

Using FireFox's Web Developer tool, I am getting an error "b is null".

答:
I had a problem like you too. And now I fix it. The problem is my json that return from my server contain a syntax error.

In http://api.jquery.com/jQuery.getJSON/ tells that if there are some error in JSON, it will fail silently. The JSON must match the JSON standard here http://json.org/ .

For my error is my string in JSON is wrapping in only one quote. But the JSON standard accept only string that wrap in double quotes.

eg. "Hello World" not 'Hello World'

When you fix it you can set the source as string URL. The term will be in "term" query string. And it works!!

ContentLicense: CC BY-SA 2.5

Title: jquery ui autocomplete with database

Body:
I fairly new to JQuery and perhaps trying to achieve something that might be abit harder for a beginner.  However I am trying to create an autocomplete that sends the current value to a PHP script and then returns the necessary values.

Here is my Javascript code

$("#login_name").autocomplete({
    source: function(request, response) {
 $.ajax({
     url: "http://www.myhost.com/myscript.php",
     dataType: "jsonp",

     success: function(data) {
  alert(data);
  response($.map(data, function(item) {
      return {
   label: item.user_login_name,
   value: item.user_id
      }
  }))
     }
 })
    },
    minLength: 2
});

And here is the the last half of "myscript.php"

while($row = $Database->fetch(MYSQLI_ASSOC))
{
    foreach($row as $column=>$val)
    {
        $results[$i][$column] = $val;
    }
    $i++;
}
print json_encode($results);

Which produces the following output

[{"user_id":"2","user_login_name":"Name1"},{"user_id":"3","user_login_name":"Name2"},{"user_id":"4","user_login_name":"Name3"},{"user_id":"5","user_login_name":"Name4"},{"user_id":"6","user_login_name":"Name5"},{"user_id":"7","user_login_name":"Name6"}]

Can anyone tell me where I am going wrong please?  Starting to get quite frustrated.  The input box just turns "white" and no options are shown.  The code does work if I specify an array of values.

UPDATE
I have changed the code to and still having no luck.

$("#login_name").autocomplete({
    source: "/ajax/login_name.php",
    dataType: "json",
    minLength: 2,
    cache: false,
    select: function(event, ui) {
        alert(ui);
    }
});

Using FireFox's Web Developer tool, I am getting an error "b is null".