问:
java infix expression derivation
I have 2 strings

```<code>String expression = add(,subtract(,));

String values = (3,(10,4));
</code>```

I want to evaluate the expression.. So the output should be like below.

```<code>add(3 , subtract(10,4) )
</code>```

What I tried:  The approach i tried is remove special chars from expression , tokenize and store the function names in an array.. So in above example the array will be having add , subtract.  Then , loop and replace 3 with add(3) and  10,4 with subtract(10,4).  I am getting desired output if I have only 1 or 2 functions.  But if there are multiple nested functions , I am unable to derive the output for expressions like below.

For ex:

```<code> expression= add(subtract(,) , multiply(,))
 value = ( (4,3)  , (2,2) )

output = add( subtract(4,3) , multiply(2,2))
</code>```

答:
You can try the below procedure to achieve your result:

Proposed procedure:

```<code>//base case
1. if count of'(' != count of ')' // unbalanced parenthesis
    print 'Invalid Expression'
    exit the program
2. Store all the operations (like add, subtract, multiply,etc.) from the expressions string.
3. for char ch in values
     replace each occurrence of open parenthesis(() with  stored operation in step 2 along with (.
</code>```

Implementation of the above procedure in java(I recommend you please try your own ways to implement the above procedure. The code can be optimized further):

```<code>import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Main{
// Regex to extract all the operations from the expression string.
    private static final Pattern pattern = Pattern.compile("\\w+");
    public static void main(String[] args){
        String expression = "add(divide(add(,),) , subtract(,))";
        String value = "(((5 , 5), 2),(10,4))";

        StringBuilder sb = new StringBuilder(); // To store the final result.
        Matcher matcher = pattern.matcher(expression);
        ArrayList<String> arr = new ArrayList<>(); //to store all the operations from the expression string.
        if(count(value, '(') != count(value,')')){
            System.out.println("Invalid expression");
            System.exit(0);
        }
        while(matcher.find())
            arr.add(matcher.group(0));
        int counter = 0;
        for(char ch: value.toCharArray()){
            if(ch == '('){
               sb.append(arr.get(counter) + "(");
               // counter only gets incremented if operations get appended to sb
               counter++;
            }
            else sb.append(ch);
        }
        System.out.println(sb.toString());
    }
// utility method to fulfill step 1 of proposed procedure.
    public static int count(String str, char ch){
        int count = 0;
        for(char chr:str.toCharArray()){
            if(chr == ch)count++;
        }
        return count;
    }
}
</code>```

You can find the sample run of the above implementation in here.

Title: java infix expression derivation

Body:
I have 2 strings

String expression = add(,subtract(,));

String values = (3,(10,4));

I want to evaluate the expression.. So the output should be like below.

add(3 , subtract(10,4) )

What I tried:  The approach i tried is remove special chars from expression , tokenize and store the function names in an array.. So in above example the array will be having add , subtract.  Then , loop and replace 3 with add(3) and  10,4 with subtract(10,4).  I am getting desired output if I have only 1 or 2 functions.  But if there are multiple nested functions , I am unable to derive the output for expressions like below.

For ex:

 expression= add(subtract(,) , multiply(,))
 value = ( (4,3)  , (2,2) )

output = add( subtract(4,3) , multiply(2,2))

Body:
You can try the below procedure to achieve your result:

Proposed procedure:

//base case
1. if count of'(' != count of ')' // unbalanced parenthesis
    print 'Invalid Expression'
    exit the program
2. Store all the operations (like add, subtract, multiply,etc.) from the expressions string.
3. for char ch in values
     replace each occurrence of open parenthesis(() with  stored operation in step 2 along with (.

Implementation of the above procedure in java(I recommend you please try your own ways to implement the above procedure. The code can be optimized further):

import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Main{
// Regex to extract all the operations from the expression string.
    private static final Pattern pattern = Pattern.compile("\\w+");
    public static void main(String[] args){
        String expression = "add(divide(add(,),) , subtract(,))";
        String value = "(((5 , 5), 2),(10,4))";

        StringBuilder sb = new StringBuilder(); // To store the final result.
        Matcher matcher = pattern.matcher(expression);
        ArrayList<String> arr = new ArrayList<>(); //to store all the operations from the expression string.
        if(count(value, '(') != count(value,')')){
            System.out.println("Invalid expression");
            System.exit(0);
        }
        while(matcher.find())
            arr.add(matcher.group(0));
        int counter = 0;
        for(char ch: value.toCharArray()){
            if(ch == '('){
               sb.append(arr.get(counter) + "(");
               // counter only gets incremented if operations get appended to sb
               counter++;
            }
            else sb.append(ch);
        }
        System.out.println(sb.toString());
    }
// utility method to fulfill step 1 of proposed procedure.
    public static int count(String str, char ch){
        int count = 0;
        for(char chr:str.toCharArray()){
            if(chr == ch)count++;
        }
        return count;
    }
}

You can find the sample run of the above implementation in here.


来源: stackexchange

问:
How do I open a new PHP page with posted data from a javascript file
I have updated my form:

```<code><form method = "post" name= "account" action= "validated.php" target="_blank">
...
<submit value= "submit" onclick= "validate()" >Submit</submit>
</code>```

It validates correctly from the validate.js file but still does not open a new page for validated.php

In validated.php just to start:

```<code><p>Welcome <?php echo $_GET["fname"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?> and your birthday is: <?php echo $_GET["bdate"]; ?>
</p>
</code>```

I think the issue is in the html. Any ideas?

答:
Your code makes no sense at all.

I am answering the question that had XMLHttpRequest in it

There exists no tag called submit

You have $_GET but you POST your xmlhttprequest

Since you want to open a new page in PHP, just have this (default is GET)

```<code><form name="account" action= "validated.php">
  ...
  <input type="submit" value="Submit" />
</form>
</code>```

BUT if you really want to ajax, you need to change your $_GET to $_POST and do something like this

window.addEventListener("load",function() {
  document.getElementById("account").addEventListener("submit",function(e) {
    e.preventDefault();
    let formData = new FormData();
    formData.append("fname", this.fname.value);
    formData.append("email", this.email.value); // assuming field names here
    formData.append("bdate",this.bdate.value);
    console.log(formData);
    const xhttp = new XMLHttpRequest();
    xhttp.onload=function(response) { console.log(response) }; // or some other process
    xhttp.open("POST", 'validated.php', true);
    xhttp.send(formData);
  });
});
```

<p>using a form with an ID</p>

<pre class="lang-html prettyprint-override"><code><form id="account">
...
  <input type="submit" value="Submit" />
</form>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have updated my form:

<form method = "post" name= "account" action= "validated.php" target="_blank">
...
<submit value= "submit" onclick= "validate()" >Submit</submit>

It validates correctly from the validate.js file but still does not open a new page for validated.php

In validated.php just to start:

Welcome <?php echo $_GET["fname"]; ?>

Your email address is: <?php echo $_GET["email"]; ?> and your birthday is: <?php echo $_GET["bdate"]; ?>

I think the issue is in the html. Any ideas?

Body:
Your code makes no sense at all.

I am answering the question that had XMLHttpRequest in it

There exists no tag called submit

You have $_GET but you POST your xmlhttprequest

Since you want to open a new page in PHP, just have this (default is GET)

<form name="account" action= "validated.php">
  ...
  <input type="submit" value="Submit" />
</form>

BUT if you really want to ajax, you need to change your $_GET to $_POST and do something like this

window.addEventListener("load",function() {
  document.getElementById("account").addEventListener("submit",function(e) {
    e.preventDefault();
    let formData = new FormData();
    formData.append("fname", this.fname.value);
    formData.append("email", this.email.value); // assuming field names here
    formData.append("bdate",this.bdate.value);
    console.log(formData);
    const xhttp = new XMLHttpRequest();
    xhttp.onload=function(response) { console.log(response) }; // or some other process
    xhttp.open("POST", 'validated.php', true);
    xhttp.send(formData);
  });
});

using a form with an ID

<form id="account">
...
  <input type="submit" value="Submit" />
</form>


问:
Java Runtime exec() does not resolve environment variable
If I run the following in a terminal I get the expected 123

```<code>$ /bin/sh
$ FOO=123
$ echo $FOO
123
</code>```

Now I try to do the following with Java's Runtime's exec():

```<code>String[] envp = { "FOO=123" };
String   cmd  = "echo $FOO";
Process  p    = Runtime.getRuntime().exec(cmd, envp);
java.io.BufferedReader reader =
    new java.io.BufferedReader(
        new java.io.InputStreamReader(p.getInputStream()
    )
);
System.out.println(reader.readLine());
</code>```

I expect to see 123 but instead I get $FOO.

What am I missing?

答:
The following works under Windows.</p>

```<code>String[] envp = { "FOO=123" };
String   cmd  = "cmd /c echo %FOO%";
Process  p    = Runtime.getRuntime().exec(cmd, envp);
p.waitFor();
java.io.BufferedReader reader =
    new java.io.BufferedReader(
        new java.io.InputStreamReader(p.getInputStream()
    )
);
String line;
while((line = reader.readLine()) != null) {
    System.out.println(line);
}
</code>```

Body:
If I run the following in a terminal I get the expected 123

$ /bin/sh
$ FOO=123
$ echo $FOO
123

Now I try to do the following with Java's Runtime's exec():

String[] envp = { "FOO=123" };
String   cmd  = "echo $FOO";
Process  p    = Runtime.getRuntime().exec(cmd, envp);
java.io.BufferedReader reader =
    new java.io.BufferedReader(
        new java.io.InputStreamReader(p.getInputStream()
    )
);
System.out.println(reader.readLine());

I expect to see 123 but instead I get $FOO.

What am I missing?

Body:
The following works under Windows.

String[] envp = { "FOO=123" };
String   cmd  = "cmd /c echo %FOO%";
Process  p    = Runtime.getRuntime().exec(cmd, envp);
p.waitFor();
java.io.BufferedReader reader =
    new java.io.BufferedReader(
        new java.io.InputStreamReader(p.getInputStream()
    )
);
String line;
while((line = reader.readLine()) != null) {
    System.out.println(line);
}


问:
Error on PHPhotoLibrary, cannot save video
I am trying to save a video in my photo library. But sometimes I get an error: The operation couldn’t be completed. (PHPhotosErrorDomain error -1.)

This is my code:

```<code>PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: exporter!.outputURL!)
               }) { saved, error in
                   if saved {
                       print("video saved to camera roll")
                   } else {
                    print(error?.localizedDescription)
                }
               }
