问:
Trigger onClick event when Enter keypress in a Twitter Bootstrap Modal
I've a few modals build on top of Twitter Bootstrap Modal, each have at least one submit button which is the default action I need to trigger in most cases since the second button is for go back (dismiss the modal), how, on a modal, when I hit enter I can trigger whatever action that submit has? For example right now, as they are button I have something like:

```<code>$("#btn").on("click", function(e){
    e.preventDefault(); // wait... not send form yet, will be a Ajax call
});
</code>```

Any help? Example code?

For reference, this is the modal content (I using with Twig as part of a Symfony2 project so don't worry about {{ }}):

```<code><div class="modal fade " id="addNorma" tabindex="-1" role="dialog" aria-labelledby="addNorma" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">{{ 'boton.cerrar'|trans({}, 'AppBundle') }}</span></button>
                <h4 class="modal-title" id="myModalLabel">{{ 'modal.normas.titulo'|trans({}, 'AppBundle') }}</h4>
            </div>
            <div class="modal-body">
                <form id="buscadorNorma" method="POST">
                    <div class="spacer10"></div>
                    <div class="row">
                        <div class="col-md-5 col-lg-5 col-sm-5 col-xs-5">
                            <label for="codigo_norma">{{ 'modal.normas.codigo'|trans({}, 'AppBundle') }}</label>
                            <input type="text" class="form-control" id="codigo_norma" name="codigo_norma" placeholder="{{ 'modal.normas.codigoPlaceholder'|trans({}, 'AppBundle') }}">
                        </div>
                        <div class="col-md-5 col-lg-5 col-sm-5 col-xs-5 col-md-offset-2">
                            <label for="ano_publicacion">{{ 'modal.normas.anno'|trans({}, 'AppBundle') }}</label>
                            <input type="text" class="form-control" id="ano_publicacion" name="ano_publicacion" placeholder="{{ 'modal.normas.annoPlaceholder'|trans({}, 'AppBundle') }}">
                        </div>
                    </div>
                    <div class="spacer10"></div>
                    <div class="row">
                        <div class="col-md-12">
                            <label for="nombre_norma">{{ 'modal.normas.term'|trans({}, 'AppBundle') }}</label>
                            <input type="text" class="form-control" id="nombre_norma" name="nombre_norma" placeholder="{{ 'modal.normas.termPlaceholder'|trans({}, 'AppBundle') }}">
                        </div>
                    </div>
                    <div class="spacer10"></div>
                    <div class="row">
                        <div class="col-md-12">
                            <label for="procedencia_producto">{{ 'modal.normas.comite'|trans({}, 'AppBundle') }}</label>
                            <div class="form-group">
                                <div>
                                    <select name="comite_tecnico" id="comite_tecnico" class="form-control toSelect2">
                                        <option value="" selected="selected">{{ 'seleccioneOpcion'|trans({}, 'AppBundle') }}</option>
                                        {% for key, item in comiteTecnico %}
                                            <option value="{{ key }}">{{ item.nombre }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="spacer5"></div>
                    <div class="row">
                        <div class="col-md-12">
                            <button type="button" class="btn btn-default pull-right" disabled="disabled" id="btnBuscarNorma"><i class="fa fa-binoculars"></i> {{ 'boton.buscar'|trans({}, 'AppBundle') }}</button>
                        </div>
                    </div>
                </form>
                <div class="spacer10"></div>
                <table  class="table table-hover table-condensed" id="resultadoNorma" style="display: none">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="toggleCheckboxNorma" name="toggleCheckboxNorma" /></th>
                            <th>{{ 'columnas.normas.no'|trans({}, 'AppBundle') }}</th>
                            <th>{{ 'columnas.normas.norma'|trans({}, 'AppBundle') }}</th>
                            <th>{{ 'columnas.normas.anno'|trans({}, 'AppBundle') }}</th>
                            <th>{{ 'columnas.normas.comite'|trans({}, 'AppBundle') }}</th>
                        </tr>
                    </thead>
                    <tbody id="resultadoNormaBody"></tbody>
                </table>
                <div class="alert alert-danger" role="alert" style="display: none;" id="sinResultadosBuscarNormas">
                    {{ 'mensajes.msgNoEncontrado'|trans({}, 'AppBundle') }}
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">{{ 'boton.regresar'|trans({}, 'AppBundle') }}</button>
                <button type="submit" class="btn btn-primary" id="btnAplicarNorma" disabled="disabled"><i class="fa fa-save"></i> {{ 'boton.aplicar'|trans({}, 'AppBundle') }}</button>
            </div>
        </div>
    </div>
</div>
</code>```

And that's the code I trigger when I click on #btnBuscarNorma:

```<code>$('button#btnBuscarNorma').on('click', function (ev) {
    ev.preventDefault();
    $.post(Routing.generate('filtrarNormas'), $('#buscadorNorma').serialize(), 'json')
        .done(function (data, textStatus, jqXHR) {
            $('#resultadoNorma').toggle(!!data.entities.length);
            $("#sinResultadosBuscarNormas").toggle(!data.entities.length);

            if (data.entities.length > 0) {
                var $html = '';
                data.entities.forEach(function (value, index, array) {
                    $html += '<tr>';
                    $html += '<td><input type="checkbox" id="' + value.id + '" value="' + value.id + '"></td>';
                    $html += '<td>' + value.codigo + '</td>';
                    $html += '<td>' + value.norma + '</td>';
                    $html += '<td>' + value.anno + '</td>';
                    $html += '<td>' + value.comiteTecnico + '</td>';
                    $html += '</tr>';
                });

                $("table tbody#resultadoNormaBody").html($html);
                marcarTodosCheck('#toggleCheckboxNorma', '#resultadoNormaBody');
            }
        });
});
</code>```

The idea is Enter key will trigger #btnBuscarNorma click event and not #btnAplicarNorma click event.

答:
When modal is opened in class is active on it.
So you can get in JQuery:

```<code>$("#addNorma.in").on("keydown",function(e){
    if(e.which == 13){
        //Do something.
    }
});
</code>```

Body:
I've a few modals build on top of Twitter Bootstrap Modal, each have at least one submit button which is the default action I need to trigger in most cases since the second button is for go back (dismiss the modal), how, on a modal, when I hit enter I can trigger whatever action that submit has? For example right now, as they are button I have something like:

$("#btn").on("click", function(e){
    e.preventDefault(); // wait... not send form yet, will be a Ajax call
});

Any help? Example code?

For reference, this is the modal content (I using with Twig as part of a Symfony2 project so don't worry about {{ }}):

                <button type="button" class="close" data-dismiss="modal">×{{ 'boton.cerrar'|trans({}, 'AppBundle') }}</button>

{{ 'modal.normas.titulo'|trans({}, 'AppBundle') }}

                <form id="buscadorNorma" method="POST">

                            {{ 'modal.normas.codigo'|trans({}, 'AppBundle') }}
                            <input type="text" class="form-control" id="codigo_norma" name="codigo_norma" placeholder="{{ 'modal.normas.codigoPlaceholder'|trans({}, 'AppBundle') }}">

                            {{ 'modal.normas.anno'|trans({}, 'AppBundle') }}
                            <input type="text" class="form-control" id="ano_publicacion" name="ano_publicacion" placeholder="{{ 'modal.normas.annoPlaceholder'|trans({}, 'AppBundle') }}">

                            {{ 'modal.normas.term'|trans({}, 'AppBundle') }}
                            <input type="text" class="form-control" id="nombre_norma" name="nombre_norma" placeholder="{{ 'modal.normas.termPlaceholder'|trans({}, 'AppBundle') }}">

                            {{ 'modal.normas.comite'|trans({}, 'AppBundle') }}

                                    <select name="comite_tecnico" id="comite_tecnico" class="form-control toSelect2">
                                        <option value="" selected="selected">{{ 'seleccioneOpcion'|trans({}, 'AppBundle') }}</option>
                                        {% for key, item in comiteTecnico %}
                                            <option value="{{ key }}">{{ item.nombre }}</option>
                                        {% endfor %}
                                    </select>

                            <button type="button" class="btn btn-default pull-right" disabled="disabled" id="btnBuscarNorma"> {{ 'boton.buscar'|trans({}, 'AppBundle') }}</button>

                </form>

                            <input type="checkbox" id="toggleCheckboxNorma" name="toggleCheckboxNorma" />
                            {{ 'columnas.normas.no'|trans({}, 'AppBundle') }}
                            {{ 'columnas.normas.norma'|trans({}, 'AppBundle') }}
                            {{ 'columnas.normas.anno'|trans({}, 'AppBundle') }}
                            {{ 'columnas.normas.comite'|trans({}, 'AppBundle') }}

                    {{ 'mensajes.msgNoEncontrado'|trans({}, 'AppBundle') }}

                <button type="button" class="btn btn-danger" data-dismiss="modal">{{ 'boton.regresar'|trans({}, 'AppBundle') }}</button>
                <button type="submit" class="btn btn-primary" id="btnAplicarNorma" disabled="disabled"> {{ 'boton.aplicar'|trans({}, 'AppBundle') }}</button>

And that's the code I trigger when I click on #btnBuscarNorma:

$('button#btnBuscarNorma').on('click', function (ev) {
    ev.preventDefault();
    $.post(Routing.generate('filtrarNormas'), $('#buscadorNorma').serialize(), 'json')
        .done(function (data, textStatus, jqXHR) {
            $('#resultadoNorma').toggle(!!data.entities.length);
            $("#sinResultadosBuscarNormas").toggle(!data.entities.length);

            if (data.entities.length > 0) {
                var $html = '';
                data.entities.forEach(function (value, index, array) {
                    $html += '
';
                    $html += '<input type="checkbox" id="' + value.id + '" value="' + value.id + '">	';
                    $html += '' + value.codigo + '	';
                    $html += '' + value.norma + '	';
                    $html += '' + value.anno + '	';
                    $html += '' + value.comiteTecnico + '	';
                    $html += '
';
                });

                $("table tbody#resultadoNormaBody").html($html);
                marcarTodosCheck('#toggleCheckboxNorma', '#resultadoNormaBody');
            }
        });
});

The idea is Enter key will trigger #btnBuscarNorma click event and not #btnAplicarNorma click event.

Body:
When modal is opened in class is active on it.
So you can get in JQuery:

$("#addNorma.in").on("keydown",function(e){
    if(e.which == 13){
        //Do something.
    }
});


来源: stackexchange

问:
Is there a way to understand if Android App Update was installed by users?
I just published an update to my Android App on Android Market and Android market sent notification for the update which is fine. But I am trying to figure out if there is a way to know if the users installed the update that was published?

I do not see any details in Android Market Developer console.
These are users who were using the earlier version already not new users. Any insight would be very helpful.

答:
Integrate Crashlytics into your app. This will give you a complete report of active users and crashes per day for each version you release.

Tutorial to integrate Crashlytics to your app

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Vertically align text next to an image in
Hello I am making simple mailing and have a trouble.

I can't align text next to image in

```<code><td width="433" style="color:#707177; font-family:Arial, Helvetica, sans-serif; font-size:14px; text-align:left; width:433px;" valign="middle">
  <img alt="email" src="https://cdn3.iconfinder.com/data/icons/streamline-icon-set-free-pack/48/Streamline-18-128.png" height="15" width="15" style="vertical-align:middle;">
  <span style="color:#707177;font-size:14px;">000 000 000</span>
</td>
</code>```

I've created jsFiddle.

I can't use something like 	text

答:
Add vertical-align:middle; to your span. It's a small difference, but it works.

```<code><span class="feed" style="color:#707177;font-size:14px;vertical-align:middle;">000 000 000</span>
</code>```

https://jsfiddle.net/8va7zLdn/1/

Title: Vertically align text next to an image in <td>

Body:
Hello I am making simple mailing and have a trouble.

I can't align text next to image in

  000 000 000

I've created jsFiddle.

I can't use something like 	text

Body:
Add vertical-align:middle; to your span. It's a small difference, but it works.

<span class="feed" style="color:#707177;font-size:14px;vertical-align:middle;">000 000 000</span>

https://jsfiddle.net/8va7zLdn/1/


问:
price of developer license for Windows Phone 7?
Does Microsoft offer developer license for professionals and students? Is there a special student program?</p>

答:
To develop applications, it's free.

But if you need to know the price to submit your apps to the marketplace:

Check out Windows Development App Hub

It's $99 US Dollers or £65 in the UK.

That allows you to submit 5 applications. It is $19.99 for each app after that. If you are a student, you get a load of tools free. You can access the student membership via the link above.


问:
Maven error : Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher
I'd been stuck with this simple issue for an hour now. Maven was working fine last week, I don't know what went wrong it gives me this error. I tried all the ways to debug and all the solutions found in StackOverflow and many other places. I even tried replacing M2_HOME path with M3_HOME and MAVEN_HOME. Nothing worked. I'm on OS X. Below is the output of few maven commands. I'll be happy to provide more information</p>

```<code>$ mvn
Error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

$ which mvn
/Library/Maven-3.3.3/bin/mvn

$ echo $M2_HOME
/Library/Maven-3.3.3

$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home

$ which java
/usr/bin/java

$ /Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home/bin/java -version
java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.75-b04, mixed mode)

$ echo $PATH
/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Tomcat/bin:/Library/Maven-3.3.3/bin

$ java -version
java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.75-b04, mixed mode)

$  ls -lR /Library/Maven-3.3.3
total 56
-rw-r--r--@  1 USERNAME  wheel  19091 Apr 22 04:58 LICENSE
-rw-r--r--@  1 USERNAME  wheel    182 Apr 22 04:58 NOTICE
-rw-r--r--@  1 USERNAME  wheel   2541 Apr 22 04:55 README.txt
drwxr-xr-x@  8 USERNAME  wheel    272 Oct 14 12:24 bin
drwxr-xr-x@  3 USERNAME  wheel    102 Oct 14 12:24 boot
drwxr-xr-x@  5 USERNAME  wheel    170 Apr 22 04:55 conf
drwxr-xr-x@ 75 USERNAME  wheel   2550 Oct 14 12:24 lib

/Library/Maven-3.3.3/bin:
total 64
-rw-r--r--@ 1 USERNAME  wheel   230 Apr 22 04:58 m2.conf
-rwxr-xr-x@ 1 USERNAME  wheel  7075 Apr 22 04:58 mvn
-rw-r--r--@ 1 USERNAME  wheel  6007 Apr 22 04:58 mvn.cmd
-rwxr-xr-x@ 1 USERNAME  wheel  1796 Apr 22 04:58 mvnDebug
-rw-r--r--@ 1 USERNAME  wheel  1513 Apr 22 04:58 mvnDebug.cmd
-rwxr-xr-x@ 1 USERNAME  wheel  1843 Apr 22 04:58 mvnyjp

/Library/Maven-3.3.3/boot:
total 104
-rw-r--r--@ 1 USERNAME  wheel  52684 Aug 29  2014 plexus-classworlds-2.5.2.jar

/Library/Maven-3.3.3/conf:
total 32
drwxr-xr-x@ 3 USERNAME  wheel    102 Apr 22 04:55 logging
-rw-r--r--@ 1 USERNAME  wheel  10216 Apr 22 04:55 settings.xml
-rw-r--r--@ 1 USERNAME  wheel   3649 Apr 22 04:55 toolchains.xml

/Library/Maven-3.3.3/conf/logging:
total 8
-rw-r--r--@ 1 USERNAME  wheel  1126 Apr 22 04:55 simplelogger.properties

/Library/Maven-3.3.3/lib:
total 18656
-rw-r--r--@ 1 USERNAME  wheel   136324 Jan 29  2015 aether-api-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-api.license
-rw-r--r--@ 1 USERNAME  wheel    36745 Jan 29  2015 aether-connector-basic-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-connector-basic.license
-rw-r--r--@ 1 USERNAME  wheel   172998 Jan 29  2015 aether-impl-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-impl.license
-rw-r--r--@ 1 USERNAME  wheel    30705 Jan 29  2015 aether-spi-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-spi.license
-rw-r--r--@ 1 USERNAME  wheel    25355 Jan 29  2015 aether-transport-wagon-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-transport-wagon.license
-rw-r--r--@ 1 USERNAME  wheel   146876 Jan 29  2015 aether-util-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-util.license
-rw-r--r--@ 1 USERNAME  wheel     4467 May  7  2013 aopalliance-1.0.jar
-rw-r--r--@ 1 USERNAME  wheel    44908 May  7  2013 cdi-api-1.0.jar
-rw-r--r--@ 1 USERNAME  wheel    21837 Apr 22 04:58 cdi-api.license
-rw-r--r--@ 1 USERNAME  wheel    41123 May  7  2013 commons-cli-1.2.jar
-rw-r--r--@ 1 USERNAME  wheel   173587 May  7  2013 commons-io-2.2.jar
-rw-r--r--@ 1 USERNAME  wheel   284220 May  7  2013 commons-lang-2.6.jar
drwxr-xr-x@ 3 USERNAME  wheel      102 Apr 22 04:55 ext
-rw-r--r--@ 1 USERNAME  wheel  2256213 Nov  1  2014 guava-18.0.jar
-rw-r--r--@ 1 USERNAME  wheel     2497 May  7  2013 javax.inject-1.jar
-rw-r--r--@ 1 USERNAME  wheel   293671 Jul 24  2013 jsoup-1.7.2.jar
-rw-r--r--@ 1 USERNAME  wheel     3449 Apr 22 04:58 jsoup.license
-rw-r--r--@ 1 USERNAME  wheel     5848 May  7  2013 jsr250-api-1.0.jar
-rw-r--r--@ 1 USERNAME  wheel    18116 Apr 22 04:58 jsr250-api.license
-rw-r--r--@ 1 USERNAME  wheel    66349 Apr 22 04:57 maven-aether-provider-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-aether-provider.license
-rw-r--r--@ 1 USERNAME  wheel    55090 Apr 22 04:56 maven-artifact-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-artifact.license
-rw-r--r--@ 1 USERNAME  wheel    14964 Apr 22 04:56 maven-builder-support-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-builder-support.license
-rw-r--r--@ 1 USERNAME  wheel   286726 Apr 22 04:58 maven-compat-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-compat.license
-rw-r--r--@ 1 USERNAME  wheel   631881 Apr 22 04:57 maven-core-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-core.license
-rw-r--r--@ 1 USERNAME  wheel    86051 Apr 22 04:58 maven-embedder-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-embedder.license
-rw-r--r--@ 1 USERNAME  wheel   160817 Apr 22 04:56 maven-model-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel   176410 Apr 22 04:56 maven-model-builder-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-model-builder.license
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-model.license
-rw-r--r--@ 1 USERNAME  wheel    46099 Apr 22 04:56 maven-plugin-api-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-plugin-api.license
-rw-r--r--@ 1 USERNAME  wheel    25957 Apr 22 04:57 maven-repository-metadata-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-repository-metadata.license
-rw-r--r--@ 1 USERNAME  wheel    43032 Apr 22 04:57 maven-settings-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    43154 Apr 22 04:57 maven-settings-builder-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-settings-builder.license
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-settings.license
-rw-r--r--@ 1 USERNAME  wheel   375267 Feb 20  2015 org.eclipse.sisu.inject-0.3.0.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 org.eclipse.sisu.inject.license
-rw-r--r--@ 1 USERNAME  wheel   205404 Feb 20  2015 org.eclipse.sisu.plexus-0.3.0.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 org.eclipse.sisu.plexus.license
-rw-r--r--@ 1 USERNAME  wheel    13350 May  7  2013 plexus-cipher-1.7.jar
-rw-r--r--@ 1 USERNAME  wheel    21837 Apr 22 04:58 plexus-cipher.license
-rw-r--r--@ 1 USERNAME  wheel     4211 May  7  2013 plexus-component-annotations-1.5.5.jar
-rw-r--r--@ 1 USERNAME  wheel    62458 Oct 29  2014 plexus-interpolation-1.21.jar
-rw-r--r--@ 1 USERNAME  wheel    28555 May  7  2013 plexus-sec-dispatcher-1.3.jar
-rw-r--r--@ 1 USERNAME  wheel    21837 Apr 22 04:58 plexus-sec-dispatcher.license
-rw-r--r--@ 1 USERNAME  wheel   243128 Oct 29  2014 plexus-utils-3.0.20.jar
-rw-r--r--@ 1 USERNAME  wheel   399672 Feb 20  2015 sisu-guice-3.2.5-no_aop.jar
-rw-r--r--@ 1 USERNAME  wheel    26084 Jul 24  2013 slf4j-api-1.7.5.jar
-rw-r--r--@ 1 USERNAME  wheel    14853 Apr 22 04:58 slf4j-api.license
-rw-r--r--@ 1 USERNAME  wheel    10680 Aug 17  2013 slf4j-simple-1.7.5.jar
-rw-r--r--@ 1 USERNAME  wheel    14853 Apr 22 04:58 slf4j-simple.license
-rw-r--r--@ 1 USERNAME  wheel    11432 Apr 21 06:27 wagon-file-2.9.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 wagon-file.license
-rw-r--r--@ 1 USERNAME  wheel  2259073 Apr 21 06:32 wagon-http-2.9-shaded.jar
-rw-r--r--@ 1 USERNAME  wheel    11787 Apr 21 06:27 wagon-http-shared-2.9.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 wagon-http-shared.license
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 wagon-http.license
-rw-r--r--@ 1 USERNAME  wheel    53543 Apr 21 06:27 wagon-provider-api-2.9.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 wagon-provider-api.license

/Library/Maven-3.3.3/lib/ext:
total 8
-rw-r--r--@ 1 USERNAME  wheel  152 Apr 22 04:55 README.txt
</code>```

答: For absolute new people to maven, make sure you download the "Binary archives" from the Maven site, and not the "Source archives".</p>

Body:
I'd been stuck with this simple issue for an hour now. Maven was working fine last week, I don't know what went wrong it gives me this error. I tried all the ways to debug and all the solutions found in StackOverflow and many other places. I even tried replacing M2_HOME path with M3_HOME and MAVEN_HOME. Nothing worked. I'm on OS X. Below is the output of few maven commands. I'll be happy to provide more information

$ mvn
Error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

$ which mvn
/Library/Maven-3.3.3/bin/mvn

$ echo $M2_HOME
/Library/Maven-3.3.3

$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home

$ which java
/usr/bin/java

$ /Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home/bin/java -version
java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.75-b04, mixed mode)

$ echo $PATH
/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Tomcat/bin:/Library/Maven-3.3.3/bin

$ java -version
java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.75-b04, mixed mode)

