问:
Issue while including enum type in unions within avro schema
I am working with Apache Kafka to send messages to Kafka topics. I am trying to use unions in Avro Schemas including enum types for message validation. But I am facing an issue with the usage of enum types within union. I am using Kafka REST API through POSTMAN tool to post a record/message to a topic with schema validation. Below is the request payload including schema and records inline -

```<code>{
    "key_schema": "{\"type\": \"record\", \"name\": \"key\", \"fields\": [{\"name\": \"keyInput\", \"type\": \"string\"}]}",
    "value_schema": "{\"type\": \"record\", \"name\": \"value\", \"fields\": [{\"name\": \"valueInput1\", \"type\": \"string\"},{\"name\": \"valueInput2\",\"type\":[{\"type\":\"enum\",\"name\":\"actorobjType\",\"symbols\":[\"Agent\",\"Group\"]},\"null\"],\"default\":null}]}",
    "records": [
        {
            "key": {
                "keyInput": "testUser-key"
            },
            "value": {
                "valueInput1": "testUser-value",
                "valueInput2": "Agent"
            }
        }
    ]
}
</code>```

I am getting the following error when I am trying to insert a record using above request payload -

```<code>{
  "error_code": 42203,
  "message": "Conversion of JSON to Avro failed: Failed to convert JSON to Avro: Expected start-union. Got VALUE_STRING"
}
</code>```

After searching in different sites including stackoverflow, I came through a suggestion

asking to explicitly specify the type while passing the record as below -

```<code>{
    "key_schema": "{\"type\": \"record\", \"name\": \"key\", \"fields\": [{\"name\": \"keyInput\", \"type\": \"string\"}]}",
    "value_schema": "{\"type\": \"record\", \"name\": \"value\", \"fields\": [{\"name\": \"valueInput1\", \"type\": \"string\"},{\"name\": \"valueInput2\",\"type\":[{\"type\":\"enum\",\"name\":\"actorobjType\",\"symbols\":[\"Agent\",\"Group\"]},\"null\"],\"default\":null}]}",
    "records": [
        {
            "key": {
                "keyInput": "testUser-key"
            },
            "value": {
                "valueInput1": "testUser-value",
                "valueInput2": {
                    "enum": "Agent"
                }
            }
        }
    ]
}
</code>```

But then I face the below error -

```<code>{
  "error_code": 42203,
  "message": "Conversion of JSON to Avro failed: Failed to convert JSON to Avro: Unknown union branch enum"
}
</code>```

The same suggestion worked fine for unions with other types like string and map, but with unions including enum, that does not seem to work.

I also thought there may be some other type which needs to be used for enum specification, Hence I tried some other words like below -

```<code>"valueInput2": {
                    "string": "Agent"
                }
</code>```

and

```<code>"valueInput2": {
                    "enumeration": "Agent"
                }
</code>```

But none of them seem to work. Please help me resolve this.

答:
As ENUM type is not exist in JSON format, value type should be changed to correct one:
namespace + type name
In your case, it will be namespace + actorobjtype : "agent"</p>

Body:
I am working with Apache Kafka to send messages to Kafka topics. I am trying to use unions in Avro Schemas including enum types for message validation. But I am facing an issue with the usage of enum types within union. I am using Kafka REST API through POSTMAN tool to post a record/message to a topic with schema validation. Below is the request payload including schema and records inline -

{
    "key_schema": "{\"type\": \"record\", \"name\": \"key\", \"fields\": [{\"name\": \"keyInput\", \"type\": \"string\"}]}",
    "value_schema": "{\"type\": \"record\", \"name\": \"value\", \"fields\": [{\"name\": \"valueInput1\", \"type\": \"string\"},{\"name\": \"valueInput2\",\"type\":[{\"type\":\"enum\",\"name\":\"actorobjType\",\"symbols\":[\"Agent\",\"Group\"]},\"null\"],\"default\":null}]}",
    "records": [
        {
            "key": {
                "keyInput": "testUser-key"
            },
            "value": {
                "valueInput1": "testUser-value",
                "valueInput2": "Agent"
            }
        }
    ]
}

I am getting the following error when I am trying to insert a record using above request payload -

{
  "error_code": 42203,
  "message": "Conversion of JSON to Avro failed: Failed to convert JSON to Avro: Expected start-union. Got VALUE_STRING"
}

After searching in different sites including stackoverflow, I came through a suggestion

asking to explicitly specify the type while passing the record as below -

{
    "key_schema": "{\"type\": \"record\", \"name\": \"key\", \"fields\": [{\"name\": \"keyInput\", \"type\": \"string\"}]}",
    "value_schema": "{\"type\": \"record\", \"name\": \"value\", \"fields\": [{\"name\": \"valueInput1\", \"type\": \"string\"},{\"name\": \"valueInput2\",\"type\":[{\"type\":\"enum\",\"name\":\"actorobjType\",\"symbols\":[\"Agent\",\"Group\"]},\"null\"],\"default\":null}]}",
    "records": [
        {
            "key": {
                "keyInput": "testUser-key"
            },
            "value": {
                "valueInput1": "testUser-value",
                "valueInput2": {
                    "enum": "Agent"
                }
            }
        }
    ]
}

But then I face the below error -

{
  "error_code": 42203,
  "message": "Conversion of JSON to Avro failed: Failed to convert JSON to Avro: Unknown union branch enum"
}

The same suggestion worked fine for unions with other types like string and map, but with unions including enum, that does not seem to work.

I also thought there may be some other type which needs to be used for enum specification, Hence I tried some other words like below -

"valueInput2": {
                    "string": "Agent"
                }

and

"valueInput2": {
                    "enumeration": "Agent"
                }

But none of them seem to work. Please help me resolve this.


来源: stackexchange

问:
how to transform sub views along with main view in landscape mode
i am crating an application.

That contains one main view and 4 subviews.

i add all these 4 views as subview with their respected button actions.

Now i need to support my application to both land scape and portrayed.

when ever i rotate my simulator from portrayed  to land scape sub view are not rotated.

it will shown like this.  link1,link2

some where i found we need to transform our self when device detect rotation.

i did n't find how can i,

can any one please help me.

Thank u in advance.

答:
First of all you have to implement
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
and return YES for all supported orientations.

Then you either implement - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration and setup you subviews' properties accordingly or specify proper autoresizingMask for the subviews

ContentLicense: CC BY-SA 2.5


问:
undefined is not an object (evaluating 'nativeVersion.major')
I got this error when I built and started a react-native app on expo.

The app was built using create-react-native-app and ran on an Android device.

答: Updating to the latest version of expo app fixed this for me. Expo was probably expecting a previous version of react-native library and I was using the latest one.</p>

ContentLicense: CC BY-SA 3.0


问:
Correlation in R - missing values
I want to run correlations on the following dataset. I want correlations among all (V1 with V2, V3, V4, V5; V2 with V1, V3, V4, V5 and so on...). I want the correlation coefficient and the p-values.

mydataset

```<code>   Group    V1        V2          V3         V4       V5
   OH      0.3        5          -3.09      2.5      NA
   OH      0.5        1           NA        1.8      2.5
   ON      2          2.5         NA       -3.11    -7.5
   OH      1.5       -3.35       -0.82       NA     -2.5
   ON      6.5       -2.85        2.5        NA      NA
   OH      3          0.5         1.8      -2.85     NA
</code>```

I ran this code

```<code>    correlations <- corr.test (mydataset, use = "pairwise").
</code>```

I have also run:

```<code>    correlations <- cor(mydataset, use = "complete.obs", method = "pearson")
</code>```

I don't know how to deal with missing values. And I am not getting any output whatsoever. I keep getting this error:

```<code>    Error in cor(x, use = use, method = method) : 'x' must be numeric
</code>```

Any suggestions on what might work?

Thanks!

答:
corr.test(test[2:6], use = 'pairwise') is what you want. You have to exclude the first column, which is a character vector. Below is a reprex with output. You get the coefficients and p-values.

library('tidyverse')
#> ── Attaching packages ─────────────────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
#> ✔ ggplot2 2.2.1     ✔ purrr   0.2.4
#> ✔ tibble  1.3.4     ✔ dplyr   0.7.4
#> ✔ tidyr   0.7.2     ✔ stringr 1.2.0
#> ✔ readr   1.1.1     ✔ forcats 0.2.0
#> ── Conflicts ────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag()    masks stats::lag()
library('psych')
#>
#> Attaching package: 'psych'
#> The following objects are masked from 'package:ggplot2':
#>
#>     %+%, alpha
test = tibble::tribble(
  ~Group, ~V1, ~V2, ~V3, ~V4, ~V5,
  'OH',      0.3,        5,          -3.09,      2.5,      NA,
  'OH',      0.5,        1,           NA,        1.8,      2.5,
  'ON',      2 ,         2.5,         NA,       -3.11,    -7.5,
  'OH',      1.5,       -3.35,       -0.82,       NA,     -2.5,
  'ON',      6.5,       -2.85,        2.5,        NA,      NA,
  'OH',      3,          0.5,         1.8,      -2.85,     NA
)
corr.test(test[2:6], use = 'pairwise')
#> Warning in sqrt(n - 2): NaNs produced
#> Warning in corr.test(test[2:6], use = "pairwise"): Number of subjects must
#> be greater than 3 to find confidence intervals.
#> Warning in sqrt(n[lower.tri(n)] - 3): NaNs produced
#> Call:corr.test(x = test[2:6], use = "pairwise")
#> Correlation matrix
#>       V1    V2    V3    V4    V5
#> V1  1.00 -0.59  0.89 -0.94 -0.98
#> V2 -0.59  1.00 -0.64  0.49 -0.25
#> V3  0.89 -0.64  1.00 -1.00    NA
#> V4 -0.94  0.49 -1.00  1.00  1.00
#> V5 -0.98 -0.25    NA  1.00  1.00
#> Sample Size
#>    V1 V2 V3 V4 V5
#> V1  6  6  4  4  3
#> V2  6  6  4  4  3
#> V3  4  4  4  2  1
#> V4  4  4  2  4  2
#> V5  3  3  1  2  3
#> Probability values (Entries above the diagonal are adjusted for multiple tests.)
#>      V1   V2   V3   V4   V5
#> V1 0.00 0.86 0.66 0.45 0.66
#> V2 0.22 0.00 1.00 1.00 1.00
#> V3 0.11 0.36 0.00  NaN   NA
#> V4 0.06 0.51  NaN 0.00  NaN
#> V5 0.12 0.84   NA  NaN 0.00
#>
#>  To see confidence intervals of the correlations, print with the short=FALSE option
```

Title: Correlation in R - missing values

Body:
I want to run correlations on the following dataset. I want correlations among all (V1 with V2, V3, V4, V5; V2 with V1, V3, V4, V5 and so on...). I want the correlation coefficient and the p-values.

mydataset

   Group    V1        V2          V3         V4       V5
   OH      0.3        5          -3.09      2.5      NA
   OH      0.5        1           NA        1.8      2.5
   ON      2          2.5         NA       -3.11    -7.5
   OH      1.5       -3.35       -0.82       NA     -2.5
   ON      6.5       -2.85        2.5        NA      NA
   OH      3          0.5         1.8      -2.85     NA

I ran this code

    correlations <- corr.test (mydataset, use = "pairwise").

I have also run:

    correlations <- cor(mydataset, use = "complete.obs", method = "pearson")

I don't know how to deal with missing values. And I am not getting any output whatsoever. I keep getting this error:

    Error in cor(x, use = use, method = method) : 'x' must be numeric

Any suggestions on what might work?

Thanks!


问:
how to set index.html to another page, not homepage
I want to show index.html on special page '/chess', not on home page '/'.

Simple

```<code>app.get('/chess', function(req, res) {
 res.sendFile(__dirname + '/public/index.html');

});
</code>```

doesn't work.

I get the below error

答:
Don't forget to declare the public director using use method. </p>

```<code>app.use(express.static(__dirname + '/public'));
</code>```

Body:
I want to show index.html on special page '/chess', not on home page '/'.

Simple

app.get('/chess', function(req, res) {
 res.sendFile(__dirname + '/public/index.html');

});

doesn't work.

I get the below error

Body:
Don't forget to declare the public director using use method.

app.use(express.static(__dirname + '/public'));


问:
WordPress Rest API Image Upload CORS Issue
I'm having a (seemingly simple) problem uploading images to Wordpress through it's REST API. Here's the situation right now:

I'm currently developing locally on my machine so I'm running Wordpress with MAMP.

I'm using React on the front end of my application and using Wordpress REST API as the backend; so I'm running a headless CMS app right now.

Using Postman, I am able to upload an image onto Wordpress. I can go to the Wordpress admin panel and see the image actually there in the dashboard. I've got authentication down too, I'm logged in both on my app and have the JWT token being passed in with the headers with Postman.

The Problem: I'm using Axios to make the same Post request as I am from Postman but I get some sort of CORS error and I'm not sure how to safely enable CORS on the Wordpress Backend.

Here's the exact error from my browser's console:

Failed to load http://localhost:8888/wp-json/wp/v2/media: Request header field cache-control is not allowed by
  Access-Control-Allow-Headers in preflight response.

My AJAX Call (this is in React and using Axios)

onFileChange(event) {
    let files = event.target.files || event.dataTransfer.files;
    if (!files.length) {
        console.log('no files');
    } else {
      axios.post('http://localhost:8888/wp-json/wp/v2/media', files, {
        headers: {
          'content-type': 'image/png',
          'content-disposition': 'attachment; filename=testImageNum2.png',
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'cache-control': 'no-cache',
        }
      })
    }
  }

  render() {
    return (

Upload A File Here:

        <input id="file_selector" type="file" name="file" onChange={this.onFileChange} />

    )
  }```