</code>```

答: I was able to resolve this by removing the AVVideoQualityKey within AVVideoCompressionPropertiesKey in my video output settings for AVAssetWriter.</p>

Body:
I am trying to save a video in my photo library. But sometimes I get an error: The operation couldn’t be completed. (PHPhotosErrorDomain error -1.)

This is my code:

PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: exporter!.outputURL!)
               }) { saved, error in
                   if saved {
                       print("video saved to camera roll")
                   } else {
                    print(error?.localizedDescription)
                }
               }


问:
Class Not Found in PHP Laravel 6.x when another class extends
I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.

However, another child class that is located in same directory could extend class A successfully.

In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.

Please help me on this.
Thanks in an advance.

Parent class: myContext

```<code><?php
namespace config\models;

class myContext {
    public static $conn;
    ...
}
</code>```

Class myUser: extension is fine.

```<code><?php
namespace config\models;

class myUser extends myContext {
   private $name;
   ...
}
</code>```

Class oauth: extension returns myContext class not found.

```<code><?php
namespace config\models;

class oauth extends myContext {
    private $user;
}
</code>```

Instantiate the class - returns class not found.

```<code><?php

use config\models\myContext as context;

$cont = new context();
</code>```

答:
To get the provided example codes to work you need to use require_once

<?php
require_once('models/myContext.php');

use app\config\models\myContext as context;

$test = new context();
```

A search on SO brought me to this source

Body:
I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.

However, another child class that is located in same directory could extend class A successfully.

In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.

Please help me on this.
Thanks in an advance.

Parent class: myContext

<?php
namespace config\models;

class myContext {
    public static $conn;
    ...
}

Class myUser: extension is fine.

<?php
namespace config\models;

class myUser extends myContext {
   private $name;
   ...
}

Class oauth: extension returns myContext class not found.

<?php
namespace config\models;

class oauth extends myContext {
    private $user;
}

Instantiate the class - returns class not found.

<?php

use config\models\myContext as context;

$cont = new context();

Body:
To get the provided example codes to work you need to use require_once

<?php
require_once('models/myContext.php');

use app\config\models\myContext as context;

$test = new context();

A search on SO brought me to this source


问:
How to remove border bottom width in ant design modal header
I'm building web app with Ant Design Vue.

I would like to know how to remove bottom-width in the header of .

This is the screenshot of what I would like to.

This is my code.

```<code><template>
  <a-modal width="1000px" title="demo">
    Hi, Modal
  </a-modal>
</template>

<script>
:

</script>

<style lang="less" scoped>
.ant-modal-header {
  border-bottom-width: 0;
}
</style>
</code>```

I know the class ant-modal-header defines border-bottom-width in Chrome Developer Tool.

So I defined new ant-modal-header in

答:
You can use wrapClassName prop to give class to this specific modal container, and once you give class name to container you can target it but scoped style won't work here because classes are assigned in your current component

so something like this should work.

<template>

    Hi, Modal

</template>

```

Body:
I'm building web app with Ant Design Vue.

I would like to know how to remove bottom-width in the header of .

This is the screenshot of what I would like to.

This is my code.

<template>

    Hi, Modal

</template>

I know the class ant-modal-header defines border-bottom-width in Chrome Developer Tool.

So I defined new ant-modal-header in

Body:
You can use wrapClassName prop to give class to this specific modal container, and once you give class name to container you can target it but scoped style won't work here because classes are assigned in your current component

so something like this should work.

<template>
  <a-modal width="1000px" wrap-class-name="my-special-modal" title="demo">
    Hi, Modal
  </a-modal>
</template>

<script>
:

</script>

<style lang="less">
.my-special-modal {
  .ant-modal-header {
    border-bottom-width: 0;
  }
}
</style>


问:
"Un-melt" Dataframe and keep rest of columns? Python Pandas
I have a table in this format, which I would like to transform with the "opposite" of melting. There is another question that addresses this but it doesn't work with so many other columns that I'd like to keep.

The original:

```<code>COUNTRY   STATE     CATEGORY   RESTAURANT         STARS     REVIEWS
US        Texas     NaN        Texas Chicken      4.1       1,157
US        Texas     Spicy      Texas Chicken      4.1       1,157
US        Ohio      NaN        Mamas Shop         3.6       700
US        Ohio      NaN        Pizza Hut          4.5       855
US        Ohio      Pizza      Pizza Hut          4.5       855
</code>```

The desired output:

```<code>COUNTRY   STATE     RESTAURANT        STARS    REVIEWS  SPICY   PIZZA
US        Texas     Texas Chicken     4.1      1,157    1       0
US        Ohio      Mamas Shop        3.6      700      0       0
US        Ohio      Pizza Hut         4.5      855      0       1
</code>```

Essentially I would like to "group by" many columns, while creating extra columns based on the categories in the Category column. Restaurants that do not have any particular category would have the value 0 for all these additional columns. I also do not want any extra layers of columns as I am intending to write all of it to JSON.

Would appreciate any help on this and thank you in advance!

答:
A combination of set_index, crosstab and reindex can 'unmelt' the dataframe, and take care of the null values present in the dataframe:</p>

```<code>#set aside required multiindex of country, state, restaurant, stars, and reviews
ind = df.set_index(['COUNTRY','STATE','RESTAURANT','STARS','REVIEWS']).index

#get frequency count for Pizza and Spicy
res = pd.crosstab([df.COUNTRY,df.STATE,df.RESTAURANT,df.STARS,df.REVIEWS],df.CATEGORY)

#reindex frequency dataframe with ind
res = res.reindex(ind,fill_value=0).drop_duplicates()
res

                CATEGORY                    Pizza   Spicy
COUNTRY STATE   RESTAURANT     STARS  REVIEWS
 US     Texas   Texas Chicken   4.1    1,157    0   1
        Ohio    Mamas Shop      3.6    700      0   0
                Pizza Hut       4.5    855      1   0
</code>```

Body:
I have a table in this format, which I would like to transform with the "opposite" of melting. There is another question that addresses this but it doesn't work with so many other columns that I'd like to keep.

The original:

COUNTRY   STATE     CATEGORY   RESTAURANT         STARS     REVIEWS
US        Texas     NaN        Texas Chicken      4.1       1,157
US        Texas     Spicy      Texas Chicken      4.1       1,157
US        Ohio      NaN        Mamas Shop         3.6       700
US        Ohio      NaN        Pizza Hut          4.5       855
US        Ohio      Pizza      Pizza Hut          4.5       855

The desired output:

COUNTRY   STATE     RESTAURANT        STARS    REVIEWS  SPICY   PIZZA
US        Texas     Texas Chicken     4.1      1,157    1       0
US        Ohio      Mamas Shop        3.6      700      0       0
US        Ohio      Pizza Hut         4.5      855      0       1

Essentially I would like to "group by" many columns, while creating extra columns based on the categories in the Category column. Restaurants that do not have any particular category would have the value 0 for all these additional columns. I also do not want any extra layers of columns as I am intending to write all of it to JSON.

Would appreciate any help on this and thank you in advance!

Body:
A combination of set_index, crosstab and reindex can 'unmelt' the dataframe, and take care of the null values present in the dataframe:

#set aside required multiindex of country, state, restaurant, stars, and reviews
ind = df.set_index(['COUNTRY','STATE','RESTAURANT','STARS','REVIEWS']).index

#get frequency count for Pizza and Spicy
res = pd.crosstab([df.COUNTRY,df.STATE,df.RESTAURANT,df.STARS,df.REVIEWS],df.CATEGORY)

#reindex frequency dataframe with ind
res = res.reindex(ind,fill_value=0).drop_duplicates()
res

                CATEGORY                    Pizza   Spicy
COUNTRY STATE   RESTAURANT     STARS  REVIEWS
 US     Texas   Texas Chicken   4.1    1,157    0   1
        Ohio    Mamas Shop      3.6    700      0   0
                Pizza Hut       4.5    855      1   0


问:
How to do product sorting when we search for certain product in Django?
views.py:-

```<code>def search(request):
global pro
global products
if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2':
    q = request.GET.get("q")
    products = Product.objects.filter(active=True, name__icontains=q)
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
                "brands": brands,
                "title": q + " - search"}
    return render(request, "shop/home.html", context)
pro = products