$  ls -lR /Library/Maven-3.3.3
total 56
-rw-r--r--@  1 USERNAME  wheel  19091 Apr 22 04:58 LICENSE
-rw-r--r--@  1 USERNAME  wheel    182 Apr 22 04:58 NOTICE
-rw-r--r--@  1 USERNAME  wheel   2541 Apr 22 04:55 README.txt
drwxr-xr-x@  8 USERNAME  wheel    272 Oct 14 12:24 bin
drwxr-xr-x@  3 USERNAME  wheel    102 Oct 14 12:24 boot
drwxr-xr-x@  5 USERNAME  wheel    170 Apr 22 04:55 conf
drwxr-xr-x@ 75 USERNAME  wheel   2550 Oct 14 12:24 lib

/Library/Maven-3.3.3/bin:
total 64
-rw-r--r--@ 1 USERNAME  wheel   230 Apr 22 04:58 m2.conf
-rwxr-xr-x@ 1 USERNAME  wheel  7075 Apr 22 04:58 mvn
-rw-r--r--@ 1 USERNAME  wheel  6007 Apr 22 04:58 mvn.cmd
-rwxr-xr-x@ 1 USERNAME  wheel  1796 Apr 22 04:58 mvnDebug
-rw-r--r--@ 1 USERNAME  wheel  1513 Apr 22 04:58 mvnDebug.cmd
-rwxr-xr-x@ 1 USERNAME  wheel  1843 Apr 22 04:58 mvnyjp

