问:
How to get the data from MVC view to controller
I'm working on a simple project. Following is the code. The thing is I'm unable to get all the information from the view to the controller. So I already have book ID, Name and price (which is coming from separate Productcontroller) in the Homecontroller and I'm able to view it as well and I want to post the quantity of books when I make a post request. So, when I try to make a post request and debug it, I can only see the quantity and I see null for book ID, Name and price.

I’m not sure what is going wrong. Any help would be really appreciated.
Thank You!

1.Product.cs

```<code>public class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public decimal ProductPrice { get; set; }
        public int Quantity { get; set; }
    }
</code>```

2.Cart.cshtml

```<code>@model DAL.Models.Product
@{
    ViewBag.Title = "Purchase";
}

@ViewBag.bookName
<h2>Purchase</h2>

<div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-6">
        @using (Html.BeginForm("Cart", "Home", FormMethod.Post))
        {
            <div class="panel panel-primary">

                <div class="panel-heading">Purchase Book</div>
                <div class="panel-body">
                    <div>
                        <dl class="dl-horizontal">
                            <dt>
                                @Html.DisplayNameFor(model => model.ProductName)
                            </dt>

                            <dd>
                                @Html.DisplayFor(model => model.ProductName)
                            </dd>

                            <dt>
                                @Html.DisplayNameFor(model => model.ProductPrice)
                            </dt>

                            <dd>
                                @Html.DisplayFor(model => model.ProductPrice)
                            </dd>

                        </dl>
                    </div>
                    @Html.LabelFor(model => model.Quantity, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })
                    </div><br />

                    <div class="col-md-10">
                        <input type="submit" value="Submit" class="btn btn-default"/>
                    </div>
                </div>
            </div>
        }
    </div>
    <div class="col-md-3"></div>
</div>
</code>```

Following is the screen shot:

答:
Only editable values will be included in the POST (where you are using @Html.EditorFor etc).  To include other values in the POST, simply use the @Html.HiddenFor() helper.

For example:

```<code>@Html.HiddenFor(model => model.ProductID)
@Html.HiddenFor(model => model.ProductName)
@Html.HiddenFor(model => model.ProductPrice)
</code>```

These will then be passed back and available in the controller.

Body:
I'm working on a simple project. Following is the code. The thing is I'm unable to get all the information from the view to the controller. So I already have book ID, Name and price (which is coming from separate Productcontroller) in the Homecontroller and I'm able to view it as well and I want to post the quantity of books when I make a post request. So, when I try to make a post request and debug it, I can only see the quantity and I see null for book ID, Name and price.

I’m not sure what is going wrong. Any help would be really appreciated.
Thank You!

1.Product.cs

public class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public decimal ProductPrice { get; set; }
        public int Quantity { get; set; }
    }

2.Cart.cshtml

@model DAL.Models.Product
@{
    ViewBag.Title = "Purchase";
}

@ViewBag.bookName

Purchase

        @using (Html.BeginForm("Cart", "Home", FormMethod.Post))
        {

Purchase Book

                                @Html.DisplayNameFor(model => model.ProductName)

                                @Html.DisplayFor(model => model.ProductName)

                                @Html.DisplayNameFor(model => model.ProductPrice)

                                @Html.DisplayFor(model => model.ProductPrice)

                    @Html.LabelFor(model => model.Quantity, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })

                        <input type="submit" value="Submit" class="btn btn-default"/>

        }

Following is the screen shot:

Body:
Only editable values will be included in the POST (where you are using @Html.EditorFor etc).  To include other values in the POST, simply use the @Html.HiddenFor() helper.

For example:

@Html.HiddenFor(model => model.ProductID)
@Html.HiddenFor(model => model.ProductName)
@Html.HiddenFor(model => model.ProductPrice)

These will then be passed back and available in the controller.


来源: stackexchange

问:
Upload image in symfony form
I am having a weird problem. I added an upload image field to a form. Every thing work fine when i use this code in the twig file

```<code>{{ form_start(form) }}
<button>d</button>
{{ form_end(form) }}
</code>```

But when ever i want to use form_widget to costumize the look of the form this error appear when ever i try to sumit the form

FatalErrorException
  Error: Call to a member function getFileName() on string.

This is the View that cause the problem

```<code>{% extends 'BridgeTravelBundle:Admin:layout.html.twig' %}

{% block body %}
    <div class="col-md-12 col-sm-12 col-xs-12">
        <div class="x_panel">
            <form method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left">
                <div class="form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12">Nom</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                        {{ form_widget(form.name, { 'attr': {'class': 'form-control', 'placeholder': 'Prenom' } }) }}
                        {{ form_errors(form.name) }}
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12">Icon</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                        {{ form_widget(form.icon, { 'attr': {'class': 'form-control', 'placeholder': 'Prenom' } }) }}
                        {{ form_errors(form.icon) }}
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12">Icon</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                        {{ form_widget(form.file) }}
                        {{ form_errors(form.file) }}
                    </div>
                </div>

                <div class="ln_solid"></div>
                <div class="form-group">
                    <div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
                        <button class="btn btn-success">Valider</button>
                    </div>
                </div>

            </form>
        </div>
    </div>
{% endblock body %}
</code>```

This is the Action that control the form.

```<code>public function addCategoryAction(Request $request){

        $category=new Category();
        $form=$this->createForm(CategoryType::class,$category);
        $form->handleRequest($request);

        if ($form->isSubmitted())
        {
            $image= $form['file']->getData();
            $em=$this->getDoctrine()->getManager();
            $req = $request->request->get('Bridge_TravelBundle_Category');
            $category->setName($req['name']);
            $category->setIcon($req['icon']);
            $name = $req['name'];
            try {
                if(!is_dir("CategoriesPictures")){
                    mkdir("CategoriesPictures");
                }

                move_uploaded_file($image,"CategoriesPictures/".$image->getFileName());
                rename("CategoriesPictures/".$image->getFileName() , "CategoriesPictures/".$name.".jpg");

            }
            catch (IOExceptionInterface $e) {
                echo "Erreur Profil existant ou erreur upload image ".$e->getPath();
            }

            $em->persist($category);
            $em->flush();
            return $this->redirectToRoute('admin_categories');
        }

        return $this->render("BridgeTravelBundle:Admin:addcategory.html.twig",array('form' => $form->createView(),));
    }
</code>```

This the CategoryType.php

```<code>use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CategoryType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name')
            ->add('icon')
            ->add('file',FileType::class, array(
                    'multiple'    => false,
                    'attr' => array(

                        'accept' => 'image/*',
                    )
                )
            )       ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Bridge\TravelBundle\Entity\Category'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'Bridge_TravelBundle_Category';
    }
}
</code>```

答:
This attribute enctype='multipart/form-data' is missing from your form tag.

You should just you form_start & form_end instead writing form tag by yourself.

You can also put custom attributes with form_start function like this

```<code>{{ form_start(form, { 'attr': {'class': 'foo', 'id': 'bar' } }) }}
</code>```

Also, form_end is very important because it also print out form_rest and any missing field.

```<code><form method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left">
</code>```

will become

```<code>{{ form_start(form, { 'attr': { 'id': 'demo-form2', 'data-parsley-validate': null, 'class': 'form-horizontal form-label-left' } }) }}
</code>```

and

```<code></form>
</code>```

will become

```<code>{{ form_end(form) }}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Upload image in symfony form

Body:
I am having a weird problem. I added an upload image field to a form. Every thing work fine when i use this code in the twig file

{{ form_start(form) }}
<button>d</button>
{{ form_end(form) }}

But when ever i want to use form_widget to costumize the look of the form this error appear when ever i try to sumit the form

FatalErrorException
  Error: Call to a member function getFileName() on string.

This is the View that cause the problem

{% extends 'BridgeTravelBundle:Admin:layout.html.twig' %}

{% block body %}

            <form method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left">

                    Nom

                        {{ form_widget(form.name, { 'attr': {'class': 'form-control', 'placeholder': 'Prenom' } }) }}
                        {{ form_errors(form.name) }}

                    Icon

                        {{ form_widget(form.icon, { 'attr': {'class': 'form-control', 'placeholder': 'Prenom' } }) }}
                        {{ form_errors(form.icon) }}

                    Icon

                        {{ form_widget(form.file) }}
                        {{ form_errors(form.file) }}

                        <button class="btn btn-success">Valider</button>

            </form>

{% endblock body %}

This is the Action that control the form.

public function addCategoryAction(Request $request){

        $category=new Category();
        $form=$this->createForm(CategoryType::class,$category);
        $form->handleRequest($request);

        if ($form->isSubmitted())
        {
            $image= $form['file']->getData();
            $em=$this->getDoctrine()->getManager();
            $req = $request->request->get('Bridge_TravelBundle_Category');
            $category->setName($req['name']);
            $category->setIcon($req['icon']);
            $name = $req['name'];
            try {
                if(!is_dir("CategoriesPictures")){
                    mkdir("CategoriesPictures");
                }

                move_uploaded_file($image,"CategoriesPictures/".$image->getFileName());
                rename("CategoriesPictures/".$image->getFileName() , "CategoriesPictures/".$name.".jpg");

            }
            catch (IOExceptionInterface $e) {
                echo "Erreur Profil existant ou erreur upload image ".$e->getPath();
            }

            $em->persist($category);
            $em->flush();
            return $this->redirectToRoute('admin_categories');
        }

        return $this->render("BridgeTravelBundle:Admin:addcategory.html.twig",array('form' => $form->createView(),));
    }

This the CategoryType.php

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CategoryType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name')
            ->add('icon')
            ->add('file',FileType::class, array(
                    'multiple'    => false,
                    'attr' => array(

                        'accept' => 'image/*',
                    )
                )
            )       ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Bridge\TravelBundle\Entity\Category'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'Bridge_TravelBundle_Category';
    }
}

Body:
This attribute enctype='multipart/form-data' is missing from your form tag.

You should just you form_start & form_end instead writing form tag by yourself.

You can also put custom attributes with form_start function like this

{{ form_start(form, { 'attr': {'class': 'foo', 'id': 'bar' } }) }}

Also, form_end is very important because it also print out form_rest and any missing field.

<form method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left">

will become

{{ form_start(form, { 'attr': { 'id': 'demo-form2', 'data-parsley-validate': null, 'class': 'form-horizontal form-label-left' } }) }}

and

</form>

will become

{{ form_end(form) }}


问:
Using webpack compiled library as external in CLJS
I have some legacy code which uses D3 and is compiled with webpack.
I'm toying with the idea of porting the D3 bits as external library, and wrapping them as a reagent/re-frame component, yet I have problems importing the JS bits.

I created a small project which demonstrates the problem:

The JS library code .

The webpack config used to (UMD) compile it.

The compiled library (without minify for readability).

Now in a JS project I would use the library like this:

```<code>import * as module from 'd3-lib.js'

