问:
Reading a csv file in Python with the module csv
I'm trying to read a csv file in Python using the module csv.
To do that, I use a reader variable :

```<code> with open('oneOrganization.csv', 'r', newline='') as csvfile2:
    reader2 = csv.DictReader(csvfile2, delimiter=',')

    for row in reader2:
        if row["role"] == []:
            row_dict['Role'] = "User"
        else:
            row_dict['Role'] = row["role"]
</code>```

However, running the program, I realize that it does get in the loop at all although the cvs file exists and is indeed called oneOrganization.csv. What could be the reason of that ?

I'm starting in Python,  usually this method works.

答:
The problem that prevents your code from accessing the if loop if row['Role']==[] is because you're trying to find empty elements the wrong way.

try this instead:

Method 1:

```<code>with open('oneOrganization.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    my_list = list(reader)
    for row in reader:
        if row['test1'] in (None,''): # to check if cell is empty
            row_dict['Role'] = "User"
        else:
            row_dict['Role'] = row["role"]
</code>```

Method 2: provided by @Jean-François Fabre

```<code>with open('oneOrganization.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        if not row['test1']:
            row_dict['Role'] = "User"
        else:
            row_dict['Role'] = row["role"]
</code>```

Method 3 : "elegant one liner" - by @Jean-François Fabre

```<code>with open('oneOrganization.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        row_dict['Role'] = row["role"] or "User"
</code>```

I tried it on a csv example that can be represented like this: (np.array form)

```<code>[['test1' 'test2' 'test3']
 [   1       2       3   ]
 [   11      22      33  ]
 [           222     333]]
</code>```

and used this code:

```<code>import csv

with open('test_csv.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        if row['test1'] in (None,''):
            print('no')
        else:
            print(row['test1'])
</code>```

or with method 2:

```<code>import csv

with open('test_csv.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        if not row['test1']:
            print('no')
        else:
            print(row['test1'])
</code>```

or method 3

```<code>import csv

with open('test_csv.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        print(row['test1'] or 'no')
</code>```

output:

```<code>1
11
no
</code>```

you can refer to this topic for more informations about how to check if a "cell" is empty in a csv file.

Body:
I'm trying to read a csv file in Python using the module csv.
To do that, I use a reader variable :

 with open('oneOrganization.csv', 'r', newline='') as csvfile2:
    reader2 = csv.DictReader(csvfile2, delimiter=',')

    for row in reader2:
        if row["role"] == []:
            row_dict['Role'] = "User"
        else:
            row_dict['Role'] = row["role"]

However, running the program, I realize that it does get in the loop at all although the cvs file exists and is indeed called oneOrganization.csv. What could be the reason of that ?

I'm starting in Python,  usually this method works.

Body:
The problem that prevents your code from accessing the if loop if row['Role']==[] is because you're trying to find empty elements the wrong way.

try this instead:

Method 1:

with open('oneOrganization.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    my_list = list(reader)
    for row in reader:
        if row['test1'] in (None,''): # to check if cell is empty
            row_dict['Role'] = "User"
        else:
            row_dict['Role'] = row["role"]

Method 2: provided by @Jean-François Fabre

with open('oneOrganization.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        if not row['test1']:
            row_dict['Role'] = "User"
        else:
            row_dict['Role'] = row["role"]

Method 3 : "elegant one liner" - by @Jean-François Fabre

with open('oneOrganization.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        row_dict['Role'] = row["role"] or "User"

I tried it on a csv example that can be represented like this: (np.array form)

[['test1' 'test2' 'test3']
 [   1       2       3   ]
 [   11      22      33  ]
 [           222     333]]

and used this code:

import csv

with open('test_csv.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        if row['test1'] in (None,''):
            print('no')
        else:
            print(row['test1'])

or with method 2:

import csv

with open('test_csv.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        if not row['test1']:
            print('no')
        else:
            print(row['test1'])

or method 3

import csv

with open('test_csv.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        print(row['test1'] or 'no')

output:

1
11
no

you can refer to this topic for more informations about how to check if a "cell" is empty in a csv file.


来源: stackexchange

问:
How to search for extension in magic files
I know you can find the extension with

```<code>file *.myext
</code>```

But I'm wondering if I can write into my magic file a line which for example return a success message on all the ".42" ex : myfile.42

imagine a folder with the following files

test1.42

test2.kk

test3.42

what should be the content of my magic file in order to make a success only on test1.42 and test2.42

I tried that for the moment

```<code>>0xA2 string 42 success
</code>```

答: linux/unix doesn't care about filename extensions, magic numbers represents first bytes of file which are used to determine type of file.</p>

ContentLicense: CC BY-SA 3.0

Body:
I know you can find the extension with

file *.myext

But I'm wondering if I can write into my magic file a line which for example return a success message on all the ".42" ex : myfile.42

imagine a folder with the following files

test1.42

test2.kk

test3.42

what should be the content of my magic file in order to make a success only on test1.42 and test2.42

I tried that for the moment

>0xA2 string 42 success


问:
How to hide sections in a table view using a radio button?
Here i am having four sections in a table view but in  the first section all the cells are having radio buttons. Whenever it is active, I need to show remaining three sections, if not I need to hide the remaining last three sections can anyone help me how to implement this ?

The image is as shown below ?

```<code> @IBAction func selectRadioButton(_ sender: KGRadioButton) {
        let chekIndex = self.checkIsRadioSelect.index(of: sender.tag)
        if sender.isSelected {

        } else{
            if(chekIndex == nil){
                self.checkIsRadioSelect.removeAll(keepingCapacity: false)
                self.checkIsRadioSelect.append(sender.tag)
                self.ProductTableView.reloadData()
            }
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int{
     return 4
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if (section == 0){
            return "PAYMENT INFORMATION"
        }
        else if (section == 1){
            return "ORDER REVIEW"
        }
        else if (section == 2){
            return "PRODUCT"
        }
        else{
            return ""
        }
    }
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
        let header = view as! UITableViewHeaderFooterView
        header.textLabel?.textColor = UIColor.gray
        header.textLabel?.textAlignment = NSTextAlignment.center
        header.textLabel?.font = UIFont(name: "Futura", size: 17)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (section == 0){
            return paymentmethodsArray.count
        }
        else if (section == 2) {
            return productsDetails.count
        }
        else{
            return 1
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        if (indexPath.section == 0){
            return 44
        }
        else if (indexPath.section == 1){
            return 410
        }
        else if (indexPath.section == 2){
            return 120
        }
        else{
            return 230
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath.section == 0){
            let paymentcell = tableView.dequeueReusableCell(withIdentifier: "paymentcell",for:indexPath) as! paymentTableViewCell
            myActivityIndicator.stopAnimating()
            let arr = self.paymentmethodsArray[indexPath.row]
            paymentcell.paymentNameLabel.text = arr["name"]as? String
            paymentcell.radioButton.tag = indexPath.row
            let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
            if(checkIndex != nil){
                paymentcell.radioButton.isSelected = true
            }else{
                paymentcell.radioButton.isSelected = false
            }
            return paymentcell
        }
        else if (indexPath.section == 1){
            let shippingAddresscell = tableView.dequeueReusableCell(withIdentifier: "shippingaddresscell",for:indexPath) as! ShippingAddressTableViewCell
            shippingAddresscell.nameLabel.text = name
            shippingAddresscell.addressLabel.text = billingaddress
            shippingAddresscell.mobileNumberLabel.text = String(describing: phoneNumber)
            shippingAddresscell.shippingNameLabel.text = name
            shippingAddresscell.shippingAddressLabel.text = billingaddress
            shippingAddresscell.shippingMobileNumberLabel.text = String(describing: phoneNumber)
            shippingAddresscell.shippingMethodNameLabel.text = shippingMethod
            shippingAddresscell.paymentMethodNameLabel.text = paymentMethod
            return shippingAddresscell
        }
        else if (indexPath.section == 2){
            let productNamecell = tableView.dequeueReusableCell(withIdentifier: "productNamecell",for:indexPath) as! ProductNameTableViewCell
            let arr = productsDetails[indexPath.row]
            let array = arr["product name"] as! String
            productNamecell.productNameLabel.text = array
            productNamecell.priceLabel.text = arr["Price"] as! String
            productNamecell.QuantityLabel.text = String(describing: arr["Quantity"] as! Int)
            productNamecell.subTotalLabel.text = arr["SubTotal"] as! String
            return productNamecell
        }
        else{
            let ordercell = tableView.dequeueReusableCell(withIdentifier: "ordercell",for:indexPath) as! orderTableViewCell
            ordercell.subTotalLabel.text = subTotal
            ordercell.shippingLabel.text = shippingHandling
            ordercell.grandTotalLabel.text = total
            return ordercell
        }
    }
</code>```

答:
Here you need to change the numberOfSections method according to the condition. Instead of returning numberOfSections as 4 you need to change it according to the radio button selection.
You can keep a boolean variable to check whether the button is selected or not and based on its value change numberOfSections method like

```<code>func numberOfSections(in tableView: UITableView) -> Int{
let numberOfRows = ifRadioButtonSelected ? 4 : 1
     return numberOfRows
    }
</code>```

Body:
Here i am having four sections in a table view but in  the first section all the cells are having radio buttons. Whenever it is active, I need to show remaining three sections, if not I need to hide the remaining last three sections can anyone help me how to implement this ?

The image is as shown below ?

 @IBAction func selectRadioButton(_ sender: KGRadioButton) {
        let chekIndex = self.checkIsRadioSelect.index(of: sender.tag)
        if sender.isSelected {

        } else{
            if(chekIndex == nil){
                self.checkIsRadioSelect.removeAll(keepingCapacity: false)
                self.checkIsRadioSelect.append(sender.tag)
                self.ProductTableView.reloadData()
            }
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int{
     return 4
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if (section == 0){
            return "PAYMENT INFORMATION"
        }
        else if (section == 1){
            return "ORDER REVIEW"
        }
        else if (section == 2){
            return "PRODUCT"
        }
        else{
            return ""
        }
    }
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
        let header = view as! UITableViewHeaderFooterView
        header.textLabel?.textColor = UIColor.gray
        header.textLabel?.textAlignment = NSTextAlignment.center
        header.textLabel?.font = UIFont(name: "Futura", size: 17)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (section == 0){
            return paymentmethodsArray.count
        }
        else if (section == 2) {
            return productsDetails.count
        }
        else{
            return 1
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        if (indexPath.section == 0){
            return 44
        }
        else if (indexPath.section == 1){
            return 410
        }
        else if (indexPath.section == 2){
            return 120
        }
        else{
            return 230
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath.section == 0){
            let paymentcell = tableView.dequeueReusableCell(withIdentifier: "paymentcell",for:indexPath) as! paymentTableViewCell
            myActivityIndicator.stopAnimating()
            let arr = self.paymentmethodsArray[indexPath.row]
            paymentcell.paymentNameLabel.text = arr["name"]as? String
            paymentcell.radioButton.tag = indexPath.row
            let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
            if(checkIndex != nil){
                paymentcell.radioButton.isSelected = true
            }else{
                paymentcell.radioButton.isSelected = false
            }
            return paymentcell
        }
        else if (indexPath.section == 1){
            let shippingAddresscell = tableView.dequeueReusableCell(withIdentifier: "shippingaddresscell",for:indexPath) as! ShippingAddressTableViewCell
            shippingAddresscell.nameLabel.text = name
            shippingAddresscell.addressLabel.text = billingaddress
            shippingAddresscell.mobileNumberLabel.text = String(describing: phoneNumber)
            shippingAddresscell.shippingNameLabel.text = name
            shippingAddresscell.shippingAddressLabel.text = billingaddress
            shippingAddresscell.shippingMobileNumberLabel.text = String(describing: phoneNumber)
            shippingAddresscell.shippingMethodNameLabel.text = shippingMethod
            shippingAddresscell.paymentMethodNameLabel.text = paymentMethod
            return shippingAddresscell
        }
        else if (indexPath.section == 2){
            let productNamecell = tableView.dequeueReusableCell(withIdentifier: "productNamecell",for:indexPath) as! ProductNameTableViewCell
            let arr = productsDetails[indexPath.row]
            let array = arr["product name"] as! String
            productNamecell.productNameLabel.text = array
            productNamecell.priceLabel.text = arr["Price"] as! String
            productNamecell.QuantityLabel.text = String(describing: arr["Quantity"] as! Int)
            productNamecell.subTotalLabel.text = arr["SubTotal"] as! String
            return productNamecell
        }
        else{
            let ordercell = tableView.dequeueReusableCell(withIdentifier: "ordercell",for:indexPath) as! orderTableViewCell
            ordercell.subTotalLabel.text = subTotal
            ordercell.shippingLabel.text = shippingHandling
            ordercell.grandTotalLabel.text = total
            return ordercell
        }
    }

Body:
Here you need to change the numberOfSections method according to the condition. Instead of returning numberOfSections as 4 you need to change it according to the radio button selection.
You can keep a boolean variable to check whether the button is selected or not and based on its value change numberOfSections method like

func numberOfSections(in tableView: UITableView) -> Int{
let numberOfRows = ifRadioButtonSelected ? 4 : 1
     return numberOfRows
    }


问:
SQL: How to return any Part that occurs more than Once
I have the following query which returns the following error:
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

SELECT Part from Parts Where count(Part) > 1

How could i rewrite it to return the part that appears more than once.

答:
You need to use a GROUP BY and HAVING clause like this:</p>

```<code>SELECT part
FROM Parts
GROUP BY part
HAVING COUNT(*) > 1
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You need to use a GROUP BY and HAVING clause like this:

SELECT part
FROM Parts
GROUP BY part
HAVING COUNT(*) > 1


问:
Java libGDX different sizes of animation frames
How to deal with different sizes of frames? If I setBounds(0, 0, 100, 100) in constructor then some frames are smaller but if I update it then frames are moved to left and up. How to make that every frame will be in the same place?

mayby you can see it
http://imgur.com/a/AN8Gc

```<code>public class Player extends Sprite{

//floats
private float animationTimer;

//box2d variables
public World world;
public Body body;

//enums
public enum State{STANDING, MOVING, SHOOTING, RELOAD, MALEE_ATTACK}
public State currentState;
public State previousState;

//booleans
boolean shoot;
boolean reload;
boolean maleeAttack;

private TextureRegion region;

public PlayScreen playScreen;

public Player(PlayScreen playScreen){
    this.playScreen = playScreen;
    this.world = playScreen.getWorld();
    definePlayer();

    animationTimer = 0;

    region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);

    setRegion(region);
    setBounds(0, 0, getRegionWidth() / Constants.PPM, getRegionHeight() / Constants.PPM);
    setPosition(0, 0);

    currentState = State.STANDING;
    previousState = State.STANDING;

    shoot = false;
    reload = false;
    maleeAttack = false;
}

public void definePlayer(){
    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(100 / Constants.PPM, 100 / Constants.PPM);
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    body = world.createBody(bodyDef);

    FixtureDef fixtureDef = new FixtureDef();
    CircleShape shape = new CircleShape();
    shape.setRadius(50 / Constants.PPM);
    fixtureDef.shape = shape;
    body.createFixture(fixtureDef).setUserData(this);

    body.setLinearDamping(Constants.LINEAR_DAMPING);
}

public void update(float delta){
    region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);
    setRegion(getFrame(delta));
    moving();
    //rotate();

}

public void moving(){
    setPosition(body.getPosition().x - getWidth() / 2,  body.getPosition(). y - getHeight() / 2);
//setBounds(0, 0, getRegionWidth() / Constants.PPM, getRegionHeight() / Constants.PPM); update bounds
    if (input.isKeyPressed(Input.Keys.W) && body.getLinearVelocity().y < 5){
        body.applyLinearImpulse(new Vector2(0, 1), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.S) && body.getLinearVelocity().y > -5){
        body.applyLinearImpulse(new Vector2(0, -1), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.D) && body.getLinearVelocity().x < 5){
        body.applyLinearImpulse(new Vector2(1, 0), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.A) && body.getLinearVelocity().x > -5){
        body.applyLinearImpulse(new Vector2(-1, 0), body.getWorldCenter(), true);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.R)){
        reload = true;
    }

    if (Gdx.input.isKeyPressed(Input.Keys.F)){
        maleeAttack = true;
    }
    if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)){
        shoot = true;
    }

}

public TextureRegion getFrame(float delta){
    TextureRegion region;

    currentState = getState();

    switch (currentState){
        case MOVING:
            region = Assets.instance.playerAssets.moveAnimation.getKeyFrame(animationTimer);
            break;
        case SHOOTING:
            maleeAttack = false;
            region = Assets.instance.playerAssets.shootAniamtion.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.shootAniamtion.isAnimationFinished(animationTimer)){
                shoot = false;
            }
            break;
        case RELOAD:
            region = Assets.instance.playerAssets.reloadAnimation.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.reloadAnimation.isAnimationFinished(animationTimer)){
                reload = false;
            }
            break;
        case MALEE_ATTACK:
            region = Assets.instance.playerAssets.maleeAttackAnimation.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.maleeAttackAnimation.isAnimationFinished(animationTimer)) {
                maleeAttack = false;
            }
            break;
        default:
            region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);
            break;
    }

    animationTimer = currentState == previousState ? animationTimer + delta : 0;
    previousState = currentState;

    return region;
}

public State getState(){
    if ((body.getLinearVelocity().x > 1 || body.getLinearVelocity().x < -1 || body.getLinearVelocity().y > 1 || body.getLinearVelocity().y < - 1)  && !reload && !shoot && !maleeAttack){
        return State.MOVING;
    }
    if (shoot && !reload){
        return State.SHOOTING;
    }
    if (reload && !maleeAttack){
        return State.RELOAD;
    }
    if (maleeAttack){
        return State.MALEE_ATTACK;
    }
    else {
        return State.STANDING;
    }
}

public Vector2 getMousePosition(){
    Vector2 mousePosition;
    mousePosition = playScreen.getViewport().unproject(new Vector2(Gdx.input.getX(), Gdx.input.getY()));
    return mousePosition;
}

public float getMouseAngle(){
    float angle = (float) Math.atan2(getMousePosition().y - body.getPosition().y, getMousePosition().x -  body.getPosition().x);
    return angle;
}

public void rotate(){
    setOrigin(getWidth() / 2, getHeight() / 2 );
    setRotation((float) (getMouseAngle() * (180/Math.PI)));
    body.setTransform(body.getPosition(), getMouseAngle());
}
</code>```

}

答:
You need to use the additional data information a TextureAtlas provides as an AtlasRegion.

One complete animation should have the same (width/height) size for each keyframe. Pick a size where the biggest keyfarme fits into. Also be aware of positioning correctly. Have the same pivot point for each keyframe.

To avoid wasting space when packing your TextureAtlas enable "trim" function. Should be supported by any TexturePacker Tool out there.

The texture data file (for libGDX) then has entries like this:

```<code>walk_animation
  rotate: false
  xy: 794, 235
  size: 86, 109
  orig: 160, 170
  offset: 37, 22
  index: 5
</code>```

Use the AtlasRegion to draw things at the correct size and position:

```<code>float width = 400; // pick your size here
float height = 300;

float offsetPctX = atlasRegion.offsetX / atlasRegion.originalWidth;
float offsetPctY = atlasRegion.offsetY / atlasRegion.originalHeight;

float scaleWidth = (float) atlasRegion.packedWidth / atlasRegion.originalWidth;
float scaleHeight = (float) atlasRegion.packedHeight / atlasRegion.originalHeight;

float drawWidth = width * scaleWidth;
float drawHeight = height * scaleHeight;

float regionOffsetX = offsetPctX * width;
float regionOffsetY = offsetPctY * height;

float drawScaleX = 1; // adjust to your needs
float drawScaleY = 1;

float drawOriginX = 0; // adjust to tour needs
float drawOriginY = 0;

float drawRotation = false;

float x = 100 + offsetX + regionOffsetX; // adjust to your needs
float y = 100 + offsetY + regionOffsetY;