/Library/Maven-3.3.3/boot:
total 104
-rw-r--r--@ 1 USERNAME  wheel  52684 Aug 29  2014 plexus-classworlds-2.5.2.jar

/Library/Maven-3.3.3/conf:
total 32
drwxr-xr-x@ 3 USERNAME  wheel    102 Apr 22 04:55 logging
-rw-r--r--@ 1 USERNAME  wheel  10216 Apr 22 04:55 settings.xml
-rw-r--r--@ 1 USERNAME  wheel   3649 Apr 22 04:55 toolchains.xml

/Library/Maven-3.3.3/conf/logging:
total 8
-rw-r--r--@ 1 USERNAME  wheel  1126 Apr 22 04:55 simplelogger.properties

/Library/Maven-3.3.3/lib:
total 18656
-rw-r--r--@ 1 USERNAME  wheel   136324 Jan 29  2015 aether-api-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-api.license
-rw-r--r--@ 1 USERNAME  wheel    36745 Jan 29  2015 aether-connector-basic-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-connector-basic.license
-rw-r--r--@ 1 USERNAME  wheel   172998 Jan 29  2015 aether-impl-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-impl.license
-rw-r--r--@ 1 USERNAME  wheel    30705 Jan 29  2015 aether-spi-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-spi.license
-rw-r--r--@ 1 USERNAME  wheel    25355 Jan 29  2015 aether-transport-wagon-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-transport-wagon.license
-rw-r--r--@ 1 USERNAME  wheel   146876 Jan 29  2015 aether-util-1.0.2.v20150114.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 aether-util.license
-rw-r--r--@ 1 USERNAME  wheel     4467 May  7  2013 aopalliance-1.0.jar
-rw-r--r--@ 1 USERNAME  wheel    44908 May  7  2013 cdi-api-1.0.jar
-rw-r--r--@ 1 USERNAME  wheel    21837 Apr 22 04:58 cdi-api.license
-rw-r--r--@ 1 USERNAME  wheel    41123 May  7  2013 commons-cli-1.2.jar
-rw-r--r--@ 1 USERNAME  wheel   173587 May  7  2013 commons-io-2.2.jar
-rw-r--r--@ 1 USERNAME  wheel   284220 May  7  2013 commons-lang-2.6.jar
drwxr-xr-x@ 3 USERNAME  wheel      102 Apr 22 04:55 ext
-rw-r--r--@ 1 USERNAME  wheel  2256213 Nov  1  2014 guava-18.0.jar
-rw-r--r--@ 1 USERNAME  wheel     2497 May  7  2013 javax.inject-1.jar
-rw-r--r--@ 1 USERNAME  wheel   293671 Jul 24  2013 jsoup-1.7.2.jar
-rw-r--r--@ 1 USERNAME  wheel     3449 Apr 22 04:58 jsoup.license
-rw-r--r--@ 1 USERNAME  wheel     5848 May  7  2013 jsr250-api-1.0.jar
-rw-r--r--@ 1 USERNAME  wheel    18116 Apr 22 04:58 jsr250-api.license
-rw-r--r--@ 1 USERNAME  wheel    66349 Apr 22 04:57 maven-aether-provider-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-aether-provider.license
-rw-r--r--@ 1 USERNAME  wheel    55090 Apr 22 04:56 maven-artifact-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-artifact.license
-rw-r--r--@ 1 USERNAME  wheel    14964 Apr 22 04:56 maven-builder-support-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-builder-support.license
-rw-r--r--@ 1 USERNAME  wheel   286726 Apr 22 04:58 maven-compat-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-compat.license
-rw-r--r--@ 1 USERNAME  wheel   631881 Apr 22 04:57 maven-core-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-core.license
-rw-r--r--@ 1 USERNAME  wheel    86051 Apr 22 04:58 maven-embedder-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-embedder.license
-rw-r--r--@ 1 USERNAME  wheel   160817 Apr 22 04:56 maven-model-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel   176410 Apr 22 04:56 maven-model-builder-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-model-builder.license
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-model.license
-rw-r--r--@ 1 USERNAME  wheel    46099 Apr 22 04:56 maven-plugin-api-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-plugin-api.license
-rw-r--r--@ 1 USERNAME  wheel    25957 Apr 22 04:57 maven-repository-metadata-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-repository-metadata.license
-rw-r--r--@ 1 USERNAME  wheel    43032 Apr 22 04:57 maven-settings-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    43154 Apr 22 04:57 maven-settings-builder-3.3.3.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-settings-builder.license
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 maven-settings.license
-rw-r--r--@ 1 USERNAME  wheel   375267 Feb 20  2015 org.eclipse.sisu.inject-0.3.0.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 org.eclipse.sisu.inject.license
-rw-r--r--@ 1 USERNAME  wheel   205404 Feb 20  2015 org.eclipse.sisu.plexus-0.3.0.jar
-rw-r--r--@ 1 USERNAME  wheel    12637 Apr 22 04:58 org.eclipse.sisu.plexus.license
-rw-r--r--@ 1 USERNAME  wheel    13350 May  7  2013 plexus-cipher-1.7.jar
-rw-r--r--@ 1 USERNAME  wheel    21837 Apr 22 04:58 plexus-cipher.license
-rw-r--r--@ 1 USERNAME  wheel     4211 May  7  2013 plexus-component-annotations-1.5.5.jar
-rw-r--r--@ 1 USERNAME  wheel    62458 Oct 29  2014 plexus-interpolation-1.21.jar
-rw-r--r--@ 1 USERNAME  wheel    28555 May  7  2013 plexus-sec-dispatcher-1.3.jar
-rw-r--r--@ 1 USERNAME  wheel    21837 Apr 22 04:58 plexus-sec-dispatcher.license
-rw-r--r--@ 1 USERNAME  wheel   243128 Oct 29  2014 plexus-utils-3.0.20.jar
-rw-r--r--@ 1 USERNAME  wheel   399672 Feb 20  2015 sisu-guice-3.2.5-no_aop.jar
-rw-r--r--@ 1 USERNAME  wheel    26084 Jul 24  2013 slf4j-api-1.7.5.jar
-rw-r--r--@ 1 USERNAME  wheel    14853 Apr 22 04:58 slf4j-api.license
-rw-r--r--@ 1 USERNAME  wheel    10680 Aug 17  2013 slf4j-simple-1.7.5.jar
-rw-r--r--@ 1 USERNAME  wheel    14853 Apr 22 04:58 slf4j-simple.license
-rw-r--r--@ 1 USERNAME  wheel    11432 Apr 21 06:27 wagon-file-2.9.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 wagon-file.license
-rw-r--r--@ 1 USERNAME  wheel  2259073 Apr 21 06:32 wagon-http-2.9-shaded.jar
-rw-r--r--@ 1 USERNAME  wheel    11787 Apr 21 06:27 wagon-http-shared-2.9.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 wagon-http-shared.license
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 wagon-http.license
-rw-r--r--@ 1 USERNAME  wheel    53543 Apr 21 06:27 wagon-provider-api-2.9.jar
-rw-r--r--@ 1 USERNAME  wheel    11358 Apr 22 04:58 wagon-provider-api.license

/Library/Maven-3.3.3/lib/ext:
total 8
-rw-r--r--@ 1 USERNAME  wheel  152 Apr 22 04:55 README.txt


问:
Add children objects to a parent only if they don't yet exist
I am busy developing an action for parent that should add a number of children given by the user input.

The children have 3 properties, and combining them, each child should always be unique.

I make use of Symfony and Doctrine and my basic parent class looks like this:

```<code>class Parent
{
    /**
     * @var Child[]|ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Child", mappedBy="parent")
     * @ORM\OrderBy({"dateCreated": "DESC"})
     */
    private $childs;

    /**
     * Add child
     *
     * @param \AppBundle\Entity\Child $child
     *
     * @return Parent
     */
    public function addChild(\AppBundle\Entity\Child $child)
    {
        $this->childs[] = $child;
        $child->setParent($this);
        return $this;
    }

    /**
     * Remove child
     *
     * @param \AppBundle\Entity\Child $child
     */
    public function removeChild(\AppBundle\Entity\Child $child)
    {
        $this->childs->removeElement($child);
    }

    /**
     * Get childs
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getChilds()
    {
        return $this->childs;
    }
}
</code>```

My child class look like this (again really basic):

