问:
System.BadImageFormatException: Image is too small .Net Core MVC
I have recently deployed my application to the server and below is the error I get. When I run it locally, everything works fine.

The application is uisng Microsoft.AspNetCore 1.1.3

I also tried to force the application to use x86.

```<code>System.BadImageFormatException: Image is too small.
   at System.Reflection.Throw.ImageTooSmall()
   at     System.Reflection.PortableExecutable.PEHeaders.SkipDosHeader(PEBinaryReader& reader, Boolean& isCOFFOnly)
   at System.Reflection.PortableExecutable.PEHeaders..ctor(Stream peStream, Int32 size, Boolean isLoadedImage)
   at System.Reflection.PortableExecutable.PEReader..ctor(Stream peStream, PEStreamOptions options, Int32 size)
   at Microsoft.CodeAnalysis.ModuleMetadata.CreateFromStream(Stream peStream, PEStreamOptions options)
   at Microsoft.AspNetCore.Mvc.Razor.Compilation.MetadataReferenceFeatureProvider.CreateMetadataReference(String path)
   at Microsoft.AspNetCore.Mvc.Razor.Compilation.MetadataReferenceFeatureProvider.PopulateFeature(IEnumerable`1 parts, MetadataReferenceFeature feature)
   at Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature[TFeature](TFeature feature)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorReferenceManager.GetCompilationReferences()
   at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorReferenceManager.get_CompilationReferences()
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRoslynCompilationService.CreateCompilation(String compilationContent, String assemblyName)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRoslynCompilationService.Compile(RelativeFileInfo fileInfo, String compilationContent)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorCompilationService.Compile(RelativeFileInfo file)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.CompilerCache.CreateCacheEntry(String relativePath, String normalizedPath, Func`2 compile)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.CompilerCache.GetOrAdd(String relativePath, Func`2 compile)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorPageFactoryProvider.CreateFactory(String relativePath)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.CreateCacheResult(HashSet`1 expirationTokens, String relativePath, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.OnCacheMiss(ViewLocationExpanderContext expanderContext, ViewLocationCacheKey cacheKey)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.LocatePageFromViewLocations(ActionContext actionContext, String pageName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.ViewEngines.CompositeViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
</code>```

答: It turned out that the dll files weren't copied over correctly. The file sizes to the publish and the deployment were the same but when I copied everything over from scratch, the website started working.</p>

Body:
I have recently deployed my application to the server and below is the error I get. When I run it locally, everything works fine.

The application is uisng Microsoft.AspNetCore 1.1.3

I also tried to force the application to use x86.

System.BadImageFormatException: Image is too small.
   at System.Reflection.Throw.ImageTooSmall()
   at     System.Reflection.PortableExecutable.PEHeaders.SkipDosHeader(PEBinaryReader& reader, Boolean& isCOFFOnly)
   at System.Reflection.PortableExecutable.PEHeaders..ctor(Stream peStream, Int32 size, Boolean isLoadedImage)
   at System.Reflection.PortableExecutable.PEReader..ctor(Stream peStream, PEStreamOptions options, Int32 size)
   at Microsoft.CodeAnalysis.ModuleMetadata.CreateFromStream(Stream peStream, PEStreamOptions options)
   at Microsoft.AspNetCore.Mvc.Razor.Compilation.MetadataReferenceFeatureProvider.CreateMetadataReference(String path)
   at Microsoft.AspNetCore.Mvc.Razor.Compilation.MetadataReferenceFeatureProvider.PopulateFeature(IEnumerable`1 parts, MetadataReferenceFeature feature)
   at Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature[TFeature](TFeature feature)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorReferenceManager.GetCompilationReferences()
   at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorReferenceManager.get_CompilationReferences()
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRoslynCompilationService.CreateCompilation(String compilationContent, String assemblyName)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRoslynCompilationService.Compile(RelativeFileInfo fileInfo, String compilationContent)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorCompilationService.Compile(RelativeFileInfo file)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.CompilerCache.CreateCacheEntry(String relativePath, String normalizedPath, Func`2 compile)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.CompilerCache.GetOrAdd(String relativePath, Func`2 compile)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorPageFactoryProvider.CreateFactory(String relativePath)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.CreateCacheResult(HashSet`1 expirationTokens, String relativePath, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.OnCacheMiss(ViewLocationExpanderContext expanderContext, ViewLocationCacheKey cacheKey)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.LocatePageFromViewLocations(ActionContext actionContext, String pageName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.ViewEngines.CompositeViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)


来源: stackexchange

问:
Right & Left Img Borders Being Cut Off on Mobile - Force Mobile to Display Images + Borders?
I have a series 8.5" x 11" @ 72ppi magazine pages exported from InDesign as jpegs that I wish to display within Blogger posts. I want to display a 1 pixel border around each of these images so the edges of the pages are more easily discerned. I am testing the mobile version of the Blogger site in Chrome's emulator.

The images are correctly be resized to fit the mobile device; however the right and left borders are being cut off. Sometimes the page will load with one border showing, but the opposing border is then 2 pixels off screen. Sometimes when I reload the blog, or change devices, the borders might appear correctly, but then start not appearing once again. How do I make sure the images are correctly resized with the border on each side

```<code>.post-body-container img {
border:1px solid #000000;
padding:0px;
width: 612px;
height:100%;
display: block;
}
</code>```

答:
Thanks for the replies. I slightly modified the supplied code by adding a margin. This works for all the devices in the Chrome emulator except for the two Nexus devices, which keep scaling the images so as to cut off the left and rights borders. This could be a problem with the emulator. Another solution which works on all devices is to add a 1 pixel border graphic inside InDesign and export the images with a 1 pixel border.</p>

```<code>.post-body-container {
max-width: 100%;
}

.post-body-container img {
border:1px solid #000000;
margin:2px;
width: 100%;
height: auto;
display: block;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a series 8.5" x 11" @ 72ppi magazine pages exported from InDesign as jpegs that I wish to display within Blogger posts. I want to display a 1 pixel border around each of these images so the edges of the pages are more easily discerned. I am testing the mobile version of the Blogger site in Chrome's emulator.

The images are correctly be resized to fit the mobile device; however the right and left borders are being cut off. Sometimes the page will load with one border showing, but the opposing border is then 2 pixels off screen. Sometimes when I reload the blog, or change devices, the borders might appear correctly, but then start not appearing once again. How do I make sure the images are correctly resized with the border on each side

.post-body-container img {
border:1px solid #000000;
padding:0px;
width: 612px;
height:100%;
display: block;
}

Body:
Thanks for the replies. I slightly modified the supplied code by adding a margin. This works for all the devices in the Chrome emulator except for the two Nexus devices, which keep scaling the images so as to cut off the left and rights borders. This could be a problem with the emulator. Another solution which works on all devices is to add a 1 pixel border graphic inside InDesign and export the images with a 1 pixel border.

.post-body-container {
max-width: 100%;
}

.post-body-container img {
border:1px solid #000000;
margin:2px;
width: 100%;
height: auto;
display: block;
}


问:
Using the open(' ', 'w') function but file is not being edited
I'm using the code below to attempt to open a file and edit the text in the file (this is; my string), but after running this code, the file remains unchanged when I open it in my documents. Anyone got an idea why? </p>

```<code>myfile=open("file","w")
mod= "this is; my string ".split(";")
myfile.write(" ".join(mod))
myfile.close()
</code>```

答:
Try this:

```<code>with open("file","w+") as myfile:  # Use mode w+
   mod= "this is; my string ".split(";")
   myfile.write(" ".join(mod))
</code>```

using with open() as x you do not need to run .close()

Body:
I'm using the code below to attempt to open a file and edit the text in the file (this is; my string), but after running this code, the file remains unchanged when I open it in my documents. Anyone got an idea why?

myfile=open("file","w")
mod= "this is; my string ".split(";")
myfile.write(" ".join(mod))
myfile.close()

Body:
Try this:

with open("file","w+") as myfile:  # Use mode w+
   mod= "this is; my string ".split(";")
   myfile.write(" ".join(mod))

using with open() as x you do not need to run .close()


问:
How To: 100% Height Table only Scroll tbody
is it possible to scroll the content of a 100% height table and not the header using CSS and only showing the scroll bar to the side of the tbody content and not the header row? Thanks!</p>

答:
Mat that is simple. Here's what you want to do

CSS:

```<code><style>
  article, aside, figure, footer, header, hgroup,
  menu, nav, section { display: block; }

  html, body{ width: 100%; height: 100%;}
  table{
    width: 100%;
    height: 100%;
    background-color: #aaa;
  }

  tbody{
    width: 100%;
    height: 100%;
    -display: block;
    background-color: #ccc;
    overflow-y: scroll;
    overflow-x: hidden;

  }

  td{
    width: 100px;
    height: 200px;
    background-color: #eee;
  }

</style>
</code>```

HTML:

```<code><table>

  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
     <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>

</table>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Mat that is simple. Here's what you want to do

CSS:

<style>
  article, aside, figure, footer, header, hgroup,
  menu, nav, section { display: block; }

  html, body{ width: 100%; height: 100%;}
  table{
    width: 100%;
    height: 100%;
    background-color: #aaa;
  }

  tbody{
    width: 100%;
    height: 100%;
    -display: block;
    background-color: #ccc;
    overflow-y: scroll;
    overflow-x: hidden;

  }

  td{
    width: 100px;
    height: 200px;
    background-color: #eee;
  }

</style>

HTML:

<table>

  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
     <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>

</table>


问:
Incremental search in Idea the word under cursor
I would like to search in current file the word under cursor like Alt+F3, except manually selecting current word? Is there alike keyboard shortcut?

答:
Not entirely sure what you are looking to do when you say "manually selecting current word", but F3 (Next) and Shift+F3 (previous) will search for the word under the cursor. You can use Ctrl+W (Extend selection) to select the word under the cursor. Finally Ctrl+F will open the find/search tool. More options are listed in help: https://www.jetbrains.com/help/idea/search.html

EDIT

I forgot to mention, if you first use the mouse or Ctrl+W to select the word, and then open the search bar using Ctrl+F, or search & replace using Ctrl+R, IDEA will populate the search field with the selected text.


问:
Mean stack: display products into ng smart table
Im trying to display the product data using ng2-smart-table plugin.

I am able to get the products in the browser log, but i need to display the same onChange of a drop down value.

\app\components\layout\blank-page\blank-page.component.html

```<code><form role="form">
        <fieldset class="form-group">
            <label>Select Category</label><br/><br/>
                <select [(ngModel)]="selectedObject" (ngModelChange)="onChange(selectedObject)" name="selectedObject" class="form-control">
                        <option>--Select Category--</option>
                        <option *ngFor="let category of categories" [value]="category._id">{{category.category_name}}</option>
                </select>
        </fieldset>
    </form>

//This is where table data is displaying, need to show my data here

<ng2-smart-table [settings]="view_update_items_settings" [source]="view_update_items_smart_data" (userRowSelect)="onUserRowSelect($event)"  class="table table-hover table-striped"></ng2-smart-table>
</code>```

app\components\layout\blank-page\blank-page.component.ts

```<code>onChange(categoryid) {

this.productService.getProductsOncategory(categoryid).subscribe(data => {
  if (data.success) {
    //this.selectedObject = data.mainProducts;
    console.log(data)
    console.log('Products obtained');
  } else {
    console.log('Not obtained!');
  }
});

}
</code>```

app\services\product.service.ts

```<code>getProductsOncategory(category_id){
  console.log(category_id)
  let catUrl="http://10.*.*.*:5000/products/getProductsOncategory"
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  let catIdObj = JSON.stringify({category_id:category_id})
  console.log(catIdObj)
  return this.http.post(catUrl,catIdObj,{headers:headers})
  .map((response:Response)=>response.json())
  .do(data=>console.log(JSON.stringify(data)))
  .catch(this.handleError);
}
</code>```

On selection of a value from drop down, i get data posted in my browser, i need to display the same in my ng2-smart-table

答:
Bind "view_update_items_smart_data" with the data you obtain from server.

```<code>    onChange(categoryid) {

this.productService.getProductsOncategory(categoryid).subscribe(data => {
  if (data.success) {
    //this.selectedObject = data.mainProducts;
    console.log(data)
    console.log('Products obtained');
    this.view_update_items_smart_data.load(data);
  } else {
    console.log('Not obtained!');
  }
});

}
</code>```

For more information you can refer to
https://akveo.github.io/ng2-smart-table/#/examples/populate-from-server

Body:
Im trying to display the product data using ng2-smart-table plugin.

I am able to get the products in the browser log, but i need to display the same onChange of a drop down value.

\app\components\layout\blank-page\blank-page.component.html

<form role="form">
        <fieldset class="form-group">
            Select Category

                <select [(ngModel)]="selectedObject" (ngModelChange)="onChange(selectedObject)" name="selectedObject" class="form-control">
                        <option>--Select Category--</option>
                        <option *ngFor="let category of categories" [value]="category._id">{{category.category_name}}</option>
                </select>
        </fieldset>
    </form>

//This is where table data is displaying, need to show my data here

<ng2-smart-table [settings]="view_update_items_settings" [source]="view_update_items_smart_data" (userRowSelect)="onUserRowSelect($event)"  class="table table-hover table-striped"></ng2-smart-table>

app\components\layout\blank-page\blank-page.component.ts

onChange(categoryid) {

this.productService.getProductsOncategory(categoryid).subscribe(data => {
  if (data.success) {
    //this.selectedObject = data.mainProducts;
    console.log(data)
    console.log('Products obtained');
  } else {
    console.log('Not obtained!');
  }
});

}

app\services\product.service.ts

getProductsOncategory(category_id){
  console.log(category_id)
  let catUrl="http://10.*.*.*:5000/products/getProductsOncategory"
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  let catIdObj = JSON.stringify({category_id:category_id})
  console.log(catIdObj)
  return this.http.post(catUrl,catIdObj,{headers:headers})
  .map((response:Response)=>response.json())
  .do(data=>console.log(JSON.stringify(data)))
  .catch(this.handleError);
}

On selection of a value from drop down, i get data posted in my browser, i need to display the same in my ng2-smart-table

Body:
Bind "view_update_items_smart_data" with the data you obtain from server.

    onChange(categoryid) {

this.productService.getProductsOncategory(categoryid).subscribe(data => {
  if (data.success) {
    //this.selectedObject = data.mainProducts;
    console.log(data)
    console.log('Products obtained');
    this.view_update_items_smart_data.load(data);
  } else {
    console.log('Not obtained!');
  }
});

}

For more information you can refer to
https://akveo.github.io/ng2-smart-table/#/examples/populate-from-server


问:
Run long Oracle stored procedure from PHP
I have a stored procedure which I run from PHP using:

```<code>//Request does not change
$sql = 'BEGIN SP_GET_MY_DATA(:POP, :SEG, :DUR, :VIEW, :PAGE, :OUTPUT_CUR); END;';

//Statement does not change
$stmt = oci_parse($conn,$sql);
oci_bind_by_name($stmt,':POP',$pop);
oci_bind_by_name($stmt,':SEG',$seg);
oci_bind_by_name($stmt,':DUR',$dur);
oci_bind_by_name($stmt,':VIEW',$view);
oci_bind_by_name($stmt,':PAGE',$page);

//But BEFORE statement, Create your cursor
$cursor = oci_new_cursor($conn)

// On your code add the latest parameter to bind the cursor resource to the Oracle argument
oci_bind_by_name($stmt,":OUTPUT_CUR", $cursor,-1,OCI_B_CURSOR);

// Execute the statement as in your first try
oci_execute($stmt);

// and now, execute the cursor
oci_execute($cursor);

// Use OCIFetchinto in the same way as you would with SELECT
while ($data = oci_fetch_assoc($cursor, OCI_RETURN_LOBS )) {
    print_r($data}
}
</code>```

The problem is I have millions of rows and complex logic in stored procedure. When I execute SP_GET_MY_DATA through SQL developer, it takes around 2 hours to complete it.

PHP is timing out when I do it. I cannot increase the max_execution_time in PHP as well.

How can I run this on Oracle or using PHP without timing out? Please help.

答:
Don't increase max_execution_time, set it to 0, allow it to run indefinitely. If you are going to return loads of rows, make sure to either increase memory (ini_set) or allow immediate buffer flushing so that it can output directly to client.

The latter will also prevent clients from prematurely disconnecting because they didn't get any data. (ob_implicit_flush(true);)

Body:
I have a stored procedure which I run from PHP using:

//Request does not change
$sql = 'BEGIN SP_GET_MY_DATA(:POP, :SEG, :DUR, :VIEW, :PAGE, :OUTPUT_CUR); END;';

//Statement does not change
$stmt = oci_parse($conn,$sql);
oci_bind_by_name($stmt,':POP',$pop);
oci_bind_by_name($stmt,':SEG',$seg);
oci_bind_by_name($stmt,':DUR',$dur);
oci_bind_by_name($stmt,':VIEW',$view);
oci_bind_by_name($stmt,':PAGE',$page);

//But BEFORE statement, Create your cursor
$cursor = oci_new_cursor($conn)

// On your code add the latest parameter to bind the cursor resource to the Oracle argument
oci_bind_by_name($stmt,":OUTPUT_CUR", $cursor,-1,OCI_B_CURSOR);

// Execute the statement as in your first try
oci_execute($stmt);

// and now, execute the cursor
oci_execute($cursor);

// Use OCIFetchinto in the same way as you would with SELECT
while ($data = oci_fetch_assoc($cursor, OCI_RETURN_LOBS )) {
    print_r($data}
}

The problem is I have millions of rows and complex logic in stored procedure. When I execute SP_GET_MY_DATA through SQL developer, it takes around 2 hours to complete it.

PHP is timing out when I do it. I cannot increase the max_execution_time in PHP as well.

How can I run this on Oracle or using PHP without timing out? Please help.


问:
How to additionally include File as response of WebAPI
My current web API already responding JSON data as below.

```<code>public HttpResponseMessage GetFieldInfo()
        {
  //....
return Ok(GetFieldsInstance());  //GetFieldsInstance returning with DTO class instance.
}
</code>```

Now, I need to include, file along with JSON response. I could not find any link which shows, how to include filestream and JSON in single response.

For file stream, it will work as below but, not able to find way, how to include JSON object property with filestream.

```<code>result = Request.CreateResponse(HttpStatusCode.OK);
                result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
                result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentDisposition.FileName = "FieldFile";
</code>```

答:
You can covert (serialize) the file to a base64 string and include it as a property in the JSON response.

```<code>public IHttpActionResult GetFieldInfo() {
    //...

    var model = new {
        //assuming: byte[] GetBinaryFile(...)
        data = Convert.ToBase64String(GetBinaryFile(localFilePath)),
        result = "final",
        //...other properties...
    };

    return Ok(model);
}
</code>```

The client would then need to convert (desrialize) the base64 string back to your desired file to be used as desired.

Take note that depending on the size of the file it can drastically increase the size of the response and the client should take that into consideration.

Body:
My current web API already responding JSON data as below.

public HttpResponseMessage GetFieldInfo()
        {
  //....
return Ok(GetFieldsInstance());  //GetFieldsInstance returning with DTO class instance.
}

Now, I need to include, file along with JSON response. I could not find any link which shows, how to include filestream and JSON in single response.

For file stream, it will work as below but, not able to find way, how to include JSON object property with filestream.

result = Request.CreateResponse(HttpStatusCode.OK);
                result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
                result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentDisposition.FileName = "FieldFile";

Body:
You can covert (serialize) the file to a base64 string and include it as a property in the JSON response.

public IHttpActionResult GetFieldInfo() {
    //...

    var model = new {
        //assuming: byte[] GetBinaryFile(...)
        data = Convert.ToBase64String(GetBinaryFile(localFilePath)),
        result = "final",
        //...other properties...
    };

    return Ok(model);
}

The client would then need to convert (desrialize) the base64 string back to your desired file to be used as desired.

Take note that depending on the size of the file it can drastically increase the size of the response and the client should take that into consideration.


问:
jQuery prev next elements
My issue in jQuery code. I have this code jsFiddle.

```<code>$(document).ready(function(){
  $("#clickinput1").click(function (evt) {
     $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
  });
});
</code>```

Before click on button, input is disable and have dark background. I need, when click on button input be enabled(this work) and background change on white color or none. I cannot make this. Please help)

答:
```<code>$(document).ready(function(){
    $("#clickinput1").click(function (evt) {
        $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
        $(".input").css("background-color", "white");
    });
});
</code>```

Title: jQuery prev next elements

Body:
My issue in jQuery code. I have this code jsFiddle.

$(document).ready(function(){
  $("#clickinput1").click(function (evt) {
     $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
  });
});

Before click on button, input is disable and have dark background. I need, when click on button input be enabled(this work) and background change on white color or none. I cannot make this. Please help)


