问:
How to find which radio Button is selected after a div
How can I find which radio button is selected after a precise div?

This is an Example:

```<code><div class="largelines">
    <p class="line">OPTION 1</p>
    <div class="delete">
        <a href="#" title="Delete"></a>
    </div>
    <fieldset>
        <input type="radio" id="option1" name="option1" value="option1"><label for="option1">option1 </label><br>
        <input type="radio" id="option2" name="option2" value="option2"><label for="option2">option2 </label>
    </fieldset>
</div>
</code>```

Here, when I click on the class .delete I would like to check (with jQuery) if one of the radio button below (inside the fieldset) has been selected. Do you have any hints?

Thanks in advance.

答:
This find only checked radio under .largelines scope of clicked .delete element.

$(function () {
  $(document).on('click', '.delete', function () {
    var isChecked = $('input:radio:checked', $(this).parent()).length > 0
    alert(isChecked)
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="largelines">
    <p class="line">OPTION 1</p>
    <div class="delete">
        Check 1
    </div>
    <fieldset>
        <input type="radio" id="option1" name="option1" value="option1"><label for="option1">option1 </label><br>
        <input type="radio" id="option2" name="option2" value="option2"><label for="option2">option2 </label>
    </fieldset>
</div>
<hr>
<div class="largelines">
    <p class="line">OPTION 2</p>
    <div class="delete">
        Check 2
    </div>
    <fieldset>
        <input type="radio" id="option21" name="option1" value="option1"><label for="option1">option1 </label><br>
        <input type="radio" id="option22" name="option2" value="option2"><label for="option2">option2 </label>
    </fieldset>
</div></code>```

Body:
How can I find which radio button is selected after a precise div?

This is an Example:

OPTION 1

    <fieldset>
        <input type="radio" id="option1" name="option1" value="option1">option1

        <input type="radio" id="option2" name="option2" value="option2">option2
    </fieldset>

Here, when I click on the class .delete I would like to check (with jQuery) if one of the radio button below (inside the fieldset) has been selected. Do you have any hints?

Thanks in advance.

Body:
This find only checked radio under .largelines scope of clicked .delete element.

$(function () {
  $(document).on('click', '.delete', function () {
    var isChecked = $('input:radio:checked', $(this).parent()).length > 0
    alert(isChecked)
  })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="largelines">
    <p class="line">OPTION 1</p>
    <div class="delete">
        <a href="#" title="Delete">Check 1</a>
    </div>
    <fieldset>
        <input type="radio" id="option1" name="option1" value="option1"><label for="option1">option1 </label><br>
        <input type="radio" id="option2" name="option2" value="option2"><label for="option2">option2 </label>
    </fieldset>
</div>
<hr>
<div class="largelines">
    <p class="line">OPTION 2</p>
    <div class="delete">
        <a href="#" title="Delete">Check 2</a>
    </div>
    <fieldset>
        <input type="radio" id="option21" name="option1" value="option1"><label for="option1">option1 </label><br>
        <input type="radio" id="option22" name="option2" value="option2"><label for="option2">option2 </label>
    </fieldset>
</div>


来源: stackexchange

问:
How to get files contained in a path
In the following path:

```<code>app/test/vehicle/
</code>```

there are several .js file. Is there any way in Javascript where I can get the number of .js file contains in the above-mentioned path?

I am using webStorm environment

答:
There is no way to access the file system from a web page.

If you are using nodejs, then you can use fs.readdir or fs.readdirSync:

```<code>const fs = require('fs');
const dir = './directory';

fs.readdir(dir, (err, files) => {
   console.log(files.filter(file => file.endsWith(".js")).length);
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get files contained in a path

Body:
In the following path:

app/test/vehicle/

there are several .js file. Is there any way in Javascript where I can get the number of .js file contains in the above-mentioned path?

I am using webStorm environment

Body:
There is no way to access the file system from a web page.

If you are using nodejs, then you can use fs.readdir or fs.readdirSync:

const fs = require('fs');
const dir = './directory';

fs.readdir(dir, (err, files) => {
   console.log(files.filter(file => file.endsWith(".js")).length);
});


问:
Eclipse Plugin Development: How to drag element from Desktop to custom Node in Project Explorer
I am making a drag &  drop Eclipse plugin that can drop elements into custom Nodes in Project Explorer.

So far I am able to drag a file from Project Explorer and drop it into one of my custom Nodes I have added in Project Explorer view.
I have registered dropAssistant in plugin.xml and have added possibleDropTargets.

However I am having trouble dragging an element from Desktop (System Explorer) to my Nodes in Project Explorer. When the mouse cursor is over one of my Nodes the cursor changes to 'X' mark, meaning that I can not drop the element into it.

Here is my navigatorContent in plugin.xml

```<code><plugin>
   <extension
         point="org.eclipse.ui.navigator.navigatorContent">
      <navigatorContent
            activeByDefault="true"
            id="flashimageviewer.navigatorContent"
            name="BinNavigatorContent"
            contentProvider="com.mycompany.flashimageviewer.providers.BinContentProvider"
            labelProvider="com.mycompany.flashimageviewer.providers.BinLabelProvider"  >
         <triggerPoints>
                <and>
                    <adapt type="org.eclipse.core.resources.IResource">
                        <test property="org.eclipse.core.resources.name" value="*.bin" />
                    </adapt>
                    <instanceof value="org.eclipse.core.resources.IFile"/>
                </and>
         </triggerPoints>
         <!--  The possbile childredn are not needen when Drag & Drop inside ProjectExplorer    -->
         <possibleChildren>
            <or>

             <adapt type="com.mycompany.flashimageviewer.model.Node"/>
             <adapt type="org.eclipse.core.resources.IFile"/>
             <adapt type="org.eclipse.core.resources.IResource"/>
            </or>
         </possibleChildren>

         <dropAssistant
              class="com.mycompany.flashimageviewer.MyCommonDropAdapterAssistant"
              id="com.mycompany.flashimageviewer.myCommonDropAdapterAssistant">

            <!--  The possbile targets are not needen when Drag & Drop inside ProjectExplorer    -->
           <possibleDropTargets>
               <or>
                <and>
                    <instanceof value="org.eclipse.core.resources.IFile">
                        <test property="org.eclipse.core.resources.name" value="*.bin" />
                    </instanceof>
                </and>

               <adapt type="com.mycompany.flashimageviewer.model.Node"/>

               <adapt type="org.eclipse.core.resources.IFile"/>
               <adapt type="org.eclipse.core.resources.IResource"/>
           </or>
           </possibleDropTargets>
       </dropAssistant>

       <!--
       <dragAssistant
         class="com.mycompany.flashimageviewer.MyDragListener"
         viewerId="org.eclipse.ui.navigator.ProjectExplorer"/>
           -->
        <!--
         <enablement>
           <or>
            <adapt type="org.eclipse.core.resources.IFile" />
            <adapt type="org.eclipse.core.resources.IFolder" />
                   <adapt type="org.eclipse.core.resources.IProject" />
                     <adapt type="org.eclipse.core.resources.IWorkspaceRoot" />
           </or>
          </enablement>
        -->
      </navigatorContent>
   </extension>
</code>```

And here is my implementation of CommonDropAdapterAssistant:

```<code>public class MyCommonDropAdapterAssistant extends CommonDropAdapterAssistant     {

private static final String VALID_MESSAGE = "This drop is valid";
private static final String INVALID_MESSAGE = "Can not handle this drop";

@Override
public IStatus validateDrop(Object target, int operation, TransferData transferType) {
    IStatus iStatus  = null;
    if(target instanceof Node) {
        iStatus= new Status(IStatus.OK, Util.FLASH_IMAGE_VIEWER_PLUGIN_ID, VALID_MESSAGE );
    }else {
        iStatus = new Status(IStatus.CANCEL, Util.FLASH_IMAGE_VIEWER_PLUGIN_ID,  INVALID_MESSAGE);
    }
    return iStatus;
}

@Override
public IStatus handleDrop(CommonDropAdapter aDropAdapter, DropTargetEvent aDropTargetEvent, Object aTarget) {

    if (aTarget instanceof Node) {
        final Node targetNode = (Node) aTarget;
        performOperation(targetNode, aDropTargetEvent, aTarget);    // <-- This method here does the actual moving of the dragged element
    }

    return null;
}
</code>```

How can I add support for dragging an element from System Explorer to my Node in Project Explorer?

EDIT:  I forgot to mention that when hovering an element which I have dragged from Desktop, my overrided method validateDrop in  MyCommonDropAdapterAssistant is never called.

答:
Your implementation of CommonDropAdapterAssistant needs to override the isSupportedType method, so as to be considered when handling file drops:

```<code>public boolean isSupportedType(TransferData aTransferType)
{
    return super.isSupportedType(aTransferType)
            || FileTransfer.getInstance().isSupportedType(aTransferType);
}
</code>```

Body:
I am making a drag &  drop Eclipse plugin that can drop elements into custom Nodes in Project Explorer.

So far I am able to drag a file from Project Explorer and drop it into one of my custom Nodes I have added in Project Explorer view.
I have registered dropAssistant in plugin.xml and have added possibleDropTargets.

However I am having trouble dragging an element from Desktop (System Explorer) to my Nodes in Project Explorer. When the mouse cursor is over one of my Nodes the cursor changes to 'X' mark, meaning that I can not drop the element into it.

Here is my navigatorContent in plugin.xml

<plugin>
   <extension
         point="org.eclipse.ui.navigator.navigatorContent">
      <navigatorContent
            activeByDefault="true"
            id="flashimageviewer.navigatorContent"
            name="BinNavigatorContent"
            contentProvider="com.mycompany.flashimageviewer.providers.BinContentProvider"
            labelProvider="com.mycompany.flashimageviewer.providers.BinLabelProvider"  >
         <triggerPoints>
                <and>
                    <adapt type="org.eclipse.core.resources.IResource">
                        <test property="org.eclipse.core.resources.name" value="*.bin" />
                    </adapt>
                    <instanceof value="org.eclipse.core.resources.IFile"/>
                </and>
         </triggerPoints>

         <possibleChildren>
            <or>

             <adapt type="com.mycompany.flashimageviewer.model.Node"/>
             <adapt type="org.eclipse.core.resources.IFile"/>
             <adapt type="org.eclipse.core.resources.IResource"/>
            </or>
         </possibleChildren>

         <dropAssistant
              class="com.mycompany.flashimageviewer.MyCommonDropAdapterAssistant"
              id="com.mycompany.flashimageviewer.myCommonDropAdapterAssistant">

           <possibleDropTargets>
               <or>
                <and>
                    <instanceof value="org.eclipse.core.resources.IFile">
                        <test property="org.eclipse.core.resources.name" value="*.bin" />
                    </instanceof>
                </and>

               <adapt type="com.mycompany.flashimageviewer.model.Node"/>

               <adapt type="org.eclipse.core.resources.IFile"/>
               <adapt type="org.eclipse.core.resources.IResource"/>
           </or>
           </possibleDropTargets>
       </dropAssistant>

      </navigatorContent>
   </extension>

And here is my implementation of CommonDropAdapterAssistant:

public class MyCommonDropAdapterAssistant extends CommonDropAdapterAssistant     {

private static final String VALID_MESSAGE = "This drop is valid";
private static final String INVALID_MESSAGE = "Can not handle this drop";

@Override
public IStatus validateDrop(Object target, int operation, TransferData transferType) {
    IStatus iStatus  = null;
    if(target instanceof Node) {
        iStatus= new Status(IStatus.OK, Util.FLASH_IMAGE_VIEWER_PLUGIN_ID, VALID_MESSAGE );
    }else {
        iStatus = new Status(IStatus.CANCEL, Util.FLASH_IMAGE_VIEWER_PLUGIN_ID,  INVALID_MESSAGE);
    }
    return iStatus;
}

@Override
public IStatus handleDrop(CommonDropAdapter aDropAdapter, DropTargetEvent aDropTargetEvent, Object aTarget) {

    if (aTarget instanceof Node) {
        final Node targetNode = (Node) aTarget;
        performOperation(targetNode, aDropTargetEvent, aTarget);    // <-- This method here does the actual moving of the dragged element
    }

    return null;
}

How can I add support for dragging an element from System Explorer to my Node in Project Explorer?

EDIT:  I forgot to mention that when hovering an element which I have dragged from Desktop, my overrided method validateDrop in  MyCommonDropAdapterAssistant is never called.

Body:
Your implementation of CommonDropAdapterAssistant needs to override the isSupportedType method, so as to be considered when handling file drops:

public boolean isSupportedType(TransferData aTransferType)
{
    return super.isSupportedType(aTransferType)
            || FileTransfer.getInstance().isSupportedType(aTransferType);
}


问:
PHP's curl on Apache only opens one connection per server per browser
I'm having a problem with curl in PHP that I can't figure out.  I have a web server (Apache) that talks to a web service over HTTPS on another Apache server.  We'll call them "server A" and "server B".

The problem I'm seeing is that server A only makes one connection at a time using curl to server B per browser that's connected to server A.  I'm not sure if this is a curl or apache problem.  I have seen references in several places to a max connection per server setting of one for a curl client but I can't verify that it exists.

Scenario:

I load up twenty different pages in three different browsers, each in its own tab/window within that browser. I tried Firefox, Chrome, and Konqueror all at the same time.  Firefox had all its per-server connection limits raised significantly through about:config

All of those pages are hosted on server A and loading was started close to simultaneously

Each instance of the page on server A talks to server B using curl

A single call of this type to server B normally takes ~10 seconds

Only one TCP connection from A->B is open at any one time per browser that is connected to server A (3 total from A->B)

I verified that multiple connections from the browsers are opened to server A

AFAICT the requests are all serialized.  I'm able to verify that multiple connections are open from browsers to server A, but only one https connection is open from A->B per browser connected to A.

Server B can handle many connections simultaneously but for some reason server A won't open multiple connections to server B.  I have tried sending "Connection: close" from both servers A and B to see if that would help.  It did not.

I have found lots of people talking about making multiple asynchronous connections per script but what I want to do is open multiple connections across different page instances to one external server.

Any ideas on what the problem is or how to fix it?

答: Native php sessions(files handler) use an exclusive locking model - only a single process/thread can work with the data for a specific session id at a time. When session_start() is called, execution will block until the process can acquire a lock on the session file. The lock is released when session_write_close() is called, which php automatically calls upon script termination. You can call it manually to release the lock and commit your changes. If desired, you can session_start() and session_write_close() multiple times per script execution.</p>

ContentLicense: CC BY-SA 2.5


问:
Django: Why does this test fail?
I an new to Django and to Test Driven Devolopment as well.

After working through the tutorials in the 1.11 official documentation
I am starting my first app:  wos_2017_2

This test fails and I cannot figure out why:

```<code>import unittest
from django.test import TestCase
from django.test import Client
from .models import *
from .views import *
class SimpleTest(unittest.TestCase):
    def test_index(self):
        client = Client()
        response = client.get('/')
        self.assertEqual(response.status_code, 200)

FAIL: test_index (wos_2017_2.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/js/django/wos/wos_2017_2/tests.py", line 16, in test_index
    self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200
</code>```

This link in the browser works without a problem:

```<code>http://localhost:8000/wos_2017_2/
</code>```

In the shell (run from the project root):

```<code>>>> from django.test import Client
>>> client = Client()
>>> response = client.get('/')
>>> response = client.get('wos_2017_2/index')
Not Found: /wos_2017_2index
>>> response = client.get('wos_2017_2/')
Not Found: /wos_2017_2
>>> response = client.get('/wos_2017_2/')
>>> response = client.get('/wos_2017_2/index/')
Not Found: /wos_2017_2/index/
>>> response = client.get('/wos_2017_2/')
>>> response.status_code
200
</code>```

in wos_2017_1.urls.py:

```<code>from . import views
from django.conf.urls import url
urlpatterns = [
    url(r'^$', views.index, name='index'),
]
</code>```

答:
client.get('/') is failing because you haven't defined a URL pattern for ^$ in your root url config (the one in the same directory as your settings.py).

You have included your urls with:

```<code>url(r'^wos_2017_2/', include('wos_2017_2.urls')),
</code>```

and in that urls you have

```<code>url(r'^$', views.index, name='index'),
</code>```

Therefore in your test you should use response = client.get('/wos_2017_2/')

Title: Django: Why does this test fail?

Body:
I an new to Django and to Test Driven Devolopment as well.

After working through the tutorials in the 1.11 official documentation
I am starting my first app:  wos_2017_2

This test fails and I cannot figure out why:

import unittest
from django.test import TestCase
from django.test import Client
from .models import *
from .views import *
class SimpleTest(unittest.TestCase):
    def test_index(self):
        client = Client()
        response = client.get('/')
        self.assertEqual(response.status_code, 200)

FAIL: test_index (wos_2017_2.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/js/django/wos/wos_2017_2/tests.py", line 16, in test_index
    self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200

This link in the browser works without a problem:

http://localhost:8000/wos_2017_2/

In the shell (run from the project root):

>>> from django.test import Client
>>> client = Client()
>>> response = client.get('/')
>>> response = client.get('wos_2017_2/index')
Not Found: /wos_2017_2index
>>> response = client.get('wos_2017_2/')
Not Found: /wos_2017_2
>>> response = client.get('/wos_2017_2/')
>>> response = client.get('/wos_2017_2/index/')
Not Found: /wos_2017_2/index/
>>> response = client.get('/wos_2017_2/')
>>> response.status_code
200

in wos_2017_1.urls.py:

from . import views
from django.conf.urls import url
urlpatterns = [
    url(r'^$', views.index, name='index'),
]

Body:
client.get('/') is failing because you haven't defined a URL pattern for ^$ in your root url config (the one in the same directory as your settings.py).

You have included your urls with:

url(r'^wos_2017_2/', include('wos_2017_2.urls')),

and in that urls you have

url(r'^$', views.index, name='index'),

Therefore in your test you should use response = client.get('/wos_2017_2/')


问:
Exporting table to CSV via php button
I am really new to php and everything I have learned is from my school textbook and online research. With that said I am trying to complete an assignment and I am stuck on the last part. for the final part the assignment says to "Create a PHP script that will dump the contents of the employee table into CSV text file that has comma separated values for each record. Each new record should begin on a new line". I have tried many online tutorials but none of them teach how to put this event in a button. I am including my code so you can see the mess I have. It's not to bad but I am sure I can do the same task with much less code. Again I am just starting out and this is the best I can do for now. Could anyone give any suggestions on how this could be done. I have my button on line 140. I also used a db_connect() function so i don't have to write it many times. I can peon use this to read the database before I save as a csv.

Any suggestions would be greatly appreciated. Be warned It's a lot of code to follow.

```<code>    <h2>Employee Search</h2>
    <form action="Draft.php" name="dbToCSV" method="GET">
        <input type="submit" name="dbToCSV" value="Export Database to CSV" <?php if     (isset($_GET['dbToCSV']))
                    {
                        //Do this code
                    }
                    else
                    {
                        echo "Error!";
                    } ?>><br />

    </form>
    <form action="Draft.php" method="GET">
        By name: <input type="text" name="searchName">
        <input type="submit" value="Search Name"><br />
    </form>
    <form action="Draft.php" method="GET">
        By language: <input type="text" name="searchLang">
        <input type="submit" value="Search Language"><br />
    </form>
</code>```

答:
Following is PHP script which I am using. </p>

```<code><?php

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$table_name = "employees";

$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$table_name.'.csv"');
header('Pragma: no-cache');
header('Expires: 0');

$result = mysql_query("SELECT * FROM $table_name");
if (!$result) die("Couldn't fetch records");
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
    $headers[] = mysql_field_name($result , $i);
}

if ($fp && $result) {
    fputcsv($fp, $headers);
    while ($row = mysql_fetch_assoc($result)) {
        fputcsv($fp, $row);
    }
}

exit;
?>
</code>```

Title: Exporting table to CSV via php button

Body:
I am really new to php and everything I have learned is from my school textbook and online research. With that said I am trying to complete an assignment and I am stuck on the last part. for the final part the assignment says to "Create a PHP script that will dump the contents of the employee table into CSV text file that has comma separated values for each record. Each new record should begin on a new line". I have tried many online tutorials but none of them teach how to put this event in a button. I am including my code so you can see the mess I have. It's not to bad but I am sure I can do the same task with much less code. Again I am just starting out and this is the best I can do for now. Could anyone give any suggestions on how this could be done. I have my button on line 140. I also used a db_connect() function so i don't have to write it many times. I can peon use this to read the database before I save as a csv.

Any suggestions would be greatly appreciated. Be warned It's a lot of code to follow.

Employee Search

    <form action="Draft.php" name="dbToCSV" method="GET">
        <input type="submit" name="dbToCSV" value="Export Database to CSV" <?php if     (isset($_GET['dbToCSV']))
                    {
                        //Do this code
                    }
                    else
                    {
                        echo "Error!";
                    } ?>>

    </form>
    <form action="Draft.php" method="GET">
        By name: <input type="text" name="searchName">
        <input type="submit" value="Search Name">

    </form>
    <form action="Draft.php" method="GET">
        By language: <input type="text" name="searchLang">
        <input type="submit" value="Search Language">

    </form>

Body:
Following is PHP script which I am using.

<?php

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$table_name = "employees";

$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$table_name.'.csv"');
header('Pragma: no-cache');
header('Expires: 0');

$result = mysql_query("SELECT * FROM $table_name");
if (!$result) die("Couldn't fetch records");
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
    $headers[] = mysql_field_name($result , $i);
}

if ($fp && $result) {
    fputcsv($fp, $headers);
    while ($row = mysql_fetch_assoc($result)) {
        fputcsv($fp, $row);
    }
}

exit;
?>


问:
How can I define types for external libraries. TypeScript , Angular and Google Picker
I'm trying to use the Google Picker API in my Angular 4 app.
To be able to use the features of Google Picker I have to import the library, and I do that in my index.html file.

index.html:

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="theme-color" content="#2185d0">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <title>Librostic</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script src="https://use.fontawesome.com/18845e1b3c.js"></script>

  <link href="https://fonts.googleapis.com/css?family=Alfa+Slab+One" rel="stylesheet">
</head>
<body>
  <app-root>
  </app-root>
  <!-- See the bellow script -->
  <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>

<script>
  $('.ui.dropdown')
    .dropdown()
  ;
</script>
</html>
</code>```

So the problem is where I try to use some methods because Typescript doesn't know what that is.
Let's see that in an example.
I got the following function:

```<code>function createPicker() {
      if (pickerApiLoaded && oauthToken) {
        // Here I get errors like: Cannot find name 'google'.
        var view = new google.picker.View(google.picker.ViewId.DOCS);
        view.setMimeTypes('application/pdf');
        var picker = new google.picker.PickerBuilder()
          .enableFeature(google.picker.Feature.NAV_HIDDEN)
          .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
          .setAppId(appId)
          .setOAuthToken(oauthToken)
          .addView(view)
          .addView(new google.picker.DocsUploadView())
          .setDeveloperKey(developerKey)
          .setCallback(pickerCallback)
          .build();
        picker.setVisible(true);
      }
    }
</code>```

This is just a TypeScript error meaning that the function is excecuted without a TS compiler. How can I solve this problem?
Thanks!

答:
Augmenting CRice's answer,

you're looking for     npm install @types/google.picker  @types/gapi.client --save-dev

Body:
I'm trying to use the Google Picker API in my Angular 4 app.
To be able to use the features of Google Picker I have to import the library, and I do that in my index.html file.

index.html:

<!doctype html>

  <meta charset="utf-8">
  <meta name="theme-color" content="#2185d0">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <title>Librostic</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link href="https://fonts.googleapis.com/css?family=Alfa+Slab+One" rel="stylesheet">

  <app-root>
  </app-root>

So the problem is where I try to use some methods because Typescript doesn't know what that is.
Let's see that in an example.
I got the following function:

function createPicker() {
      if (pickerApiLoaded && oauthToken) {
        // Here I get errors like: Cannot find name 'google'.
        var view = new google.picker.View(google.picker.ViewId.DOCS);
        view.setMimeTypes('application/pdf');
        var picker = new google.picker.PickerBuilder()
          .enableFeature(google.picker.Feature.NAV_HIDDEN)
          .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
          .setAppId(appId)
          .setOAuthToken(oauthToken)
          .addView(view)
          .addView(new google.picker.DocsUploadView())
          .setDeveloperKey(developerKey)
          .setCallback(pickerCallback)
          .build();
        picker.setVisible(true);
      }
    }

This is just a TypeScript error meaning that the function is excecuted without a TS compiler. How can I solve this problem?
Thanks!


问:
ASP.NET Core 2 all users password reset as admin
I'm looking for a possibility to reset the password for all users in a database. Is it anyhow possible? All I have found so far, was about enabling password reset for the user himself, but it's not that I need.

I need to force old user to recreate a password for our app. Maybe there are some better solutions?

答:
If you are trying to reset the password to something specific for all users, then you'd need to update the asnetUsers table with a hashed password and password salt for the new password.

From experience, the easiest way to do do this is the change the password using the app for a specific user, grab the PasswordHash and PasswordSalt from that changed user, and then run a SQL UPDATE on all other users with the same combination.

It's not exactly secure, but it will do the job.

More or less:

```<code>-- Update User using App, and get the ID
DECLARE @Id INT = XX -- Your app userid here
DECLARE @PasswordHash NVARCHAR(MAX), @PasswordSalt NVARCHAR(MAX)

-- get the password hash and salt for the changed user
SELECT @PasswordHash = PasswordHash, @PasswordSalt = PasswordSalt
FROM aspnetUsers
WHERE Id = @Id

-- Update the other users with the same password and salt
UPDATE aspnetUsers SET
    PasswordHash = @PasswordHash,
    PasswordSalt = @PasswordSalt
WHERE
    Id IN (---whatever you need to filter by)
</code>```

Body:
If you are trying to reset the password to something specific for all users, then you'd need to update the asnetUsers table with a hashed password and password salt for the new password.

From experience, the easiest way to do do this is the change the password using the app for a specific user, grab the PasswordHash and PasswordSalt from that changed user, and then run a SQL UPDATE on all other users with the same combination.

It's not exactly secure, but it will do the job.

More or less:

-- Update User using App, and get the ID
DECLARE @Id INT = XX -- Your app userid here
DECLARE @PasswordHash NVARCHAR(MAX), @PasswordSalt NVARCHAR(MAX)

-- get the password hash and salt for the changed user
SELECT @PasswordHash = PasswordHash, @PasswordSalt = PasswordSalt
FROM aspnetUsers
WHERE Id = @Id

-- Update the other users with the same password and salt
UPDATE aspnetUsers SET
    PasswordHash = @PasswordHash,
    PasswordSalt = @PasswordSalt
WHERE
    Id IN (---whatever you need to filter by)


问:
Log into my app using WSO2IS login page
I'm working with WSO2 Identity Server 5.3.0 (it's installed on a VM in a server).

So, I would access to my application using WSO2IS login page.
I've already set the Service Provider by Management Console.
I've not set the IdP because I've thought that must be the Resident one.
It's enought like thta? Should I modify some files?
I cannot find the related page on the Documentation.
Hope to be clear.

After doing all, the /authenticationendpoint/login.do doesn't returns the possibility to introduce username and password.

Edit:
@Bee I add here the screenshot

and this is my url:

http://myurl:9763/authenticationendpoint/login.do?response_type=code&scope=openid&client_id=my_clientID&redirect_uri=/myuri/

答:
Here you have multiple options. You can use either basic auth, OpenID Connect, SAML SSO, Federated authentication etc to authenticate to your app. Some useful links are below.

https://docs.wso2.com/display/IS530/Authentication
https://docs.wso2.com/display/IS530/Basic+Client+Profile+with+Playground
https://docs.wso2.com/display/IS530/Writing+a+Web+Service+Client+for+Authentication+and+User+Admin+Services
https://docs.wso2.com/display/IS530/Authenticators+and+Provisioning+Connectors

Title: Log into my app using WSO2IS login page


问:
When I try to install body parser with npm, I get npm does not support Node.js v9.2.0
Console error:</p>

```<code>npm WARN npm npm does not support Node.js v9.2.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8.
npm WARN npm You can find the latest version at https://nodejs.org/
WARNING: You are likely using a version of node-tar or npm that is incompatible with this version of Node.js.
Please use either the version of npm that is bundled with Node.js, or a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) that is compatible with Node.js 9 and above.
C:\Program Files\nodejs\node.exe: src\node_zlib.cc:437: Assertion `args.Length() == 7 && "init(windowBits, level, memLevel, strategy, writeResult, writeCallback," " dictionary)"' failed.
</code>```

答:
The Version of npm you're using and the version of Node.js you're using are not paired together and the version of npm you've doesn't support it.

So what you can do, is either uninstall and reinstall node with npm or update npm like this:

```<code>npm i -g npm
</code>```

this will update npm to the latest version :)

Body:
Console error:

npm WARN npm npm does not support Node.js v9.2.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8.
npm WARN npm You can find the latest version at https://nodejs.org/
WARNING: You are likely using a version of node-tar or npm that is incompatible with this version of Node.js.
Please use either the version of npm that is bundled with Node.js, or a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) that is compatible with Node.js 9 and above.
C:\Program Files\nodejs\node.exe: src\node_zlib.cc:437: Assertion `args.Length() == 7 && "init(windowBits, level, memLevel, strategy, writeResult, writeCallback," " dictionary)"' failed.

Body:
The Version of npm you're using and the version of Node.js you're using are not paired together and the version of npm you've doesn't support it.

So what you can do, is either uninstall and reinstall node with npm or update npm like this:

npm i -g npm

this will update npm to the latest version :)


问:
static files and django templates
I want to put all my link tags in .

However, I don't know how to render all the link tags in the head of my DOM when I include shared templates via the built in include tag.  So my link tags are rendered wherever I happen to include my shared templates.  I've added code below to better illustrate my problem.

Layout:

```<code><html>
<head>
    {% block references %}{% endblock %}
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
</code>```

Extending the layout with a template:

```<code>{% extends "layout.html" %}
{% load staticfiles %}
{% block references %}
    <link rel="stylesheet" href="{% static "myStylesheet.css" %}" type="text/css">
{% endblock %}
...
{% include "mySharedTemplate.html" %}
...
</code>```

Shared template.  Note, this template is shared among a few but not all of my templates:

```<code>{% load staticfiles %}
<link rel="stylesheet" href="{% static "mySharedTemplateStylesheet.css" %}" type="text/css">
...
</code>```

Is there a way to put all my link tags in the head of my DOM while using shared templates?  Is there a completely different or better way to do this?  I'm a week into my first django project, so even suggestions of basic features may help me!

答:
Use verbatim tag to stop template engine to interpret your tags to be his tags.

```<code>{% verbatim %}
    {{if dying}}Still alive.{{/if}}
{% endverbatim %}
</code>```

Django and Chartjs template conflict

Title: static files and django templates

Body:
I want to put all my link tags in .

However, I don't know how to render all the link tags in the head of my DOM when I include shared templates via the built in include tag.  So my link tags are rendered wherever I happen to include my shared templates.  I've added code below to better illustrate my problem.

Layout:

    {% block references %}{% endblock %}

    {% block content %}{% endblock %}

Extending the layout with a template:

{% extends "layout.html" %}
{% load staticfiles %}
{% block references %}
    <link rel="stylesheet" href="{% static "myStylesheet.css" %}" type="text/css">
{% endblock %}
...
{% include "mySharedTemplate.html" %}
...

Shared template.  Note, this template is shared among a few but not all of my templates:

{% load staticfiles %}
<link rel="stylesheet" href="{% static "mySharedTemplateStylesheet.css" %}" type="text/css">
...

Is there a way to put all my link tags in the head of my DOM while using shared templates?  Is there a completely different or better way to do this?  I'm a week into my first django project, so even suggestions of basic features may help me!

Body:
Use verbatim tag to stop template engine to interpret your tags to be his tags.

{% verbatim %}
    {{if dying}}Still alive.{{/if}}
{% endverbatim %}

Django and Chartjs template conflict


问:
How to log 3rd party output in RapidMiner extension?
I am trying to write a data source for RapidMiner that wraps an API connector library which my company develops for years.

The code is fine, but it fails to instantiate some classes. I am looking for the cause, but RapidMiner seems to suppress the 3rd party lib logging output.

Our library uses Log4J and for investigation I added a hack:

```<code>Logger.getRootLogger().setLevel(Level.DEBUG);
// the appender writes the Log4J output to the JUL logger of RapidMiner
Logger.getRootLogger().addAppender(new AppenderSkeleton() {

  @Override
  public boolean requiresLayout() {
    return false;
  }

  @Override
  public void close() {}

  @Override
  protected void append(final LoggingEvent event) {
    getLogger().info(event.getRenderedMessage());
  }
});
</code>```

As a result it writes at least the WARN messages to the RapidMiner log.

Then I found this article stating that some operations are not permitted. That would be a possible source of my issues.

So my questions:

How can I achieve that RapidMiner logs all the 3rd party lib output?

Why does RapidMiner not log the security violations? That would help a lot for investigation.

Is there any chance to bypass all the security restrictions of RapidMiner at least for development?

答: I would repost to the RapidMiner community (go to Developer forum) as the developers monitor that channel regularly.</p>

Body:
I am trying to write a data source for RapidMiner that wraps an API connector library which my company develops for years.

The code is fine, but it fails to instantiate some classes. I am looking for the cause, but RapidMiner seems to suppress the 3rd party lib logging output.

Our library uses Log4J and for investigation I added a hack:

Logger.getRootLogger().setLevel(Level.DEBUG);
// the appender writes the Log4J output to the JUL logger of RapidMiner
Logger.getRootLogger().addAppender(new AppenderSkeleton() {

  @Override
  public boolean requiresLayout() {
    return false;
  }

  @Override
  public void close() {}

  @Override
  protected void append(final LoggingEvent event) {
    getLogger().info(event.getRenderedMessage());
  }
});

As a result it writes at least the WARN messages to the RapidMiner log.

Then I found this article stating that some operations are not permitted. That would be a possible source of my issues.

So my questions:

How can I achieve that RapidMiner logs all the 3rd party lib output?

Why does RapidMiner not log the security violations? That would help a lot for investigation.

Is there any chance to bypass all the security restrictions of RapidMiner at least for development?


问:
Data type size impact on performance
I'm running intensive numerical simulations. I often use long integers, but I realized it would be safe to use integers instead. Would this improve the speed of my simulations significantly?</p>

答: Depends on your data set sizes. Obviously, halving the size of your integers could double the amount of data that fits into CPU caches and thus access to data would be faster. For more details I suggest you read the famous Ulrich Drepper's paper What Every Programmer Should Know About Memory.</p>

Title: Data type size impact on performance


问:
Python Class Attribute Use
I would like to print(use) some attributes of an object instance in the following way. But the code generates an error:
AttributeError: 'Obj' object has no attribute 'alphabet'</p>

```<code>class Obj(object):
    def __init__(self):
        self.a = 0
        self.b = 1

Obj_instance = Obj()

l = ['a', 'b']

for alphabet in l:
    print Obj_instance.alphabet
</code>```

答:
As @fredtantini said use getattr. Here's an example - </p>

```<code>class Obj(object):
def __init__(self):
    self.a = 0
    self.b = 1

Obj_instance = Obj()

l = ['a', 'b']

for alphabet in l:
    print getattr(Obj_instance, alphabet)
</code>```

Title: Python Class Attribute Use

Body:
I would like to print(use) some attributes of an object instance in the following way. But the code generates an error:
AttributeError: 'Obj' object has no attribute 'alphabet'

class Obj(object):
    def __init__(self):
        self.a = 0
        self.b = 1

Obj_instance = Obj()

l = ['a', 'b']

for alphabet in l:
    print Obj_instance.alphabet

Body:
As @fredtantini said use getattr. Here's an example -

class Obj(object):
def __init__(self):
    self.a = 0
    self.b = 1

Obj_instance = Obj()

l = ['a', 'b']

for alphabet in l:
    print getattr(Obj_instance, alphabet)


问:
Putting text on a border with css html
How can i hide border behind MON and give some space like in this pic

https://www.screencast.com/t/SJmg63NZuF

div {
  height: 100px;
  width: 100px;
  border: 2px solid black;
}

h2 {
  width: 50px;
  margin-top: -15px;
  margin-left: 0px;
  padding: 0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h2>MON</h2>
  <p>7am - yeah</p>
</div></code>```

答:
Looks like you just need to set the background color from transparent.

div {
  height: 100px;
  width: 100px;
  border: 2px solid black;
  background: white;
}

h2 {
  width: 50px;
  margin-top: -15px;
  margin-left: 8px;
  padding: 0 14px 0 10px;
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h2>MON</h2>
  <p>7am - yeah</p>
</div></code>```

Title: Putting text on a border with css html

Body:
How can i hide border behind MON and give some space like in this pic

https://www.screencast.com/t/SJmg63NZuF

div {
  height: 100px;
  width: 100px;
  border: 2px solid black;
}

h2 {
  width: 50px;
  margin-top: -15px;
  margin-left: 0px;
  padding: 0 10px;
}

MON

7am - yeah

Body:
Looks like you just need to set the background color from transparent.

div {
  height: 100px;
  width: 100px;
  border: 2px solid black;
  background: white;
}

h2 {
  width: 50px;
  margin-top: -15px;
  margin-left: 8px;
  padding: 0 14px 0 10px;
  background: white;
}

<div>
  <h2>MON</h2>
  <p>7am - yeah</p>
</div>


问:
Aggregate event log to weekly overview
Suppose I have the following table:

```<code>Table A: Event Log

ID        Step        WeekArrived        WeekCompleted
-------------------------------------------------------
1         A           1                  1
1         B           1                  3
2         B           3                  3
</code>```

So in week 1, case 1 arrives. For this case, step A is completed in week 1, but step B is not. Step B is completed in week 3. Case 2 also arrives in week 3, and step B is completed in the same week (Step A wasn't needed for this case).

I would like to aggregate this event log into a weekly per step overview like this:

```<code>Table B: Weekly Overview

Week      Step        In                 Backlog               Out
------------------------------------------------------------------
1         A           1                  0                     1
1         B           1                  1                     0
2         A           0                  0                     0
2         B           0                  1                     0
3         A           0                  0                     0
3         B           1                  0                     2
</code>```

For each week X and step Y, this table shows:

In: the number of cases that started step Y in week X

Backlog: the number of cases which arrived at step Y in week <= X, and are not yet completed at the end of week X.

Out: the number of cases that completed step Y in week X

How can I get from table A to table B?

答:
You need a list of weeks so you can evaluate if there is data on that week.

in sql server for example something like this How to generate a range of numbers between two numbers?

Then you join with your steps. Will work better if you have a separated table for steps too.

```<code>SELECT weeks.week_id, steps.step,
       CASE WHEN s_in.WeekArrived IS NULL THEN 0 ELSE 1 END as step_in,
       CASE WHEN s_completed.WeekCompleted IS NULL THEN 0 ELSE 1 END as step_out,
       CASE WHEN s_pending.WeekArrived IS NULL THEN 0 ELSE 1 END as step_pending
FROM weeks
CROSS JOIN (SELECT DISTINCT step
            FROM event_log) as steps

LEFT JOIN event_Log as s_in
  ON weeeks.week_id = e.WeekArrived
 AND steps.step = e.step

LEFT JOIN event_Log as s_completed
  ON weeeks.week_id = e.WeekCompleted
 AND steps.step = e.step

LEFT JOIN event_Log as s_pending
  ON weeeks.week_id > e.WeekArrived
 AND weeeks.week_id < e.WeekCompleted
 AND steps.step = e.step
</code>```

NOTE: Dont know what back log is.

Title: Aggregate event log to weekly overview

Body:
Suppose I have the following table:

Table A: Event Log

ID        Step        WeekArrived        WeekCompleted
-------------------------------------------------------
1         A           1                  1
1         B           1                  3
2         B           3                  3

So in week 1, case 1 arrives. For this case, step A is completed in week 1, but step B is not. Step B is completed in week 3. Case 2 also arrives in week 3, and step B is completed in the same week (Step A wasn't needed for this case).

I would like to aggregate this event log into a weekly per step overview like this:

Table B: Weekly Overview

Week      Step        In                 Backlog               Out
------------------------------------------------------------------
1         A           1                  0                     1
1         B           1                  1                     0
2         A           0                  0                     0
2         B           0                  1                     0
3         A           0                  0                     0
3         B           1                  0                     2

For each week X and step Y, this table shows:

In: the number of cases that started step Y in week X

Backlog: the number of cases which arrived at step Y in week <= X, and are not yet completed at the end of week X.

Out: the number of cases that completed step Y in week X

How can I get from table A to table B?

Body:
You need a list of weeks so you can evaluate if there is data on that week.

in sql server for example something like this How to generate a range of numbers between two numbers?

Then you join with your steps. Will work better if you have a separated table for steps too.

SELECT weeks.week_id, steps.step,
       CASE WHEN s_in.WeekArrived IS NULL THEN 0 ELSE 1 END as step_in,
       CASE WHEN s_completed.WeekCompleted IS NULL THEN 0 ELSE 1 END as step_out,
       CASE WHEN s_pending.WeekArrived IS NULL THEN 0 ELSE 1 END as step_pending
FROM weeks
CROSS JOIN (SELECT DISTINCT step
            FROM event_log) as steps

LEFT JOIN event_Log as s_in
  ON weeeks.week_id = e.WeekArrived
 AND steps.step = e.step

LEFT JOIN event_Log as s_completed
  ON weeeks.week_id = e.WeekCompleted
 AND steps.step = e.step

LEFT JOIN event_Log as s_pending
  ON weeeks.week_id > e.WeekArrived
 AND weeeks.week_id < e.WeekCompleted
 AND steps.step = e.step

NOTE: Dont know what back log is.


问:
Common Lisp: Optimizing functions in SBCL
For 2D graphics I need to optimize my functions, but in SBCL I get lots of comments about SBCL not being able to inline arithmetic operations. I tried all sorts of declarations but it doesn't seem to make the compiler happy. Here is a simple example:

```<code>(defun test-floor (x div)
  (declare (type single-float x)
           (type (signed-byte 64) div)
           (optimize (speed 3)))
  (floor x div))
</code>```

gives the following 4 notes below. I'm completely lost as #'floor is a builtin function. I tried to find information/tutorials on how to properly give the compiler hints in SBCL and didn't find the right information, so any info would be very appreciated! Unfortunately optimization in Common Lisp is quite unknown territory for me. I'm using SBCL 1.3.20 on a Linux machine.

```<code>; file: /tmp/file595dqU
; in: defun test-floor
;     (FLOOR CL-FLOCKS::X CL-FLOCKS::DIV)
; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL TRUNCATE LET*
; ==>
;   (SB-KERNEL:%UNARY-TRUNCATE/SINGLE-FLOAT (/ SB-C::X SB-C::F))
;
; note: forced to do full call
;       unable to do inline float truncate (cost 5) because:
;       The result is a (values integer &optional), not a (values
;                                                          (signed-byte 64) &rest
;                                                          t).

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL TRUNCATE LET* VALUES - *
; ==>
;   (SB-KERNEL:%SINGLE-FLOAT SB-C::RES)
;
; note: forced to do full call
;       unable to do inline float coercion (cost 5) because:
;       The first argument is a integer, not a (signed-byte 64).

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL FUNCTION IF VALUES 1-
; ==>
;   (- SB-C::TRU 1)
;
; note: forced to do generic-- (cost 10)
;       unable to do inline fixnum arithmetic (cost 1) because:
;       The first argument is a integer, not a fixnum.
;       The result is a (values integer &optional), not a (values fixnum &rest t).
;       unable to do inline fixnum arithmetic (cost 2) because:
;       The first argument is a integer, not a fixnum.
;       The result is a (values integer &optional), not a (values fixnum &rest t).
;       etc.

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL FUNCTION IF VALUES
; ==>
;   (+ REM SB-C::DIVISOR)
;
; note: doing signed word to integer coercion (cost 20) from div, for:
;       the second argument of generic-+
;
; compilation unit finished
;   printed 4 notes

CL-USER>
</code>```

答:
SBCL is claiming that it can’t optimise the call to floor because it isn’t sure the return value will be small enough to fit into a 64-bit integer.

```<code>CL-USER> (test-floor 1f25 1234)
8103727629894569426944 ;
0.0
CL-USER> (format nil “~b” *)
;; a long binary string
CL-USER> (length *)
73
</code>```

A 73 bit Integer may be returned but does not fit into 64 bits.

Se also the SBCL manual:

4 Compiler

4.1.3 Understanding Compiler Diagnostics

6 Efficiency

Edit: after some searching I have found the transformation for floor. It is here. I reproduce it below:

```<code>(deftransform floor ((number divisor))
  `(multiple-value-bind (tru rem) (truncate number divisor)
     (if (and (not (zerop rem))
              (if (minusp divisor)
                  (plusp number)
                  (minusp number)))
         (values (1- tru) (+ rem divisor))
         (values tru rem))))
</code>```

So that explains what the compiler messages were talking about

Body:
For 2D graphics I need to optimize my functions, but in SBCL I get lots of comments about SBCL not being able to inline arithmetic operations. I tried all sorts of declarations but it doesn't seem to make the compiler happy. Here is a simple example:

(defun test-floor (x div)
  (declare (type single-float x)
           (type (signed-byte 64) div)
           (optimize (speed 3)))
  (floor x div))

gives the following 4 notes below. I'm completely lost as #'floor is a builtin function. I tried to find information/tutorials on how to properly give the compiler hints in SBCL and didn't find the right information, so any info would be very appreciated! Unfortunately optimization in Common Lisp is quite unknown territory for me. I'm using SBCL 1.3.20 on a Linux machine.

; file: /tmp/file595dqU
; in: defun test-floor
;     (FLOOR CL-FLOCKS::X CL-FLOCKS::DIV)
; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL TRUNCATE LET*
; ==>
;   (SB-KERNEL:%UNARY-TRUNCATE/SINGLE-FLOAT (/ SB-C::X SB-C::F))
;
; note: forced to do full call
;       unable to do inline float truncate (cost 5) because:
;       The result is a (values integer &optional), not a (values
;                                                          (signed-byte 64) &rest
;                                                          t).

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL TRUNCATE LET* VALUES - *
; ==>
;   (SB-KERNEL:%SINGLE-FLOAT SB-C::RES)
;
; note: forced to do full call
;       unable to do inline float coercion (cost 5) because:
;       The first argument is a integer, not a (signed-byte 64).

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL FUNCTION IF VALUES 1-
; ==>
;   (- SB-C::TRU 1)
;
; note: forced to do generic-- (cost 10)
;       unable to do inline fixnum arithmetic (cost 1) because:
;       The first argument is a integer, not a fixnum.
;       The result is a (values integer &optional), not a (values fixnum &rest t).
;       unable to do inline fixnum arithmetic (cost 2) because:
;       The first argument is a integer, not a fixnum.
;       The result is a (values integer &optional), not a (values fixnum &rest t).
;       etc.

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL FUNCTION IF VALUES
; ==>
;   (+ REM SB-C::DIVISOR)
;
; note: doing signed word to integer coercion (cost 20) from div, for:
;       the second argument of generic-+
;
; compilation unit finished
;   printed 4 notes

CL-USER>

Body:
SBCL is claiming that it can’t optimise the call to floor because it isn’t sure the return value will be small enough to fit into a 64-bit integer.

CL-USER> (test-floor 1f25 1234)
8103727629894569426944 ;
0.0
CL-USER> (format nil “~b” *)
;; a long binary string
CL-USER> (length *)
73

A 73 bit Integer may be returned but does not fit into 64 bits.

Se also the SBCL manual:

4 Compiler

4.1.3 Understanding Compiler Diagnostics

6 Efficiency

Edit: after some searching I have found the transformation for floor. It is here. I reproduce it below:

(deftransform floor ((number divisor))
  `(multiple-value-bind (tru rem) (truncate number divisor)
     (if (and (not (zerop rem))
              (if (minusp divisor)
                  (plusp number)
                  (minusp number)))
         (values (1- tru) (+ rem divisor))
         (values tru rem))))

So that explains what the compiler messages were talking about


问:
Are immutable objects good practice?
Should I make my classes immutable where possible?

I once read the book "Effective Java" by Joshua Bloch and he recommended to make all business objects immutable for various reasons. (for example thread safety)
Does this apply for C# too?

Do you try to make your objects immutable, so you have less problems when working with them?
Or is it not worth the inconvenience you have to create them?

答: Immutable objects are the central feature of functional programming; it has its own advantages and disadvantages. (E.g. linked lists are practically impossible to be immutable, but immutable objects make parallelism a piece of cake.) So as a comment on your post noted, the answer is "it depends".</p>

Title: Are immutable objects good practice?


问:
jackson deserialize string to a parameterized map
I have a json string in the following structure:

```<code>{
    "1": { ... },
    "2": { ... },
    "3": { ... }
}
</code>```

where 1, 2 and 3 are identifiers.

I want to deserialize this string and cast it to the following type - Map<Integer, List<MyCustomPojo>>

The thing is that each value { ... } has its own structure, but I need to parse them all and cast to a common structure - MyCustomPojo.

I can do it by implementing a custom deserializer:

```<code>public class CustomMapDeserializer extends JsonDeserializer<Map<Integer, List<MyCustomPojo>>> {

    @Override
    public Map<Integer, List<MyCustomPojo>> deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
        JsonNode root = jsonParser.getCodec().readTree(jsonParser);

    // parse JsonNode and return  Map<Integer, List<MyCustomPojo>>
}
</code>```

Now I need to add this deserializer to a module and then register it with an object mapper.

```<code>SimpleModule module = new SimpleModule();
module.addDeserializer(Map.class, new CustomMapDeserializer()); // can’t specify type for map
objectMapper.registerModule(module);
</code>```

The problem is that now it will be applied to all Map classes in my application. I want it to apply only to parameterized map - Map<Integer, List<MyCustomPojo>>.

Is it possible to do it?

答: The way you're thinking of isn't going to work, and might need to rewrite some of the code to apply ONLY to your parameterized map. I don't want to give any false info, sorry I can't provide a solution, but I hope this comment will help others to provide a solution for other abled coders.</p>

Body:
I have a json string in the following structure:

{
    "1": { ... },
    "2": { ... },
    "3": { ... }
}

where 1, 2 and 3 are identifiers.

I want to deserialize this string and cast it to the following type - Map<Integer, List<MyCustomPojo>>

The thing is that each value { ... } has its own structure, but I need to parse them all and cast to a common structure - MyCustomPojo.

I can do it by implementing a custom deserializer:

public class CustomMapDeserializer extends JsonDeserializer<Map<Integer, List<MyCustomPojo>>> {

    @Override
    public Map<Integer, List<MyCustomPojo>> deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
        JsonNode root = jsonParser.getCodec().readTree(jsonParser);

    // parse JsonNode and return  Map<Integer, List<MyCustomPojo>>
}

Now I need to add this deserializer to a module and then register it with an object mapper.

SimpleModule module = new SimpleModule();
module.addDeserializer(Map.class, new CustomMapDeserializer()); // can’t specify type for map
objectMapper.registerModule(module);

The problem is that now it will be applied to all Map classes in my application. I want it to apply only to parameterized map - Map<Integer, List<MyCustomPojo>>.

Is it possible to do it?


问:
How to autogenerate parameters in an input step from Jenkins pipeline?
I would like to dynamically generate my parameters on an input step from a loop inside my Jenkins pipeline.

This is my code:

```<code>var = input message: 'Tags a saisir', ok: 'Build!',
        parameters: [
                     choice(name: 'name1', choices: file1),
                     choice(name: 'name2', choices: file2),
                     choice(name: 'name3', choices: file3),
                     choice(name: 'name4', choices: file4)
]
</code>```

I would like to know if it is possible to generate each parameter from a loop like :

```<code>for (int i = 0; i < myList.size(); i++) {
   theChoice = "choice(name : "+myList.get(i)+'choices: file"+i+")
}
</code>```

and generate the input step from those lines.

Is that kind of approach possible ?

The main goal is to generate an input step with modular variables dependending on the jenkins file clone from the Git SCM

Regards,

Guillaume

答:
You can do it like this

```<code>def parameterNames = fileMap.keySet().toList()
def choices = []
for (int i = 0; i < parameterNames.size(); i++) {
   choices += choice(name : parameterNames[i], choices: fileMap[parameterNames[i]])
}

def var = input message: 'Tags a saisir', ok: 'Build!', parameters: choices
</code>```

Where fileMap is a Map which contains possible choices fore each parameter name (key is a parameter name, value is a String of possible choices)

Body:
I would like to dynamically generate my parameters on an input step from a loop inside my Jenkins pipeline.

This is my code:

var = input message: 'Tags a saisir', ok: 'Build!',
        parameters: [
                     choice(name: 'name1', choices: file1),
                     choice(name: 'name2', choices: file2),
                     choice(name: 'name3', choices: file3),
                     choice(name: 'name4', choices: file4)
]

I would like to know if it is possible to generate each parameter from a loop like :

for (int i = 0; i < myList.size(); i++) {
   theChoice = "choice(name : "+myList.get(i)+'choices: file"+i+")
}

and generate the input step from those lines.

Is that kind of approach possible ?

The main goal is to generate an input step with modular variables dependending on the jenkins file clone from the Git SCM

Regards,

Guillaume

Body:
You can do it like this

def parameterNames = fileMap.keySet().toList()
def choices = []
for (int i = 0; i < parameterNames.size(); i++) {
   choices += choice(name : parameterNames[i], choices: fileMap[parameterNames[i]])
}

def var = input message: 'Tags a saisir', ok: 'Build!', parameters: choices

Where fileMap is a Map which contains possible choices fore each parameter name (key is a parameter name, value is a String of possible choices)


问:
Could not load file or assembly Temporary ASP.NET Files
I am developing a website on ASP.NET in C# (.NET Framework 4). After creating a new website project I tried to run the project. But I am getting the below error:

Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5\b9e740fc\App_global.asax.yfqtni9g.dll' or one of its dependencies. The system cannot find the file specified.

I already went through the below links [and all speaks about access to the folder], but it didn't help me :(

https://stackoverflow.com/questions/10496875/could-not-load-file-or-assembly-file-c-windows-microsoft-net-framework-v4-0

https://stackoverflow.com/questions/784157/asp-net-corrupt-assembly-could-not-load-file-or-assembly-app-web

http://web.archive.org/web/20101023213019/http://www.yetanotherdeveloper.com/post/2008/08/10/Could-not-load-file-or-assembly-App_Web.aspx

I checked and gave full access "Temporary ASP.NET Files" and to its sub folders and files for Users user-group.

 Assembly Load Trace

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

 Stack Trace

```<code>[FileNotFoundException: Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +39
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) +132
System.Reflection.Assembly.Load(AssemblyName assemblyRef, Evidence assemblySecurity) +28
System.CodeDom.Compiler.CompilerResults.get_CompiledAssembly() +93
System.Web.Compilation.BuildProvider.CreateBuildResult(CompilerResults results) +60
System.Web.Compilation.BuildProvider.GetBuildResult(CompilerResults results) +16
System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean isPrecompiledApp) +9118863
System.Web.Compilation.BuildManager.CompileGlobalAsax() +44
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +265

[HttpException (0x80004005): Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +62
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +421
System.Web.Compilation.BuildManager.CallAppInitializeMethod() +31
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +691

[HttpException (0x80004005): Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9090876
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +258
</code>```

 Please give me a link if this is a repeated question

 Thanks in adv.

I got the Log as follows

```

The operation was successful.
Bind result: hr = 0x0. The operation completed successfully.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: User = John-PC\John
LOG: DisplayName = Microsoft.VisualStudio.ComponentModelHost, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)
LOG: Appbase = file:///G:/WorkShop/HTML-CSS/ASP/MyFirst/
LOG: Initial PrivatePath = G:\WorkShop\HTML-CSS\ASP\MyFirst\bin
LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5
LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5
LOG: AppName = b9e740fc
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: G:\WorkShop\HTML-CSS\ASP\MyFirst\web.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Found assembly by looking in the GAC.
LOG: Binding succeeds. Returns assembly from C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.ComponentModelHost\v4.0_10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.ComponentModelHost.dll.
LOG: Assembly is loaded in default load context.
```

I am not able to trace any error. Please help me....

答:
I had same problem. I just solve it by changing
on web.config -> system.web -> compilation -> debug="false".
Then it work fine</p>

ContentLicense: CC BY-SA 4.0

Body:
I am developing a website on ASP.NET in C# (.NET Framework 4). After creating a new website project I tried to run the project. But I am getting the below error:

Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5\b9e740fc\App_global.asax.yfqtni9g.dll' or one of its dependencies. The system cannot find the file specified.

I already went through the below links [and all speaks about access to the folder], but it didn't help me :(

https://stackoverflow.com/questions/10496875/could-not-load-file-or-assembly-file-c-windows-microsoft-net-framework-v4-0

https://stackoverflow.com/questions/784157/asp-net-corrupt-assembly-could-not-load-file-or-assembly-app-web

http://web.archive.org/web/20101023213019/http://www.yetanotherdeveloper.com/post/2008/08/10/Could-not-load-file-or-assembly-App_Web.aspx

I checked and gave full access "Temporary ASP.NET Files" and to its sub folders and files for Users user-group.

 Assembly Load Trace

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

 Stack Trace

[FileNotFoundException: Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +39
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) +132
System.Reflection.Assembly.Load(AssemblyName assemblyRef, Evidence assemblySecurity) +28
System.CodeDom.Compiler.CompilerResults.get_CompiledAssembly() +93
System.Web.Compilation.BuildProvider.CreateBuildResult(CompilerResults results) +60
System.Web.Compilation.BuildProvider.GetBuildResult(CompilerResults results) +16
System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean isPrecompiledApp) +9118863
System.Web.Compilation.BuildManager.CompileGlobalAsax() +44
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +265

[HttpException (0x80004005): Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +62
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +421
System.Web.Compilation.BuildManager.CallAppInitializeMethod() +31
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +691

[HttpException (0x80004005): Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9090876
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +258

 Please give me a link if this is a repeated question

 Thanks in adv.

I got the Log as follows

The operation was successful.
Bind result: hr = 0x0. The operation completed successfully.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: User = John-PC\John
LOG: DisplayName = Microsoft.VisualStudio.ComponentModelHost, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)
LOG: Appbase = file:///G:/WorkShop/HTML-CSS/ASP/MyFirst/
LOG: Initial PrivatePath = G:\WorkShop\HTML-CSS\ASP\MyFirst\bin
LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5
LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5
LOG: AppName = b9e740fc
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: G:\WorkShop\HTML-CSS\ASP\MyFirst\web.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Found assembly by looking in the GAC.
LOG: Binding succeeds. Returns assembly from C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.ComponentModelHost\v4.0_10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.ComponentModelHost.dll.
LOG: Assembly is loaded in default load context.

I am not able to trace any error. Please help me....


问:
Firebase Serve Error
I am new to firebase and am trying to make a simple app that utilizes user authentication.  At this point in the project I am trying to run firebase on a local server using CLI commands.

I have set up firebase init and firebase deploy.  When I type firebase serve on my project folder i get the response,

"an unexpected error has occurred".

Below i am attaching the contents of my firebase-debug.log file.  Any help would be appreciated.  Thanks

command requires scopes:

["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase",...
[debug] [2017-06-11T17:09:09.607Z] > authorizing via signed-in user

TypeError: Cannot read property 'public' of undefined

答:
I think you may have skipped an initialization step by accident (I did the same thing on my first run-through)

Try this (from your same project directory):

1) firebase init

2) When prompted for which services you'll need make sure that Database AND Hosting options have their markers highlighted green (tab to Hosting with the spacebar).  It's easy to select just database and let it run its configuration and assume it configures all of the bulleted options below it if you do not watch closely because the stdout info isn't very clear. Now hit Enter

3) Accept the default database settings as you probably did before, and when asked "What do you want to use as your public directory? (public)", hit Enter.

At this point you should be good to go spin up a local firebase web server...

4) try 'firebase serve', hit Enter, and you should get a verification that hosting files are being served from /public

Hope this helps.  Good luck.

Title: Firebase Serve Error


问:
SoftLayer API: Retrieve Datacenters with Improved Capabilities
When I go to order NFS storage volumes in the SoftLayer UI, the options are different based on which datacenter is selected. Some datacenters have "improved capabilities". The ones that do allow a wider selection of NFS devices. In the UI window, improved datacenters are denoted with an asterisk next to their name.

I'd like to be able to retrieve this same list of datacenters with "improved capabilities" via API, or be able to inspect a specific datacenter to see if it is an improved datacenter. I can retrieve the full list of datacenters with SoftLayer_Location::getDatacenters, but the SoftLayer_Location datatype doesn't have a field for improved capabilities. Where can I go to retrieve this information? Is it possible via API?

答:
you need to call this method:

https://sldn.softlayer.com/reference/services/softlayer_network_storage/getfileblockencryptedlocations

it is gonna return the datacenters marked with * in the UI


问:
Easiest way to merge 2 or more ELF files
I'm working on some embedded code for a class project that currently (per requirements) creates a number of srec files and merges them. I'd like to be able to load this code into QEMU, but it is generally only happy with ELF files. What is the esiest way to merge the original ELF files instead of the srecs.
Also acceptable, a method to convert the srec back into an ELF and have the resulting file be loadable (objcopy seems to produce fairly broken files doing this (no architecture amoung others).
The tools must be capable of working with m68k binaries, but the host system is plain x86.</p>

答:
Easy...
let's assume : a.c and b.c

```<code>gcc a.c -c -o a.o
gcc b.c -c -o b.o
ld -r a.o b.oc -o c.o
</code>```

c.o now containes both a.o and b.o as a relocatable ELF file.

--Ivan

Body:
Easy...
let's assume : a.c and b.c

gcc a.c -c -o a.o
gcc b.c -c -o b.o
ld -r a.o b.oc -o c.o

c.o now containes both a.o and b.o as a relocatable ELF file.

--Ivan


问:
(VB6) Convert a 32bit Long to a String*6 [A-Z]
I wish to convert a 32bit Long to a String*6 which will only use the characters [A-Z].

Using VB6 (don't ask!).

I've calculated that a single letter uses 5 bits, so I can get 6 letters out of a 32 bit long.

Can anyone give me a pointer on how to do this, as I have no clue.

答:
A single letter uses 5 bits

correct

I can get 6 letters out of a 32 bit
  long.

You can encode 6 letters into a 32-bit long.

But that doesn't mean you can encode every 32-bit long into 6 letters.

Because 32^6 (1,073,741,824) < 2^32 (4,294,967,296)

That's even assuming you have 32 possible values (5-bits) per character.

It's even worse with 26 letters (which is less than 32-bits): 26^6 = 308,915,776

OwnerDisplayName: DingoBaby

OwnerDisplayName: Cade Roux


问:
jquery ajax sumit without page refresh problem
I need a ajax submission system without page refresh, I found one from the submit-a-form-without-page-refresh-using-jquery  script site

After a little modify, remove jquery-ajax\images\form_bg.png, How to do submit the data many times? I mean when submit first time, then I empty the text box, how to write another message then submit again? And another problem: when I submit once, it appears Submitted! success. one time. I submit twice, it appears Submitted! success. two times. I submit third times, it appears Submitted! success. third times. How to solve it? Thanks.

```<code>success: function() {
$('#contact_form').append("<div id='message'></div>");
$('#message').append("<h2>Submitted!</h2>")
.append("<p>success.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='check.png' />");
})
.fadeOut(3000, function() {
$('#message').css('display','none');
});
$('#name').val('');
$('#message').val('');
}
</code>```

答:
In your submit function return false; as the last statement.

```<code>success: function() {
    $('#contact_form').append("<div id='message'></div>");
    $('#message').html("<h2>Submitted!</h2>")
            .append("<p>success.</p>")
            .hide()
            .fadeIn(1500, function() {
        $('#message').append("<img id='checkmark' src='check.png' />");
    })
            .fadeOut(3000, function() {
        $('#message').css('display', 'none');
    });
    $('#name').val('');
    $('#message').val('');
}
</code>```

su

Body:
I need a ajax submission system without page refresh, I found one from the submit-a-form-without-page-refresh-using-jquery  script site

After a little modify, remove jquery-ajax\images\form_bg.png, How to do submit the data many times? I mean when submit first time, then I empty the text box, how to write another message then submit again? And another problem: when I submit once, it appears Submitted! success. one time. I submit twice, it appears Submitted! success. two times. I submit third times, it appears Submitted! success. third times. How to solve it? Thanks.

success: function() {
$('#contact_form').append("

");
$('#message').append("
Submitted!
")
.append("
success.
")
.hide()
.fadeIn(1500, function() {
$('#message').append("");
})
.fadeOut(3000, function() {
$('#message').css('display','none');
});
$('#name').val('');
$('#message').val('');
}

Body:
In your submit function return false; as the last statement.

success: function() {
    $('#contact_form').append("<div id='message'></div>");
    $('#message').html("<h2>Submitted!</h2>")
            .append("<p>success.</p>")
            .hide()
            .fadeIn(1500, function() {
        $('#message').append("<img id='checkmark' src='check.png' />");
    })
            .fadeOut(3000, function() {
        $('#message').css('display', 'none');
    });
    $('#name').val('');
    $('#message').val('');
}

su


问:
Missing type specifier
While compiling below code I am getting missing type specifier error. Any way I can solve this issue? I have been trying for few days now and couldnt make any progress. Done almost everything that was suggested for this similar issue but cant seem to get through

CPP

```<code>#include "MemoryProtection.h"
#include "Resources.h"
#include "stdafx.h"

pWriteProcessMemory pfnWriteProcessMemory = NULL;
pReadProcessMemory pfnReadProcessMemory = NULL;
</code>```

HEADER

```<code>#pragma once

#include <Windows.h>
#include "3rd\detours.h"
#include <Psapi.h>
#include <atlstr.h>

#pragma comment(lib, "Detours.lib")

typedef LONG NTSTATUS;

#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)

LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam);

typedef BOOL(WINAPI* pReadProcessMemory) (HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead);
typedef BOOL(WINAPI* pWriteProcessMemory) (HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten);
</code>```

ERROR

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int        6
Error   C2146   syntax error: missing ';' before identifier 'pfnWriteProcessMemory'     6
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int        7
Error   C2146   syntax error: missing ';' before identifier 'pfnReadProcessMemory'      7
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int        8
</code>```

答:
If you're using pre-compiled headers #include "stdafx.h" should be the first  pre-processor line. Otherwise all previous includes are overwritten.

/Yu (Use Precompiled Header File)

The compiler treats all code occurring before the .h file as precompiled. It skips to just beyond the #include directive associated with the .h file, uses the code contained in the .pch file, and then compiles all code after filename.
  -- https://msdn.microsoft.com/en-us/library/z0atkd6c.aspx

See also What's the use for “stdafx.h” in Visual Studio? and StdAfx.h for Novices on cplusplus.com.

Title: Missing type specifier

Body:
While compiling below code I am getting missing type specifier error. Any way I can solve this issue? I have been trying for few days now and couldnt make any progress. Done almost everything that was suggested for this similar issue but cant seem to get through

CPP

#include "MemoryProtection.h"
#include "Resources.h"
#include "stdafx.h"

pWriteProcessMemory pfnWriteProcessMemory = NULL;
pReadProcessMemory pfnReadProcessMemory = NULL;

HEADER

#pragma once

#include <Windows.h>
#include "3rd\detours.h"
#include <Psapi.h>
#include <atlstr.h>

#pragma comment(lib, "Detours.lib")

typedef LONG NTSTATUS;

#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)

LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam);

typedef BOOL(WINAPI* pReadProcessMemory) (HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead);
typedef BOOL(WINAPI* pWriteProcessMemory) (HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten);

ERROR

Severity    Code    Description Project File    Line    Suppression State
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int        6
Error   C2146   syntax error: missing ';' before identifier 'pfnWriteProcessMemory'     6
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int        7
Error   C2146   syntax error: missing ';' before identifier 'pfnReadProcessMemory'      7
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int        8


问:
Proper way to send FCM device token to a webview
I have a webapp built on Laravel that is to be displayed on a mobile app (both android and ios, which are being built using React Native) via WebView.

I managed to use evollu/react-native-fcm to generate the token.

My question is: what is the proper way to send this token to the WebView, so my webapp can relate it to a user and store it on the database?

My first idea was to pass it along to the URL being called by the WebView as a GET parameter, but the parameter always come blank on the other side, probably because the token is requested asynchronously and when the webview is called it didn't come yet.

What can I do?

答: I managed to delay the rendering until the token was ready by using an if on the render method that would not return the webview if a state "loading" is true; then in the function that gets the token I used setState to change the value of loading to false.</p>


问:
Stop Visual Studio from launching a new browser window when starting debug?
I already have a window open with the web site I'm debugging. I don't need VS to launch another one for me every time I need to debug.

Is there a way to stop this behavior?

答:
While there are several excellent answers, ranging from usual suspects to newer solutions, I would like to provide one more to the fray that addresses what you should do when you are working on a solution with multiple projects.

Before I arrived at this solution, I kept looking at bindingInformation in the applicationhost.config of the solution, tirelessly looking for any hint of why things were simply not working.

Turns out, the simple thing that I overlooked was that different projects have individual settings too.

So, besides Project > {Project-Name} Properties... > Web > Start Action on my Backend Project, I also had to Go to Website > Start Options... > Start Action on my Frontend Project. Once there, I selected Don't open a page. Wait for a request from an external application and have been happy ever since!

OwnerDisplayName: sker


问:
How to turn header on while querying CSV file using SQL?
Spark SQL can query on CSV file directly. See the example below.

```<code>val df = spark.sql("SELECT * FROM csv.`csv/file/path/in/hdfs`")
</code>```

However, how can we let Spark that there's a header line in the CSV file?

答:
You can use a view:</p>

```<code>spark.sql("""CREATE TEMPORARY VIEW df
             USING csv
             OPTIONS (header "true", path "csv/file/path/in/hdfs")""")
spark.sql("""SELECT * FROM df""")
</code>```

Body:
Spark SQL can query on CSV file directly. See the example below.

val df = spark.sql("SELECT * FROM csv.`csv/file/path/in/hdfs`")

However, how can we let Spark that there's a header line in the CSV file?

Body:
You can use a view:

spark.sql("""CREATE TEMPORARY VIEW df
             USING csv
             OPTIONS (header "true", path "csv/file/path/in/hdfs")""")
spark.sql("""SELECT * FROM df""")