```<code>class Child
{
    /**
     * @var int
     *
     * @ORM\Column(name="cupboard", type="integer")
     */
    private $cupboard;

    /**
     * @var int
     *
     * @ORM\Column(name="shelf", type="integer")
     */
    private $shelf;

    /**
     * @var int
     *
     * @ORM\Column(name="item", type="integer")
     */
    private $item;

    /**
     * @var Parent
     *
     * @ORM\ManyToOne(targetEntity="Parent", inversedBy="childs")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
     * })
     */
    private $parent;

    /**
     * Set cupboard
     *
     * @param string $cupboard
     *
     * @return Child
     */
    public function setCupboard($cupboard)
    {
        $this->cupboard = $cupboard;

        return $this;
    }

    /**
     * Get cupboard
     *
     * @return int
     */
    public function getCupboard()
    {
        return $this->cupboard;
    }

    /**
     * Set shelf
     *
     * @param string $shelf
     *
     * @return Child
     */
    public function setShelf($shelf)
    {
        $this->shelf = $shelf;

        return $this;
    }

    /**
     * Get shelf
     *
     * @return int
     */
    public function getShelf()
    {
        return $this->shelf;
    }

    /**
     * Set item
     *
     * @param string $item
     *
     * @return Child
     */
    public function setItem($item)
    {
        $this->item = $item;

        return $this;
    }

    /**
     * Get item
     *
     * @return int
     */
    public function getItem()
    {
        return $this->item;
    }

    /**
     * Set parent
     *
     * @param Parent $parent
     *
     * @return Child
     */
    public function setParent(Parent $parent)
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * Get parent
     *
     * @return Parent
     */
    public function getParent()
    {
        return $this->parent;
    }
}
</code>```

Then I have an action per parent object (kind of the same as an edit action) that has to create children for it. When I click the link (for the specific parent) a form is generated that has three input fields:

Cupboard

Shelf

Number of items

The user then has to specify with integers how many items he wants to add in what cupboard and what shelf. If the item (integer) already exist in that given cupboard on that given shelf it should not make it again, but the first next available integer should be used for item.

How can I make this as simple as possible? I understand I can use the addChild function from the Parent class, but I'm not sure how.

What I have tried so far is to create an array and group all items according to cupboard and shelf and then if the item does not exist in that array it should be created.

This is my code:

```<code>public function addItemAction(Request $request, $id = null){
    $parent = $this->admin->getSubject();

    if (!$parent) {
        throw new NotFoundHttpException(sprintf('Unable to find the object with id: %s', $id));
    }

    $em = $this->getDoctrine()->getManager();

    $form = $this->createForm(AddItemType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $kids = $popUnit->getChilds();
        $formParams = $request->request->get('add_item');

        $units = array();
        foreach ($kids as $kid) {
            $units[$kid->getCupboard()][$kid->getShelf()][$kid->getItem()] = $kid->getItem();
        }

        $givenShelf = $units[$formParams['cupboard']][$formParams['shelf']];

        for ($i = 1; $i <= $formParams['itemAmount']; $i++) {
            if (!in_array($i, $givenShelf)) {
                $child = new Child();
                $child->setParent($parent);
                $child->setCupboard($formParams['cupboard']);
                $child->setShelf($formParams['shelf']);
                $child->setItem($i);

                $em->persist($child);
                $em->flush();
            }
        }
        return new RedirectResponse($this->admin->generateUrl('show', array('id' => $parent->getId())));
    }

    return $this->render('AppBundle:Parent:add_childs.html.twig', array(
        'form' => $form->createView(),
        'parent' =>$parent,
    ));
}
</code>```

For extra information, this is how my form builder looks:

```<code>public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
        ->add('cupboard', NumberType::class)
        ->add('shelf', NumberType::class)
        ->add('itemAmount', NumberType::class, array('label' => 'Number of Items'))
    ;
}
</code>```

How can I make this action as simple as possible with the fact to make sure only unique items is added to a shelf in a cupboard for the parent. I can't change the properties nor the classes. I have to work with this. I don' want to use any other complex way like creating any listeners or other until functions.

I hope I've explained my situation well and I hope somebody can help me with some good feedback.

答:
You are correct that you can modify the addChild function of the Parent class like this:

```<code>    /**
     * Add child
     *
     * @param \AppBundle\Entity\Child $child
     *
     * @return Parent
     */
    public function addChild(Child $child)
    {
        if ( ! is_array($this->childs) || ! in_array($child, $this->childs)) {
            $this->childs[] = $child;
            $child->setParent($this);
        }
        return $this;
    }
</code>```

This conditional simply states that if there are no children yet, add the child or if the child is not already in the $this->childs array then add it.

Body:
I am busy developing an action for parent that should add a number of children given by the user input.

The children have 3 properties, and combining them, each child should always be unique.

I make use of Symfony and Doctrine and my basic parent class looks like this:

class Parent
{
    /**
     * @var Child[]|ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Child", mappedBy="parent")
     * @ORM\OrderBy({"dateCreated": "DESC"})
     */
    private $childs;

    /**
     * Add child
     *
     * @param \AppBundle\Entity\Child $child
     *
     * @return Parent
     */
    public function addChild(\AppBundle\Entity\Child $child)
    {
        $this->childs[] = $child;
        $child->setParent($this);
        return $this;
    }

    /**
     * Remove child
     *
     * @param \AppBundle\Entity\Child $child
     */
    public function removeChild(\AppBundle\Entity\Child $child)
    {
        $this->childs->removeElement($child);
    }

    /**
     * Get childs
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getChilds()
    {
        return $this->childs;
    }
}

My child class look like this (again really basic):

class Child
{
    /**
     * @var int
     *
     * @ORM\Column(name="cupboard", type="integer")
     */
    private $cupboard;

    /**
     * @var int
     *
     * @ORM\Column(name="shelf", type="integer")
     */
    private $shelf;

    /**
     * @var int
     *
     * @ORM\Column(name="item", type="integer")
     */
    private $item;

    /**
     * @var Parent
     *
     * @ORM\ManyToOne(targetEntity="Parent", inversedBy="childs")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
     * })
     */
    private $parent;

    /**
     * Set cupboard
     *
     * @param string $cupboard
     *
     * @return Child
     */
    public function setCupboard($cupboard)
    {
        $this->cupboard = $cupboard;

        return $this;
    }

    /**
     * Get cupboard
     *
     * @return int
     */
    public function getCupboard()
    {
        return $this->cupboard;
    }

    /**
     * Set shelf
     *
     * @param string $shelf
     *
     * @return Child
     */
    public function setShelf($shelf)
    {
        $this->shelf = $shelf;

        return $this;
    }

    /**
     * Get shelf
     *
     * @return int
     */
    public function getShelf()
    {
        return $this->shelf;
    }

    /**
     * Set item
     *
     * @param string $item
     *
     * @return Child
     */
    public function setItem($item)
    {
        $this->item = $item;

        return $this;
    }

    /**
     * Get item
     *
     * @return int
     */
    public function getItem()
    {
        return $this->item;
    }

    /**
     * Set parent
     *
     * @param Parent $parent
     *
     * @return Child
     */
    public function setParent(Parent $parent)
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * Get parent
     *
     * @return Parent
     */
    public function getParent()
    {
        return $this->parent;
    }
}

Then I have an action per parent object (kind of the same as an edit action) that has to create children for it. When I click the link (for the specific parent) a form is generated that has three input fields:

Cupboard

Shelf

Number of items

The user then has to specify with integers how many items he wants to add in what cupboard and what shelf. If the item (integer) already exist in that given cupboard on that given shelf it should not make it again, but the first next available integer should be used for item.

How can I make this as simple as possible? I understand I can use the addChild function from the Parent class, but I'm not sure how.

What I have tried so far is to create an array and group all items according to cupboard and shelf and then if the item does not exist in that array it should be created.

This is my code:

public function addItemAction(Request $request, $id = null){
    $parent = $this->admin->getSubject();

    if (!$parent) {
        throw new NotFoundHttpException(sprintf('Unable to find the object with id: %s', $id));
    }

    $em = $this->getDoctrine()->getManager();

    $form = $this->createForm(AddItemType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $kids = $popUnit->getChilds();
        $formParams = $request->request->get('add_item');

        $units = array();
        foreach ($kids as $kid) {
            $units[$kid->getCupboard()][$kid->getShelf()][$kid->getItem()] = $kid->getItem();
        }

        $givenShelf = $units[$formParams['cupboard']][$formParams['shelf']];

        for ($i = 1; $i <= $formParams['itemAmount']; $i++) {
            if (!in_array($i, $givenShelf)) {
                $child = new Child();
                $child->setParent($parent);
                $child->setCupboard($formParams['cupboard']);
                $child->setShelf($formParams['shelf']);
                $child->setItem($i);

                $em->persist($child);
                $em->flush();
            }
        }
        return new RedirectResponse($this->admin->generateUrl('show', array('id' => $parent->getId())));
    }

    return $this->render('AppBundle:Parent:add_childs.html.twig', array(
        'form' => $form->createView(),
        'parent' =>$parent,
    ));
}

For extra information, this is how my form builder looks:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
        ->add('cupboard', NumberType::class)
        ->add('shelf', NumberType::class)
        ->add('itemAmount', NumberType::class, array('label' => 'Number of Items'))
    ;
}

How can I make this action as simple as possible with the fact to make sure only unique items is added to a shelf in a cupboard for the parent. I can't change the properties nor the classes. I have to work with this. I don' want to use any other complex way like creating any listeners or other until functions.

I hope I've explained my situation well and I hope somebody can help me with some good feedback.

Body:
You are correct that you can modify the addChild function of the Parent class like this:

    /**
     * Add child
     *
     * @param \AppBundle\Entity\Child $child
     *
     * @return Parent
     */
    public function addChild(Child $child)
    {
        if ( ! is_array($this->childs) || ! in_array($child, $this->childs)) {
            $this->childs[] = $child;
            $child->setParent($this);
        }
        return $this;
    }

This conditional simply states that if there are no children yet, add the child or if the child is not already in the $this->childs array then add it.


问:
Perform arithmetic on a pointer returned using cudaMalloc() in host code
I am reading Cuda by examples book and I came across this sentence:

However, it is the responsibility of the programmer not to dereference the pointer
  returned by cudaMalloc() from code that executes on the host. Host code may
  pass this pointer around, perform arithmetic on it, or even cast it to a different
  type. But you cannot use it to read or write from memory.

Specifically, how would the 'perform an arithmetic on a pointer returned by cudaMalloc()' be done?

I tried running the following addition code with 2 additional lines before and after the kernel was called, but it had no effect on the output(which is 12 with or without those lines).

```<code>#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>

__global__
void add(int a, int b, int *c)
{
    *c += a + b;
}

int main()
{
    int *c, d;
    cudaMalloc((void**)&c, sizeof(int));
    *c = 10;
    add << <1,1>> > (5,7,c);
    *c += 5;
    cudaMemcpy(&d, c, sizeof(int), cudaMemcpyDeviceToHost);
    std::cout << d<<std::endl;
    return 0;
}
</code>```

I am a beginner and wold appreciate your help.

答:
pointer arithmetic is a concept associated with C and C++, it is not unique or specific to CUDA.

This is not an example of pointer arithmetic:

```<code> *c = 10;
</code>```

nor is this:

```<code> *c += 5;
</code>```

These are both modifications of what the pointer is pointing to, not the pointer itself.  Pointer arithmetic involves adjustments to the pointer value itself. (And by the way the code you have shown is illegal in CUDA - it is not legal to dereference ordinary device pointers in host code.  *c is an operation that dereferences the pointer c.  It is not the same as pointer arithmetic.)

Suppose I had a device memory allocation of 1024 int quantities:

```<code>cudaMalloc(&data, 1024 * sizeof(int));
</code>```

Now suppose I wanted to cause the first invocation of a CUDA kernel to start working on the beginning of the array, and a second invocation of a CUDA kernel to start working at the midpoint of the array, but otherwise perform the same work.

I might do something like this, and the second kernel invocation has an argument that involves pointer arithmetic:

```<code>kernel<<<...>>>(data, 512);
kernel<<<...>>>(data+512, 512);
</code>```

The data+512 argument involves pointer arithmetic.  This will pass a pointer to the kernel that points to the midpoint of the data array, rather than the beginning of the array.  If I wanted to carry this pointer around in host code, I could do:

```<code>int *datahalf = data+512;
</code>```

Body:
I am reading Cuda by examples book and I came across this sentence:

However, it is the responsibility of the programmer not to dereference the pointer
  returned by cudaMalloc() from code that executes on the host. Host code may
  pass this pointer around, perform arithmetic on it, or even cast it to a different
  type. But you cannot use it to read or write from memory.

Specifically, how would the 'perform an arithmetic on a pointer returned by cudaMalloc()' be done?

I tried running the following addition code with 2 additional lines before and after the kernel was called, but it had no effect on the output(which is 12 with or without those lines).

#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>

__global__
void add(int a, int b, int *c)
{
    *c += a + b;
}

int main()
{
    int *c, d;
    cudaMalloc((void**)&c, sizeof(int));
    *c = 10;
    add << <1,1>> > (5,7,c);
    *c += 5;
    cudaMemcpy(&d, c, sizeof(int), cudaMemcpyDeviceToHost);
    std::cout << d<<std::endl;
    return 0;
}

I am a beginner and wold appreciate your help.

Body:
pointer arithmetic is a concept associated with C and C++, it is not unique or specific to CUDA.

This is not an example of pointer arithmetic:

 *c = 10;

nor is this:

 *c += 5;

These are both modifications of what the pointer is pointing to, not the pointer itself.  Pointer arithmetic involves adjustments to the pointer value itself. (And by the way the code you have shown is illegal in CUDA - it is not legal to dereference ordinary device pointers in host code.  *c is an operation that dereferences the pointer c.  It is not the same as pointer arithmetic.)

Suppose I had a device memory allocation of 1024 int quantities:

cudaMalloc(&data, 1024 * sizeof(int));

Now suppose I wanted to cause the first invocation of a CUDA kernel to start working on the beginning of the array, and a second invocation of a CUDA kernel to start working at the midpoint of the array, but otherwise perform the same work.

I might do something like this, and the second kernel invocation has an argument that involves pointer arithmetic:

kernel<<<...>>>(data, 512);
kernel<<<...>>>(data+512, 512);

The data+512 argument involves pointer arithmetic.  This will pass a pointer to the kernel that points to the midpoint of the data array, rather than the beginning of the array.  If I wanted to carry this pointer around in host code, I could do:

int *datahalf = data+512;


问:
How to validate input using external javascript?
Im doing app based on phonegap. Im trying t validate my input with external javascript file. But getting error validateForm is not defined at HTMLFormElement.onclick. What's wrong with my code?

HTML

```<code><div data-role="page" id="page1">

    <div data-role="header">
        <a href="#pageMain" class="ui-btn ui-icon-back">Back</a>
        <h2>Add New</h2>
    </div>
    <!-- main -->
    <div data-role="main" class="ui-content">

        <form name="myform" onclick="return validateForm()" method="post">
        Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
        <button type="button" id="but_submit">Submit</button>
        </form>

    </div>
    <!-- footer -->
    <div data-role="footer">
        <h2>mine</h2>
    </div>

</div>
</code>```

Code from external javascript

```<code>function validateForm(){
var x = document.forms["myform"]["myname"].value;
if (x==null || x==""){
    alert("enter name");
    return false;
} else{
    return true;
}
}
</code>```

答:
You should use the onchange event because onclick triggers before having a chance to actually write something in the input.

This way you can deal with the validation after the value has changed and not wait for the form to be submitted.

Or if you want to validate just before submit you can use the onsubmit event like LGSon suggested.