if request.GET.get('price_filter') == '1':
    products = pro.order_by('price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

elif request.GET.get('price_filter') == '2':
    products = pro.order_by('-price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)
</code>```

In HTML:-

```<code><form method='get' action='#' style="margin-top:-20px; margin-left: 8px;">
        <input class="btn btn-outline-dark" type="checkbox" value="1" name="price_filter"/>Low to High

        <input class="btn btn-outline-dark" type="checkbox" value="2" name="price_filter"/>High to Low
        <button class="btn" type="submit" value="Sort">Sort</button>
    </form>
</code>```

Using that search we I am able to sort low to high, but when I choose High to Low, it shows certain Error:-

```<code>Cannot use None as a query value
</code>```

I know this is not the right method to do this, but can please help me out with this, or guide me with the correct way to do sorting.

答:
you should try code as i give

```<code>def search(request):
    price_filter = request.GET.get('price_filter',None)
    context = {}
    if price_filter not in '12':
        q = request.GET.get("q")
        products = Product.objects.filter(active=True, name__icontains=q)
        context = {"title": q + " - search"}

    if price_filter == '1':
        pro = Product.objects.filter(active=True, name__icontains=q) if request.GET.get("q",None) else  Product.objects.filter(active=True)
        products = pro.order_by('price')

    elif price_filter == '2':
        pro = Product.objects.filter(active=True, name__icontains=q) if request.GET.get("q",None) else  Product.objects.filter(active=True)
        products = pro.order_by('-price')

    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context =context.update({"products": products,
                   "categories": categories,
                    "brands": brands})
    return render(request, "shop/home.html", context)
</code>```

If any problem face or work this stuff then let me know

Body:
views.py:-

def search(request):
global pro
global products
if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2':
    q = request.GET.get("q")
    products = Product.objects.filter(active=True, name__icontains=q)
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
                "brands": brands,
                "title": q + " - search"}
    return render(request, "shop/home.html", context)
pro = products

if request.GET.get('price_filter') == '1':
    products = pro.order_by('price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

elif request.GET.get('price_filter') == '2':
    products = pro.order_by('-price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

In HTML:-

<form method='get' action='#' style="margin-top:-20px; margin-left: 8px;">
        <input class="btn btn-outline-dark" type="checkbox" value="1" name="price_filter"/>Low to High

        <input class="btn btn-outline-dark" type="checkbox" value="2" name="price_filter"/>High to Low
        <button class="btn" type="submit" value="Sort">Sort</button>
    </form>

Using that search we I am able to sort low to high, but when I choose High to Low, it shows certain Error:-

Cannot use None as a query value

I know this is not the right method to do this, but can please help me out with this, or guide me with the correct way to do sorting.

Body:
you should try code as i give

def search(request):
    price_filter = request.GET.get('price_filter',None)
    context = {}
    if price_filter not in '12':
        q = request.GET.get("q")
        products = Product.objects.filter(active=True, name__icontains=q)
        context = {"title": q + " - search"}

    if price_filter == '1':
        pro = Product.objects.filter(active=True, name__icontains=q) if request.GET.get("q",None) else  Product.objects.filter(active=True)
        products = pro.order_by('price')

    elif price_filter == '2':
        pro = Product.objects.filter(active=True, name__icontains=q) if request.GET.get("q",None) else  Product.objects.filter(active=True)
        products = pro.order_by('-price')

    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context =context.update({"products": products,
                   "categories": categories,
                    "brands": brands})
    return render(request, "shop/home.html", context)

If any problem face or work this stuff then let me know


问:
How to avoid CORS origin error with docker and elastic search image
I contrived to bypass the CORS origin error client side by setting up an apache web server with docker so as to use modules. Nevertheless, when I add elasticsearch service to my docker-compose and I try to get my json response from it I still have it. It says "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9200/"

my docker-compose :

version: '2'

services:
  apache:
    image: 'bitnami/apache:latest'
    ports:
      - '80:8080'
      - '443:8443'
    volumes:
      - .:/app
  es01:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.7.0
    container_name: es01
    environment:
      - node.name=es01
      - cluster.name=es-docker-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - data01:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
    networks:
      - elastic

volumes:
  data01:
    driver: local

networks:
  elastic:
    driver: bridge
```
<p>my index.html:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>

<div class="home">
    <h5>Elastic home</h5>
    <p> Cluster name:</p>
    <p id="cluster_name"></p>
    <p> Cluster version: </p>
    <p id="cluster_version"></p>
</div>

<link rel="stylesheet" href="style.css">
<script type="application/javascript">
    fetch('http://localhost:9200')
        .then(async (response) => {
            let data = await response.json()
            document.getElementById('cluster_name').innerText = data.cluster_name
            document.getElementById('cluster_version').innerText = data.version.number
        })
</script>
</body>
</html>
</code>```

答:
I found out how, I changed my environment elastic service to</p>

```<code>   environment:
     - discovery.type=single-node
     - node.name=es01
     - cluster.name=es-docker-cluster
     - bootstrap.memory_lock=true
     - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
     - http.host=0.0.0.0
     - http.port=9200
     - "http.cors.allow-origin=http://localhost"
     - "http.cors.enabled=true"
     - "http.cors.allow-headers=X-Requested-With,X-Auth-Token,Content-Type,Content-Length,Authorization"
     - "http.cors.allow-credentials=true"

</code>```

Body:
I contrived to bypass the CORS origin error client side by setting up an apache web server with docker so as to use modules. Nevertheless, when I add elasticsearch service to my docker-compose and I try to get my json response from it I still have it. It says "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9200/"

my docker-compose :

version: '2'

services:
  apache:
    image: 'bitnami/apache:latest'
    ports:
      - '80:8080'
      - '443:8443'
    volumes:
      - .:/app
  es01:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.7.0
    container_name: es01
    environment:
      - node.name=es01
      - cluster.name=es-docker-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - data01:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
    networks:
      - elastic

volumes:
  data01:
    driver: local

networks:
  elastic:
    driver: bridge

my index.html:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Home</title>

Elastic home

 Cluster name:

 Cluster version:

<link rel="stylesheet" href="style.css">

Body:
I found out how, I changed my environment elastic service to

   environment:
     - discovery.type=single-node
     - node.name=es01
     - cluster.name=es-docker-cluster
     - bootstrap.memory_lock=true
     - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
     - http.host=0.0.0.0
     - http.port=9200
     - "http.cors.allow-origin=http://localhost"
     - "http.cors.enabled=true"
     - "http.cors.allow-headers=X-Requested-With,X-Auth-Token,Content-Type,Content-Length,Authorization"
     - "http.cors.allow-credentials=true"


问:
MSVC2015 not detected when installed via 2019 build tools
I am trying to create a windows docker container for a VS2015 C++ build. I found some documentation how to install build tools in a container and it works for VS2017.

However, when trying to setup the 2015 version, MSBuild.exe complains that it cannot find v140 and despite adding --add Microsoft.VisualStudio.Component.VC.v140 to the vs_buildtools.exe call. I also was not able to find any v140 cl.exe in any of the subfolders.

Obviously, GUI based solutions like this are not an option.

Here is my changed Dockerfile:

```<code># escape=`

# Use the latest Windows Server Core image with .NET Framework 4.8.
FROM mcr.microsoft.com/windows/servercore:1903

# Restore the default Windows shell for correct batch processing.
SHELL ["cmd", "/S", "/C"]
ARG BUILD_TOOLS_VERSION=16

# Download the Build Tools bootstrapper.
ADD https://aka.ms/vs/${BUILD_TOOLS_VERSION}/release/vs_buildtools.exe C:\TEMP\vs_buildtools.exe

RUN C:\TEMP\vs_buildtools.exe --quiet --wait --norestart --nocache `
    --installPath C:\BuildTools `
    --add Microsoft.VisualStudio.Workload.VCTools `
    --add Microsoft.VisualStudio.Component.VC.CLI.Support `
    --add Microsoft.VisualStudio.Component.VC.v140 `
    --add Microsoft.VisualStudio.Component.Windows10SDK.18362 `
    --add Microsoft.VisualStudio.Component.VC.CMake.Project `
 || IF "%ERRORLEVEL%"=="3010" EXIT 0

# put MSBuild.exe on PATH
RUN setx path "%path%;C:\BuildTools\MSBuild\Current\Bin"

# Define the entry point for the docker container.
# This entry point starts the developer command prompt and launches the PowerShell shell.
ENTRYPOINT ["C:\\BuildTools\\Common7\\Tools\\VsDevCmd.bat", "&&", "powershell.exe", "-NoLogo", "-ExecutionPolicy", "Bypass"]
</code>```

答:
MSVC2015 not detected when installed via 2019 build tools

Build Tool for VS2019 can install v140 build tool for VS2015 so far.

The main issue is that you use the wrong Component ID for v140 build tool.

As this document said, you should use

Microsoft.VisualStudio.Component.VC.140.

Solution

Use this:

--add Microsoft.VisualStudio.Component.VC.140 rather than --add Microsoft.VisualStudio.Component.VC.v140.

Body:
I am trying to create a windows docker container for a VS2015 C++ build. I found some documentation how to install build tools in a container and it works for VS2017.

However, when trying to setup the 2015 version, MSBuild.exe complains that it cannot find v140 and despite adding --add Microsoft.VisualStudio.Component.VC.v140 to the vs_buildtools.exe call. I also was not able to find any v140 cl.exe in any of the subfolders.

Obviously, GUI based solutions like this are not an option.

Here is my changed Dockerfile:

# escape=`

# Use the latest Windows Server Core image with .NET Framework 4.8.
FROM mcr.microsoft.com/windows/servercore:1903

# Restore the default Windows shell for correct batch processing.
SHELL ["cmd", "/S", "/C"]
ARG BUILD_TOOLS_VERSION=16

# Download the Build Tools bootstrapper.
ADD https://aka.ms/vs/${BUILD_TOOLS_VERSION}/release/vs_buildtools.exe C:\TEMP\vs_buildtools.exe

RUN C:\TEMP\vs_buildtools.exe --quiet --wait --norestart --nocache `
    --installPath C:\BuildTools `
    --add Microsoft.VisualStudio.Workload.VCTools `
    --add Microsoft.VisualStudio.Component.VC.CLI.Support `
    --add Microsoft.VisualStudio.Component.VC.v140 `
    --add Microsoft.VisualStudio.Component.Windows10SDK.18362 `
    --add Microsoft.VisualStudio.Component.VC.CMake.Project `
 || IF "%ERRORLEVEL%"=="3010" EXIT 0

# put MSBuild.exe on PATH
RUN setx path "%path%;C:\BuildTools\MSBuild\Current\Bin"

# Define the entry point for the docker container.
# This entry point starts the developer command prompt and launches the PowerShell shell.
ENTRYPOINT ["C:\\BuildTools\\Common7\\Tools\\VsDevCmd.bat", "&&", "powershell.exe", "-NoLogo", "-ExecutionPolicy", "Bypass"]


问:
Search returns an empty array
```<code>router.get('/direcciones', isAuthenticated, async (req, res) => {
    let id = req.user._id
    let id2 = id.toString()
    await Dir.find({
        uid: {
            $elemMatch: { _id: id2}
        }
        },  async (err, dir) => {
            console.log(dir);
            res.render('direcciones', {dir: dir, id: id})
    });
});
</code>```

When I search by ID I don't get any results.

```<code>_id:ObjectId("5ed71f27e391a332b8f4aea8")
active:true
dir:"asdasd, Pariahuanca, Los Olivos, Peru"
dirname:"aeds"
uid:Object
   _id:ObjectId("5ed6ef2251c32527a03bf1ca")
__v:0
</code>```

This is the Schema.

What should I do?

答:
$elemMatch operators are used to match inside an array. In your case, it looks like an object, not an array so can use dot notation to match field in a embedded document. uuid._id is of type ObjectId, so need to cast it to ObjectId before querying. Also, you don't need to use callback when using await

```<code>try {
  const result = await Dir.find({ "uuid._id": mongoose.Types.ObjectId(id2) });
  // handle response
} catch (err) {
  // handle failure response
}
</code>```

Title: Search returns an empty array

Body:
router.get('/direcciones', isAuthenticated, async (req, res) => {
    let id = req.user._id
    let id2 = id.toString()
    await Dir.find({
        uid: {
            $elemMatch: { _id: id2}
        }
        },  async (err, dir) => {
            console.log(dir);
            res.render('direcciones', {dir: dir, id: id})
    });
});

When I search by ID I don't get any results.

_id:ObjectId("5ed71f27e391a332b8f4aea8")
active:true
dir:"asdasd, Pariahuanca, Los Olivos, Peru"
dirname:"aeds"
uid:Object
   _id:ObjectId("5ed6ef2251c32527a03bf1ca")
__v:0

This is the Schema.

What should I do?

Body:
$elemMatch operators are used to match inside an array. In your case, it looks like an object, not an array so can use dot notation to match field in a embedded document. uuid._id is of type ObjectId, so need to cast it to ObjectId before querying. Also, you don't need to use callback when using await

try {
  const result = await Dir.find({ "uuid._id": mongoose.Types.ObjectId(id2) });
  // handle response
} catch (err) {
  // handle failure response
}


问:
RxJava: how to do a second api call if first is successful and then create a combinded response
This is what I want to do:

call first rest API

if first succeeds call seconds rest API

if both are successful -> create an aggregated response

I'm using RxJava2 in Micronaut.

This is what I have but I'm not sure it's correct. What would happen if the first or second API call fails?

```<code>@Singleton
public class SomeService {
    private final FirstRestApi firstRestApi;
    private final SecondRestApi secondRestApi;

    public SomeService(FirstRestApi firstRestApi, SecondRestApi secondRestApi) {
        this.firstRestApi = firstRestApi;
        this.secondRestApi = secondRestApi;
    }

    public Single<AggregatedResponse> login(String data) {
        Single<FirstResponse> firstResponse = firstRestApi.call(data);
        Single<SecondResponse> secondResponse = secondRestApi.call();
        return firstResponse.zipWith(secondResponse, this::convertResponse);
    }

    private AggregatedResponse convertResponse(FirstResponse firstResponse, SecondResponse secondResponse) {
        return AggregatedResponse
                   .builder()
                   .something1(firstResponse.getSomething1())
                   .something2(secondResponse.getSomething2())
                   .build();
    }
}
</code>```

答:
This should be as simple as

```<code>public Single<AggregatedResponse> login(String data) {
    return firstRestApi.call(data)
             .flatMap((firstResponse) -> secondRestApi.call().map((secondResponse) -> {
                 return Pair.create(firstResponse, secondResponse);
             })
             .map((pair) -> {
                 return convertResponse(pair.getFirst(), pair.getSecond());
             });
}
</code>```

In which case you no longer need zipWith. Errors just go to error stream as usual.

Body:
This is what I want to do:

call first rest API

if first succeeds call seconds rest API

if both are successful -> create an aggregated response

I'm using RxJava2 in Micronaut.

This is what I have but I'm not sure it's correct. What would happen if the first or second API call fails?

@Singleton
public class SomeService {
    private final FirstRestApi firstRestApi;
    private final SecondRestApi secondRestApi;

    public SomeService(FirstRestApi firstRestApi, SecondRestApi secondRestApi) {
        this.firstRestApi = firstRestApi;
        this.secondRestApi = secondRestApi;
    }

    public Single<AggregatedResponse> login(String data) {
        Single<FirstResponse> firstResponse = firstRestApi.call(data);
        Single<SecondResponse> secondResponse = secondRestApi.call();
        return firstResponse.zipWith(secondResponse, this::convertResponse);
    }

    private AggregatedResponse convertResponse(FirstResponse firstResponse, SecondResponse secondResponse) {
        return AggregatedResponse
                   .builder()
                   .something1(firstResponse.getSomething1())
                   .something2(secondResponse.getSomething2())
                   .build();
    }
}

Body:
This should be as simple as

public Single<AggregatedResponse> login(String data) {
    return firstRestApi.call(data)
             .flatMap((firstResponse) -> secondRestApi.call().map((secondResponse) -> {
                 return Pair.create(firstResponse, secondResponse);
             })
             .map((pair) -> {
                 return convertResponse(pair.getFirst(), pair.getSecond());
             });
}

In which case you no longer need zipWith. Errors just go to error stream as usual.


问:
Visual Studio C++: Unit test exe project with google test?
Using Visual Studio 2010 C++.  I'm experimenting with unit testing and decided to try Google Test (gtest).  I have an existing project which compiles to an MFC executable (I'm also interested in how to test a project that compiles to a DLL).  My understanding of the convention for unit testing is that you should create a new separate project for your tests.  So I created a new project in the same solution for my unit tests.  But how do I link the projects?  Can I test arbitrary functions/methods of my exe project from my test project?

What is the conventional way to do this?

答: Either put the functionality you want to test into a static library which is linked into both your test project and your MFC project, or put your files in both projects. The first is more complicated, but the second will cause you to compile everything twice....</p>

ContentLicense: CC BY-SA 3.0


问:
Selecting data from 100 tables in AWS Glue/PySpark
I have a catalog of 100 tables in the AWS Glue catalog of the format:

```<code>user_1
user_2
...
user_100
</code>```

Each table has this format:

```<code>| id | user_id | date     | expense |
|----|---------|----------|---------|
| 1  | 1       | 20200521 | 200     |
| 2  | 2       | 20200601 | 100     |
| 3  | 1       | 20200603 | 90      |
</code>```

Every table has the same schema where one column is expense (int type).
Each users rows get randomly inserted in to one these 100 tables.

What I want do is to check the sum of the expense column of each of the tables for a given user.

What is the most efficient way of doing this rather than creating 100 Dynamic frames and joining them. I suppose I need to create 100 datasources for each table, but is there an easier way to select the rows for a given user from all 100 tables and get the sum?

Thank you.

答:
You are using glue catalog, so the data must be lying in s3.
So you can create a list of all the tables path on s3 and read them as one df. This way you can also apply pushdown conditions.</p>

```<code>Path = [path1, path2 .....path100]
Df = spark.read.csv(*path)

Df.groupby('user_id').agg(sum(expense)).show()
</code>```

Body:
I have a catalog of 100 tables in the AWS Glue catalog of the format:

user_1
user_2
...
user_100

Each table has this format:

| id | user_id | date     | expense |
|----|---------|----------|---------|
| 1  | 1       | 20200521 | 200     |
| 2  | 2       | 20200601 | 100     |
| 3  | 1       | 20200603 | 90      |

Every table has the same schema where one column is expense (int type).
Each users rows get randomly inserted in to one these 100 tables.

What I want do is to check the sum of the expense column of each of the tables for a given user.

What is the most efficient way of doing this rather than creating 100 Dynamic frames and joining them. I suppose I need to create 100 datasources for each table, but is there an easier way to select the rows for a given user from all 100 tables and get the sum?

Thank you.

Body:
You are using glue catalog, so the data must be lying in s3.
So you can create a list of all the tables path on s3 and read them as one df. This way you can also apply pushdown conditions.

Path = [path1, path2 .....path100]
Df = spark.read.csv(*path)

Df.groupby('user_id').agg(sum(expense)).show()


问:
Treating NaN as 0 when adding and NaN when dividing
I have a sparse dataframe where I need to do some column operations involving adding and weighted averaging.

```<code>df
     A   B   C    D   E   F
0  NaN NaN NaN   30  15  25
1  15  25   35  NaN NaN NaN
2  NaN NaN NaN   35  10  15
3  10  20   35  NaN NaN NaN
</code>```

Now I have to create three new columns where one is (A + D), one is ((A * B) + (D * E)) / (A + D), and the last one is  ((A * B * C) + (D * E * F)) / ((A * B) + (D * E)). The problem I am having is that when I treat NaN as 0 then when I divide I get errors because you cant divide by 0 but when I perform operations with NaN then my result is NaN. I tried just writing a conditional but I get an error because its a column so that doesnt work. I didnt want to do it a row at a time because speed matter. Any help would be greatly appreciated.

Body:
I have a sparse dataframe where I need to do some column operations involving adding and weighted averaging.

df
     A   B   C    D   E   F
0  NaN NaN NaN   30  15  25
1  15  25   35  NaN NaN NaN
2  NaN NaN NaN   35  10  15
3  10  20   35  NaN NaN NaN

Now I have to create three new columns where one is (A + D), one is ((A * B) + (D * E)) / (A + D), and the last one is  ((A * B * C) + (D * E * F)) / ((A * B) + (D * E)). The problem I am having is that when I treat NaN as 0 then when I divide I get errors because you cant divide by 0 but when I perform operations with NaN then my result is NaN. I tried just writing a conditional but I get an error because its a column so that doesnt work. I didnt want to do it a row at a time because speed matter. Any help would be greatly appreciated.

Body:
I read in your data and used .fillna(0) to replace NaN values. Is that an option?

import pandas as pd
df = pd.read_clipboard().fillna(0)
df

    A       B       C       D       E       F
0   0.0     0.0     0.0     30.0    15.0    25.0
1   15.0    25.0    35.0    0.0     0.0     0.0
2   0.0     0.0     0.0     35.0    10.0    15.0
3   10.0    20.0    35.0    0.0     0.0     0.0

Then I simply inputted your formulas:

df['G'] = (df['A'] + df['D'])
df['H'] = ((df['A'] * df['B']) + (df['D'] * df['E'])) / (df['A'] + df['D'])
df['I'] = ((df['A'] * df['B'] * df['C']) + (df['D'] * df['E'] * df['F'])) / ((df['A'] * df['B']) + (df['C'] * df['D']))
df

Is this what you are expecting below?

    A       B       C       D       E       F       G       H       I
0   0.0     0.0     0.0     30.0    15.0    25.0    30.0    15.0    inf
1   15.0    25.0    35.0    0.0     0.0     0.0     15.0    25.0    35.0
2   0.0     0.0     0.0     35.0    10.0    15.0    35.0    10.0    inf
3   10.0    20.0    35.0    0.0     0.0     0.0     10.0    20.0    35.0

Finally, if you want to change inf values to nan values, you can use df.replace(np.inf, np.nan)


问:
How to get file name using `URLUtil`?
How to guess the possible file name before downloading it? I am using String nameOfFile = URLUtil.guessFileName(url, contentDisposition, mimetype); but it only returns the file name, not the extension. Extension is always returned ".bin". How do I fix this? I have searched everywhere on the internet.

答:
Note: If the file don't have extension then URLUtil adds .bin to it automatically

```<code>String nameOfFile = URLUtil.guessFileName(Url, null, null);

    Intent intent = new Intent(Intent.ACTION_VIEW);

    if (guessedFileName.contains(".gif")) {
        // GIF file
        mimeType = "image/gif";
    } else if (guessedFileName.contains(".jpg") || guessedFileName.contains(".jpeg")) {
        // JPG file
        mimeType = "image/jpeg";
    } else if (guessedFileName.contains(".png")) {
        // PNG file
        mimeType = "image/png";
    } else if (guessedFileName.contains(".txt")) {
        // Text file
        mimeType = "text/plain";
    } else if (
        guessedFileName.contains(".mpg") ||
        guessedFileName.contains(".mpeg") ||
        guessedFileName.contains(".mpe") ||
        guessedFileName.contains(".mp4") ||
        guessedFileName.contains(".avi") ||
        guessedFileName.contains(".3gp") ||
        guessedFileName.contains(".3gpp")  ||
        guessedFileName.contains(".3g2")
    ) {
        // Video files
        mimeType = "video/*";
    } else if (guessedFileName.contains(".doc") || guessedFileName.contains(".docx")) {
        // Word document
        mimeType = "application/msword";
    } else if (guessedFileName.contains(".pdf")) {
        // PDF file
        mimeType = "application/pdf";
    } else if (guessedFileName.contains(".ppt") || guessedFileName.contains(".pptx")) {
        // Powerpoint file
        mimeType = "application/vnd.ms-powerpoint";
    } else if (guessedFileName.contains(".xls") || guessedFileName.contains(".xlsx")) {
        // Excel file
        mimeType = "application/vnd.ms-excel";
    } else if (guessedFileName.contains(".rtf")) {
        // RTF file
        mimeType = "application/rtf";
    } else if (guessedFileName.contains(".apk")) {
        mimeType = "application/vnd.android.package-archive";
    } else if (guessedFileName.contains(".eml")) {
        mimeType = "message/rfc822";
    }
</code>```

A brief explanation is available: Here

Title: How to get file name using `URLUtil`?

Body:
Note: If the file don't have extension then URLUtil adds .bin to it automatically

String nameOfFile = URLUtil.guessFileName(Url, null, null);

    Intent intent = new Intent(Intent.ACTION_VIEW);

    if (guessedFileName.contains(".gif")) {
        // GIF file
        mimeType = "image/gif";
    } else if (guessedFileName.contains(".jpg") || guessedFileName.contains(".jpeg")) {
        // JPG file
        mimeType = "image/jpeg";
    } else if (guessedFileName.contains(".png")) {
        // PNG file
        mimeType = "image/png";
    } else if (guessedFileName.contains(".txt")) {
        // Text file
        mimeType = "text/plain";
    } else if (
        guessedFileName.contains(".mpg") ||
        guessedFileName.contains(".mpeg") ||
        guessedFileName.contains(".mpe") ||
        guessedFileName.contains(".mp4") ||
        guessedFileName.contains(".avi") ||
        guessedFileName.contains(".3gp") ||
        guessedFileName.contains(".3gpp")  ||
        guessedFileName.contains(".3g2")
    ) {
        // Video files
        mimeType = "video/*";
    } else if (guessedFileName.contains(".doc") || guessedFileName.contains(".docx")) {
        // Word document
        mimeType = "application/msword";
    } else if (guessedFileName.contains(".pdf")) {
        // PDF file
        mimeType = "application/pdf";
    } else if (guessedFileName.contains(".ppt") || guessedFileName.contains(".pptx")) {
        // Powerpoint file
        mimeType = "application/vnd.ms-powerpoint";
    } else if (guessedFileName.contains(".xls") || guessedFileName.contains(".xlsx")) {
        // Excel file
        mimeType = "application/vnd.ms-excel";
    } else if (guessedFileName.contains(".rtf")) {
        // RTF file
        mimeType = "application/rtf";
    } else if (guessedFileName.contains(".apk")) {
        mimeType = "application/vnd.android.package-archive";
    } else if (guessedFileName.contains(".eml")) {
        mimeType = "message/rfc822";
    }

A brief explanation is available: Here


问:
Julia InexactError: Int64
I am new to Julia. Got this InexactError . To mention that I have tried to convert to float beforehand and it did not work, maybe I am doing something wrong.</p>

```<code>column = df[:, i]
max = maximum(column)
min = minimum(column)
scaled_column = (column .- min)/max   # This is the error, I think
df[:, i] = scaled_column
</code>```

```<code>julia> VERSION
v"1.4.2"
</code>```

答:
As a side note you can use transform! to achieve what you want like this:

```<code>transform!(df, i => (x -> (x .- minimum(x)) ./ maximum(x)) => i)
</code>```

and this operation will replace the column.

Title: Julia InexactError: Int64

Body:
I am new to Julia. Got this InexactError . To mention that I have tried to convert to float beforehand and it did not work, maybe I am doing something wrong.

column = df[:, i]
max = maximum(column)
min = minimum(column)
scaled_column = (column .- min)/max   # This is the error, I think
df[:, i] = scaled_column

julia> VERSION
v"1.4.2"

Body:
As a side note you can use transform! to achieve what you want like this:

transform!(df, i => (x -> (x .- minimum(x)) ./ maximum(x)) => i)

and this operation will replace the column.


问:
menu popup, when hover, on css
I have a sidebar on the site, on the left, with certain menu items. There are also subclauses. I can’t make it so that when you hover, a pop-up block with sub-items is displayed on the main menu item. The main sidebar has position: sticky. What you need to display in the popup block in the main_menu_content_list_submenu tag. Please help sort it out. Thank you so much!

.main {
  font-family: PT Sans;
  position: relative;
  display: flex;
  flex-direction: row;
  min-height: 100%;
}

.main_menu {
  display: flex;
  flex-direction: column;
  width: auto;
  background-color: #38618C;
  padding: 50px 50px 0 50px;
}

.main_menu_content {
  display: flex;
  flex-direction: column;
  position: sticky;
  top: 50px;
  width: 100%;
}
.main_menu_content_list {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  text-align: center;
  height: 700px;
}

.main_menu_content_list li {
  list-style-type: none;
}

.main_menu_content_list a {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-style: normal;
  font-weight: normal;
  font-size: 18px;
  line-height: 23px;
  color: #D7DFE8;
  text-decoration: none;
}

.main_content {
  display: flex;
  align-items: center;
  flex-direction: column;
  width: 100%;
  max-width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
<div class="main_menu">
            <div class="main_menu_content">
                <ul class="main_menu_content_list">
                    <li>
                            <div class="main_menu_content_list_int"></div>Text1
                        </li>

                        <ul class="main_menu_content_list_submenu">
                            <li>Text1.1</li>
                            <li>Text1.2</li>
                        </ul>

                    <li>
                            <div class="main_menu_content_list_tv"></div>Text2
                        </li>
                    <li>
                            <div class="main_menu_content_list_video"></div>Text3
                        </li>
                </ul>
            </div>
</div>
<div class="main_content">
</div>
</div></code>```

答:
I think this will help you

.main {
  font-family: PT Sans;
  position: relative;
  display: flex;
  flex-direction: row;
  min-height: 100%;
}

.main_menu {
  display: flex;
  flex-direction: column;
  width: auto;
  background-color: #38618C;
}

.main_menu_content {
  display: flex;
  flex-direction: column;
  position: sticky;
  top: 50px;
  width: 100%;
}

.main_menu_content_list {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  text-align: center;
  height: 700px;
  padding: 0;
  margin: 0;
}

.main_menu_content_list li {
  list-style-type: none;
}

.main_menu_content_list>li>a {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-style: normal;
  font-weight: normal;
  font-size: 18px;
  line-height: 23px;
  color: #D7DFE8;
  text-decoration: none;
  padding: 10px 15px
}

.main_content {
  display: flex;
  align-items: center;
  flex-direction: column;
  width: 100%;
  max-width: 100%;
  height: 100%;
}

.main_menu_content_list_submenu {
  position: absolute;
  padding: 0;
  margin: 0;
  left: 90%;
  height: 100vh;
  background: #f1f1f1;
  top: 0;
  pointer-events: none;
  opacity: 0;
  transition: all linear 0.1s 0s;
  width: 200px;
  padding: 10px 0;
}

.main_menu_content_list li:hover .main_menu_content_list_submenu {
  opacity: 1;
  pointer-events: auto;
  left: 100%;
}

.main_menu_content_list_submenu li {}

.main_menu_content_list_submenu li a {
  padding: 0 10px;
  font-size: 18px;
  line-height: 23px;
  color: #ddd;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="main_menu">
    <div class="main_menu_content">
      <ul class="main_menu_content_list">
        <li>

            <div class="main_menu_content_list_int"></div>Text1

          <ul class="main_menu_content_list_submenu">
            <li>Text1.1</li>
            <li>Text1.2</li>
          </ul>
        </li>

        <li>

            <div class="main_menu_content_list_tv"></div>Text2

        </li>
        <li>

            <div class="main_menu_content_list_video"></div>Text3

        </li>
      </ul>
    </div>
  </div>
  <div class="main_content">
  </div>
</div></code>```

Title: menu popup, when hover, on css

Body:
I have a sidebar on the site, on the left, with certain menu items. There are also subclauses. I can’t make it so that when you hover, a pop-up block with sub-items is displayed on the main menu item. The main sidebar has position: sticky. What you need to display in the popup block in the main_menu_content_list_submenu tag. Please help sort it out. Thank you so much!

.main {
  font-family: PT Sans;
  position: relative;
  display: flex;
  flex-direction: row;
  min-height: 100%;
}

.main_menu {
  display: flex;
  flex-direction: column;
  width: auto;
  background-color: #38618C;
  padding: 50px 50px 0 50px;
}

.main_menu_content {
  display: flex;
  flex-direction: column;
  position: sticky;
  top: 50px;
  width: 100%;
}
.main_menu_content_list {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  text-align: center;
  height: 700px;
}

.main_menu_content_list li {
  list-style-type: none;
}

.main_menu_content_list a {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-style: normal;
  font-weight: normal;
  font-size: 18px;
  line-height: 23px;
  color: #D7DFE8;
  text-decoration: none;
}

.main_content {
  display: flex;
  align-items: center;
  flex-direction: column;
  width: 100%;
  max-width: 100%;
  height: 100%;
}

Text1

Text1.1

Text1.2

Text2

Text3

Body:
I think this will help you

.main {
  font-family: PT Sans;
  position: relative;
  display: flex;
  flex-direction: row;
  min-height: 100%;
}

.main_menu {
  display: flex;
  flex-direction: column;
  width: auto;
  background-color: #38618C;
}

.main_menu_content {
  display: flex;
  flex-direction: column;
  position: sticky;
  top: 50px;
  width: 100%;
}

.main_menu_content_list {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  text-align: center;
  height: 700px;
  padding: 0;
  margin: 0;
}

.main_menu_content_list li {
  list-style-type: none;
}

.main_menu_content_list>li>a {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-style: normal;
  font-weight: normal;
  font-size: 18px;
  line-height: 23px;
  color: #D7DFE8;
  text-decoration: none;
  padding: 10px 15px
}

.main_content {
  display: flex;
  align-items: center;
  flex-direction: column;
  width: 100%;
  max-width: 100%;
  height: 100%;
}

.main_menu_content_list_submenu {
  position: absolute;
  padding: 0;
  margin: 0;
  left: 90%;
  height: 100vh;
  background: #f1f1f1;
  top: 0;
  pointer-events: none;
  opacity: 0;
  transition: all linear 0.1s 0s;
  width: 200px;
  padding: 10px 0;
}

.main_menu_content_list li:hover .main_menu_content_list_submenu {
  opacity: 1;
  pointer-events: auto;
  left: 100%;
}

.main_menu_content_list_submenu li {}

.main_menu_content_list_submenu li a {
  padding: 0 10px;
  font-size: 18px;
  line-height: 23px;
  color: #ddd;
}

<div class="main">
  <div class="main_menu">
    <div class="main_menu_content">
      <ul class="main_menu_content_list">
        <li>
          <a href="">
            <div class="main_menu_content_list_int"></div>Text1
          </a>
          <ul class="main_menu_content_list_submenu">
            <li><a href="">Text1.1</a></li>
            <li><a href="">Text1.2</a></li>
          </ul>
        </li>

        <li>
          <a href="">
            <div class="main_menu_content_list_tv"></div>Text2
          </a>
        </li>
        <li>
          <a href="">
            <div class="main_menu_content_list_video"></div>Text3
          </a>
        </li>
      </ul>
    </div>
  </div>
  <div class="main_content">
  </div>
</div>


问:
AWS API GATEWAY configuration to return binary pdf file from lambda
I want to return a pdf from a AWS Lambda function, and I use API Gateway for calling it from a any browser.

I have a aws lambda function in c# that returns an API Gateway Response which body is a pdf in base64 encoded string.

So far the endpoint returns a file with .pdf extension but not in binary. Instead, is a text file with the base64 string.

The headers i'm returning from the c# code are:

```<code>  var headersDic = new Dictionary<string, string>();
      headersDic.Add("Content-type", "application/pdf");
      headersDic.Add("Content-disposition", "attachment; filename=file.pdf");
</code>```

I converted manually the base64 string to binary file and opened it as a pdf, and it works, I mean, the base64 string is correct so I assume the problem is being the API Gateway.

In the integration response console of the API Gateway, I got this:

But i'm not able to make it work.

I also have binary media types enabled.

答:
Response Headers

```<code>'Content-Type': 'application/pdf'
'Content-disposition', 'attachment; filename=fileName.pdf'
</code>```

Response to Client

```<code>{
 statusCode: 200
 headers: responseHeader,
 body: pdfContent.toString(base64),
 isBase64Encoded: true,
}
</code>```

API Gateway Binary Media Types

Hope it will help

Body:
I want to return a pdf from a AWS Lambda function, and I use API Gateway for calling it from a any browser.

I have a aws lambda function in c# that returns an API Gateway Response which body is a pdf in base64 encoded string.

So far the endpoint returns a file with .pdf extension but not in binary. Instead, is a text file with the base64 string.

The headers i'm returning from the c# code are:

  var headersDic = new Dictionary<string, string>();
      headersDic.Add("Content-type", "application/pdf");
      headersDic.Add("Content-disposition", "attachment; filename=file.pdf");

I converted manually the base64 string to binary file and opened it as a pdf, and it works, I mean, the base64 string is correct so I assume the problem is being the API Gateway.

In the integration response console of the API Gateway, I got this:

But i'm not able to make it work.

I also have binary media types enabled.

Body:
Response Headers

'Content-Type': 'application/pdf'
'Content-disposition', 'attachment; filename=fileName.pdf'

Response to Client

{
 statusCode: 200
 headers: responseHeader,
 body: pdfContent.toString(base64),
 isBase64Encoded: true,
}

API Gateway Binary Media Types

Hope it will help


问:
How to get records in tree view from mysql / php
I have to create a tree view from the records of my table below

```<code>id user_id friend_id property_id
1    123       321          1
2    123       456          1
3    456       909          1
4    909       222          1
</code>```

I have the user_id i.e 123 and property_id i.e 1 I need to know how can I make a tree with friends with whom I share this property, and afterwards with users with whom my friends share this ID.

答:
Ok since there are several steps I'll start out on a high level. If you need help with any of those, ask again!

First of all, you'll need the "root" nodes, ie those users who don't appear as children in the friend column.

Then, for each of these users, start polling all their children. For this, define a function that gets all the children of a user and which calls itself recursively for the children of the child it finds.

This is pretty abstract, because the question is what you want to do with this structure. This depends on the last part, your presentation layer. That's what I know least about; there may be a framework which helps you visualize trees in PHP, but I don't know. There will typically be some sort of object structure with layout properties and child objects; instantiate those properties in your recursive function from the last step.

As a side node, it isn't clear if the data structure you obtain is actually a tree. If you are A, have friends B and C, and C is also a friend of B, B will show up as your friend (on level 2 of the tree) and as C's friend (on level 3). You'll have to check what's your desired behaviour in that spot and might have to, e.g., ignore C the second time you encounter it.

Body:
I have to create a tree view from the records of my table below

id user_id friend_id property_id
1    123       321          1
2    123       456          1
3    456       909          1
4    909       222          1

I have the user_id i.e 123 and property_id i.e 1 I need to know how can I make a tree with friends with whom I share this property, and afterwards with users with whom my friends share this ID.


问:
Rails logger middleware error
In a controller, in I have defined a method which looks something like this:

```<code>def blah
  begin
    # do something
    # works fine till here, no issues
    # breaks in the next line, (while rendering json??)
    render json: { status: 1 }
  rescue StandardError => e
    # code never reaches here(??)
    # log exception
  end
end
</code>```

Even the begin-rescue block is unable to catch this error.
What really stumps me is that there is not a single line from the codebase in the stacktrace. Any pointers?

Full stacktrace:

undefined method `logger' for ["{\"status\":1}"]:Array

activesupport (4.0.13) lib/active_support/configurable.rb, line 112

```<code>  107           options = names.extract_options!
  108
  109           names.each do |name|
  110             raise NameError.new('invalid config attribute name') unless name =~ /^[_A-Za-z]\w*$/
  111
> 112             reader, reader_line = "def #{name}; config.#{name}; end", __LINE__
  113             writer, writer_line = "def #{name}=(value); config.#{name} = value; end", __LINE__
  114
  115             singleton_class.class_eval reader, __FILE__, reader_line
  116             singleton_class.class_eval writer, __FILE__, writer_line
  117
</code>```

App backtrace

Full backtrace

```<code>- activesupport (4.0.13) lib/active_support/configurable.rb:112:in `logger'
- geokit-rails (2.0.1) lib/geokit-rails/geocoder_control.rb:15:in `set_geokit_domain'
- activesupport (4.0.13) lib/active_support/callbacks.rb:397:in `_run__489562034147364391__process_action__callbacks'
- activesupport (4.0.13) lib/active_support/callbacks.rb:80:in `run_callbacks'
- actionpack (4.0.13) lib/abstract_controller/callbacks.rb:17:in `process_action'
- actionpack (4.0.13) lib/action_controller/metal/rescue.rb:29:in `process_action'
- actionpack (4.0.13) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
- activesupport (4.0.13) lib/active_support/notifications.rb:159:in `block in instrument'
- activesupport (4.0.13) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
- activesupport (4.0.13) lib/active_support/notifications.rb:159:in `instrument'
- actionpack (4.0.13) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
- actionpack (4.0.13) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
- activerecord (4.0.13) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
- actionpack (4.0.13) lib/abstract_controller/base.rb:136:in `process'
- actionpack (4.0.13) lib/abstract_controller/rendering.rb:44:in `process'
- actionpack (4.0.13) lib/action_controller/metal.rb:195:in `dispatch'
- actionpack (4.0.13) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
- actionpack (4.0.13) lib/action_controller/metal.rb:231:in `block in action'
- actionpack (4.0.13) lib/action_dispatch/routing/route_set.rb:82:in `dispatch'
- actionpack (4.0.13) lib/action_dispatch/routing/route_set.rb:50:in `call'
- actionpack (4.0.13) lib/action_dispatch/journey/router.rb:71:in `block in call'
- actionpack (4.0.13) lib/action_dispatch/journey/router.rb:59:in `call'
- actionpack (4.0.13) lib/action_dispatch/routing/route_set.rb:676:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack-pjax (0.8.0) lib/rack/pjax.rb:12:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- omniauth (1.2.1) lib/omniauth/strategy.rb:186:in `call!'
- omniauth (1.2.1) lib/omniauth/strategy.rb:164:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/rack/agent_hooks.rb:30:in `traced_call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/rack/browser_monitoring.rb:32:in `traced_call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- exception_notification (4.1.1) lib/exception_notification/rack.rb:32:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
- warden (1.2.3) lib/warden/manager.rb:34:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/etag.rb:23:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/conditionalget.rb:25:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/head.rb:11:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- remotipart (1.3.0) lib/remotipart/middleware.rb:32:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/flash.rb:241:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/session/abstract/id.rb:225:in `context'
- rack (1.5.5) lib/rack/session/abstract/id.rb:220:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/cookies.rb:486:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- activerecord (4.0.13) lib/active_record/query_cache.rb:36:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- activerecord (4.0.13) lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- activerecord (4.0.13) lib/active_record/migration.rb:373:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
- activesupport (4.0.13) lib/active_support/callbacks.rb:373:in `_run__2519945963821911877__call__callbacks'
- activesupport (4.0.13) lib/active_support/callbacks.rb:80:in `run_callbacks'
- actionpack (4.0.13) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/reloader.rb:64:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- bugsnag (4.2.1) lib/bugsnag/rack.rb:33:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- better_errors (2.0.0) lib/better_errors/middleware.rb:84:in `protected_app_call'
- better_errors (2.0.0) lib/better_errors/middleware.rb:79:in `better_errors_call'
- better_errors (2.0.0) lib/better_errors/middleware.rb:57:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- railties (4.0.13) lib/rails/rack/logger.rb:38:in `call_app'
- railties (4.0.13) lib/rails/rack/logger.rb:22:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- request_store (1.2.0) lib/request_store/middleware.rb:8:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/request_id.rb:21:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/methodoverride.rb:21:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/runtime.rb:17:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- activesupport (4.0.13) lib/active_support/cache/strategy/local_cache.rb:83:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/lock.rb:17:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/static.rb:84:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/sendfile.rb:112:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- railties (4.0.13) lib/rails/engine.rb:511:in `call'
- railties (4.0.13) lib/rails/application.rb:97:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/lock.rb:17:in `call'
- rack (1.5.5) lib/rack/content_length.rb:14:in `call'
rack (1.5.5) lib/rack/handler/webrick.rb:60:in `service'
- /{path-to-ruby}/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
- /{path-to-ruby}/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
- /{path-to-ruby}/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'
</code>```

答:
One possible cause could be better_errors.

If an error is raised in a rescue block, its cause would be the original error. better_errors displays that cause instead, meaning the backtrace will not be in the rescue block. This gives you the illusion that it is never rescued.

See https://github.com/BetterErrors/better_errors/pull/459 for more details

Title: Rails logger middleware error

Body:
In a controller, in I have defined a method which looks something like this:

def blah
  begin
    # do something
    # works fine till here, no issues
    # breaks in the next line, (while rendering json??)
    render json: { status: 1 }
  rescue StandardError => e
    # code never reaches here(??)
    # log exception
  end
end

Even the begin-rescue block is unable to catch this error.
What really stumps me is that there is not a single line from the codebase in the stacktrace. Any pointers?

Full stacktrace:

undefined method `logger' for ["{\"status\":1}"]:Array

activesupport (4.0.13) lib/active_support/configurable.rb, line 112

  107           options = names.extract_options!
  108
  109           names.each do |name|
  110             raise NameError.new('invalid config attribute name') unless name =~ /^[_A-Za-z]\w*$/
  111
> 112             reader, reader_line = "def #{name}; config.#{name}; end", __LINE__
  113             writer, writer_line = "def #{name}=(value); config.#{name} = value; end", __LINE__
  114
  115             singleton_class.class_eval reader, __FILE__, reader_line
  116             singleton_class.class_eval writer, __FILE__, writer_line
  117

App backtrace

Full backtrace

- activesupport (4.0.13) lib/active_support/configurable.rb:112:in `logger'
- geokit-rails (2.0.1) lib/geokit-rails/geocoder_control.rb:15:in `set_geokit_domain'
- activesupport (4.0.13) lib/active_support/callbacks.rb:397:in `_run__489562034147364391__process_action__callbacks'
- activesupport (4.0.13) lib/active_support/callbacks.rb:80:in `run_callbacks'
- actionpack (4.0.13) lib/abstract_controller/callbacks.rb:17:in `process_action'
- actionpack (4.0.13) lib/action_controller/metal/rescue.rb:29:in `process_action'
- actionpack (4.0.13) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
- activesupport (4.0.13) lib/active_support/notifications.rb:159:in `block in instrument'
- activesupport (4.0.13) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
- activesupport (4.0.13) lib/active_support/notifications.rb:159:in `instrument'
- actionpack (4.0.13) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
- actionpack (4.0.13) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
- activerecord (4.0.13) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
- actionpack (4.0.13) lib/abstract_controller/base.rb:136:in `process'
- actionpack (4.0.13) lib/abstract_controller/rendering.rb:44:in `process'
- actionpack (4.0.13) lib/action_controller/metal.rb:195:in `dispatch'
- actionpack (4.0.13) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
- actionpack (4.0.13) lib/action_controller/metal.rb:231:in `block in action'
- actionpack (4.0.13) lib/action_dispatch/routing/route_set.rb:82:in `dispatch'
- actionpack (4.0.13) lib/action_dispatch/routing/route_set.rb:50:in `call'
- actionpack (4.0.13) lib/action_dispatch/journey/router.rb:71:in `block in call'
- actionpack (4.0.13) lib/action_dispatch/journey/router.rb:59:in `call'
- actionpack (4.0.13) lib/action_dispatch/routing/route_set.rb:676:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack-pjax (0.8.0) lib/rack/pjax.rb:12:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- omniauth (1.2.1) lib/omniauth/strategy.rb:186:in `call!'
- omniauth (1.2.1) lib/omniauth/strategy.rb:164:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/rack/agent_hooks.rb:30:in `traced_call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/rack/browser_monitoring.rb:32:in `traced_call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- exception_notification (4.1.1) lib/exception_notification/rack.rb:32:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
- warden (1.2.3) lib/warden/manager.rb:34:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/etag.rb:23:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/conditionalget.rb:25:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/head.rb:11:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- remotipart (1.3.0) lib/remotipart/middleware.rb:32:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/flash.rb:241:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/session/abstract/id.rb:225:in `context'
- rack (1.5.5) lib/rack/session/abstract/id.rb:220:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/cookies.rb:486:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- activerecord (4.0.13) lib/active_record/query_cache.rb:36:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- activerecord (4.0.13) lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- activerecord (4.0.13) lib/active_record/migration.rb:373:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
- activesupport (4.0.13) lib/active_support/callbacks.rb:373:in `_run__2519945963821911877__call__callbacks'
- activesupport (4.0.13) lib/active_support/callbacks.rb:80:in `run_callbacks'
- actionpack (4.0.13) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/reloader.rb:64:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- bugsnag (4.2.1) lib/bugsnag/rack.rb:33:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- better_errors (2.0.0) lib/better_errors/middleware.rb:84:in `protected_app_call'
- better_errors (2.0.0) lib/better_errors/middleware.rb:79:in `better_errors_call'
- better_errors (2.0.0) lib/better_errors/middleware.rb:57:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- railties (4.0.13) lib/rails/rack/logger.rb:38:in `call_app'
- railties (4.0.13) lib/rails/rack/logger.rb:22:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- request_store (1.2.0) lib/request_store/middleware.rb:8:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/request_id.rb:21:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/methodoverride.rb:21:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/runtime.rb:17:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- activesupport (4.0.13) lib/active_support/cache/strategy/local_cache.rb:83:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/lock.rb:17:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- actionpack (4.0.13) lib/action_dispatch/middleware/static.rb:84:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/sendfile.rb:112:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- railties (4.0.13) lib/rails/engine.rb:511:in `call'
- railties (4.0.13) lib/rails/application.rb:97:in `call'
- newrelic_rpm (3.16.2.321) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'
- rack (1.5.5) lib/rack/lock.rb:17:in `call'
- rack (1.5.5) lib/rack/content_length.rb:14:in `call'
rack (1.5.5) lib/rack/handler/webrick.rb:60:in `service'
- /{path-to-ruby}/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
- /{path-to-ruby}/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
- /{path-to-ruby}/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'


问:
Prevent dropdown menu to push div underneath
I'm working on an Angular project for an e-commerce platform and I'm having some problems with a dropdown menu. The menu pushes the div underneath down, but I want to go over it, not pushing it.
Here's some images:

After clicking the menu:

While I'm trying to achieve this (this is the template html page):

As you can see the menu goes over the div underneath and doesn't push it down.
Here it is the code:

$('.hero__categories__all').on('click', function(){
      $('.hero__categories ul').slideToggle(400);
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hero.hero-normal {
  padding-bottom: 30px;
  z-index: 1000;
}

.hero.hero-normal .hero__categories {
  position: relative;
}

.hero.hero-normal .hero__categories ul {
 display: none;
 position: absolute;
 left: 0;
 top: 46px;
 width: 100%;
 z-index: 1000;
 background: #ffffff;
}
.hero__categories__all {
 background: #7fad39;
  position: relative;
  z-index: 1000;
 padding: 10px 25px 10px 40px;
 cursor: pointer;
}

.hero__categories__all i {
 font-size: 16px;
 color: #ffffff;
 margin-right: 10px;
}

.hero__categories__all span {
 font-size: 18px;
 font-weight: 700;
 color: #ffffff;
}

.hero__categories__all:after {
 position: absolute;
 right: 18px;
 top: 9px;
 content: "3";
 font-family: "ElegantIcons";
 font-size: 18px;
  color: #ffffff;
  z-index: 1000;
}

.hero__categories ul {
 border: 1px solid #ebebeb;
 padding-left: 40px;
  padding-top: 10px;
  z-index: 1000;
  padding-bottom: 12px;
}

.hero__categories ul li {
 list-style: none;
}

.hero__categories ul li a {
 font-size: 16px;
 color: #1c1c1c;
 line-height: 39px;
 display: block;
}</code>```

                      Categorie

                          {{category.name}}

```

I'm not really a CSS and HTML expert so thanks for your help!

EDIT 1

I gave position: absolute to the ul in css code and now this happens:

答: I managed to solve the problem, all I had to do was adding position: absolute in css to the ul element and top and left properties in place of padding-top and padding-left. I also removed padding-bottom</p>

Body:
I'm working on an Angular project for an e-commerce platform and I'm having some problems with a dropdown menu. The menu pushes the div underneath down, but I want to go over it, not pushing it.
Here's some images:

After clicking the menu:

While I'm trying to achieve this (this is the template html page):

As you can see the menu goes over the div underneath and doesn't push it down.
Here it is the code:

$('.hero__categories__all').on('click', function(){
      $('.hero__categories ul').slideToggle(400);
  });

.hero.hero-normal {
  padding-bottom: 30px;
  z-index: 1000;
}

.hero.hero-normal .hero__categories {
  position: relative;
}

.hero.hero-normal .hero__categories ul {
 display: none;
 position: absolute;
 left: 0;
 top: 46px;
 width: 100%;
 z-index: 1000;
 background: #ffffff;
}
.hero__categories__all {
 background: #7fad39;
  position: relative;
  z-index: 1000;
 padding: 10px 25px 10px 40px;
 cursor: pointer;
}

.hero__categories__all i {
 font-size: 16px;
 color: #ffffff;
 margin-right: 10px;
}

.hero__categories__all span {
 font-size: 18px;
 font-weight: 700;
 color: #ffffff;
}

.hero__categories__all:after {
 position: absolute;
 right: 18px;
 top: 9px;
 content: "3";
 font-family: "ElegantIcons";
 font-size: 18px;
  color: #ffffff;
  z-index: 1000;
}

.hero__categories ul {
 border: 1px solid #ebebeb;
 padding-left: 40px;
  padding-top: 10px;
  z-index: 1000;
  padding-bottom: 12px;
}

.hero__categories ul li {
 list-style: none;
}

.hero__categories ul li a {
 font-size: 16px;
 color: #1c1c1c;
 line-height: 39px;
 display: block;
}

                      Categorie

                          {{category.name}}

I'm not really a CSS and HTML expert so thanks for your help!

EDIT 1

I gave position: absolute to the ul in css code and now this happens:


问:
React Material UI Autocmplete with React-window rerenders at top of list
I have recently started learning React and could use any help.

I am having an issue with the Material-ui autocomplete component. Need some real React gurus to figure this one out. The problem I am having is that when I select an option from the autocomplete drop down it resets to the top of the list. I am using react-window because the list is over 300 elements. The ingredient filter is the one that I am trying to fix, the other filters work fine. I have created code sandboxes that demonstrate what should happen and what is currently happening. I have messed around with React.memo but that does not have any affect on it. Please let me know if you have any ideas. The correct sandbox is from the material-ui site: autcomplete component

Correct: correct sandbox

correct gif

Issue: issue sandbox

issue gif

Please let me know if you need any clarification

答:
I had to use useCallback on ListboxComponent, please try now.
Link to code: https://codesandbox.io/s/material-demo-33l5y?file=/demo.js:11315-11331

Old answer:

Seems like when we call setIngredients it is re-rendering the component and causes the list to jump to top, memoizing the handleIngredients function seems to fix it.

```<code>const handleIngredients = React.useMemo((event, value) => {
  setIngredients(value);
}, []);
</code>```

Body:
I had to use useCallback on ListboxComponent, please try now.
Link to code: https://codesandbox.io/s/material-demo-33l5y?file=/demo.js:11315-11331

Old answer:

Seems like when we call setIngredients it is re-rendering the component and causes the list to jump to top, memoizing the handleIngredients function seems to fix it.

const handleIngredients = React.useMemo((event, value) => {
  setIngredients(value);
}, []);