问:
how can I increase hdfs capacity
How can I increase the configured capacity of my hadoop DFS from the default 50GB to 100GB?

My present setup is hadoop 1.2.1 running on a centOS6 machine with 120GB of 450GB used.  Have set up hadoop to be in psudodistributed mode with the /conf  suggested by "Hadoop the Definitive Guide 3'rd).
hdfs-site.xml had only one configured property:

```<code>   <configuration>
    <property>
         <name>dfs.replication</name>
         <value>1</value>
     </property>
 </configuration>
</code>```

The following line gave no error feedback... comes back to the prompt.

```<code>hadoop dfsadmin -setSpaceQuota 100g  /tmp/hadoop-myUserID
</code>```

If I am in a regen loop (have executed

```<code> rm -rf /tmp/hadoop-myUserId
</code>```

in a attempt to "start from scratch")  This seeming success of the setSpaceQuota occurs iff-and-only-if  I have executed

```<code>  start-all.sh
  hadoop namenode -format
</code>```

The failure of my dfs capacity configuration is shown by

```<code> hadoop dfsadmin -report
</code>```

which shows the same 50GB of configured capacity.

I would be willing to switch over to hadoop 2.2 (now stable release) if that is the current best way to get 100GB hdfs configured capacity.
  Seems like there should be a configuration property for hdfs-site.xml which would allow me to use more of my free partition.