There doesn't seem to be too much information on this topic with the WP REST API at the moment. If anyone could help shed some light on this topic, I would be extremely grateful!

答: The error states that your client (axios) is sending a request which has a "cache-control" header ('cache-control': 'no-cache',) but cache-control isn't in Apache's Access-Control-Allow-Headers list of allowed headers. Add "cache-control" to that list or disable it in axios.

Body:
I'm having a (seemingly simple) problem uploading images to Wordpress through it's REST API. Here's the situation right now:

I'm currently developing locally on my machine so I'm running Wordpress with MAMP.

I'm using React on the front end of my application and using Wordpress REST API as the backend; so I'm running a headless CMS app right now.

Using Postman, I am able to upload an image onto Wordpress. I can go to the Wordpress admin panel and see the image actually there in the dashboard. I've got authentication down too, I'm logged in both on my app and have the JWT token being passed in with the headers with Postman.

The Problem: I'm using Axios to make the same Post request as I am from Postman but I get some sort of CORS error and I'm not sure how to safely enable CORS on the Wordpress Backend.

Here's the exact error from my browser's console:

Failed to load http://localhost:8888/wp-json/wp/v2/media: Request header field cache-control is not allowed by
  Access-Control-Allow-Headers in preflight response.

My AJAX Call (this is in React and using Axios)

onFileChange(event) {
    let files = event.target.files || event.dataTransfer.files;
    if (!files.length) {
        console.log('no files');
    } else {
      axios.post('http://localhost:8888/wp-json/wp/v2/media', files, {
        headers: {
          'content-type': 'image/png',
          'content-disposition': 'attachment; filename=testImageNum2.png',
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'cache-control': 'no-cache',
        }
      })
    }
  }

  render() {
    return (

Upload A File Here:

        <input id="file_selector" type="file" name="file" onChange={this.onFileChange} />

    )
  }

There doesn't seem to be too much information on this topic with the WP REST API at the moment. If anyone could help shed some light on this topic, I would be extremely grateful!


问:
Read in a text file 1 line at a time and split the words into an Array Java
The user selects a text file. I take the file and split 1 line into individual words. I then take an if statement to see if one of the words is equal to the word "the". There is the word "the" in the first line however it's not saying there is.IT IS picking up other "the"s just not the very first one (yes I know this is a mess, but it's what I'm working with at the moment)</p>

```<code>try {
    BufferedReader br = new BufferedReader(new FileReader(test));
    //String text = "";
    String line = br.readLine();

    //while (line != null)
    if(line != null) {
        for(int j = 0; j < 20; j++) //loops through first 20 lines {
            if(line != null) {
                //text += line;
                String[] words = line.toLowerCase().split(" ");
                for(int i = 0; i < words.length; i++){//loops array of split up words
                    if(words[i].equals("the")) {
                        System.out.println("Found T H E");
                    } else {
                        System.out.println("Didn't find the");
                        System.out.println(words[i]);
                    }
                    line = br.readLine();
                }
            } else {
                System.out.println("");
            }
        }
    } else {
        System.out.println("It's null");
    }
    br.close();
} catch (Exception ex) {
    System.err.println("Error" + ex);
}
</code>```

答:
Try moving the line

```<code>line = br.readLine();
</code>```

outside of the loop

```<code>for(int i = 0; i < words.length; i++){
</code>```

Body:
The user selects a text file. I take the file and split 1 line into individual words. I then take an if statement to see if one of the words is equal to the word "the". There is the word "the" in the first line however it's not saying there is.IT IS picking up other "the"s just not the very first one (yes I know this is a mess, but it's what I'm working with at the moment)

try {
    BufferedReader br = new BufferedReader(new FileReader(test));
    //String text = "";
    String line = br.readLine();

    //while (line != null)
    if(line != null) {
        for(int j = 0; j < 20; j++) //loops through first 20 lines {
            if(line != null) {
                //text += line;
                String[] words = line.toLowerCase().split(" ");
                for(int i = 0; i < words.length; i++){//loops array of split up words
                    if(words[i].equals("the")) {
                        System.out.println("Found T H E");
                    } else {
                        System.out.println("Didn't find the");
                        System.out.println(words[i]);
                    }
                    line = br.readLine();
                }
            } else {
                System.out.println("");
            }
        }
    } else {
        System.out.println("It's null");
    }
    br.close();
} catch (Exception ex) {
    System.err.println("Error" + ex);
}

Body:
Try moving the line

line = br.readLine();

outside of the loop

for(int i = 0; i < words.length; i++){


问:
Making elements appear and disappear loop
I have a problem with the below code. This is supposed to return the section on the page that has an id, so I can then remove the id and give it to another section that is invisible, making the new one visible. These are tied to a click eventhandler. What happens though, is that the next window appears for a fraction of a second and then disappears. I need it to stay, and on the next click on the button the next section should appear etc.
I believe it might have something to do with the loop, but I can't figure out what. What am I missing?

Edit: I added everything HTML, CSS JS now so everything is there.

JS

```<code>var sections = document.querySelectorAll("section");

var btns = document.querySelector("input[type='submit']");

//*
This part should switch to the next ingredient selection
*//
function next(){
    var i=0;
    while (i+1 <= sections.length) {
if (sections[i].hasAttribute ("id")) {
        sections[i].removeAttribute("id");
        i=i+1;
        sections[i].setAttribute("id","visible");
        break;
} }}

btns.addEventListener('click', next);
</code>```

HTML

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Pete's Pizzeria</title>
        <link href="https://fonts.googleapis.com/css?family=Kaushan+Script|Mr+Dafoe|Nothing+You+Could+Do|Yellowtail|Roboto" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <h1 id="mainh1">Pete's pizzeria</h1>
        <main>
        <section id="visible">
            <header>
                <h1>Choose your size!</h1>
            </header>
            <form>
                <p>Personal<input type="radio" name="size" value="personal" checked><span class="price" data-price="6">$6.00</span> </p>
                <p>Medium<input type="radio" name="size" value="medium"><span class="price" value=10>$10.00</span> </p>
                <p>Large<input type="radio" name="size" value="large"><span class="price" data-price="14">$14.00</span></p>
                <p>Extra Large <input type="radio" name="size" value="extralarge"><span class="price" data-price="16">$16.00</span></p>
                <input type="submit" value="Next">
            </form>
        </section>
        <section>
            <header>
                <h1>Nice to meat you!</h1>
                <p>The first meat item is complimentary. All additional meat items cost $1 each.</p>
            </header>
            <form>
                <p>Pepperoni<input type="checkbox" name="meat" value="pepperoni" checked></p>
                <p>Sausage<input type="checkbox" name="meat" value="sausage" ></p>
                <p>Canadian Bacon<input type="checkbox" name="meat" value="canadianBacon" ></p>
                <p>Ground Beef <input type="checkbox" name="meat" value="groundBeef"></p>
                <p>Anchovy <input type="checkbox" name="meat" value="anchovy"></p>
                <p>Chicken <input type="checkbox" name="meat" value="chicken"></p>
                <input type="submit" value="Next">
            </form>
        </section>
         <section>
             <header>
                 <h1>How cheesy<br>are you?</h1>
             </header>
            <form>
                <p>Regular<input type="radio" name="cheese" value="regularcheese" checked></p>
                <p>No cheese<input type="radio" name="cheese" value="nocheese" ></p>
                <p>Extra Cheese <span data-price="3">(+$3.00)</span><input type="radio" name="cheese" value="extracheese"></p>             <input type="submit" value="Next">
            </form>
        </section>
        <section>
            <header>
                <h1>Everyone bites<br>the crust</h1>
            </header>
            <form>
                <p>Plain Crust<input type="radio" name="crust" value="plainCrust" checked></p>
                <p>Garlic Butter Crust<input type="radio" name="crust" value="garlicButterCrust" ></p>
                <p>Cheese Stuffed Crust <span data-price="3">(+$3.00)</span><input type="radio" name="crust" value="cheeseStuffedCrust" ></p>
                <p>Spicy Crust<input type="radio" name="crust" value="spicyCrust"></p>
                <p>House Special Crust<input type="radio" name="crust" value="houseSpecialCrust"></p>
                <input type="submit" value="Next">
            </form>
        </section>
        <section>
            <header>
                <h1>Our pizzas are saucy</h1>
            </header>
            <form>
                <p>Marinara sauce<input type="radio" name="sauce" value="marinaraSauce" checked></p>
                <p>White sauce<input type="radio" name="sauce" value="garlicButterCrust" ></p>
                <p>Barbeque sauce<input type="radio" name="sauce" value="BBQsauce" ></p>
                <p>No Sauce<input type="radio" name="sauce" value="noSauce"></p>
                <input type="submit" value="Next">
            </form>
        </section>
        <section>
            <form>

                <header>
                    <h1>Always eat your veggies</h1>
                    The first type of veggie is complimentary. All additional veggie items cost $1 each.
                </header>

                <p>Tomatoes<input type="checkbox" name="veggies" value="tomatoes" checked></p>
                <p>Onions<input type="checkbox" name="veggies" value="onions" ></p>
                <p>Olives<input type="checkbox" name="veggies" value="olives" ></p>
                <p>Green Peppers<input type="checkbox" name="veggies" value="greenPeppers"></p>
                <p>Mushrooms<input type="checkbox" name="veggies" value="mushrooms"></p>
                <p>Pineapple <input type="checkbox" name="veggies" value="pineapple"></p>
                <p>Spinach <input type="checkbox" name="veggies" value="spinach"></p>
                <p>Jalapeno <input type="checkbox" name="veggies" value="jalapeno"></p>
                <input type="submit" value="Next">
            </form>
        </section>
        <section id="tally">
            <h1>The bottom line</h1>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
        </section>
</main>

        <script src="scripts.js"></script>
    </body>
</html>
</code>```

CSS

```<code>body {
    margin: 0 0 auto auto;
    background-image: url(images/food-pizza-box-chalkboard.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    font-family: 'Roboto', sans-serif;
    }

/*
==============================================================
Pete's pizzera title
==============================================================
*/
#mainh1 {
    font-family: 'Nothing You Could Do', cursive;
    color: white;
    position: absolute;
    top: 2rem;
    left: 3rem;
    font-size: 2.5rem;
    text-shadow: 1px 1px 2px #ffffff;
}
/*
==============================================================
The box with the content
==============================================================
*/
section {
    background-color: rgba(255,255,255,0.5);
    position: absolute;
    top:0 0;
    margin-left: 3rem;
    margin-top: 8rem;
    padding: 1.5rem;
    border-radius: 15px;
    border: 5px solid rgba(232, 232, 232,0.5);
    width: 15rem;
    box-shadow: 5px 5px 5px rgba(0,0,0,0.5);
    display: none;}

/*
==============================================================
The class that will hide all boxes unless the person clicks on next, in which case the next is going to appear.
==============================================================
*/

#visible {
    display: block;
}

