问:
Google map is not showing in partial view?
I am trying to implement google map in a partial view and trying to call partial view on a page
here is my google map script which I placed on a main view

```<code> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDLhntIiMFhAoHu5XtrxDuh4EeNbm2ZuH0&libraries=places&callback=initAutocomplete" async defer></script>
    <script type="text/javascript">
        function initAutocomplete()
        {

            var map = new google.maps.Map(document.getElementById('map'),
                {
                center: { lat: -33.8688, lng: 151.2195 },
                zoom: 13,
                mapTypeId: 'roadmap'
            });
            console.log('map', map);
            // Create the search box and link it to the UI element.
            var input = document.getElementById('pac-input');
            var searchBox = new google.maps.places.SearchBox(input);
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

            // Bias the SearchBox results towards current map's viewport.
            map.addListener('bounds_changed', function () {
                searchBox.setBounds(map.getBounds());
            });

            var markers = [];
            // Listen for the event fired when the user selects a prediction and retrieve
            // more details for that place.
            searchBox.addListener('places_changed', function () {
                var places = searchBox.getPlaces();

                if (places.length == 0) {
                    return;
                }

                // Clear out the old markers.
                markers.forEach(function (marker) {
                    marker.setMap(null);
                });
                markers = [];

                // For each place, get the icon, name and location.
                var bounds = new google.maps.LatLngBounds();
                places.forEach(function (place) {
                    if (!place.geometry) {
                        console.log("Returned place contains no geometry");
                        return;
                    }
                    var icon = {
                        url: place.icon,
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(25, 25)
                    };
                    // Create a marker for each place.
                    markers.push(new google.maps.Marker({
                        map: map,
                        icon: icon,
                        title: place.name,
                        position: place.geometry.location
                    }));

                    if (place.geometry.viewport) {
                        // Only geocodes have viewport.
                        bounds.union(place.geometry.viewport);
                    } else {
                        bounds.extend(place.geometry.location);
                    }
                    var address = $('#pac-input').val();
                    //document.getElementById('pac-input');
                    $.ajax({
                        url: "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false",
                        type: "POST",
                        success: function (res) {
                            latitude = res.results[0].geometry.location.lat;
                            longitude = res.results[0].geometry.location.lng;
                        }
                    });
                });
                map.fitBounds(bounds);
            });
        }
</code>```

And here is my HTML which is placed in partial view

```<code> <div class="form-group">
            <label>Type a location to Search on Map</label>
            <input type="text" id="pac-input" class="form-control" ng-model="MyLocations.Location" required>
            <div class="selectlocatinonmap" id="map">
            </div>
    </div>
</code>```

I have placed this script  on a page where I have to call a partial view but google map is not working on a partial view
I am attaching the image also
please take a look

however console is not showing any error.

答:
Maybe it's because when the callback function that generate maps is called, the map container is hidden. You can call the init map callback on click on the button that shows your form, after the fading or sliding effects are done.

EDIT

```<code>$('#my_button_wich_show_form').click(initAutocomplete);
</code>```

Remember to delete callback param from maps url. If you use some effects before showing your modal, call the initAutocomplete function after the effects are done.

In your initAutocomplete function you have to check if #map is empty so you can execute your script or just trigger the map resize event :

```<code><script type="text/javascript">

    function initAutocomplete()
    {
        if( !$('#map').is(':empty') ){
            google.maps.event.trigger(this.map, 'resize');
            return false;
        }
        this.map = new google.maps.Map(document.getElementById('map'),
            {
            center: { lat: -33.8688, lng: 151.2195 },
            zoom: 13,
            mapTypeId: 'roadmap'
        });
        var map = this.map;
        console.log('map', map);
        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function () {
            searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function () {
            var places = searchBox.getPlaces();

            if (places.length == 0) {
                return;
            }

            // Clear out the old markers.
            markers.forEach(function (marker) {
                marker.setMap(null);
            });
            markers = [];

            // For each place, get the icon, name and location.
            var bounds = new google.maps.LatLngBounds();
            places.forEach(function (place) {
                if (!place.geometry) {
                    console.log("Returned place contains no geometry");
                    return;
                }
                var icon = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25)
                };
                // Create a marker for each place.
                markers.push(new google.maps.Marker({
                    map: map,
                    icon: icon,
                    title: place.name,
                    position: place.geometry.location
                }));

                if (place.geometry.viewport) {
                    // Only geocodes have viewport.
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
                var address = $('#pac-input').val();
                //document.getElementById('pac-input');
                $.ajax({
                    url: "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false",
                    type: "POST",
                    success: function (res) {
                        latitude = res.results[0].geometry.location.lat;
                        longitude = res.results[0].geometry.location.lng;
                    }
                });
            });
            map.fitBounds(bounds);
        });
    }
</code>```

Body:
Maybe it's because when the callback function that generate maps is called, the map container is hidden. You can call the init map callback on click on the button that shows your form, after the fading or sliding effects are done.

EDIT

$('#my_button_wich_show_form').click(initAutocomplete);

Remember to delete callback param from maps url. If you use some effects before showing your modal, call the initAutocomplete function after the effects are done.

In your initAutocomplete function you have to check if #map is empty so you can execute your script or just trigger the map resize event :

<script type="text/javascript">

    function initAutocomplete()
    {
        if( !$('#map').is(':empty') ){
            google.maps.event.trigger(this.map, 'resize');
            return false;
        }
        this.map = new google.maps.Map(document.getElementById('map'),
            {
            center: { lat: -33.8688, lng: 151.2195 },
            zoom: 13,
            mapTypeId: 'roadmap'
        });
        var map = this.map;
        console.log('map', map);
        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function () {
            searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function () {
            var places = searchBox.getPlaces();

            if (places.length == 0) {
                return;
            }

            // Clear out the old markers.
            markers.forEach(function (marker) {
                marker.setMap(null);
            });
            markers = [];

            // For each place, get the icon, name and location.
            var bounds = new google.maps.LatLngBounds();
            places.forEach(function (place) {
                if (!place.geometry) {
                    console.log("Returned place contains no geometry");
                    return;
                }
                var icon = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25)
                };
                // Create a marker for each place.
                markers.push(new google.maps.Marker({
                    map: map,
                    icon: icon,
                    title: place.name,
                    position: place.geometry.location
                }));

                if (place.geometry.viewport) {
                    // Only geocodes have viewport.
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
                var address = $('#pac-input').val();
                //document.getElementById('pac-input');
                $.ajax({
                    url: "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false",
                    type: "POST",
                    success: function (res) {
                        latitude = res.results[0].geometry.location.lat;
                        longitude = res.results[0].geometry.location.lng;
                    }
                });
            });
            map.fitBounds(bounds);
        });
    }


来源: stackexchange

问:
Grails 3.3.0 M1 and 3.3.0 M2 Combining MongoDB and Hibernate fail
Step1: use command create app

```<code>grails create-app test
</code>```

Step2: create domain

```<code>grails create-domain-class test
</code>```

Step3: configue build.gradle

```<code>compile 'org.grails.plugins:mongodb'
</code>```

Step4: configue application.yml

```<code>grails:
   mongodb:
       host: "localhost"
       port: 27017
       username: ""
       password: ""
       databaseName: "test"
environments:
development:
    dataSource:
        dbCreate: none
        url:jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
        logSql: true
</code>```

Step5: use mapWith in Test.groovy

```<code>static mapWith="mongo"
</code>```

Step6: query test in bootstrap

```<code>println Test.findAll()
</code>```

Stop7: run grails app

```<code>grails run-app
</code>```

the error is :

```<code> org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not prepare statement; bad SQL grammar [select this_.id as id1_0_0_, this_.version as version2_0_0_ from test this_]; nested exception is org.h2.jdbc.JdbcSQLException: Table "TEST" not found; SQL statement:
select this_.id as id1_0_0_, this_.version as version2_0_0_ from test this_ [42102-194]
        at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
        at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
        at org.grails.orm.hibernate.GrailsHibernateTemplate.convertJdbcAccessException(GrailsHibernateTemplate.java:723)
        at org.grails.orm.hibernate.GrailsHibernateTemplate.convertHibernateAccessException(GrailsHibernateTemplate.java:711)
        at org.grails.orm.hibernate.GrailsHibernateTemplate.doExecute(GrailsHibernateTemplate.java:302)
        at org.grails.orm.hibernate.GrailsHibernateTemplate.execute(GrailsHibernateTemplate.java:242)
        at org.grails.orm.hibernate.GrailsHibernateTemplate.execute(GrailsHibernateTemplate.java:116)
        at org.grails.orm.hibernate.HibernateGormStaticApi.list(HibernateGormStaticApi.groovy:74)
        at org.grails.datastore.gorm.GormStaticApi.findAll(GormStaticApi.groovy:579)
        at org.grails.datastore.gorm.GormEntity$Trait$Helper.findAll(GormEntity.groovy:671)
        at org.grails.datastore.gorm.GormEntity$Trait$Helper$findAll$0.call(Unknown Source)
</code>```

use other version :

3.2.3 is OK

3.2.5 is OK

3.2.9 is Ok

My code is :
the demo in github

what change in 3.3.0.M1 and 3.3.0.M2 ?

答:
```<code>grails:
    mongodb:
       host: "localhost"
       port: 27017
       username: ""
       password: ""
       databaseName: "test"

environments:
    development:
        dataSource:
            dbCreate: none
            url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
            logSql: true
    test:
        dataSource:
            dbCreate: update
            url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    production:
        dataSource:
            dbCreate: none
            url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
            properties:
                jmxEnabled: true
                initialSize: 5
                maxActive: 50
                minIdle: 5
                maxIdle: 25
                maxWait: 10000
                maxAge: 600000
                timeBetweenEvictionRunsMillis: 5000
                minEvictableIdleTimeMillis: 60000
                validationQuery: SELECT 1
                validationQueryTimeout: 3
                validationInterval: 15000
                testOnBorrow: true
                testWhileIdle: true
                testOnReturn: false
                jdbcInterceptors: ConnectionState
                defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
</code>```