答:
Stop all the service: stop-all.sh

then add these properties in terms of increasing the storage size in hdfs-site.xml:

```<code>    <property>
        <name>dfs.disk.balancer.enabled</name>
        <value>true</value>
</property>
<property>
        <name>dfs.storage.policy.enabled</name>
        <value>true</value>
</property>
<property>
        <name>dfs.blocksize</name>
        <value>134217728</value>
</property>
<property>
        <name>dfs.namenode.handler.count</name>
        <value>100</value>
</property>
 <property>
         <name>dfs.namenode.name.dir</name>
         <value>file:///usr/local/hadoop_store/hdfs/namenode</value>
</property>
<property>
<name>dfs.datanode.data.dir</name>
<value>file:///usr/local/hadoop_store/hdfs/datanode,[disk]file:///hadoop_store2/hdfs/datanode</value>
</property>
</code>```

also remember to put [disk] for including a extra disk on folder, [ssd] for dedicated extra ssd drive. always remember to check the "///" triple "/" for the directory pointing.

After that,

format the namenode to get the settings inherited in the Hadoop cluster, by giving a command

hadoop namenode -format
then start the services from beginning:
Start-all.sh

"/* remember without formating the hdfs the setting will not be activated as it will search for the Blockpool Id (BP_ID) in dfs.datanode.data.dir, and for the new location it will not found any BP_ID. "/*

Title: how can I increase hdfs capacity

Body:
How can I increase the configured capacity of my hadoop DFS from the default 50GB to 100GB?

My present setup is hadoop 1.2.1 running on a centOS6 machine with 120GB of 450GB used.  Have set up hadoop to be in psudodistributed mode with the /conf  suggested by "Hadoop the Definitive Guide 3'rd).
hdfs-site.xml had only one configured property:

   <configuration>
    <property>
         <name>dfs.replication</name>
         <value>1</value>
     </property>
 </configuration>

The following line gave no error feedback... comes back to the prompt.

hadoop dfsadmin -setSpaceQuota 100g  /tmp/hadoop-myUserID

If I am in a regen loop (have executed

 rm -rf /tmp/hadoop-myUserId

in a attempt to "start from scratch")  This seeming success of the setSpaceQuota occurs iff-and-only-if  I have executed

  start-all.sh
  hadoop namenode -format

The failure of my dfs capacity configuration is shown by

 hadoop dfsadmin -report

which shows the same 50GB of configured capacity.

I would be willing to switch over to hadoop 2.2 (now stable release) if that is the current best way to get 100GB hdfs configured capacity.
  Seems like there should be a configuration property for hdfs-site.xml which would allow me to use more of my free partition.

Body:
Stop all the service: stop-all.sh

then add these properties in terms of increasing the storage size in hdfs-site.xml:

    <property>
        <name>dfs.disk.balancer.enabled</name>
        <value>true</value>
</property>
<property>
        <name>dfs.storage.policy.enabled</name>
        <value>true</value>
</property>
<property>
        <name>dfs.blocksize</name>
        <value>134217728</value>
</property>
<property>
        <name>dfs.namenode.handler.count</name>
        <value>100</value>
</property>
 <property>
         <name>dfs.namenode.name.dir</name>
         <value>file:///usr/local/hadoop_store/hdfs/namenode</value>
</property>
<property>
<name>dfs.datanode.data.dir</name>
<value>file:///usr/local/hadoop_store/hdfs/datanode,[disk]file:///hadoop_store2/hdfs/datanode</value>
</property>

also remember to put [disk] for including a extra disk on folder, [ssd] for dedicated extra ssd drive. always remember to check the "///" triple "/" for the directory pointing.

After that,

format the namenode to get the settings inherited in the Hadoop cluster, by giving a command

hadoop namenode -format
then start the services from beginning:
Start-all.sh

"/* remember without formating the hdfs the setting will not be activated as it will search for the Blockpool Id (BP_ID) in dfs.datanode.data.dir, and for the new location it will not found any BP_ID. "/*


问:
Finding matching value in sheet 2 and copy adjacent cells value in sheet 1
I have searched through many similar topics but could find nothing that will do what I need.

I am trying to create a worksheet that will track scores for a darts game.

On Sheet 1 I have two columns that simply tracks each players throws from 501 down to 0

Row 25 is the amount remaining for each player.

In Sheet 2 I have 2 columns. The Column A contains scores that you can check out on, and Column B contains the checkout e.g. (T20, T20, D18). So if the value in row 25 of Sheet 1 matches any of the values in Column A of sheet 2, the I want to display the Value of Column B in the matching row on Sheet 2 Underneath the remaining score on Sheet 1.

Can anyone point me in the right direction?

答:
You can use this:</p>

```<code>=IFERROR(VLOOKUP(A4, Sheet2!$C$2:$E$65535, 3, FALSE),0)
</code>```

Body:
You can use this:

=IFERROR(VLOOKUP(A4, Sheet2!$C$2:$E$65535, 3, FALSE),0)


问:
Python currency codes into a list
Does anyone have a nifty way to get all the three letter alphabetic currency codes (an example of the ones I mean is at  http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm) into a list in Python 2.5? Note I don't want to do a screen scraping version as the code has to work offline - the website is just an example of the codes.

It looks like there should be a way using the locale library but it's not clear to me from reading the documentation and there must be a better way than copy pasting those into a file!

To clear the question up more, in C# for the same problem, the following code did it very neatly using the internal locale libraries:

```<code>CultureInfo.GetCultures(CultureTypes.SpecificCultures)
          .Select(c => new RegionInfo(c.LCID).CurrencySymbol)
          .Distinct()
</code>```

I was hoping there might be an equivalent in python. And thanks to everyone who has provided an answer so far.

答:
Not very elegant or nifty, but you can generate the list once and save to use it later:

```<code>import urllib, re
url = "http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm"
print re.findall(r'\<td valign\="top"\>\s+([A-WYZ][A-Z]{2})\s+\</td\>', urllib.urlopen(url).read())
</code>```

output:

```<code>['AFN', 'EUR', 'ALL', 'DZD', 'USD', 'EUR', 'AOA', 'ARS', 'AMD', 'AWG', 'AUD',
...
'UZS', 'VUV', 'EUR', 'VEF', 'VND', 'USD', 'USD', 'MAD', 'YER', 'ZMK', 'ZWL', 'SDR']
</code>```

Note that you'll need to prune everything after X.. as they are apparently reserved names, which means that you'll get one rogue entry (SDR, the last element) which you can just delete by yourself.

Title: Python currency codes into a list

Body:
Does anyone have a nifty way to get all the three letter alphabetic currency codes (an example of the ones I mean is at  http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm) into a list in Python 2.5? Note I don't want to do a screen scraping version as the code has to work offline - the website is just an example of the codes.

It looks like there should be a way using the locale library but it's not clear to me from reading the documentation and there must be a better way than copy pasting those into a file!

To clear the question up more, in C# for the same problem, the following code did it very neatly using the internal locale libraries:

CultureInfo.GetCultures(CultureTypes.SpecificCultures)
          .Select(c => new RegionInfo(c.LCID).CurrencySymbol)
          .Distinct()

I was hoping there might be an equivalent in python. And thanks to everyone who has provided an answer so far.

Body:
Not very elegant or nifty, but you can generate the list once and save to use it later:

import urllib, re
url = "http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm"
print re.findall(r'\<td valign\="top"\>\s+([A-WYZ][A-Z]{2})\s+\</td\>', urllib.urlopen(url).read())

output:

['AFN', 'EUR', 'ALL', 'DZD', 'USD', 'EUR', 'AOA', 'ARS', 'AMD', 'AWG', 'AUD',
...
'UZS', 'VUV', 'EUR', 'VEF', 'VND', 'USD', 'USD', 'MAD', 'YER', 'ZMK', 'ZWL', 'SDR']

Note that you'll need to prune everything after X.. as they are apparently reserved names, which means that you'll get one rogue entry (SDR, the last element) which you can just delete by yourself.


问:
VPN metrics in Cloudwatch
Recently I have configured the ALARM in Cloudwatch for tracking VPN Tunnel connection. It is well known that 0 indicates tunnel is DOWN and 1 indicates tunnel is UP. When Connection is down, I have seen some data points on the graph shown as 0.66, 0.75.

So what does that mean, is the connection is DOWN or UP?

答: That happens if your graph shows averages (that is why both of your values are between 1 and 0). In the ClouWatch console select your metric and then click on the Graphed metrics tab. There you will see Statistics column which is most likely set to Average now.

Title: VPN metrics in Cloudwatch


问:
Pytorch FloatClassNLLCriterion_updateOutput error
I am getting the following error message while computing the loss of my neural net: TypeError: FloatClassNLLCriterion_updateOutput received an invalid combination of arguments - got (int, torch.FloatTensor, !torch.FloatTensor!, torch.FloatTensor, bool, NoneType, torch.FloatTensor, int), but expected (int state, torch.FloatTensor input, torch.LongTensor target, torch.FloatTensor output, bool sizeAverage, [torch.FloatTensor weights or None], torch.FloatTensor total_weight, int ignore_index) on this line: loss = criterion(outputs,one_hot_target).

I have tried several things and searched the web, but I can't seem to find my mistake. Does someone have an idea?

The code used:

```<code>class Net(nn.Module):
def _init_(self,input_size,hidden_size, num_classes):
    super(Net, self)._init_()
    self.l1 = nn.Linear(input_size,hidden_size)
    self.l2 = nn.Linear(hidden_size,num_classes)

def forward(self,x):
    x = self.l1(x)
    x = F.tanh(x)
    x = self.l2(x)
    x = F.softmax(x)
    return x

mlp = Net(input_size,hidden_size,num_classes)

criterion = nn.NLLLoss()
optimizer = torch.optim.SGD(mlp.parameters(), lr=learning_rate)

for i in range(N-1,len(word_list)):

  # Define input vector x
  x = None

  for j in range(0,N-1):
      try:
          x = np.r_[x,w2v[word_list[j]]]
      except:
          x = w2v[word_list[j-N+1]]

  # Done with defining  x

  np.reshape(x,(len(x),1))
  x = autograd.Variable(torch.FloatTensor(x))
  optimizer.zero_grad()

  outputs = mlp(x)
  outputs = outputs.unsqueeze(0)
  outputs = outputs.transpose(0,1)

  index = w2i[word_list[i]]
  one_hot_target = np.zeros([num_classes,1],dtype=float)

  one_hot_target[index] = float(1)

  one_hot_target = autograd.Variable(torch.Tensor(one_hot_target))
  print (one_hot_target)
  loss = criterion(outputs,one_hot_target)
  #loss.backward()
  #optimizer.step()
</code>```

答:
The target tensor you are passing to your loss function is of type Float Tensor. That's happening here:
one_hot_target = autograd.Variable(torch.Tensor(one_hot_target))

That is, because the default Tensor type in PyTorch is FloatTensor.
However, the NLLLoss() function is expecting a LongTensor as target. You can double check in the example in the documentation, which you can find here: NLLLoss Pytorch docs.

You can simply convert your target Tensor to a LongTensor like this:

one_hot_target = autograd.Variable(torch.Tensor(one_hot_target)).long()

Body:
I am getting the following error message while computing the loss of my neural net: TypeError: FloatClassNLLCriterion_updateOutput received an invalid combination of arguments - got (int, torch.FloatTensor, !torch.FloatTensor!, torch.FloatTensor, bool, NoneType, torch.FloatTensor, int), but expected (int state, torch.FloatTensor input, torch.LongTensor target, torch.FloatTensor output, bool sizeAverage, [torch.FloatTensor weights or None], torch.FloatTensor total_weight, int ignore_index) on this line: loss = criterion(outputs,one_hot_target).

I have tried several things and searched the web, but I can't seem to find my mistake. Does someone have an idea?

The code used:

class Net(nn.Module):
def _init_(self,input_size,hidden_size, num_classes):
    super(Net, self)._init_()
    self.l1 = nn.Linear(input_size,hidden_size)
    self.l2 = nn.Linear(hidden_size,num_classes)

def forward(self,x):
    x = self.l1(x)
    x = F.tanh(x)
    x = self.l2(x)
    x = F.softmax(x)
    return x

mlp = Net(input_size,hidden_size,num_classes)

criterion = nn.NLLLoss()
optimizer = torch.optim.SGD(mlp.parameters(), lr=learning_rate)

for i in range(N-1,len(word_list)):

  # Define input vector x
  x = None

  for j in range(0,N-1):
      try:
          x = np.r_[x,w2v[word_list[j]]]
      except:
          x = w2v[word_list[j-N+1]]

  # Done with defining  x

  np.reshape(x,(len(x),1))
  x = autograd.Variable(torch.FloatTensor(x))
  optimizer.zero_grad()

  outputs = mlp(x)
  outputs = outputs.unsqueeze(0)
  outputs = outputs.transpose(0,1)

  index = w2i[word_list[i]]
  one_hot_target = np.zeros([num_classes,1],dtype=float)

  one_hot_target[index] = float(1)

  one_hot_target = autograd.Variable(torch.Tensor(one_hot_target))
  print (one_hot_target)
  loss = criterion(outputs,one_hot_target)
  #loss.backward()
  #optimizer.step()


问:
Filling nulls with a list in Pandas using fillna
Given a pd.Series, I would like to replace null values with a list. That is, given:

```<code>import numpy as np
import pandas as pd
ser = pd.Series([0,1,np.nan])
</code>```

I want a function that would return

```<code>0        0
1        1
2    [nan]
</code>```

But if I try using the natural function for this, namely fillna:

```<code>result = ser.fillna([np.nan])
</code>```

but I get the error

TypeError: "value" parameter must be a scalar or dict, but you passed a "list"

Any suggestions of a simple way to acheive this?

答:
Use apply, because fillna working with scalars only:

```<code>print (ser.apply(lambda x: [np.nan] if pd.isnull(x) else x))
0        0
1        1
2    [nan]
dtype: object
</code>```

Body:
Given a pd.Series, I would like to replace null values with a list. That is, given:

import numpy as np
import pandas as pd
ser = pd.Series([0,1,np.nan])

I want a function that would return

0        0
1        1
2    [nan]

But if I try using the natural function for this, namely fillna:

result = ser.fillna([np.nan])

but I get the error

TypeError: "value" parameter must be a scalar or dict, but you passed a "list"

Any suggestions of a simple way to acheive this?

Body:
Use apply, because fillna working with scalars only:

print (ser.apply(lambda x: [np.nan] if pd.isnull(x) else x))
0        0
1        1
2    [nan]
dtype: object


问:
Something in for-loop breaks down after 17 loops
I have the following for-loop:

```<code>i = 1
y = 4
for column in new_columns:
    df[column] = (df['column1'] * (1+G1)**i * (df['ER1'] - df['ER2']) \
                    * df['column2'] * (1+ df['Column3'])**i + df['column1'] \
                    * (1+G1)**i * df['E2'] * df['Column2'] * (1+ df['Column3'])**i \
                    * (1 - ER2) * df['Column4'])/ (1 + df['ER4'])**y
    i += 1
    y += 1
</code>```

I noticed a bizarre kink in a graph made of the new columns and I decided to double-check the calculation by running the same thing in MS Excel. The ratio between the Python and Excel columns is 1 until loop number 17. On the 18th loop, the ratio jumps to 1.0249 (Python produces 2.5 % higher numbers) and stays there until the last loop (30). There is no kink on the graph produced in MS Excel. Any wise thoughts?

答: After spending about 8 hours on this, I finally noticed that I had a duplicate in new columnswhich obviously didn't show up on the resulting dataframe and hence the difference with Excel. Sorry guys.

Body:
I have the following for-loop:

i = 1
y = 4
for column in new_columns:
    df[column] = (df['column1'] * (1+G1)**i * (df['ER1'] - df['ER2']) \
                    * df['column2'] * (1+ df['Column3'])**i + df['column1'] \
                    * (1+G1)**i * df['E2'] * df['Column2'] * (1+ df['Column3'])**i \
                    * (1 - ER2) * df['Column4'])/ (1 + df['ER4'])**y
    i += 1
    y += 1

I noticed a bizarre kink in a graph made of the new columns and I decided to double-check the calculation by running the same thing in MS Excel. The ratio between the Python and Excel columns is 1 until loop number 17. On the 18th loop, the ratio jumps to 1.0249 (Python produces 2.5 % higher numbers) and stays there until the last loop (30). There is no kink on the graph produced in MS Excel. Any wise thoughts?


问:
Cannot create objects in scheme
I began learning Scheme (R5RS) and immediately ran into problems. I have this code:

```<code>(define make-source (lambda (seq)
  (define next list)
  (define peek list)
  (let ((seq seq)
        ;(endl (if (null? endl) #f endl))
        )
  (lambda (selector data)
    (cond ((equal? selector 'seq) seq)
          ;((equal? selector "endl") endl)
          ((equal? selector 'next) (car seq))
          ((equal? selector 'peek) (list-ref seq 0))
          (else '()))))))

(define s (make-source "abc"))
(next s)
</code>```

What I'm trying to do is to create object which can be used to work with strings, lists and vectors like with IO ports. My methods next and peek should work like read-char and peek-char respectively. But every time i try to run it I get

```<code>next: undefined;
 cannot reference undefined identifier
</code>```

What causing the problem? Is it the right way to create object like this? Also, how can I implement optional parameter endl?

答:
The idea you have tried to implement is normally called message passing. This works by creating a closure scope. In this scope stuff is defined, which is by default private to the scope. At the end of the closure a dispatcher function is returned. The dispatcher takes messages and returns stuff from the captured scope. By this the private stuff gets public. Typically functions are returned. If the caller gets a function, the caller can call the function with any argument, the function accepts.

Your implementation has some cosmetic concerns and some failures.

You should stay with one way defining functions. Either the more verbose syntax:

```<code>(define f (lambda () (display "Hello, World!\n")))
</code>```

Or the more compact syntax:

```<code>(define (f) (display "Hello, World!\n"))
</code>```

But do not mix them.

First you have to convert the string into a list in order to use car on the sequence.  This is done with the function string->list. You can not use car on a string.

Then you have to implement next and peek to do the right thing. It is not enough to make it aliases to list. The function next consumes a character from the input stream. This means the code most mutate some state somewhere. This requires the use of set!.

The dispatch function compares just symbols. It is easier to compare the symbols with case instead of cond. You can also use cond, but it is more to type.

The sequence of characters is normally limited to the scope of the closure.  If you expose the sequence by the seq selector to the calling scope, you violate the idea of encapsulation.  This is normally only done for debugging.

If a wrong message is passed to the dispatcher function, it is wise to throw an error instead of returning something useless or undefined.

This shows the code for make-source according to the above suggestions.

```<code>(define (make-source seq)

  (let ((seq (string->list seq)))  ;; convert string into list

    (define (next)
      (if (pair? seq)
          (let ((c (car seq)))
            (set! seq (cdr seq))  ;; mutation of the sequence
            c)))

    (define (peek)
      (car seq))

    (define (endl arg1 arg2)  ;; use of the arguments
      (map list->string
           (map (lambda (x)
                  (list arg1 x arg2))
                seq)))

    (lambda (selector)
      (case selector
        ((seq) seq) ;; this is only for debugging
        ;; for correct messages, just return the functions
        ((endl) endl)
        ((next) next)
        ((peek) peek)
        ;; throw error
        (else (error "undefined"))))))
</code>```

If you call make-source it generates the dispatcher function:

```<code>(define s (make-source "abc"))
</code>```

Now you can pass messages in the form of symbols to the dispatcher.

The following returns the function peeking a character.

```<code>(s 'peek)  ;; => <procedure>
</code>```

In order to execute it, you have to use application twice.

```<code>((s 'peek))  ;; => a
</code>```

You can give it a name, if you feel uncomfortable with the double application.

```<code>(define peek-s (s 'peek))
(peek-s)    ;; => a
</code>```

But you can not define generics this way. A generic is a function called peek instead of peek-s and peeks from any object belonging to the class of source objects. We have defined just peek-s, which peeks just from the s object. In order to define generics, you have to read the Thant Tessman paper "Adding Generics to Scheme". Because of this and other limitations, the above approach is sometimes called poor man's objects. But almost every Scheme has some kind of object system inspired by Common Lisp called CLOS (Common Lisp Object System) or tiny CLOS.

Finally passing arguments to the exposed function is as simple as passing arguments to functions. If you have the exposed function, you can pass whatever the function accepts to it.

```<code>((s 'endl) #\< #\>)  ;; => ("<a>" "<b>" "<c>")
</code>```

Title: Cannot create objects in scheme

Body:
I began learning Scheme (R5RS) and immediately ran into problems. I have this code:

(define make-source (lambda (seq)
  (define next list)
  (define peek list)
  (let ((seq seq)
        ;(endl (if (null? endl) #f endl))
        )
  (lambda (selector data)
    (cond ((equal? selector 'seq) seq)
          ;((equal? selector "endl") endl)
          ((equal? selector 'next) (car seq))
          ((equal? selector 'peek) (list-ref seq 0))
          (else '()))))))

(define s (make-source "abc"))
(next s)

What I'm trying to do is to create object which can be used to work with strings, lists and vectors like with IO ports. My methods next and peek should work like read-char and peek-char respectively. But every time i try to run it I get

next: undefined;
 cannot reference undefined identifier

What causing the problem? Is it the right way to create object like this? Also, how can I implement optional parameter endl?

Body:
The idea you have tried to implement is normally called message passing. This works by creating a closure scope. In this scope stuff is defined, which is by default private to the scope. At the end of the closure a dispatcher function is returned. The dispatcher takes messages and returns stuff from the captured scope. By this the private stuff gets public. Typically functions are returned. If the caller gets a function, the caller can call the function with any argument, the function accepts.

Your implementation has some cosmetic concerns and some failures.

You should stay with one way defining functions. Either the more verbose syntax:

(define f (lambda () (display "Hello, World!\n")))

Or the more compact syntax:

(define (f) (display "Hello, World!\n"))

But do not mix them.

First you have to convert the string into a list in order to use car on the sequence.  This is done with the function string->list. You can not use car on a string.

Then you have to implement next and peek to do the right thing. It is not enough to make it aliases to list. The function next consumes a character from the input stream. This means the code most mutate some state somewhere. This requires the use of set!.

The dispatch function compares just symbols. It is easier to compare the symbols with case instead of cond. You can also use cond, but it is more to type.

The sequence of characters is normally limited to the scope of the closure.  If you expose the sequence by the seq selector to the calling scope, you violate the idea of encapsulation.  This is normally only done for debugging.

If a wrong message is passed to the dispatcher function, it is wise to throw an error instead of returning something useless or undefined.

This shows the code for make-source according to the above suggestions.

(define (make-source seq)

  (let ((seq (string->list seq)))  ;; convert string into list

    (define (next)
      (if (pair? seq)
          (let ((c (car seq)))
            (set! seq (cdr seq))  ;; mutation of the sequence
            c)))

    (define (peek)
      (car seq))

    (define (endl arg1 arg2)  ;; use of the arguments
      (map list->string
           (map (lambda (x)
                  (list arg1 x arg2))
                seq)))

    (lambda (selector)
      (case selector
        ((seq) seq) ;; this is only for debugging
        ;; for correct messages, just return the functions
        ((endl) endl)
        ((next) next)
        ((peek) peek)
        ;; throw error
        (else (error "undefined"))))))

If you call make-source it generates the dispatcher function:

(define s (make-source "abc"))

Now you can pass messages in the form of symbols to the dispatcher.

The following returns the function peeking a character.

(s 'peek)  ;; => <procedure>

In order to execute it, you have to use application twice.

((s 'peek))  ;; => a

You can give it a name, if you feel uncomfortable with the double application.

(define peek-s (s 'peek))
(peek-s)    ;; => a

But you can not define generics this way. A generic is a function called peek instead of peek-s and peeks from any object belonging to the class of source objects. We have defined just peek-s, which peeks just from the s object. In order to define generics, you have to read the Thant Tessman paper "Adding Generics to Scheme". Because of this and other limitations, the above approach is sometimes called poor man's objects. But almost every Scheme has some kind of object system inspired by Common Lisp called CLOS (Common Lisp Object System) or tiny CLOS.

Finally passing arguments to the exposed function is as simple as passing arguments to functions. If you have the exposed function, you can pass whatever the function accepts to it.

((s 'endl) #\< #\>)  ;; => ("<a>" "<b>" "<c>")


答:
You are giving css as $("#white").css("background-color:#fff");. That's not the right way to defince css in jquery. It should be $("#white").css("background-color","#fff");. Another thing is you haven't given id as white to any of the element. Changing all these will solve your issue.

$(document).ready(function() {
  $("#clickinput1").click(function(evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
    $("#white").css("background-color", "#fff");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.input {
  border: 0px;
  outline: none;
  background: #ccc;
  height: 20px;
  width: 250px;
  font: 18px Calibri;
  margin-top: 1px;
}

body {
  background-color: #006699;
}</code>```

<input type="text" name="customername" class="input" value="" id="white" disabled />

button
```
</div>
</div>
</p>

<p>Even we don't need to define any id. This can simply be done like this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
  $("#clickinput1").click(function(evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).focus().css("background-color", "#fff");

  });
});</code>```

.input {
  border: 0px;
  outline: none;
  background: #ccc;
  height: 20px;
  width: 250px;
  font: 18px Calibri;
  margin-top: 1px;
}

body {
  background-color: #006699;
}```
<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>
<input type="text" name="customername" class="input" value="" id="white" disabled />
<div style="float:right;cursor:pointer;margin:2px 0 0 0px;" id="clickinput1"><img src="img/edit.png" />button</div></code>```

Title: jQuery prev next elements

Body:
You are giving css as $("#white").css("background-color:#fff");. That's not the right way to defince css in jquery. It should be $("#white").css("background-color","#fff");. Another thing is you haven't given id as white to any of the element. Changing all these will solve your issue.

$(document).ready(function() {
  $("#clickinput1").click(function(evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
    $("#white").css("background-color", "#fff");
  });
});

.input {
  border: 0px;
  outline: none;
  background: #ccc;
  height: 20px;
  width: 250px;
  font: 18px Calibri;
  margin-top: 1px;
}

body {
  background-color: #006699;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="customername" class="input" value="" id="white" disabled />
<div style="float:right;cursor:pointer;margin:2px 0 0 0px;" id="clickinput1"><img src="img/edit.png" />button</div>

Even we don't need to define any id. This can simply be done like this

$(document).ready(function() {
  $("#clickinput1").click(function(evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).focus().css("background-color", "#fff");

  });
});

.input {
  border: 0px;
  outline: none;
  background: #ccc;
  height: 20px;
  width: 250px;
  font: 18px Calibri;
  margin-top: 1px;
}

body {
  background-color: #006699;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="customername" class="input" value="" id="white" disabled />
<div style="float:right;cursor:pointer;margin:2px 0 0 0px;" id="clickinput1"><img src="img/edit.png" />button</div>


问:
Laravel intervention/image doesn't resize image
I am trying to use laravel intervention plugin. I installed it without problem but can't use it.
I am trying to make a test function which returns resized image, but without success;
I think the problem may be in image path, please help me fix my code.

function test($img)
{
   /* $img = Image::make('public/image1.jpg');
    $img->resize(300, 200);
    return $img; */

   $image = Image::make('http://localhost/cms/digital-cms/public/image1.jpg')->resize(200, 200, function ($c) {
        $c->aspectRatio();
        $c->upsize();
    });
    return $image;

    //$h=200; $w=200;
    //return Image::make(public_path('public/image1.jpg')->resize($h, $w)->response('jpg'));
}```

答:
```<code> //get image
 $image=$request->file('image');
 //rename image
 $input = time().'.'.$image->getClientOriginalExtension();
            //your directory to upload
            $destinationPath = 'main/images/company';
            //save and resize image
            $img = Image::make($image->getRealPath());
            $img->resize(20,20, function ($constraint) {
              $constraint->aspectRatio();
              })->save($destinationPath.'/'.$input);