var m = new module.Module()

m.setData("miserables.json").render();
</code>```

I tried to mimick that:

I specify the ns the library provides using foreign-libs in project.clj.

Import the library.

Instantiate via the JS-interop

Yet I keep getting:

Uncaught Error: goog.require could not find: d3_lib

答:
Have you tried to use the d3 package from cljsjs ?

Using the cljsjs/d3 package

Add the dependency coordinates [cljsjs/d3 "4.3.0-5"] to the list of :dependencies in your project.
     Make sure to require cljsjs.d3 somewhere in your project so it is added to your compiled ClojureScript code.

(ns your.namespace
       (:require [cljsjs.d3]))

You can now use your newly added library by accessing it through the global Javascript namespace, e.g.js/ReactPlease check the project's documentation to find out what global the library uses. Please note: You can not use :as or :refer with CLJSJS dependencies.

Body:
I have some legacy code which uses D3 and is compiled with webpack.
I'm toying with the idea of porting the D3 bits as external library, and wrapping them as a reagent/re-frame component, yet I have problems importing the JS bits.

I created a small project which demonstrates the problem:

The JS library code .

The webpack config used to (UMD) compile it.

The compiled library (without minify for readability).

Now in a JS project I would use the library like this:

import * as module from 'd3-lib.js'

var m = new module.Module()

m.setData("miserables.json").render();

I tried to mimick that:

I specify the ns the library provides using foreign-libs in project.clj.

Import the library.

Instantiate via the JS-interop

Yet I keep getting:

Uncaught Error: goog.require could not find: d3_lib


问:
How can I send a notification by using the email inserted by another user who requested the notification using Cloud Functions for Firebase?
I'm a beginner on Cloud Functions for Firebase and I'm developing a web app using it to send notifications to specific users. However, the problem is that I want to let the user decid for who he wants to send the message, and the way I've found out to do this was allowing the user to insert through a form in my site the receiver's email, so that I could save it in my database and then activate a function that would send a previously created notification to the registered user who had the same email inserted by the sender user.

So, I know that I have to trigger the function whenever a user sends the form with the receiver's email, since it's when my database is changed. However, I don't know how to compare the email inserted with the email of all others users and then catch only the right user's token to send the notification. Does anyone know how to do this?

These are my code, which I took some parts of this question as a base, and the JSON from part of my database:

Function

```<code>const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPush =
functions.database.ref('/Messages/Receivers/{pushId}').onWrite(event => {

const snapshot = event.data;

const email = snapshot.val().email;
const getAllUsersPromise = admin.database().ref('Users/').once('value');

const payload = {

    notification: {
        title: 'You have a notification',
        body: 'You received a new message'
    }

};

return getAllUsersPromise.then(result => {
    const userUidSnapShot = result;

    const users = Object.keys(userUidSnapShot.val());

    var AllUsersFCMPromises = [];
    for (var i = 0;i<userUidSnapShot.numChildren(); i++) {
        const user=users[i];
        console.log('getting promise of user uid=',user);
        AllUsersFCMPromises[i]= admin.database().ref(`/Users/${user}/email`).equalTo(email).once('value').then(token => {
            var token = admin.database().ref(`/Users/${user}/token`).once('value');
            return token;
        });
    }

    return Promise.all(AllUsersFCMPromises).then(results => {

        var tokens = [];
        for(var i in results){
            var usersTokenSnapShot=results[i];
            console.log('For user = ',i);
            if(usersTokenSnapShot.exists()){
                if (usersTokenSnapShot.hasChildren()) {
                    const t=  Object.keys(usersTokenSnapShot.val());
                    tokens = tokens.concat(t);
                    console.log('token[s] of user = ',t);
                }
                else{

                }
            }
        }
        console.log('final tokens = ',tokens," notification= ",payload);
        return admin.messaging().sendToDevice(tokens, payload).then(response => {

            const tokensToRemove = [];
            response.results.forEach((result, index) => {
                const error = result.error;
                if (error) {
                    console.error('Failure sending notification to uid=', tokens[index], error);

                    if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {
                        tokensToRemove.push(usersTokenSnapShot.ref.child(tokens[index]).remove());
                    }
                }
                else{
                    console.log("notification sent",result);
                }
            });
        });
    });
});
});
</code>```

JSON Structure

```<code>    {
  "Messages" : {
    "Receivers" : {
      "-Ko-Gc8Ch58uYKGIT_Ze" : {
        "email" : "phgrespan@gmail.com"
      },
    }
  },

  "Users" : {
    "1rwdq0O9Iqdo1JUNauwmlC9HXfY2" : {
      "apartamento" : "12",
      "bloco" : "L",
      "celular" : "148162491784",
      "email" : "jose@gmail.com",
      "nome" : "josé",
      "sobrenome" : "josé",
      "telefone" : "418947912497",
      "token" : "een1HZ0ZzP0:APA91bHaY06dT68W3jtlC3xykcnnC7nS3zaNiKBYOayBq-wuZsbv1DMFL8zE6oghieYkvvSn39bDCkXLtc3pfC82AGd8-uvmkuXCkPoTuzxMk14wVQNOB01AQ6L7bmsQBisycm2-znz7"
    },
    "CZv1oxUkfsVpbXNBMQsUZNzSvbt1" : {
      "apartamento" : "8",
      "bloco" : "P",
      "celular" : "123456789",
      "email" : "phgrespan@gmail.com",
      "nome" : "Pedro",
      "sobrenome" : "Henrique",
      "telefone" : "99876543234",
      "token" : "dvE4gBh1fwU:APA91bF9zLC1cOxT4jLsfPRdsxE8q0Z9P4uKuZlp8M5fIoxWd2MOS30u4TLuOQ4G2Sg0mlDqFMuzvjX3_ZSSi9XATyGtTtNse4AxwLYuD-Piw9oFn6Ma68nGfPSTnIEpvDYRwVnRI2e4"
    },
  }
}
</code>```

I hope I have been able to make myself understood and thanks since then.

答:
It seems like you're querying all users when you only need to query the user or users who have the selected email. Instead of using getAllUsersPromise, use .orderByChild() and query the children whose email is equal to the selected email.

```<code>let selectedUsers = admin.database.ref('Users/').orderByChild('email').equalTo(email).once(snap => {
    // Get the token
})
</code>```

This will give you the snapshot of just the user or users who have that email. You can then iterate through the snapshots and get the token(s).

Body:
I'm a beginner on Cloud Functions for Firebase and I'm developing a web app using it to send notifications to specific users. However, the problem is that I want to let the user decid for who he wants to send the message, and the way I've found out to do this was allowing the user to insert through a form in my site the receiver's email, so that I could save it in my database and then activate a function that would send a previously created notification to the registered user who had the same email inserted by the sender user.

So, I know that I have to trigger the function whenever a user sends the form with the receiver's email, since it's when my database is changed. However, I don't know how to compare the email inserted with the email of all others users and then catch only the right user's token to send the notification. Does anyone know how to do this?

These are my code, which I took some parts of this question as a base, and the JSON from part of my database:

Function

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPush =
functions.database.ref('/Messages/Receivers/{pushId}').onWrite(event => {

const snapshot = event.data;

const email = snapshot.val().email;
const getAllUsersPromise = admin.database().ref('Users/').once('value');

const payload = {

    notification: {
        title: 'You have a notification',
        body: 'You received a new message'
    }

};

return getAllUsersPromise.then(result => {
    const userUidSnapShot = result;

    const users = Object.keys(userUidSnapShot.val());

    var AllUsersFCMPromises = [];
    for (var i = 0;i<userUidSnapShot.numChildren(); i++) {
        const user=users[i];
        console.log('getting promise of user uid=',user);
        AllUsersFCMPromises[i]= admin.database().ref(`/Users/${user}/email`).equalTo(email).once('value').then(token => {
            var token = admin.database().ref(`/Users/${user}/token`).once('value');
            return token;
        });
    }

    return Promise.all(AllUsersFCMPromises).then(results => {

        var tokens = [];
        for(var i in results){
            var usersTokenSnapShot=results[i];
            console.log('For user = ',i);
            if(usersTokenSnapShot.exists()){
                if (usersTokenSnapShot.hasChildren()) {
                    const t=  Object.keys(usersTokenSnapShot.val());
                    tokens = tokens.concat(t);
                    console.log('token[s] of user = ',t);
                }
                else{

                }
            }
        }
        console.log('final tokens = ',tokens," notification= ",payload);
        return admin.messaging().sendToDevice(tokens, payload).then(response => {

            const tokensToRemove = [];
            response.results.forEach((result, index) => {
                const error = result.error;
                if (error) {
                    console.error('Failure sending notification to uid=', tokens[index], error);

                    if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {
                        tokensToRemove.push(usersTokenSnapShot.ref.child(tokens[index]).remove());
                    }
                }
                else{
                    console.log("notification sent",result);
                }
            });
        });
    });
});
});

JSON Structure

    {
  "Messages" : {
    "Receivers" : {
      "-Ko-Gc8Ch58uYKGIT_Ze" : {
        "email" : "phgrespan@gmail.com"
      },
    }
  },

  "Users" : {
    "1rwdq0O9Iqdo1JUNauwmlC9HXfY2" : {
      "apartamento" : "12",
      "bloco" : "L",
      "celular" : "148162491784",
      "email" : "jose@gmail.com",
      "nome" : "josé",
      "sobrenome" : "josé",
      "telefone" : "418947912497",
      "token" : "een1HZ0ZzP0:APA91bHaY06dT68W3jtlC3xykcnnC7nS3zaNiKBYOayBq-wuZsbv1DMFL8zE6oghieYkvvSn39bDCkXLtc3pfC82AGd8-uvmkuXCkPoTuzxMk14wVQNOB01AQ6L7bmsQBisycm2-znz7"
    },
    "CZv1oxUkfsVpbXNBMQsUZNzSvbt1" : {
      "apartamento" : "8",
      "bloco" : "P",
      "celular" : "123456789",
      "email" : "phgrespan@gmail.com",
      "nome" : "Pedro",
      "sobrenome" : "Henrique",
      "telefone" : "99876543234",
      "token" : "dvE4gBh1fwU:APA91bF9zLC1cOxT4jLsfPRdsxE8q0Z9P4uKuZlp8M5fIoxWd2MOS30u4TLuOQ4G2Sg0mlDqFMuzvjX3_ZSSi9XATyGtTtNse4AxwLYuD-Piw9oFn6Ma68nGfPSTnIEpvDYRwVnRI2e4"
    },
  }
}

I hope I have been able to make myself understood and thanks since then.

Body:
It seems like you're querying all users when you only need to query the user or users who have the selected email. Instead of using getAllUsersPromise, use .orderByChild() and query the children whose email is equal to the selected email.

let selectedUsers = admin.database.ref('Users/').orderByChild('email').equalTo(email).once(snap => {
    // Get the token
})

This will give you the snapshot of just the user or users who have that email. You can then iterate through the snapshots and get the token(s).


问:
Caliburn.Micro GetAllInstances only returns one viewModel(Caliburn.Micro MVVM)
I've been trying to integrate Caliburn.Micro MVVM framework in a C# WPF project I am in the middle off.

I currently only have three view models:

ShellViewModel - (A Window view with a ContentControl)

AboutViewModel - (A usercontrol view)

ChatViewModel - (Another usercontrol view)

Currently I am trying to use a button at the AboutView that is bind to the 'Chat()' method at the AboutViewModel and should take the user to the ChatView, yet I am testing this with the AboutViewModel. (As seen in the handler)

What I need is that all the Screen/ViewModels to be Singleton and only have one instance and when I try to change page, it returns to an already existant page.

The issue here is that I only have one instance registered when I do IoC.GetAllInstances(), the ShellViewModel and even though I've tried multiple configurations at the bootstrapper, I cannot register my other ViewModels in a way to make their instances "reachable"

I thank you for your time, and here is the code I think it's relevant for the issue:

Here is my bootstrapper:

```<code>public class AppBootstrapper : BootstrapperBase
{
    private SimpleContainer _container = new SimpleContainer();

    public AppBootstrapper()
    {
        Initialize();

        var config = new TypeMappingConfiguration
        {
            DefaultSubNamespaceForViewModels = "ViewModel",
            DefaultSubNamespaceForViews = "View"
        };

        ViewLocator.ConfigureTypeMappings(config);
        Caliburn.Micro.ViewModelLocator.ConfigureTypeMappings(config);
    }

    protected override void Configure()
    {
        _container.Singleton<ShellViewModel, ShellViewModel>();
        _container.Singleton<IWindowManager, WindowManager>();
        //tried registering AboutViewModel in multiple ways
        _container.Singleton<AboutViewModel, AboutViewModel>();
        _container.RegisterSingleton(typeof(AboutViewModel), null,typeof(AboutViewModel));

        /
    }

    protected override void OnStartup(object sender, StartupEventArgs e)
    {
        DisplayRootViewFor<ShellViewModel>();
    }

    protected override object GetInstance(Type service, string key)
    {
        var instance = _container.GetInstance(service, key);
        if (instance != null)
            return instance;
        throw new InvalidOperationException("Could not locate any instances.");
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return _container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance)
    {
        _container.BuildUp(instance);
    }

}
</code>```

ShellViewModel.cs:

```<code>public class ShellViewModel : Conductor<object>, IHandle<NavigationMessage>
{
    /// <summary>
    /// Caliburn.Micro event aggregator. (Publish/Subscribe pattern)
    /// </summary>
    public IEventAggregator events = new EventAggregator();
    public ShellViewModel()
    {
        //var aaa = IoC.Get<IEventAggregator>();
        events.Subscribe(this);
        ActivateItem(new AboutViewModel(events));
    }

    public void Handle(NavigationMessage message)
    {
        //var instance = IoC.GetInstance(message.ViewModelType,null);
        var instances = IoC.GetAllInstances(null);
        foreach(var i in instances)
        {

            MessageBox.Show(i.ToString());
        }
        ActivateItem(new AboutViewModel(events));

    }
}
</code>```

And the AboutViewModel.cs:

```<code>/// <summary>
/// ViewModel belonging to the AboutView.xaml.
/// </summary>
/// <seealso cref="AboutView.xaml"/>
public class AboutViewModel : Screen, IHandle<NavigationMessage>
{
    private readonly IEventAggregator _eventAggregator;
    /// <summary>
    /// Private container for the 'Version' public property.
    /// </summary>
    /// <see cref="Version"/>
    private string _version;

