问:
How to resolve a http baddata Angular error?
I am working on an application using Angular in the frontend and J2EE in the backend , I made a form where i have to post data to be saved in the database

  The problem that the post work fine but I cant get the server response after the add ,always i get this error(strangely the error comes in gray color not in red and usually)

Error: [$http:baddata]
  http://errors.angularjs.org/1.6.4/$http/baddata?p0=%7B%22success%22%7D&p1=%7B%7D
      at angular.min.js:6
      at nc (angular.min.js:96)
      at angular.min.js:97
      at q (angular.min.js:7)
      at xd (angular.min.js:97)
      at f (angular.min.js:99)
      at angular.min.js:134
      at m.$digest (angular.min.js:145)
      at m.$apply (angular.min.js:149)
      at l (angular.min.js:102)

Here's the angular code

```<code>$scope.wflow = {
    "worcode": "HELLOoo",
    "wordest": "AVDOSS",
    "worstatus": "ACTIF",
    "worheight": 0,
    "lancode": "EN",
    "worlabel": "Salut monde",
    "wordescription": "Salut monde",
    "size": 0
};
$scope.submitForm = function () {
    console.log(JSON.stringify($scope.wflow));

    $http({
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        url: host + 'api/workflow/add',
        data: $scope.wflow
    }).then(function (response) {
        console.log(response);
    }, function (response) {
        console.log(response);
    });

};
</code>```

And here's the Java one

```<code>@RequestMapping(value = "/add", method = RequestMethod.POST)
 @ResponseBody
 public ResponseEntity<String> addWorkflow(@RequestBody LWflow lworkflow){
  service.addWorkflow(lworkflow);
  return new ResponseEntity<String>("{\"success\"}", HttpStatus.OK);
 }
</code>```

this is the html part if needed

```<code>        <table class="table">
        <tbody>
        <tr>
        <td><b>Code</b></td>
        <td><input type="text" name="worcode" class="form-control" ng-model="wflow.worcode"></td>
        </tr>
        <tr>
        <td><b>Destination</b></td>
        <td><input type="text" name="wordest" class="form-control" ng-model="wflow.wordest"><td>
        </tr>
        <tr>
        <td><b>Status</b></td>
        <td><input type="text" name="worstatus" class="form-control" ng-model="wflow.worstatus"></td>
        </tr>
        <tr>
        <td><b>Height</b></td>
        <td><input type="number" name="worheight" class="form-control" ng-model="wflow.worheight"><td>
        </tr>
        <tr>
        <td><b>Langue</b></td>
        <td><input type="text" name="lancode" class="form-control" ng-model="wflow.lancode"></td>
        </tr>
        <tr>
        <td><b>Label</b></td>
        <td><input type="text" name="worlabel" class="form-control" ng-model="wflow.worlabel"></td>
        </tr>
        <tr>
        <td><b>Description</b></td>
        <td><input type="text" name="wordescription" class="form-control" ng-model="wflow.wordescription"></td>
        </tr>
        <tr>
        <td><b>Taille</b></td>
        <td><input type="number" name="size" class="form-control" ng-model="wflow.size"></td>
        </tr>
        </tbody>
        </table>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save changes</button>
      </div>
      </form>
</code>```

note that the error comes from the errorCallback function

答:
Try This way</p>

```<code> $http({
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        url: host + 'api/workflow/add',
        data: angular.toJson($scope.wflow)
    }).then(function (response) {
        console.log(response);
    }, function (response) {
        console.log(response);
    });
</code>```

Body:
I am working on an application using Angular in the frontend and J2EE in the backend , I made a form where i have to post data to be saved in the database

  The problem that the post work fine but I cant get the server response after the add ,always i get this error(strangely the error comes in gray color not in red and usually)

Error: [$http:baddata]
  http://errors.angularjs.org/1.6.4/$http/baddata?p0=%7B%22success%22%7D&p1=%7B%7D
      at angular.min.js:6
      at nc (angular.min.js:96)
      at angular.min.js:97
      at q (angular.min.js:7)
      at xd (angular.min.js:97)
      at f (angular.min.js:99)
      at angular.min.js:134
      at m.$digest (angular.min.js:145)
      at m.$apply (angular.min.js:149)
      at l (angular.min.js:102)

Here's the angular code

$scope.wflow = {
    "worcode": "HELLOoo",
    "wordest": "AVDOSS",
    "worstatus": "ACTIF",
    "worheight": 0,
    "lancode": "EN",
    "worlabel": "Salut monde",
    "wordescription": "Salut monde",
    "size": 0
};
$scope.submitForm = function () {
    console.log(JSON.stringify($scope.wflow));

    $http({
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        url: host + 'api/workflow/add',
        data: $scope.wflow
    }).then(function (response) {
        console.log(response);
    }, function (response) {
        console.log(response);
    });

};

And here's the Java one

@RequestMapping(value = "/add", method = RequestMethod.POST)
 @ResponseBody
 public ResponseEntity<String> addWorkflow(@RequestBody LWflow lworkflow){
  service.addWorkflow(lworkflow);
  return new ResponseEntity<String>("{\"success\"}", HttpStatus.OK);
 }

this is the html part if needed

        Code
        <input type="text" name="worcode" class="form-control" ng-model="wflow.worcode">

        Destination
        <input type="text" name="wordest" class="form-control" ng-model="wflow.wordest">

        Status
        <input type="text" name="worstatus" class="form-control" ng-model="wflow.worstatus">

        Height
        <input type="number" name="worheight" class="form-control" ng-model="wflow.worheight">

        Langue
        <input type="text" name="lancode" class="form-control" ng-model="wflow.lancode">

        Label
        <input type="text" name="worlabel" class="form-control" ng-model="wflow.worlabel">

        Description
        <input type="text" name="wordescription" class="form-control" ng-model="wflow.wordescription">

        Taille
        <input type="number" name="size" class="form-control" ng-model="wflow.size">

        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save changes</button>

      </form>

note that the error comes from the errorCallback function

Body:
Try This way

 $http({
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        url: host + 'api/workflow/add',
        data: angular.toJson($scope.wflow)
    }).then(function (response) {
        console.log(response);
    }, function (response) {
        console.log(response);
    });


来源: stackexchange

问:
Mongodb find distinct count with condition
How to have to select in mongodb.

```<code>Select room(distinct), count(where read =1)
from chat
where from = "1" or to ="1"
</code>```

This is my json

```<code>{
    "_id" : ObjectId("595da6052008fc2213db32f6"),
    "room" : "1_40",
    "from" : "1",
    "to" : "40",
    "user_name" : "Tran Cot",
    "mes" : "hgfd",
    "time" : 1499309573832,
    "read" : 1
}
</code>```

答:
if you want total read messages for each room..

use aggregation

updated

```<code>db.chat.aggregate([
  { $match: { $or: [{ from: "41" }, { to: "41" }] } },
  { $group: {
    _id: "$room",
    count: {
      $sum: {
        $cond: { if: $eq: ["$read", false], then: 1, else: 0 }
      }
    }
  }}
]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to have to select in mongodb.

Select room(distinct), count(where read =1)
from chat
where from = "1" or to ="1"

This is my json

{
    "_id" : ObjectId("595da6052008fc2213db32f6"),
    "room" : "1_40",
    "from" : "1",
    "to" : "40",
    "user_name" : "Tran Cot",
    "mes" : "hgfd",
    "time" : 1499309573832,
    "read" : 1
}

Body:
if you want total read messages for each room..

use aggregation

updated

db.chat.aggregate([
  { $match: { $or: [{ from: "41" }, { to: "41" }] } },
  { $group: {
    _id: "$room",
    count: {
      $sum: {
        $cond: { if: $eq: ["$read", false], then: 1, else: 0 }
      }
    }
  }}
]);


问:
How to make enemy meter detector in libgdx?
In my top down game, I have an enemy detector to detect the enemy is near.My problem is how can I create animate my meter bar with transition? I'm to new to this framework. Thank's and Advance

When player detect the enemy near, the meter bar will animate just like the image screen shot bellow

Without enemy

My code:

```<code>    //detector
    meter_bar = new Texture("meter_bar.png");
    myTextureRegion = new TextureRegion(meter_bar);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    actormeter_bar = new Image(myTexRegionDrawable);
    actormeter_bar.setPosition(200,1005);
    stage.addActor(actormeter_bar);

    meter = new Texture("meter.png");
    myTextureRegion = new TextureRegion(meter);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    actormetter = new Image(myTexRegionDrawable);
    actormetter.setPosition(190,990);
    stage.addActor( actormetter);
</code>```

Player Movement (forward):

```<code>//right_control
    right_paw = new Texture(Gdx.files.internal("right_paw.png"));
    myTextureRegion = new TextureRegion(right_paw);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    moveForward = new ImageButton(myTexRegionDrawable); //Set the button up
    moveForward.getStyle().imageUp = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("right_paw.png"))));
    //the hover
    moveForward.getStyle().imageDown = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("right_paw-hover.png"))));
    moveForward.setPosition(520,110);
    stage.addActor(moveForward); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    moveForward.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Right Button Pressed");
            progressKnobX = progressKnobX + 4;

            actorprogressknob.setX(progressKnobX); // x-position to move to
            if(progressKnobX > 418 ) progressKnobX= 418 ;
            music.play();
            motionState=MotionState.NONE;
        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            motionState=MotionState.UP;
            return true;
        }
    });
    stage.addActor(moveForward);
</code>```

EnemySprite Movement:

```<code> zombie = new Texture(Gdx.files.internal("enemy/ZombieSprite.png"));
    zombiesprite = new Sprite(zombie);
    zombieenemy = new Rectangle();
    zombieenemy.setWidth(zombiesprite.getWidth());

    zombieenemy = zombiesprite.getBoundingRectangle();
    zombieenemy.x = zombieX;
    zombieenemy.y = zombieY;
    TextureRegion[][] zom = TextureRegion.split(zombie, zombie.getWidth() / Zombie_FRAME_COLS, zombie.getHeight() / Zombie_FRAME_ROWS);
    TextureRegion[] zwalkFrames  = new TextureRegion[Zombie_FRAME_COLS * Zombie_FRAME_ROWS];
    index = 0;
    for (int i = 0; i < Zombie_FRAME_ROWS; i++) {
        for (int j = 0; j < Zombie_FRAME_COLS; j++) {
            zwalkFrames[index++] = zom[i][j];
        }
    }
    zombiewalkAnimation = new Animation<TextureRegion>(0.120f, zwalkFrames);