</code>```


答:
your code will create file at the directory where the script is running. you should use: </p>

```<code>  file_path = os.path.abspath(__file__) + "/file"

  f = open(file_path,"w")
  f.write(.....)
  f.close()
</code>```

<p>and then it will create file in the directory you want. </p>

Title: Using the open(' ', 'w') function but file is not being edited

Body:
I'm using the code below to attempt to open a file and edit the text in the file (this is; my string), but after running this code, the file remains unchanged when I open it in my documents. Anyone got an idea why?

myfile=open("file","w")
mod= "this is; my string ".split(";")
myfile.write(" ".join(mod))
myfile.close()

Body:
your code will create file at the directory where the script is running. you should use:

  file_path = os.path.abspath(__file__) + "/file"

  f = open(file_path,"w")
  f.write(.....)
  f.close()

and then it will create file in the directory you want.


问:
Visual Studio Doesn't Create Xamarin Bin Folder
I'm trying to build an iPad project from Visual Studio 2017 for windows, However whenever I try to debug the app I get this error

Launch failed. The app 'B2C.iPad' could not be launched on 'iPad Air
  iOS 11.0'. Error: error MT0069: The app directory
  '/Users/user/Library/Caches/Xamarin/mtbs/builds/B2C.iPad/acb039527d504c900b2e6c86d8d84d09/bin/iPhoneSimulator/Debug/MobiBusiness.app'
  does not exist. . Please check the logs for more details.

I noticed that visual studio doesn't create bin folder on the Mac machine although it indicates the build is succeeded.

I tried building the solution without debugging and looked at the log file nothing looked suspicious and there was no error.

does anyone know what might cause this error?

答: Okay this is embarrassing apparently the iPad project wasn't not selected in the build configuration, so needed to select the projects from build --> Configuration Manager</p>


问:
Can I grab and populate a screen made by a programmatically triggered button push?
Am I able to grab a screen that is created by a programmatically triggered button push call and populate it with values?

My specific example is that I want to grab the new e-mail screen that is made when I execute this code:

```<code>CRCommunicationDraft graph = PXGraph.CreateInstance<CRCommunicationDraft>();
graph.AddNew.PressButton();
</code>```

I want to grab the screen created after AddNew.PressButton() is executed. Is there any way to do this?

答:
For this specific case, I think is answered here:

How can I open an editable, sendable e-mail screen with prepopoulated values?

For most cases you want to:

Override the Action Handler of the button. You can use OVERRIDE METHOD button of customization editor for that. In your case override the AddNew action event handler.

Create a new graph instance for your target screen, here it is CREmailActivityMaint.

Assign to or insert a record into the current DataView of that graph, in your case use CREmailActivityMaint.Message DataView.

Redirect to the screen, using PXRedirectHelper class.

Body:
Am I able to grab a screen that is created by a programmatically triggered button push call and populate it with values?

My specific example is that I want to grab the new e-mail screen that is made when I execute this code:

CRCommunicationDraft graph = PXGraph.CreateInstance<CRCommunicationDraft>();
graph.AddNew.PressButton();

I want to grab the screen created after AddNew.PressButton() is executed. Is there any way to do this?


问:
Xamarin Forms Grid with mixed xaml and code-behind content?
I wanted to have most rows defined xaml code and only one added programmatically in code-behind, but I am not able to do it.

Here is my XAML simplified code:

```<code><Grid x:Name="gridTest">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="auto" />
    </Grid.RowDefinitions>