spriteBatch.draw(atlasRegion, x, y, drawOriginX, drawOriginY, drawWidth, drawHeight, drawScaleX, drawScaleY, drawRotation);
</code>```

Body:
How to deal with different sizes of frames? If I setBounds(0, 0, 100, 100) in constructor then some frames are smaller but if I update it then frames are moved to left and up. How to make that every frame will be in the same place?

mayby you can see it
http://imgur.com/a/AN8Gc

public class Player extends Sprite{

//floats
private float animationTimer;

//box2d variables
public World world;
public Body body;

//enums
public enum State{STANDING, MOVING, SHOOTING, RELOAD, MALEE_ATTACK}
public State currentState;
public State previousState;

//booleans
boolean shoot;
boolean reload;
boolean maleeAttack;

private TextureRegion region;

public PlayScreen playScreen;

public Player(PlayScreen playScreen){
    this.playScreen = playScreen;
    this.world = playScreen.getWorld();
    definePlayer();

    animationTimer = 0;

    region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);

    setRegion(region);
    setBounds(0, 0, getRegionWidth() / Constants.PPM, getRegionHeight() / Constants.PPM);
    setPosition(0, 0);

    currentState = State.STANDING;
    previousState = State.STANDING;

    shoot = false;
    reload = false;
    maleeAttack = false;
}

public void definePlayer(){
    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(100 / Constants.PPM, 100 / Constants.PPM);
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    body = world.createBody(bodyDef);

    FixtureDef fixtureDef = new FixtureDef();
    CircleShape shape = new CircleShape();
    shape.setRadius(50 / Constants.PPM);
    fixtureDef.shape = shape;
    body.createFixture(fixtureDef).setUserData(this);

    body.setLinearDamping(Constants.LINEAR_DAMPING);
}

public void update(float delta){
    region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);
    setRegion(getFrame(delta));
    moving();
    //rotate();

}

public void moving(){
    setPosition(body.getPosition().x - getWidth() / 2,  body.getPosition(). y - getHeight() / 2);
//setBounds(0, 0, getRegionWidth() / Constants.PPM, getRegionHeight() / Constants.PPM); update bounds
    if (input.isKeyPressed(Input.Keys.W) && body.getLinearVelocity().y < 5){
        body.applyLinearImpulse(new Vector2(0, 1), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.S) && body.getLinearVelocity().y > -5){
        body.applyLinearImpulse(new Vector2(0, -1), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.D) && body.getLinearVelocity().x < 5){
        body.applyLinearImpulse(new Vector2(1, 0), body.getWorldCenter(), true);
    }
    if (input.isKeyPressed(Input.Keys.A) && body.getLinearVelocity().x > -5){
        body.applyLinearImpulse(new Vector2(-1, 0), body.getWorldCenter(), true);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.R)){
        reload = true;
    }

    if (Gdx.input.isKeyPressed(Input.Keys.F)){
        maleeAttack = true;
    }
    if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)){
        shoot = true;
    }

}

public TextureRegion getFrame(float delta){
    TextureRegion region;

    currentState = getState();

    switch (currentState){
        case MOVING:
            region = Assets.instance.playerAssets.moveAnimation.getKeyFrame(animationTimer);
            break;
        case SHOOTING:
            maleeAttack = false;
            region = Assets.instance.playerAssets.shootAniamtion.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.shootAniamtion.isAnimationFinished(animationTimer)){
                shoot = false;
            }
            break;
        case RELOAD:
            region = Assets.instance.playerAssets.reloadAnimation.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.reloadAnimation.isAnimationFinished(animationTimer)){
                reload = false;
            }
            break;
        case MALEE_ATTACK:
            region = Assets.instance.playerAssets.maleeAttackAnimation.getKeyFrame(animationTimer);
            if (Assets.instance.playerAssets.maleeAttackAnimation.isAnimationFinished(animationTimer)) {
                maleeAttack = false;
            }
            break;
        default:
            region = Assets.instance.playerAssets.idleAniamtion.getKeyFrame(animationTimer);
            break;
    }

    animationTimer = currentState == previousState ? animationTimer + delta : 0;
    previousState = currentState;

    return region;
}

public State getState(){
    if ((body.getLinearVelocity().x > 1 || body.getLinearVelocity().x < -1 || body.getLinearVelocity().y > 1 || body.getLinearVelocity().y < - 1)  && !reload && !shoot && !maleeAttack){
        return State.MOVING;
    }
    if (shoot && !reload){
        return State.SHOOTING;
    }
    if (reload && !maleeAttack){
        return State.RELOAD;
    }
    if (maleeAttack){
        return State.MALEE_ATTACK;
    }
    else {
        return State.STANDING;
    }
}

public Vector2 getMousePosition(){
    Vector2 mousePosition;
    mousePosition = playScreen.getViewport().unproject(new Vector2(Gdx.input.getX(), Gdx.input.getY()));
    return mousePosition;
}

public float getMouseAngle(){
    float angle = (float) Math.atan2(getMousePosition().y - body.getPosition().y, getMousePosition().x -  body.getPosition().x);
    return angle;
}

public void rotate(){
    setOrigin(getWidth() / 2, getHeight() / 2 );
    setRotation((float) (getMouseAngle() * (180/Math.PI)));
    body.setTransform(body.getPosition(), getMouseAngle());
}

}

Body:
You need to use the additional data information a TextureAtlas provides as an AtlasRegion.

One complete animation should have the same (width/height) size for each keyframe. Pick a size where the biggest keyfarme fits into. Also be aware of positioning correctly. Have the same pivot point for each keyframe.

To avoid wasting space when packing your TextureAtlas enable "trim" function. Should be supported by any TexturePacker Tool out there.

The texture data file (for libGDX) then has entries like this:

walk_animation
  rotate: false
  xy: 794, 235
  size: 86, 109
  orig: 160, 170
  offset: 37, 22
  index: 5

Use the AtlasRegion to draw things at the correct size and position:

float width = 400; // pick your size here
float height = 300;

float offsetPctX = atlasRegion.offsetX / atlasRegion.originalWidth;
float offsetPctY = atlasRegion.offsetY / atlasRegion.originalHeight;

float scaleWidth = (float) atlasRegion.packedWidth / atlasRegion.originalWidth;
float scaleHeight = (float) atlasRegion.packedHeight / atlasRegion.originalHeight;

float drawWidth = width * scaleWidth;
float drawHeight = height * scaleHeight;

float regionOffsetX = offsetPctX * width;
float regionOffsetY = offsetPctY * height;

float drawScaleX = 1; // adjust to your needs
float drawScaleY = 1;

float drawOriginX = 0; // adjust to tour needs
float drawOriginY = 0;

float drawRotation = false;

float x = 100 + offsetX + regionOffsetX; // adjust to your needs
float y = 100 + offsetY + regionOffsetY;

spriteBatch.draw(atlasRegion, x, y, drawOriginX, drawOriginY, drawWidth, drawHeight, drawScaleX, drawScaleY, drawRotation);


问:
artifactory yum relative path not working
I have https://packages.cloud.google.com/yum configured as a remote repo in Artifactory.

My repo file on Centos 7.3 looks like this:

```<code>    [kubernetes]
    name=kubernetes
    baseurl=https://artifactory.company.com/artifactory/packages.cloud.google.com-yum/repos/kubernetes-el7-x86_64/
    enabled=1
    gpgcheck=1
</code>```

When I run yum install -y kubelet it prints this error:

```<code>    e7a4403227dd24036f3b0615663a37 FAILED
    https://artifactory.company.com/artifactory/packages.cloud.google.com-yum/repos/kubernetes-el7-x86_64/../../pool/e7a4403227dd24036f3b0615663a371c4e07a95be5fee53505e647fd8ae58aa6-kubernetes-cni-0.5.1-0.x86_64.rpm: [Errno 14] HTTPS Error 500 - Internal Server Error
    Trying other mirror.
</code>```

I am pretty sure the problem is the relative path in the URL: kubernetes-el7-x86_64/../../pool

If I wget the URL it works fine because wget is resolving out the relative path before sending the HTTP request, but yum does not do this and Artifactory returns a 500 when you give it a url with ../ in it. Does anyone know how to enable relative URLs in Artifactory? Or how to get yum to resolve URLs before sending the requests?

I am running these versions:

Artifactory 5.2.0

Yum 3.4.3-150

Update: This is the HTTP response body from artifactory:

```<code>    {
      "errors" : [ {
        "status" : 500,
        "message" : "Could not process download request: Path element cannot end with a dot: packages.cloud.google.com-yum-cache/repos/kubernetes-el7-x86_64/../"
      } ]
    }