</code>```

MoveForward Button Function:

```<code>//button functions
MotionState motionState=MotionState.NONE;
enum MotionState {
    NONE {
        @Override
        public boolean update(Rectangle player) {
            return true;
        }
    },
    UP {
        @Override
        public boolean update(Rectangle player) {
            player.y += 300 * Gdx.graphics.getDeltaTime();
            return false;
        }
    },
    DOWN{
        @Override
        public boolean update(Rectangle player) {
            player.y -= 300 * Gdx.graphics.getDeltaTime();
            return false;
        }
    },
    LEFT{
        @Override
        public boolean update(Rectangle player)  {
            player.x -= 100 * Gdx.graphics.getDeltaTime();
            return false;
        }
    },
    RIGHT{
        @Override
        public boolean update(Rectangle player) {
            player.x  += 100 * Gdx.graphics.getDeltaTime();
            return false;
        }
    };
    public abstract boolean update(Rectangle player);
}
</code>```

Render

```<code>    if(Gdx.input.isKeyPressed(Input.Keys.DOWN)) motionState = MotionState.DOWN;
    if(Gdx.input.isKeyPressed(Input.Keys.UP)) motionState=MotionState.UP;
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) motionState=MotionState.LEFT;
    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) motionState=MotionState.RIGHT;

    if(motionState.update(player)) motionState=MotionState.NONE;

    if(player.y> 1910){
        zombieenemy.y -= 60 * Gdx.graphics.getDeltaTime();
    }
</code>```

答:
I use the Stack class to create the Meter class. The meter image needs to be transparent and the bar image needs to be an animation. Stack Actor can overlap the images and render it on top of each other. Here is the Meter class:

```<code>public class Meter extends Stack {

    private Animation<Drawable> animation;
    private Image bar;

    public Meter( Skin skin ){

        Array<Drawable> drawables = new Array<Drawable>();

        for ( int i = 0; i < TestScreen.LENGTH; ++i ){
            drawables.add( skin.getDrawable( TestScreen.BAR + Integer.toString( i ) ) );
        }

        animation = new Animation<Drawable>( 1f, drawables );
        bar = new Image( animation.getKeyFrame( 0f ) );
        addActor( bar );
        addActor( new Image( skin.getDrawable( TestScreen.METER ) ) );
        setTouchable( Touchable.disabled );
    }

    /**
     * Set the "hotness" of the meter.
     * @param value float between 0 and 1
     */
    public void setValue( float value ){

        // actions are the default way to animate simple effects to the actors
        // this is just to add a pop in effect when you have a really smooth animation this isn't really necessary
        bar.addAction( Actions.sequence(
            Actions.alpha( 0 ),
            Actions.fadeIn( 0.01f, Interpolation.smooth )
        ) );

        // set the new image to the value percentage
        bar.setDrawable( animation.getKeyFrame( value * animation.getAnimationDuration() ) );
        bar.setSize( bar.getPrefWidth(), bar.getPrefHeight() );
    }
}
</code>```

Stage class that uses skin to set the actors.

```<code>public class MyStage extends Stage {

    public Meter meter;

    public MyStage( Skin skin ){

        super();

        meter = new Meter( skin );

        Table table = new Table( skin );
        table.setFillParent( true );
        table.setOrigin( Align.top );
        table.add( meter ).width( (1/10f) * Gdx.graphics.getWidth() );

        addActor( table );
    }
}
</code>```

Best practice is to create a skin and put all the ui resources in there. Load from file in a TextureAtlas object and pass that object into the skin. I created a simple animation this doesn't scale correctly its just as an example. In the screen object or game object:

```<code>private MyStage myStage;

@Override
public void show(){

    Skin skin = new Skin();
    skin.add( METER, new TextureRegionDrawable( new TextureRegion( meter_texture ) ), Drawable.class );

    float w = meter_bar_texture.getWidth() / (float) LENGTH;

    for ( int i = 0; i < LENGTH; ++i ){
        TextureRegion region = new TextureRegion( meter_bar_texture, 0, 0, (int)(i * w), meter_bar_texture.getHeight() );

        skin.add( BAR + Integer.toString( i ), new TextureRegionDrawable( region ), Drawable.class );
    }

    this.myStage = new MyStage( skin );
}

@Override
public void hide() {

    super.hide();

    this.meter_bar_texture.dispose();
    this.meter_texture.dispose();
}

@Override
public void update( float delta ) {

    if ( dangerIncreased() && value < 100 ){
        danger += 5;

        this.myStage.meter.setValue( danger / 100f );
    } else if ( dangerDecreased() && danger > 0 ){
        danger -= 5;

        this.myStage.meter.setValue( danger / 100f );
    }

    this.myStage.act( delta );
}

public static final String METER = "meter";
public static final String BAR = "bar";
public static final int LENGTH = 10;
</code>```

Body:
In my top down game, I have an enemy detector to detect the enemy is near.My problem is how can I create animate my meter bar with transition? I'm to new to this framework. Thank's and Advance

When player detect the enemy near, the meter bar will animate just like the image screen shot bellow

Without enemy

My code:

    //detector
    meter_bar = new Texture("meter_bar.png");
    myTextureRegion = new TextureRegion(meter_bar);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    actormeter_bar = new Image(myTexRegionDrawable);
    actormeter_bar.setPosition(200,1005);
    stage.addActor(actormeter_bar);

    meter = new Texture("meter.png");
    myTextureRegion = new TextureRegion(meter);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    actormetter = new Image(myTexRegionDrawable);
    actormetter.setPosition(190,990);
    stage.addActor( actormetter);

Player Movement (forward):

//right_control
    right_paw = new Texture(Gdx.files.internal("right_paw.png"));
    myTextureRegion = new TextureRegion(right_paw);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    moveForward = new ImageButton(myTexRegionDrawable); //Set the button up
    moveForward.getStyle().imageUp = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("right_paw.png"))));
    //the hover
    moveForward.getStyle().imageDown = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("right_paw-hover.png"))));
    moveForward.setPosition(520,110);
    stage.addActor(moveForward); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    moveForward.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Right Button Pressed");
            progressKnobX = progressKnobX + 4;

            actorprogressknob.setX(progressKnobX); // x-position to move to
            if(progressKnobX > 418 ) progressKnobX= 418 ;
            music.play();
            motionState=MotionState.NONE;
        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            motionState=MotionState.UP;
            return true;
        }
    });
    stage.addActor(moveForward);

EnemySprite Movement:

 zombie = new Texture(Gdx.files.internal("enemy/ZombieSprite.png"));
    zombiesprite = new Sprite(zombie);
    zombieenemy = new Rectangle();
    zombieenemy.setWidth(zombiesprite.getWidth());

    zombieenemy = zombiesprite.getBoundingRectangle();
    zombieenemy.x = zombieX;
    zombieenemy.y = zombieY;
    TextureRegion[][] zom = TextureRegion.split(zombie, zombie.getWidth() / Zombie_FRAME_COLS, zombie.getHeight() / Zombie_FRAME_ROWS);
    TextureRegion[] zwalkFrames  = new TextureRegion[Zombie_FRAME_COLS * Zombie_FRAME_ROWS];
    index = 0;
    for (int i = 0; i < Zombie_FRAME_ROWS; i++) {
        for (int j = 0; j < Zombie_FRAME_COLS; j++) {
            zwalkFrames[index++] = zom[i][j];
        }
    }
    zombiewalkAnimation = new Animation<TextureRegion>(0.120f, zwalkFrames);

MoveForward Button Function:

//button functions
MotionState motionState=MotionState.NONE;
enum MotionState {
    NONE {
        @Override
        public boolean update(Rectangle player) {
            return true;
        }
    },
    UP {
        @Override
        public boolean update(Rectangle player) {
            player.y += 300 * Gdx.graphics.getDeltaTime();
            return false;
        }
    },
    DOWN{
        @Override
        public boolean update(Rectangle player) {
            player.y -= 300 * Gdx.graphics.getDeltaTime();
            return false;
        }
    },
    LEFT{
        @Override
        public boolean update(Rectangle player)  {
            player.x -= 100 * Gdx.graphics.getDeltaTime();
            return false;
        }
    },
    RIGHT{
        @Override
        public boolean update(Rectangle player) {
            player.x  += 100 * Gdx.graphics.getDeltaTime();
            return false;
        }
    };
    public abstract boolean update(Rectangle player);
}

Render

    if(Gdx.input.isKeyPressed(Input.Keys.DOWN)) motionState = MotionState.DOWN;
    if(Gdx.input.isKeyPressed(Input.Keys.UP)) motionState=MotionState.UP;
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) motionState=MotionState.LEFT;
    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) motionState=MotionState.RIGHT;

    if(motionState.update(player)) motionState=MotionState.NONE;

    if(player.y> 1910){
        zombieenemy.y -= 60 * Gdx.graphics.getDeltaTime();
    }

Body:
I use the Stack class to create the Meter class. The meter image needs to be transparent and the bar image needs to be an animation. Stack Actor can overlap the images and render it on top of each other. Here is the Meter class:

public class Meter extends Stack {

    private Animation<Drawable> animation;
    private Image bar;

    public Meter( Skin skin ){

        Array<Drawable> drawables = new Array<Drawable>();

        for ( int i = 0; i < TestScreen.LENGTH; ++i ){
            drawables.add( skin.getDrawable( TestScreen.BAR + Integer.toString( i ) ) );
        }

        animation = new Animation<Drawable>( 1f, drawables );
        bar = new Image( animation.getKeyFrame( 0f ) );
        addActor( bar );
        addActor( new Image( skin.getDrawable( TestScreen.METER ) ) );
        setTouchable( Touchable.disabled );
    }

    /**
     * Set the "hotness" of the meter.
     * @param value float between 0 and 1
     */
    public void setValue( float value ){

        // actions are the default way to animate simple effects to the actors
        // this is just to add a pop in effect when you have a really smooth animation this isn't really necessary
        bar.addAction( Actions.sequence(
            Actions.alpha( 0 ),
            Actions.fadeIn( 0.01f, Interpolation.smooth )
        ) );

        // set the new image to the value percentage
        bar.setDrawable( animation.getKeyFrame( value * animation.getAnimationDuration() ) );
        bar.setSize( bar.getPrefWidth(), bar.getPrefHeight() );
    }
}

Stage class that uses skin to set the actors.

public class MyStage extends Stage {

    public Meter meter;

    public MyStage( Skin skin ){

        super();

        meter = new Meter( skin );

        Table table = new Table( skin );
        table.setFillParent( true );
        table.setOrigin( Align.top );
        table.add( meter ).width( (1/10f) * Gdx.graphics.getWidth() );

        addActor( table );
    }
}

Best practice is to create a skin and put all the ui resources in there. Load from file in a TextureAtlas object and pass that object into the skin. I created a simple animation this doesn't scale correctly its just as an example. In the screen object or game object:

private MyStage myStage;

@Override
public void show(){

    Skin skin = new Skin();
    skin.add( METER, new TextureRegionDrawable( new TextureRegion( meter_texture ) ), Drawable.class );

    float w = meter_bar_texture.getWidth() / (float) LENGTH;

    for ( int i = 0; i < LENGTH; ++i ){
        TextureRegion region = new TextureRegion( meter_bar_texture, 0, 0, (int)(i * w), meter_bar_texture.getHeight() );

        skin.add( BAR + Integer.toString( i ), new TextureRegionDrawable( region ), Drawable.class );
    }

    this.myStage = new MyStage( skin );
}

@Override
public void hide() {

    super.hide();

    this.meter_bar_texture.dispose();
    this.meter_texture.dispose();
}

@Override
public void update( float delta ) {

    if ( dangerIncreased() && value < 100 ){
        danger += 5;

        this.myStage.meter.setValue( danger / 100f );
    } else if ( dangerDecreased() && danger > 0 ){
        danger -= 5;

        this.myStage.meter.setValue( danger / 100f );
    }

    this.myStage.act( delta );
}

public static final String METER = "meter";
public static final String BAR = "bar";
public static final int LENGTH = 10;


问:
"fatal: ref HEAD is not a symbolic ref" during interactive git rebase
Got 3 commits - one proper, and then two silly cleanup ones, typos etc. So I want to squash them. Fire away:

```<code>git rebase -i HEAD~3
</code>```

Sounds simple, and it should work - I've tried it after running into a problem, in a brand new repo, and it works as expected. Editor shows 3 commits, pick the top, squash the other two, save and quit, done. If I run in verbose mode, I see more details - git enters the detached HEAD state by checking out the 1st commit I 'picked', then does 'Rebasing 2/3' and 'Rebasing 3/3', apparently creating some temp commits along the way -- and then a success message; editor pops up again at some point, offering me to change the commit message. All's good.

But same command dies in a work repo! 3 commits in an editor, pick-squash-squash.. but this time, I don't see 'Rebasing 2/3', instead the very first line after 'HEAD is now at my-SHA-1', it runs into a fatal!

```<code>HEAD is now at 48a6c3d... <commit message>
fatal: ref HEAD is not a symbolic ref
</code>```

But why would git expect HEAD to be a symbolic ref? Rebase process does detach HEAD - same as I see in my exploratory example - so why then the fatal in this second example, but not in the first one? cat .git/HEAD give me the SHA1 of the commit I've 'picked'...

I've spend several hours reading and researching, but something's just not right here, and I can't find what it is! I suspect that maybe some hooks are responsible (know little about them, and know the problematic repo does have some). Thank you for your consideration in answering this!

答:
Your "work" repo is probably broken somehow. See I can't git rebase --interactive anymore for details.

I'd try running git status in your work repo to figure out what is going on. Then e.g. git rebase --abort, git merge --abort or something like that may be required.

I'd run git fsck, too.

After your repo and working directory is good to go, interactive rebase should work fine. Also note that you may need git rebase --root --preserve-merges ... in case you want to touch the first commit in the repo.

ContentLicense: CC BY-SA 4.0

Body:
Got 3 commits - one proper, and then two silly cleanup ones, typos etc. So I want to squash them. Fire away:

git rebase -i HEAD~3

Sounds simple, and it should work - I've tried it after running into a problem, in a brand new repo, and it works as expected. Editor shows 3 commits, pick the top, squash the other two, save and quit, done. If I run in verbose mode, I see more details - git enters the detached HEAD state by checking out the 1st commit I 'picked', then does 'Rebasing 2/3' and 'Rebasing 3/3', apparently creating some temp commits along the way -- and then a success message; editor pops up again at some point, offering me to change the commit message. All's good.

But same command dies in a work repo! 3 commits in an editor, pick-squash-squash.. but this time, I don't see 'Rebasing 2/3', instead the very first line after 'HEAD is now at my-SHA-1', it runs into a fatal!

HEAD is now at 48a6c3d... <commit message>
fatal: ref HEAD is not a symbolic ref

But why would git expect HEAD to be a symbolic ref? Rebase process does detach HEAD - same as I see in my exploratory example - so why then the fatal in this second example, but not in the first one? cat .git/HEAD give me the SHA1 of the commit I've 'picked'...

I've spend several hours reading and researching, but something's just not right here, and I can't find what it is! I suspect that maybe some hooks are responsible (know little about them, and know the problematic repo does have some). Thank you for your consideration in answering this!


问:
value collectAsMap is not a member of org.apache.spark.rdd.RDD
I am trying to use collectAsMap() in the following statement:

```<code>import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.rdd.RDD
...
documents_input.
  filter(_ != documents_header).
  map(_.split(",")).
  map(Document.parse(_)).
  keyBy((_.id)).collectAsMap()