</Grid>

<Label Grid.Row="0" Text="row 0"></Label>

<Label Grid.Row="1" Text="row 1"></Label>
</code>```

And in my code-behind:

```<code>gridTest.Children.Add(new Label { Text = "row 2" }, 0, 2);
</code>```

The output is just "row 2"

Is this really impossible or am I missing something?

Tks

答:
your XAML labels need to be within your <Grid></Grid> tags

```<code><Grid x:Name="gridTest">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="auto" />
    </Grid.RowDefinitions>
  <Label Grid.Row="0" Text="row 0"></Label>
  <Label Grid.Row="1" Text="row 1"></Label>
</Grid>
</code>```

Body:
I wanted to have most rows defined xaml code and only one added programmatically in code-behind, but I am not able to do it.

Here is my XAML simplified code:

<Grid x:Name="gridTest">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="auto" />
    </Grid.RowDefinitions>
</Grid>

And in my code-behind:

gridTest.Children.Add(new Label { Text = "row 2" }, 0, 2);

The output is just "row 2"

Is this really impossible or am I missing something?

Tks

Body:
your XAML labels need to be within your <Grid></Grid> tags

<Grid x:Name="gridTest">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="auto" />
    </Grid.RowDefinitions>
  <Label Grid.Row="0" Text="row 0"></Label>
  <Label Grid.Row="1" Text="row 1"></Label>
</Grid>


问:
csvwriter doesn't write data into csv file
I have a list of tuple which named output and I want to write it in csv file.
I've tried this.

```<code>f = open('filename.csv' ,'w')
w = csv.writer(f)
w.writerow(output)
f.close()
</code>```

There's no error message. It just don't work.

答:
The code you wrote works for me, as long as your output variable is an iterable object, such as a list. For example:

```<code>import csv