</code>```

答:
The remote repository should be set with the following url in Artifactory
https://packages.cloud.google.com/yum/

The baseurl on the yum client should point on the repodata folder with the following:
baseurl=http://artifactory.company.com/artifactory/yum-remote/repos/kubernetes-el7-x86_64/
(The name of the remote repository is 'yum remote')

This should work without any further configuration from the Artifactory side.

The error you have mentioned regardin the relative path 'kubernetes-el7-x86_64/../../pool' happens during the caching of the artifact.
Artifactory cannot cache to a path which contains the '..' pattern so the request is failing.
It can be solved from Artifactory side with a user plugin.
If the path contains the '..' pattern then the plugin will modify the path where the artifact will cached so it will not include this pattern.
This is now redundant as the registry retrieves paths which doesn't include '..' in them.

Body:
I have https://packages.cloud.google.com/yum configured as a remote repo in Artifactory.

My repo file on Centos 7.3 looks like this:

    [kubernetes]
    name=kubernetes
    baseurl=https://artifactory.company.com/artifactory/packages.cloud.google.com-yum/repos/kubernetes-el7-x86_64/
    enabled=1
    gpgcheck=1

When I run yum install -y kubelet it prints this error:

    e7a4403227dd24036f3b0615663a37 FAILED
    https://artifactory.company.com/artifactory/packages.cloud.google.com-yum/repos/kubernetes-el7-x86_64/../../pool/e7a4403227dd24036f3b0615663a371c4e07a95be5fee53505e647fd8ae58aa6-kubernetes-cni-0.5.1-0.x86_64.rpm: [Errno 14] HTTPS Error 500 - Internal Server Error
    Trying other mirror.

I am pretty sure the problem is the relative path in the URL: kubernetes-el7-x86_64/../../pool

If I wget the URL it works fine because wget is resolving out the relative path before sending the HTTP request, but yum does not do this and Artifactory returns a 500 when you give it a url with ../ in it. Does anyone know how to enable relative URLs in Artifactory? Or how to get yum to resolve URLs before sending the requests?

I am running these versions:

Artifactory 5.2.0

Yum 3.4.3-150

Update: This is the HTTP response body from artifactory:

    {
      "errors" : [ {
        "status" : 500,
        "message" : "Could not process download request: Path element cannot end with a dot: packages.cloud.google.com-yum-cache/repos/kubernetes-el7-x86_64/../"
      } ]
    }


问:
How to check SqLite database file and get my defined database user-version?
I am developing an app that using sq-lite database. in my app when user tap on backup my sq-lite db file save on another place. i now write a new version of my app and in new version my sq-lite db has some more fields. how can i check sq-lite database file and get user-version of that file to open it with true fields avoiding force-close?
in new version off my app the db version is 2:

```<code>private final static String DB_NAME="cDb";
private final static String DB_TABLE="_table";
private final static int DB_VERSION=2;
</code>```

But in old version my db version is 1.
How can i check if my db file is for version 1 or 2?

答:
In phonegap sqlite (cordova-sqlite-storage plugin), you can get user_version as :</p>

```<code>db.executeSql('PRAGMA user_version', [], migrate, function(){console.log('unable to fetch user_version');});

function migrate(db, resultSet {console.log(resultSet.rows.item(0).user_version);}
</code>```

Body:
I am developing an app that using sq-lite database. in my app when user tap on backup my sq-lite db file save on another place. i now write a new version of my app and in new version my sq-lite db has some more fields. how can i check sq-lite database file and get user-version of that file to open it with true fields avoiding force-close?
in new version off my app the db version is 2:

private final static String DB_NAME="cDb";
private final static String DB_TABLE="_table";
private final static int DB_VERSION=2;

But in old version my db version is 1.
How can i check if my db file is for version 1 or 2?

Body:
In phonegap sqlite (cordova-sqlite-storage plugin), you can get user_version as :

db.executeSql('PRAGMA user_version', [], migrate, function(){console.log('unable to fetch user_version');});

function migrate(db, resultSet {console.log(resultSet.rows.item(0).user_version);}


问:
TextInputLayout enabled not saved after destroy and recreate
Simple layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.infinitebounds.myapplication.Main2Activity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/tip"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <EditText
            android:id="@+id/et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="hint" />
    </android.support.design.widget.TextInputLayout>
</LinearLayout>
</code>```

And I am disabling the textInputLayout if the activity is initialised for the first time:

```<code>class Main2Activity : AppCompatActivity() {

    lateinit var tip: TextInputLayout
    lateinit var et: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        tip = findViewById(R.id.tip) as TextInputLayout
        et = findViewById(R.id.et) as EditText

        if (savedInstanceState == null) tip.isEnabled = false
    }
}
</code>```

I have checked "Don't Keep Activities" option.

So initially when the activity is launched, the TextInputLayout is disabled. When I press home and come back, it is re-enabled again.

So my questions are:

Is this the expected behaviour?

How do I keep TextInputLayout disabled when recreated?

Edit:

This seems to happen with the EditText as well.

答:
Is this the expected behaviour?

Yes, it is (assuming "Don't Keep Activities" is checked).

First time the app is being launched the savedInstanceState is null - your if check passes and sets TextInputLayout's state to disabled.

As soon as you press home button and come back, onCreate() is being called, but this time savedInstanceState is not null - your if check does not pass.

How do I keep TextInputLayout disabled when recreated?

Get rid of of if check entirely, it's useless. Perform tip.isEnabled = false directly within onCreate(), or perform that in xml: android:enabled="false".

Body:
Simple layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.infinitebounds.myapplication.Main2Activity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/tip"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <EditText
            android:id="@+id/et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="hint" />
    </android.support.design.widget.TextInputLayout>
</LinearLayout>

And I am disabling the textInputLayout if the activity is initialised for the first time:

class Main2Activity : AppCompatActivity() {

    lateinit var tip: TextInputLayout
    lateinit var et: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        tip = findViewById(R.id.tip) as TextInputLayout
        et = findViewById(R.id.et) as EditText

        if (savedInstanceState == null) tip.isEnabled = false
    }
}

I have checked "Don't Keep Activities" option.

So initially when the activity is launched, the TextInputLayout is disabled. When I press home and come back, it is re-enabled again.

So my questions are:

Is this the expected behaviour?

How do I keep TextInputLayout disabled when recreated?

Edit:

This seems to happen with the EditText as well.


问:
How to deploy Node app to server
I have an Angular app that I have on a server and loads the html page when the page loads. I have since made it a fullstack app by using node which entry point is server.js which holds the routes.

Locally, I run node server.js in a powershell cmd but I dont know how to do that on the remote server

How do I tell the server that this is now a node app and that it needs to initally run server.js instead of the angular's html page?

答: The command is node server.js. Alternatively you can download nodemon which restarts the server everytime the code is changed.</p>

Title: How to deploy Node app to server


问:
sending notifications with alarmmanager and Broadcast receiver
Actually I have implemented notifications for my app.Whenever I click a button it set the time for notification and call broadcast receiver.but when the request for 3 notifications like one for 3 pm,4 pm,5 pm is sent it send only 5 pm notification not 3 pm and 4 pm because 5 pm one was triggered last. I think it is related with notification id. I am passing id as 0.what I should do.please help.

my broadcast receiver

```<code>public class NotificationMessage extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        Log.d("Tag","dd");
        showNotification(context);
    }

    private void showNotification(Context context) {
        Log.d("Tag", "visible");

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.logo)
                        .setContentTitle("HURRY UP!!")
                        .setContentText("You have a session in 15 minutes.");
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        int notiid = preferences.getInt("Id", -1 );

        int notification_id = notiid;
        Log.d("ID1", String.valueOf(notification_id));

        mNotificationManager.notify(notification_id, mBuilder.build());
        Log.d("Tag","fuck u");
    }
}
</code>```

this is where I am calling:

```<code>holder.accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                Call<AcceptedDealResponse> call = service.acceptedDeal(acceptDealRequest);
                call.enqueue(new Callback<AcceptedDealResponse>() {
                    @Override
                    public void onResponse(Call<AcceptedDealResponse> call, Response<AcceptedDealResponse> response) {
                        AcceptedDealResponse response1 = response.body();
                        if(response.body().getMessage().equals("Successful !! Deal Booked !!")){
                            Log.d(",,", "" + " deal boooked");

                            Log.d("jkhdjksahda  ","" + newDealResponsess.getResponses().get(position).getTimeFrom() );

                            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                            try {
                                date1 = formatter.parse(String.valueOf(newDealResponsess.getResponses().get(position).getTimeFrom()));

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            cal = Calendar.getInstance();
                            cal.setTime(date1);

                            Log.d("Tag", String.valueOf(cal.get(Calendar.DATE)));

                            calendar = Calendar.getInstance();

                            calendar.set(Calendar.YEAR, cal.get(Calendar.YEAR));
                            calendar.set(Calendar.MONTH, cal.get(Calendar.MONTH));
                            calendar.set(Calendar.DATE, cal.get(Calendar.DATE));
                            calendar.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
                            calendar.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
                            calendar.set(Calendar.SECOND, cal.get(Calendar.SECOND));

                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.HOUR_OF_DAY));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.MINUTE));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.SECOND));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.DATE));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.MONTH));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.YEAR));

                            Intent notificationmassage = new Intent(v.getContext(),NotificationMessage.class);

                            Log.d("Tag","cool");

                            PendingIntent pi = PendingIntent.getBroadcast(v.getContext(), 0,notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT);

                            Log.d("Tag","cooled");
                            AlarmManager am = (AlarmManager) v.getContext().getSystemService(ALARM_SERVICE);
                            Log.d("Tag","cooooled");

                            int id = (int) calendar.getTimeInMillis();

                            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putInt("Id", id);
                            Log.d("ID", String.valueOf(id));
                            editor.apply();

                            am.set(AlarmManager.RTC_WAKEUP, (calendar.getTimeInMillis() - 900000), pi);
</code>```

答:
I guess the problem is in your PendingIntent with same REQUEST_CODE. May be you have used same REQUEST_CODE with your PendingInetent for all alarm when setting an alarm using AlarmManager.

Try using different REQUEST_CODE for different PendingIntent for
  different Alarm.

Use below code for setting Alarm using AlarmManager:

```<code>    int notiId = UNIQUE_ID;

    // Intent
    Intent mIntent = new Intent(getApplicationContext(), NotificationMessage.class);
    mIntent.putExtra("NOTIFICATION_ID", notiId);

    // Pending broadcast intent
    PendingIntent mPI = PendingIntent.getBroadcast(getApplicationContext(),
                        notiId, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Alarm manager
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, TARGET_TIME_MILLISECONDS, mPI);
</code>```

Hope this will work~

Body:
Actually I have implemented notifications for my app.Whenever I click a button it set the time for notification and call broadcast receiver.but when the request for 3 notifications like one for 3 pm,4 pm,5 pm is sent it send only 5 pm notification not 3 pm and 4 pm because 5 pm one was triggered last. I think it is related with notification id. I am passing id as 0.what I should do.please help.

my broadcast receiver

public class NotificationMessage extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        Log.d("Tag","dd");
        showNotification(context);
    }

    private void showNotification(Context context) {
        Log.d("Tag", "visible");

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.logo)
                        .setContentTitle("HURRY UP!!")
                        .setContentText("You have a session in 15 minutes.");
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        int notiid = preferences.getInt("Id", -1 );

        int notification_id = notiid;
        Log.d("ID1", String.valueOf(notification_id));

        mNotificationManager.notify(notification_id, mBuilder.build());
        Log.d("Tag","fuck u");
    }
}