    /// <summary>
    /// Property containing a string of the application's current version (e.g.: 0.1.3.45)
    /// </summary>
    /// <see cref="_version"/>
    [JsonIgnore]
    public string Version
    {
        get
        {
            return _version;
        }
        set
        {
            _version = value;
            NotifyOfPropertyChange(() => Version);
        }
    }

    /// <summary>
    /// Base constructor for the AboutViewModel class.
    /// </summary>
    public AboutViewModel(IEventAggregator eventAggregator)
    {
        Logging.Info("Initialize AboutViewModel", this.GetType());
        Logging.Debug("Subscribing to the eventAggregator", this.GetType());
        _eventAggregator = eventAggregator;
        _eventAggregator.Subscribe(this);

        _version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        Logging.Debug("Version loaded (" + _version + ")", this.GetType());
    }

    /// <summary>
    /// Boolean method connected to the ChatCommand activates or deactivates based on it's return
    /// </summary>
    /// <param name="obj">Object of type GotoPageMessage received from the messenger</param>
    public bool CanChat(object obj)
    {
        return true;
    }
    /// <summary>
    /// Method connected to the ChatCommand that sends the user to the 'Chat' view
    /// </summary>
    /// <param name="obj">Object of type GotoPageMessage received from the messenger</param>
    public void Chat(object obj)
    {

        _eventAggregator.PublishOnUIThread(new NavigationMessage(typeof(AboutViewModel)));
    }

    public void Handle(NavigationMessage message)
    {
        //This handle is used only to know how many instances I have active
        MessageBox.Show("about");
    }
}
</code>```

Edit 1:

P.S.: I used to have my ShellViewModel as Conductor.Collection.OneActive. Still didn't work. Maybe AllActive may work?...

答:
I actually found a solution right now, without messing with Assemblies.

I noticed that the ShellViewModel's instance was accesible, and by saving the instance into a object and debugging it, I noticed all the viewModel instances I created were there at the 'Items'.

Basically this was what I did, in the handler that is inside the ShellViewModel:

```<code>    public void Handle(NavigationMessage message)
    {
        ShellViewModel Shell = (ShellViewModel)IoC.GetInstance(typeof(ShellViewModel), null);
        object Instance = null;

        foreach (var item in Shell.Items)
        {
            if (item.ToString().Contains(message.ViewModelType.ToString()))
                Instance = item;
        }
        object AuxObject = new object();

        if (Instance == null)
        {
            try
            {
                Instance = Activator.CreateInstance(message.ViewModelType, Shell.events);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        ActivateItem(Instance);

    }
</code>```

Body:
I've been trying to integrate Caliburn.Micro MVVM framework in a C# WPF project I am in the middle off.

I currently only have three view models:

ShellViewModel - (A Window view with a ContentControl)

AboutViewModel - (A usercontrol view)

ChatViewModel - (Another usercontrol view)

Currently I am trying to use a button at the AboutView that is bind to the 'Chat()' method at the AboutViewModel and should take the user to the ChatView, yet I am testing this with the AboutViewModel. (As seen in the handler)

What I need is that all the Screen/ViewModels to be Singleton and only have one instance and when I try to change page, it returns to an already existant page.

The issue here is that I only have one instance registered when I do IoC.GetAllInstances(), the ShellViewModel and even though I've tried multiple configurations at the bootstrapper, I cannot register my other ViewModels in a way to make their instances "reachable"

I thank you for your time, and here is the code I think it's relevant for the issue:

Here is my bootstrapper:

public class AppBootstrapper : BootstrapperBase
{
    private SimpleContainer _container = new SimpleContainer();

    public AppBootstrapper()
    {
        Initialize();

        var config = new TypeMappingConfiguration
        {
            DefaultSubNamespaceForViewModels = "ViewModel",
            DefaultSubNamespaceForViews = "View"
        };

        ViewLocator.ConfigureTypeMappings(config);
        Caliburn.Micro.ViewModelLocator.ConfigureTypeMappings(config);
    }

    protected override void Configure()
    {
        _container.Singleton<ShellViewModel, ShellViewModel>();
        _container.Singleton<IWindowManager, WindowManager>();
        //tried registering AboutViewModel in multiple ways
        _container.Singleton<AboutViewModel, AboutViewModel>();
        _container.RegisterSingleton(typeof(AboutViewModel), null,typeof(AboutViewModel));

        /
    }

    protected override void OnStartup(object sender, StartupEventArgs e)
    {
        DisplayRootViewFor<ShellViewModel>();
    }

    protected override object GetInstance(Type service, string key)
    {
        var instance = _container.GetInstance(service, key);
        if (instance != null)
            return instance;
        throw new InvalidOperationException("Could not locate any instances.");
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return _container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance)
    {
        _container.BuildUp(instance);
    }

}

ShellViewModel.cs:

public class ShellViewModel : Conductor<object>, IHandle<NavigationMessage>
{
    ///
    /// Caliburn.Micro event aggregator. (Publish/Subscribe pattern)
    ///
    public IEventAggregator events = new EventAggregator();
    public ShellViewModel()
    {
        //var aaa = IoC.Get<IEventAggregator>();
        events.Subscribe(this);
        ActivateItem(new AboutViewModel(events));
    }

    public void Handle(NavigationMessage message)
    {
        //var instance = IoC.GetInstance(message.ViewModelType,null);
        var instances = IoC.GetAllInstances(null);
        foreach(var i in instances)
        {

            MessageBox.Show(i.ToString());
        }
        ActivateItem(new AboutViewModel(events));

    }
}

And the AboutViewModel.cs:

///
/// ViewModel belonging to the AboutView.xaml.
///
/// <seealso cref="AboutView.xaml"/>
public class AboutViewModel : Screen, IHandle<NavigationMessage>
{
    private readonly IEventAggregator _eventAggregator;
    ///
    /// Private container for the 'Version' public property.
    ///
    /// <see cref="Version"/>
    private string _version;

    ///
    /// Property containing a string of the application's current version (e.g.: 0.1.3.45)
    ///
    /// <see cref="_version"/>
    [JsonIgnore]
    public string Version
    {
        get
        {
            return _version;
        }
        set
        {
            _version = value;
            NotifyOfPropertyChange(() => Version);
        }
    }

    ///
    /// Base constructor for the AboutViewModel class.
    ///
    public AboutViewModel(IEventAggregator eventAggregator)
    {
        Logging.Info("Initialize AboutViewModel", this.GetType());
        Logging.Debug("Subscribing to the eventAggregator", this.GetType());
        _eventAggregator = eventAggregator;
        _eventAggregator.Subscribe(this);

        _version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        Logging.Debug("Version loaded (" + _version + ")", this.GetType());
    }

    ///
    /// Boolean method connected to the ChatCommand activates or deactivates based on it's return
    ///
    /// <param name="obj">Object of type GotoPageMessage received from the messenger</param>
    public bool CanChat(object obj)
    {
        return true;
    }
    ///
    /// Method connected to the ChatCommand that sends the user to the 'Chat' view
    ///
    /// <param name="obj">Object of type GotoPageMessage received from the messenger</param>
    public void Chat(object obj)
    {

        _eventAggregator.PublishOnUIThread(new NavigationMessage(typeof(AboutViewModel)));
    }

    public void Handle(NavigationMessage message)
    {
        //This handle is used only to know how many instances I have active
        MessageBox.Show("about");
    }
}

Edit 1:

P.S.: I used to have my ShellViewModel as Conductor.Collection.OneActive. Still didn't work. Maybe AllActive may work?...

Body:
I actually found a solution right now, without messing with Assemblies.

I noticed that the ShellViewModel's instance was accesible, and by saving the instance into a object and debugging it, I noticed all the viewModel instances I created were there at the 'Items'.

Basically this was what I did, in the handler that is inside the ShellViewModel:

    public void Handle(NavigationMessage message)
    {
        ShellViewModel Shell = (ShellViewModel)IoC.GetInstance(typeof(ShellViewModel), null);
        object Instance = null;

        foreach (var item in Shell.Items)
        {
            if (item.ToString().Contains(message.ViewModelType.ToString()))
                Instance = item;
        }
        object AuxObject = new object();

        if (Instance == null)
        {
            try
            {
                Instance = Activator.CreateInstance(message.ViewModelType, Shell.events);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        ActivateItem(Instance);

    }


问:
My script parses all the links again and again from a infinite scrolling webpage
I've written a script using python in combination with selenium to get all the company links from a webpage which doesn't display all the links until scrolled downmost. However, when I run my script, I get desired links but there are lots of duplicates being scraped along. At this point, I can't get any idea how can I modify my script to get the unique links. Here is what I've tried so far:</p>

```<code>from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://fortune.com/fortune500/list/')
while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(3)

    for items in driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]"):
        item = items.find_elements_by_xpath('.//a')[0]
        print(item.get_attribute("href"))

driver.close()
</code>```

答:
I don't know python but I do know what you are doing wrong. Hopefully you'll be able to figure out the code for yourself ;)

Every time you scroll down 50 links are added to the page until there are 1000 links. Well almost... it starts with 20 links and then adds 30 and then 50 each time until there are 1000.

The way your code is now you are printing of:

The 1st 20 links.

The 1st 20 again + the next 30.

The 1st 50 + the next 50.

And so on...

What you actually want to do is just scroll down the page until you have all the links on the page and then print them. Hope that helps.

Here's the updated Python code (I've checked it and it works)

```<code>from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://fortune.com/fortune500/list/')

while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(5)
    listElements = driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]//a")
    print(len(listElements))
    if (len(listElements) == 1000):
        break