Replace your these lines to this

```<code>environments:
    development:
        grails:
            mongodb:
                host: "localhost"
                port: 27017
                username: ""
                password: ""
                databaseName: "test"
    test:
        mongodb:
                host: "localhost"
                port: 27017
                username: ""
                password: ""
                databaseName: "test"
    production:
        grails:
            mongodb:
                host: "localhost"
                port: 27017
                username: ""
                password: ""
                databaseName: "test"
            properties:
                jmxEnabled: true
                initialSize: 5
                maxActive: 50
                minIdle: 5
                maxIdle: 25
                maxWait: 10000
                maxAge: 600000
                timeBetweenEvictionRunsMillis: 5000
                minEvictableIdleTimeMillis: 60000
                validationQuery: SELECT 1
                validationQueryTimeout: 3
                validationInterval: 15000
                testOnBorrow: true
                testWhileIdle: true
                testOnReturn: false
                jdbcInterceptors: ConnectionState
                defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Step1: use command create app

grails create-app test

Step2: create domain

grails create-domain-class test

Step3: configue build.gradle

compile 'org.grails.plugins:mongodb'

Step4: configue application.yml

grails:
   mongodb:
       host: "localhost"
       port: 27017
       username: ""
       password: ""
       databaseName: "test"
environments:
development:
    dataSource:
        dbCreate: none
        url:jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
        logSql: true

Step5: use mapWith in Test.groovy

static mapWith="mongo"

Step6: query test in bootstrap

println Test.findAll()

Stop7: run grails app

grails run-app

the error is :

 org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not prepare statement; bad SQL grammar [select this_.id as id1_0_0_, this_.version as version2_0_0_ from test this_]; nested exception is org.h2.jdbc.JdbcSQLException: Table "TEST" not found; SQL statement:
select this_.id as id1_0_0_, this_.version as version2_0_0_ from test this_ [42102-194]
        at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
        at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
        at org.grails.orm.hibernate.GrailsHibernateTemplate.convertJdbcAccessException(GrailsHibernateTemplate.java:723)
        at org.grails.orm.hibernate.GrailsHibernateTemplate.convertHibernateAccessException(GrailsHibernateTemplate.java:711)
        at org.grails.orm.hibernate.GrailsHibernateTemplate.doExecute(GrailsHibernateTemplate.java:302)
        at org.grails.orm.hibernate.GrailsHibernateTemplate.execute(GrailsHibernateTemplate.java:242)
        at org.grails.orm.hibernate.GrailsHibernateTemplate.execute(GrailsHibernateTemplate.java:116)
        at org.grails.orm.hibernate.HibernateGormStaticApi.list(HibernateGormStaticApi.groovy:74)
        at org.grails.datastore.gorm.GormStaticApi.findAll(GormStaticApi.groovy:579)
        at org.grails.datastore.gorm.GormEntity$Trait$Helper.findAll(GormEntity.groovy:671)
        at org.grails.datastore.gorm.GormEntity$Trait$Helper$findAll$0.call(Unknown Source)

use other version :

3.2.3 is OK

3.2.5 is OK

3.2.9 is Ok

My code is :
the demo in github

what change in 3.3.0.M1 and 3.3.0.M2 ?

Body:
grails:
    mongodb:
       host: "localhost"
       port: 27017
       username: ""
       password: ""
       databaseName: "test"

environments:
    development:
        dataSource:
            dbCreate: none
            url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
            logSql: true
    test:
        dataSource:
            dbCreate: update
            url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    production:
        dataSource:
            dbCreate: none
            url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
            properties:
                jmxEnabled: true
                initialSize: 5
                maxActive: 50
                minIdle: 5
                maxIdle: 25
                maxWait: 10000
                maxAge: 600000
                timeBetweenEvictionRunsMillis: 5000
                minEvictableIdleTimeMillis: 60000
                validationQuery: SELECT 1
                validationQueryTimeout: 3
                validationInterval: 15000
                testOnBorrow: true
                testWhileIdle: true
                testOnReturn: false
                jdbcInterceptors: ConnectionState
                defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED

Replace your these lines to this

environments:
    development:
        grails:
            mongodb:
                host: "localhost"
                port: 27017
                username: ""
                password: ""
                databaseName: "test"
    test:
        mongodb:
                host: "localhost"
                port: 27017
                username: ""
                password: ""
                databaseName: "test"
    production:
        grails:
            mongodb:
                host: "localhost"
                port: 27017
                username: ""
                password: ""
                databaseName: "test"
            properties:
                jmxEnabled: true
                initialSize: 5
                maxActive: 50
                minIdle: 5
                maxIdle: 25
                maxWait: 10000
                maxAge: 600000
                timeBetweenEvictionRunsMillis: 5000
                minEvictableIdleTimeMillis: 60000
                validationQuery: SELECT 1
                validationQueryTimeout: 3
                validationInterval: 15000
                testOnBorrow: true
                testWhileIdle: true
                testOnReturn: false
                jdbcInterceptors: ConnectionState
                defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED


问:
Different radius to box-shadow and div
I want to apply different border-radius to box-shadow and div(on which box shadow is applied). Want to make something like this.
https://www.screencast.com/t/mEjBxMnbt

I make div and apply box-shadow and then apply border-radius:1px 0 0 1px to div which gives radius to box shadow which is fine but I want to give more border-radius to my div without changing my box-shadow radius.Can apply css only on div can't wrap it up or take parent container for it.

Please see link for more understanding.

Tried this is far

https://codepen.io/naveen_dharni/pen/Kqdyer

答:
Can't your problem be solved with overlapping multiple shadows?

body
{
  background-color:pink;
  padding-left:20px;
}
div
{
    display:inline-block;
    margin-top:30px;
    margin-right:10px;
    margin-left:8px;
    height: 100px;
    width: 100px;
    border: 3px solid black;
    max-width: 100%;
    max-height: 100%;
    box-shadow:
      -27px -27px 0 -9px blue,
      -27px 27px 0 -9px blue,
      -9px -9px 0 9px blue,
       -9px 9px 0 9px blue,
       9px -9px 0 9px blue,
       9px 9px 0 9px blue;
   border-radius: 10px;
}
div:first-child {
  box-shadow:
      -9px -9px 0 9px blue,
       -9px 9px 0 9px blue,
       9px -9px 0 9px blue,
       9px 9px 0 9px blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div><!-- no space between inline-blocks to make gaps predictable
--><div></div><!--
--><div></div><!--
--><div></div></code>```

Title: Different radius to box-shadow and div

Body:
Can't your problem be solved with overlapping multiple shadows?

body
{
  background-color:pink;
  padding-left:20px;
}
div
{
    display:inline-block;
    margin-top:30px;
    margin-right:10px;
    margin-left:8px;
    height: 100px;
    width: 100px;
    border: 3px solid black;
    max-width: 100%;
    max-height: 100%;
    box-shadow:
      -27px -27px 0 -9px blue,
      -27px 27px 0 -9px blue,
      -9px -9px 0 9px blue,
       -9px 9px 0 9px blue,
       9px -9px 0 9px blue,
       9px 9px 0 9px blue;
   border-radius: 10px;
}
div:first-child {
  box-shadow:
      -9px -9px 0 9px blue,
       -9px 9px 0 9px blue,
       9px -9px 0 9px blue,
       9px 9px 0 9px blue;
}

<div></div><!-- no space between inline-blocks to make gaps predictable
--><div></div><!--
--><div></div><!--
--><div></div>


问:
File Upload - Allert if occurred error without submit
I have multiple upload script and I will implement it to file with bigger html formwhich shoud be fill before submit. I need to allert error if selected file is more then written megabytes or type is wrong without submit.
P.S It would be nice if you tell me how to upload file with button and do not submit bigger form.

 Here is my code:

var abc = 0; //Declaring and defining global increement variable

$(document).ready(function() {

//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
    $('#add_more').click(function() {
        $(this).before($("
", {id: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
                $("

")
                ));
    });

//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
            if (this.files && this.files[0]) {
                 abc += 1; //increementing global variable by 1

    var z = abc - 1;
                var x = $(this).parent().find('#previewimg' + z).remove();
                $(this).before("

");

       var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);

       $(this).hide();
                $("#abcd"+ abc).append($("", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
                $(this).parent().parent().remove();
                }));
            }
        });

//To preview image
    function imageIsLoaded(e) {
        $('#previewimg' + abc).attr('src', e.target.result);
    };

    $('#upload').click(function(e) {
        var name = $(":file").val();
        if (!name)
        {
            alert("First Image Must Be Selected");
            e.preventDefault();
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(http://fonts.googleapis.com/css?family=Droid+Sans);
form{
    background-color:white;
}
#maindiv{
    width:960px;
    margin:10px auto;
    padding:10px;
    font-family: 'Droid Sans', sans-serif;
}
#formdiv{
    width:500px;
    float:left;
    text-align: center;
}
form{
    padding: 40px 20px;
    box-shadow: 0px 0px 10px;
    border-radius: 2px;
}
h2{
    margin-left: 30px;
}
.upload{
    background-color:#ff0000;
    border:1px solid #ff0000;
    color:#fff;
    border-radius:5px;
    padding:10px;
    text-shadow:1px 1px 0px green;
    box-shadow: 2px 2px 15px rgba(0,0,0, .75);
}
.upload:hover{
    cursor:pointer;
    background:#c20b0b;
    border:1px solid #c20b0b;
    box-shadow: 0px 0px 5px rgba(0,0,0, .75);
}
#file{
    color:green;
    padding:5px; border:1px dashed #123456;
    background-color: #f9ffe5;
}
#upload{
    margin-left: 45px;
}

#noerror{
    color:green;
    text-align: left;
}
#error{
    color:red;
    text-align: left;
}

.abcd{
    text-align: center;
}