this is where I am calling:

holder.accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                Call<AcceptedDealResponse> call = service.acceptedDeal(acceptDealRequest);
                call.enqueue(new Callback<AcceptedDealResponse>() {
                    @Override
                    public void onResponse(Call<AcceptedDealResponse> call, Response<AcceptedDealResponse> response) {
                        AcceptedDealResponse response1 = response.body();
                        if(response.body().getMessage().equals("Successful !! Deal Booked !!")){
                            Log.d(",,", "" + " deal boooked");

                            Log.d("jkhdjksahda  ","" + newDealResponsess.getResponses().get(position).getTimeFrom() );

                            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                            try {
                                date1 = formatter.parse(String.valueOf(newDealResponsess.getResponses().get(position).getTimeFrom()));

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            cal = Calendar.getInstance();
                            cal.setTime(date1);

                            Log.d("Tag", String.valueOf(cal.get(Calendar.DATE)));

                            calendar = Calendar.getInstance();

                            calendar.set(Calendar.YEAR, cal.get(Calendar.YEAR));
                            calendar.set(Calendar.MONTH, cal.get(Calendar.MONTH));
                            calendar.set(Calendar.DATE, cal.get(Calendar.DATE));
                            calendar.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
                            calendar.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
                            calendar.set(Calendar.SECOND, cal.get(Calendar.SECOND));

                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.HOUR_OF_DAY));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.MINUTE));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.SECOND));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.DATE));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.MONTH));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.YEAR));

                            Intent notificationmassage = new Intent(v.getContext(),NotificationMessage.class);

                            Log.d("Tag","cool");

                            PendingIntent pi = PendingIntent.getBroadcast(v.getContext(), 0,notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT);

                            Log.d("Tag","cooled");
                            AlarmManager am = (AlarmManager) v.getContext().getSystemService(ALARM_SERVICE);
                            Log.d("Tag","cooooled");

                            int id = (int) calendar.getTimeInMillis();

                            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putInt("Id", id);
                            Log.d("ID", String.valueOf(id));
                            editor.apply();

                            am.set(AlarmManager.RTC_WAKEUP, (calendar.getTimeInMillis() - 900000), pi);

Body:
I guess the problem is in your PendingIntent with same REQUEST_CODE. May be you have used same REQUEST_CODE with your PendingInetent for all alarm when setting an alarm using AlarmManager.

Try using different REQUEST_CODE for different PendingIntent for
  different Alarm.

Use below code for setting Alarm using AlarmManager:

    int notiId = UNIQUE_ID;

    // Intent
    Intent mIntent = new Intent(getApplicationContext(), NotificationMessage.class);
    mIntent.putExtra("NOTIFICATION_ID", notiId);

    // Pending broadcast intent
    PendingIntent mPI = PendingIntent.getBroadcast(getApplicationContext(),
                        notiId, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Alarm manager
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, TARGET_TIME_MILLISECONDS, mPI);

Hope this will work~


问:
Is the query processing fast if I create an index on a column but make a query for multiple column out of which one is the indexed column?
For example, let's say I created index on 'id' but I make a query like this:

```<code>select id, class, name from student;
</code>```

Will the query processing be random or will it be optimised according to the id column?

答:
Obviously it's optimized.
As index is there on id column it will make faster execution of same query.</p>

Body:
For example, let's say I created index on 'id' but I make a query like this:

select id, class, name from student;

Will the query processing be random or will it be optimised according to the id column?


问:
Override ActionMailer defaults with a method called from inside any mailer
Given we have a custom header set in application.rb as

config.action_mailer.default_options = {
    'X-MyCustomHeader' => "Default_value" }

I would like to be able to call a method, such as remove_custom_headerfrom inside any mailer and it have the header removed, or at least set to nil.

Because its a custom header (starting with X-) ActionMailer will allow more than one to be created rather than reseting it as it would with standard headers.

What is the best way to define a method that can overide it?

The issue i have is that is you call headers['X-MyCustomHeader'] = nilinside the mailer method it will not override it, it simply creates a second header where the entry is nil, leaving the original from application.rb on the email.

The only way i can find to override the default set there is to call default 'X-MyCustomHeader' => nil inside the ApplicationMailer (or in any inheriting mailers class'), like below, but not in the method.

```<code>    class ApplicatioMailer < ActionMailer::Base
       helper :application
       default 'X-MyCustomHeader' => nil
     end
</code>```

but i would like to call this on a method basis, not in the mailer class itself as the app has many many mailer classes and im looking to disable this for one or 2 methods in some of the Mailers.

My current solution is:

```<code>      class ApplicatioMailer < ActionMailer::Base
        helper :application
        default 'X-MyCustomHeader' => Proc.new { @is_disabled ? nil : Rails.config.action_mailer.default_header }

        def remove_custom_header
          @is_disabled = true
        end
      end
</code>```

and this seems to work as you are using the default call from ActionMailer to override. Now i have tested this and it does work with multiple calls, so  the value of @is_disableddoes not seem to persist between mailer calls. I dont understand how the class var works here, in a SuperClass of the mailer that calls it and when no new object of the class is created, but it seems to be null every new call to the ApplicationMailer, so for me it works. However, is this a good solution? Have i missed something obvious? I dont feel comfterable using a class var in this situation, but i can think of another way!

Thanks in advance for any help!

EDIT:: For example, i would like to call in my mailers like so..

```<code>    class MyMailer < ApplicatioMailer
      def mail_method_one(email)
        # my call
        remove_custom_header
        mail from: a.format, subject: email.subject
      end
    end
</code>```

And if my method above of setting the class var is valid and sane (which i doubt somehow) can someone explain why as i would be interested how it works and will have to justify it to my lead dev! :)

答:
Contrary to what it looks like, @is_disabled is not a class variable, it's an instance variable.  Just as the method you defined is defined as an instance class

Note that you're doing...

```<code>def mail_method_one(email)
</code>```

...not...

```<code>def self.mail_method_one(email)
</code>```

You can confirm this yourself by stopping execution using the pry gem or some other inspection tool...

```<code>def mail_method_one(email)
  binding.pry
</code>```

And if you examine self you'll see you're in an instance of the mailer.

You do call it as a class method, but that's because action mailer uses method_missing to test if the missing class method is actually an instance method and creates a new instance of MessageDelivery passing the class name, the method name and the arguments, and subsequently calls the method on an instance of the mailer class.

Here's the code where it does that...

```<code>  def method_missing(method_name, *args)
    if action_methods.include?(method_name.to_s)
      MessageDelivery.new(self, method_name, *args)
    else
      super
    end
  end
</code>```

You can examine the code here...
https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb

Body:
Given we have a custom header set in application.rb as

config.action_mailer.default_options = {
    'X-MyCustomHeader' => "Default_value" }

I would like to be able to call a method, such as remove_custom_headerfrom inside any mailer and it have the header removed, or at least set to nil.

Because its a custom header (starting with X-) ActionMailer will allow more than one to be created rather than reseting it as it would with standard headers.

What is the best way to define a method that can overide it?

The issue i have is that is you call headers['X-MyCustomHeader'] = nilinside the mailer method it will not override it, it simply creates a second header where the entry is nil, leaving the original from application.rb on the email.

The only way i can find to override the default set there is to call default 'X-MyCustomHeader' => nil inside the ApplicationMailer (or in any inheriting mailers class'), like below, but not in the method.

    class ApplicatioMailer < ActionMailer::Base
       helper :application
       default 'X-MyCustomHeader' => nil
     end

but i would like to call this on a method basis, not in the mailer class itself as the app has many many mailer classes and im looking to disable this for one or 2 methods in some of the Mailers.

My current solution is:

      class ApplicatioMailer < ActionMailer::Base
        helper :application
        default 'X-MyCustomHeader' => Proc.new { @is_disabled ? nil : Rails.config.action_mailer.default_header }

        def remove_custom_header
          @is_disabled = true
        end
      end

and this seems to work as you are using the default call from ActionMailer to override. Now i have tested this and it does work with multiple calls, so  the value of @is_disableddoes not seem to persist between mailer calls. I dont understand how the class var works here, in a SuperClass of the mailer that calls it and when no new object of the class is created, but it seems to be null every new call to the ApplicationMailer, so for me it works. However, is this a good solution? Have i missed something obvious? I dont feel comfterable using a class var in this situation, but i can think of another way!

Thanks in advance for any help!

EDIT:: For example, i would like to call in my mailers like so..

    class MyMailer < ApplicatioMailer
      def mail_method_one(email)
        # my call
        remove_custom_header
        mail from: a.format, subject: email.subject
      end
    end

And if my method above of setting the class var is valid and sane (which i doubt somehow) can someone explain why as i would be interested how it works and will have to justify it to my lead dev! :)

Body:
Contrary to what it looks like, @is_disabled is not a class variable, it's an instance variable.  Just as the method you defined is defined as an instance class

Note that you're doing...

def mail_method_one(email)

...not...

def self.mail_method_one(email)

You can confirm this yourself by stopping execution using the pry gem or some other inspection tool...

def mail_method_one(email)
  binding.pry

And if you examine self you'll see you're in an instance of the mailer.

You do call it as a class method, but that's because action mailer uses method_missing to test if the missing class method is actually an instance method and creates a new instance of MessageDelivery passing the class name, the method name and the arguments, and subsequently calls the method on an instance of the mailer class.

Here's the code where it does that...

  def method_missing(method_name, *args)
    if action_methods.include?(method_name.to_s)
      MessageDelivery.new(self, method_name, *args)
    else
      super
    end
  end

You can examine the code here...
https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb


问:
java.time.DateTimeException: Hijrah date out of range
today I was discovering Java's 8 Hijrah Date, and I am trying to convert from Hijri date to gregorian date; I have been getting this error:

java.time.DateTimeException: Hijrah date out of range