for item in listElements:
    print(item.get_attribute("href"))

driver.close()
</code>```

If you want it to work a bit faster you could swap out the "time.sleep(5)" for Anderson's wait statement

Body:
I've written a script using python in combination with selenium to get all the company links from a webpage which doesn't display all the links until scrolled downmost. However, when I run my script, I get desired links but there are lots of duplicates being scraped along. At this point, I can't get any idea how can I modify my script to get the unique links. Here is what I've tried so far:

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://fortune.com/fortune500/list/')
while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(3)

    for items in driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]"):
        item = items.find_elements_by_xpath('.//a')[0]
        print(item.get_attribute("href"))

driver.close()

Body:
I don't know python but I do know what you are doing wrong. Hopefully you'll be able to figure out the code for yourself ;)

Every time you scroll down 50 links are added to the page until there are 1000 links. Well almost... it starts with 20 links and then adds 30 and then 50 each time until there are 1000.

The way your code is now you are printing of:

The 1st 20 links.

The 1st 20 again + the next 30.

The 1st 50 + the next 50.

And so on...

What you actually want to do is just scroll down the page until you have all the links on the page and then print them. Hope that helps.

Here's the updated Python code (I've checked it and it works)

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://fortune.com/fortune500/list/')

while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(5)
    listElements = driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]//a")
    print(len(listElements))
    if (len(listElements) == 1000):
        break

for item in listElements:
    print(item.get_attribute("href"))

driver.close()

If you want it to work a bit faster you could swap out the "time.sleep(5)" for Anderson's wait statement


问:
What does "@Override" and "<? extends Page>" mean?
```<code>@Override
public Class< ? extends Page> getHomePage() {
            return HomePage.class;
}

public Class<HomePage> getHomePage(){
        return HomePage.class;
}
</code>```

The first one has an annotation
    Override. What does that mean or
    what does it send to the framework.

Will both the methods return the same class. I mean what does this mean  ? extends Page. I mean the ? Mark.

答: JavaDoc</p>

ContentLicense: CC BY-SA 2.5

Body:
@Override
public Class< ? extends Page> getHomePage() {
            return HomePage.class;
}

public Class<HomePage> getHomePage(){
        return HomePage.class;
}

The first one has an annotation
    Override. What does that mean or
    what does it send to the framework.

Will both the methods return the same class. I mean what does this mean  ? extends Page. I mean the ? Mark.

Body: JavaDoc


问:
powershell invoke-restmethod multipart/form-data
I'm currently trying to upload a file to a Webserver by using a REST API. And as mentioned I'm using PowerShell for this. With curl this is no problem. The call looks like this:

```<code>curl -H "Auth_token:"$AUTH_TOKEN -H "Content-Type:multipart/form-data" -X POST -F appInfo='{"name": "test","description": "test"}' -F uploadFile=@/test/test.test https://server/api/
</code>```

But I'm completely helpless when it comes to exporting this to powershell with a Invoke-Restmethod command. As far as I searched it is not possible to use the Invoke-Restmethod for this. https://www.snip2code.com/Snippet/396726/PowerShell-V3-Multipart-formdata-example
But even with that Snipped I'm not smart enough to get this working since I don´t want to upload two files but instead one file and some arguments.

I would be very thankful if someone could get me back on the track with this :o
Thanks!

答:
I had some troubles trying to do the following curl command using Invoke-RestMethod:

curl --request POST \
  --url https://example.com/upload_endpoint/ \
  --header 'content-type: multipart/form-data' \
  --form 'file=@example.csv'
  -v
```
<p>In my case, it turned out to be easier to use <code>curl</code> with powershell.</p>
<pre class="lang-powershell prettyprint-override"><code>$FilePath = "C:\example.csv"
$CurlExecutable = "C:\curl-7.54.1-win64-mingw\bin\curl.exe"

$CurlArguments = '--request', 'POST',
                'https://example.com/upload_endpoint/',
                '--header', "'content-type: multipart/form-data'",
                '--form', "file=@$FilePath"
                '-v',

# Debug the above variables to see what's going to be executed
Write-Host "FilePath" $FilePath
Write-Host "CurlExecutable" $FilePath
Write-Host "CurlArguments" $CurlArguments