</code>```

However I am getting the following error:

```<code>value collectAsMap is not a member of org.apache.spark.rdd.RDD[(Int, `com.codependent.MyApp.Document)]`
</code>```

Any idea why or how I could turn the Array into a Map?

答:
Fixed after updating the imports as Ram Ghadiyaram suggested:</p>

```<code>import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.rdd.RDD
</code>```

Body:
I am trying to use collectAsMap() in the following statement:

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.rdd.RDD
...
documents_input.
  filter(_ != documents_header).
  map(_.split(",")).
  map(Document.parse(_)).
  keyBy((_.id)).collectAsMap()

However I am getting the following error:

value collectAsMap is not a member of org.apache.spark.rdd.RDD[(Int, `com.codependent.MyApp.Document)]`

Any idea why or how I could turn the Array into a Map?

Body:
Fixed after updating the imports as Ram Ghadiyaram suggested:

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.rdd.RDD


问:
How to convert types when reading data from Elasticsearch using elasticsearch-spark in SPARK
When i try to read data from elasticsearch using the esRDD("index") function in elasticsearch-spark, i get the results in type org.apache.spark.rdd.RDD[(String, scala.collection.Map[String,AnyRef])]. And when i check the values, they are all type AnyRef. However, i saw in on ES site, it says :

elasticsearch-hadoop automatically converts Spark built-in types to Elasticsearch types (and back)

My dependencies are:

```<code>scalaVersion := "2.11.8"
libraryDependencies += "org.apache.spark" %% "spark-core" % "2.1.0"
libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.1.0"
libraryDependencies += "org.apache.spark" %% "spark-mllib" % "2.1.0"
libraryDependencies += "org.elasticsearch" % "elasticsearch-spark-20_2.11" % "5.4.0"
</code>```

Do I miss something? And how can i convert the types in a convenient way?

答:
OK, I found a solution.
If you use esRDD, all types information are lost.

It is better if we use:

```<code>val df = sparkSession.read.format("org.elasticsearch.spark.sql").option("es.read.field.as.array.include", "").load("index")
</code>```

You can config es in option, if you have done it before, option can be ignored.

The data returend is in DataFrame, and the data types are preserved (converted to sql.DataTypes) in schema as long as the conversion is supported by elasticsearch-spark.

And now you can do whatever you want.

Body:
When i try to read data from elasticsearch using the esRDD("index") function in elasticsearch-spark, i get the results in type org.apache.spark.rdd.RDD[(String, scala.collection.Map[String,AnyRef])]. And when i check the values, they are all type AnyRef. However, i saw in on ES site, it says :

elasticsearch-hadoop automatically converts Spark built-in types to Elasticsearch types (and back)

My dependencies are:

scalaVersion := "2.11.8"
libraryDependencies += "org.apache.spark" %% "spark-core" % "2.1.0"
libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.1.0"
libraryDependencies += "org.apache.spark" %% "spark-mllib" % "2.1.0"
libraryDependencies += "org.elasticsearch" % "elasticsearch-spark-20_2.11" % "5.4.0"

Do I miss something? And how can i convert the types in a convenient way?

Body:
OK, I found a solution.
If you use esRDD, all types information are lost.

It is better if we use:

val df = sparkSession.read.format("org.elasticsearch.spark.sql").option("es.read.field.as.array.include", "").load("index")

You can config es in option, if you have done it before, option can be ignored.

The data returend is in DataFrame, and the data types are preserved (converted to sql.DataTypes) in schema as long as the conversion is supported by elasticsearch-spark.

And now you can do whatever you want.


问:
How to pass a list of coordinates to the default google Map Application?
From my app i am opening the default google map app. Here is how i am doing it.

```<code>String uri = String.format(Locale.ENGLISH, "geo:0,0?q=%f,%f(%s)",
                locationList.get(1).getLatitude(), locationList.get(1).getLongitude(),"My location");
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        Log.i(TAG, "Uri is "+ uri);
        this.startActivity(intent);
</code>```

This is working fine. But is it possible to pass a list of coordinates and plot them all so i could create a path?

答:
Here try this:

```<code>String destination = locationList.get(1).getLatitude()+","
                    +locationList.get(1).getLongitude();
            Uri gmmIntentUri = Uri.parse("google.navigation:q="+destination+"&mode=d");
            Log.e(TAG,"Intent uri : "+gmmIntentUri.toString());
            Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
            mapIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mapIntent.setPackage("com.google.android.apps.maps");
            this.startActivity(mapIntent);
</code>```

this will open map in navigation mode from your current location to the specified destination.

you can have a look at the below link to specify way points between your source and destination:
https://developers.google.com/maps/documentation/urls/android-intents
https://developers.google.com/maps/documentation/urls/guide

Let me know if you have any doubts.

Body:
From my app i am opening the default google map app. Here is how i am doing it.

String uri = String.format(Locale.ENGLISH, "geo:0,0?q=%f,%f(%s)",
                locationList.get(1).getLatitude(), locationList.get(1).getLongitude(),"My location");
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        Log.i(TAG, "Uri is "+ uri);
        this.startActivity(intent);

This is working fine. But is it possible to pass a list of coordinates and plot them all so i could create a path?

Body:
Here try this:

String destination = locationList.get(1).getLatitude()+","
                    +locationList.get(1).getLongitude();
            Uri gmmIntentUri = Uri.parse("google.navigation:q="+destination+"&mode=d");
            Log.e(TAG,"Intent uri : "+gmmIntentUri.toString());
            Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
            mapIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mapIntent.setPackage("com.google.android.apps.maps");
            this.startActivity(mapIntent);

this will open map in navigation mode from your current location to the specified destination.

you can have a look at the below link to specify way points between your source and destination:
https://developers.google.com/maps/documentation/urls/android-intents
https://developers.google.com/maps/documentation/urls/guide

Let me know if you have any doubts.


问:
Form validation with jquery - return false
Can some one tell my why the folowing code doesn't work. It alerts as it should. But it return true afterwards, even if a field is empty.</p>

```<code><form id="theform" method="post" action="mailme.php">
<input id="field1" name="a" value="field1" type="text" />
<input id="field2" name="b" value="field2" type="text" />
<input id="field3" name="c" value="field3" type="text" />
<input id="field4" name="d" value="field4" type="text" />