```<code>    String repayDate = date.substring(0, 4)+"-"+date.substring(4, 6)+"-"+date.substring(6, 8);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date inputDate = dateFormat.parse(repayDate);
        Calendar cl=Calendar.getInstance();
        cl.setTime(inputDate);

        HijrahDate hDate=    HijrahChronology.INSTANCE.date(LocalDate.of(cl.get(1),cl.get(Calendar.MONTH)+1, cl.get(Calendar.DATE)));

        return IsoChronology.INSTANCE.date(hDate).toString() ;
</code>```

the content of date is : 1400-01-01

Thanks

答:
You could parse your input date manually, then create a Hijrah date from it and convert it to Gregorian like this.</p>

```<code>public static LocalDate hijrahToGregorian(String input){
    int year = Integer.parseInt(input.substring(0,4));
    int month = Integer.parseInt(input.substring(4,6));
    int day = Integer.parseInt(input.substring(6,8));

    HijrahDate hijrah = HijrahDate.of(year, month, day);
    return IsoChronology.INSTANCE.date(hijrah);
}
</code>```

Body:
today I was discovering Java's 8 Hijrah Date, and I am trying to convert from Hijri date to gregorian date; I have been getting this error:

java.time.DateTimeException: Hijrah date out of range

    String repayDate = date.substring(0, 4)+"-"+date.substring(4, 6)+"-"+date.substring(6, 8);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date inputDate = dateFormat.parse(repayDate);
        Calendar cl=Calendar.getInstance();
        cl.setTime(inputDate);

        HijrahDate hDate=    HijrahChronology.INSTANCE.date(LocalDate.of(cl.get(1),cl.get(Calendar.MONTH)+1, cl.get(Calendar.DATE)));

        return IsoChronology.INSTANCE.date(hDate).toString() ;

the content of date is : 1400-01-01

Thanks

Body:
You could parse your input date manually, then create a Hijrah date from it and convert it to Gregorian like this.

public static LocalDate hijrahToGregorian(String input){
    int year = Integer.parseInt(input.substring(0,4));
    int month = Integer.parseInt(input.substring(4,6));
    int day = Integer.parseInt(input.substring(6,8));

    HijrahDate hijrah = HijrahDate.of(year, month, day);
    return IsoChronology.INSTANCE.date(hijrah);
}


问:
What is the best way to use assembly versioning attributes?
The AssemblyVersion and AssemblyFileVersion attributes are the built-in way of handling version numbers for .NET assemblies. While the framework provides the ability to have the least significant parts of a version number (build and revision, in Microsoft terms) automatically determined, I find the method for this pretty weak, and no doubt have many others.

So I'd like to ask, what ways have been determined to do the best job of having version numbers that better reflect the actual version of a project? Do you have a pre-build script that sets part of the version to the date and time, or repository version for your working copy of a project? Do you just use the automatic generation provided by the framework? Or something else? What's the best way to manage assembly/file versioning?

答: I see many posts here about using the subversion revision number as a component of the assembly version. Beware: the 4 version numbers available in windows (a.b.c.d) are each limited to 16 bit (max = 65535). The subversion revision number can easily exceed this limit, especially if you host multiple projects in the same repository.

OwnerDisplayName: Chris Charabaruk

OwnerDisplayName: wcoenen


问:
RIA Services - Pagination
I am testing out RIA services. I put together a RIA Services library and built a custom DomainService (i.e. not an Entity Framework Domain Service). I am accessing the library from a Silverlight app and all is working as expected. I can call the RIA service functions and get the results.

My issue is with pagination. I cannot find anywhere a description of using pagination on a RIA service that uses custom domainServices. My RIA Service is accessing a specialized DAL for access to data (and is not compatible with the Entity Framework). What I have found was an indication to pass the pagination parameters (i.e. page, page size) to a RIA Service function. So I have done just that - created a RIA service function that takes additional parameters for Page [index] and Page size. I am testing this in Silverlight using a DataGrid and a DataPager. The RIA service with the pagination parameters is called (and returns data) and the DataGrid is populated. The problem I'm having is when I go to another page. What is occurring is the RIA service is called twice. The first time with the proper params (i.e. correct page index) then again with a page index of zero). I.e. always resets to first page. I don't understand why this is occurring; I believe I put everything together properly (hopefully). The following is the XAML script:

```<code><riaControls:DomainDataSource
    Name="ddsScheduleTemplates"
    LoadSize="20"
    QueryName="GetPagedScheduleTemplates"
    AutoLoad="True"
>

    <riaControls:DomainDataSource.DomainContext>
        <ds:ScheduleEngineDomainContext/>
    </riaControls:DomainDataSource.DomainContext>

    <riaControls:DomainDataSource.QueryParameters>
        <riaControls:Parameter ParameterName="UserLogonName" Value="admin" />
        <riaControls:Parameter ParameterName="UserPassword" Value="admin" />
        <riaControls:Parameter ParameterName="Page" Value="{Binding ElementName=dpScheduleTemplates, Path=PageIndex}" />
        <riaControls:Parameter ParameterName="PageSize" Value="{Binding ElementName=dpScheduleTemplates, Path=PageSize}" />
    </riaControls:DomainDataSource.QueryParameters>

</riaControls:DomainDataSource>

<StackPanel>

    <dg:DataGrid
        Name="ScheduleTemplatesGrid"
        MinHeight="100"
        MaxHeight="300"
        IsReadOnly="True"
        ItemsSource="{Binding ElementName=ddsScheduleTemplates, Path=Data}"
    />

    <dg:DataPager
        x:Name="dpScheduleTemplates"
        PageSize="10"
        Source="{Binding ElementName=ddsScheduleTemplates, Path=Data}"
        PageIndexChanged="dpScheduleTemplates_PageIndexChanged"
    />

</StackPanel>
</code>```

I have modified the above script to call the general loading function (GetPagedScheduleTemplates - returns all records) and adjusted the QueryParameters list for the function. The DataGrid loads properly - and pagination works properly.

This confused me - it sort of looked like the DataPager required all data to be loaded in order for it to work properly - but I did a test where I loaded all data on a paged request operation; (i.e. pagination properties setup and calling pagination version of RIA service function) but DataGrid still resets.

Note: I had read that the DataPager requires the return list to be ordered - so I did so - but did not affect operation - paging always reset to page 1 - the following is the return list from the RIA service function
   newList.ToArray().AsQueryable().OrderBy(x=>x.ScheduleTemplateID)

So; my question is - has anyone seen this behavior - or am I making a horrendous mistake - if so what am I doing wrong?

Peter

答:
Once I integrated the Legecay DAL library I mentioned above all was working properly. Review the library - it is easy to use (but there is some reading/review to get up to speed with it). Also make sure your RIA service is properly configured for pagination. From what I have read and found - setting a page size in the pager and domain data source is required for proper operation. The ria service call also requires a count operation (for the specific entity object) also that return the MAX record count (if this is not done then things like you mention may occur -- the domain data source does not know the total records to paginate through -so it may just go the beginning because it does not have enough info -- this is usally apparent because the pager will not show the proper max page count or will show 1 or zero for the max page).

Peter

Title: RIA Services - Pagination

Body:
I am testing out RIA services. I put together a RIA Services library and built a custom DomainService (i.e. not an Entity Framework Domain Service). I am accessing the library from a Silverlight app and all is working as expected. I can call the RIA service functions and get the results.

My issue is with pagination. I cannot find anywhere a description of using pagination on a RIA service that uses custom domainServices. My RIA Service is accessing a specialized DAL for access to data (and is not compatible with the Entity Framework). What I have found was an indication to pass the pagination parameters (i.e. page, page size) to a RIA Service function. So I have done just that - created a RIA service function that takes additional parameters for Page [index] and Page size. I am testing this in Silverlight using a DataGrid and a DataPager. The RIA service with the pagination parameters is called (and returns data) and the DataGrid is populated. The problem I'm having is when I go to another page. What is occurring is the RIA service is called twice. The first time with the proper params (i.e. correct page index) then again with a page index of zero). I.e. always resets to first page. I don't understand why this is occurring; I believe I put everything together properly (hopefully). The following is the XAML script:

<riaControls:DomainDataSource
    Name="ddsScheduleTemplates"
    LoadSize="20"
    QueryName="GetPagedScheduleTemplates"
    AutoLoad="True"
>

    <riaControls:DomainDataSource.DomainContext>
        <ds:ScheduleEngineDomainContext/>
    </riaControls:DomainDataSource.DomainContext>

    <riaControls:DomainDataSource.QueryParameters>
        <riaControls:Parameter ParameterName="UserLogonName" Value="admin" />
        <riaControls:Parameter ParameterName="UserPassword" Value="admin" />
        <riaControls:Parameter ParameterName="Page" Value="{Binding ElementName=dpScheduleTemplates, Path=PageIndex}" />
        <riaControls:Parameter ParameterName="PageSize" Value="{Binding ElementName=dpScheduleTemplates, Path=PageSize}" />
    </riaControls:DomainDataSource.QueryParameters>

</riaControls:DomainDataSource>

<StackPanel>

    <dg:DataGrid
        Name="ScheduleTemplatesGrid"
        MinHeight="100"
        MaxHeight="300"
        IsReadOnly="True"
        ItemsSource="{Binding ElementName=ddsScheduleTemplates, Path=Data}"
    />

    <dg:DataPager
        x:Name="dpScheduleTemplates"
        PageSize="10"
        Source="{Binding ElementName=ddsScheduleTemplates, Path=Data}"
        PageIndexChanged="dpScheduleTemplates_PageIndexChanged"
    />

</StackPanel>

I have modified the above script to call the general loading function (GetPagedScheduleTemplates - returns all records) and adjusted the QueryParameters list for the function. The DataGrid loads properly - and pagination works properly.

This confused me - it sort of looked like the DataPager required all data to be loaded in order for it to work properly - but I did a test where I loaded all data on a paged request operation; (i.e. pagination properties setup and calling pagination version of RIA service function) but DataGrid still resets.

Note: I had read that the DataPager requires the return list to be ordered - so I did so - but did not affect operation - paging always reset to page 1 - the following is the return list from the RIA service function
   newList.ToArray().AsQueryable().OrderBy(x=>x.ScheduleTemplateID)

So; my question is - has anyone seen this behavior - or am I making a horrendous mistake - if so what am I doing wrong?