# Execute the curl command with its arguments
& $CurlExecutable @CurlArguments
</code>```

Download the executable for your os on curl's website.

Here are some reasons that could make you pick curl instead of powershell's invoke-restmethod

Many of the tools out there can generate curl commands

curl supports uploading files larger than 2GB (see Shukri Adams comment)

Both Curl and Powershell's invoke-restmethod are fine solutions. You might want to consider curl if none of the other answers worked for you. It is usually better to stick with built-in solutions, but sometimes alternatives can be useful.

Body:
I'm currently trying to upload a file to a Webserver by using a REST API. And as mentioned I'm using PowerShell for this. With curl this is no problem. The call looks like this:

curl -H "Auth_token:"$AUTH_TOKEN -H "Content-Type:multipart/form-data" -X POST -F appInfo='{"name": "test","description": "test"}' -F uploadFile=@/test/test.test https://server/api/

But I'm completely helpless when it comes to exporting this to powershell with a Invoke-Restmethod command. As far as I searched it is not possible to use the Invoke-Restmethod for this. https://www.snip2code.com/Snippet/396726/PowerShell-V3-Multipart-formdata-example
But even with that Snipped I'm not smart enough to get this working since I don´t want to upload two files but instead one file and some arguments.

I would be very thankful if someone could get me back on the track with this :o
Thanks!

Body:
I had some troubles trying to do the following curl command using Invoke-RestMethod:

curl --request POST \
  --url https://example.com/upload_endpoint/ \
  --header 'content-type: multipart/form-data' \
  --form 'file=@example.csv'
  -v

In my case, it turned out to be easier to use curl with powershell.

$FilePath = "C:\example.csv"
$CurlExecutable = "C:\curl-7.54.1-win64-mingw\bin\curl.exe"

$CurlArguments = '--request', 'POST',
                'https://example.com/upload_endpoint/',
                '--header', "'content-type: multipart/form-data'",
                '--form', "file=@$FilePath"
                '-v',

# Debug the above variables to see what's going to be executed
Write-Host "FilePath" $FilePath
Write-Host "CurlExecutable" $FilePath
Write-Host "CurlArguments" $CurlArguments

# Execute the curl command with its arguments
& $CurlExecutable @CurlArguments

Download the executable for your os on curl's website.

Here are some reasons that could make you pick curl instead of powershell's invoke-restmethod

Many of the tools out there can generate curl commands

curl supports uploading files larger than 2GB (see Shukri Adams comment)

Both Curl and Powershell's invoke-restmethod are fine solutions. You might want to consider curl if none of the other answers worked for you. It is usually better to stick with built-in solutions, but sometimes alternatives can be useful.

ContentLicense: CC BY-SA 4.0


问:
How do I refer to a list item in a React Component?
I have a component that I'm giving a list to. I do loop through the list in the component to display another component, but each item in the list has an identical property that I want to display one level higher in the component.

Can I do that? If so, how?

Example code:

```<code>export const MyComponent = ({someText, someList}) => (
  <div>
    <h1>{someText}</h1>
    <span>{someList[0].identicalProperty}</span>
    {someList.map((entity, i=0) =>
    <Entity
      identicalProperty={entity.identicalProperty}
      someProperty=[entity.otherPropery}
    />
  </div>
)
</code>```

The idea being that I want to display "identicalProperty" once in the parent component but it is only available on each entity in someList. Is this possible?

Edit:

I forgot to mention, I am getting an error when I try this:
"Error: Objects are not valid as a React child (found: object with keys {someText, someList}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.

答:
Why not put

```<code><span>{someList[0].identicalProperty}</span>
</code>```

as part of the Entity component?

Body:
I have a component that I'm giving a list to. I do loop through the list in the component to display another component, but each item in the list has an identical property that I want to display one level higher in the component.

Can I do that? If so, how?

Example code:

export const MyComponent = ({someText, someList}) => (

{someText}

    {someList[0].identicalProperty}
    {someList.map((entity, i=0) =>
    <Entity
      identicalProperty={entity.identicalProperty}
      someProperty=[entity.otherPropery}
    />

)

The idea being that I want to display "identicalProperty" once in the parent component but it is only available on each entity in someList. Is this possible?

Edit:

I forgot to mention, I am getting an error when I try this:
"Error: Objects are not valid as a React child (found: object with keys {someText, someList}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.

Body:
Why not put

<span>{someList[0].identicalProperty}</span>

as part of the Entity component?


问:
When tapping Quartz events, what is CGEventType 0x1D (29)?
When dealing with Quartz events I can not seem to find any documentation on what event 0x1D, 29 is and how to deal with it.

I have looked here and at an assortment of header files...
https://developer.apple.com/documentation/coregraphics/cgeventtype?language=objc

The event in question is produced when using the touch bar and the track pad.

My specific problem is tapping the trapping touch bar soft keys like escape.  When the user touches escape, a 0x1D event is fired.  If this event isn't returned from the event callback then the kCGEventKeyDown and kCGEventKeyUp events are never fired.  If this event is returned then subsequent events are fired like the button is on a traditional keyboard.

```<code>eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, 0, kCGEventMaskForAllEvents, myCGEventCallback, NULL);

//No touch bar soft key events will ever fire
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type,  CGEventRef event, void *refcon) {
     if(type == 0x1D) {
          return NULL;
     }
}
</code>```

Clearly, I could just always blindly return events of this type, but I would much rather understand what this event represents and what information is available inside it's CGEventRef.

答:
Sometimes things like this are "hidden" in header files. If you take a look at NSEvent.h (CGEventType and NSEventType map onto the same values), you'll find your value:

```<code>// snip...
/* The following event types are available on some hardware on 10.5.2 and later */
NSEventTypeGesture NS_ENUM_AVAILABLE_MAC(10_5)       = 29,
NSEventTypeMagnify NS_ENUM_AVAILABLE_MAC(10_5)       = 30,
NSEventTypeSwipe   NS_ENUM_AVAILABLE_MAC(10_5)       = 31,
// snip...
</code>```

So 29 is a "gesture" event.

Body:
When dealing with Quartz events I can not seem to find any documentation on what event 0x1D, 29 is and how to deal with it.

I have looked here and at an assortment of header files...
https://developer.apple.com/documentation/coregraphics/cgeventtype?language=objc

The event in question is produced when using the touch bar and the track pad.

My specific problem is tapping the trapping touch bar soft keys like escape.  When the user touches escape, a 0x1D event is fired.  If this event isn't returned from the event callback then the kCGEventKeyDown and kCGEventKeyUp events are never fired.  If this event is returned then subsequent events are fired like the button is on a traditional keyboard.

eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, 0, kCGEventMaskForAllEvents, myCGEventCallback, NULL);

//No touch bar soft key events will ever fire
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type,  CGEventRef event, void *refcon) {
     if(type == 0x1D) {
          return NULL;
     }
}

Clearly, I could just always blindly return events of this type, but I would much rather understand what this event represents and what information is available inside it's CGEventRef.

Body:
Sometimes things like this are "hidden" in header files. If you take a look at NSEvent.h (CGEventType and NSEventType map onto the same values), you'll find your value:

// snip...
/* The following event types are available on some hardware on 10.5.2 and later */
NSEventTypeGesture NS_ENUM_AVAILABLE_MAC(10_5)       = 29,
NSEventTypeMagnify NS_ENUM_AVAILABLE_MAC(10_5)       = 30,
NSEventTypeSwipe   NS_ENUM_AVAILABLE_MAC(10_5)       = 31,
// snip...

So 29 is a "gesture" event.


答:
@Override—

the @Override annotation informs the compiler that the element is meant to override an element declared in a superclass (overriding methods will be discussed in the the lesson titled "Interfaces and Inheritance").

Also See

Javadoc

when-do-you-use-javas-override-annotation-and-why

Title: What does "@Override" and "<? extends Page>" mean?


问:
JSP filepath from servlet filter after deploying in Tomcat
I am trying to get the file paths of various JSP files inside my webapp folder after deploying the project in Tomcat. Here is what my directory structure looks like:

```<code>-project
|-top
||-java
|||-com
||||-...
|||-filter
||||-MyFilter.java
||-webapp
|||-jsp
||||-MyJSP.jsp
</code>```

So when the code hits my filter, what would the path be to MyJSP.jsp inside of the doFilter() method? I am trying to edit the contents of the file, so I need to be able to do read and write operations.

When I do request.getServletPath(), it shows the path: /jsp/MyJSP.jsp. However, when I try to read using the following code:

```<code>String str = "";
BufferedReader br = new BufferedReader(new FileReader("/jsp/MyJSP.jsp"));

while ((str = br.readLine()) != null) {
    System.out.println(str );
}

br.close();
</code>```

I get a FileNotFoundException. What am I doing wrong? Is that not the actual path of the jsp file after it is deployed in Tomcat?

Also, I noticed some other questions saying put the files in the WEB-INF folder, however, there is nothing in that folder except for web.xml and I am not allowed to put anything in there.

Any help would be appreciated!

答:
You may have to use request.getServletContext().getRealPath("/jsp/MyJSP.jsp").

```<code>BufferedReader br = new BufferedReader(new FileReader(request.getServletContext().getRealPath("/jsp/MyJSP.jsp")));
</code>```

Body:
I am trying to get the file paths of various JSP files inside my webapp folder after deploying the project in Tomcat. Here is what my directory structure looks like:

-project
|-top
||-java
|||-com
||||-...
|||-filter
||||-MyFilter.java
||-webapp
|||-jsp
||||-MyJSP.jsp

So when the code hits my filter, what would the path be to MyJSP.jsp inside of the doFilter() method? I am trying to edit the contents of the file, so I need to be able to do read and write operations.

When I do request.getServletPath(), it shows the path: /jsp/MyJSP.jsp. However, when I try to read using the following code:

String str = "";
BufferedReader br = new BufferedReader(new FileReader("/jsp/MyJSP.jsp"));

while ((str = br.readLine()) != null) {
    System.out.println(str );
}

br.close();

I get a FileNotFoundException. What am I doing wrong? Is that not the actual path of the jsp file after it is deployed in Tomcat?

Also, I noticed some other questions saying put the files in the WEB-INF folder, however, there is nothing in that folder except for web.xml and I am not allowed to put anything in there.

Any help would be appreciated!

Body:
You may have to use request.getServletContext().getRealPath("/jsp/MyJSP.jsp").

BufferedReader br = new BufferedReader(new FileReader(request.getServletContext().getRealPath("/jsp/MyJSP.jsp")));


问:
Convert JAX-RS resultset to array no loop
I want to convert the resultset to json list but the result just show for 1 row:

result:

{"kodekasus":70,"nama":"string","isdelete":0,"createdby":"string","createddate":"2017-06-29","updatedby":"string","updateddate":"2017-06-29"}

controller:

```<code>@GET
@Path("/tes")
@Produces(MediaType.APPLICATION_JSON)
public Kasuss getTest() throws SQLException {
    String sqlquery = "Select * from Kasus";
    dbCon = new DBConnection();

    try{
        conn = DBConnection.setDBConnection();
        rs = dbCon.getResultSet(sqlquery, conn);
        Kasuss kasus = new Kasuss();

        JSONObject jObj = new JSONObject();
        ArrayList<Kasuss> list = new ArrayList<Kasuss>();
        Map<String, String> map = new HashMap<String, String>();

            while(rs.next()){
                kasus.setKodekasus(rs.getInt(1));
                kasus.setNama(rs.getString(2));
                kasus.setIsdelete(rs.getInt(3));
                kasus.setCreatedby(rs.getString(4));
                kasus.setCreateddate(rs.getDate(5));
                kasus.setUpdatedby(rs.getString(6));
                kasus.setUpdateddate(rs.getDate(7));
                list.add(kasus);
            }
            return kasus;

    }catch(Exception e){
        System.out.println(e);
    }
    return null;
}
</code>```

in database record, not just one record. How to show the list array result? not just one row record.

答:
If you need to receive all records instead of one your method return type should be a collection, e.g.

```<code>public Collection<Kasuss> getTest() throws SQLException {
</code>```

and you need to return the list var not the kasus one.

Body:
I want to convert the resultset to json list but the result just show for 1 row:

result:

{"kodekasus":70,"nama":"string","isdelete":0,"createdby":"string","createddate":"2017-06-29","updatedby":"string","updateddate":"2017-06-29"}

controller:

@GET
@Path("/tes")
@Produces(MediaType.APPLICATION_JSON)
public Kasuss getTest() throws SQLException {
    String sqlquery = "Select * from Kasus";
    dbCon = new DBConnection();

    try{
        conn = DBConnection.setDBConnection();
        rs = dbCon.getResultSet(sqlquery, conn);
        Kasuss kasus = new Kasuss();

        JSONObject jObj = new JSONObject();
        ArrayList<Kasuss> list = new ArrayList<Kasuss>();
        Map<String, String> map = new HashMap<String, String>();

            while(rs.next()){
                kasus.setKodekasus(rs.getInt(1));
                kasus.setNama(rs.getString(2));
                kasus.setIsdelete(rs.getInt(3));
                kasus.setCreatedby(rs.getString(4));
                kasus.setCreateddate(rs.getDate(5));
                kasus.setUpdatedby(rs.getString(6));
                kasus.setUpdateddate(rs.getDate(7));
                list.add(kasus);
            }
            return kasus;

    }catch(Exception e){
        System.out.println(e);
    }
    return null;
}

in database record, not just one record. How to show the list array result? not just one row record.

Body:
If you need to receive all records instead of one your method return type should be a collection, e.g.

public Collection<Kasuss> getTest() throws SQLException {

and you need to return the list var not the kasus one.


问:
Coerce dataframe groups to list
I have a dataframe such as

```<code>id <- c(1,1,1,2,2,3,3,3,3)
element <- c(25122,356,4454,5432,342340,12443,12354,123536,234134)
df <- data.frame(id = as.factor(id), element)
</code>```

I would like to create a list of the id groups with their corresponding elements such as:

```<code>dflist <- list(c(25122,356,4454), c(5432,342340), c(12443,12354,123536,234134))
</code>```

答:
We can use split

```<code>unname(split(df$element, df$id))
</code>```

Or with unstack

```<code>unname(unstack(df, element ~id))
</code>```

Title: Coerce dataframe groups to list

Body:
I have a dataframe such as

id <- c(1,1,1,2,2,3,3,3,3)
element <- c(25122,356,4454,5432,342340,12443,12354,123536,234134)
df <- data.frame(id = as.factor(id), element)

I would like to create a list of the id groups with their corresponding elements such as:

dflist <- list(c(25122,356,4454), c(5432,342340), c(12443,12354,123536,234134))

Body:
We can use split

unname(split(df$element, df$id))

Or with unstack

unname(unstack(df, element ~id))


问:
Change Display Format Of List<KeyValuePair<string, string>>
I am using a Xamarin.Forms Picker and it's being populated by a List<KeyValuePair<string, string>>.  The issue is that it isn't displaying the way I would like.

XAML:

```<code><Picker x:Name="VersionPicker" ItemsSource="{Binding}"/>
</code>```

C#:

```<code>Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
    { "asv1901", "American Standard Version" },
    { "bbe", "Bible In Basic English" },
};
List<KeyValuePair<string, string>> VersionList = VersionDictionary.ToList();