output = ["Foo", "Bar"]

f = open("filename.csv", "w")
w = csv.writer(f)
w.writerow(output)
f.close()
</code>```

Successfully created the file: "filename.csv", with contents:

```<code>Foo,Bar
</code>```

Body:
I have a list of tuple which named output and I want to write it in csv file.
I've tried this.

f = open('filename.csv' ,'w')
w = csv.writer(f)
w.writerow(output)
f.close()

There's no error message. It just don't work.

Body:
The code you wrote works for me, as long as your output variable is an iterable object, such as a list. For example:

import csv

output = ["Foo", "Bar"]

f = open("filename.csv", "w")
w = csv.writer(f)
w.writerow(output)
f.close()

Successfully created the file: "filename.csv", with contents:

Foo,Bar


问:
JavaScript - Bing Maps - WellKnownText
I have the follow code:

```<code>var area = new Microsoft.Maps.WellKnownText.read(x, { strokeColor: stroke, strokeThickness: 10 });
$scope.map.setView({ center: new Microsoft.Maps.Location(lat, lng), zoom: 17 });
$scope.map.entities.push(area);
</code>```

Which should map a Well Known Text (wkt) string.  This works fine if I have a POINT() but for any other WKT String, it shows nothing.  I've looked at the MSDN example, but it only demonstrates POINT(), and no matter what I try, I can't get the other shapes to show up.

Has anyone been able to map shapes through the wkt handler?

Thanks
Docmur

答:
Sorry, to be honest, I forgot about this post.  We solved this problem a while ago and I can't remember what the issue was.  We were having massive problems with CORS errors and 500 error codes from Bing Maps, which have disappeared.  Something was wrong with our key, at least that was the best guess they ever came up with.

We currently have the WKT mapping working like a treat.

Thanks
Docmur

Title: JavaScript - Bing Maps - WellKnownText

Body:
I have the follow code:

var area = new Microsoft.Maps.WellKnownText.read(x, { strokeColor: stroke, strokeThickness: 10 });
$scope.map.setView({ center: new Microsoft.Maps.Location(lat, lng), zoom: 17 });
$scope.map.entities.push(area);

Which should map a Well Known Text (wkt) string.  This works fine if I have a POINT() but for any other WKT String, it shows nothing.  I've looked at the MSDN example, but it only demonstrates POINT(), and no matter what I try, I can't get the other shapes to show up.

Has anyone been able to map shapes through the wkt handler?

Thanks
Docmur


问:
Can't scroll to element by attribute
I have a a search form which searches words inside a UL LI element. when there is a result - i want it to be scrolled by the result's attribute position (data-target).

I can't get the LI's position by it's attribute, and therefor - can't navigate to it.

I get "Cannot read property 'top' of undefined" when i try to get the position of the element_id variable :

```<code>$(".faq_cont_right .scroll ul li").each(function() {
    if ($(this).text().search(new RegExp(filter, "i")) < 0) {
        var element_id = $(".faq_cont_right .scroll ul li").filter('[data-target="#item1"]');
        $('.scroll').animate({
            scrollTop: $(element_id).position().top - 500,
        }, 200);
    } else {
        $(this).show();
        $(this).trigger('click');
        var element_id = $(this).attr('data-target');
        var scroller = $('.scroll').offset().top;
        console.log($(element_id).offset().top); // error

        $('.scroll').animate({
            scrollTop: $(element_id).offset().top - scroller,
        }, 200);
    }
});
</code>```

/**
 * Created by Roy Barak on 22-Oct-17.
 */
$(document).ready(function() {

  $('.questions_header').text($(".active_search").text());

  $('.question_div').on('shown.bs.tab', function() {

    $('.questions_header').text($(this).text());

  });

  $('#faq_chat_btn').on('click', function() {

    $(this).toggleClass('faq_chat_off faq_chat_on');
    if ($(this).hasClass("faq_chat_off")) {
      $('.faq_chat_header_left p').text('fermé');
      $('.faq_chat_middle').hide();
    }
    if ($(this).hasClass("faq_chat_on")) {

      $('.faq_chat_header_left p').text('ouvert');
      $('.faq_chat_middle').show();
    }

  });

  $('#faq_search').bind('keydown', 'keyup', function(event) {
    if (event.keyCode == 13) {
      event.preventDefault();

    }

    var filter = $(this).val();

    if (filter.length && filter !== null && filter !== '') {

      $(".faq_cont_right .scroll ul li").each(function() {

        if ($(this).text().search(new RegExp(filter, "i")) < 0) {

          var element_id = $(".faq_cont_right .scroll ul li").filter('[data-target="#item1"]');

          $('.scroll').animate({
            scrollTop: $(element_id).position().top - 500,
          }, 200);

        } else {

          $(this).show();

          $(this).trigger('click');
          var element_id = $(this).attr('data-target');
          var scroller = $('.scroll').offset().top;

          console.log($(element_id).offset().top);

          $('.scroll').animate({
            scrollTop: $(element_id).offset().top - scroller,
          }, 200);

        }
      });
      $(".tab-content>.active").each(function() {

        if ($(this).text().search(new RegExp(filter, "i")) < 0) {

          $(this).show();

        } else {

          $(this).show();

        }
      });

    }

  });

  $(".faq_cont_right .scroll ul li").on('click', function(e) {

    $(".faq_cont_right .scroll ul li").removeClass('active_search');
    $(this).toggleClass('active_search');

    e.preventDefault();

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Styles go here */

#faq_page .page_container {
  height: 100vh;
}

.faq_cont_right {
  float: left;
  width: 33.33333333%;
}

.scroll {
  width: 100%;
  height: 88vh;
  overflow-y: scroll;
  overflow-x: hidden;
}

.faq_cont_left .tab-content {
  padding: 15px!important;
}

.faq_tab_content {
  height: 88%;
}

.faq_question_header {
  padding: 15px;
  height: 12%;
  display: flex;
  align-items: center;
}

.faq_question_header p {
  margin: 0!important;
}

.questions_header {
  font-family: 'Roboto', sans-serif;
  color: #5d3c95;
  font-size: 1rem;
  text-transform: uppercase;
}

.answer_content {
  font-family: 'Roboto', sans-serif;
  color: #48484a;
  font-size: 1rem;
}

.search_bar {
  background-color: #fff;
  border-right: 2px solid #e9e9e9;
  border-left: 2px solid #e9e9e9;
  height: 12vh;
  display: flex;
  align-items: center;
  padding: 0 10px 0 20px;
}

.faq_search_form input {
  margin-left: 10px;
  outline: none;
  border: none;
  font-size: 11px;
}

form.faq_search_form {
  display: flex;
  align-items: center;
}

input.input_search::-webkit-input-placeholder {
  font-family: 'Roboto', sans-serif;
  font-size: 12px;
  color: #767678;
}

input.input_search::-moz-placeholder {
  font-family: 'Roboto', sans-serif;
  font-size: 12px;
  color: #767678;
}

input.input_search:-ms-input-placeholder {
  font-family: 'Roboto', sans-serif;
  font-size: 12px;
  color: #767678;
}

input.input_search {
  padding: 0 !important;
}

form.faq_search_form i:before {
  content: "\f002";
  font-size: 2vw;
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  text-decoration: inherit;
  color: #767678;
}

.faq_cont_left {
  height: 100vh;
  background-color: white;
  float: left;
  width: 66.66666667%;
}

.faq_questions {
  padding: 0;
  width: 100%;
  list-style: none;
  margin-top: 0 !important;
  margin-bottom: 0px !important;
}

.faq_questions li:hover {
  font-weight: 600;
}

.question_div {
  font-family: 'Roboto', sans-serif;
  font-size: 11px;
  background-color: #e9e9e9;
  display: flex;
  align-items: center;
  height: 80px;
  justify-content: center;
}

.questions_border {
  height: 100%;
  border-bottom: 0.5px solid white;
  display: flex;
  align-items: center;
  width: 70%;
}

.questions_cont p {
  margin: 0;
}

.questions_cont {
  /*padding-left: 22px;*/
  /*padding-right: 55px;*/
}

.question_div {
  position: relative;
  z-index: 10000;
}

.active_search {
  font-weight: 600;
  background-color: #5d3c95;
  color: white;
}

.scroll::-webkit-scrollbar-track {
  background-color: #F5F5F5;
}

.scroll::-webkit-scrollbar {
  width: 7px;
  background-color: #d8d8d8;
}

.scroll::-webkit-scrollbar-thumb {
  background-color: #bebebe;
  border: none;
}

/*-------------chat---------------*/

.faq_chat_box {
  width: 66.66666667%;
  background-color: #d3f2f1;
  position: absolute;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  right: 0;
  padding: 20px;
}

.faq_chat_box_wrap {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.faq_chat_header {
  padding: 15px 20px 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #5d3c95;
  color: #fff;
}

.faq_chat_header_right img {
  width: 11%;
}

.faq_chat_header_right span {
  font-family: 'Roboto', sans-serif;
  font-size: 1.3rem;
  color: #fff;
  padding: 10px;
  margin: 0 !important;
  font-weight: 300;
}

.faq_chat_header_left p {
  font-family: 'Montserrat Semi Bold', sans-serif;
  font-size: 11px;
  color: #fff;
  padding: 10px;
  margin: 0 !important;
}

.faq_chat_middle {
  width: 100%;
  background-color: #fff;
  padding: 10px;
}

.chat_text {
  font-family: 'Roboto', sans-serif;
  font-size: 1.3rem;
  color: #48484a;
}

.chat_parme_text {
  margin-bottom: 15px;
}

.chat_parme_text_header {
  font-family: 'Roboto', sans-serif;
  font-size: 1.3rem;
  color: #5d3c95;
}

.chat_client_text_header {
  font-family: 'Roboto', sans-serif;
  font-size: 1.3rem;
  color: #41c8c2;
}

#faq_chat_btn:hover {
  cursor: pointer;
  cursor: hand;
}

.faq_chat_footer {
  padding: 18px;
  background-color: #41c8c2;
}

.faq_chat_middle .scroll {
  height: 20vh;
  width: 100%;
  overflow-y: scroll;
  overflow-x: hidden;
}

.faq_chat_icon {
  position: relative;
}

.faq_chat_header_left {
  display: flex;
  align-items: center;
}

.faq_chat_status i {
  font-size: 18px;
}

.faq_chat_on {
  color: #41c8c2;
}

.faq_chat_off {
  color: #ff4444;
}

.input-icon {
  position: absolute;
  color: #41c8c2;
  right: 17px;
  font-size: 18px;
  top: calc(50% - 0.5em);
  /* Keep icon in center of input, regardless of the input height */
}

input#faq_chat {
  border-radius: 5px;
  outline: none;
  border: none;
}

.input-wrapper {
  position: relative;
}</code>```

    <form class="faq_search_form">
      <input class="form-control input_search" placeholder="Rechercher une question..." name="faq_search" id="faq_search" type="text" autocomplete="off">
    </form>

            Les salariés SNCF en activité sont-ils les seuls à pouvoir déposer une demande ?

            Mon futur hébergement est pris en charge par mon entreprise. Quelles sont les démarches à effectuer ?

            Une famille peut-elle faire une demande de logement ?

            Qu'est-ce que le contrat d'occupation ?

            Qu'est-ce que le garant physique ou cautionnement ?

            Quelles conditions doit remplir mon garant physique ou cautionnaire ?

            How to ask question

            Terris civitates civitates quam honorem?

            Une famille peut-elle faire une demande de logement ?

            Qu'est-ce que le contrat d'occupation ?

            Qu'est-ce que le foo ?