<input type="submit" />
</form>
<script>
$('#theform').submit(function(){
    $('#theform input[type=text]').each(function(n,element){
        if ($(element).val()=='') {
             alert('The ' + element.id+' must have a value');
             return false;
        }
    });
    return true;
});

</script>
</code>```

答: Your two return statements are in different contexts, so your each function returns false, but that is not the same as a return statement for your submit function, which will always return true on the last line.</p>

ContentLicense: CC BY-SA 2.5

Body:
Can some one tell my why the folowing code doesn't work. It alerts as it should. But it return true afterwards, even if a field is empty.

<form id="theform" method="post" action="mailme.php">
<input id="field1" name="a" value="field1" type="text" />
<input id="field2" name="b" value="field2" type="text" />
<input id="field3" name="c" value="field3" type="text" />
<input id="field4" name="d" value="field4" type="text" />

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


问:
Retrieve contacts of facebook into my application and show it in table view?
I have to show the contacts from facebook into my application.I am not getting how to do this.
I am using this code but not getting any contact list. I am getting this type in the array but not getting any facebook list of contacts.

```<code><__NSArrayM 0x608000457430>(
<CPRecord: 0x7fd37d5c3290 ABPerson>,
<CPRecord: 0x7fd37d5c34c0 ABPerson>,
<CPRecord: 0x7fd37d5c3d60 ABPerson>,
<CPRecord: 0x7fd37d5c3f90 ABPerson>,
<CPRecord: 0x7fd37d5c42e0 ABPerson>,
<CPRecord: 0x7fd37d5c4630 ABPerson>,
<CPRecord: 0x7fd37d5c4980 ABPerson>,
<CPRecord: 0x7fd37d5c4df0 ABPerson>,
<CPRecord: 0x7fd37d5c5140 ABPerson>,
<CPRecord: 0x7fd37d5c5490 ABPerson>,
<CPRecord: 0x7fd37d5c57e0 ABPerson>,
<CPRecord: 0x7fd37d5c5c50 ABPerson>,
<CPRecord: 0x7fd37d5c5fa0 ABPerson>,
<CPRecord: 0x7fd37d5c62f0 ABPerson>,
<CPRecord: 0x7fd37d5c6640 ABPerson>,
<CPRecord: 0x7fd37d404e10 ABPerson>,
<CPRecord: 0x7fd37d450e00 ABPerson>,
<CPRecord: 0x7fd37d460370 ABPerson>,
<CPRecord: 0x7fd37d460930 ABPerson>,
<CPRecord: 0x7fd37d44f730 ABPerson>,
<CPRecord: 0x7fd37d44f960 ABPerson>,
<CPRecord: 0x7fd37d460ff0 ABPerson>,
<CPRecord: 0x7fd37d461460 ABPerson>,
<CPRecord: 0x7fd37d4617b0 ABPerson>,
<CPRecord: 0x7fd37d461b00 ABPerson>,
<CPRecord: 0x7fd37d461fa0 ABPerson>,
<CPRecord: 0x7fd37d4624f0 ABPerson>,
</code>```

Please help.

```<code>if (&ABAddressBookRequestAccessWithCompletion) { // if in iOS 6

        // Request authorization to Address Book
        ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);

        if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
            ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
                [self getFacebookContacts:addressBookRef];
            });
        }
        else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
            [self getFacebookContacts:addressBookRef];
        }
        else {
            // The user has previously denied access
            // Send an alert telling user to change privacy setting in settings app
        }
    }
    else{ // if not in iOS 6

        ABAddressBookRef addressBookRef = ABAddressBookCreate();
        [self getFacebookContacts:addressBookRef];
        NSLog(@"Not ios 6");
    }