Peter


问:
Get IntentSender object for createChooser method in Android
I would like to use new version of Intent.createChooser method which uses IntentSender.

Documentation states only that I can grab it from PendingIntent instance. In my case it seems that PendingIntent won't have any other use.

Is there another way to obtain IntentSender or do I need create PendingIntent?

答:
Another way to do it. </p>

```<code>    /**
     * Receiver to record the chosen component when sharing an Intent.
     */
    static class TargetChosenReceiver extends BroadcastReceiver {
        private static final String EXTRA_RECEIVER_TOKEN = "receiver_token";
        private static final Object LOCK = new Object();

        private static String sTargetChosenReceiveAction;
        private static TargetChosenReceiver sLastRegisteredReceiver;

        static boolean isSupported() {
            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
        static void sendChooserIntent(Activity activity, Intent sharingIntent) {
            synchronized (LOCK) {
                if (sTargetChosenReceiveAction == null) {
                    sTargetChosenReceiveAction = activity.getPackageName() + "/"
                            + TargetChosenReceiver.class.getName() + "_ACTION";
                }
                Context context = activity.getApplicationContext();
                if (sLastRegisteredReceiver != null) {
                    context.unregisterReceiver(sLastRegisteredReceiver);
                }
                sLastRegisteredReceiver = new TargetChosenReceiver();
                context.registerReceiver(
                        sLastRegisteredReceiver, new IntentFilter(sTargetChosenReceiveAction));
            }

            Intent intent = new Intent(sTargetChosenReceiveAction);
            intent.setPackage(activity.getPackageName());
            intent.putExtra(EXTRA_RECEIVER_TOKEN, sLastRegisteredReceiver.hashCode());
            final PendingIntent callback = PendingIntent.getBroadcast(activity, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
            Intent chooserIntent = Intent.createChooser(sharingIntent,
                    activity.getString(R.string.share_link_chooser_title),
                    callback.getIntentSender());
            activity.startActivity(chooserIntent);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            synchronized (LOCK) {
                if (sLastRegisteredReceiver != this) return;
                context.getApplicationContext().unregisterReceiver(sLastRegisteredReceiver);
                sLastRegisteredReceiver = null;
            }
            if (!intent.hasExtra(EXTRA_RECEIVER_TOKEN)
                    || intent.getIntExtra(EXTRA_RECEIVER_TOKEN, 0) != this.hashCode()) {
                return;
            }

            ComponentName target = intent.getParcelableExtra(Intent.EXTRA_CHOSEN_COMPONENT);
            if (target != null) {
                setLastShareComponentName(context, target);
            }
        }
    }
</code>```

Body:
Another way to do it.

    /**
     * Receiver to record the chosen component when sharing an Intent.
     */
    static class TargetChosenReceiver extends BroadcastReceiver {
        private static final String EXTRA_RECEIVER_TOKEN = "receiver_token";
        private static final Object LOCK = new Object();

        private static String sTargetChosenReceiveAction;
        private static TargetChosenReceiver sLastRegisteredReceiver;

        static boolean isSupported() {
            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
        static void sendChooserIntent(Activity activity, Intent sharingIntent) {
            synchronized (LOCK) {
                if (sTargetChosenReceiveAction == null) {
                    sTargetChosenReceiveAction = activity.getPackageName() + "/"
                            + TargetChosenReceiver.class.getName() + "_ACTION";
                }
                Context context = activity.getApplicationContext();
                if (sLastRegisteredReceiver != null) {
                    context.unregisterReceiver(sLastRegisteredReceiver);
                }
                sLastRegisteredReceiver = new TargetChosenReceiver();
                context.registerReceiver(
                        sLastRegisteredReceiver, new IntentFilter(sTargetChosenReceiveAction));
            }

            Intent intent = new Intent(sTargetChosenReceiveAction);
            intent.setPackage(activity.getPackageName());
            intent.putExtra(EXTRA_RECEIVER_TOKEN, sLastRegisteredReceiver.hashCode());
            final PendingIntent callback = PendingIntent.getBroadcast(activity, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
            Intent chooserIntent = Intent.createChooser(sharingIntent,
                    activity.getString(R.string.share_link_chooser_title),
                    callback.getIntentSender());
            activity.startActivity(chooserIntent);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            synchronized (LOCK) {
                if (sLastRegisteredReceiver != this) return;
                context.getApplicationContext().unregisterReceiver(sLastRegisteredReceiver);
                sLastRegisteredReceiver = null;
            }
            if (!intent.hasExtra(EXTRA_RECEIVER_TOKEN)
                    || intent.getIntExtra(EXTRA_RECEIVER_TOKEN, 0) != this.hashCode()) {
                return;
            }

            ComponentName target = intent.getParcelableExtra(Intent.EXTRA_CHOSEN_COMPONENT);
            if (target != null) {
                setLastShareComponentName(context, target);
            }
        }
    }


问:
How to flip the image inside an svg horizontally?
I have the following svg image and I want to flip the image horizontally. How can I do that? Already tried adding scale(-1, 1) to some of the transform statements, but it does not seem to work.

Note: The svg is an export from sketch, so it might be a little strange formatted.

```<code><?xml version="1.0" encoding="UTF-8"?>
<svg width="645px" height="470px" viewBox="0 0 645 470" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <path d="M38.5969948,-2.22080132e-11 C16.8456745,30.2125678 3.07305242,70.3781435 0.923015792,123.840504 C-7.15396842,324.681101 174,465.890038 341,469.890015 C508,473.889991 658.942386,367.295224 643.971193,180.147362 C637.875363,103.946248 607.401187,44.0482171 563.7625,-2.35331754e-11 L38.5969948,-1.42108547e-14 Z" id="path-1"></path>
    </defs>
    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="Bitmap">
            <mask id="mask-2" fill="white">
                <use xlink:href="#path-1"></use>
            </mask>
            <image mask="url(#mask-2)" x="-800" y="0" width="1867.94872" height="470" xlink:href="http://www.castleknockhotel.com/cmsGallery/imagerow/5904/resized/1600x400/cycling_passion_of_life_high_resolution_wallpaper_for_desktop_background_download_cycling_images_free.jpg">
            </image>
        </g>
    </g>
</svg>
</code>```

Note: I only want to flip the image, and don't want to flip the mask.

Body:
I have the following svg image and I want to flip the image horizontally. How can I do that? Already tried adding scale(-1, 1) to some of the transform statements, but it does not seem to work.

Note: The svg is an export from sketch, so it might be a little strange formatted.

<?xml version="1.0" encoding="UTF-8"?>
<svg width="645px" height="470px" viewBox="0 0 645 470" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <path d="M38.5969948,-2.22080132e-11 C16.8456745,30.2125678 3.07305242,70.3781435 0.923015792,123.840504 C-7.15396842,324.681101 174,465.890038 341,469.890015 C508,473.889991 658.942386,367.295224 643.971193,180.147362 C637.875363,103.946248 607.401187,44.0482171 563.7625,-2.35331754e-11 L38.5969948,-1.42108547e-14 Z" id="path-1"></path>
    </defs>
    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="Bitmap">
            <mask id="mask-2" fill="white">
                <use xlink:href="#path-1"></use>
            </mask>
            <image mask="url(#mask-2)" x="-800" y="0" width="1867.94872" height="470" xlink:href="http://www.castleknockhotel.com/cmsGallery/imagerow/5904/resized/1600x400/cycling_passion_of_life_high_resolution_wallpaper_for_desktop_background_download_cycling_images_free.jpg">
            </image>
        </g>
    </g>
</svg>

Note: I only want to flip the image, and don't want to flip the mask.

Body:
Aaah... I found a solution. I needed to wrap the image and add the mask to the container. Then transform the image.

<?xml version="1.0" encoding="UTF-8"?>
<svg width="645px" height="470px" viewBox="0 0 645 470" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <path d="M38.5969948,-2.22080132e-11 C16.8456745,30.2125678 3.07305242,70.3781435 0.923015792,123.840504 C-7.15396842,324.681101 174,465.890038 341,469.890015 C508,473.889991 658.942386,367.295224 643.971193,180.147362 C637.875363,103.946248 607.401187,44.0482171 563.7625,-2.35331754e-11 L38.5969948,-1.42108547e-14 Z" id="path-1"></path>
    </defs>
    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="Bitmap">
            <mask id="mask-2" fill="white">
                <use xlink:href="#path-1"></use>
            </mask>
            <g mask="url(#mask-2)">
                <image x="-800" y="0" width="1867.94872" height="470" xlink:href="http://www.castleknockhotel.com/cmsGallery/imagerow/5904/resized/1600x400/cycling_passion_of_life_high_resolution_wallpaper_for_desktop_background_download_cycling_images_free.jpg" transform="scale(-1 1)">
                </image>
            </g>
        </g>
    </g>
</svg>


问:
IN MVC6 return Json(rows, JsonRequestBehavior.AllowGet) ISSUE
IN MVC6 return Json(rows, JsonRequestBehavior.AllowGet);  method is changed and not allowing to set JsonrequestBehavior. What is alternative in MVC6</p>

答:
Try this</p>

```<code> [HttpGet]
    public JsonResult List()
    {
        var settings = new JsonSerializerSettings();

        return Json(rows, settings);
    }
</code>```

Body:
Try this

 [HttpGet]
    public JsonResult List()
    {
        var settings = new JsonSerializerSettings();

        return Json(rows, settings);
    }


问:
Are square brackets permitted in URLs?
Are square brackets in URLs allowed?

I noticed that Apache commons HttpClient (3.0.1) throws an IOException, wget and Firefox however accept square brackets.

URL example:

```<code>http://example.com/path/to/file[3].html
</code>```

My HTTP client encounters such URLs but I'm not sure whether to patch the code or to throw an exception (as it actually should be).

答:
Square brackets [ and ] in URLs are not often supported.

Replace them by %5B and %5D:

Using a command line, the following example is based on bash and sed:

```<code>url='http://example.com?day=[0-3][0-9]'
encoded_url="$( sed 's/\[/%5B/g;s/]/%5D/g' <<< "$url")"
</code>```

Using Java URLEncoder.encode(String s, String enc)

Using PHP rawurlencode() or urlencode()

```<code><?php
echo '<a href="http://example.com/day/',
    rawurlencode('[0-3][0-9]'), '">';
?>
</code>```

output:

```<code><a href="http://example.com/day/%5B0-3%5D%5B0-9%5D">
</code>```

or:

```<code><?php
$query_string = 'day=' . urlencode('[0-3][0-9]') .
                '&month=' . urlencode('[0-1][0-9]');
echo '<a href="http://example.com?',
      htmlentities($query_string), '">';
?>
</code>```

Using your favorite programming language... Please extend this answer by posting a comment or editing directly this answer to add the function you use from your programming language ;-)

For more details, see the RFC 3986 specifying the URL syntax. The Appendix A is about %-encoding in the query string (brackets as belonging to “gen-delims” to be %-encoded).

OwnerDisplayName: bene

Title: Are square brackets permitted in URLs?

Body:
Are square brackets in URLs allowed?

I noticed that Apache commons HttpClient (3.0.1) throws an IOException, wget and Firefox however accept square brackets.

URL example:

http://example.com/path/to/file[3].html

My HTTP client encounters such URLs but I'm not sure whether to patch the code or to throw an exception (as it actually should be).

LastEditorDisplayName: bene

Body:
Square brackets [ and ] in URLs are not often supported.

Replace them by %5B and %5D:

Using a command line, the following example is based on bash and sed:

url='http://example.com?day=[0-3][0-9]'
encoded_url="$( sed 's/\[/%5B/g;s/]/%5D/g' <<< "$url")"

Using Java URLEncoder.encode(String s, String enc)

Using PHP rawurlencode() or urlencode()

<?php
echo '<a href="http://example.com/day/',
    rawurlencode('[0-3][0-9]'), '">';
?>

output:

<a href="http://example.com/day/%5B0-3%5D%5B0-9%5D">

or:

<?php
$query_string = 'day=' . urlencode('[0-3][0-9]') .
                '&month=' . urlencode('[0-1][0-9]');
echo '<a href="http://example.com?',
      htmlentities($query_string), '">';
?>

Using your favorite programming language... Please extend this answer by posting a comment or editing directly this answer to add the function you use from your programming language ;-)