/*The title of the box*/
h1 {
    font-family: 'Nothing You Could Do', cursive;
    font-size: 1.7rem;
    margin:0;
}

/*
==============================================================
aligning the check and radio buttons vertically
==============================================================
*/
input[type="checkbox"],input[type="radio"]{
    display: inline-block;
    position: absolute;
    right: 1rem;
}
/*
==============================================================
aligning the prices vertically
==============================================================
*/
span {
    display: inline-block;
    position: absolute;
    right: 4rem;
}
/*
==============================================================
line-spacing of paragraphs in the forms
==============================================================
*/

form p {
    padding: 0;
    margin: 0.5rem;
}

/*
==============================================================
Formatting of the "Next" button
==============================================================
*/
input[type="submit"] {
    width: 100px;
    margin-top: 25px;
    border-bottom-right-radius: 10px;
    border-top-right-radius: 10px;
    padding: 0.25rem;
}
/*
==============================================================
The box with the content
==============================================================
*/
#tally {
    background-color: rgba(255,255,255,0.7);
    position: absolute;
    top:0;
    right: 15rem;
    padding: 1.5rem;
    border-radius: 15px;
    border: 5px solid rgba(232, 232, 232,0.5);
    width: 15rem;
    box-shadow: 5px 5px 5px rgba(0,0,0,0.5)
    }

#tally h1 {
    top: 2rem;
}

#tally p {
margin: 0.3rem;
}
</code>```

答:
var btns = document.getElementsByClassName("submit");

//console.log(btns);
function next(){
  var sections = document.getElementsByClassName('section-card');
    //console.log(sections);
  for(var i = 0; i < sections.length - 1; i++){
if (sections[i].classList.contains('visible')) {
        //sections[i].removeAttribute("id");
        sections[i].classList.remove('visible');

        //sections[i].setAttribute("id","visible");
        sections[i+1].classList.add('visible');
        break;
} }}

for(var i = 0; i < btns.length; i++){
  btns[i].addEventListener('click', next);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    margin: 0 0 auto auto;
    background-image: url(images/food-pizza-box-chalkboard.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    font-family: 'Roboto', sans-serif;
    }

/*
==============================================================
Pete's pizzera title
==============================================================
*/
#mainh1 {
    font-family: 'Nothing You Could Do', cursive;
    color: white;
    position: absolute;
    top: 2rem;
    left: 3rem;
    font-size: 2.5rem;
    text-shadow: 1px 1px 2px #ffffff;
}
/*
==============================================================
The box with the content
==============================================================
*/
.section-card {
    background-color: rgba(255,255,255,0.5);
    position: absolute;
    top:0 0;
    margin-left: 3rem;
    margin-top: 8rem;
    padding: 1.5rem;
    border-radius: 15px;
    border: 5px solid rgba(232, 232, 232,0.5);
    width: 15rem;
    box-shadow: 5px 5px 5px rgba(0,0,0,0.5);
    display: none;}

/*
==============================================================
The class that will hide all boxes unless the person clicks on next, in which case the next is going to appear.
==============================================================
*/
.section-card.visible{
  background-color: rgba(255,255,255,0.5);
  position: absolute;
  top:0 0;
  margin-left: 3rem;
  margin-top: 8rem;
  padding: 1.5rem;
  border-radius: 15px;
  border: 5px solid rgba(232, 232, 232,0.5);
  width: 15rem;
  box-shadow: 5px 5px 5px rgba(0,0,0,0.5);
  display: block;}
}

/*The title of the box*/
h1 {
    font-family: 'Nothing You Could Do', cursive;
    font-size: 1.7rem;
    margin:0;
}

/*
==============================================================
aligning the check and radio buttons vertically
==============================================================
*/
input[type="checkbox"],input[type="radio"]{
    display: inline-block;
    position: absolute;
    right: 1rem;
}
/*
==============================================================
aligning the prices vertically
==============================================================
*/
span {
    display: inline-block;
    position: absolute;
    right: 4rem;
}
/*
==============================================================
line-spacing of paragraphs in the forms
==============================================================
*/

form p {
    padding: 0;
    margin: 0.5rem;
}

/*
==============================================================
Formatting of the "Next" button
==============================================================
*/
.submit {
    width: 100px;
    margin-top: 25px;
    border-bottom-right-radius: 10px;
    border-top-right-radius: 10px;
    padding: 0.25rem;
}
/*
==============================================================
The box with the content
==============================================================
*/
#tally {
    background-color: rgba(255,255,255,0.7);
    position: absolute;
    top:0;
    right: 15rem;
    padding: 1.5rem;
    border-radius: 15px;
    border: 5px solid rgba(232, 232, 232,0.5);
    width: 15rem;
    box-shadow: 5px 5px 5px rgba(0,0,0,0.5)
    }

#tally h1 {
    top: 2rem;
}

#tally p {
margin: 0.3rem;
}</code>```

Pete's pizzeria

Choose your size!

Personal<input type="radio" name="size" value="personal" checked>$6.00

Medium<input type="radio" name="size" value="medium">$10.00

Large<input type="radio" name="size" value="large">$14.00

Extra Large <input type="radio" name="size" value="extralarge">$16.00

                <button class="submit">Next</button>

Nice to meat you!

The first meat item is complimentary. All additional meat items cost $1 each.

Pepperoni<input type="checkbox" name="meat" value="pepperoni" checked>

Sausage<input type="checkbox" name="meat" value="sausage" >

Canadian Bacon<input type="checkbox" name="meat" value="canadianBacon" >

Ground Beef <input type="checkbox" name="meat" value="groundBeef">

Anchovy <input type="checkbox" name="meat" value="anchovy">

Chicken <input type="checkbox" name="meat" value="chicken">

                <button class="submit">Next</button>

How cheesy
are you?

Regular<input type="radio" name="cheese" value="regularcheese" checked>

No cheese<input type="radio" name="cheese" value="nocheese" >

Extra Cheese (+$3.00)<input type="radio" name="cheese" value="extracheese">

           <button class="submit">Next</button>

Everyone bites
the crust

Plain Crust<input type="radio" name="crust" value="plainCrust" checked>

Garlic Butter Crust<input type="radio" name="crust" value="garlicButterCrust" >

Cheese Stuffed Crust (+$3.00)<input type="radio" name="crust" value="cheeseStuffedCrust" >

Spicy Crust<input type="radio" name="crust" value="spicyCrust">

House Special Crust<input type="radio" name="crust" value="houseSpecialCrust">

                <button class="submit">Next</button>

Our pizzas are saucy

Marinara sauce<input type="radio" name="sauce" value="marinaraSauce" checked>

White sauce<input type="radio" name="sauce" value="garlicButterCrust" >

Barbeque sauce<input type="radio" name="sauce" value="BBQsauce" >

No Sauce<input type="radio" name="sauce" value="noSauce">

                <button class="submit">Next</button>

Always eat your veggies

                    The first type of veggie is complimentary. All additional veggie items cost $1 each.

Tomatoes<input type="checkbox" name="veggies" value="tomatoes" checked>

Onions<input type="checkbox" name="veggies" value="onions" >

Olives<input type="checkbox" name="veggies" value="olives" >

Green Peppers<input type="checkbox" name="veggies" value="greenPeppers">

Mushrooms<input type="checkbox" name="veggies" value="mushrooms">

Pineapple <input type="checkbox" name="veggies" value="pineapple">

Spinach <input type="checkbox" name="veggies" value="spinach">

Jalapeno <input type="checkbox" name="veggies" value="jalapeno">

            <button class="submit">Next</button>

The bottom line

testPizzaIngredient $10

testPizzaIngredient $10

testPizzaIngredient $10

testPizzaIngredient $10

testPizzaIngredient $10

testPizzaIngredient $10

testPizzaIngredient $10