```

Fiddle

答:
There are some issues with your selectors.

First off, element_id is set on two different occasions in your code:

```<code>var element_id = $(".faq_cont_right .scroll ul li").filter('[data-target="#item1"]')
...
var element_id = $(this).attr('data-target')
</code>```

The first one returns a jQuery object and the second one returns a string. This means there is no unified way to treat element_id. A suggestion would be to name the jQuery object $element_id and the string element_id to have them separated.

Secondly, the data attributes in your markup hold values like #item11. This means the jQuery selector $(element_id) will equal e.g. $('#item11'), trying to select an item with id="item11". None of the elements in your markup, however, have IDs set and thus the selector will return undefined.

With your current markup you can try to use a selector like $('[data-target="'+element_id+'"]') to target the elements by their data attributes, although why not skip the data-target attribute and simply go for an ID?

I also suggest you prevent the scrolling animation from building a queue when the user types fast, as this will scroll the results back and forth. Do this by adding .stop() like this: $('.scroll').stop().animate({ //... }).

I've put together an example with my suggestions above. This does not fix up all of your code (now where's the fun in that? :o), but hopefully this will get you somewhere along the right path. Might need some more tweaking, but at least the errors should be gone.

Title: Can't scroll to element by attribute

Body:
I have a a search form which searches words inside a UL LI element. when there is a result - i want it to be scrolled by the result's attribute position (data-target).

I can't get the LI's position by it's attribute, and therefor - can't navigate to it.

I get "Cannot read property 'top' of undefined" when i try to get the position of the element_id variable :

$(".faq_cont_right .scroll ul li").each(function() {
    if ($(this).text().search(new RegExp(filter, "i")) < 0) {
        var element_id = $(".faq_cont_right .scroll ul li").filter('[data-target="#item1"]');
        $('.scroll').animate({
            scrollTop: $(element_id).position().top - 500,
        }, 200);
    } else {
        $(this).show();
        $(this).trigger('click');
        var element_id = $(this).attr('data-target');
        var scroller = $('.scroll').offset().top;
        console.log($(element_id).offset().top); // error

        $('.scroll').animate({
            scrollTop: $(element_id).offset().top - scroller,
        }, 200);
    }
});

/**
 * Created by Roy Barak on 22-Oct-17.
 */
$(document).ready(function() {

  $('.questions_header').text($(".active_search").text());

  $('.question_div').on('shown.bs.tab', function() {

    $('.questions_header').text($(this).text());

  });

  $('#faq_chat_btn').on('click', function() {

    $(this).toggleClass('faq_chat_off faq_chat_on');
    if ($(this).hasClass("faq_chat_off")) {
      $('.faq_chat_header_left p').text('fermé');
      $('.faq_chat_middle').hide();
    }
    if ($(this).hasClass("faq_chat_on")) {

      $('.faq_chat_header_left p').text('ouvert');
      $('.faq_chat_middle').show();
    }

  });

  $('#faq_search').bind('keydown', 'keyup', function(event) {
    if (event.keyCode == 13) {
      event.preventDefault();

    }

    var filter = $(this).val();

    if (filter.length && filter !== null && filter !== '') {

      $(".faq_cont_right .scroll ul li").each(function() {

        if ($(this).text().search(new RegExp(filter, "i")) < 0) {

          var element_id = $(".faq_cont_right .scroll ul li").filter('[data-target="#item1"]');

          $('.scroll').animate({
            scrollTop: $(element_id).position().top - 500,
          }, 200);

        } else {

          $(this).show();

          $(this).trigger('click');
          var element_id = $(this).attr('data-target');
          var scroller = $('.scroll').offset().top;

          console.log($(element_id).offset().top);

          $('.scroll').animate({
            scrollTop: $(element_id).offset().top - scroller,
          }, 200);

        }
      });
      $(".tab-content>.active").each(function() {

        if ($(this).text().search(new RegExp(filter, "i")) < 0) {

          $(this).show();

        } else {

          $(this).show();

        }
      });

    }

  });

  $(".faq_cont_right .scroll ul li").on('click', function(e) {

    $(".faq_cont_right .scroll ul li").removeClass('active_search');
    $(this).toggleClass('active_search');

    e.preventDefault();

  });
});

/* Styles go here */

#faq_page .page_container {
  height: 100vh;
}

.faq_cont_right {
  float: left;
  width: 33.33333333%;
}

.scroll {
  width: 100%;
  height: 88vh;
  overflow-y: scroll;
  overflow-x: hidden;
}

.faq_cont_left .tab-content {
  padding: 15px!important;
}

.faq_tab_content {
  height: 88%;
}

.faq_question_header {
  padding: 15px;
  height: 12%;
  display: flex;
  align-items: center;
}

.faq_question_header p {
  margin: 0!important;
}

.questions_header {
  font-family: 'Roboto', sans-serif;
  color: #5d3c95;
  font-size: 1rem;
  text-transform: uppercase;
}

.answer_content {
  font-family: 'Roboto', sans-serif;
  color: #48484a;
  font-size: 1rem;
}

.search_bar {
  background-color: #fff;
  border-right: 2px solid #e9e9e9;
  border-left: 2px solid #e9e9e9;
  height: 12vh;
  display: flex;
  align-items: center;
  padding: 0 10px 0 20px;
}

.faq_search_form input {
  margin-left: 10px;
  outline: none;
  border: none;
  font-size: 11px;
}

form.faq_search_form {
  display: flex;
  align-items: center;
}

input.input_search::-webkit-input-placeholder {
  font-family: 'Roboto', sans-serif;
  font-size: 12px;
  color: #767678;
}

input.input_search::-moz-placeholder {
  font-family: 'Roboto', sans-serif;
  font-size: 12px;
  color: #767678;
}

input.input_search:-ms-input-placeholder {
  font-family: 'Roboto', sans-serif;
  font-size: 12px;
  color: #767678;
}

input.input_search {
  padding: 0 !important;
}

form.faq_search_form i:before {
  content: "\f002";
  font-size: 2vw;
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  text-decoration: inherit;
  color: #767678;
}

.faq_cont_left {
  height: 100vh;
  background-color: white;
  float: left;
  width: 66.66666667%;
}

.faq_questions {
  padding: 0;
  width: 100%;
  list-style: none;
  margin-top: 0 !important;
  margin-bottom: 0px !important;
}

.faq_questions li:hover {
  font-weight: 600;
}

.question_div {
  font-family: 'Roboto', sans-serif;
  font-size: 11px;
  background-color: #e9e9e9;
  display: flex;
  align-items: center;
  height: 80px;
  justify-content: center;
}

.questions_border {
  height: 100%;
  border-bottom: 0.5px solid white;
  display: flex;
  align-items: center;
  width: 70%;
}

.questions_cont p {
  margin: 0;
}

.questions_cont {
  /*padding-left: 22px;*/
  /*padding-right: 55px;*/
}

.question_div {
  position: relative;
  z-index: 10000;
}

.active_search {
  font-weight: 600;
  background-color: #5d3c95;
  color: white;
}

.scroll::-webkit-scrollbar-track {
  background-color: #F5F5F5;
}

.scroll::-webkit-scrollbar {
  width: 7px;
  background-color: #d8d8d8;
}

.scroll::-webkit-scrollbar-thumb {
  background-color: #bebebe;
  border: none;
}

/*-------------chat---------------*/

.faq_chat_box {
  width: 66.66666667%;
  background-color: #d3f2f1;
  position: absolute;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  right: 0;
  padding: 20px;
}

.faq_chat_box_wrap {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.faq_chat_header {
  padding: 15px 20px 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #5d3c95;
  color: #fff;
}

.faq_chat_header_right img {
  width: 11%;
}

.faq_chat_header_right span {
  font-family: 'Roboto', sans-serif;
  font-size: 1.3rem;
  color: #fff;
  padding: 10px;
  margin: 0 !important;
  font-weight: 300;
}

.faq_chat_header_left p {
  font-family: 'Montserrat Semi Bold', sans-serif;
  font-size: 11px;
  color: #fff;
  padding: 10px;
  margin: 0 !important;
}

.faq_chat_middle {
  width: 100%;
  background-color: #fff;
  padding: 10px;
}

.chat_text {
  font-family: 'Roboto', sans-serif;
  font-size: 1.3rem;
  color: #48484a;
}

.chat_parme_text {
  margin-bottom: 15px;
}

.chat_parme_text_header {
  font-family: 'Roboto', sans-serif;
  font-size: 1.3rem;
  color: #5d3c95;
}

.chat_client_text_header {
  font-family: 'Roboto', sans-serif;
  font-size: 1.3rem;
  color: #41c8c2;
}

#faq_chat_btn:hover {
  cursor: pointer;
  cursor: hand;
}

.faq_chat_footer {
  padding: 18px;
  background-color: #41c8c2;
}

.faq_chat_middle .scroll {
  height: 20vh;
  width: 100%;
  overflow-y: scroll;
  overflow-x: hidden;
}

.faq_chat_icon {
  position: relative;
}

.faq_chat_header_left {
  display: flex;
  align-items: center;
}

.faq_chat_status i {
  font-size: 18px;
}

.faq_chat_on {
  color: #41c8c2;
}

.faq_chat_off {
  color: #ff4444;
}

.input-icon {
  position: absolute;
  color: #41c8c2;
  right: 17px;
  font-size: 18px;
  top: calc(50% - 0.5em);
  /* Keep icon in center of input, regardless of the input height */
}

input#faq_chat {
  border-radius: 5px;
  outline: none;
  border: none;
}

.input-wrapper {
  position: relative;
}

    <form class="faq_search_form">
      <input class="form-control input_search" placeholder="Rechercher une question..." name="faq_search" id="faq_search" type="text" autocomplete="off">
    </form>

            Les salariés SNCF en activité sont-ils les seuls à pouvoir déposer une demande ?

            Mon futur hébergement est pris en charge par mon entreprise. Quelles sont les démarches à effectuer ?

            Une famille peut-elle faire une demande de logement ?

            Qu'est-ce que le contrat d'occupation ?

            Qu'est-ce que le garant physique ou cautionnement ?

            Quelles conditions doit remplir mon garant physique ou cautionnaire ?

            How to ask question

            Terris civitates civitates quam honorem?

            Une famille peut-elle faire une demande de logement ?

            Qu'est-ce que le contrat d'occupation ?

            Qu'est-ce que le foo ?

Fiddle

Body:
There are some issues with your selectors.

First off, element_id is set on two different occasions in your code:

var element_id = $(".faq_cont_right .scroll ul li").filter('[data-target="#item1"]')
...
var element_id = $(this).attr('data-target')

The first one returns a jQuery object and the second one returns a string. This means there is no unified way to treat element_id. A suggestion would be to name the jQuery object $element_id and the string element_id to have them separated.

Secondly, the data attributes in your markup hold values like #item11. This means the jQuery selector $(element_id) will equal e.g. $('#item11'), trying to select an item with id="item11". None of the elements in your markup, however, have IDs set and thus the selector will return undefined.

With your current markup you can try to use a selector like $('[data-target="'+element_id+'"]') to target the elements by their data attributes, although why not skip the data-target attribute and simply go for an ID?

I also suggest you prevent the scrolling animation from building a queue when the user types fast, as this will scroll the results back and forth. Do this by adding .stop() like this: $('.scroll').stop().animate({ //... }).

I've put together an example with my suggestions above. This does not fix up all of your code (now where's the fun in that? :o), but hopefully this will get you somewhere along the right path. Might need some more tweaking, but at least the errors should be gone.


问:
Pandoc - Can you change margins and fontsize simultaneously?
Sample Markdown used as a Reproducible Example (GitHub hyperlink)

I pasted the markdown from the hyperlink above into the Atom text editor and saved it as a documentation.md file. I can run the following two seperate Pandoc commands and each of them works to reduce the margins on my pdf -and- increase the font size to 12 on the output pdf.

pandoc -s -V documentation.md geometry:margin=1in -o documentation.pdf

pandoc -s -V documentation.md fontsize=12 -o documentation.pdf

When I combine the two commands into the following I get the error shown below. Is there a problem in my Pandoc syntax?

pandoc -s -V documentation.md geometry:margin=1in fontsize=12 -o documentation.pdf

pandoc geometry:margin=1in openBinaryFile: does not exist (No such file or
  directory)

答:
Try this:

```<code>pandoc documentation.md -V geometry:margin=1in -V fontsize:12pt -s -o documentation.pdf
</code>```

Pandoc's FAQs state:

How do I change the margins in PDF output?

The option

```<code>-V geometry:margin=1in
</code>```

will set the margins to one inch on each side.

Note that geometry:margin=1in is the value of the -V flag. However, you have the filename documentation.md between the flag and its value. Therefore, you are causing the value of the flag to be documentation.md and geometry:margin=1in is assumed to be a filename. After all, any string of text no preceded by a flag should be a filename (which explains the "No such file or directory" error).

By way of explanation, the documentation for the -V flag gives this format:

```<code>-V KEY[:VAL]
</code>```

Note that the brackets in [:VAL] indicate that that part is optional. So -V KEY is completely valid with no value, which means that -V documentation.md resulted in documentation.md being the KEY of the -V flag (with a default VAL of true as per the docs).

Admittedly, -V geometry:margin=1in is an especially weird case and its easy to see how one might be confused by it. In this case however, -V is the flag, geometry is the "KEY" and margin=1in is the "VAL". I realize that margin=1in looks like a KEY=VAL, but in this instance it is all a "VAL" on its own. Presumably, Pandoc does some further processing on it later to break the "VAL" up into its parts.

Of course, fontsize is another variable, so you need a second -V flag to define that variable: -V fontsize:12pt.

Finally, the -s flag does not accept a value, so I moved it so that that is clear.

Body:
Try this:

pandoc documentation.md -V geometry:margin=1in -V fontsize:12pt -s -o documentation.pdf

Pandoc's FAQs state:

How do I change the margins in PDF output?

The option

-V geometry:margin=1in

will set the margins to one inch on each side.

Note that geometry:margin=1in is the value of the -V flag. However, you have the filename documentation.md between the flag and its value. Therefore, you are causing the value of the flag to be documentation.md and geometry:margin=1in is assumed to be a filename. After all, any string of text no preceded by a flag should be a filename (which explains the "No such file or directory" error).

By way of explanation, the documentation for the -V flag gives this format:

-V KEY[:VAL]

Note that the brackets in [:VAL] indicate that that part is optional. So -V KEY is completely valid with no value, which means that -V documentation.md resulted in documentation.md being the KEY of the -V flag (with a default VAL of true as per the docs).

Admittedly, -V geometry:margin=1in is an especially weird case and its easy to see how one might be confused by it. In this case however, -V is the flag, geometry is the "KEY" and margin=1in is the "VAL". I realize that margin=1in looks like a KEY=VAL, but in this instance it is all a "VAL" on its own. Presumably, Pandoc does some further processing on it later to break the "VAL" up into its parts.

Of course, fontsize is another variable, so you need a second -V flag to define that variable: -V fontsize:12pt.

Finally, the -s flag does not accept a value, so I moved it so that that is clear.


问:
Close qemu from a process in xv6
I started learning xv6 recently and was trying to implement a shutdown mechanism in xv6 and i was able to kill all the process running gracefully and wait for some of them to finish and then terminate them. But i am not able to close qemu from the shutdown process.

Could someone suggest how to close qemu from a a xv6 process?

I googled and found out someone used 'outb' and 'outw' commands but both of them don't work.

答: In QEMU, "exit the QEMU process" happens when the guest powers down the emulated hardware. So your guest OS 'shutdown' needs to work by doing the correct hardware operations to power down. (How that is done depends on what hardware QEMU is emulating -- for instance some Arm boards don't have any mechanism for software controlled powerdown at all. Check the documentation for the relevant hardware.)</p>

Title: Close qemu from a process in xv6


问:
Django: how to stay DRY using custom querysets with Q object?
In the custom queryset example bellow, the displayable method uses a combination of permanent and scheduled method. It works, but as you can see, I'm repeating myself:

```<code>class ArticlesByCategoryQuerySet(models.QuerySet):
    def permanent(self):
        return self.filter(is_permanent=True)

    def scheduled(self, service):
        return self.filter(scheduled_services__in=[service])

    def displayable(self, service):
        complex_query = Q(is_permanent=True) | Q(scheduled_services__in=[service])
        return self.filter(complex_query)