For more details, see the RFC 3986 specifying the URL syntax. The Appendix A is about %-encoding in the query string (brackets as belonging to “gen-delims” to be %-encoded).


问:
stackoverflow exception was unhandled
In the code below it should multiply 2 numbers. It works for 3 and less than 3 digits numbers but when I give numbers with 4 digits or bigger it gives runtime error: stackoverflow exception was unhandled. I've commented where the problem is. I thought the problem is for defining variables in int and changed them in long but the problem still exists. Where is the mistake?

edited:
now,whats do you think about the problem?it doesnt do anything

```<code>        public long Prod2(long u, long v)
    {
        var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
        int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1),(int)Math.Floor(Math.Log10(v) + 1));
        int threshold = 3;

        if (u == 0 || v == 0)
        {
            return 0;
        }
        else if (n <= threshold)
        {
            return u * v;
        }
        else
        {
            int m = (int)Math.Ceiling(n / 2.0);

            int x = (int)(u / Math.Pow(10, m));
            int y = (int)(u % Math.Pow(10, m));
            int w = (int)(u / Math.Pow(10, m));
            int z = (int)(v % Math.Pow(10, m));

            long r = Prod2(x + y, w + z);
            long p = Prod2(x, w);
            long q = Prod2(y, z);

            return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
            long result = Prod2(numbers[0], numbers[1]);
            textBox1.Text = result.ToString();
        }
    }
</code>```

答: Pow method returns double, so I think your x, y, z, w, and z should be declared as double as well.</p>

Title: stackoverflow exception was unhandled

Body:
In the code below it should multiply 2 numbers. It works for 3 and less than 3 digits numbers but when I give numbers with 4 digits or bigger it gives runtime error: stackoverflow exception was unhandled. I've commented where the problem is. I thought the problem is for defining variables in int and changed them in long but the problem still exists. Where is the mistake?

edited:
now,whats do you think about the problem?it doesnt do anything

        public long Prod2(long u, long v)
    {
        var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
        int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1),(int)Math.Floor(Math.Log10(v) + 1));
        int threshold = 3;

        if (u == 0 || v == 0)
        {
            return 0;
        }
        else if (n <= threshold)
        {
            return u * v;
        }
        else
        {
            int m = (int)Math.Ceiling(n / 2.0);

            int x = (int)(u / Math.Pow(10, m));
            int y = (int)(u % Math.Pow(10, m));
            int w = (int)(u / Math.Pow(10, m));
            int z = (int)(v % Math.Pow(10, m));

            long r = Prod2(x + y, w + z);
            long p = Prod2(x, w);
            long q = Prod2(y, z);

            return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
            long result = Prod2(numbers[0], numbers[1]);
            textBox1.Text = result.ToString();
        }
    }


问:
Regex to validate ascending and decending number in javascript
I want to put restriction on setting login pin which should not accept ascending order eg. 123456789 etc but accept 1256... and also should not accept descending order eg. 987654321 etc but accept 9865 etc  max 4-6 digit are allowed.

Any help is appreciated.

Thanks in advance.

答:
Instead of using regex you could use a simple validator like this one:

function checkPIN(str) {
  return "123456789".indexOf(str) === -1 && "987654321".indexOf(str) === -1 && str.length > 3 && str.length < 7
}

console.log(checkPIN("1234"))
console.log(checkPIN("12345"))
console.log(checkPIN("1245"))```


问:
How to partially check object with Jasmine
is there a way how to partially match object with array property? Let's suppose that I'd like to test this object

```

    {
       "groups": [
          {
             "id": 1,
             "name": "Group 1",
             "people": [
                {
                   "firstName": "John",
                   "age": 23
                },
                {
                   "firstName": "Ethan",
                   "age": 18
                }
             ]
          },
          {
             "id": 2,
             "name": "Group 2",
             "people": [
                {
                   "firstName": "Peter",
                   "age": 47
                },
                {
                   "firstName": "Henry",
                   "age": 55
                }
             ]
          }
       ]
    }

```

and ensure that it contains group with name Group 1 that contains John and Ethan.
I'm aware of jasmine.objectContaining but I don't know how to apply to this particular case.
Thank for any advice.

答:
you mean something like this ? assume obj is ur object

```<code>var res = obj["groups"].find(function(a) { return a["name"] == "group 1"; });
res = res["people"].filter(function(person) {
         return ["Ethan","John"].includes(person["name"]);
   });
</code>```

now you can check if ( res["people"].length == 2 )

Body:
is there a way how to partially match object with array property? Let's suppose that I'd like to test this object

    {
       "groups": [
          {
             "id": 1,
             "name": "Group 1",
             "people": [
                {
                   "firstName": "John",
                   "age": 23
                },
                {
                   "firstName": "Ethan",
                   "age": 18
                }
             ]
          },
          {
             "id": 2,
             "name": "Group 2",
             "people": [
                {
                   "firstName": "Peter",
                   "age": 47
                },
                {
                   "firstName": "Henry",
                   "age": 55
                }
             ]
          }
       ]
    }

and ensure that it contains group with name Group 1 that contains John and Ethan.
I'm aware of jasmine.objectContaining but I don't know how to apply to this particular case.
Thank for any advice.

Body:
you mean something like this ? assume obj is ur object

var res = obj["groups"].find(function(a) { return a["name"] == "group 1"; });
res = res["people"].filter(function(person) {
         return ["Ethan","John"].includes(person["name"]);
   });

now you can check if ( res["people"].length == 2 )


问:
jQuery UI : Draggable element is moving inside the sidebar. Why?
I have to make a sidebar which has divs inside it and the divs are Draggable and Droppable to the drop area.

So what I have done:

I have make a sidebar.

```<code>$(".draggable").each(function() {
    $(this).draggable({
      zIndex: 999,
      scroll: false,
      revert: 'invalid',
      refreshPosition: true,
    });
});

$(".droppable").droppable({
        accept: '',
        drop: function(event, ui) {
            console.log('Function working successfully');
        }

    })
</code>```

Here it is fiddle

Problem:

My problem is that when I drag the element the dragged element does not go outside the sidebar. Why is it happening and how can I resolve this problem.

Update :

Fiddle

答:
You have written overflow: hidden to your sidebar. If you remove that, it will work just fine.

```<code>.class_sidebar {
    position: fixed;
    width: 300px;
    height: 100%;
    /* z-index: 1; */
    top: 0;
    left: 0;
    background-color: #E6E9EC;
    /* overflow: hidden; */
    -webkit-transition: 0.5s;
    transition: 0.5s;
}
</code>```

The overflow property specifies what happens if content overflows an element's box. This property specifies whether to clip content or to add scrollbars when an element's content is too big to fit in a specified area.

It needs to be removed for the required action to happen.

Body:
I have to make a sidebar which has divs inside it and the divs are Draggable and Droppable to the drop area.

So what I have done:

I have make a sidebar.

$(".draggable").each(function() {
    $(this).draggable({
      zIndex: 999,
      scroll: false,
      revert: 'invalid',
      refreshPosition: true,
    });
});

$(".droppable").droppable({
        accept: '',
        drop: function(event, ui) {
            console.log('Function working successfully');
        }

    })

Here it is fiddle

Problem:

My problem is that when I drag the element the dragged element does not go outside the sidebar. Why is it happening and how can I resolve this problem.

Update :

Fiddle

Body:
You have written overflow: hidden to your sidebar. If you remove that, it will work just fine.

.class_sidebar {
    position: fixed;
    width: 300px;
    height: 100%;
    /* z-index: 1; */
    top: 0;
    left: 0;
    background-color: #E6E9EC;
    /* overflow: hidden; */
    -webkit-transition: 0.5s;
    transition: 0.5s;
}

The overflow property specifies what happens if content overflows an element's box. This property specifies whether to clip content or to add scrollbars when an element's content is too big to fit in a specified area.

It needs to be removed for the required action to happen.