b{
    color:red;
}
#formget{
    float:right;

}</code>```

                <form action = "" enctype="multipart/form-data" action="" method="post">

<input name="file[]" type="file" id="file"/>

     <input type="text" required >
                    <input type="button" id="add_more" class="upload" value="Add More Files"/>
                    <input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
                </form>

                <?php include "upload.php"; ?>

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

<p>And my php file: </p>

```<?php
if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image

    $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png", "pdf");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array

      if (($_FILES["file"]["size"][$i] < 4194304) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').Image uploaded successfully!.

';
            } else {//if file was not moved.
                echo $j. ').please try again!.

';
            }
        } else {//if file size and file type was incorrect.
            echo $j. ').***Invalid file Size or Type***

';
        }
    }}?>
```

答:
using jquery and html5

<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
```

Body:
I have multiple upload script and I will implement it to file with bigger html formwhich shoud be fill before submit. I need to allert error if selected file is more then written megabytes or type is wrong without submit.
P.S It would be nice if you tell me how to upload file with button and do not submit bigger form.

 Here is my code:

var abc = 0; //Declaring and defining global increement variable

$(document).ready(function() {

//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
    $('#add_more').click(function() {
        $(this).before($("
", {id: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
                $("

")
                ));
    });

//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
            if (this.files && this.files[0]) {
                 abc += 1; //increementing global variable by 1

    var z = abc - 1;
                var x = $(this).parent().find('#previewimg' + z).remove();
                $(this).before("

");

       var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);

       $(this).hide();
                $("#abcd"+ abc).append($("", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
                $(this).parent().parent().remove();
                }));
            }
        });

//To preview image
    function imageIsLoaded(e) {
        $('#previewimg' + abc).attr('src', e.target.result);
    };

    $('#upload').click(function(e) {
        var name = $(":file").val();
        if (!name)
        {
            alert("First Image Must Be Selected");
            e.preventDefault();
        }
    });
});

@import url(http://fonts.googleapis.com/css?family=Droid+Sans);
form{
    background-color:white;
}
#maindiv{
    width:960px;
    margin:10px auto;
    padding:10px;
    font-family: 'Droid Sans', sans-serif;
}
#formdiv{
    width:500px;
    float:left;
    text-align: center;
}
form{
    padding: 40px 20px;
    box-shadow: 0px 0px 10px;
    border-radius: 2px;
}
h2{
    margin-left: 30px;
}
.upload{
    background-color:#ff0000;
    border:1px solid #ff0000;
    color:#fff;
    border-radius:5px;
    padding:10px;
    text-shadow:1px 1px 0px green;
    box-shadow: 2px 2px 15px rgba(0,0,0, .75);
}
.upload:hover{
    cursor:pointer;
    background:#c20b0b;
    border:1px solid #c20b0b;
    box-shadow: 0px 0px 5px rgba(0,0,0, .75);
}
#file{
    color:green;
    padding:5px; border:1px dashed #123456;
    background-color: #f9ffe5;
}
#upload{
    margin-left: 45px;
}

#noerror{
    color:green;
    text-align: left;
}
#error{
    color:red;
    text-align: left;
}

.abcd{
    text-align: center;
}

b{
    color:red;
}
#formget{
    float:right;

}

                <form action = "" enctype="multipart/form-data" action="" method="post">

<input name="file[]" type="file" id="file"/>

     <input type="text" required >
                    <input type="button" id="add_more" class="upload" value="Add More Files"/>
                    <input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
                </form>

                <?php include "upload.php"; ?>

And my php file:

<?php
if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image

    $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png", "pdf");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array

      if (($_FILES["file"]["size"][$i] < 4194304) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').Image uploaded successfully!.

';
            } else {//if file was not moved.
                echo $j. ').please try again!.

';
            }
        } else {//if file size and file type was incorrect.
            echo $j. ').***Invalid file Size or Type***

';
        }
    }}?>

Body:
using jquery and html5

<script type="text/javascript">
    function Upload() {
        var fileUpload = document.getElementById("fileUpload");
        if (typeof (fileUpload.files) != "undefined") {
            var size = parseFloat(fileUpload.files[0].size / 1024).toFixed(2);
            alert(size + " KB.");
        } else {
            alert("This browser does not support HTML5.");
        }
    }
</script>

<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>


问:
I'm passing three 3 parameter on a javascript function but it only get's the first parameter what could be wrong
//this is the data i get from controller ********************************************************************************************************************************************************************************************************************

    </p>

```<code>//this is where i call the function fun_view() where im passing the name, company_name, mobile_phone

<td><a href="" data-id="" class="display" data-toggle="modal" data-target="#myModal" onclick="fun_view('{{ $dat->name,$dat->company_name,$dat->mobile_phone }}')"><?php echo $dat->name;?></a></td>

//this is fun_view function 'im calling

function fun_view(name, company_name, mobile) {
    var name = name;
    var company_name = company_name;
    var mobile = mobile;
    alert(name);
    alert(company_name);
    alert(mobile);
    document.getElementById("view_name").innerHTML = name;
    document.getElementById("view_company_name").innerHTML = company_name;
    document.getElementById("view_mobile").innerHTML = mobile;
    return name, company_name, mobile;
}

//this is where is display the result of fun_view function
//this is where i display the variable that i should be getting on fun_view() javascript function
</code>```

答:
you're wrapping all variables under a single quote:

It needs to be:

```<code>fun_view('{{ $dat->name}}','{{$dat->company_name}}','{{$dat->mobile_phone }}')
</code>```

In addition you're not allowed to return multiple values from a function, you need something like:

```<code>return { name: name, company_name: company_name, mobile_phone: mobile_phone }
</code>```

Example usage:

```<code> var result = fun_view('a','b','c');

 console.log(result.name, result.company_name, result.mobile_phone);
</code>```

In addition you should use href='javascript:void(0)' as a href. This will prevent the page from redirecting. You could also use # .

Body:
//this is the data i get from controller ********************************************************************************************************************************************************************************************************************

//this is where i call the function fun_view() where im passing the name, company_name, mobile_phone

name,$dat->company_name,$dat->mobile_phone }}')"><?php echo $dat->name;?>

//this is fun_view function 'im calling

function fun_view(name, company_name, mobile) {
    var name = name;
    var company_name = company_name;
    var mobile = mobile;
    alert(name);
    alert(company_name);
    alert(mobile);
    document.getElementById("view_name").innerHTML = name;
    document.getElementById("view_company_name").innerHTML = company_name;
    document.getElementById("view_mobile").innerHTML = mobile;
    return name, company_name, mobile;
}

//this is where is display the result of fun_view function
//this is where i display the variable that i should be getting on fun_view() javascript function

Body:
you're wrapping all variables under a single quote:

It needs to be:

fun_view('{{ $dat->name}}','{{$dat->company_name}}','{{$dat->mobile_phone }}')

In addition you're not allowed to return multiple values from a function, you need something like:

return { name: name, company_name: company_name, mobile_phone: mobile_phone }

Example usage:

 var result = fun_view('a','b','c');

 console.log(result.name, result.company_name, result.mobile_phone);

In addition you should use href='javascript:void(0)' as a href. This will prevent the page from redirecting. You could also use # .


问:
Passing values from radio buttons into the script in Matlab
So i created GUI in guide that looks like this:

GUI

I want to access data from radio button and then change the variables in my simulation (Bitrate and Modulation are the button groups, Improvement is a single radio button). For example - in the simulation I have a variable Rs=1e9, so when 1Gbps button is selected I want it to remain 1e9, but if 10Gbps button is selected I want it to change its value to 10e9.