-(void) getFacebookContacts:(ABAddressBookRef) addressBookRef
{
    CFArrayRef allContacts = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    CFIndex contactCount = CFArrayGetCount(allContacts);
    // Traverse through contacts
    for(int i=0; i<contactCount; i++)
    {
        ABRecordRef ref = CFArrayGetValueAtIndex(allContacts, i);
        //Check if contact has social profile
        ABMultiValueRef social = ABRecordCopyValue(( ABRecordRef)ref, kABPersonSocialProfileProperty);
        if (social) {
            // *****   This is coming as 0     **********
            CFIndex count = ABMultiValueGetCount(social);
            for (int i = 0 ; i < count; i++) {
                CFDictionaryRef socialValue = ABMultiValueCopyValueAtIndex(social, i);
                if(CFStringCompare( CFDictionaryGetValue(socialValue, kABPersonSocialProfileServiceKey), kABPersonSocialProfileServiceFacebook, 0)==kCFCompareEqualTo) {
                    NSLog(@"Facebook Contact %d : %@",i, (NSString*) CFDictionaryGetValue(socialValue, kABPersonSocialProfileUserIdentifierKey));
                }
            }
        }
    }
}
</code>```

答:
Didn't run the below code, but try and make a few changes as required.

```<code>-(void) getFacebookContacts:(ABAddressBookRef) addressBookRef
{
    CFArrayRef allContacts =
    ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    CFIndex contactCount = CFArrayGetCount(allContacts);
    CFStringRef str1 = CFSTR("FACEBOOK");

    // Traverse through contacts
    for(int i=0; i<contactCount; i++)
    {
        ABRecordRef ref = CFArrayGetValueAtIndex(allContacts, i);
        //Check if contact has social profile
        ABMultiValueRef social = ABRecordCopyValue(( ABRecordRef)ref, kABPersonSocialProfileProperty);

        if (social) {
        for (NSInteger i=0 ; i < ABMultiValueGetCount(social); i++) {
            CFDictionaryRef instantMessageValue = ABMultiValueCopyValueAtIndex(social, i);
            CFStringRef instantMessageString = CFDictionaryGetValue(instantMessageValue, kABPersonInstantMessageServiceKey);
            // Check if service is FACEBOOK
            if (CFStringCompare(instantMessageString, str1, 0) == kCFCompareEqualTo) {
            returnValue = YES;

            NSDictionary * powerDic = (__bridge NSDictionary *)instantMessageValue;
            NSLog(@"%@", [powerDic valueForKey:@"service"]);
            NSLog(@"%@", [powerDic valueForKey:@"url"]);
            NSLog(@"%@", [powerDic valueForKey:@"username"]);
            NSLog(@"%@", [powerDic valueForKey:@"displayname"]);

        }
      }
    }
}
</code>```

Hope this helps :)
EDIT: Tested and working.

Body:
I have to show the contacts from facebook into my application.I am not getting how to do this.
I am using this code but not getting any contact list. I am getting this type in the array but not getting any facebook list of contacts.

<__NSArrayM 0x608000457430>(
<CPRecord: 0x7fd37d5c3290 ABPerson>,
<CPRecord: 0x7fd37d5c34c0 ABPerson>,
<CPRecord: 0x7fd37d5c3d60 ABPerson>,
<CPRecord: 0x7fd37d5c3f90 ABPerson>,
<CPRecord: 0x7fd37d5c42e0 ABPerson>,
<CPRecord: 0x7fd37d5c4630 ABPerson>,
<CPRecord: 0x7fd37d5c4980 ABPerson>,
<CPRecord: 0x7fd37d5c4df0 ABPerson>,
<CPRecord: 0x7fd37d5c5140 ABPerson>,
<CPRecord: 0x7fd37d5c5490 ABPerson>,
<CPRecord: 0x7fd37d5c57e0 ABPerson>,
<CPRecord: 0x7fd37d5c5c50 ABPerson>,
<CPRecord: 0x7fd37d5c5fa0 ABPerson>,
<CPRecord: 0x7fd37d5c62f0 ABPerson>,
<CPRecord: 0x7fd37d5c6640 ABPerson>,
<CPRecord: 0x7fd37d404e10 ABPerson>,
<CPRecord: 0x7fd37d450e00 ABPerson>,
<CPRecord: 0x7fd37d460370 ABPerson>,
<CPRecord: 0x7fd37d460930 ABPerson>,
<CPRecord: 0x7fd37d44f730 ABPerson>,
<CPRecord: 0x7fd37d44f960 ABPerson>,
<CPRecord: 0x7fd37d460ff0 ABPerson>,
<CPRecord: 0x7fd37d461460 ABPerson>,
<CPRecord: 0x7fd37d4617b0 ABPerson>,
<CPRecord: 0x7fd37d461b00 ABPerson>,
<CPRecord: 0x7fd37d461fa0 ABPerson>,
<CPRecord: 0x7fd37d4624f0 ABPerson>,

Please help.

if (&ABAddressBookRequestAccessWithCompletion) { // if in iOS 6

        // Request authorization to Address Book
        ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);

        if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
            ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
                [self getFacebookContacts:addressBookRef];
            });
        }
        else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
            [self getFacebookContacts:addressBookRef];
        }
        else {
            // The user has previously denied access
            // Send an alert telling user to change privacy setting in settings app
        }
    }
    else{ // if not in iOS 6

        ABAddressBookRef addressBookRef = ABAddressBookCreate();
        [self getFacebookContacts:addressBookRef];
        NSLog(@"Not ios 6");
    }

-(void) getFacebookContacts:(ABAddressBookRef) addressBookRef
{
    CFArrayRef allContacts = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    CFIndex contactCount = CFArrayGetCount(allContacts);
    // Traverse through contacts
    for(int i=0; i<contactCount; i++)
    {
        ABRecordRef ref = CFArrayGetValueAtIndex(allContacts, i);
        //Check if contact has social profile
        ABMultiValueRef social = ABRecordCopyValue(( ABRecordRef)ref, kABPersonSocialProfileProperty);
        if (social) {
            // *****   This is coming as 0     **********
            CFIndex count = ABMultiValueGetCount(social);
            for (int i = 0 ; i < count; i++) {
                CFDictionaryRef socialValue = ABMultiValueCopyValueAtIndex(social, i);
                if(CFStringCompare( CFDictionaryGetValue(socialValue, kABPersonSocialProfileServiceKey), kABPersonSocialProfileServiceFacebook, 0)==kCFCompareEqualTo) {
                    NSLog(@"Facebook Contact %d : %@",i, (NSString*) CFDictionaryGetValue(socialValue, kABPersonSocialProfileUserIdentifierKey));
                }
            }
        }
    }
}

Body:
Didn't run the below code, but try and make a few changes as required.

-(void) getFacebookContacts:(ABAddressBookRef) addressBookRef
{
    CFArrayRef allContacts =
    ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    CFIndex contactCount = CFArrayGetCount(allContacts);
    CFStringRef str1 = CFSTR("FACEBOOK");

    // Traverse through contacts
    for(int i=0; i<contactCount; i++)
    {
        ABRecordRef ref = CFArrayGetValueAtIndex(allContacts, i);
        //Check if contact has social profile
        ABMultiValueRef social = ABRecordCopyValue(( ABRecordRef)ref, kABPersonSocialProfileProperty);

        if (social) {
        for (NSInteger i=0 ; i < ABMultiValueGetCount(social); i++) {
            CFDictionaryRef instantMessageValue = ABMultiValueCopyValueAtIndex(social, i);
            CFStringRef instantMessageString = CFDictionaryGetValue(instantMessageValue, kABPersonInstantMessageServiceKey);
            // Check if service is FACEBOOK
            if (CFStringCompare(instantMessageString, str1, 0) == kCFCompareEqualTo) {
            returnValue = YES;

            NSDictionary * powerDic = (__bridge NSDictionary *)instantMessageValue;
            NSLog(@"%@", [powerDic valueForKey:@"service"]);
            NSLog(@"%@", [powerDic valueForKey:@"url"]);
            NSLog(@"%@", [powerDic valueForKey:@"username"]);
            NSLog(@"%@", [powerDic valueForKey:@"displayname"]);

        }
      }
    }
}

Hope this helps :)
EDIT: Tested and working.


问:
Google Speech API Audio too slow in streaming mode
I am trying to pass my UDP audio data to Google Speech API and it works pretty well. However I got an issue:

When I start recognizing, I am waiting for packages, and thus no data is passed to Google Speech API. When packages come, I start sending them to API and it returns an error:
Audio data is being streamed too slow. Please stream audio data approximately at real time.
So, the problem is - when there is a delay after establishing the connection to Google Speech API and no data is sent before sending data start, it always leads to such behaviour.

Is it an intended behaviour or some workaround maybe?

Regards,
Artemiy

答:
We have seen this error when our application was too slow in feeding audio to the Google Speech platform or when there was an excessive delay among two consecutive writes:

You must be ready to start streaming of audio (writes of audio chunks) towards the Google Speech platform as soon as you send the initial Recognize

Your application must continue to feed audio to the Google Speech platform at a stable rate (e.g. if working with 8Khz audio x 8 bit, you must provide approximatively 8KB of audio each second, for example with consecutive writes of 4KB, delayed of about 0.5s)


问:
SSRS indicator sizing

When adding an indicator to a report as per the image, is it possible to have all the indicators the same size regardless of the cell size (so centre them all rather than stretching to fill the cell)

答:
Exporting SSRS report to Excel did not go as expected.

Report with indicators in rectangles exported to Excel was randomly adding 0 height rows between the records which was not what I wanted. My indicators where simple green ticks and red crosses, based on true false. I have tried everything I found out there, even a subreport for indicator. No luck...

Figured it out that the indicators randomly outgrows the parent item when you export it, just like a chart. Ended up with saving a tick and a cross as an image. Then used an image control(with fit proportional set) and embedded Image with conditional statement to pick specific image. Also added some padding not to overlap borders.

The only problem I could think of is if the background of the report is not white as I could not change the background color of the cell the Image is and there is no option for the Image background.

Hope this helps someone else.

Title: SSRS indicator sizing


问:
oracle between query not taking end date time
Oracle between query ignoring end date time.

Below is my table.

```<code>Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM
3   05-JUL-17 12.04.15.334000000 PM
</code>```

My requirement is to fetch the files between the given date time.

```<code> select * from fileupload where uploaddate between to_DATE('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')

select * from fileupload where uploaddate between to_timestamp('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_timestamp('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')
</code>```

Both queries not returns the end date time it returns only two row.

```<code>Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM
</code>```

But the expected result is

```<code> Id   Upload Date
    1   05-JUL-17 12.02.11.309000000 PM
    2   05-JUL-17 12.03.34.123000000 PM
    3   05-JUL-17 12.04.15.334000000 PM
</code>```

why the end date time is not fetching when using between.

Any help will be greatly appreciated!!!!

Body:
Oracle between query ignoring end date time.

Below is my table.

Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM
3   05-JUL-17 12.04.15.334000000 PM

My requirement is to fetch the files between the given date time.

 select * from fileupload where uploaddate between to_DATE('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')

select * from fileupload where uploaddate between to_timestamp('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_timestamp('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')

Both queries not returns the end date time it returns only two row.

Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM

But the expected result is

 Id   Upload Date
    1   05-JUL-17 12.02.11.309000000 PM
    2   05-JUL-17 12.03.34.123000000 PM
    3   05-JUL-17 12.04.15.334000000 PM

why the end date time is not fetching when using between.

Any help will be greatly appreciated!!!!

Body: to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS') smaller than    "05-JUL-17 12.04.15.334000000 PM"(because it is 05-JUL-17 12.04.15.00), try to change to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS') to to_DATE('05-07-17 12:04:16', 'DD-MM-YY HH24:MI:SS')


问:
How can I fill in values in pandas merge when merged rows don't match
I have two dataframes with a common "License Number" column. I want to merge them with indicator so I can later pick left_only or right_only to find entries that only appear in one of the dataframes.

However, I find that when merging, everything goes fine as long as the entries are the same in A and B, so theoretically, this would work perfectly for dataframes of the same size where all the entries are equal.

If there is an entry in A, but not in B, the merge will still pull row data from B and put it besides the data from A, even though the key used to merge (License Number) don't match between those rows.

Here is how I do it (code you can run with sample data is here):

```<code>merged_sheet = pd.merge(df1, df2, on='License Number', left_index=True, right_index=True, how='outer', indicator=True)
</code>```

In the example with data that I attach, the three first rows are fine, but when it arrives to the fourth row, there is no match between both dataframes, but instead of labeling it as NaN or whatever (what Excel would tag as #N/A in a VLOOKUP) it just simply pulls information from a totally unrelated row.

My expected result is that when the License Number column don't match, the merge just leaves either a blank space or some error message, but not that it moves all the data one row up.

答:
In this particular case, you shouldn't join on indexes, remove left_index = True and right_index = True.

```<code>merged_sheet = pd.merge(df1, df2, on='License Number', how='outer', indicator=True)
</code>```

Then you can see all non-matching rows in the outer join with the following statement:

```<code>merged_sheet.query('_merge != "both"')
</code>```

Body:
I have two dataframes with a common "License Number" column. I want to merge them with indicator so I can later pick left_only or right_only to find entries that only appear in one of the dataframes.

However, I find that when merging, everything goes fine as long as the entries are the same in A and B, so theoretically, this would work perfectly for dataframes of the same size where all the entries are equal.

If there is an entry in A, but not in B, the merge will still pull row data from B and put it besides the data from A, even though the key used to merge (License Number) don't match between those rows.

Here is how I do it (code you can run with sample data is here):

merged_sheet = pd.merge(df1, df2, on='License Number', left_index=True, right_index=True, how='outer', indicator=True)

In the example with data that I attach, the three first rows are fine, but when it arrives to the fourth row, there is no match between both dataframes, but instead of labeling it as NaN or whatever (what Excel would tag as #N/A in a VLOOKUP) it just simply pulls information from a totally unrelated row.

My expected result is that when the License Number column don't match, the merge just leaves either a blank space or some error message, but not that it moves all the data one row up.

Body:
In this particular case, you shouldn't join on indexes, remove left_index = True and right_index = True.

merged_sheet = pd.merge(df1, df2, on='License Number', how='outer', indicator=True)

Then you can see all non-matching rows in the outer join with the following statement:

merged_sheet.query('_merge != "both"')


问:
My devise User model custom field username always nil. I have tried all the other solutions on stack overflow
My application controller file

```<code>  class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up)  {|u| u.permit(:username, :email, :password, :password_confirmation, :remember_me)}
    devise_parameter_sanitizer.permit(:sign_in)  {|u| u.permit(:username, :email, :password, :password_confirmation, :remember_me)}
    devise_parameter_sanitizer.permit(:account_update) {|u| u.permit(:email, :password, :password_confirmation, :remember_me)}
  end
end
</code>```

My routes.rb file

```<code>Rails.application.routes.draw do
  devise_for :users

  root 'pages#index'

  get 'home' => 'pages#home'

  get 'profile' => 'pages#profile'

  get 'explore' => 'pages#explore'

end
</code>```

My migration files

```<code>class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end
</code>```

My add username column migration

```<code>class AddUsernameToUsers < ActiveRecord::Migration
  def change
    add_column :users, :username, :string
    add_index :users, :username, unique: true
  end
end
</code>```

My views/devise/registrations/new.html.erb

```<code><%= bootstrap_devise_error_messages! %>
<div class="panel panel-default devise-bs">
  <div class="panel-heading">
    <h4><%= t('.sign_up', default: 'Sign up') %></h4>
  </div>
  <div class="panel-body">
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { role: 'form' }) do |f| %>
      <div class="form-group">
        <%= f.label :username %>
        <%= f.text_field :email, autofocus: true, class: 'form-control' %>
      </div>
      <div class="form-group">
        <%= f.label :email %>
        <%= f.email_field :email, class: 'form-control' %>
      </div>
      <div class="form-group">
        <%= f.label :password %>
        <%= f.password_field :password, class: 'form-control' %>
      </div>
      <div class="form-group">
        <%= f.label :password_confirmation %>
        <%= f.password_field :password_confirmation, class: 'form-control' %>
      </div>
      <%= f.submit t('.sign_up', default: 'Sign up'), class: 'btn btn-primary' %>
    <% end %>
  </div>
</div>
<%= render 'devise/shared/links' %>
</code>```

So even after using strong parameters when the usernames being added through browser are not reflected back in the database.

It gives this result

```<code>irb(main):001:0> u = User.all
  User Load (20.0ms)  SELECT "users".* FROM "users"
=> #<ActiveRecord::Relation [#<User id: 1, email: "testuser@test.com", created_at: "2017-07-05 19:42:19", updated_at: "2017-07-05 21:11:38", username: nil>, #<User id: 2, email: "ajha@test.com", created_at: "2017-07-06 08:45:18", updated_at: "2017-07-06 08:45:18", username: nil>, #<User id: 3, email: "akasd@test.com", created_at: "2017-07-06 08:56:15", updated_at: "2017-07-06 08:56:15", username: nil>, #<User id: 4, email: "rcontest@test.com", created_at: "2017-07-06 09:23:55", updated_at: "2017-07-06 09:23:55", username: nil>]>
</code>```

Any help will be appreciated. Also tell me if you need to see any other files.

答:
My devise User model custom field username always nil

Because you don't have it in the form. Change

```<code><div class="form-group">
  <%= f.label :username %>
  <%= f.text_field :email, autofocus: true, class: 'form-control' %>
</div>
</code>```

to this

```<code><div class="form-group">
  <%= f.label :username %>
  <%= f.text_field :username, autofocus: true, class: 'form-control' %>