VersionPicker.BindingContext = VersionList;
</code>```

What it produces is like this...

```<code>[asv1901, American Standard Version]
</code>```

I would like Picker to have something along these lines...

```<code>American Standard Version (asv1901)
</code>```

Is there a way to do this?  XAML or C# would be fine (since it's purely a visual change, I was thinking XAML or a converter might make the most sense).

答:
A shout-out to jdweng (since he/she just did a comment and not an answer)...

```<code>Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
    { "asv1901", "American Standard Version" },
    { "bbe", "Bible In Basic English" },
};
// take the dictionary<string, string>, turn it into an ienumerable<keyvaluepair<string, string>>, use linq to output the contents, format a new string based on those contents, turn it into list<string>
// "Bible In Basic English (bbe)"
var VersionList = VersionDictionary.AsEnumerable().Select(x => string.Format("{0} ({1})", x.Value, x.Key)).ToList();

VersionPicker.BindingContext = VersionList;
</code>```

To get that choice back to the appropriate format...

```<code>private void VersionPicker_SelectedIndexChanged(object sender, EventArgs e)
{
    var selecteditem = VersionPicker.SelectedItem.ToString();
    // single quotes make it type Char while double quotes make it type String
    Char delimiter = '(';
    // create an array from the string separated by the delimiter
    String[] selecteditemparts = selecteditem.Split(delimiter);
    // take off the end space
    var selecteditemvalue = selecteditemparts[0].Substring(0, (selecteditemparts[0].Length - 1));
    // take off the end )
    var selecteditemkey = selecteditemparts[1].Substring(0, (selecteditemparts[1].Length - 1));
}
</code>```

As a secondary option (and the one I ended up using)...

```<code>Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
    { "asv1901", "American Standard Version" },
    { "bbe", "Bible In Basic English" },
};

var VersionList = new List<string>();

// keyvaluepair is a single instance and dictionary is a collection of keyvaluepairs
foreach (KeyValuePair<string, string> version in VersionDictionary)
{
    var key = version.Key.ToUpper();
    var value = version.Value;
    // "Bible In Basic English (BBE)"
    VersionList.Add(string.Format("{0} ({1})", value, key));
}
</code>```

It just makes more sense to my rather novice coding brain.  I'm sure jdweng's linq example is much more concise.

Body:
I am using a Xamarin.Forms Picker and it's being populated by a List<KeyValuePair<string, string>>.  The issue is that it isn't displaying the way I would like.

XAML:

<Picker x:Name="VersionPicker" ItemsSource="{Binding}"/>

C#:

Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
    { "asv1901", "American Standard Version" },
    { "bbe", "Bible In Basic English" },
};
List<KeyValuePair<string, string>> VersionList = VersionDictionary.ToList();

VersionPicker.BindingContext = VersionList;

What it produces is like this...

[asv1901, American Standard Version]

I would like Picker to have something along these lines...

American Standard Version (asv1901)

Is there a way to do this?  XAML or C# would be fine (since it's purely a visual change, I was thinking XAML or a converter might make the most sense).

Body:
A shout-out to jdweng (since he/she just did a comment and not an answer)...

Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
    { "asv1901", "American Standard Version" },
    { "bbe", "Bible In Basic English" },
};
// take the dictionary<string, string>, turn it into an ienumerable<keyvaluepair<string, string>>, use linq to output the contents, format a new string based on those contents, turn it into list<string>
// "Bible In Basic English (bbe)"
var VersionList = VersionDictionary.AsEnumerable().Select(x => string.Format("{0} ({1})", x.Value, x.Key)).ToList();

VersionPicker.BindingContext = VersionList;

To get that choice back to the appropriate format...

private void VersionPicker_SelectedIndexChanged(object sender, EventArgs e)
{
    var selecteditem = VersionPicker.SelectedItem.ToString();
    // single quotes make it type Char while double quotes make it type String
    Char delimiter = '(';
    // create an array from the string separated by the delimiter
    String[] selecteditemparts = selecteditem.Split(delimiter);
    // take off the end space
    var selecteditemvalue = selecteditemparts[0].Substring(0, (selecteditemparts[0].Length - 1));
    // take off the end )
    var selecteditemkey = selecteditemparts[1].Substring(0, (selecteditemparts[1].Length - 1));
}

As a secondary option (and the one I ended up using)...

Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
    { "asv1901", "American Standard Version" },
    { "bbe", "Bible In Basic English" },
};

var VersionList = new List<string>();

// keyvaluepair is a single instance and dictionary is a collection of keyvaluepairs
foreach (KeyValuePair<string, string> version in VersionDictionary)
{
    var key = version.Key.ToUpper();
    var value = version.Value;
    // "Bible In Basic English (BBE)"
    VersionList.Add(string.Format("{0} ({1})", value, key));
}

It just makes more sense to my rather novice coding brain.  I'm sure jdweng's linq example is much more concise.


问:
TypeError when using SLSQP solver in PyOpt library
I'm getting TypeErrors when trying to run the optimization library pyOpt. The code I'm trying to run is the basic example given here (I'm only testing for the SLSQP solver).

I'm getting the following error during the execution of the solver

la = numpy.array([max(m,1)], numpy.int)

gg = numpy.zeros([la], numpy.float)
TypeError: only integer scalar arrays can be converted to a scalar index

I suspect the error is due to changes in numpy because of the answer given here. If that is the case, what are my options to make the library work? I can think of downgrading numpy but I don't want any unforseen changes to the other libraries in my system.

Using Python 2.7 with numpy 1.12.1 on Ubuntu 14.04.

答:
replace lz with lz[0] - the issue is with version of numpy as you noted.

/usr/local/lib/python2.7/dist-packages/pyOpt/pySLSQP/pySLSQP.py

I got it to run by changing lines

```<code>374     gg = numpy.zeros([la[0]], numpy.float)
377     dg = numpy.zeros([la[0],n+1], numpy.float)
401     w = numpy.zeros([lw[0]], numpy.float)
404     jw = numpy.zeros([ljw[0]], numpy.intc)
</code>```

I ended up encountering errors during execution that were not python errors but rather errors encountered during operation of the compiled code, so I just switched to using pyGMO2 and I am satisfied.

Body:
replace lz with lz[0] - the issue is with version of numpy as you noted.

/usr/local/lib/python2.7/dist-packages/pyOpt/pySLSQP/pySLSQP.py

I got it to run by changing lines

374     gg = numpy.zeros([la[0]], numpy.float)
377     dg = numpy.zeros([la[0],n+1], numpy.float)
401     w = numpy.zeros([lw[0]], numpy.float)
404     jw = numpy.zeros([ljw[0]], numpy.intc)

I ended up encountering errors during execution that were not python errors but rather errors encountered during operation of the compiled code, so I just switched to using pyGMO2 and I am satisfied.


问:
I am using dot notation to access my object values that are being pushed to a list but it is not working. WHY?
I am attempting to build a simple list using vue.js. The problem is that I am not seeing the object values that are to be rendered to the DOM using the v-for directive.

This is the code :

I am using material design for the layout

```<code>    <template>
      <div id = "app">

        <md-card>

          <md-card-header>

            <div class = "md-title">levi is the inner eye</div>
            <div class = "md-subhead">levi Material</div>

          </md-card-header>

          <md-card-content>

            <md-button class = "md-raised md-primary" v-on:click = "fillTable()">Fill table</md-button>
        <md-button class = "md-raised md-primary" v-on:click = "clearTable()">empty table</md-button>

            <br />

             <md-table>

              <md-table-header>

                <md-table-row>

                  <md-table-head>First name</md-table-head>
                  <md-table-head>Last name</md-table-head>
                  <md-table-head>Email</md-table-head>

                </md-table-row>

              </md-table-header>

              <md-table-body>

                <md-table-row v-for = "contact in contacts" v-bind:data = "contact" v-bind:key = "contact.firstname">

                  <md-table-cell>{{ contact.firstname }}</md-table-cell>
                  <md-table-cell>{{ contact.lastname }}</md-table-cell>
                  <md-table-cell>{{ contact.email }}</md-table-cell>

                </md-table-row>

              </md-table-body>

            </md-table>

          </md-card-content>
        </md-card>
      </div>