Then after hitting Start button I want to start my simulation (which is in different .m file) with given parameters. How can I do it ? (I know about handles idea in matlab, but I don't know how to pass value to the simulation)

That's the code that controls gui - generated by guide. I added some code that starts simulation and close gui window.

```<code>function varargout = gui_final(varargin)

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @gui_final_OpeningFcn, ...
                   'gui_OutputFcn',  @gui_final_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before gui_final is made visible.
function gui_final_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

% Choose default command line output for gui_final
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes gui_final wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = gui_final_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject    handle to start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
clc
close all

message = sprintf('Wait - this is a very long simulation!\nClick the OK button and wait');
uiwait(msgbox(message));
evalin('base', 'simulation');

% --- Executes on button press in dfe.
function dfe_Callback(hObject, eventdata, handles)
% hObject    handle to dfe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of dfe

% --- Executes on button press in ook.
function ook_Callback(hObject, eventdata, handles)
% hObject    handle to ook (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of ook
</code>```

答:
You can do it using the object "hObject"

Like this: Suppose that you have an slider, everytime the slider is moved the callback is called. You can use it to store a variable. Then, when you press a button you want to use that data for whatever. The code is:

```<code>function slider_callback(hObject,eventdata)
    sval = hObject.Value;
    diffMax = hObject.Max - sval;
    data = struct('val',sval,'diffMax',diffMax);
    hObject.UserData = data;
    % For R2014a and earlier:
    % sval = get(hObject,'Value');
    % maxval = get(hObject,'Max');
    % diffMax = maxval - sval;
    % data = struct('val',sval,'diffMax',diffMax);
    % set(hObject,'UserData',data);

end

function button_callback(hObject,eventdata)
    h = findobj('Tag','slider1');
    data = h.UserData;
    % For R2014a and earlier:
    % data = get(h,'UserData');
    display([data.val data.diffMax]);
end
</code>```

REFERENCE: Matlab Docs

UPDATE

In your case you can do it with another approach if you want. When you press the button START you read the state of your radio buttons, and pass the appropiate value to your simulation_function that I suppose it is called "simulation". In the following example I suppose that you have a button-group called (tag): uibuttongroup1, and inside you have two buttons: radiobutton1 and radiobutton2

```<code>% --- Executes on button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject    handle to start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%Check which radio button is pressed
switch get(get(handles.uibuttongroup1,'SelectedObject'),'Tag')
  case 'radiobutton1',  myParameter = 1e9;
  case 'radiobutton2',  myParameter = 10e9;
end
%Execute simulation
clc
close all

message = sprintf('Wait - this is a very long simulation!\nClick the OK button and wait');
uiwait(msgbox(message));
evalin('base', 'simulation(myParameter)');
</code>```

Body:
So i created GUI in guide that looks like this:

GUI

I want to access data from radio button and then change the variables in my simulation (Bitrate and Modulation are the button groups, Improvement is a single radio button). For example - in the simulation I have a variable Rs=1e9, so when 1Gbps button is selected I want it to remain 1e9, but if 10Gbps button is selected I want it to change its value to 10e9.

Then after hitting Start button I want to start my simulation (which is in different .m file) with given parameters. How can I do it ? (I know about handles idea in matlab, but I don't know how to pass value to the simulation)

That's the code that controls gui - generated by guide. I added some code that starts simulation and close gui window.

function varargout = gui_final(varargin)

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @gui_final_OpeningFcn, ...
                   'gui_OutputFcn',  @gui_final_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before gui_final is made visible.
function gui_final_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

% Choose default command line output for gui_final
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes gui_final wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = gui_final_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject    handle to start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
clc
close all

message = sprintf('Wait - this is a very long simulation!\nClick the OK button and wait');
uiwait(msgbox(message));
evalin('base', 'simulation');

% --- Executes on button press in dfe.
function dfe_Callback(hObject, eventdata, handles)
% hObject    handle to dfe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of dfe

% --- Executes on button press in ook.
function ook_Callback(hObject, eventdata, handles)
% hObject    handle to ook (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of ook

Body:
You can do it using the object "hObject"

Like this: Suppose that you have an slider, everytime the slider is moved the callback is called. You can use it to store a variable. Then, when you press a button you want to use that data for whatever. The code is:

function slider_callback(hObject,eventdata)
    sval = hObject.Value;
    diffMax = hObject.Max - sval;
    data = struct('val',sval,'diffMax',diffMax);
    hObject.UserData = data;
    % For R2014a and earlier:
    % sval = get(hObject,'Value');
    % maxval = get(hObject,'Max');
    % diffMax = maxval - sval;
    % data = struct('val',sval,'diffMax',diffMax);
    % set(hObject,'UserData',data);

end

function button_callback(hObject,eventdata)
    h = findobj('Tag','slider1');
    data = h.UserData;
    % For R2014a and earlier:
    % data = get(h,'UserData');
    display([data.val data.diffMax]);
end

REFERENCE: Matlab Docs

UPDATE

In your case you can do it with another approach if you want. When you press the button START you read the state of your radio buttons, and pass the appropiate value to your simulation_function that I suppose it is called "simulation". In the following example I suppose that you have a button-group called (tag): uibuttongroup1, and inside you have two buttons: radiobutton1 and radiobutton2

% --- Executes on button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject    handle to start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%Check which radio button is pressed
switch get(get(handles.uibuttongroup1,'SelectedObject'),'Tag')
  case 'radiobutton1',  myParameter = 1e9;
  case 'radiobutton2',  myParameter = 10e9;
end
%Execute simulation
clc
close all

message = sprintf('Wait - this is a very long simulation!\nClick the OK button and wait');
uiwait(msgbox(message));
evalin('base', 'simulation(myParameter)');


问:
WP Pagination Loop not working in custom theme
Pagination loop not working in custom theme Home page template. Shows same content in all pages.

You can also suggest me some other code to fix the issue.

```<code><?php
// clear any other queries that may be in use!
wp_reset_query();
// check for $_GET paged value
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// setup post arguments
$args = array( 'posts_per_page' => 7, 'paged' => $paged, );
// run our query
query_posts($args);
// start loop
if (have_posts()) : while (have_posts()) : the_post();
  // if you use the <!-- more --> in your posts.
  global $more;
  $more = 0;
?>
   <div class="post">
     <?php the_title(); ?>
   </div>
<?php endwhile; ?>
<div class="navigation">
   <?php next_posts_link('Next'); ?>
   <?php previous_posts_link('Previous'); ?>
</div>
<?php else: ?>
   <div><h2>Nothing found</h2><p>No posts found for that query</p></div>
<?php endif; ?>
</code>```

答:
query_posts() isn't meant to be used by plugins or themes. Use WP_Query instead. It accepts the same parameters as query_posts does. Be aware that neither of these methods is the most efficient way to alter the default query. In fact, either method can also be responsible for breaking pagination.

If your theme is using either of these methods to query the main loop, you can replace it with the preferred way, that is to say, hooking into 'pre_get_posts' and altering the main query by using is_main_query(). This way is faster and more reliable because the query for the main loop is altered before the posts are retrieved from the database.

For example, lets say your theme queries the main loop like this on your home page and the pagination is not working:

```<code><?php
// clear any other queries that may be in use!
wp_reset_query();
// check for $_GET paged value
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// setup post arguments
$args = array( 'posts_per_page' => 7, 'paged' => $paged, );
// run our query
query_posts($args);
// start loop
if (have_posts()) : while (have_posts()) : the_post();
  // if you use the <!-- more --> in your posts.
  global $more;
  $more = 0;
?>
   <div class="post">
     <?php the_title(); ?>
   </div>
<?php endwhile; ?>
<div class="navigation">
   <?php next_posts_link('Next'); ?>
   <?php previous_posts_link('Previous'); ?>
</div>
<?php else: ?>
   <div><h2>Nothing found</h2><p>No posts found for that query</p></div>
<?php endif; ?>
</code>```

Remove the query_posts part from your code:

```<code><?php
// clear any other queries that may be in use!
wp_reset_query();
// check for $_GET paged value
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// setup post arguments
$args = array( 'posts_per_page' => 7, 'paged' => $paged, );
// run our query
query_posts($args);
?>
</code>```

And add the query for your home page back in your theme's functions.php file:

```<code>function my_post_queries( $query ) {
  // do not alter the query on wp-admin pages and only alter it if it's the main query
  if (!is_admin() && $query->is_main_query()){

    // alter the query for the home and category pages

    if(is_home()){
      $query->set('posts_per_page', 7);
    }

    if(is_category()){
      $query->set('posts_per_page', 3);
    }

  }
}
add_action( 'pre_get_posts', 'my_post_queries' );
</code>```

You can use conditional tags to target the pages where we want to alter the query. Like,

```<code>// alter the query for the Movies category page
if(is_home() || is_front_page){
  $query->set('posts_per_page', 7);
}
</code>```

Body:
Pagination loop not working in custom theme Home page template. Shows same content in all pages.

You can also suggest me some other code to fix the issue.

<?php
// clear any other queries that may be in use!
wp_reset_query();
// check for $_GET paged value
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// setup post arguments
$args = array( 'posts_per_page' => 7, 'paged' => $paged, );
// run our query
query_posts($args);
// start loop
if (have_posts()) : while (have_posts()) : the_post();
  // if you use the  in your posts.
  global $more;
  $more = 0;
?>

     <?php the_title(); ?>

<?php endwhile; ?>

   <?php next_posts_link('Next'); ?>
   <?php previous_posts_link('Previous'); ?>

<?php else: ?>

Nothing found

No posts found for that query

<?php endif; ?>

Body:
query_posts() isn't meant to be used by plugins or themes. Use WP_Query instead. It accepts the same parameters as query_posts does. Be aware that neither of these methods is the most efficient way to alter the default query. In fact, either method can also be responsible for breaking pagination.

If your theme is using either of these methods to query the main loop, you can replace it with the preferred way, that is to say, hooking into 'pre_get_posts' and altering the main query by using is_main_query(). This way is faster and more reliable because the query for the main loop is altered before the posts are retrieved from the database.

For example, lets say your theme queries the main loop like this on your home page and the pagination is not working:

<?php
// clear any other queries that may be in use!
wp_reset_query();
// check for $_GET paged value
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// setup post arguments
$args = array( 'posts_per_page' => 7, 'paged' => $paged, );
// run our query
query_posts($args);
// start loop
if (have_posts()) : while (have_posts()) : the_post();
  // if you use the <!-- more --> in your posts.
  global $more;
  $more = 0;
?>
   <div class="post">
     <?php the_title(); ?>
   </div>
<?php endwhile; ?>
<div class="navigation">
   <?php next_posts_link('Next'); ?>
   <?php previous_posts_link('Previous'); ?>
</div>
<?php else: ?>
   <div><h2>Nothing found</h2><p>No posts found for that query</p></div>
<?php endif; ?>

Remove the query_posts part from your code:

<?php
// clear any other queries that may be in use!
wp_reset_query();
// check for $_GET paged value
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// setup post arguments
$args = array( 'posts_per_page' => 7, 'paged' => $paged, );
// run our query
query_posts($args);
?>

And add the query for your home page back in your theme's functions.php file:

function my_post_queries( $query ) {
  // do not alter the query on wp-admin pages and only alter it if it's the main query
  if (!is_admin() && $query->is_main_query()){

    // alter the query for the home and category pages

    if(is_home()){
      $query->set('posts_per_page', 7);
    }

    if(is_category()){
      $query->set('posts_per_page', 3);
    }

  }
}
add_action( 'pre_get_posts', 'my_post_queries' );

You can use conditional tags to target the pages where we want to alter the query. Like,

// alter the query for the Movies category page
if(is_home() || is_front_page){
  $query->set('posts_per_page', 7);
}


问:
Iterate through a List of Strings starting from 'One' String until 'Another' String in Java
I'm trying to iterate through a List of Strings in Java.
My List consists of:

```<code>["DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux","DataFileDownload/FD/722066/71493/2016/12/31/untitled-2.aux","DataFileDownload/FD/722066/71493/2017/01/01/untitled-3.aux","DataFileDownload/FD/722066/71493/2016/01/02/untitled-4.aux"]
</code>```

And I am reading the dates from the user as:

```<code>SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date fromDate = fmt.parse("2016-12-30");
Date toDate = fmt.parse("2017-01-02");
Calendar fromCal = Calendar.getInstance();
fromCal.setTime(fromDate);
String fromYear = String.valueOf(fromCal.get(Calendar.YEAR));
String fromMonth = String.valueOf(fromCal.get(Calendar.MONTH)+1);
String fromDay = String.valueOf(fromCal.get(Calendar.DAY_OF_MONTH));
Calendar toCal = Calendar.getInstance();
toCal.setTime(toDate);
String toYear = String.valueOf(toCal.get(Calendar.YEAR));
String toMonth = String.valueOf(toCal.get(Calendar.MONTH)+1);
String toDay = String.valueOf(toCal.get(Calendar.DAY_OF_MONTH));
</code>```

If I wanted to extract the Strings from date: 30-dec-2016 to 01-Jan-2017, i.e.

```<code>"DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux","DataFileDownload/FD/722066/71493/2016/12/31/untitled-2.aux","DataFileDownload/FD/722066/71493/2017/01/01/untitled-3.aux"
</code>```

I'm using the below loop:-

```<code>for(String s : NameList){
    if((s.equals(fromYear) && s.equals(fromMonth) && s.equals(fromDay)) == true){
  while((s.equals(toYear) && s.equals(toMonth) && s.equals(toDay)) != true){
     System.out.println(s);
  }
  System.out.println(s);
}
</code>```

I get no result.

But when I try this:

```<code>       for(String s : objectNameList){
           if((s.contains(fromYear) && s.contains(fromMonth) && s.contains(fromDay))){
               System.out.println(s);
           }
       }
</code>```

I get only:

```<code>"DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux"
</code>```

Can anyone please let me know how can I improve my loop condition?

Thanks in advance!

答:
Convert the date values from String to Integer.

```<code> int fromYear=Integer.parseInt(String.valueOf(fromCal.get(Calendar.YEAR)));
 int fromMonth=Integer.parseInt(String.valueOf(fromCal.get(Calendar.MONTH)+1));
 int fromDay = Integer.parseInt(String.valueOf(fromCal.get(Calendar.DAY_OF_MONTH)));

 int toYear = Integer.parseInt(String.valueOf(toCal.get(Calendar.YEAR)));
 int toMonth = Integer.parseInt(String.valueOf(toCal.get(Calendar.MONTH)+1));
 int toDay =   Integer.parseInt(String.valueOf(toCal.get(Calendar.DAY_OF_MONTH)));
</code>```

Then split the Sting List and get year, month, day from the string inside the for block

```<code> String[] f = s.split("/");
 int year1 = Integer.parseInt(f[4]);
 int month1 = Integer.parseInt(f[5]);
 int day1 = Integer.parseInt(f[6]);
</code>```

Then apply the logic to match date in between from date and to date

```<code>            if((fromYear <  year1) && (toYear >  year1))
                    {
                            System.out.println(s);
                    }
                    else if((fromYear ==  year1))
                    {
                            if((fromMonth <=  month1) && (fromDay >= day1))
                            {
                                    System.out.println(s);
                            }
                    }
                    else if((toYear ==  year1))
                    {
                            if((toMonth >=  month1) || (toDay == day1))
                            {
                                    System.out.println(s);
                            }
                    }
</code>```

Body:
I'm trying to iterate through a List of Strings in Java.
My List consists of:

["DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux","DataFileDownload/FD/722066/71493/2016/12/31/untitled-2.aux","DataFileDownload/FD/722066/71493/2017/01/01/untitled-3.aux","DataFileDownload/FD/722066/71493/2016/01/02/untitled-4.aux"]

And I am reading the dates from the user as:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date fromDate = fmt.parse("2016-12-30");
Date toDate = fmt.parse("2017-01-02");
Calendar fromCal = Calendar.getInstance();
fromCal.setTime(fromDate);
String fromYear = String.valueOf(fromCal.get(Calendar.YEAR));
String fromMonth = String.valueOf(fromCal.get(Calendar.MONTH)+1);
String fromDay = String.valueOf(fromCal.get(Calendar.DAY_OF_MONTH));
Calendar toCal = Calendar.getInstance();
toCal.setTime(toDate);
String toYear = String.valueOf(toCal.get(Calendar.YEAR));
String toMonth = String.valueOf(toCal.get(Calendar.MONTH)+1);
String toDay = String.valueOf(toCal.get(Calendar.DAY_OF_MONTH));

If I wanted to extract the Strings from date: 30-dec-2016 to 01-Jan-2017, i.e.

"DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux","DataFileDownload/FD/722066/71493/2016/12/31/untitled-2.aux","DataFileDownload/FD/722066/71493/2017/01/01/untitled-3.aux"

I'm using the below loop:-

for(String s : NameList){
    if((s.equals(fromYear) && s.equals(fromMonth) && s.equals(fromDay)) == true){
  while((s.equals(toYear) && s.equals(toMonth) && s.equals(toDay)) != true){
     System.out.println(s);
  }
  System.out.println(s);
}

I get no result.

But when I try this:

       for(String s : objectNameList){
           if((s.contains(fromYear) && s.contains(fromMonth) && s.contains(fromDay))){
               System.out.println(s);
           }
       }

I get only:

"DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux"

Can anyone please let me know how can I improve my loop condition?

Thanks in advance!

Body:
Convert the date values from String to Integer.

 int fromYear=Integer.parseInt(String.valueOf(fromCal.get(Calendar.YEAR)));
 int fromMonth=Integer.parseInt(String.valueOf(fromCal.get(Calendar.MONTH)+1));
 int fromDay = Integer.parseInt(String.valueOf(fromCal.get(Calendar.DAY_OF_MONTH)));

 int toYear = Integer.parseInt(String.valueOf(toCal.get(Calendar.YEAR)));
 int toMonth = Integer.parseInt(String.valueOf(toCal.get(Calendar.MONTH)+1));
 int toDay =   Integer.parseInt(String.valueOf(toCal.get(Calendar.DAY_OF_MONTH)));

Then split the Sting List and get year, month, day from the string inside the for block

 String[] f = s.split("/");
 int year1 = Integer.parseInt(f[4]);
 int month1 = Integer.parseInt(f[5]);
 int day1 = Integer.parseInt(f[6]);

Then apply the logic to match date in between from date and to date

            if((fromYear <  year1) && (toYear >  year1))
                    {
                            System.out.println(s);
                    }
                    else if((fromYear ==  year1))
                    {
                            if((fromMonth <=  month1) && (fromDay >= day1))
                            {
                                    System.out.println(s);
                            }
                    }
                    else if((toYear ==  year1))
                    {
                            if((toMonth >=  month1) || (toDay == day1))
                            {
                                    System.out.println(s);
                            }
                    }


问:
C# same namespace in different files
I tried to move implementation to other file and got Error in Form1.cs "OpenPort doesn't exist in the curent context"
Any suggestions, please?</p>

```<code>Form1.cs

namespace MyApp
{
    void Form1Load(object sender, EventArgs e)
    {
        OpenPort();
    }
}

Port.cs

namespace MyApp
{
    public static void OpenPort();
}
</code>```

答:
First of all you can't declare methods or properties directly in a namespace. You have to declare a class first, in which you write your methods. Then, if you want to "spread" the same class in different files, you ought to add the partial keyword.

```<code>Form1.cs

namespace MyApp
{
    public partial class MyClass
    {
        public void Form1Load(object sender, EventArgs e)
        {
            OpenPort();
        }
    }
}

Port.cs

namespace MyApp
{
    public partial class MyClass
    {
        public static void OpenPort()
        {
            // your implementation here
        }
    }
}
</code>```

Title: C# same namespace in different files

Body:
I tried to move implementation to other file and got Error in Form1.cs "OpenPort doesn't exist in the curent context"
Any suggestions, please?

Form1.cs

namespace MyApp
{
    void Form1Load(object sender, EventArgs e)
    {
        OpenPort();
    }
}

Port.cs

namespace MyApp
{
    public static void OpenPort();
}

Body:
First of all you can't declare methods or properties directly in a namespace. You have to declare a class first, in which you write your methods. Then, if you want to "spread" the same class in different files, you ought to add the partial keyword.

Form1.cs

namespace MyApp
{
    public partial class MyClass
    {
        public void Form1Load(object sender, EventArgs e)
        {
            OpenPort();
        }
    }
}

Port.cs

namespace MyApp
{
    public partial class MyClass
    {
        public static void OpenPort()
        {
            // your implementation here
        }
    }
}


问:
Only returning Callback is not a function
Having a real difficult time with callbacks. I have a function that will take an image, run it through a method to determine the mime type of the image file. I would like to take that mime type and set the response headers and send the file.

```<code>.get(function(req,res){
    var fileName = req.params.filename;
    var UPLOAD_PATH = "__dirname + '/../uploads/images/'";

    function getFileType(fileType, callback){
      magic.detectFile(UPLOAD_PATH + fileName, function(err, fileType)
    {
        if (err) return callback(err);
        callback(null, fileType);
      });
    }

    var fileType = getFileType();
    console.log('Get file type', fileType);

    res.setHeader('Content-Type', fileType)
    fs.createReadStream(path.join(UPLOAD_PATH, req.params.filename)).pipe(res)
   });
</code>```

Would like to

Run the function to get the file type

Set the file type

Return that file type into the res.setHeader()

Right now I'm running into an error TypeError: callback is not a function

答:
Define your call back fucntion. Otherwise it will not be defined.

```<code>.get(function(req,res){
    var fileName = req.params.filename;
    var UPLOAD_PATH = "__dirname + '/../uploads/images/'";

function getFileType(fileType, callback){
  magic.detectFile(UPLOAD_PATH + fileName, function(err, fileType)
{
    if (err) return callback(err);
    callback(null, fileType);
  });
}
//Your Call back function defenition
function callback(x, type ){
 // Show him the file type.
}

var fileType = getFileType();
console.log('Get file type', fileType);

res.setHeader('Content-Type', fileType)
fs.createReadStream(path.join(UPLOAD_PATH, req.params.filename)).pipe(res)
</code>```

});

Body:
Having a real difficult time with callbacks. I have a function that will take an image, run it through a method to determine the mime type of the image file. I would like to take that mime type and set the response headers and send the file.

.get(function(req,res){
    var fileName = req.params.filename;
    var UPLOAD_PATH = "__dirname + '/../uploads/images/'";

    function getFileType(fileType, callback){
      magic.detectFile(UPLOAD_PATH + fileName, function(err, fileType)
    {
        if (err) return callback(err);
        callback(null, fileType);
      });
    }

    var fileType = getFileType();
    console.log('Get file type', fileType);

    res.setHeader('Content-Type', fileType)
    fs.createReadStream(path.join(UPLOAD_PATH, req.params.filename)).pipe(res)
   });

Would like to

Run the function to get the file type

Set the file type

Return that file type into the res.setHeader()

Right now I'm running into an error TypeError: callback is not a function

Body:
Define your call back fucntion. Otherwise it will not be defined.

.get(function(req,res){
    var fileName = req.params.filename;
    var UPLOAD_PATH = "__dirname + '/../uploads/images/'";

function getFileType(fileType, callback){
  magic.detectFile(UPLOAD_PATH + fileName, function(err, fileType)
{
    if (err) return callback(err);
    callback(null, fileType);
  });
}
//Your Call back function defenition
function callback(x, type ){
 // Show him the file type.
}

var fileType = getFileType();
console.log('Get file type', fileType);

res.setHeader('Content-Type', fileType)
fs.createReadStream(path.join(UPLOAD_PATH, req.params.filename)).pipe(res)

});


问:
change url structure manual on .htaccess in wordpress
i have a https://example.com/page/?id=123 this type of url and i wont a rule for change this url to https://example.com/page/123/

i have this code in .htaccess file

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</code>```

Can anyone help me?

答:
No need to change the pages URL with .htaccess

Step 1 log into your admin end then go to setting

Step 2 there will be a menu with name permalink

Step 3 click on it and tick the radio button with name post name check image

http://prntscr.com/fh9ry8

the URL will change automatically as you require

Body:
i have a https://example.com/page/?id=123 this type of url and i wont a rule for change this url to https://example.com/page/123/

i have this code in .htaccess file

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Can anyone help me?


问:
how to groupby in dplyr with dataframe containing POSIXlt datatypes in r
I have a dataframe with date type as POSIXlt. When I groupby in dplyr it throws an error.

```<code> delay_time <- vessel_data %>%
   group_by(Service) %>%
   dplyr::summarise(average_time <- mean(diff_pilot_alongside)) %>%
   as.data.frame()
</code>```

It throws following error

```<code>Error in grouped_df_impl(data, unname(vars), drop) :
column 'arrival_pilot_station' has unsupported class : POSIXlt, POSIXt

arrival_pilot_station
"2016-03-21 16:18:00 IST"
"2016-04-01 03:12:00 IST"/
</code>```

what is the work around to this problem ?

答:
We need to convert the column to POSIXct as dplyr doesn't support POSIXlt

```<code>vessel_data %>%
  mutate(arrival_pilot_station = as.POSIXct(arrival_pilot_station)) %>%
  group_by(Service) %>%
  dplyr::summarise(average_time <- mean(diff_pilot_alongside)) %>%
  as.data.frame()
</code>```

Body:
I have a dataframe with date type as POSIXlt. When I groupby in dplyr it throws an error.

 delay_time <- vessel_data %>%
   group_by(Service) %>%
   dplyr::summarise(average_time <- mean(diff_pilot_alongside)) %>%
   as.data.frame()

It throws following error

Error in grouped_df_impl(data, unname(vars), drop) :
column 'arrival_pilot_station' has unsupported class : POSIXlt, POSIXt

arrival_pilot_station
"2016-03-21 16:18:00 IST"
"2016-04-01 03:12:00 IST"/

what is the work around to this problem ?

Body:
We need to convert the column to POSIXct as dplyr doesn't support POSIXlt

vessel_data %>%
  mutate(arrival_pilot_station = as.POSIXct(arrival_pilot_station)) %>%
  group_by(Service) %>%
  dplyr::summarise(average_time <- mean(diff_pilot_alongside)) %>%
  as.data.frame()


问:
How can I convert Iterable <com.datastax.driver.core.Row> to Dataset?
I use Spark 2.0 and Scala 2.11.8.

I have a Cassandra ResultSet from a select query and I want to convert it to a Spark DataFrame or Dataset. How?

I've been trying to use this connector:

```<code>"com.datastax.spark" % "spark-cassandra-connector_2.11" % "2.0.0-RC1"
</code>```

and also later this:

```<code>"com.datastax.spark" % "spark-cassandra-connector_2.11" % "2.0.0-M3"
</code>```

The code:

```<code>import com.datastax.spark.connector._

val sparkConf = new SparkConf().
  setAppName(appName).
  set("spark.cassandra.connection.host", "10.60.50.134").
  set("spark.cassandra.auth.username", "xyz").
  set("spark.cassandra.auth.password", "abc")
val spark = SparkSession.builder().config(sparkConf).getOrCreate()
val rdd = spark.
  sparkContext.
  cassandraTable(keyspace = s"$keyspace", table = s"$table")
rdd.take(10).foreach(println)
</code>```

With both I am getting the following error:

```<code>Exception in thread "main" java.lang.NoSuchMethodError: com.datastax.driver.core.KeyspaceMetadata.getMaterializedViews()Ljava/util/Collection;
    at com.datastax.spark.connector.cql.Schema$.com$datastax$spark$connector$cql$Schema$$fetchTables$1(Schema.scala:281)
    at com.datastax.spark.connector.cql.Schema$$anonfun$com$datastax$spark$connector$cql$Schema$$fetchKeyspaces$1$2.apply(Schema.scala:305)
    at com.datastax.spark.connector.cql.Schema$$anonfun$com$datastax$spark$connector$cql$Schema$$fetchKeyspaces$1$2.apply(Schema.scala:304)
    at scala.collection.TraversableLike$WithFilter$$anonfun$map$2.apply(TraversableLike.scala:683)
    at scala.collection.immutable.HashSet$HashSet1.foreach(HashSet.scala:316)
    at scala.collection.immutable.HashSet$HashTrieSet.foreach(HashSet.scala:972)
    at scala.collection.TraversableLike$WithFilter.map(TraversableLike.scala:682)
    at com.datastax.spark.connector.cql.Schema$.com$datastax$spark$connector$cql$Schema$$fetchKeyspaces$1(Schema.scala:304)
    at com.datastax.spark.connector.cql.Schema$$anonfun$fromCassandra$1.apply(Schema.scala:325)
    at com.datastax.spark.connector.cql.Schema$$anonfun$fromCassandra$1.apply(Schema.scala:322)
    at com.datastax.spark.connector.cql.CassandraConnector$$anonfun$withClusterDo$1.apply(CassandraConnector.scala:122)
    at com.datastax.spark.connector.cql.CassandraConnector$$anonfun$withClusterDo$1.apply(CassandraConnector.scala:121)
    at com.datastax.spark.connector.cql.CassandraConnector$$anonfun$withSessionDo$1.apply(CassandraConnector.scala:111)
    at com.datastax.spark.connector.cql.CassandraConnector$$anonfun$withSessionDo$1.apply(CassandraConnector.scala:110)
    at com.datastax.spark.connector.cql.CassandraConnector.closeResourceAfterUse(CassandraConnector.scala:140)
    at com.datastax.spark.connector.cql.CassandraConnector.withSessionDo(CassandraConnector.scala:110)
    at com.datastax.spark.connector.cql.CassandraConnector.withClusterDo(CassandraConnector.scala:121)
    at com.datastax.spark.connector.cql.Schema$.fromCassandra(Schema.scala:322)
    at com.datastax.spark.connector.cql.Schema$.tableFromCassandra(Schema.scala:342)
    at com.datastax.spark.connector.rdd.CassandraTableRowReaderProvider$class.tableDef(CassandraTableRowReaderProvider.scala:50)
    at com.datastax.spark.connector.rdd.CassandraTableScanRDD.tableDef$lzycompute(CassandraTableScanRDD.scala:60)
    at com.datastax.spark.connector.rdd.CassandraTableScanRDD.tableDef(CassandraTableScanRDD.scala:60)
    at com.datastax.spark.connector.rdd.CassandraTableRowReaderProvider$class.verify(CassandraTableRowReaderProvider.scala:137)
    at com.datastax.spark.connector.rdd.CassandraTableScanRDD.verify(CassandraTableScanRDD.scala:60)
    at com.datastax.spark.connector.rdd.CassandraTableScanRDD.getPartitions(CassandraTableScanRDD.scala:232)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
    at org.apache.spark.rdd.RDD$$anonfun$take$1.apply(RDD.scala:1297)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:358)
    at org.apache.spark.rdd.RDD.take(RDD.scala:1292)
    at com.datastax.spark.connector.rdd.CassandraRDD.take(CassandraRDD.scala:121)
    at com.datastax.spark.connector.rdd.CassandraRDD.take(CassandraRDD.scala:122)
</code>```

答:
You seem to be using a pre-Dataset API of Spark Cassandra Connector as it supports Datasets out of the box (but may require different way of loading data from Cassandra tables).

My recommendation is to re-write/upgrade your code to use Spark Cassandra Connector's Dataset-friendly API.

From Example Changing Cluster/Keyspace Level Properties:

```<code>val df = spark
  .read
  .format("org.apache.spark.sql.cassandra")
  .options(Map( "table" -> "words", "keyspace" -> "test"))
  .load() // This Dataset will use a spark.cassandra.input.size of 128
</code>```

And later in Creating Datasets using Read Commands (highlighting mine):

The most programmatic way to create a Dataset is to invoke a read command on the SparkSession. This will build a DataFrameReader. Specify format as org.apache.spark.sql.cassandra. You can then use options to give a map of Map[String,String] of options as described above. Then finish by calling load to actually get a Dataset. This code is all lazy and will not actually load any data until an action is called.

There is org.apache.spark.sql.cassandra.CassandraSQLRow object that seems to offer a conversion from com.datastax.driver.core.Row to org.apache.spark.sql.cassandra.CassandraSQLRow:

```<code>fromJavaDriverRow(row: com.datastax.driver.core.Row, metaData: CassandraRowMetadata): CassandraSQLRow
</code>```

My limited experience with the Spark Cassandra Connector suggests to use implicit conversions if needed.

```<code>// bring all the implicit goodies from the Spark Cassandra Connector
import com.datastax.spark.connector._
</code>```

Body:
I use Spark 2.0 and Scala 2.11.8.

I have a Cassandra ResultSet from a select query and I want to convert it to a Spark DataFrame or Dataset. How?

I've been trying to use this connector:

"com.datastax.spark" % "spark-cassandra-connector_2.11" % "2.0.0-RC1"

and also later this:

"com.datastax.spark" % "spark-cassandra-connector_2.11" % "2.0.0-M3"

The code:

import com.datastax.spark.connector._

val sparkConf = new SparkConf().
  setAppName(appName).
  set("spark.cassandra.connection.host", "10.60.50.134").
  set("spark.cassandra.auth.username", "xyz").
  set("spark.cassandra.auth.password", "abc")
val spark = SparkSession.builder().config(sparkConf).getOrCreate()
val rdd = spark.
  sparkContext.
  cassandraTable(keyspace = s"$keyspace", table = s"$table")
rdd.take(10).foreach(println)

With both I am getting the following error:

Exception in thread "main" java.lang.NoSuchMethodError: com.datastax.driver.core.KeyspaceMetadata.getMaterializedViews()Ljava/util/Collection;
    at com.datastax.spark.connector.cql.Schema$.com$datastax$spark$connector$cql$Schema$$fetchTables$1(Schema.scala:281)
    at com.datastax.spark.connector.cql.Schema$$anonfun$com$datastax$spark$connector$cql$Schema$$fetchKeyspaces$1$2.apply(Schema.scala:305)
    at com.datastax.spark.connector.cql.Schema$$anonfun$com$datastax$spark$connector$cql$Schema$$fetchKeyspaces$1$2.apply(Schema.scala:304)
    at scala.collection.TraversableLike$WithFilter$$anonfun$map$2.apply(TraversableLike.scala:683)
    at scala.collection.immutable.HashSet$HashSet1.foreach(HashSet.scala:316)
    at scala.collection.immutable.HashSet$HashTrieSet.foreach(HashSet.scala:972)
    at scala.collection.TraversableLike$WithFilter.map(TraversableLike.scala:682)
    at com.datastax.spark.connector.cql.Schema$.com$datastax$spark$connector$cql$Schema$$fetchKeyspaces$1(Schema.scala:304)
    at com.datastax.spark.connector.cql.Schema$$anonfun$fromCassandra$1.apply(Schema.scala:325)
    at com.datastax.spark.connector.cql.Schema$$anonfun$fromCassandra$1.apply(Schema.scala:322)
    at com.datastax.spark.connector.cql.CassandraConnector$$anonfun$withClusterDo$1.apply(CassandraConnector.scala:122)
    at com.datastax.spark.connector.cql.CassandraConnector$$anonfun$withClusterDo$1.apply(CassandraConnector.scala:121)
    at com.datastax.spark.connector.cql.CassandraConnector$$anonfun$withSessionDo$1.apply(CassandraConnector.scala:111)
    at com.datastax.spark.connector.cql.CassandraConnector$$anonfun$withSessionDo$1.apply(CassandraConnector.scala:110)
    at com.datastax.spark.connector.cql.CassandraConnector.closeResourceAfterUse(CassandraConnector.scala:140)
    at com.datastax.spark.connector.cql.CassandraConnector.withSessionDo(CassandraConnector.scala:110)
    at com.datastax.spark.connector.cql.CassandraConnector.withClusterDo(CassandraConnector.scala:121)
    at com.datastax.spark.connector.cql.Schema$.fromCassandra(Schema.scala:322)
    at com.datastax.spark.connector.cql.Schema$.tableFromCassandra(Schema.scala:342)
    at com.datastax.spark.connector.rdd.CassandraTableRowReaderProvider$class.tableDef(CassandraTableRowReaderProvider.scala:50)
    at com.datastax.spark.connector.rdd.CassandraTableScanRDD.tableDef$lzycompute(CassandraTableScanRDD.scala:60)
    at com.datastax.spark.connector.rdd.CassandraTableScanRDD.tableDef(CassandraTableScanRDD.scala:60)
    at com.datastax.spark.connector.rdd.CassandraTableRowReaderProvider$class.verify(CassandraTableRowReaderProvider.scala:137)
    at com.datastax.spark.connector.rdd.CassandraTableScanRDD.verify(CassandraTableScanRDD.scala:60)
    at com.datastax.spark.connector.rdd.CassandraTableScanRDD.getPartitions(CassandraTableScanRDD.scala:232)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
    at org.apache.spark.rdd.RDD$$anonfun$take$1.apply(RDD.scala:1297)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:358)
    at org.apache.spark.rdd.RDD.take(RDD.scala:1292)
    at com.datastax.spark.connector.rdd.CassandraRDD.take(CassandraRDD.scala:121)
    at com.datastax.spark.connector.rdd.CassandraRDD.take(CassandraRDD.scala:122)

Body:
You seem to be using a pre-Dataset API of Spark Cassandra Connector as it supports Datasets out of the box (but may require different way of loading data from Cassandra tables).

My recommendation is to re-write/upgrade your code to use Spark Cassandra Connector's Dataset-friendly API.

From Example Changing Cluster/Keyspace Level Properties:

val df = spark
  .read
  .format("org.apache.spark.sql.cassandra")
  .options(Map( "table" -> "words", "keyspace" -> "test"))
  .load() // This Dataset will use a spark.cassandra.input.size of 128

And later in Creating Datasets using Read Commands (highlighting mine):

The most programmatic way to create a Dataset is to invoke a read command on the SparkSession. This will build a DataFrameReader. Specify format as org.apache.spark.sql.cassandra. You can then use options to give a map of Map[String,String] of options as described above. Then finish by calling load to actually get a Dataset. This code is all lazy and will not actually load any data until an action is called.

There is org.apache.spark.sql.cassandra.CassandraSQLRow object that seems to offer a conversion from com.datastax.driver.core.Row to org.apache.spark.sql.cassandra.CassandraSQLRow:

fromJavaDriverRow(row: com.datastax.driver.core.Row, metaData: CassandraRowMetadata): CassandraSQLRow

My limited experience with the Spark Cassandra Connector suggests to use implicit conversions if needed.

// bring all the implicit goodies from the Spark Cassandra Connector
import com.datastax.spark.connector._


问:
Revision control locking: Is the jury still out?
When I'm online it seems that everyone has agreed that using the exclusive locking workflow in source control is a Bad Thing. All the new revision control systems I see appear to be built for edit and merge workflows, and many don't even support exclusive locks at all.

However, everyone I work with is of the opinion that exclusive locks are a "must have" for any source control system, and working any other way would be a nightmare. Even recent hires from other companies seem to come in with this idea.

My question isn't who is right. I'm pretty sure what answer I'd get to that. My question is, is there really still any debate over this matter? Is there an honest "pro locking" camp out there that makes a serious case? Is any work being done to advance the art of revision control based around the locking model? Or are locking fans flogging a dead horse?

EDIT:
The answers so far have done a good job of explaining why exclusive locks are a good feature to use occasionally. However, I'm talking about promoting a workflow where exclusive locks are used for everything.

答:
If you believe that merges are hard (and while we've come a long way, they can be in some circumstances), and you don't have programmers frequently wanting to edit the same file, exclusive locking isn't necessarily that bad.

I wouldn't use them on an open source project, obviously, but in the corporate world where the rules are stricter and you can walk over to a guy and say "can I break your lock?", it gives visibility into what people are working on and avoids conflicts so they don't have to be resolved later.

If two people really need to work on a file at the same time, often you can branch that file, and so long as the tool makes it clear that that branch needs to be merged back in, you can do that and resolve any conflicts then.

That said, I don't think I want to have to work in an exclusive locking world again.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Darcy Casselman


问:
How to inject a bean to another bean declaration in another class?
```<code>file-a.java

package com.abcd.common;
import com.xyz.HCStrategy;
import com.xyz.DHC;

@Configuration
public class HCConfig {
    @Bean
    public HCStrategy dHC() {
        return new DHC();
    }
}

file-b.java

package com.abcd.app;
public class SCConfig {
   @Bean
   public meow() {
     //I want to call dHC here
   }

}
</code>```

One way is to create an autowire for HCConfig and then use the object to call dHC. However, I want to directly auto wire dHC from file-b and use it without creating an object of HCConfig. I can autowire HCStrategy, but it does not work since it is an import and not my own class.

答:
Try this:</p>

```<code>file-b.java

package com.abcd.app;
@Component
public class SCConfig {
   private final HCStrategy hcStrategy;

   @Autowired
   public SCConfig(HCStrategy hcStrategy){
       this.hcStrategy = hcStrategy;
   }

   public [return type] meow() {
     //you can use here hcStrategy bean
   }

}
</code>```

Body:
file-a.java

package com.abcd.common;
import com.xyz.HCStrategy;
import com.xyz.DHC;

@Configuration
public class HCConfig {
    @Bean
    public HCStrategy dHC() {
        return new DHC();
    }
}

file-b.java

package com.abcd.app;
public class SCConfig {
   @Bean
   public meow() {
     //I want to call dHC here
   }

}

One way is to create an autowire for HCConfig and then use the object to call dHC. However, I want to directly auto wire dHC from file-b and use it without creating an object of HCConfig. I can autowire HCStrategy, but it does not work since it is an import and not my own class.

Body:
Try this:

file-b.java

package com.abcd.app;
@Component
public class SCConfig {
   private final HCStrategy hcStrategy;

   @Autowired
   public SCConfig(HCStrategy hcStrategy){
       this.hcStrategy = hcStrategy;
   }

   public [return type] meow() {
     //you can use here hcStrategy bean
   }

}


问:
How to exclude fields within an object on a specific JAX - RS call?
I have the following Java Person class:

```<code>public class Person {

    private String id;

    private String name = "";

    private String score = "";
}
</code>```

There are currently 3 REST calls within my application, 2 of which will send all 3 fields within the Person object

However in my 3rd call I cannot send the "score" field within the object.

Is there a JAX-RS functionality to exclude this field for this one specific call?

Current JAX-RS Code:

```<code>if (person != null) {
            return ResponseBuilder.anOKResponse().withEntity(person).build();
        } else {
            return ResponseBuilder.notFound().withEntity(PERSON_IS_NULL_ERROR).build();
        }
</code>```

答:
If your app runs on weblogic, then your rest app is based on Jersey which uses moxy as the default message body reader and writer. Please see this blog for detail info to solve your problems.
http://blog.bdoughan.com/2012/04/jaxb-and-unmapped-properties.html</p>

Body:
I have the following Java Person class:

public class Person {

    private String id;

    private String name = "";

    private String score = "";
}

There are currently 3 REST calls within my application, 2 of which will send all 3 fields within the Person object

However in my 3rd call I cannot send the "score" field within the object.

Is there a JAX-RS functionality to exclude this field for this one specific call?

Current JAX-RS Code:

if (person != null) {
            return ResponseBuilder.anOKResponse().withEntity(person).build();
        } else {
            return ResponseBuilder.notFound().withEntity(PERSON_IS_NULL_ERROR).build();
        }


问:
Android Studio : emulator is already running
I am trying to run emulator on my android studio 8.14. When I click run it says it is already running. Any help would be appreciated.

AVD api21 is already running.

If that is not the case, delete the files at /home/sayem/.android/avd/api21.avd/*.lock and try again

答:
Follow the instructions on the error and go to your
   C:\Users\directory\.android\avd/Nexus_5_API_24.avd/*.lock
 and delete all files with the .lock extension and it should work.

ContentLicense: CC BY-SA 4.0


问:
How to modify instance variable from separate AsyncTask
let's say i have an activity with instance variable loadedMovie and a method that executes AsyncTask which is in another file

```<code>class MainActivity:AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

 var loadedMovie: Movie? = null

 ....

 fun loadMovie() {
   val task = LoadMovieTask(this)

   task.execute()
 }
}
</code>```

separate AsyncTask

```<code>class LoadMovieTask(val ctx: Activity) : AsyncTask<Void, Void, Void>() {

  var movie: Movie? = null

  override fun onPreExecute() {
    ....
  }

  // loading information from network
  override fun doInBackground(vararg params: Void?): Void? {
    movie = load()

    return null
  }

  // here i modify views with help of kotlin android extensions
  override fun onPostExecute(result: Void?) {
    ....
  }
}
</code>```

problem is: somehow i can't modify loadedMovie neither from doInBackground (which is ok, because it runs on separate thread) and onPostExecute (which is not ok)

i just type ctx.loadedMovie in onPostExecute and it's not there.. maybe i don't understand something? or maybe there is another way to do it that i'm not aware of

答:
Use this

```<code>class LoadMovieTask(val ctx: MainActivity)
</code>```

instead of

```<code>class LoadMovieTask(val ctx: Activity)
</code>```

MainActivity has the method and not the Android's Activity class itself. So even though you need the context, since you are trying to access the method specific to MainActivity, it is required to pass that

Body:
let's say i have an activity with instance variable loadedMovie and a method that executes AsyncTask which is in another file

class MainActivity:AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

 var loadedMovie: Movie? = null

 ....

 fun loadMovie() {
   val task = LoadMovieTask(this)

   task.execute()
 }
}

separate AsyncTask

class LoadMovieTask(val ctx: Activity) : AsyncTask<Void, Void, Void>() {

  var movie: Movie? = null

  override fun onPreExecute() {
    ....
  }

  // loading information from network
  override fun doInBackground(vararg params: Void?): Void? {
    movie = load()

    return null
  }

  // here i modify views with help of kotlin android extensions
  override fun onPostExecute(result: Void?) {
    ....
  }
}

problem is: somehow i can't modify loadedMovie neither from doInBackground (which is ok, because it runs on separate thread) and onPostExecute (which is not ok)

i just type ctx.loadedMovie in onPostExecute and it's not there.. maybe i don't understand something? or maybe there is another way to do it that i'm not aware of

Body:
Use this

class LoadMovieTask(val ctx: MainActivity)

instead of

class LoadMovieTask(val ctx: Activity)

MainActivity has the method and not the Android's Activity class itself. So even though you need the context, since you are trying to access the method specific to MainActivity, it is required to pass that


问:
authorize.net test declines in test mode
Using Authorize.net in test mode, how I can test "declines"?
If the test mode just approves all my transactions regardless of fake billing addresses ...</p>

答:
Testing to Generate Specific Transaction Results

When testing transaction results in the developer test environment as well as the production environment, you can produce a specific response reason code by submitting a test transaction using a test credit card number designed to generate specific transaction results: Visa test credit card number “4222222222222.” This card number is intended for testing and should only be used for that purpose. Submit the test transaction by either placing the account in Test Mode, or submitting x_test_request=TRUE, with a dollar amount value equal to the response reason code you would like to produce.

For example, to test the AVS response reason code number 27, submit the test transaction with the credit card number “4222222222222” and the amount “27.00.”

To test the AVS or CCV responses in the live environment, you will need to submit live transactions with correct street address, ZIP Code and Card Code information to generate successful responses, and incorrect street address, ZIP Code and Card Code information to generate other responses. You can void successful transactions immediately to prevent live test transactions from being processed. This can be done quickly on the Unsettled Transactions page of the Merchant Interface. It is not possible to test the AVS or CCV responses in the developer test environment. For more information about AVS, see the Merchant Integration Guide at http://www.authorize.net/support/merchant/.


问:
How can I check whether Sim Cards are installed in both sim slots in an android device?
Guys I want to know if there are both the sims available and active in android dual sim phones irrespective of the device OS. I have already checked for few links that gives the result if the device is dual sim or not. But what I want to know is if there are two sim's installed in an android device. Please help me with a code snipnnet</p>

答:
Before API 22 you cannot detect if both the sims are present or not, though you can only check for single sim presence with TelephonyManager class in Android check more on DOCS and here is code snippet as well from  similar answered SO question

From Android API 22

getActiveSubscriptionInfoList will get the SubscriptionInfo(s) of the currently inserted SIM(s). The records will be sorted by getSimSlotIndex() then by getSubscriptionId(). as mentioned on Android Docs


问:
Scraping an alt tag using Python and BeautifulSoup
New to Python, and BeautifulSoup and I am trying to scrape the number of stars that a reviewer leaves a restaurant on Yelp.

So far, I have the following code:

```<code>import requests
from bs4 import BeautifulSoup as soup