</div>
</code>```

Body:
My application controller file

  class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up)  {|u| u.permit(:username, :email, :password, :password_confirmation, :remember_me)}
    devise_parameter_sanitizer.permit(:sign_in)  {|u| u.permit(:username, :email, :password, :password_confirmation, :remember_me)}
    devise_parameter_sanitizer.permit(:account_update) {|u| u.permit(:email, :password, :password_confirmation, :remember_me)}
  end
end

My routes.rb file

Rails.application.routes.draw do
  devise_for :users

  root 'pages#index'

  get 'home' => 'pages#home'

  get 'profile' => 'pages#profile'

  get 'explore' => 'pages#explore'

end

My migration files

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

My add username column migration

class AddUsernameToUsers < ActiveRecord::Migration
  def change
    add_column :users, :username, :string
    add_index :users, :username, unique: true
  end
end

My views/devise/registrations/new.html.erb

<%= bootstrap_devise_error_messages! %>

<%= t('.sign_up', default: 'Sign up') %>

    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { role: 'form' }) do |f| %>

        <%= f.label :username %>
        <%= f.text_field :email, autofocus: true, class: 'form-control' %>

        <%= f.label :email %>
        <%= f.email_field :email, class: 'form-control' %>

        <%= f.label :password %>
        <%= f.password_field :password, class: 'form-control' %>

        <%= f.label :password_confirmation %>
        <%= f.password_field :password_confirmation, class: 'form-control' %>

      <%= f.submit t('.sign_up', default: 'Sign up'), class: 'btn btn-primary' %>
    <% end %>

<%= render 'devise/shared/links' %>

So even after using strong parameters when the usernames being added through browser are not reflected back in the database.

It gives this result

irb(main):001:0> u = User.all
  User Load (20.0ms)  SELECT "users".* FROM "users"
=> #<ActiveRecord::Relation [#<User id: 1, email: "testuser@test.com", created_at: "2017-07-05 19:42:19", updated_at: "2017-07-05 21:11:38", username: nil>, #<User id: 2, email: "ajha@test.com", created_at: "2017-07-06 08:45:18", updated_at: "2017-07-06 08:45:18", username: nil>, #<User id: 3, email: "akasd@test.com", created_at: "2017-07-06 08:56:15", updated_at: "2017-07-06 08:56:15", username: nil>, #<User id: 4, email: "rcontest@test.com", created_at: "2017-07-06 09:23:55", updated_at: "2017-07-06 09:23:55", username: nil>]>

Any help will be appreciated. Also tell me if you need to see any other files.

Body:
My devise User model custom field username always nil

Because you don't have it in the form. Change

<div class="form-group">
  <%= f.label :username %>
  <%= f.text_field :email, autofocus: true, class: 'form-control' %>
</div>

to this

<div class="form-group">
  <%= f.label :username %>
  <%= f.text_field :username, autofocus: true, class: 'form-control' %>
</div>


问:
Routing not working in reactjs application
I have created a reactjs app having three pages (components), App, Login and Register, where I need to navigate from page to page by entering the url in the browser but the navigation is not working for me. Entering any url just shows me the 'App' page.

following is the code that I have written in main.js file of the app and the url that I am using to navigate looks something like this http://localhost:8080/#/login or http://localhost:8080/#/reg

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, NavLink, Redirect, Switch, hashHistory} from 'react-router-dom'
import App from './../jsx/App.jsx';
import Login from './../jsx/Login.jsx';
import Register from './../jsx/Register.jsx';

ReactDOM.render((
     <Router history={hashHistory}>
        <div>
            <Route path="/" component={App}/>
            <Route path="/login" component={Login}/>
            <Route path="/reg" component={Register}/>
        </div>
    </Router>

), document.getElementById('app'))
</code>```

答:
Use BrowserRouter and Switch from 'react-router-dom'
if you use BrowserRouter no need to pass history as props as it handles itself.

Try this.

```<code><Router>
        <Switch>
            <Route exact path="/" component={App}/>
            <Route exact path="/login" component={Login}/>
            <Route exact path="/reg" component={Register}/>
        </Switch>
</Router>
</code>```

Body:
I have created a reactjs app having three pages (components), App, Login and Register, where I need to navigate from page to page by entering the url in the browser but the navigation is not working for me. Entering any url just shows me the 'App' page.

following is the code that I have written in main.js file of the app and the url that I am using to navigate looks something like this http://localhost:8080/#/login or http://localhost:8080/#/reg

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, NavLink, Redirect, Switch, hashHistory} from 'react-router-dom'
import App from './../jsx/App.jsx';
import Login from './../jsx/Login.jsx';
import Register from './../jsx/Register.jsx';

ReactDOM.render((
     <Router history={hashHistory}>

            <Route path="/" component={App}/>
            <Route path="/login" component={Login}/>
            <Route path="/reg" component={Register}/>

    </Router>

), document.getElementById('app'))

Body:
Use BrowserRouter and Switch from 'react-router-dom'
if you use BrowserRouter no need to pass history as props as it handles itself.

Try this.

<Router>
        <Switch>
            <Route exact path="/" component={App}/>
            <Route exact path="/login" component={Login}/>
            <Route exact path="/reg" component={Register}/>
        </Switch>
</Router>


问:
WatchKit and UIAlertView / UIAlertController popup
In my WatchKit app, when the user first launches it, I would like to present to them a helpful message alert that tells them how the app works, e.g. what the buttons do, etc.

Is there something similar to UIAlertView / UIAlertController that I can call in a WatchKit app? I couldn't find an answer on this topic which may very well mean that it's not possible.

答:
```<code>   let h0 = { print("h0 action")}
   let h1 = { print("h1 action")}

   let action1 = WKAlertAction(title: "h0 action", style: .default, handler:h0)
   let action2 = WKAlertAction(title: "h1 action", style: .default, handler:h0)

   self.presentAlert(withTitle: "Title", message: "a message", preferredStyle: .actionSheet, actions: [action1, action2])
</code>```

Code in Swift 3

Body:
   let h0 = { print("h0 action")}
   let h1 = { print("h1 action")}

   let action1 = WKAlertAction(title: "h0 action", style: .default, handler:h0)
   let action2 = WKAlertAction(title: "h1 action", style: .default, handler:h0)

   self.presentAlert(withTitle: "Title", message: "a message", preferredStyle: .actionSheet, actions: [action1, action2])

Code in Swift 3


问:
httpd local virtualhost example
-- Original post ---

I'd like to setup a dev env to play with some apache features. I'm running httpd on fedora.

I added to hosts local redirects

```<code># cat /etc/hosts
127.0.0.1 example1.com
127.0.0.1 example2.com

# cmkdir /var/www/example1;      echo "Hello from /var/www/example1/index.html" > /var/www/example1/index.html
# cmkdir /var/www/example2;      echo "Hello from /var/www/example2/index.html" > /var/www/example2/index.html
# cmkdir /var/www/example2/sub ; echo "Hello from /var/www/example2/sub/index.html" > /var/www/example2/sub/index.html

# cvi /etc/httpd/conf/httpd.conf
<VirtualHost _default_:80>
    DocumentRoot "/var//www/html"
</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example1"
    ServerName example1.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2"
    ServerName example2.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2/sub"
    ServerName sub.example2.com
    ServerPath "/sub/"
    RewriteEngine On
    RewriteRule "^(/sub/.*)" "/var/www/example2$1"

</VirtualHost>

# capachectl -t ; apachectl restart

# curl localhost
Hello from /var/www/html/index.html
# curl example1.com
Hello from /var/www/example1/index.html
# curl example2.com
Hello from /var/www/example2/index.html
# curl sub.example2.com
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
... ( lots of stuff different from the one i echoed) ...
</code>```

If I do the same thing in local firefox - localhost works as expected, example1.com works as expected, but sub.example2.com redirects me to example2.com.

Can you please help me to figure out how to configure a local sub-domain? What is missing? Based on https://httpd.apache.org/docs/2.4/vhosts/examples.html I believe what I did is correct.

-- Edit / Update ---

If I follow the advice below from Newbie and change only the rewrite rule, without making any other changes from the setup above:

```<code>    <VirtualHost 127.0.0.1:80>
        DocumentRoot "/var/www/example2/sub"
        ServerName sub.example2.com
        ServerPath "/sub/"
#        RewriteEngine On
#        RewriteRule "^(/sub/.*)" "/var/www/example2$1"

    </VirtualHost>
</code>```

I get :

```<code># curl sub.example2.com
curl: (6) Could not resolve host: sub.example2.com
</code>```

If I

```<code># cat /etc/hosts | grep sub
127.0.0.1 example2.com sub.example2.com
</code>```

It works as expected

```<code>#curl example2.com
Hello from /var/www/example2/index.html
# curl sub.example2.com
Hello from /var/www/example2/sub/index.html
</code>```

Still this seems to be strange setup. I don't want to create /etc/hosts record for each sub-domain... Shouldn't it be possible to handle this situation only via the httpd VirtualHost setting, without changing the DNS settings locally or even worse - adding C records in the DNS of a domain(if not localhost)?  Any hint what I'm doing wrong? How can I get sub.example1.com to work without modifying the dns settings?

Regards,
Pavel

答:
I believe I found out the answer to my question ...

** How to run locally sub-domains?**

/etc/hosts does not support wild cards(*.example2.com) and one needs to setup a local dns proxy server like dnsmasq for example. Otherwise for dev purposes you have to list (and then maintain :/ ) the sub-domains one-by-one in the /etc/hosts for local dev purposes.

How to run the sub-domains via official DNS records for domain ?

Seems laziest approach is to setup DNS settings having:

```<code>example2.com     A      the-server-IP
example2.com     MX 0   example2.com
*.example2.com   CNAME  example2.com
</code>```

Looking forward to your comments, if there is smarter approach.
If you agree this is the way to go - please accept the answer, so other members know it is the way to go.

Regards, Pavel

Title: httpd local virtualhost example

Body:
-- Original post ---

I'd like to setup a dev env to play with some apache features. I'm running httpd on fedora.

I added to hosts local redirects

# cat /etc/hosts
127.0.0.1 example1.com
127.0.0.1 example2.com

# cmkdir /var/www/example1;      echo "Hello from /var/www/example1/index.html" > /var/www/example1/index.html
# cmkdir /var/www/example2;      echo "Hello from /var/www/example2/index.html" > /var/www/example2/index.html
# cmkdir /var/www/example2/sub ; echo "Hello from /var/www/example2/sub/index.html" > /var/www/example2/sub/index.html

# cvi /etc/httpd/conf/httpd.conf
<VirtualHost _default_:80>
    DocumentRoot "/var//www/html"
</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example1"
    ServerName example1.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2"
    ServerName example2.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2/sub"
    ServerName sub.example2.com
    ServerPath "/sub/"
    RewriteEngine On
    RewriteRule "^(/sub/.*)" "/var/www/example2$1"