function validateForm() {
  var x = document.forms["myform"]["myname"].value;
  if (x == null || x == "") {
    alert("enter name");
    return false;
  } else {
    console.log(true, x);
    return true;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="myform" onchange="return validateForm()" method="post">
  Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name">
  <button type="button" id="but_submit">Submit</button>
</form></code>```

Body:
Im doing app based on phonegap. Im trying t validate my input with external javascript file. But getting error validateForm is not defined at HTMLFormElement.onclick. What's wrong with my code?

HTML

        Back

Add New

        <form name="myform" onclick="return validateForm()" method="post">
        Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
        <button type="button" id="but_submit">Submit</button>
        </form>

mine

Code from external javascript

function validateForm(){
var x = document.forms["myform"]["myname"].value;
if (x==null || x==""){
    alert("enter name");
    return false;
} else{
    return true;
}
}

Body:
You should use the onchange event because onclick triggers before having a chance to actually write something in the input.

This way you can deal with the validation after the value has changed and not wait for the form to be submitted.

Or if you want to validate just before submit you can use the onsubmit event like LGSon suggested.

function validateForm() {
  var x = document.forms["myform"]["myname"].value;
  if (x == null || x == "") {
    alert("enter name");
    return false;
  } else {
    console.log(true, x);
    return true;
  }
}

<form name="myform" onchange="return validateForm()" method="post">
  Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name">
  <button type="button" id="but_submit">Submit</button>
</form>


问:
Want VBA in excel to read very large CSV and create output file of a small subset of the CSV
I have a csv file of 1.2 million records of text.  The alphanumeric fields are wrapped in quotation marks, the date/time or numeric fields are not.

For example
"Fred","Smith",01/07/1967,2,"7, The High Street","Anytown","Anycounty","LS1 7AA"

What I want do is write some VBA in Excel (more or less the only tool available to me that I am reasonably proficient in the use of) that reads the CSV record by record, performs a check (as it happens on the last field, the post code) and then outputs a small subset of the 1.2m records to a new output file.

I understand how to open the two files, read the record, do what I need to do with the data and write it out (I will just output the input record with a prefix denoting an exception type)

What I don't know is how to parse the CSV in VBA properly.  I can't do a simple text scan and search for commas as the text sometimes has commas in (hence why the text fields are text delimited)

Is there a fantastic command that would let me quicky get the data from the nth field in my record?

What I want is
    s_work = field(s_input_record,5) where 5 is the field number in my CSV....

Many thanks,
C

答:
Anything you can do a-row-at-a-time with vba in excel, you can do in access with vba; plus a lot more because it's a database rather than a spreadsheet. Is access unavailable to you?

It's a lot easier to deal with logical tables, records, and fields than logical worksheets, rows, and columns.

For input, why does the "/Data/Import External Data/Text/csv" not work? Is the input not truly portable csv?

OwnerDisplayName: C J

LastEditorDisplayName: eJames

OwnerDisplayName: le dorfier

LastEditorDisplayName: le dorfier


问:
Android shrink large image size
If there is a image on my phone that I want to send up to a server thats 1mb or higher I want to take that image and shrink it to a smaller size without messing with original image in anyway. I know how to get a from the phone and I also know how to send it up to a server, I just need to know how to make the image smaller because large files higher than 1mb are giving me issues.</p>

答:
From your original Bitmap, you can use createScaledBitmap(...)
However, the difficulty might be to open the large image in the first place.

Title: Android shrink large image size


答:
Use onsubmit, and by passing this from the event handler, you can use it instead for document.forms[....]

HTML

```<code><form name="myform" onsubmit="return validateForm(this)" method="post">
</code>```

Script

```<code>function validateForm(theform){
    var x = theform["myname"].value;
    if (x==null || x==""){
        alert("enter name");
        return false;
    } else{
        return true;
    }
}
</code>```

And by using event listeners it can be even more maintainable (and unobtrusive)

HTML

```<code><form name="myform" method="post">
</code>```

Script

```<code>window.addEventListener('load', function() {  /* fires when page been loaded */

    document.querySelector('[name="myform"]').addEventListener('submit', function(e) {
        var x = e.target["myname"].value;
        if (x==null || x==""){
            alert("enter name");
            return false;
        } else{
            return true;
        }
    });

});
</code>```

Title: How to validate input using external javascript?

Body:
Use onsubmit, and by passing this from the event handler, you can use it instead for document.forms[....]

HTML

<form name="myform" onsubmit="return validateForm(this)" method="post">

Script

function validateForm(theform){
    var x = theform["myname"].value;
    if (x==null || x==""){
        alert("enter name");
        return false;
    } else{
        return true;
    }
}

And by using event listeners it can be even more maintainable (and unobtrusive)

HTML

<form name="myform" method="post">

Script

window.addEventListener('load', function() {  /* fires when page been loaded */

    document.querySelector('[name="myform"]').addEventListener('submit', function(e) {
        var x = e.target["myname"].value;
        if (x==null || x==""){
            alert("enter name");
            return false;
        } else{
            return true;
        }
    });

});


问:
Scale / Redraw d3.js gridlines on zoom / drag
I just started using d3.js yesterday and i have some trouble getting my stuff done.

For now I created a chart with two y axes, each showing some values and an x axis showing dates.

On click on the values on the y axes, I display the corresponding horizontal grid lines.

My problem is, that when zooming in or out, or dragging, the gridlines (horizontal and vertical) don't scale correctly with the axes values, they just don't move at all.

I searched a lot this afternoon and found some examples how to do it, but none of them seem to work with the code i already have.

I presume, that the logic should be added to the zoom behavior but i'm not sure

```<code>// x axis gridlines
function make_x_gridlines() {
  return d3.axisBottom(x)
      .ticks(5)
}

// add the X gridlines
let xGrid = svg.append("g")
  .attr('class', 'grid')
  .attr("id", "grid")
  .attr("transform", "translate(0," + height + ")")
  .call(make_x_gridlines()
      .tickSize(-height)
      .tickFormat("")
  )

//zoom behavior
function zoomed() {
  .. some behavior ..

  //redraw gridlines here?

  .. some behavior ..
}
</code>```

Please see this fiddle for the whole thing.

I called the second y axis (right) zAxis even if it's not a z axis.

Help would really be greatly appreciated.

答:
The axes are working when you zoom. That's because, in the function zoomed() you are updating the scales.

So in order to make the grids zoom, you just need to update its scales too. Put this code inside the function zoomed() and it should work.

```<code>xGrid.call(
    d3.axisBottom(x)
        .scale(d3.event.transform.rescaleX(x))
        .ticks(5)
        .tickSize(-height)
        .tickFormat("")
    )
</code>```

Now you just need to replicate this scale update to all other grids. Sorry that I couldn't give you a complete answer, but I don't have much time right now.

Now, in my opinion, you should not have the function make_gridlines() because it is really simple, and when you're working on lots of updates on different places it confuses me.

So, instead of calling make_gridlines() you call d3.axisBottom(x).ticks(5).

(Note that I'm new to d3 and js, so I'm recommending this based on my little experience and knowledge)

Body:
I just started using d3.js yesterday and i have some trouble getting my stuff done.

For now I created a chart with two y axes, each showing some values and an x axis showing dates.

On click on the values on the y axes, I display the corresponding horizontal grid lines.

My problem is, that when zooming in or out, or dragging, the gridlines (horizontal and vertical) don't scale correctly with the axes values, they just don't move at all.

I searched a lot this afternoon and found some examples how to do it, but none of them seem to work with the code i already have.

I presume, that the logic should be added to the zoom behavior but i'm not sure

// x axis gridlines
function make_x_gridlines() {
  return d3.axisBottom(x)
      .ticks(5)
}

// add the X gridlines
let xGrid = svg.append("g")
  .attr('class', 'grid')
  .attr("id", "grid")
  .attr("transform", "translate(0," + height + ")")
  .call(make_x_gridlines()
      .tickSize(-height)
      .tickFormat("")
  )

//zoom behavior
function zoomed() {
  .. some behavior ..

  //redraw gridlines here?

  .. some behavior ..
}

Please see this fiddle for the whole thing.

I called the second y axis (right) zAxis even if it's not a z axis.

Help would really be greatly appreciated.

Body:
The axes are working when you zoom. That's because, in the function zoomed() you are updating the scales.

So in order to make the grids zoom, you just need to update its scales too. Put this code inside the function zoomed() and it should work.

xGrid.call(
    d3.axisBottom(x)
        .scale(d3.event.transform.rescaleX(x))
        .ticks(5)
        .tickSize(-height)
        .tickFormat("")
    )

Now you just need to replicate this scale update to all other grids. Sorry that I couldn't give you a complete answer, but I don't have much time right now.

Now, in my opinion, you should not have the function make_gridlines() because it is really simple, and when you're working on lots of updates on different places it confuses me.

So, instead of calling make_gridlines() you call d3.axisBottom(x).ticks(5).

(Note that I'm new to d3 and js, so I'm recommending this based on my little experience and knowledge)


问:
How to convert a 2D array to a value object in ruby
I have a 2D array:

```<code>a = [["john doe", "01/03/2017", "01/04/2017", "event"], ["jane doe", "01/05/2017", "01/06/2017", "event"]...]
</code>```

I would like to convert it to a value object in ruby. I found how to do it with a hash Ruby / Replace value in array of hash in the second answer of this question but not a 2D array. I would like to assign the value at a[0][0] to an attribute named "name", a[0][1] to "date1", a[0][2] to "date2" and a[0][3] to "event".

This is something like what I'd like to accomplish although it is not complete and I dont know how to assign multiple indexes to the different attributes in one loop:

```<code>class Schedule_info
   arrt_accessor :name, :date1, :date2, :event

   def initialize arr
       #I would like this loop to contain all 4 attr assignments
       arr.each {|i| instance_variable_set(:name, i[0])}
</code>```

答:
You can't store the key value pairs in array index. Either you need to just remember that first index of array is gonna have "name" and assign a[0][0] = "foo" or just use array of hashes for the key value functionality you want to have

```<code>2.3.0 :006 > a = []
 => []
2.3.0 :007 > hash1 = {name: "hash1name", date: "hash1date", event: "hash1event"}
 => {:name=>"hash1name", :date=>"hash1date", :event=>"hash1event"}
2.3.0 :008 > a << hash1
 => [{:name=>"hash1name", :date=>"hash1date", :event=>"hash1event"}]
2.3.0 :009 > hash2 = {name: "hash2name", date: "hash2date", event: "hash2event"}
 => {:name=>"hash2name", :date=>"hash2date", :event=>"hash2event"}
2.3.0 :010 > a << hash2
 => [{:name=>"hash1name", :date=>"hash1date", :event=>"hash1event"}, {:name=>"hash2name", :date=>"hash2date", :event=>"hash2event"}]
</code>```

Body:
I have a 2D array:

a = [["john doe", "01/03/2017", "01/04/2017", "event"], ["jane doe", "01/05/2017", "01/06/2017", "event"]...]

I would like to convert it to a value object in ruby. I found how to do it with a hash Ruby / Replace value in array of hash in the second answer of this question but not a 2D array. I would like to assign the value at a[0][0] to an attribute named "name", a[0][1] to "date1", a[0][2] to "date2" and a[0][3] to "event".

This is something like what I'd like to accomplish although it is not complete and I dont know how to assign multiple indexes to the different attributes in one loop:

class Schedule_info
   arrt_accessor :name, :date1, :date2, :event

   def initialize arr
       #I would like this loop to contain all 4 attr assignments
       arr.each {|i| instance_variable_set(:name, i[0])}

Body:
You can't store the key value pairs in array index. Either you need to just remember that first index of array is gonna have "name" and assign a[0][0] = "foo" or just use array of hashes for the key value functionality you want to have

2.3.0 :006 > a = []
 => []
2.3.0 :007 > hash1 = {name: "hash1name", date: "hash1date", event: "hash1event"}
 => {:name=>"hash1name", :date=>"hash1date", :event=>"hash1event"}
2.3.0 :008 > a << hash1
 => [{:name=>"hash1name", :date=>"hash1date", :event=>"hash1event"}]
2.3.0 :009 > hash2 = {name: "hash2name", date: "hash2date", event: "hash2event"}
 => {:name=>"hash2name", :date=>"hash2date", :event=>"hash2event"}
2.3.0 :010 > a << hash2
 => [{:name=>"hash1name", :date=>"hash1date", :event=>"hash1event"}, {:name=>"hash2name", :date=>"hash2date", :event=>"hash2event"}]


问:
Doing a calculation while querying the database in Django
I want to obtain the objects of my Project model for whose ratio of the values in the two fields raised_amount and total_amount is less than 0.2.
I have been trying this
    project_list = Project.objects.filter((raised_amount)/(total_amount)<0.2)

I know this is the wrong way. Please help me do it the right way

答:
Try something like</p>

```<code>from django.db.models import F
Project.objects.annotate(x=F('raised_amount') / F('total_amount')).filter(x__lt=0.2)
</code>```

Body:
Try something like

from django.db.models import F
Project.objects.annotate(x=F('raised_amount') / F('total_amount')).filter(x__lt=0.2)


问:
Using annotations to flow information from model building to migrations in EF Core
For EF Core. Related to this issue on the repo.

How do I "flow information" from the model building to the migrations stages in EF Core?

That issue was discussed among the authors who obviously fully understand the internals of EF Core, but I don't. How do I implement this?

答:
First, flow your annotation from the model into the migration operations. Do this by overriding the provider-specific IMigrationsAnnotationProvider service.

```<code>class MyMigrationsAnnotationProvider : SqlServerMigrationsAnnotationProvider
{
    public override IEnumerable<IAnnotation> For(IProperty property)
        => base.For(property)
            .Concat(property.GetAnnotations().Where(a => a.Name == "MyAnnotation"));
}
</code>```

Second, use the annotation in the provider-specific IMigrationsSqlGenerator service to generate DDL.

```<code>class MyMigrationsSqlGenerator : SqlServerMigrationsSqlGenerator
{
    protected override void Generate(
        AddColumnOperation operation,
        IModel model,
        MigrationCommandListBuilder builder)
    {
        var myAnnotation = operation.FindAnnotation("MyAnnotation");
        if (myAnnotation != null)
        {
            // TODO: Add custom SQL using builder
        }
    }
}
</code>```

Finally, configure your context to use your services.

```<code>optionsBuilder.UseSqlServer(connectionString)
   .ReplaceService<SqlServerMigrationsAnnotationProvider, MyMigrationsAnnotationProvider>()
   .ReplaceService<SqlServerMigrationsSqlGenerator, MyMigrationsSqlGenerator>();
</code>```

Body:
First, flow your annotation from the model into the migration operations. Do this by overriding the provider-specific IMigrationsAnnotationProvider service.

class MyMigrationsAnnotationProvider : SqlServerMigrationsAnnotationProvider
{
    public override IEnumerable<IAnnotation> For(IProperty property)
        => base.For(property)
            .Concat(property.GetAnnotations().Where(a => a.Name == "MyAnnotation"));
}

Second, use the annotation in the provider-specific IMigrationsSqlGenerator service to generate DDL.

class MyMigrationsSqlGenerator : SqlServerMigrationsSqlGenerator
{
    protected override void Generate(
        AddColumnOperation operation,
        IModel model,
        MigrationCommandListBuilder builder)
    {
        var myAnnotation = operation.FindAnnotation("MyAnnotation");
        if (myAnnotation != null)
        {
            // TODO: Add custom SQL using builder
        }
    }
}

Finally, configure your context to use your services.

optionsBuilder.UseSqlServer(connectionString)
   .ReplaceService<SqlServerMigrationsAnnotationProvider, MyMigrationsAnnotationProvider>()
   .ReplaceService<SqlServerMigrationsSqlGenerator, MyMigrationsSqlGenerator>();


问:
Finding the dominant color of an image in an Android @drawable
You can understand why I'm trying to find the dominant color in an image if you use Windows 7.  When your mouse over a program in the taskbar, the background of that particular program changes based on the most dominant color in the icon.  I have noticed this technique used in other programs as well, but can't remember them off the top of my head.

I can see this being helpful in a number of UI techniques that I'm using to develop an application, and I was wondering how finding the most common color would be achieved from an Android drawable resource.

答:
None of the other answers did the job for me, and I didn't rule out the cause of the problem.

This is what I ended up using:

```<code>public static int getDominantColor(Bitmap bitmap) {
    if (bitmap == null) {
        return Color.TRANSPARENT;
    }
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int size = width * height;
    int pixels[] = new int[size];
    //Bitmap bitmap2 = bitmap.copy(Bitmap.Config.ARGB_4444, false);
    bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
    int color;
    int r = 0;
    int g = 0;
    int b = 0;
    int a;
    int count = 0;
    for (int i = 0; i < pixels.length; i++) {
        color = pixels[i];
        a = Color.alpha(color);
        if (a > 0) {
            r += Color.red(color);
            g += Color.green(color);
            b += Color.blue(color);
            count++;
        }
    }
    r /= count;
    g /= count;
    b /= count;
    r = (r << 16) & 0x00FF0000;
    g = (g << 8) & 0x0000FF00;
    b = b & 0x000000FF;
    color = 0xFF000000 | r | g | b;
    return color;
}
</code>```

Body:
None of the other answers did the job for me, and I didn't rule out the cause of the problem.

This is what I ended up using:

public static int getDominantColor(Bitmap bitmap) {
    if (bitmap == null) {
        return Color.TRANSPARENT;
    }
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int size = width * height;
    int pixels[] = new int[size];
    //Bitmap bitmap2 = bitmap.copy(Bitmap.Config.ARGB_4444, false);
    bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
    int color;
    int r = 0;
    int g = 0;
    int b = 0;
    int a;
    int count = 0;
    for (int i = 0; i < pixels.length; i++) {
        color = pixels[i];
        a = Color.alpha(color);
        if (a > 0) {
            r += Color.red(color);
            g += Color.green(color);
            b += Color.blue(color);
            count++;
        }
    }
    r /= count;
    g /= count;
    b /= count;
    r = (r << 16) & 0x00FF0000;
    g = (g << 8) & 0x0000FF00;
    b = b & 0x000000FF;
    color = 0xFF000000 | r | g | b;
    return color;
}


问:
WPF: message box with checkbox added
In WPF I am looking for a "do not show again" checkbox on my messagebox popup.

Does anyone know where I can get such a control or maybe how to copy the style of the regular WPF messagebox so I can create my own?

Thanks

答:
Take a look at the Dialog Boxes Overview.  The overview covers Message Boxes, Common Dialog Boxes, and Custom Dialog Boxes. In your case you'll want to create a simple Custom Dialog Box that includes a message, a checkbox, and however many buttons you need.

Basically you need to define a new code-behind file that includes your TextBlock, CheckBox, and Buttons in a panel object, and you need to extend Window. In your code-behind file you implement any necessary logic to implement the user's choice, and you return this result to the object containing the custom dialog box.

Make sure to pay special attention to this line of code when creating your custom dialog box:

```<code>// Open the dialog box modally
messageBox.ShowDialog();
</code>```

The call to ShowDialog() will ensure that the user must take action against your dialog box before moving on to other parts of your application.

Title: WPF: message box with checkbox added

Body:
Take a look at the Dialog Boxes Overview.  The overview covers Message Boxes, Common Dialog Boxes, and Custom Dialog Boxes. In your case you'll want to create a simple Custom Dialog Box that includes a message, a checkbox, and however many buttons you need.

Basically you need to define a new code-behind file that includes your TextBlock, CheckBox, and Buttons in a panel object, and you need to extend Window. In your code-behind file you implement any necessary logic to implement the user's choice, and you return this result to the object containing the custom dialog box.

Make sure to pay special attention to this line of code when creating your custom dialog box:

// Open the dialog box modally
messageBox.ShowDialog();

The call to ShowDialog() will ensure that the user must take action against your dialog box before moving on to other parts of your application.


问:
Using a Shiny html application within a Qt application
Just a general question: is it possible to display & interact with a Shiny-generated html page with charts, dropdown menus and other elements, within a Qt application? I've browsed at some documentation and videos for QtWebKit and WebView, and while mentions of basic html display are covered, I'm just wondering about more-involved uses.

The R code which I have on a VPS displays the Shiny app in html already, and is accessed via direct URL.

答:
It depends on what you mean by "interact": who does the interaction?

A human user interacts directly with the page - that's the easy case. Use the web view.

Qt bundles a complete Chromium web engine. Anything Chrome can do, so can Qt's web view. As long as your page works in the Chrome version that uses the same Chromium version as Qt does, it will be fine in Qt's web view.

Your code interacts with the page - that's more involved. You'll have to add a remote control channel working on top of websockets to interact with the page. It could be as simple as the Qt application sending javascript to execute on the page, and receiving back the json-serialized results. That gives you the most power at the lowest implementation cost (a few dozen lines of javascript and C++).


问:
mingw + gcc + gnu + -ggdb -g3 but debugging failed "no source info"
Under Windows with same i686-w64-mingw32-gcc I have two C++ projects. Both with "-ggdb -g3 -O0" - the smaller project I can debug in Eclipse but the larger one says "No source available". Both projects with " -static-libgcc -static-libstdc++"

I am failing to figure out what breaks it :(

Smaller project happy gdb:

Larger prodject not happy gdb:

Good makefile:
https://github.com/rusefi/rusefi/blob/temp_branch/unit_tests/Makefile
https://github.com/rusefi/rusefi/blob/temp_branch/unit_tests/rules.mk

Bad makefile:
https://github.com/rusefi/rusefi/blob/temp_branch/win32_functional_tests/Makefile
https://github.com/rusefi/rusefi/blob/temp_branch/win32_functional_tests/rules.mk

Both projects show symbols with objdump.exe  --syms:

Good project symbols:
https://github.com/rusefi/rusefi/blob/temp_branch/unit_tests/symbols

Bad project symbols:
https://github.com/rusefi/rusefi/blob/temp_branch/win32_functional_tests/symbols

I would like to be able to debug both projects. What am I doing wrong? :(

答:
Update: I've found a work-around:

i686-w64-mingw32-gcc (32bit embedded into Cygwin64) does not work with gdb from cygwin64

but if everything is base 32 bit cygwin things work as expected! Just to reiterate - one project works with 32 compiler from cygwin64 while another one does not, so something must be different - but since I have a workaround I am good.


问:
Creating Unfuddle SVN repositories from QT Creator?
I am writing an application that creates a default file structure for my projects so I don't have to create the folders for every new project. All the work to create these folders is done, however there are still some things that I'd like to improve.

Right now I create a new repository in Unfuddle first, check it out, run my application, then manually commit the newly created folders.

Is there a way to create a repository using the Unfuddle API INSIDE Qt Creator? This way all the work can be done from inside the application, saving some more time. If there is, how would I get started doing this? Any tips are welcome.

答: Solved the problem after following: https://unfuddle.com/stack/docs/api/repositories/.</p>


问:
How to get notified when a user leaves home in the SetSDK?
I'm using the SetSDK to show users the available bike share count at their nearby station whenever they leave their home. I'm following the example available in the pod documentation but am not getting the notification. Here is my code,

```<code>SetSDK.instance.onDeparture(.home) { notification in
    // below is my code using the notification
    let bikeStationCount = getAvailableBikes(stationsNear: notification.location)
    showNotification(withCount: bikeStationCount.count, atStation: bikeStationCount.station)
}
</code>```

But I'm not getting my app to show any notification, any idea what is wrong?

答:
It looks like your code is correct. The only thing to keep in mind is that the SetSDK will learn the user's home over time, with most users it usually takes 1-2 days for it to have enough certainty to call a place Home.

Have you had a chance to let the SDK learn long enough that it is giving you notifications now?

Hey, cool use-case!

Body:
I'm using the SetSDK to show users the available bike share count at their nearby station whenever they leave their home. I'm following the example available in the pod documentation but am not getting the notification. Here is my code,

SetSDK.instance.onDeparture(.home) { notification in
    // below is my code using the notification
    let bikeStationCount = getAvailableBikes(stationsNear: notification.location)
    showNotification(withCount: bikeStationCount.count, atStation: bikeStationCount.station)
}

But I'm not getting my app to show any notification, any idea what is wrong?


问:
Is it possible to generate step by step report in Jenkins for selenium execution
I want to know is there any way of generating a step by step execution report in Jenkins. Suppose if I'm executing my Selenium tests and it gets failed at a particular step, then the report should display at which step it got failed. Is there any way in Jenkins to do this?

Thanks

答: you can use build automation script reporting features, example... run Selinium tests in Jenkins  using Ant or Maven or Gradle and generate detailed reports.</p>


问:
Looking if the package exist before the getLaunchIntentForPackage
I'm making a special launcher : this launcher show you some determinate apps in your tablet.

For example (sudoku) :

```<code>button_sudoku.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent();
            PackageManager manager = getPackageManager();
            i = manager.getLaunchIntentForPackage("com.coolandroidappzfree.freesudoku");
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            startActivity(i);
        }
    });