url = "https://www.yelp.com/biz/monkey-house-cafe-huntington-beach"
r = requests.get(url)
page_soup = soup(r.content, "lxml")

review_container = page_soup.findAll("div", {"class": "review-content"})
review_container[0]
</code>```

When I run that code in Jupyter Notebook, I get the following, that corresponds to the most recent review:

```<code><div class="review-content">
<div class="biz-rating biz-rating-large clearfix">
<div>
<div class="i-stars i-stars--regular-5 rating-large" title="5.0 star rating">
<img alt="5.0 star rating" class="offscreen" height="303" src="https://s3-media1.fl.yelpcdn.com/assets/srv0/yelp_design_web/41341496d9db/assets/img/stars/stars.png" width="84"/>
</div>
</div>
<span class="rating-qualifier">
    5/10/2017
</span>
</div>
<p lang="en">This place is really fun and cute. I was happy to discover it.. <br/><br/>They also have beer and wine here, which is kind of a nice bonus. The sangria is good..</p>
</div>
</code>```

My question is how can I get the number of stars from each review?

I am thinking that it would be best to scrape the contents of the img alt tag but I am not sure how to do this.

答:
If you want to extract from img alt you can use :

```<code>review_container[0].select('img')[0]['alt'].split()[0]
'5.0'
</code>```

Body:
New to Python, and BeautifulSoup and I am trying to scrape the number of stars that a reviewer leaves a restaurant on Yelp.

So far, I have the following code:

import requests
from bs4 import BeautifulSoup as soup

url = "https://www.yelp.com/biz/monkey-house-cafe-huntington-beach"
r = requests.get(url)
page_soup = soup(r.content, "lxml")

review_container = page_soup.findAll("div", {"class": "review-content"})
review_container[0]

When I run that code in Jupyter Notebook, I get the following, that corresponds to the most recent review:

    5/10/2017

This place is really fun and cute. I was happy to discover it..

They also have beer and wine here, which is kind of a nice bonus. The sangria is good..

My question is how can I get the number of stars from each review?

I am thinking that it would be best to scrape the contents of the img alt tag but I am not sure how to do this.

Body:
If you want to extract from img alt you can use :

review_container[0].select('img')[0]['alt'].split()[0]
'5.0'


答: Since api 22 there is getActiveSubscriptionInfoList() method you can call.</p>

Title: How can I check whether Sim Cards are installed in both sim slots in an android device?

Body: Guys I want to know if there are both the sims available and active in android dual sim phones irrespective of the device OS. I have already checked for few links that gives the result if the device is dual sim or not. But what I want to know is if there are two sim's installed in an android device. Please help me with a code snipnnet