```

Updated with no JQuery

Here is a basic example of hiding and displaying elements on button click. I utilized opacity for transitions. You can just use display: block and display: none if you just want simple display/hide.

NEW UPDATE: (Based on entire code posted)
First of all, there is a problem with your form. It errors out on clicking next (which is why your sections disappear) because it wants a POST request. I changed the sections to divs, got rid of the forms, and changed input submits to .

You had a potentially infinite loop with your while statement, if the if statement inside is never entered, your loop will never stop, changed to a for loop to ensure it will stop.

You were not grabbing the sections again on the next button click (which causes the infinite loop mentioned above because no sections have the visible id). Now, you grab the sections every time a button is clicked.

Changed your removing and adding 'id' to removing and adding a class. Again, highly advise against changing css based on removing and adding an Id....

You also were not binding the click event to every button, just the first one, the for loop through the buttons now binds a click event to all the buttons. If you run my example now, it goes through all of your cards.

Body:
I have a problem with the below code. This is supposed to return the section on the page that has an id, so I can then remove the id and give it to another section that is invisible, making the new one visible. These are tied to a click eventhandler. What happens though, is that the next window appears for a fraction of a second and then disappears. I need it to stay, and on the next click on the button the next section should appear etc.
I believe it might have something to do with the loop, but I can't figure out what. What am I missing?

Edit: I added everything HTML, CSS JS now so everything is there.

JS

var sections = document.querySelectorAll("section");

var btns = document.querySelector("input[type='submit']");

//*
This part should switch to the next ingredient selection
*//
function next(){
    var i=0;
    while (i+1 <= sections.length) {
if (sections[i].hasAttribute ("id")) {
        sections[i].removeAttribute("id");
        i=i+1;
        sections[i].setAttribute("id","visible");
        break;
} }}

btns.addEventListener('click', next);

HTML

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Pete's Pizzeria</title>
        <link href="https://fonts.googleapis.com/css?family=Kaushan+Script|Mr+Dafoe|Nothing+You+Could+Do|Yellowtail|Roboto" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="style.css">

Pete's pizzeria

Choose your size!

            <form>

Personal<input type="radio" name="size" value="personal" checked>$6.00

Medium<input type="radio" name="size" value="medium">$10.00

Large<input type="radio" name="size" value="large">$14.00

Extra Large <input type="radio" name="size" value="extralarge">$16.00

                <input type="submit" value="Next">
            </form>

Nice to meat you!

The first meat item is complimentary. All additional meat items cost $1 each.

            <form>

Pepperoni<input type="checkbox" name="meat" value="pepperoni" checked>

Sausage<input type="checkbox" name="meat" value="sausage" >

Canadian Bacon<input type="checkbox" name="meat" value="canadianBacon" >

Ground Beef <input type="checkbox" name="meat" value="groundBeef">

Anchovy <input type="checkbox" name="meat" value="anchovy">

Chicken <input type="checkbox" name="meat" value="chicken">

                <input type="submit" value="Next">
            </form>

How cheesy
are you?

            <form>

Regular<input type="radio" name="cheese" value="regularcheese" checked>

No cheese<input type="radio" name="cheese" value="nocheese" >

Extra Cheese (+$3.00)<input type="radio" name="cheese" value="extracheese">
             <input type="submit" value="Next">
            </form>

Everyone bites
the crust

            <form>

Plain Crust<input type="radio" name="crust" value="plainCrust" checked>

Garlic Butter Crust<input type="radio" name="crust" value="garlicButterCrust" >

Cheese Stuffed Crust (+$3.00)<input type="radio" name="crust" value="cheeseStuffedCrust" >

Spicy Crust<input type="radio" name="crust" value="spicyCrust">

House Special Crust<input type="radio" name="crust" value="houseSpecialCrust">

                <input type="submit" value="Next">
            </form>

Our pizzas are saucy

            <form>

Marinara sauce<input type="radio" name="sauce" value="marinaraSauce" checked>

White sauce<input type="radio" name="sauce" value="garlicButterCrust" >

Barbeque sauce<input type="radio" name="sauce" value="BBQsauce" >

No Sauce<input type="radio" name="sauce" value="noSauce">

                <input type="submit" value="Next">
            </form>

            <form>

Always eat your veggies

                    The first type of veggie is complimentary. All additional veggie items cost $1 each.

Tomatoes<input type="checkbox" name="veggies" value="tomatoes" checked>

Onions<input type="checkbox" name="veggies" value="onions" >

Olives<input type="checkbox" name="veggies" value="olives" >

Green Peppers<input type="checkbox" name="veggies" value="greenPeppers">

Mushrooms<input type="checkbox" name="veggies" value="mushrooms">

Pineapple <input type="checkbox" name="veggies" value="pineapple">

Spinach <input type="checkbox" name="veggies" value="spinach">

Jalapeno <input type="checkbox" name="veggies" value="jalapeno">

                <input type="submit" value="Next">
            </form>

The bottom line

testPizzaIngredient $10

testPizzaIngredient $10

testPizzaIngredient $10

testPizzaIngredient $10

testPizzaIngredient $10

testPizzaIngredient $10

testPizzaIngredient $10

CSS

body {
    margin: 0 0 auto auto;
    background-image: url(images/food-pizza-box-chalkboard.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    font-family: 'Roboto', sans-serif;
    }

/*
==============================================================
Pete's pizzera title
==============================================================
*/
#mainh1 {
    font-family: 'Nothing You Could Do', cursive;
    color: white;
    position: absolute;
    top: 2rem;
    left: 3rem;
    font-size: 2.5rem;
    text-shadow: 1px 1px 2px #ffffff;
}
/*
==============================================================
The box with the content
==============================================================
*/
section {
    background-color: rgba(255,255,255,0.5);
    position: absolute;
    top:0 0;
    margin-left: 3rem;
    margin-top: 8rem;
    padding: 1.5rem;
    border-radius: 15px;
    border: 5px solid rgba(232, 232, 232,0.5);
    width: 15rem;
    box-shadow: 5px 5px 5px rgba(0,0,0,0.5);
    display: none;}

/*
==============================================================
The class that will hide all boxes unless the person clicks on next, in which case the next is going to appear.
==============================================================
*/

#visible {
    display: block;
}

/*The title of the box*/
h1 {
    font-family: 'Nothing You Could Do', cursive;
    font-size: 1.7rem;
    margin:0;
}

/*
==============================================================
aligning the check and radio buttons vertically
==============================================================
*/
input[type="checkbox"],input[type="radio"]{
    display: inline-block;
    position: absolute;
    right: 1rem;
}
/*
==============================================================
aligning the prices vertically
==============================================================
*/
span {
    display: inline-block;
    position: absolute;
    right: 4rem;
}
/*
==============================================================
line-spacing of paragraphs in the forms
==============================================================
*/

form p {
    padding: 0;
    margin: 0.5rem;
}

/*
==============================================================
Formatting of the "Next" button
==============================================================
*/
input[type="submit"] {
    width: 100px;
    margin-top: 25px;
    border-bottom-right-radius: 10px;
    border-top-right-radius: 10px;
    padding: 0.25rem;
}
/*
==============================================================
The box with the content
==============================================================
*/
#tally {
    background-color: rgba(255,255,255,0.7);
    position: absolute;
    top:0;
    right: 15rem;
    padding: 1.5rem;
    border-radius: 15px;
    border: 5px solid rgba(232, 232, 232,0.5);
    width: 15rem;
    box-shadow: 5px 5px 5px rgba(0,0,0,0.5)
    }

#tally h1 {
    top: 2rem;
}

#tally p {
margin: 0.3rem;
}

Body:
var btns = document.getElementsByClassName("submit");

//console.log(btns);
function next(){
  var sections = document.getElementsByClassName('section-card');
    //console.log(sections);
  for(var i = 0; i < sections.length - 1; i++){
if (sections[i].classList.contains('visible')) {
        //sections[i].removeAttribute("id");
        sections[i].classList.remove('visible');

        //sections[i].setAttribute("id","visible");
        sections[i+1].classList.add('visible');
        break;
} }}

for(var i = 0; i < btns.length; i++){
  btns[i].addEventListener('click', next);
}

body {
    margin: 0 0 auto auto;
    background-image: url(images/food-pizza-box-chalkboard.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    font-family: 'Roboto', sans-serif;
    }

/*
==============================================================
Pete's pizzera title
==============================================================
*/
#mainh1 {
    font-family: 'Nothing You Could Do', cursive;
    color: white;
    position: absolute;
    top: 2rem;
    left: 3rem;
    font-size: 2.5rem;
    text-shadow: 1px 1px 2px #ffffff;
}
/*
==============================================================
The box with the content
==============================================================
*/
.section-card {
    background-color: rgba(255,255,255,0.5);
    position: absolute;
    top:0 0;
    margin-left: 3rem;
    margin-top: 8rem;
    padding: 1.5rem;
    border-radius: 15px;
    border: 5px solid rgba(232, 232, 232,0.5);
    width: 15rem;
    box-shadow: 5px 5px 5px rgba(0,0,0,0.5);
    display: none;}

/*
==============================================================
The class that will hide all boxes unless the person clicks on next, in which case the next is going to appear.
==============================================================
*/
.section-card.visible{
  background-color: rgba(255,255,255,0.5);
  position: absolute;
  top:0 0;
  margin-left: 3rem;
  margin-top: 8rem;
  padding: 1.5rem;
  border-radius: 15px;
  border: 5px solid rgba(232, 232, 232,0.5);
  width: 15rem;
  box-shadow: 5px 5px 5px rgba(0,0,0,0.5);
  display: block;}
}

/*The title of the box*/
h1 {
    font-family: 'Nothing You Could Do', cursive;
    font-size: 1.7rem;
    margin:0;
}

/*
==============================================================
aligning the check and radio buttons vertically
==============================================================
*/
input[type="checkbox"],input[type="radio"]{
    display: inline-block;
    position: absolute;
    right: 1rem;
}
/*
==============================================================
aligning the prices vertically
==============================================================
*/
span {
    display: inline-block;
    position: absolute;
    right: 4rem;
}
/*
==============================================================
line-spacing of paragraphs in the forms
==============================================================
*/

form p {
    padding: 0;
    margin: 0.5rem;
}

/*
==============================================================
Formatting of the "Next" button
==============================================================
*/
.submit {
    width: 100px;
    margin-top: 25px;
    border-bottom-right-radius: 10px;
    border-top-right-radius: 10px;
    padding: 0.25rem;
}
/*
==============================================================
The box with the content
==============================================================
*/
#tally {
    background-color: rgba(255,255,255,0.7);
    position: absolute;
    top:0;
    right: 15rem;
    padding: 1.5rem;
    border-radius: 15px;
    border: 5px solid rgba(232, 232, 232,0.5);
    width: 15rem;
    box-shadow: 5px 5px 5px rgba(0,0,0,0.5)
    }

#tally h1 {
    top: 2rem;
}

#tally p {
margin: 0.3rem;
}

        <h1 id="mainh1">Pete's pizzeria</h1>
        <main>
        <div class="section-card visible">
            <header>
                <h1>Choose your size!</h1>
            </header>
                <p>Personal<input type="radio" name="size" value="personal" checked><span class="price" data-price="6">$6.00</span> </p>
                <p>Medium<input type="radio" name="size" value="medium"><span class="price" value=10>$10.00</span> </p>
                <p>Large<input type="radio" name="size" value="large"><span class="price" data-price="14">$14.00</span></p>
                <p>Extra Large <input type="radio" name="size" value="extralarge"><span class="price" data-price="16">$16.00</span></p>
                <button class="submit">Next</button>

        </div>
        <div class="section-card">
            <header>
                <h1>Nice to meat you!</h1>
                <p>The first meat item is complimentary. All additional meat items cost $1 each.</p>
            </header>
                <p>Pepperoni<input type="checkbox" name="meat" value="pepperoni" checked></p>
                <p>Sausage<input type="checkbox" name="meat" value="sausage" ></p>
                <p>Canadian Bacon<input type="checkbox" name="meat" value="canadianBacon" ></p>
                <p>Ground Beef <input type="checkbox" name="meat" value="groundBeef"></p>
                <p>Anchovy <input type="checkbox" name="meat" value="anchovy"></p>
                <p>Chicken <input type="checkbox" name="meat" value="chicken"></p>
                <button class="submit">Next</button>

        </div>
         <div class="section-card">
             <header>
                 <h1>How cheesy<br>are you?</h1>
             </header>
                <p>Regular<input type="radio" name="cheese" value="regularcheese" checked></p>
                <p>No cheese<input type="radio" name="cheese" value="nocheese" ></p>
                <p>Extra Cheese <span data-price="3">(+$3.00)</span><input type="radio" name="cheese" value="extracheese"></p>
           <button class="submit">Next</button>
        </div>
        <div class="section-card">
            <header>
                <h1>Everyone bites<br>the crust</h1>
            </header>
                <p>Plain Crust<input type="radio" name="crust" value="plainCrust" checked></p>
                <p>Garlic Butter Crust<input type="radio" name="crust" value="garlicButterCrust" ></p>
                <p>Cheese Stuffed Crust <span data-price="3">(+$3.00)</span><input type="radio" name="crust" value="cheeseStuffedCrust" ></p>
                <p>Spicy Crust<input type="radio" name="crust" value="spicyCrust"></p>
                <p>House Special Crust<input type="radio" name="crust" value="houseSpecialCrust"></p>
                <button class="submit">Next</button>

        </div>
        <div class="section-card">
            <header>
                <h1>Our pizzas are saucy</h1>
            </header>
                <p>Marinara sauce<input type="radio" name="sauce" value="marinaraSauce" checked></p>
                <p>White sauce<input type="radio" name="sauce" value="garlicButterCrust" ></p>
                <p>Barbeque sauce<input type="radio" name="sauce" value="BBQsauce" ></p>
                <p>No Sauce<input type="radio" name="sauce" value="noSauce"></p>
                <button class="submit">Next</button>

        </div>
        <div class="section-card">

                <header>
                    <h1>Always eat your veggies</h1>
                    The first type of veggie is complimentary. All additional veggie items cost $1 each.
                </header>

                <p>Tomatoes<input type="checkbox" name="veggies" value="tomatoes" checked></p>
                <p>Onions<input type="checkbox" name="veggies" value="onions" ></p>
                <p>Olives<input type="checkbox" name="veggies" value="olives" ></p>
                <p>Green Peppers<input type="checkbox" name="veggies" value="greenPeppers"></p>
                <p>Mushrooms<input type="checkbox" name="veggies" value="mushrooms"></p>
                <p>Pineapple <input type="checkbox" name="veggies" value="pineapple"></p>
                <p>Spinach <input type="checkbox" name="veggies" value="spinach"></p>
                <p>Jalapeno <input type="checkbox" name="veggies" value="jalapeno"></p>
            <button class="submit">Next</button>

        </div>
        <div id="tally">
            <h1>The bottom line</h1>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
            <p>testPizzaIngredient <span>$10</span></p>
        </div>
</main>

Updated with no JQuery

Here is a basic example of hiding and displaying elements on button click. I utilized opacity for transitions. You can just use display: block and display: none if you just want simple display/hide.

NEW UPDATE: (Based on entire code posted)
First of all, there is a problem with your form. It errors out on clicking next (which is why your sections disappear) because it wants a POST request. I changed the sections to divs, got rid of the forms, and changed input submits to .

You had a potentially infinite loop with your while statement, if the if statement inside is never entered, your loop will never stop, changed to a for loop to ensure it will stop.

You were not grabbing the sections again on the next button click (which causes the infinite loop mentioned above because no sections have the visible id). Now, you grab the sections every time a button is clicked.

Changed your removing and adding 'id' to removing and adding a class. Again, highly advise against changing css based on removing and adding an Id....

You also were not binding the click event to every button, just the first one, the for loop through the buttons now binds a click event to all the buttons. If you run my example now, it goes through all of your cards.


问:
Javascript regex - getting function name from string
I am trying to get a function name from a string in javascript.

Let's say I have this string:

```<code>function multiply($number) {
    return ($number * 2);
}
</code>```

I am using the following regex in javascript:

```<code>/([a-zA-Z_{1}][a-zA-Z0-9_]+)\(/g
</code>```

However, what is selected is multiply(. This is wrong. What I want is the word multiply without the the (, though the regex should keep in mind that the function name must be attached an (.

I can't get this done. How can I make the proper regex for this? I know that this is not something I really should do and that it is quite error sensitive, but I still wanna try to make this work.

答:
Just replace last \) with (?=\()

```<code>`function multiply($number) {
    return ($number * 2);
}`.match(/([a-zA-Z_{1}][a-zA-Z0-9_]+)(?=\()/g) // ["multiply"]
</code>```

Body:
I am trying to get a function name from a string in javascript.

Let's say I have this string:

function multiply($number) {
    return ($number * 2);
}

I am using the following regex in javascript:

/([a-zA-Z_{1}][a-zA-Z0-9_]+)\(/g

However, what is selected is multiply(. This is wrong. What I want is the word multiply without the the (, though the regex should keep in mind that the function name must be attached an (.

I can't get this done. How can I make the proper regex for this? I know that this is not something I really should do and that it is quite error sensitive, but I still wanna try to make this work.

Body:
Just replace last \) with (?=\()

`function multiply($number) {
    return ($number * 2);
}`.match(/([a-zA-Z_{1}][a-zA-Z0-9_]+)(?=\()/g) // ["multiply"]


问:
Hyperledger Composer v0.16.0 network start error
I'm trying Hyperledger Composer v0.16.0. According to this procedure, I want to Deploy BNA to Fabric network on cloud. but following error occurs.
Kindly let me know how I can solve it.

command:

```<code>composer network start --card PeerAdmin@myfabric --networkAdmin admin --networkAdminEnrollSecret adminpw --archiveFile trade-network.bna --file networkadmin.card
</code>```

result:

```<code>tarting business network from archive: trade-network.bna
Business network definition:
    Identifier: trade-network@0.1.13
    Description: Commodities Trading Business Network

Processing these Network Admins:
    userName: admin

✖ Starting business network definition. This may take a minute...
Error: Error trying to instantiate composer runtime. Error: No valid responses from any peers.
Response from attempted peer comms was an error: Error: chaincode error (status: 500, message: chaincode instantiation policy violated(Failed to authenticate policy))
</code>```

答: That error can mean that the identity you are using to perform a network start doesn't have channel admin authority and thus is not authorised to perform a network start. I would suggest you check with whoever created your Hyperledger Fabric environment and channel to find out who the right identities are for administrative authority on the channel and build a card with the appropriate crypto material representing that identity in order to perform a network start.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying Hyperledger Composer v0.16.0. According to this procedure, I want to Deploy BNA to Fabric network on cloud. but following error occurs.
Kindly let me know how I can solve it.

command:

composer network start --card PeerAdmin@myfabric --networkAdmin admin --networkAdminEnrollSecret adminpw --archiveFile trade-network.bna --file networkadmin.card

result:

tarting business network from archive: trade-network.bna
Business network definition:
    Identifier: trade-network@0.1.13
    Description: Commodities Trading Business Network

Processing these Network Admins:
    userName: admin

✖ Starting business network definition. This may take a minute...
Error: Error trying to instantiate composer runtime. Error: No valid responses from any peers.
Response from attempted peer comms was an error: Error: chaincode error (status: 500, message: chaincode instantiation policy violated(Failed to authenticate policy))


问:
Changing video source javascript
My solution:
http://jsfiddle.net/g7mrs/22/

```<code>function loadVideo(event) {
  videojs("myPlayer").src({
    type: "video/youtube",
    src: "https://youtu.be/ZSn3Tvc7jQU"
  });
  event.preventDefault();
}
</code>```

I got a working solution, however I would like to have only 1 function instead of 4

Any ideas?

答:
Adding on to @hsz answer, You can also add the first part of the url to the function, and just send the ID.

This will also help if you need to later on change your video provider, since you only will have to change the base (assuming that the id stays the same).

So your JS function:

```<code>var base = 'https://youtu.be/';

function loadVideo(id) {
    videojs("myPlayer").src({ type: "video/youtube", src: base + id });
    event.preventDefault();
}
</code>```

end then in the HTML

```<code><a href="#" onClick="loadVideo('ZSn3Tvc7jQU')">video</a>
</code>```

Title: Changing video source javascript

Body:
My solution:
http://jsfiddle.net/g7mrs/22/

function loadVideo(event) {
  videojs("myPlayer").src({
    type: "video/youtube",
    src: "https://youtu.be/ZSn3Tvc7jQU"
  });
  event.preventDefault();
}

I got a working solution, however I would like to have only 1 function instead of 4

Any ideas?

Body:
Adding on to @hsz answer, You can also add the first part of the url to the function, and just send the ID.

This will also help if you need to later on change your video provider, since you only will have to change the base (assuming that the id stays the same).

So your JS function:

var base = 'https://youtu.be/';

function loadVideo(id) {
    videojs("myPlayer").src({ type: "video/youtube", src: base + id });
    event.preventDefault();
}

end then in the HTML

<a href="#" onClick="loadVideo('ZSn3Tvc7jQU')">video</a>


问:
Python: Set a string as the default of a nested dictionary?
I am trying to loop through a list of words and nest each letter of the word and then default the last letter to the original word.

```<code>    words = ['paste', 'pasta', 'pasha']
    self.T = {}
    for word in words:
        current_dict = self.T
        for letter in word:
            current_dict = current_dict.setdefault(letter, {})
</code>```

This outputs:

```<code>{'p': {'a': {'s': {'t': {'e': {}, 'a': {}}, 'h': {'a': {}}}}}}
</code>```

but the output I want is:

```<code>{'p': {'a': {'s': {'t': {'e': 'paste', 'a': 'pasta'}, 'h': {'a': 'pasha'}}}}}
</code>```

how do I avoid this error:

```<code>AttributeError: 'str' object has no attribute 'setdefault'
</code>```

答:
```<code>words = ['paste', 'pasta', 'pasha']
self.T = {}
for word in words:
    current_dict = self.T
    for index, letter in enumerate(word):
        if index < len(word) - 1:
            current_dict = current_dict.setdefault(letter, {})
    current_dict[letter] = word
</code>```

Body:
I am trying to loop through a list of words and nest each letter of the word and then default the last letter to the original word.

    words = ['paste', 'pasta', 'pasha']
    self.T = {}
    for word in words:
        current_dict = self.T
        for letter in word:
            current_dict = current_dict.setdefault(letter, {})

This outputs:

{'p': {'a': {'s': {'t': {'e': {}, 'a': {}}, 'h': {'a': {}}}}}}

but the output I want is:

{'p': {'a': {'s': {'t': {'e': 'paste', 'a': 'pasta'}, 'h': {'a': 'pasha'}}}}}

how do I avoid this error:

AttributeError: 'str' object has no attribute 'setdefault'


问:
C++ reading char from stack to string results in "Unrecognized enum"
I am new to C++ and there must be something that I am missing. My code is this:

```<code>std::stack<char> operators;
std::stringstream stream;
stream.str("5.2 + 3");

while(stream.peek() != -1){
    char token = static_cast<char>(stream.get());
    //some code checking if the token is valid
    operators.push(token);
    auto tmp = operators.top(); //there I can still see the char (for example '+')
    std::string tmpStr = "" + tmp; //But when put into string, there is "Unrecognized enum"
}
</code>```

The variable tmpStr is filled with "Unrecognized enum" instead of the contents of tmp.

I couldn't find any solution but I believe it must be something very simple.
Thanks for any help.

Edit:
So if I use tmpStr.push_back(tmp) it works. But then I use it like this:

```<code>std::queue<std::string> outQueue;
outQueue.push(" " + operators.top());
//some code
std::string result = "";
while(!outQueue.empty()){
    result.append(outQueue.front() + " ");
    outQueue.pop();
}
//result then has for example something like "5.2 own enum 3 own enum"
</code>```

There on the positions that are appended from the operators stack, there is "own enum" and not what was actually saved there.

答:
Stop doing "" + something!

This is C++ and it will not magically make a string object out of a string literal.

If the above code actually compiles, it means that somethign is of some integral type and you are taking a stack pointer (const char*) of the location that "" points to and adding a pointer offset onto that. You are not reading some random data until the next NULL.

If you want to convert something to a string you need to convert it. The standard way to this is though a output stream operator.

```<code>enum OP
{
    OP_ADD,
    OP_SUB,
    OP_DIV,
    OP_MUL
};

std::ostream& operator << (std::ostream& os, OP op)
{
    switch (op)
    {
        case OP_ADD:
            os << "ADD";
            break;
        case OP_SUB:
            os << "SUB";
            break;
        case OP_DIV:
            os << "DIV";
            break;
        case OP_MUL:
            os << "MUL";
            break;
        default:
            throw std::logic_error("Invalid OP");
    }
}
</code>```

This can then be used like so:

```<code>OP op = OP_ADD;
std::stringstream buff;
buff << op;
std::string sop = buff.str();
</code>```

But since the above code it quite stupid, I have a shorthand for the object to string conversion:

```<code>template <typename T>
std::string to_string(T value)
{
    std::stringstream buff;
    buff << value;
    return buff.str();
}
</code>```

This can then be used like so:

```<code>OP op = OP_ADD;
std::string sop = to_string(op);
</code>```

Body:
I am new to C++ and there must be something that I am missing. My code is this:

std::stack<char> operators;
std::stringstream stream;
stream.str("5.2 + 3");

while(stream.peek() != -1){
    char token = static_cast<char>(stream.get());
    //some code checking if the token is valid
    operators.push(token);
    auto tmp = operators.top(); //there I can still see the char (for example '+')
    std::string tmpStr = "" + tmp; //But when put into string, there is "Unrecognized enum"
}

The variable tmpStr is filled with "Unrecognized enum" instead of the contents of tmp.

I couldn't find any solution but I believe it must be something very simple.
Thanks for any help.

Edit:
So if I use tmpStr.push_back(tmp) it works. But then I use it like this:

std::queue<std::string> outQueue;
outQueue.push(" " + operators.top());
//some code
std::string result = "";
while(!outQueue.empty()){
    result.append(outQueue.front() + " ");
    outQueue.pop();
}
//result then has for example something like "5.2 own enum 3 own enum"

There on the positions that are appended from the operators stack, there is "own enum" and not what was actually saved there.

Body:
Stop doing "" + something!

This is C++ and it will not magically make a string object out of a string literal.

If the above code actually compiles, it means that somethign is of some integral type and you are taking a stack pointer (const char*) of the location that "" points to and adding a pointer offset onto that. You are not reading some random data until the next NULL.

If you want to convert something to a string you need to convert it. The standard way to this is though a output stream operator.

enum OP
{
    OP_ADD,
    OP_SUB,
    OP_DIV,
    OP_MUL
};

std::ostream& operator << (std::ostream& os, OP op)
{
    switch (op)
    {
        case OP_ADD:
            os << "ADD";
            break;
        case OP_SUB:
            os << "SUB";
            break;
        case OP_DIV:
            os << "DIV";
            break;
        case OP_MUL:
            os << "MUL";
            break;
        default:
            throw std::logic_error("Invalid OP");
    }
}

This can then be used like so:

OP op = OP_ADD;
std::stringstream buff;
buff << op;
std::string sop = buff.str();

But since the above code it quite stupid, I have a shorthand for the object to string conversion:

template <typename T>
std::string to_string(T value)
{
    std::stringstream buff;
    buff << value;
    return buff.str();
}

This can then be used like so:

OP op = OP_ADD;
std::string sop = to_string(op);


问:
Bash script help, include sub-directories for processing files
I am definitely new to scripting.  I have a script that processes some files and I can't figure out how to run this against all files in a directory that has many sub-directories and thousands of files.  Basically I want to take this script and run it against a directory titled 2011 and have it process every file in every sub-folder.  </p>

```<code>#!/bin/bash
FILES=./userfiles/*
for f in $FILES
do
    echo ""
    echo ""
    echo "Processing File $f ...."
    echo ""
    echo ""
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar $f.html
    echo ""
    echo ""
    echo "File $f.html Generated"
done
</code>```

答:
Not sure what your script does, but in order to run it for every file in a tree starting at the current folder you can use:</p>

```<code>find . -exec yourscript.sh {} \;
</code>```

Body:
I am definitely new to scripting.  I have a script that processes some files and I can't figure out how to run this against all files in a directory that has many sub-directories and thousands of files.  Basically I want to take this script and run it against a directory titled 2011 and have it process every file in every sub-folder.

#!/bin/bash
FILES=./userfiles/*
for f in $FILES
do
    echo ""
    echo ""
    echo "Processing File $f ...."
    echo ""
    echo ""
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar $f.html
    echo ""
    echo ""
    echo "File $f.html Generated"
done

Body:
Not sure what your script does, but in order to run it for every file in a tree starting at the current folder you can use:

find . -exec yourscript.sh {} \;


问:
Remove any string in HTML files python
I am currently using beautiful soup to auto tag some links in HTML, the sample below shows what I get in return, everything is pretty much fine apart from the fact that "&&" is converted into

```<code>&&
</code>```

And for whatever reason, the below string of DIVs gets added

```<code></div></div></div></div></div></div></div></div></div>
</code>```

```<code>return typeof jQuery === 'function' &&
<div>
'<a href="" title="example">example</a>
</div>

</div></div></div></div></div></div></div></div>
</code>```

I would like to find a way to remove this, after I have applied the script to tag the links.
I have tried

```<code>soup.replace("</div></div></div>", '')
AttributeError: 'list' object has no attribute 'replace'

re.sub('&&',"",soup)
TypeError: expected string or bytes-like object
</code>```

I would like something like the below instead

```<code>return typeof jQuery === 'function' &&
<div>
'<a href="" title="example">example</a>
</div>
</code>```

答:
I haven't got much to go on without the full code but my guess is that you are missing script tags.

If you add the JavaScript to a script element it is not HTML encoded you get what you expect i.e. the &&.

```<code>from bs4 import BeautifulSoup

body = """
<html><body><div><a href="" title="example"></a></div></body></html>
"""
soup = BeautifulSoup(body, "lxml")
original_tag = soup.find("div")
new_tag = soup.new_tag("script")
new_tag.string = "return typeof jQuery === 'function' && <div>'"
original_tag.insert(0, new_tag)
print (soup)
</code>```

Outputs:

```<code><html><body><div><script>return typeof jQuery === 'function' && <div>'</script><a href="" title="example"></a></div></body></html>
</code>```

Where as if you add the JavaScript to the wrong element e.g. a div it doesn't work as expected you get

```<code>&&.
</code>```

This doesn't work as expected.

```<code>from bs4 import BeautifulSoup

body = """
<html><body><div><a href="" title="example"></a></div></body></html>
"""
soup = BeautifulSoup(body, "lxml")
original_tag = soup.find("div")
new_tag = soup.new_tag("div")
new_tag.string = "return typeof jQuery === 'function' && <div>'"
original_tag.insert(0, new_tag)
print (soup)
</code>```

Outputs:

```<code><html><body><div><div>return typeof jQuery === 'function' && <div>'</div><a href="" title="example"></a></div></body></html>
</code>```

The JavaScript in you example needs to be in a script element or it will not work and my guess is that it is not because you are getting the &s HTML encoded. If your JavaScript is outside script tags it is just text not code and won't work.

The extra closing div tags may well come from the same error.

Title: Remove any string in HTML files python

Body:
I am currently using beautiful soup to auto tag some links in HTML, the sample below shows what I get in return, everything is pretty much fine apart from the fact that "&&" is converted into

&&

And for whatever reason, the below string of DIVs gets added

return typeof jQuery === 'function' &&

'example

I would like to find a way to remove this, after I have applied the script to tag the links.
I have tried

soup.replace("

", '')
AttributeError: 'list' object has no attribute 'replace'

re.sub('&&',"",soup)
TypeError: expected string or bytes-like object

I would like something like the below instead

return typeof jQuery === 'function' &&

'example

Body:
I haven't got much to go on without the full code but my guess is that you are missing script tags.

If you add the JavaScript to a script element it is not HTML encoded you get what you expect i.e. the &&.

from bs4 import BeautifulSoup

body = """
<html><body><div><a href="" title="example"></a></div></body></html>
"""
soup = BeautifulSoup(body, "lxml")
original_tag = soup.find("div")
new_tag = soup.new_tag("script")
new_tag.string = "return typeof jQuery === 'function' && <div>'"
original_tag.insert(0, new_tag)
print (soup)

Outputs:

<html><body><div><script>return typeof jQuery === 'function' && <div>'</script><a href="" title="example"></a></div></body></html>

Where as if you add the JavaScript to the wrong element e.g. a div it doesn't work as expected you get

&amp;&amp;.

This doesn't work as expected.

from bs4 import BeautifulSoup

body = """
<html><body><div><a href="" title="example"></a></div></body></html>
"""
soup = BeautifulSoup(body, "lxml")
original_tag = soup.find("div")
new_tag = soup.new_tag("div")
new_tag.string = "return typeof jQuery === 'function' && <div>'"
original_tag.insert(0, new_tag)
print (soup)

Outputs:

<html><body><div><div>return typeof jQuery === 'function' &amp;&amp; &lt;div&gt;'</div><a href="" title="example"></a></div></body></html>

The JavaScript in you example needs to be in a script element or it will not work and my guess is that it is not because you are getting the &s HTML encoded. If your JavaScript is outside script tags it is just text not code and won't work.

The extra closing div tags may well come from the same error.


问:
comparing list of maps in java and printing result in table

I have two list of maps.

```<code> List1=[{1=one,2=two},{1=three,2=two}]
 List2=[{1=one,2=twoss},{1=three,2=twoss}]
</code>```

I am trying to compare maps in lists and get it in table form html. Though I am unable to get desired html format. Keys in all maps will be same but values can be different and trying to get keys in header and values beneath it comparing from screen and database, if they match the it will be wrapped in green else red. So screen has table with two rows & header. Database also has two rows and header. Storing this values in list of maps and comparing them.

```<code>public String compare(List<Map<String, Object>> list1, List<Map<String, Object>> list2) throws Exception {
    StringBuilder tbe = new StringBuilder();
    String col = "";
    String screen = "";
    String db = "";
    if (list1.size() = list2.size()) {
        for (int i = 0; i < list1.size(); i++) {
            Map<String, Object> a = list1.get(i);
            Map<String, Object> b = list2.get(i);
            for (Map.Entry<String, Object> ent : a.entrySet()) {
                col = col + "<th>" + entry.getKey() + "</th>";
                String k = ent.getKey();
                Object o1 = entry.getValue();
                if (o1.equals(b.get(key))) {
                    screen = screen + "<td bgcolor=green>" + o1 + "</td>";
                    db = db + "<td bgcolor=green>" + b.get(entry.getKey()) + "</td>";
                } else {
                    screen = screen + "<td bgcolor=red>" + o1 + "</td>";
                    db = db + "<td bgcolor=red>" + b.get(entry.getKey()) + "</td>";
                }

            }
            tbe.append("<tr><th>col</th>" + col + "</tr>");
            tbe.append("<tr><th>screen</th>" + screen + "</tr>");
            tbe.append("<tr><th>db</th>" + db + "</tr>");
            tbe.append("</table></html>");
            String tbel = tbe.toString();
            system.out.println(tbel);
            return tbel;
        }
    }
}
</code>```

Desired o/p i am looking for --column headers get printed just once, whereas now I am getting repeated html tables.

答:
```<code>    public static String compare(List<Map<String, Object>> list1, List<Map<String, Object>> list2) {
        StringBuilder tbe = new StringBuilder();
        String col = "";
        String screen = "";
        String db = "";
        if (list1.size() == list2.size()) {
            for (int i = 0; i < list1.size(); i++) {
                Map<String, Object> a = list1.get(i);
                Map<String, Object> b = list2.get(i);
                for (Map.Entry<String, Object> ent : a.entrySet()) {
                    col = col + "<th>" + ent.getKey() + "</th>";
                    String key = ent.getKey();
                    Object o1 = ent.getValue();
                    if (o1.equals(b.get(key))) {
                        screen = screen + "<td bgcolor=green>" + o1 + "</td>";
                        db = db + "<td bgcolor=green>" + b.get(ent.getKey()) + "</td>";
                    } else {
                        screen = screen + "<td bgcolor=red>" + o1 + "</td>";
                        db = db + "<td bgcolor=red>" + b.get(ent.getKey()) + "</td>";
                    }

                }
                tbe.append("<tr><th>col</th>" + col + "</tr>");
                tbe.append("<tr><th>screen</th>" + screen + "</tr>");
                tbe.append("<tr><th>db</th>" + db + "</tr>");
                tbe.append("</table></html>");
            }
        }
        return tbe.toString();
    }
</code>```

o/p:

```<code><tr>
    <th>col</th>
    <th>1</th>
    <th>2</th>
</tr>
<tr>
    <th>screen</th>
    <td bgcolor=red>One</td>
    <td bgcolor=red>Two</td>
</tr>
<tr>
    <th>db</th>
    <td bgcolor=red>M2One</td>
    <td bgcolor=red>M2Two</td>
</tr>
</table>

</html>
</code>```

Fixing compile time errors in your code is giving me this output. Is this what you are expecting?

Body:
I have two list of maps.

 List1=[{1=one,2=two},{1=three,2=two}]
 List2=[{1=one,2=twoss},{1=three,2=twoss}]

I am trying to compare maps in lists and get it in table form html. Though I am unable to get desired html format. Keys in all maps will be same but values can be different and trying to get keys in header and values beneath it comparing from screen and database, if they match the it will be wrapped in green else red. So screen has table with two rows & header. Database also has two rows and header. Storing this values in list of maps and comparing them.

public String compare(List<Map<String, Object>> list1, List<Map<String, Object>> list2) throws Exception {
    StringBuilder tbe = new StringBuilder();
    String col = "";
    String screen = "";
    String db = "";
    if (list1.size() = list2.size()) {
        for (int i = 0; i < list1.size(); i++) {
            Map<String, Object> a = list1.get(i);
            Map<String, Object> b = list2.get(i);
            for (Map.Entry<String, Object> ent : a.entrySet()) {
                col = col + "" + entry.getKey() + "	";
                String k = ent.getKey();
                Object o1 = entry.getValue();
                if (o1.equals(b.get(key))) {
                    screen = screen + "" + o1 + "	";
                    db = db + "" + b.get(entry.getKey()) + "	";
                } else {
                    screen = screen + "" + o1 + "	";
                    db = db + "" + b.get(entry.getKey()) + "	";
                }

            }
            tbe.append("
col	" + col + "
");
            tbe.append("
screen	" + screen + "
");
            tbe.append("
db	" + db + "
");
            tbe.append("
");
            String tbel = tbe.toString();
            system.out.println(tbel);
            return tbel;
        }
    }
}

Desired o/p i am looking for --column headers get printed just once, whereas now I am getting repeated html tables.

Body:
    public static String compare(List<Map<String, Object>> list1, List<Map<String, Object>> list2) {
        StringBuilder tbe = new StringBuilder();
        String col = "";
        String screen = "";
        String db = "";
        if (list1.size() == list2.size()) {
            for (int i = 0; i < list1.size(); i++) {
                Map<String, Object> a = list1.get(i);
                Map<String, Object> b = list2.get(i);
                for (Map.Entry<String, Object> ent : a.entrySet()) {
                    col = col + "<th>" + ent.getKey() + "</th>";
                    String key = ent.getKey();
                    Object o1 = ent.getValue();
                    if (o1.equals(b.get(key))) {
                        screen = screen + "<td bgcolor=green>" + o1 + "</td>";
                        db = db + "<td bgcolor=green>" + b.get(ent.getKey()) + "</td>";
                    } else {
                        screen = screen + "<td bgcolor=red>" + o1 + "</td>";
                        db = db + "<td bgcolor=red>" + b.get(ent.getKey()) + "</td>";
                    }

                }
                tbe.append("<tr><th>col</th>" + col + "</tr>");
                tbe.append("<tr><th>screen</th>" + screen + "</tr>");
                tbe.append("<tr><th>db</th>" + db + "</tr>");
                tbe.append("</table></html>");
            }
        }
        return tbe.toString();
    }

o/p:

<tr>
    <th>col</th>
    <th>1</th>
    <th>2</th>
</tr>
<tr>
    <th>screen</th>
    <td bgcolor=red>One</td>
    <td bgcolor=red>Two</td>
</tr>
<tr>
    <th>db</th>
    <td bgcolor=red>M2One</td>
    <td bgcolor=red>M2Two</td>
</tr>
</table>

</html>

Fixing compile time errors in your code is giving me this output. Is this what you are expecting?


问:
Database - phpmyadmin
I would like to know does database is erased on daily basis which is created PHPMyadmin

Yesterday I have created a database by clicking "new" option under the Server "phpmyadmin demo-MYSQL(root)".Today that database doesn't exist.Any suggestions please and let me know whether I have missed nay steps before creating a database

答: You were using a demo.phpmyadmin.net server which is not intended for production and which removes databases created by testers on a daily basis.</p>

Title: Database - phpmyadmin


问:
Dropdown based on table with additional custom value, Rails
So, I can use the following to make a select box based on a database object

```<code> <%= f.collection_select :role, Role.where(company: current_company), :name, :name %>
</code>```

I want to be able to add custom fields on top of it, such as an "all" or "none" selection, how do I do it, do I have to add temporary rows to the active record object?

答:
You could include a blank value with :include_blank as an option parameter.

Any more control and you'll need to manually build the options for the select with select and options_for_select or options_from_collection_for_select. That may sound a little more difficult, but it actually isn't that bad.

```<code><%= f.select :role, options_for_select([["none", "None"], ["all", "All"]]) +  options_from_collection_for_select(Role.where(company: current_company), :name, :name) %>
</code>```

Here we're just concatenating two strings of option markup.

Body:
So, I can use the following to make a select box based on a database object

 <%= f.collection_select :role, Role.where(company: current_company), :name, :name %>

I want to be able to add custom fields on top of it, such as an "all" or "none" selection, how do I do it, do I have to add temporary rows to the active record object?

Body:
You could include a blank value with :include_blank as an option parameter.

Any more control and you'll need to manually build the options for the select with select and options_for_select or options_from_collection_for_select. That may sound a little more difficult, but it actually isn't that bad.

<%= f.select :role, options_for_select([["none", "None"], ["all", "All"]]) +  options_from_collection_for_select(Role.where(company: current_company), :name, :name) %>

Here we're just concatenating two strings of option markup.


问:
Create Array Using JSON Results
Im trying to query an API
https://min-api.cryptocompare.com/data/pricemultifull?fsyms=XRP,BTC,ETH,BCH&tsyms=USD

The results are in teh following format
DISPLAY:XRP:USD:CHANGEPCT24HR
The above is the item i want to create an array of although XRP will re replaced with each fsyms value

This is my code so far

```<code>  $json_string =    file_get_contents("https://min-api.cryptocompare.com/data/pricemultifull?fsyms=XRP&tsyms=USD");
  $parsed_json = json_decode($json_string, true);
  $btcp = $parsed_json['DISPLAY']['XRP']['USD'];
  $btcchange = $parsed_json['DISPLAY']['XRP']['USD']['CHANGEPCT24HOUR'];
</code>```

I know I shouldnt post "how do i" questions
but there are so many possible methods jquery(map) toArray etc i just dont know where to start

答:
Here's the solution to create an array (mapped based on jQuery parameters sent to the AJAX call).

JS FIDDLE

Relevant code:

```<code>var fsyms = 'XRP,BTC,BCH', tsyms = 'USD', change_attr = 'CHANGEPCT24HOUR', values = [];

$.ajax({
  url: 'https://min-api.cryptocompare.com/data/pricemultifull',
  data: {
    fsyms: fsyms, tsyms: tsyms
  }
}).done(function (resp) {
   console.log(resp);
   var display_val = resp['DISPLAY'];
   fsyms.split(',').map(function(d) {
   values.push({name: d, value: display_val[d][tsyms][change_attr]});
});

 console.log(values);
});
</code>```

Title: Create Array Using JSON Results

Body:
Im trying to query an API
https://min-api.cryptocompare.com/data/pricemultifull?fsyms=XRP,BTC,ETH,BCH&tsyms=USD

The results are in teh following format
DISPLAY:XRP:USD:CHANGEPCT24HR
The above is the item i want to create an array of although XRP will re replaced with each fsyms value

This is my code so far

  $json_string =    file_get_contents("https://min-api.cryptocompare.com/data/pricemultifull?fsyms=XRP&tsyms=USD");
  $parsed_json = json_decode($json_string, true);
  $btcp = $parsed_json['DISPLAY']['XRP']['USD'];
  $btcchange = $parsed_json['DISPLAY']['XRP']['USD']['CHANGEPCT24HOUR'];

I know I shouldnt post "how do i" questions
but there are so many possible methods jquery(map) toArray etc i just dont know where to start

Body:
Here's the solution to create an array (mapped based on jQuery parameters sent to the AJAX call).

JS FIDDLE

Relevant code:

var fsyms = 'XRP,BTC,BCH', tsyms = 'USD', change_attr = 'CHANGEPCT24HOUR', values = [];

$.ajax({
  url: 'https://min-api.cryptocompare.com/data/pricemultifull',
  data: {
    fsyms: fsyms, tsyms: tsyms
  }
}).done(function (resp) {
   console.log(resp);
   var display_val = resp['DISPLAY'];
   fsyms.split(',').map(function(d) {
   values.push({name: d, value: display_val[d][tsyms][change_attr]});
});

 console.log(values);
});


问:
(SemanticUI + React) Changing HTML elements based on screen size best approach?
For example lets say I want to remove images when display size falls below 600px width. What would be the cleanest, fastest and most maintainable method to do that?

              Kristy

              Joined in 2013

              Kristy is an art director living in New York.

              22 Friends

```

<p>jQuery method</p>

<p><strong>EDIT</strong>: Definitely not using jQuery (it works, but read below):</p>

<blockquote>
  <p>jQuery Free</p>

  <p>jQuery is a DOM manipulation library. It reads from and writes to the
  DOM. React uses a virtual DOM (a JavaScript representation of the real
  DOM). React only writes patch updates to the DOM, but never reads from
  it.</p>

  <p>It is not feasible to keep real DOM manipulations in sync with React's
  virtual DOM. Because of this, all jQuery functionality has been
  re-implemented in React.</p>
</blockquote>

```
```

<p>SemanticUI method (Doc)</p>

```

  Contents

```

<p>Using React only?</p>

```  render() {
    let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />;
    return(

{content}

        <childComponent myWidth= {this.state.width}></childComponent >
        <childComponent2 myWidth= {this.state.width}></childComponent2 >

  )
```

答:
Use a media query and attach to your class. e.g.

HTML:

```<code> <div class="image hideOnSmallScreen">
              <img src="http://placehold.it/256x256">
          </div>
</code>```

CSS:

```<code>.image {
   display:block;
}

/* Small screens */
@media all and (max-width: 700px) {
   .image.hideOnSmallScreen {
      display:none;
   }
}
</code>```

Body:
For example lets say I want to remove images when display size falls below 600px width. What would be the cleanest, fastest and most maintainable method to do that?

              Kristy

              Joined in 2013

              Kristy is an art director living in New York.

              22 Friends

jQuery method

EDIT: Definitely not using jQuery (it works, but read below):

jQuery Free

jQuery is a DOM manipulation library. It reads from and writes to the
  DOM. React uses a virtual DOM (a JavaScript representation of the real
  DOM). React only writes patch updates to the DOM, but never reads from
  it.

It is not feasible to keep real DOM manipulations in sync with React's
  virtual DOM. Because of this, all jQuery functionality has been
  re-implemented in React.

SemanticUI method (Doc)

  Contents

Using React only?

  render() {
    let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />;
    return(

{content}

        <childComponent myWidth= {this.state.width}></childComponent >
        <childComponent2 myWidth= {this.state.width}></childComponent2 >

  )

Body:
Use a media query and attach to your class. e.g.

HTML:

 <div class="image hideOnSmallScreen">
              <img src="http://placehold.it/256x256">
          </div>

CSS:

.image {
   display:block;
}

/* Small screens */
@media all and (max-width: 700px) {
   .image.hideOnSmallScreen {
      display:none;
   }
}


问:
How to find the first node of the tree in a dict?
i have a big problem , in a function for start to work i need to find the first node in a tree , here an example :

```<code>              "hi"
            /     \
           /       \
          "ok"     "no"
          /
         /
       "lol"
</code>```

the problem is that i dont know how to take it from a dict , because the input is like this :

```<code>{ "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
</code>```

so in this case "hi" is the first because nobody has "hi" in dict.values() the problem is how to say that and most important the dict has 50'000 nodes so if i check one by one it goes in overtime .

i wrote this :

```<code>    d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
    x = d.values()
    x = str(x)
    for y in d.keys():
        if not y in x :
            first_node = y
            break
</code>```

but the problem is that can be a word like "hello" and a "key" like "hell" so "hell" is in "hellow" but is not "hellow" :(

答:
You could pick a random node and follow it to the top.
I just wrote something up, im gonna timeit and report results:

```<code>d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : []}

node = list(d.keys())[0]
found = False
while not found:
    found = True
    for key, value in d.items():
        if node in value:
            node = key
            found = False

print(node)
</code>```

Turns out that my solution performed best in the test environment:

```<code>**10 nodes**
0.0000020000017 s - my solution
0.0000043555594 s - using set.diffrence by Patrick Haugh
0.0001111112098 s - list comprehension by Ajax1234

**1000 nodes**
0.0007560006720 s - my solution
0.0015977791980 s - using set.diffrence by Patrick Haugh
0.3337478522203 s - list comprehension by Ajax1234

**10000 nodes**
0.0077213401967 s - my solution
0.0138804567826 s - using set.diffrence by Patrick Haugh
35.264710457520 s - list comprehension by Ajax1234
</code>```

Body:
i have a big problem , in a function for start to work i need to find the first node in a tree , here an example :

              "hi"
            /     \
           /       \
          "ok"     "no"
          /
         /
       "lol"

the problem is that i dont know how to take it from a dict , because the input is like this :

{ "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }

so in this case "hi" is the first because nobody has "hi" in dict.values() the problem is how to say that and most important the dict has 50'000 nodes so if i check one by one it goes in overtime .

i wrote this :

    d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
    x = d.values()
    x = str(x)
    for y in d.keys():
        if not y in x :
            first_node = y
            break

but the problem is that can be a word like "hello" and a "key" like "hell" so "hell" is in "hellow" but is not "hellow" :(

Body:
You could pick a random node and follow it to the top.
I just wrote something up, im gonna timeit and report results:

d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : []}

node = list(d.keys())[0]
found = False
while not found:
    found = True
    for key, value in d.items():
        if node in value:
            node = key
            found = False

print(node)

Turns out that my solution performed best in the test environment:

**10 nodes**
0.0000020000017 s - my solution
0.0000043555594 s - using set.diffrence by Patrick Haugh
0.0001111112098 s - list comprehension by Ajax1234

**1000 nodes**
0.0007560006720 s - my solution
0.0015977791980 s - using set.diffrence by Patrick Haugh
0.3337478522203 s - list comprehension by Ajax1234

**10000 nodes**
0.0077213401967 s - my solution
0.0138804567826 s - using set.diffrence by Patrick Haugh
35.264710457520 s - list comprehension by Ajax1234


问:
Finding whats in one table that is not in another table
I have following two tables:

```<code>CREATE TABLE TEMP1(ID INT)
CREATE TABLE TEMP2(ID INT)

INSERT INTO TEMP1 SELECT 1
INSERT INTO TEMP1 SELECT 2
INSERT INTO TEMP1 SELECT 3
INSERT INTO TEMP1 SELECT 4

INSERT INTO TEMP2 SELECT 1
INSERT INTO TEMP2 SELECT 2
INSERT INTO TEMP2 SELECT 3
INSERT INTO TEMP2 SELECT 4
INSERT INTO TEMP2 SELECT 5

SELECT * FROM TEMP1
SELECT * FROM TEMP2
</code>```

I am trying to find the records which are in TEMP2, but not in TEMP1 i.e. 5.
If I run the following query, I get the proper result:

```<code>  SELECT DISTINCT [ID2] FROM (
   SELECT DISTINCT
   C1.[ID] AS [ID1]
   ,C2.[ID] AS [ID2]
   FROM TEMP1 C1
   FULL JOIN TEMP2 C2 ON C1.[ID]=C2.[ID]
   )A
   WHERE [ID1] IS NULL
   ORDER BY 1
</code>```

But when I run following query, I don't return anything:

```<code>   SELECT DISTINCT T2.[ID] FROM TEMP2 T2
   WHERE T2.[ID] NOT IN (SELECT DISTINCT T1.[ID] FROM TEMP1 T1 )
   ORDER BY 1
</code>```

Any idea whats wrong?

答:
Don't use not in with a subquery.  It doesn't have the right semantics.  I returns no rows if even one value in the subquery is NULL.  Use not exists instead:

```<code>SELECT T2.[ID]
FROM TEMP2 T2
WHERE NOT EXISTS (SELECT 1 FROM TEMP1 T1 WHERE T2.[ID] = T1.[ID])
ORDER BY 1;
</code>```

I assumes the SELECT DISTINCT is not needed in the outer query.

Body:
I have following two tables:

CREATE TABLE TEMP1(ID INT)
CREATE TABLE TEMP2(ID INT)

INSERT INTO TEMP1 SELECT 1
INSERT INTO TEMP1 SELECT 2
INSERT INTO TEMP1 SELECT 3
INSERT INTO TEMP1 SELECT 4

INSERT INTO TEMP2 SELECT 1
INSERT INTO TEMP2 SELECT 2
INSERT INTO TEMP2 SELECT 3
INSERT INTO TEMP2 SELECT 4
INSERT INTO TEMP2 SELECT 5

SELECT * FROM TEMP1
SELECT * FROM TEMP2

I am trying to find the records which are in TEMP2, but not in TEMP1 i.e. 5.
If I run the following query, I get the proper result:

  SELECT DISTINCT [ID2] FROM (
   SELECT DISTINCT
   C1.[ID] AS [ID1]
   ,C2.[ID] AS [ID2]
   FROM TEMP1 C1
   FULL JOIN TEMP2 C2 ON C1.[ID]=C2.[ID]
   )A
   WHERE [ID1] IS NULL
   ORDER BY 1

But when I run following query, I don't return anything:

   SELECT DISTINCT T2.[ID] FROM TEMP2 T2
   WHERE T2.[ID] NOT IN (SELECT DISTINCT T1.[ID] FROM TEMP1 T1 )
   ORDER BY 1

Any idea whats wrong?

Body:
Don't use not in with a subquery.  It doesn't have the right semantics.  I returns no rows if even one value in the subquery is NULL.  Use not exists instead:

SELECT T2.[ID]
FROM TEMP2 T2
WHERE NOT EXISTS (SELECT 1 FROM TEMP1 T1 WHERE T2.[ID] = T1.[ID])
ORDER BY 1;

I assumes the SELECT DISTINCT is not needed in the outer query.