</code>```

But imagine if the app com.coolandroidappzfree.freesudoku is not on the tablet ? So the app crash!

I would like to verify before if the app is on the tablett and after the click, install the app if not.

It is possible ?

Thanks

答:
I found the solution.
This function launch the appPackageName if is installed in the device or launch the PlayStore if not :</p>

```<code>public static boolean launchPackage(Context context, String appPackageName){

        List<ApplicationInfo> packages;
        PackageManager pm;

        pm = context.getPackageManager();
        packages = pm.getInstalledApplications(0);
        for (ApplicationInfo packageInfo : packages)
        {
            if(packageInfo.packageName.equals(appPackageName))
            {
                Intent i = new Intent();
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                PackageManager manager = context.getPackageManager();
                i = manager.getLaunchIntentForPackage(appPackageName);
                i.addCategory(Intent.CATEGORY_LAUNCHER);
                context.startActivity(i);
                return true;
            }
        }

        Intent i2 = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName));
        i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i2);

        return false;
    }
</code>```

Body:
I'm making a special launcher : this launcher show you some determinate apps in your tablet.

For example (sudoku) :

button_sudoku.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent();
            PackageManager manager = getPackageManager();
            i = manager.getLaunchIntentForPackage("com.coolandroidappzfree.freesudoku");
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            startActivity(i);
        }
    });

But imagine if the app com.coolandroidappzfree.freesudoku is not on the tablet ? So the app crash!

I would like to verify before if the app is on the tablett and after the click, install the app if not.

It is possible ?

Thanks

Body:
I found the solution.
This function launch the appPackageName if is installed in the device or launch the PlayStore if not :

public static boolean launchPackage(Context context, String appPackageName){

        List<ApplicationInfo> packages;
        PackageManager pm;

        pm = context.getPackageManager();
        packages = pm.getInstalledApplications(0);
        for (ApplicationInfo packageInfo : packages)
        {
            if(packageInfo.packageName.equals(appPackageName))
            {
                Intent i = new Intent();
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                PackageManager manager = context.getPackageManager();
                i = manager.getLaunchIntentForPackage(appPackageName);
                i.addCategory(Intent.CATEGORY_LAUNCHER);
                context.startActivity(i);
                return true;
            }
        }

        Intent i2 = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName));
        i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i2);

        return false;
    }


问:
How to extend method run in TimerTask . Must accept string parameter
I have this code

```<code>private void startActionPerformed(java.awt.event.ActionEvent evt) {
    this.start.setBackground(Color.green);
    this.stop.setBackground(Color.lightGray);
    if (!stopped) {
        timer.cancel();
    }
    stopped = false;
    stato.setText("Avviato");
    timer = new Timer();
    if(giacRitardo>0)
        timer.schedule(S.run("argiacenze"), giacRitardo, giacRitardo);//parti dopo x secondi e itera ogni x secondi
    if(cliRitardo>0)
        timer.schedule(S.run("arclienti"), cliRitardo, cliRitardo);//parti dopo x secondi e itera ogni x secondi
</code>```

// some other code

and

```<code>class TaskSchedulato extends TimerTask {

    @Override
    public void run() {
        redirectSystemStreams();
        DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        URL sito = null;
        try {
            sito = new URL(sUrl + "?aggiornamento=arlingue");
        } catch (MalformedURLException ex) {
            System.out.println("Indirizzo del sito mal formato o inesistente");
        }
        URLConnection yc = null;
        try {
            yc = sito.openConnection();
        } catch (IOException ex) {
            System.out.println("Errore di connessione _ ");
        }
        BufferedReader in = null;
        try {
            in = new BufferedReader(
                    new InputStreamReader(
                            yc.getInputStream()));
        } catch (IOException ex) {
            Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
        }
        String inputLine;
        try {
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        } catch (IOException ex) {
            Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
            dataErrore = new Date();
            System.out.println(sdf.format(dataErrore));
            System.out.println("Errore di connessione: " + dataErrore);
        }
        try {
            in.close();
        } catch (IOException ex) {
            Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
</code>```

and

```<code>TaskSchedulato S = new TaskSchedulato();
</code>```

I need to extend the method run above, so that i can pass a string parameter to it.
How can a do it.
I'm almost a newbye in java. So, please forgive me for the inexperience.

Actually I receive the error:
no suitable method found for run(String)
  method TimerTask.run() is not applicable
(actual and formal argument lists differ in length)
method MainForm.TaskSchedulato.run() is not applicable
(actual and formal argument lists differ in length)

Thank you in advance

答:
This can be easily achieved with method overloading.

In short, method overloading is a language feature that allows to declare multiple methods with the same name, but different parameters.

Applied to your problem, instead of overriding the parent's run() method, just declare another run() method like this:

```<code>public void run(String someInput) {
    /* ... */
}
</code>```

Of course, you can call run() from within run(String) if that makes sense in your program:

```<code>public void run(String someInput) {
    /* Do something with someInput */
    run(); // Hand over to parent's run() method
    /* Maybe do some other stuff */
}
</code>```

Depending on what you are trying to do, you might want to use both, method overloading as well as overriding. Some more context would be required to give more specific advice.

Body:
I have this code

private void startActionPerformed(java.awt.event.ActionEvent evt) {
    this.start.setBackground(Color.green);
    this.stop.setBackground(Color.lightGray);
    if (!stopped) {
        timer.cancel();
    }
    stopped = false;
    stato.setText("Avviato");
    timer = new Timer();
    if(giacRitardo>0)
        timer.schedule(S.run("argiacenze"), giacRitardo, giacRitardo);//parti dopo x secondi e itera ogni x secondi
    if(cliRitardo>0)
        timer.schedule(S.run("arclienti"), cliRitardo, cliRitardo);//parti dopo x secondi e itera ogni x secondi

// some other code

and

class TaskSchedulato extends TimerTask {

    @Override
    public void run() {
        redirectSystemStreams();
        DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        URL sito = null;
        try {
            sito = new URL(sUrl + "?aggiornamento=arlingue");
        } catch (MalformedURLException ex) {
            System.out.println("Indirizzo del sito mal formato o inesistente");
        }
        URLConnection yc = null;
        try {
            yc = sito.openConnection();
        } catch (IOException ex) {
            System.out.println("Errore di connessione _ ");
        }
        BufferedReader in = null;
        try {
            in = new BufferedReader(
                    new InputStreamReader(
                            yc.getInputStream()));
        } catch (IOException ex) {
            Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
        }
        String inputLine;
        try {
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        } catch (IOException ex) {
            Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
            dataErrore = new Date();
            System.out.println(sdf.format(dataErrore));
            System.out.println("Errore di connessione: " + dataErrore);
        }
        try {
            in.close();
        } catch (IOException ex) {
            Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

and

TaskSchedulato S = new TaskSchedulato();

I need to extend the method run above, so that i can pass a string parameter to it.
How can a do it.
I'm almost a newbye in java. So, please forgive me for the inexperience.

Actually I receive the error:
no suitable method found for run(String)
  method TimerTask.run() is not applicable
(actual and formal argument lists differ in length)
method MainForm.TaskSchedulato.run() is not applicable
(actual and formal argument lists differ in length)

Thank you in advance

Body:
This can be easily achieved with method overloading.

In short, method overloading is a language feature that allows to declare multiple methods with the same name, but different parameters.

Applied to your problem, instead of overriding the parent's run() method, just declare another run() method like this:

public void run(String someInput) {
    /* ... */
}

Of course, you can call run() from within run(String) if that makes sense in your program:

public void run(String someInput) {
    /* Do something with someInput */
    run(); // Hand over to parent's run() method
    /* Maybe do some other stuff */
}

Depending on what you are trying to do, you might want to use both, method overloading as well as overriding. Some more context would be required to give more specific advice.


问:
QTreeWidgetItem hide child checkboxes but not parent checkboxes
I have a QTreeWidget with two levels.  Parent level is first and child level underneath.  I want the parent level to contain checkboxes, but I want the children to have no checkboxes.  In the following example, every QTreeWidgetItem shows a checkbox.  If I remove "child.setCheckState(0, Qt.Unchecked)" then ALL checkboxes disappear, not just the child checkboxes.

How can I hide the child checkboxes, but not the parent checkboxes?

```<code>from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

def main():
    app        = QApplication (sys.argv)
    tree       = QTreeWidget ()
    headerItem = QTreeWidgetItem()
    item       = QTreeWidgetItem()

    for i in xrange(2):
        parent = QTreeWidgetItem(tree)
        parent.setText(0, "Parent {}".format(i))
        parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
        parent.setExpanded(True)
        parent.setCheckState(0, Qt.Unchecked)
        for x in xrange(3):
            child = QTreeWidgetItem(parent)
            child.setFlags(child.flags() & ~(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable))
            child.setText(0, "Child {}".format(x))
            #child.setCheckState(0, Qt.Unchecked)
    tree.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

答:
You should remove the the flag ItemIsUserChechable and ItemIsSelectable from your child flags instead of adding them:

```<code>child.setFlags(child.flags() & ~(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable))
</code>```

I would also expect that you shouldn't set the checkState of the child, but that of the parent.
See the python documentation for more information about binary operations.

Body:
I have a QTreeWidget with two levels.  Parent level is first and child level underneath.  I want the parent level to contain checkboxes, but I want the children to have no checkboxes.  In the following example, every QTreeWidgetItem shows a checkbox.  If I remove "child.setCheckState(0, Qt.Unchecked)" then ALL checkboxes disappear, not just the child checkboxes.

How can I hide the child checkboxes, but not the parent checkboxes?

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

def main():
    app        = QApplication (sys.argv)
    tree       = QTreeWidget ()
    headerItem = QTreeWidgetItem()
    item       = QTreeWidgetItem()

    for i in xrange(2):
        parent = QTreeWidgetItem(tree)
        parent.setText(0, "Parent {}".format(i))
        parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
        parent.setExpanded(True)
        parent.setCheckState(0, Qt.Unchecked)
        for x in xrange(3):
            child = QTreeWidgetItem(parent)
            child.setFlags(child.flags() & ~(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable))
            child.setText(0, "Child {}".format(x))
            #child.setCheckState(0, Qt.Unchecked)
    tree.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Body:
You should remove the the flag ItemIsUserChechable and ItemIsSelectable from your child flags instead of adding them:

child.setFlags(child.flags() & ~(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable))

I would also expect that you shouldn't set the checkState of the child, but that of the parent.
See the python documentation for more information about binary operations.


问:
JVM Hot Swap best practices while debugging
I am spending a lot of time in the debugger while maintaining a legacy project.  The start time for the app is very long, I cannot afford to wait for the program to restart every time I test new changes, so I'm making extensive use of JVM's hot-swap capabilities. The problem I am facing is there is a limited range of operations that the hot swap allows me to perform.  I can modify the body of a method but cannot add additional methods.  Are there any best practices available for using the hot swap capabilities to the maximum?  The ability to modify the body of a method is great but is it somehow possible to get around some of the existing limitations (for example, to be able to add new fields).  I know it's explicitly not supported but maybe it's possible to do it indirectly somehow</p>

答: I've used JRebel for this with some success.</p>


问:
Round numbers to 50 thousands in Python
How can I round a number to the nearest up or down 50 thousand?

I want to round this 542756 to this 550000, or round this 521405 to this 500000. Considering that the number to be rounded is a variable x.

I tried this:

```<code>import math

def roundup(x):
    return int(math.ceil(x / 50000.0)) * 50000
</code>```

But it only round up and I need to round both up or down.

I also tried this:

```<code>round(float(x), -5)
</code>```

But this round to the nearest hundred thousand.

I suppose there is a simple solution but couldn't find anything.

答:
divmod could be your friend in this case

```<code>def roundmynumber(x):
    y,z = divmod(x,50000)
    if z >25000: y +=1
    return int(50000*y)

>>> roundmynumber(83000)
100000
>>> roundmynumber(13000)
0
>>> roundmynumber(52000)
50000
>>> roundmynumber(152000)
150000
>>> roundmynumber(172000)
150000
>>> roundmynumber(152000.045)
150000
>>> roundmynumber(-152000.045)
-150000
</code>```

Title: Round numbers to 50 thousands in Python

Body:
How can I round a number to the nearest up or down 50 thousand?

I want to round this 542756 to this 550000, or round this 521405 to this 500000. Considering that the number to be rounded is a variable x.

I tried this:

import math

def roundup(x):
    return int(math.ceil(x / 50000.0)) * 50000

But it only round up and I need to round both up or down.

I also tried this:

round(float(x), -5)

But this round to the nearest hundred thousand.

I suppose there is a simple solution but couldn't find anything.

Body:
divmod could be your friend in this case

def roundmynumber(x):
    y,z = divmod(x,50000)
    if z >25000: y +=1
    return int(50000*y)

>>> roundmynumber(83000)
100000
>>> roundmynumber(13000)
0
>>> roundmynumber(52000)
50000
>>> roundmynumber(152000)
150000
>>> roundmynumber(172000)
150000
>>> roundmynumber(152000.045)
150000
>>> roundmynumber(-152000.045)
-150000


问:
How to validate input using external javascript?
Im doing app based on phonegap. Im trying t validate my input with external javascript file. But getting error validateForm is not defined at HTMLFormElement.onclick. What's wrong with my code?

HTML

```<code><div data-role="page" id="page1">

    <div data-role="header">
        <a href="#pageMain" class="ui-btn ui-icon-back">Back</a>
        <h2>Add New</h2>
    </div>
    <!-- main -->
    <div data-role="main" class="ui-content">

        <form name="myform" onclick="return validateForm()" method="post">
        Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
        <button type="button" id="but_submit">Submit</button>
        </form>

    </div>
    <!-- footer -->
    <div data-role="footer">
        <h2>mine</h2>
    </div>

</div>
</code>```

Code from external javascript

```<code>function validateForm(){
var x = document.forms["myform"]["myname"].value;
if (x==null || x==""){
    alert("enter name");
    return false;
} else{
    return true;
}
}
</code>```

答:
Use below html code:</p>

```<code><form name="myform" onsubmit="return validateForm()" method="post">
        Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
        <button type="button" id="but_submit">Submit</button>
        </form>
</code>```

Body:
Im doing app based on phonegap. Im trying t validate my input with external javascript file. But getting error validateForm is not defined at HTMLFormElement.onclick. What's wrong with my code?

HTML

        Back

Add New

        <form name="myform" onclick="return validateForm()" method="post">
        Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
        <button type="button" id="but_submit">Submit</button>
        </form>

mine

Code from external javascript

function validateForm(){
var x = document.forms["myform"]["myname"].value;
if (x==null || x==""){
    alert("enter name");
    return false;
} else{
    return true;
}
}

Body:
Use below html code:

<form name="myform" onsubmit="return validateForm()" method="post">
        Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
        <button type="button" id="but_submit">Submit</button>
        </form>