</VirtualHost>

# capachectl -t ; apachectl restart

# curl localhost
Hello from /var/www/html/index.html
# curl example1.com
Hello from /var/www/example1/index.html
# curl example2.com
Hello from /var/www/example2/index.html
# curl sub.example2.com
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">

Body:
I believe I found out the answer to my question ...

** How to run locally sub-domains?**

/etc/hosts does not support wild cards(*.example2.com) and one needs to setup a local dns proxy server like dnsmasq for example. Otherwise for dev purposes you have to list (and then maintain :/ ) the sub-domains one-by-one in the /etc/hosts for local dev purposes.

How to run the sub-domains via official DNS records for domain ?

Seems laziest approach is to setup DNS settings having:

example2.com     A      the-server-IP
example2.com     MX 0   example2.com
*.example2.com   CNAME  example2.com

Looking forward to your comments, if there is smarter approach.
If you agree this is the way to go - please accept the answer, so other members know it is the way to go.

Regards, Pavel


问:
Problems came up in the following areas during load: Table
I have generated an excel file from xml. But i can not open it with Excel. Excel gives the following error opening it:

```<code>Problems came up in the following areas during load:
Table
</code>```

Then it shows a message that the log file corresponding the error can be found at : C:/Documents and Setting/myUserName/Local Settings/Temporary Internet Files/Content.MSO/xxxxx.log

But i can not find Content.MSO folder in my windows. I checked folder settings and made all folders visible but i still can not access this folder. So that i can not analise the log file.

how could i find the generated log file?

答:
I had the SAME problem,
and its because de file is TOO BIG.
I try an extract from SAP, more little than the one with that make the error)  and save it in XML file. and it WORK, no more error.

so maybe if you can save in 2 Excel files XML instead of 1 it will be good ;)

ALicia

Body:
I have generated an excel file from xml. But i can not open it with Excel. Excel gives the following error opening it:

Problems came up in the following areas during load:
Table

Then it shows a message that the log file corresponding the error can be found at : C:/Documents and Setting/myUserName/Local Settings/Temporary Internet Files/Content.MSO/xxxxx.log

But i can not find Content.MSO folder in my windows. I checked folder settings and made all folders visible but i still can not access this folder. So that i can not analise the log file.

how could i find the generated log file?


问:
upload image in folder MVC
I am beginner in asp.net and trying to upload the image in my project Images folder but it is not uploading it in desired folder. Anybody please give me suggestion.

Create.cshtml

```<code>@using (Html.BeginForm("Create", "Lenses", FormMethod.Post,
                            new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>lens</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.lens_img, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" name="file" id="file" style="width: 100%;" />
            </div>
        </div>
        <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>

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

Controller.cs

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "lens_img")] lens lens, HttpPostedFileBase file)
{
    if (ModelState.IsValid)
    {
        if (file != null)
        {
            file.SaveAs(HttpContext.Server.MapPath("~/Content/Images/")
                                                          + file.FileName);
            lens.lens_img = file.FileName;
        }
        db.lenses.Add(lens);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(lens);
}
</code>```

答:
If file is reaching the controller action and file parameter is not null, then you should be using Path.Combine method to generate the correct path, do not use string concatenation for this, you should try it in following way:

```<code>file.SaveAs(Path.Combine(HttpContext.Server.MapPath("~/Content/Images/"), file.FileName);
</code>```

For more clarity, let's break in to two steps:

```<code>var mappedPath = HttpContext.Server.MapPath("~/Content/Images/");
file.SaveAs(Path.Combine(mappedPath, file.FileName);
</code>```

Also have a look at this answer as well which is related.

Hope it helps!

Title: upload image in folder MVC

Body:
I am beginner in asp.net and trying to upload the image in my project Images folder but it is not uploading it in desired folder. Anybody please give me suggestion.

Create.cshtml