</template>
</code>```

Script element

```<code><script>

export default {
  name: 'app',

    data: function() {

    return {

        contacts: []

        }

    },

    methods: {

        fillTable: function() {

    this.contacts.push({firstname: 'Sebastian', lastname: 'Escheiler', email: 's.eschweiler@mail.com'});

        this.contacts.push({firstname: 'Bill', lastname: 'Smith', email: 'b.smith@mail.com'});

        this.contacts.push({firstname: 'Ann', lastname: 'Parker', email: 'a.parker@mail.com'});

        },

        clearTable: function() {

            this.contacts.splice(0, this.contacts.length);
        }
    }

}

</script>
</code>```

Style element

```<code><style>

#app {
  font-family:'Heiti SC';
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 40px;
}

</style>
</code>```

答:
This actually appears to be working: https://codepen.io/aprouja1/pen/rwvYyV

Only thing changed in the Codepen is creating the Vue instance and selecting the #app element.

```<code>Vue.use(VueMaterial)

const app = new Vue( {
  name: "app",
  el:"#app",
  data: function() {
    return {
      contacts: []
    }
  },
  methods: {
    fillTable: function() {
      this.contacts.push({
        firstname: "Sebastian",
        lastname: "Escheiler",
        email: "s.eschweiler@mail.com"
      });

      this.contacts.push({
        firstname: "Bill",
        lastname: "Smith",
        email: "b.smith@mail.com"
      });

      this.contacts.push({
        firstname: "Ann",
        lastname: "Parker",
        email: "a.parker@mail.com"
      });
    },

    clearTable: function() {
      this.contacts.splice(0, this.contacts.length);
    }
  }
});
</code>```

Body:
I am attempting to build a simple list using vue.js. The problem is that I am not seeing the object values that are to be rendered to the DOM using the v-for directive.

This is the code :

I am using material design for the layout

    <template>

        <md-card>

          <md-card-header>

levi is the inner eye

levi Material

          </md-card-header>

          <md-card-content>

            <md-button class = "md-raised md-primary" v-on:click = "fillTable()">Fill table</md-button>
        <md-button class = "md-raised md-primary" v-on:click = "clearTable()">empty table</md-button>

             <md-table>

              <md-table-header>

                <md-table-row>

                  <md-table-head>First name</md-table-head>
                  <md-table-head>Last name</md-table-head>
                  <md-table-head>Email</md-table-head>

                </md-table-row>

              </md-table-header>

              <md-table-body>

                <md-table-row v-for = "contact in contacts" v-bind:data = "contact" v-bind:key = "contact.firstname">

                  <md-table-cell>{{ contact.firstname }}</md-table-cell>
                  <md-table-cell>{{ contact.lastname }}</md-table-cell>
                  <md-table-cell>{{ contact.email }}</md-table-cell>

                </md-table-row>

              </md-table-body>

            </md-table>

          </md-card-content>
        </md-card>

</template>

Script element

Style element

Body:
This actually appears to be working: https://codepen.io/aprouja1/pen/rwvYyV

Only thing changed in the Codepen is creating the Vue instance and selecting the #app element.

Vue.use(VueMaterial)

const app = new Vue( {
  name: "app",
  el:"#app",
  data: function() {
    return {
      contacts: []
    }
  },
  methods: {
    fillTable: function() {
      this.contacts.push({
        firstname: "Sebastian",
        lastname: "Escheiler",
        email: "s.eschweiler@mail.com"
      });

      this.contacts.push({
        firstname: "Bill",
        lastname: "Smith",
        email: "b.smith@mail.com"
      });

      this.contacts.push({
        firstname: "Ann",
        lastname: "Parker",
        email: "a.parker@mail.com"
      });
    },

    clearTable: function() {
      this.contacts.splice(0, this.contacts.length);
    }
  }
});


问:
Cocoapods linker error when running app from Xcode project
I tried installing some Cocoapods based on some instructions online and the whole process went as described. But I now get an error:

ld: framework not found Pods_Happ
  clang: error: linker command failed with exit code 1 (use -v to see invocation)

I tried installing a pod called "WCLShineButton". I think it has something to do with my app's framework because the "Pods_Happ.framework" is red:

Pods_Happ.framework red

答:
Close the .xcodeproj file and open the .xcworkspace file in Xcode instead.

CocoaPods wraps your Xcode project (.xcodeproj) into an Xcode workspace. After that you should always work with the workspace instead of the project.


问:
How to get sidebar full length of page below top navigation with bootstrap 4?
New to bootstrap and using the alpha version of bootstrap 4 to create a site for my home network.

I'd like the sidebar to fill the entire left side of the page, starting below the top nav bar. Right now there is a small 20 or so pixel gap between the top navbar and sidebar. I'd also like it to continue all the way down, despite the size of the page.

I'm using the admin template from bootstrap and modified it to my needs.

https://jsfiddle.net/ced6ee78/

CSS:

```<code>body, html {
  height: 100%;
}

body {
  padding-top: 70px;
}

/* BrandName Top Navbar */
.so-navbar-top {
    background-color: #087ca7;
    height: 48px;
}

.so-navbar-top .navbar-brand {
  font-size: 1.5em;
}

.so-navbar-top .nav-item {
  font-size: 0.75em;
}

/* BrandName Sidebar */
.so-sidebar {
  background-color: #13293d;
}

/* workaround modal-open padding issue */

body.modal-open {

padding-right: 0 !important;

}

#sidebar {

padding-left:0;

}

/*

* Off Canvas at medium breakpoint

* --------------------------------------------------

*/

@media screen and (max-width: 48em) {

  .row-offcanvas {

    position: relative;

    -webkit-transition: all 0.25s ease-out;

    -moz-transition: all 0.25s ease-out;

    transition: all 0.25s ease-out;

  }

  .row-offcanvas-left
  .sidebar-offcanvas {

    left: -33%;
  }

  .row-offcanvas-left.active {

    left: 33%;

    margin-left: -6px;

  }

  .sidebar-offcanvas {

    position: absolute;

    top: 0;

    width: 33%;

    height: 100%;

  }

}

/*

* Off Canvas wider at sm breakpoint

* --------------------------------------------------

*/

@media screen and (max-width: 34em) {

  .row-offcanvas-left
  .sidebar-offcanvas {

    left: -45%;

  }

  .row-offcanvas-left.active {

    left: 45%;

    margin-left: -6px;

  }

  .sidebar-offcanvas {

    width: 45%;

  }

}

.card {

    overflow:hidden;

}

.card-block .rotate {

    z-index: 8;

    float: right;

    height: 100%;

}

.card-block .rotate i {

    color: rgba(20, 20, 20, 0.15);

    position: absolute;

    left: 0;

    left: auto;

    right: -10px;

    bottom: 0;

    display: block;

    -webkit-transform: rotate(-44deg);

    -moz-transform: rotate(-44deg);

    -o-transform: rotate(-44deg);

    -ms-transform: rotate(-44deg);
    transform: rotate(-44deg);

}
</code>```

HTML

```<code><!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/brandname/css/style.css" rel="stylesheet">

    <script src="assets/jquery/jquery.min.js"></script>
    <script src="assets/jquery-ui/jquery-ui.min.js"></script>

    <title>Dashboard | BrandName</title>

  </head>

  <body>

    <nav class="navbar fixed-top navbar-toggleable-sm navbar-light bg-fade mb-3 so-navbar-top">

      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#collapsingNavbar">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="flex-row d-flex">

        <a class="navbar-brand mb-1" href="#" title="ServiceOps">BrandName</a>

        <button type="button" class="hidden-md-up navbar-toggler" data-toggle="offcanvas" title="Toggle responsive left sidebar">
          <span class="navbar-toggler-icon"></span>
        </button>

      </div>

      <div class="navbar-collapse collapse" id="collapsingNavbar">

        <ul class="navbar-nav ml-auto">

          <li class="nav-item">
            <a class="nav-link" href="#">
              <i class="fa fa-bell-o"></i><span class="badge badge-pill badge-danger">1</span> Alerts</a>
          </li>

          <li class="nav-item">
            <a class="nav-link" href="#">
              <i class="fa fa-cog"></i> Settings
            </a>
          </li>

          <li class="nav-item">
            <a class="nav-link" href="#">
              <i class="fa fa-user"></i> Profile
            </a>
          </li>

          <li class="nav-item">
            <a class="nav-link" href="#">
              <i class="fa fa-sign-out"></i> Logout
            </a>
          </li>

        </ul>

      </div>

    </nav>

    <div class="container-fluid" id="main">

      <div class="row row-offcanvas row-offcanvas-left">

        <div class="col-md-3 col-lg-2 sidebar-offcanvas so-sidebar" id="sidebar" role="navigation">

          <ul class="nav flex-column pl-1">

            <li class="nav-item"><a class="nav-link" href="#">Dashboard</a></li>

            <li class="nav-item">

              <a class="nav-link" href="#submenu1" data-toggle="collapse" data-target="#submenu1">Sites</a>

              <ul class="list-unstyled flex-column pl-3 collapse" id="submenu1" aria-expanded="false">
                <li class="nav-item"><a class="nav-link" href="">Item 1</a></li>
                <li class="nav-item"><a class="nav-link" href="">Item 2</a></li>
              </ul>

            </li>

          </ul>

        </div>

        <div class="col-md-9 col-lg-10 main">

          <!--toggle sidebar button
          <p class="hidden-md-up">
            <button type="button" class="btn btn-primary-outline btn-sm" data-toggle="offcanvas"><i class="fa fa-chevron-left"></i> Menu</button>
          </p>-->

          <h1 class="display-2 hidden-xs-down">Dashboard</h1>

          <div class="row mb-3">

            <div class="col-xl-3 col-lg-6">

              <div class="card card-inverse card-success">

                <div class="card-block bg-success">

                  <div class="rotate">
                    <i class="fa fa-user fa-5x"></i>
                  </div>

                  <h6 class="text-uppercase">Users</h6>
                  <h1 class="display-1">134</h1>

                </div>

              </div>

            </div>

            <div class="col-xl-3 col-lg-6">

              <div class="card card-inverse card-danger">

                <div class="card-block bg-danger">

                  <div class="rotate">

                    <i class="fa fa-list fa-4x"></i>

                  </div>

                  <h6 class="text-uppercase">Posts</h6>
                  <h1 class="display-1">87</h1>

                </div>

              </div>

            </div>

            <div class="col-xl-3 col-lg-6">

              <div class="card card-inverse card-info">

                <div class="card-block bg-info">

                  <div class="rotate">

                    <i class="fa fa-twitter fa-5x"></i>

                  </div>

                  <h6 class="text-uppercase">Tweets</h6>
                  <h1 class="display-1">125</h1>

                </div>

              </div>

            </div>

            <div class="col-xl-3 col-lg-6">

              <div class="card card-inverse card-warning">

                <div class="card-block bg-warning">

                  <div class="rotate">

                    <i class="fa fa-share fa-5x"></i>

                  </div>

                  <h6 class="text-uppercase">Shares</h6>
                  <h1 class="display-1">36</h1>

                </div>

              </div>

            </div>

          </div>

        </div>

      </div>

    </div>

    <footer class="container-fluid">

      <p class="text-right small">©2017 BrandName</p>

    </footer>

  </body>