</code>```

What is the correct syntax to use Q() and stay DRY? I didn't find such an example in Django documentation.
I tried something like that, but it raises a ValueError: too many values to unpack (expected 2):

```<code>def displayable(self, service):
    complex_query = Q(self.permanent()) | Q(self.scheduled(service))
    return self.filter(complex_query)
</code>```

Thanks for your help.

答:
Could you store your Q objects in a method like so:</p>

```<code>class ArticlesByCategoryQuerySet(models.QuerySet):
    def objects(self, service=None):
        return {
            'permanent': {
                'is_permanent': True,
            },
            'scheduled': {
                'scheduled_services__in': [service],
            },
        }

    def permanent(self):
        return self.filter(**self.objects(service)['permanent'])

    def scheduled(self, service):
        return self.filter(**self.objects(service)['scheduled'])

    def displayable(self, service):
        complex_query = Q(**self.objects(service)['permanent']) | Q(**self.objects(service)['scheduled'])
        return self.filter(complex_query)
</code>```

Body:
In the custom queryset example bellow, the displayable method uses a combination of permanent and scheduled method. It works, but as you can see, I'm repeating myself:

class ArticlesByCategoryQuerySet(models.QuerySet):
    def permanent(self):
        return self.filter(is_permanent=True)

    def scheduled(self, service):
        return self.filter(scheduled_services__in=[service])

    def displayable(self, service):
        complex_query = Q(is_permanent=True) | Q(scheduled_services__in=[service])
        return self.filter(complex_query)

What is the correct syntax to use Q() and stay DRY? I didn't find such an example in Django documentation.
I tried something like that, but it raises a ValueError: too many values to unpack (expected 2):

def displayable(self, service):
    complex_query = Q(self.permanent()) | Q(self.scheduled(service))
    return self.filter(complex_query)

Thanks for your help.

Body:
Could you store your Q objects in a method like so:

class ArticlesByCategoryQuerySet(models.QuerySet):
    def objects(self, service=None):
        return {
            'permanent': {
                'is_permanent': True,
            },
            'scheduled': {
                'scheduled_services__in': [service],
            },
        }

    def permanent(self):
        return self.filter(**self.objects(service)['permanent'])

    def scheduled(self, service):
        return self.filter(**self.objects(service)['scheduled'])

    def displayable(self, service):
        complex_query = Q(**self.objects(service)['permanent']) | Q(**self.objects(service)['scheduled'])
        return self.filter(complex_query)