@using (Html.BeginForm("Create", "Lenses", FormMethod.Post,
                            new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

lens

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

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

                <input type="file" name="file" id="file" style="width: 100%;" />

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

}

Controller.cs

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "lens_img")] lens lens, HttpPostedFileBase file)
{
    if (ModelState.IsValid)
    {
        if (file != null)
        {
            file.SaveAs(HttpContext.Server.MapPath("~/Content/Images/")
                                                          + file.FileName);
            lens.lens_img = file.FileName;
        }
        db.lenses.Add(lens);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(lens);
}

Body:
If file is reaching the controller action and file parameter is not null, then you should be using Path.Combine method to generate the correct path, do not use string concatenation for this, you should try it in following way:

file.SaveAs(Path.Combine(HttpContext.Server.MapPath("~/Content/Images/"), file.FileName);

For more clarity, let's break in to two steps:

var mappedPath = HttpContext.Server.MapPath("~/Content/Images/");
file.SaveAs(Path.Combine(mappedPath, file.FileName);

Also have a look at this answer as well which is related.

Hope it helps!


问:
How to capture exception by SQL Server to console program?
```<code>for(int i=0; i < fileDirectories.Count;i++){

string script = File.ReadAllText(@fileDirectories[i]);
string[] singleCommand = Regex.Split(script,"^GO", RegexOptions.Multiline);
StringCollection scl = new StringCollection();

foreach(string t in singleCommand){
    if(t.Trim().Length > 0) scl.Add(t.Trim());
}

try
{
    int[] result = Server
               .ConnectionContext
               .ExecuteNonQuery(scl, ExecutionTypes.ContinueOnError);
}catch(Exception e)
{
//whatever
}
}
</code>```

The objective of this program is to run multiple scripts and if fail, capture the exceptions thrown by SQL SERVER and continue running the remaining scripts.

In order to try out, INSERT PERMISSION has been taken away from DB and hence first query (INSERT query) will fail when being executed on SQL SERVER manually because INSERT PERMISSION been taken away with below Error

The INSERT permission was denied on object 'xxx',database 'xxxxx', schema 'xx'

When running the program, variable result will have value 0 indicating the query failed but however it's not throwing error and being catch at catch? How should I pass the exception given by SQL Server to my console program?

答:
You could use

```<code>public int ExecuteNonQuery(
    string sqlCommand,
    ExecutionTypes executionType
)
</code>```

instead of

```<code>public int[] ExecuteNonQuery(
    StringCollection sqlCommands,
    ExecutionTypes executionType
)
</code>```

For example

```<code>foreach (string t in singleCommand)
        {
            if (t.Trim().Length > 0)
            {
                try
                {
                    // do not use ExecutionTypes.ContinueOnError, it will not
                    // throw any exceptions
                    int result = Server
                        .ConnectionContext
                        .ExecuteNonQuery(t, ExecutionTypes.Default);
                }
                catch (ExecutionFailureException ex)
                {
                    // do anything
                    // do not throw error here
                }
                catch (Exception e)
                {
                    // do anything
                    // do not throw error here
                }
            }
        }
</code>```

Body:
for(int i=0; i < fileDirectories.Count;i++){

string script = File.ReadAllText(@fileDirectories[i]);
string[] singleCommand = Regex.Split(script,"^GO", RegexOptions.Multiline);
StringCollection scl = new StringCollection();

foreach(string t in singleCommand){
    if(t.Trim().Length > 0) scl.Add(t.Trim());
}

try
{
    int[] result = Server
               .ConnectionContext
               .ExecuteNonQuery(scl, ExecutionTypes.ContinueOnError);
}catch(Exception e)
{
//whatever
}
}

The objective of this program is to run multiple scripts and if fail, capture the exceptions thrown by SQL SERVER and continue running the remaining scripts.

In order to try out, INSERT PERMISSION has been taken away from DB and hence first query (INSERT query) will fail when being executed on SQL SERVER manually because INSERT PERMISSION been taken away with below Error

The INSERT permission was denied on object 'xxx',database 'xxxxx', schema 'xx'

When running the program, variable result will have value 0 indicating the query failed but however it's not throwing error and being catch at catch? How should I pass the exception given by SQL Server to my console program?

Body:
You could use

public int ExecuteNonQuery(
    string sqlCommand,
    ExecutionTypes executionType
)

instead of

public int[] ExecuteNonQuery(
    StringCollection sqlCommands,
    ExecutionTypes executionType
)

For example

foreach (string t in singleCommand)
        {
            if (t.Trim().Length > 0)
            {
                try
                {
                    // do not use ExecutionTypes.ContinueOnError, it will not
                    // throw any exceptions
                    int result = Server
                        .ConnectionContext
                        .ExecuteNonQuery(t, ExecutionTypes.Default);
                }
                catch (ExecutionFailureException ex)
                {
                    // do anything
                    // do not throw error here
                }
                catch (Exception e)
                {
                    // do anything
                    // do not throw error here
                }
            }
        }


问:
Mysql FIND_In_SET return rows having all the values of that set
*********Thanx In ADvance*****************

I'm running this query :

```<code>SELECT * FROM `test_lab_mapping` tlm
WHERE FIND_IN_SET(tlm.testID,'1,2')
</code>```

And result is in this image:

I want to get all labId(COLUMN) rows which have corresponding entries to ALL the  testId(column) which we will pass in find_in_set function.
as per above query i passed FIND_IN_SET(labId,'1,2');
its returning all the data right but with one extra row which has labId = 3
as labId =1 has corresponding entry of testId=1 and testId=2 AND labId =2 has also same corresponding entries for both the testId 1 and 2 .

But labId=3 has only corresponding entry to testId=1 its does not have testId = 2 entry so it should not come in result.

答:
FIND_IN_SET doesn't do this.

One way to do this is to use a join for each testId you want to include:

```<code>SELECT labId FROM test_lab_mapping WHERE testId = 1
  JOIN SELECT labId FROM test_lab_mapping WHERE testId = 2
  USING (labId)
</code>```

This results in only those labId values that appear in both tests. The second SELECT in the join does not result in a row for labId = 3, as there is no row where testId = 2 and labId = 3, so labId 3 does not appear in the result.

If you need to check more tests, add more JOINed selects:

```<code>SELECT labId FROM test_lab_mapping WHERE testId = 1
  JOIN SELECT labId FROM test_lab_mapping WHERE testId = 2
  JOIN SELECT labId FROM test_lab_mapping WHERE testId = 3
  ... etc
  USING (labId)
</code>```

Body:
*********Thanx In ADvance*****************

I'm running this query :

SELECT * FROM `test_lab_mapping` tlm
WHERE FIND_IN_SET(tlm.testID,'1,2')

And result is in this image:

I want to get all labId(COLUMN) rows which have corresponding entries to ALL the  testId(column) which we will pass in find_in_set function.
as per above query i passed FIND_IN_SET(labId,'1,2');
its returning all the data right but with one extra row which has labId = 3
as labId =1 has corresponding entry of testId=1 and testId=2 AND labId =2 has also same corresponding entries for both the testId 1 and 2 .

But labId=3 has only corresponding entry to testId=1 its does not have testId = 2 entry so it should not come in result.

Body:
FIND_IN_SET doesn't do this.

One way to do this is to use a join for each testId you want to include:

SELECT labId FROM test_lab_mapping WHERE testId = 1
  JOIN SELECT labId FROM test_lab_mapping WHERE testId = 2
  USING (labId)

This results in only those labId values that appear in both tests. The second SELECT in the join does not result in a row for labId = 3, as there is no row where testId = 2 and labId = 3, so labId 3 does not appear in the result.

If you need to check more tests, add more JOINed selects:

SELECT labId FROM test_lab_mapping WHERE testId = 1
  JOIN SELECT labId FROM test_lab_mapping WHERE testId = 2
  JOIN SELECT labId FROM test_lab_mapping WHERE testId = 3
  ... etc
  USING (labId)


问:
value collectAsMap is not a member of org.apache.spark.rdd.RDD
I am trying to use collectAsMap() in the following statement:

```<code>import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.rdd.RDD
...
documents_input.
  filter(_ != documents_header).
  map(_.split(",")).
  map(Document.parse(_)).
  keyBy((_.id)).collectAsMap()
</code>```

However I am getting the following error:

```<code>value collectAsMap is not a member of org.apache.spark.rdd.RDD[(Int, `com.codependent.MyApp.Document)]`
</code>```

Any idea why or how I could turn the Array into a Map?

答: It depends on how you read the documents_input. If you read it using sparkContext then you should be able to use collectAsMap. But if you have read the documents_input as Source or any other scala api then collectAsMap won't do the trick. In that case you can use toMap

Body:
I am trying to use collectAsMap() in the following statement:

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.rdd.RDD
...
documents_input.
  filter(_ != documents_header).
  map(_.split(",")).
  map(Document.parse(_)).
  keyBy((_.id)).collectAsMap()

However I am getting the following error:

value collectAsMap is not a member of org.apache.spark.rdd.RDD[(Int, `com.codependent.MyApp.Document)]`

Any idea why or how I could turn the Array into a Map?


问:
QT5 QML Charts: how to label only subset of points
By default, in QML Charts LineSeries all the points are labelled. I need to label only specific points, how to achieve this ?

Here is my qml file (part of big project). I have set corresponding properties for LineSeries to show point labels, but I need only couple of labels displayed instead of complete set of points. Is there a way in Qml to control this ?

```<code>import QtQuick 2.7
import QtCharts 2.2
import QtQuick.Layouts 1.3
import aa.ui.backend 1.0

Item {
property DSPBackend backend: analyzer.dsp

property alias titleV: chartV.title
property alias seriesV: lineSeriesV
property alias titleI: chartI.title
property alias seriesI: lineSeriesI

GridLayout {
    id: gridSpectrum
    anchors.fill: parent
    columns: 2
    rows: 1
    columnSpacing: 0
    flow: GridLayout.LeftToRight

    ChartView {
        id: chartV
        Layout.fillWidth: true
        Layout.fillHeight: true
        /*title: "Spectrum (V-channel)"
        titleFont.pixelSize: 10*/
        theme: ChartView.ChartThemeBlueCerulean
        antialiasing: false
        legend.visible: false
        legend.font.pointSize: 10
        margins.top: 2
        margins.left: 2
        margins.right: 2
        margins.bottom: 4

        ValueAxis {
            id: axisXV
            titleFont.pointSize: 7
            labelsFont.pointSize: 7
        }

        ValueAxis {
            id: axisYV
            titleFont.pointSize: 7
            labelsFont.pointSize: 7
        }

        LineSeries {
            id: lineSeriesV
            axisX: axisXV
            axisY: axisYV
            color: "#66cc00"
            name: "V-channel"
            pointLabelsFormat: "(@xPoint Hz, @yPoint dB)"
            pointLabelsVisible: true
            width: 3
            useOpenGL: false
        }
    }

    ChartView {
        id: chartI
        /*title: "Spectrum (I-channel)"
        titleFont.pixelSize: 10*/
        antialiasing: true
        theme: ChartView.ChartThemeBlueCerulean
        legend.visible: false
        legend.font.pointSize: 10
        margins.top: 2
        margins.left: 2
        margins.right: 2
        margins.bottom: 4
        Layout.fillWidth: true
        Layout.fillHeight: true

        ValueAxis {
            id: axisXI
            titleFont.pointSize: 7
            labelsFont.pointSize: 7
        }

        ValueAxis {
            id: axisYI
            titleFont.pointSize: 7
            labelsFont.pointSize: 7
        }

        LineSeries {
            id: lineSeriesI
            axisX: axisXI
            axisY: axisYI
            color: "#0099ff"
            name: "I-channel"
            pointLabelsFormat: "(@xPoint Hz, @yPoint dB)"
            pointLabelsVisible: true
            width: 3
            useOpenGL: false
        }

    }

}

Timer {
    id: timerSpectrum
    interval: 500
    running: true
    repeat: true
    onTriggered: {
        backend.update_spectrum(seriesV, seriesI);
    }
}

Component.onCompleted: {
    backend.setup_spectrum(axisXV, axisYV, axisXI, axisYI)
}
}
</code>```

答:
You can set a bool property or a function that returns a bool. Then evaluate it in the pointLabelsFormat property.

```<code>pointLabelsFormat: myBool? "(@xPoint Hz, @yPoint dB)" : ""
</code>```

If the boolean is false it sets the point's label to an empty string.

Body:
By default, in QML Charts LineSeries all the points are labelled. I need to label only specific points, how to achieve this ?

Here is my qml file (part of big project). I have set corresponding properties for LineSeries to show point labels, but I need only couple of labels displayed instead of complete set of points. Is there a way in Qml to control this ?

import QtQuick 2.7
import QtCharts 2.2
import QtQuick.Layouts 1.3
import aa.ui.backend 1.0

Item {
property DSPBackend backend: analyzer.dsp

property alias titleV: chartV.title
property alias seriesV: lineSeriesV
property alias titleI: chartI.title
property alias seriesI: lineSeriesI

GridLayout {
    id: gridSpectrum
    anchors.fill: parent
    columns: 2
    rows: 1
    columnSpacing: 0
    flow: GridLayout.LeftToRight

    ChartView {
        id: chartV
        Layout.fillWidth: true
        Layout.fillHeight: true
        /*title: "Spectrum (V-channel)"
        titleFont.pixelSize: 10*/
        theme: ChartView.ChartThemeBlueCerulean
        antialiasing: false
        legend.visible: false
        legend.font.pointSize: 10
        margins.top: 2
        margins.left: 2
        margins.right: 2
        margins.bottom: 4

        ValueAxis {
            id: axisXV
            titleFont.pointSize: 7
            labelsFont.pointSize: 7
        }

        ValueAxis {
            id: axisYV
            titleFont.pointSize: 7
            labelsFont.pointSize: 7
        }

        LineSeries {
            id: lineSeriesV
            axisX: axisXV
            axisY: axisYV
            color: "#66cc00"
            name: "V-channel"
            pointLabelsFormat: "(@xPoint Hz, @yPoint dB)"
            pointLabelsVisible: true
            width: 3
            useOpenGL: false
        }
    }

    ChartView {
        id: chartI
        /*title: "Spectrum (I-channel)"
        titleFont.pixelSize: 10*/
        antialiasing: true
        theme: ChartView.ChartThemeBlueCerulean
        legend.visible: false
        legend.font.pointSize: 10
        margins.top: 2
        margins.left: 2
        margins.right: 2
        margins.bottom: 4
        Layout.fillWidth: true
        Layout.fillHeight: true

        ValueAxis {
            id: axisXI
            titleFont.pointSize: 7
            labelsFont.pointSize: 7
        }

        ValueAxis {
            id: axisYI
            titleFont.pointSize: 7
            labelsFont.pointSize: 7
        }

        LineSeries {
            id: lineSeriesI
            axisX: axisXI
            axisY: axisYI
            color: "#0099ff"
            name: "I-channel"
            pointLabelsFormat: "(@xPoint Hz, @yPoint dB)"
            pointLabelsVisible: true
            width: 3
            useOpenGL: false
        }

    }

}

Timer {
    id: timerSpectrum
    interval: 500
    running: true
    repeat: true
    onTriggered: {
        backend.update_spectrum(seriesV, seriesI);
    }
}

Component.onCompleted: {
    backend.setup_spectrum(axisXV, axisYV, axisXI, axisYI)
}
}

Body:
You can set a bool property or a function that returns a bool. Then evaluate it in the pointLabelsFormat property.

pointLabelsFormat: myBool? "(@xPoint Hz, @yPoint dB)" : ""

If the boolean is false it sets the point's label to an empty string.


问:
CollapsiblePanelExtender set collapsed
I am using a CollapsiblePanelExtender in the AjaxToolkit 3.5 to show/hide search filter options.

I want the CollapsiblePanelExtender to be expanded when the page first loads, !Page.IsPostBack.

After that I want the CollapsiblePanelExtender to be collapsed because this means they either submitted some filter options or are going to another page in the search results.  In either event I want the CollapsiblePanelExtender to be collpased.

Is there a way I can acheive this?

In the code-behind in the button submit handler I've tried adding:

CollapsiblePanelExtenderID.CollapsedSize = 0
CollapsiblePanelExtenderID.Collapsed = true

but this doesn't seem to be working.  I also added this to the lvProducts_PagePropertiesChanging handler where the Paging is handled.

答:
I figured it out again.

I needed to add this:

```<code>    if (!Page.IsPostBack)
    {
        // do something
    }
    else
    {
        cpFilter.Collapsed = true;
        cpFilter.ClientState = "true";
    }
</code>```

thanks to this link: http://www.dotnetcurry.com/ShowArticle.aspx?ID=230&AspxAutoDetectCookieSupport=1

OwnerDisplayName: Dukebaby

Title: CollapsiblePanelExtender set collapsed

Body:
I figured it out again.

I needed to add this:

    if (!Page.IsPostBack)
    {
        // do something
    }
    else
    {
        cpFilter.Collapsed = true;
        cpFilter.ClientState = "true";
    }

thanks to this link: http://www.dotnetcurry.com/ShowArticle.aspx?ID=230&AspxAutoDetectCookieSupport=1


问:
How display a loading image correctly on Android phone
I have been trying to use a .gif file from my resources, but I get no movement when it loads.  I am using it as a loading image while I am doing an asynchronous task.  I was previously using a progress dialog but now I would like to display the image myself and not use a dialog.    How can I get this image to display correctly?</p>

答: If you are deadset on using a gif image you can just use a WebView instead of an ImageView. Then make an html doc that displays your gif image. When you show it in the WebView it will be animated for you.</p>