</html>
</code>```

答:
The gap between the header and sidebar is caused by padding-top: 70px; on the body, which causes everything besides for the fixed header to be 70px from the top of the page.

You need this rule to prevent all other elements from starting behind your fixed header, however, to prevent any gap, give it the exact height of your header.

```<code>padding-top: 48px;
</code>```

To make the sidebar take up the entire length of the page, give it a minimum height of 100vh minus the body's padding (header's height)

You can do that with CSS3's calc():

```<code>min-height: calc(100vh - 48px);
</code>```

With this layout, you can put the footer together with the rest of the app to prevent it from appearing below the sidebar.

Here's a jsFiddle.

The other option would be adding position: fixed to the sidebar, and adding padding/margins so the rest of the elements don't overlap.

Body:
New to bootstrap and using the alpha version of bootstrap 4 to create a site for my home network.

I'd like the sidebar to fill the entire left side of the page, starting below the top nav bar. Right now there is a small 20 or so pixel gap between the top navbar and sidebar. I'd also like it to continue all the way down, despite the size of the page.

I'm using the admin template from bootstrap and modified it to my needs.

https://jsfiddle.net/ced6ee78/

CSS:

body, html {
  height: 100%;
}

body {
  padding-top: 70px;
}

/* BrandName Top Navbar */
.so-navbar-top {
    background-color: #087ca7;
    height: 48px;
}

.so-navbar-top .navbar-brand {
  font-size: 1.5em;
}

.so-navbar-top .nav-item {
  font-size: 0.75em;
}

/* BrandName Sidebar */
.so-sidebar {
  background-color: #13293d;
}

/* workaround modal-open padding issue */

body.modal-open {

padding-right: 0 !important;

}

#sidebar {

padding-left:0;

}

/*

* Off Canvas at medium breakpoint

* --------------------------------------------------

*/

@media screen and (max-width: 48em) {

  .row-offcanvas {

    position: relative;

    -webkit-transition: all 0.25s ease-out;

    -moz-transition: all 0.25s ease-out;

    transition: all 0.25s ease-out;

  }

  .row-offcanvas-left
  .sidebar-offcanvas {

    left: -33%;
  }

  .row-offcanvas-left.active {

    left: 33%;

    margin-left: -6px;

  }

  .sidebar-offcanvas {

    position: absolute;

    top: 0;

    width: 33%;

    height: 100%;

  }

}

/*

* Off Canvas wider at sm breakpoint

* --------------------------------------------------

*/

@media screen and (max-width: 34em) {

  .row-offcanvas-left
  .sidebar-offcanvas {

    left: -45%;

  }

  .row-offcanvas-left.active {

    left: 45%;

    margin-left: -6px;

  }

  .sidebar-offcanvas {

    width: 45%;

  }

}

.card {

    overflow:hidden;

}

.card-block .rotate {

    z-index: 8;

    float: right;

    height: 100%;

}

.card-block .rotate i {

    color: rgba(20, 20, 20, 0.15);

    position: absolute;

    left: 0;

    left: auto;

    right: -10px;

    bottom: 0;

    display: block;

    -webkit-transform: rotate(-44deg);

    -moz-transform: rotate(-44deg);

    -o-transform: rotate(-44deg);

    -ms-transform: rotate(-44deg);
    transform: rotate(-44deg);

}

HTML

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/brandname/css/style.css" rel="stylesheet">

    <title>Dashboard | BrandName</title>

      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#collapsingNavbar">

      </button>

        BrandName

        <button type="button" class="hidden-md-up navbar-toggler" data-toggle="offcanvas" title="Toggle responsive left sidebar">

        </button>

              1 Alerts

               Settings

               Profile

               Logout

Dashboard

              Sites

Item 1

Item 2

Dashboard

Users

134

Posts

87

Tweets

125

Shares

36

©2017 BrandName

Body:
The gap between the header and sidebar is caused by padding-top: 70px; on the body, which causes everything besides for the fixed header to be 70px from the top of the page.

You need this rule to prevent all other elements from starting behind your fixed header, however, to prevent any gap, give it the exact height of your header.

padding-top: 48px;

To make the sidebar take up the entire length of the page, give it a minimum height of 100vh minus the body's padding (header's height)

You can do that with CSS3's calc():

min-height: calc(100vh - 48px);

With this layout, you can put the footer together with the rest of the app to prevent it from appearing below the sidebar.

Here's a jsFiddle.

The other option would be adding position: fixed to the sidebar, and adding padding/margins so the rest of the elements don't overlap.


问:
Why is print_r return value and 1
My class getting the name

```<code>public function getGameName($gameID){
    $gameIDValid = false;

    try {
        $db = database::databaseConnect();

        $getGame_stmt = $db->prepare('SELECT gameID, shortTitle FROM games WHERE gameID =:gameID');
        $getGame_stmt->bindParam(':gameID', $gameID, PDO::PARAM_INT);

        $getGame_stmt->execute();

        if($getGame_stmt->rowCount() == 1){
            $gameIDValid = true;
        }

        $db = NULL;

    } catch (PDOException $e) {
        $gameIDValid = false;
    }

    return $gameIDValid;

}
</code>```

From my class doing error checking

```<code>public function validategameID($gameID) {
    $validGame = userValidation::getGameName($gameID);
    if($validGame === false){
         return 'Problem adding your game';
    }
}
</code>```

My Validation code:

```<code>$validatedGameID = $validateUserInput->validategameID($gameID);
die($validatedGameID);
</code>```

If I choose a wrong Game ID I get the error message.  However when I use:

```<code>    die(print_r($validatedGameID));
</code>```

I get the following output:

```<code>Problem adding your game1
</code>```

If I use the correct Game ID I can't execute any other code after the:

```<code>die($validatedGameID);
</code>```

Can anyone please help?  Why is the function returning a 1 at the end of the error message when I use print_r and why can't I execute any code after the die even with a correct game id?

答:
The print_r function prints all its output to the screen and returns true as a value. If you want it to return the data rather than print to screen add true as the second parameter

```<code>$dump = print_r($var, true);
</code>```

See http://php.net/manual/en/function.print-r.php

Title: Why is print_r return value and 1

Body:
My class getting the name

public function getGameName($gameID){
    $gameIDValid = false;

    try {
        $db = database::databaseConnect();

        $getGame_stmt = $db->prepare('SELECT gameID, shortTitle FROM games WHERE gameID =:gameID');
        $getGame_stmt->bindParam(':gameID', $gameID, PDO::PARAM_INT);

        $getGame_stmt->execute();

        if($getGame_stmt->rowCount() == 1){
            $gameIDValid = true;
        }

        $db = NULL;

    } catch (PDOException $e) {
        $gameIDValid = false;
    }

    return $gameIDValid;

}

From my class doing error checking

public function validategameID($gameID) {
    $validGame = userValidation::getGameName($gameID);
    if($validGame === false){
         return 'Problem adding your game';
    }
}

My Validation code:

$validatedGameID = $validateUserInput->validategameID($gameID);
die($validatedGameID);

If I choose a wrong Game ID I get the error message.  However when I use:

    die(print_r($validatedGameID));

I get the following output:

Problem adding your game1

If I use the correct Game ID I can't execute any other code after the:

die($validatedGameID);

Can anyone please help?  Why is the function returning a 1 at the end of the error message when I use print_r and why can't I execute any code after the die even with a correct game id?

Body:
The print_r function prints all its output to the screen and returns true as a value. If you want it to return the data rather than print to screen add true as the second parameter

$dump = print_r($var, true);

See http://php.net/manual/en/function.print-r.php


问:
Is there any way to detect when a CSS file has been fully loaded?
I've been testing a lot of lazy-loaders for JavaScript and CSS that insert

答:
Using a script loader like Supply, this would look like:

```<code>supply.listen('text/css', function(payload, filename) {
    switch(filename) {
        case: 'foo.css': {
            // do something
            break;
        }
        case: 'baseball.css': {
            break;
        }
        // ...
    }
});

supply.files({
    stylesheet: [
        'foo.css',
        'baseball.css'
    ]
});
</code>```

Ref.: SupplyJS

Body:
Using a script loader like Supply, this would look like:

supply.listen('text/css', function(payload, filename) {
    switch(filename) {
        case: 'foo.css': {
            // do something
            break;
        }
        case: 'baseball.css': {
            break;
        }
        // ...
    }
});

supply.files({
    stylesheet: [
        'foo.css',
        'baseball.css'
    ]
});

Ref.: SupplyJS