问:
Animation not showing in React Native mobile app
I have created a React Native app to test animations. I have a background and when the user presses this background I want an animation to appear over the background and animate. The code:

```<code>import * as React from 'react';

import { StyleSheet, Text, View,  TouchableOpacity, Image, ImageBackground, Animated, Easing, Platform
} from 'react-native';
import { frame1 } from '../app-master-test/assets/index';
import { frame2 } from '../app-master-test/assets/index';
import { frame3 } from '../app-master-test/assets/index';
import { frame4 } from '../app-master-test/assets/index';
import { frame5 } from '../app-master-test/assets/index';
import { frame6 } from '../app-master-test/assets/index';
import { frame7 } from '../app-master-test/assets/index';
import { frame8 } from '../app-master-test/assets/index';

import { background } from '../app-master-test/assets/index';

const Images= [
  { id: 1, source: frame1},
  { id: 2, source: frame2 },
  { id: 3, source: frame3 },
  { id: 4, source: frame4 },
  { id: 5, source: frame5 },
  { id: 6, source: frame6 },
  { id: 7, source: frame7 },
  { id: 8, source: frame8 },

]

const length = Images.length;

export default class Timer extends React.Component {
  constructor(props){
  super(props);

  this.state = {

    isOn: false,

  }

  this.animations = new Animated.Value(0);
  this.opacity = [];
  Images.map((item, index) => {
    this.opacity.push(
      this.animations.interpolate({
        inputRange: [index - 1, index, index + 1],
        outputRange: [0, 1, 0],
      }),
    );

  });

}

onItemMouseDown = () => {
  Animated.loop(
    Animated.timing(this.animations, {
      toValue: length - 1,
      duration: 2000 * length,
      easing: Easing.linear,
      useNativeDriver: true,
    }),
  ).start();
console.log(this.animations)
  this.setState({
    isOn:true,

  }, () => {
    console.log(this.state.isOn)

  })

}

onItemMouseUp = () => {
  this.setState({
    isOn:false

  }, () => {
    console.log(this.state.isOn)
  })
}

  render() {

    return(
      <ImageBackground source={background} style={styles.background}>

     <TouchableOpacity
     onPressIn={this.onItemMouseDown}
     onPressOut={this.onItemMouseUp}

     >
     <Text style={styles.touchbutton}>Touch this</Text>

     </TouchableOpacity>

   {this.state.isOn === true ?

      <View style={styles.container}>
      {/* <Image source={frame1}></Image> */} //I can render this image if this.state.isOn is true

          {Images.map((item, index) => { //but this does not show ANYTHING!
          const opacity = this.opacity[index];
          {/* console.log(item)
          console.log(index) */}
          return(
            <Animated.View
             key={item.id}
            style={[styles.anim, {animations: item, opacity}]}
            />

          )

        })}

      </View>
  : null }

       </ImageBackground>
     )

  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: 'center',

  },
  background: {
    flex: 1,
    resizeMode: "cover",
    justifyContent: "center",
    alignItems: 'center',
  },
  anim: {

    width: 100,
    height: 100,

    },
  touchbutton: {
    flex: 1,
    position: 'relative',
    marginTop: 300,
  },
  touchbuttontest: {
    flex:1,
    position: 'relative',
    marginTop: 200,
  }

});
</code>```

As mentioned, nothing appears. I'm not sure whether it's this bit:

```<code><Animated.View
      key={item.id}
      style={[styles.anim, {animations: item, opacity}]}
   />

</code>```

particularly the style line. I'm not sure that is correct. I don't fully understand what is going on there. I don't know what to put instead of animations: item. I think it should be a property of something but what, I don't know.
I've watched this and none of what is suggests works:
https://egghead.io/lessons/react-animate-styles-of-a-react-native-view-with-animated-timing

答:
there is no problem in your code you can give backgroundColor:"red" in anim to check if it is working or not

you have to make position:"absolute" to container for start animation from top and you have to wrap image inside Animated.View

you can check demo here :https://snack.expo.io/@nomi9995/animation

```<code>import * as React from "react";

import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Image,
  ImageBackground,
  Animated,
  Easing,
  Platform,
} from "react-native";
import { frame1 } from "../app-master-test/assets/index";
import { frame2 } from "../app-master-test/assets/index";
import { frame3 } from "../app-master-test/assets/index";
import { frame4 } from "../app-master-test/assets/index";
import { frame5 } from "../app-master-test/assets/index";
import { frame6 } from "../app-master-test/assets/index";
import { frame7 } from "../app-master-test/assets/index";
import { frame8 } from "../app-master-test/assets/index";

import { background } from "../app-master-test/assets/index";

const Images = [
  { id: 1, source: frame1 },
  { id: 2, source: frame2 },
  { id: 3, source: frame3 },
  { id: 4, source: frame4 },
  { id: 5, source: frame5 },
  { id: 6, source: frame6 },
  { id: 7, source: frame7 },
  { id: 8, source: frame8 },
];

const length = Images.length;

export default class Timer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isOn: false,
    };

    this.animations = new Animated.Value(0);
    this.opacity = [];
    Images.map((item, index) => {
      this.opacity.push(
        this.animations.interpolate({
          inputRange: [index - 1, index, index + 1],
          outputRange: [0, 1, 0],
        })
      );
    });
  }

  onItemMouseDown = () => {
    Animated.loop(
      Animated.timing(this.animations, {
        toValue: length - 1,
        duration: 2000 * length,
        easing: Easing.linear,
        useNativeDriver: true,
      })
    ).start();
    console.log(this.animations);
    this.setState(
      {
        isOn: true,
      },
      () => {
        console.log(this.state.isOn, "nominominomi");
      }
    );
  };

  onItemMouseUp = () => {
    this.setState(
      {
        isOn: false,
      },
      () => {
        console.log(this.state.isOn);
      }
    );
  };

  render() {
    return (
      <ImageBackground source={background} style={styles.background}>
        <TouchableOpacity
          onPressIn={this.onItemMouseDown}
          onPressOut={this.onItemMouseUp}
        >
          <Text style={styles.touchbutton}>Touch this</Text>
        </TouchableOpacity>
        {this.state.isOn === true ? (
          <View style={styles.container}>
            {Images.map((item, index) => {
              const opacity = this.opacity[index];
              return (
                <Animated.View
                  key={item.id}
                  style={[styles.anim, { animations: item, opacity }]}
                >
                  <Image
                    source={item.source}
                    style={{ height: 100, width: 100, zIndex: 100 }}
                  />
                </Animated.View>
              );
            })}
          </View>
        ) : null}
      </ImageBackground>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: 'center',
    position:"absolute"

  },
  background: {
    flex: 1,
    resizeMode: "cover",
    justifyContent: "center",
    alignItems: 'center',
  },
  anim: {
    position:"absolute",
    width: 100,
    height: 100,
    },
  touchbutton: {
    flex: 1,
    position: 'relative',
    marginTop: 300,
  },
  touchbuttontest: {
    flex:1,
    position: 'relative',
    marginTop: 200,
  }
});

</code>```

Body:
I have created a React Native app to test animations. I have a background and when the user presses this background I want an animation to appear over the background and animate. The code:

import * as React from 'react';

import { StyleSheet, Text, View,  TouchableOpacity, Image, ImageBackground, Animated, Easing, Platform
} from 'react-native';
import { frame1 } from '../app-master-test/assets/index';
import { frame2 } from '../app-master-test/assets/index';
import { frame3 } from '../app-master-test/assets/index';
import { frame4 } from '../app-master-test/assets/index';
import { frame5 } from '../app-master-test/assets/index';
import { frame6 } from '../app-master-test/assets/index';
import { frame7 } from '../app-master-test/assets/index';
import { frame8 } from '../app-master-test/assets/index';

import { background } from '../app-master-test/assets/index';

const Images= [
  { id: 1, source: frame1},
  { id: 2, source: frame2 },
  { id: 3, source: frame3 },
  { id: 4, source: frame4 },
  { id: 5, source: frame5 },
  { id: 6, source: frame6 },
  { id: 7, source: frame7 },
  { id: 8, source: frame8 },

]

const length = Images.length;

export default class Timer extends React.Component {
  constructor(props){
  super(props);

  this.state = {

    isOn: false,

  }

  this.animations = new Animated.Value(0);
  this.opacity = [];
  Images.map((item, index) => {
    this.opacity.push(
      this.animations.interpolate({
        inputRange: [index - 1, index, index + 1],
        outputRange: [0, 1, 0],
      }),
    );

  });

}

onItemMouseDown = () => {
  Animated.loop(
    Animated.timing(this.animations, {
      toValue: length - 1,
      duration: 2000 * length,
      easing: Easing.linear,
      useNativeDriver: true,
    }),
  ).start();
console.log(this.animations)
  this.setState({
    isOn:true,

  }, () => {
    console.log(this.state.isOn)

  })

}

onItemMouseUp = () => {
  this.setState({
    isOn:false

  }, () => {
    console.log(this.state.isOn)
  })
}

  render() {

    return(
      <ImageBackground source={background} style={styles.background}>

     <TouchableOpacity
     onPressIn={this.onItemMouseDown}
     onPressOut={this.onItemMouseUp}

     >
     <Text style={styles.touchbutton}>Touch this</Text>

     </TouchableOpacity>

   {this.state.isOn === true ?

      <View style={styles.container}>
      {/* <Image source={frame1}></Image> */} //I can render this image if this.state.isOn is true

          {Images.map((item, index) => { //but this does not show ANYTHING!
          const opacity = this.opacity[index];
          {/* console.log(item)
          console.log(index) */}
          return(
            <Animated.View
             key={item.id}
            style={[styles.anim, {animations: item, opacity}]}
            />

          )

        })}

      </View>
  : null }

       </ImageBackground>
     )

  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: 'center',

  },
  background: {
    flex: 1,
    resizeMode: "cover",
    justifyContent: "center",
    alignItems: 'center',
  },
  anim: {

    width: 100,
    height: 100,

    },
  touchbutton: {
    flex: 1,
    position: 'relative',
    marginTop: 300,
  },
  touchbuttontest: {
    flex:1,
    position: 'relative',
    marginTop: 200,
  }

});

As mentioned, nothing appears. I'm not sure whether it's this bit:

<Animated.View
      key={item.id}
      style={[styles.anim, {animations: item, opacity}]}
   />

particularly the style line. I'm not sure that is correct. I don't fully understand what is going on there. I don't know what to put instead of animations: item. I think it should be a property of something but what, I don't know.
I've watched this and none of what is suggests works:
https://egghead.io/lessons/react-animate-styles-of-a-react-native-view-with-animated-timing

Body:
there is no problem in your code you can give backgroundColor:"red" in anim to check if it is working or not

you have to make position:"absolute" to container for start animation from top and you have to wrap image inside Animated.View

you can check demo here :https://snack.expo.io/@nomi9995/animation

import * as React from "react";

import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Image,
  ImageBackground,
  Animated,
  Easing,
  Platform,
} from "react-native";
import { frame1 } from "../app-master-test/assets/index";
import { frame2 } from "../app-master-test/assets/index";
import { frame3 } from "../app-master-test/assets/index";
import { frame4 } from "../app-master-test/assets/index";
import { frame5 } from "../app-master-test/assets/index";
import { frame6 } from "../app-master-test/assets/index";
import { frame7 } from "../app-master-test/assets/index";
import { frame8 } from "../app-master-test/assets/index";

import { background } from "../app-master-test/assets/index";

const Images = [
  { id: 1, source: frame1 },
  { id: 2, source: frame2 },
  { id: 3, source: frame3 },
  { id: 4, source: frame4 },
  { id: 5, source: frame5 },
  { id: 6, source: frame6 },
  { id: 7, source: frame7 },
  { id: 8, source: frame8 },
];

const length = Images.length;

export default class Timer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isOn: false,
    };

    this.animations = new Animated.Value(0);
    this.opacity = [];
    Images.map((item, index) => {
      this.opacity.push(
        this.animations.interpolate({
          inputRange: [index - 1, index, index + 1],
          outputRange: [0, 1, 0],
        })
      );
    });
  }

  onItemMouseDown = () => {
    Animated.loop(
      Animated.timing(this.animations, {
        toValue: length - 1,
        duration: 2000 * length,
        easing: Easing.linear,
        useNativeDriver: true,
      })
    ).start();
    console.log(this.animations);
    this.setState(
      {
        isOn: true,
      },
      () => {
        console.log(this.state.isOn, "nominominomi");
      }
    );
  };

  onItemMouseUp = () => {
    this.setState(
      {
        isOn: false,
      },
      () => {
        console.log(this.state.isOn);
      }
    );
  };

  render() {
    return (
      <ImageBackground source={background} style={styles.background}>
        <TouchableOpacity
          onPressIn={this.onItemMouseDown}
          onPressOut={this.onItemMouseUp}
        >
          <Text style={styles.touchbutton}>Touch this</Text>
        </TouchableOpacity>
        {this.state.isOn === true ? (
          <View style={styles.container}>
            {Images.map((item, index) => {
              const opacity = this.opacity[index];
              return (
                <Animated.View
                  key={item.id}
                  style={[styles.anim, { animations: item, opacity }]}
                >
                  <Image
                    source={item.source}
                    style={{ height: 100, width: 100, zIndex: 100 }}
                  />
                </Animated.View>
              );
            })}
          </View>
        ) : null}
      </ImageBackground>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: 'center',
    position:"absolute"

  },
  background: {
    flex: 1,
    resizeMode: "cover",
    justifyContent: "center",
    alignItems: 'center',
  },
  anim: {
    position:"absolute",
    width: 100,
    height: 100,
    },
  touchbutton: {
    flex: 1,
    position: 'relative',
    marginTop: 300,
  },
  touchbuttontest: {
    flex:1,
    position: 'relative',
    marginTop: 200,
  }
});


来源: stackexchange

问:
Struggling to structure libgdx project
I know this question might get taken down but I'm going to ask it anyway.

I've been trying to make a draughts game in Java using Libgdx; I've been using Stage2D as well.

I don't know how to structure the project as I plan on having separate classes for the board, game, players, pieces and GUI. Also, I have written some code to draw a board, however, it doesn't seem to work with Stage2D.

I still want to figure this out myself, as I want to learn from this project. So, please do not give too much away.

However, I don't know how to draw the board or start this project.

All the resources and tutorials I have found online have been very unclear. I don't really know what to do.

package com.mygdx.game;

public enum Color {
    BLACK, WHITE
}
```

<pre class="lang-java prettyprint-override"><code>package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.scenes.scene2d.Stage;

public class GUI {
    float r_brown = (float) 163 / 255;
    float g_brown = (float) 102 / 255;
    float b_brown = (float) 46 / 255;

    float r_cream = (float) 240 / 255;
    float g_cream = (float) 187 / 255;
    float b_cream = (float) 108 / 255;

    private ShapeRenderer shapeRenderer;
    private OrthographicCamera camera;

    public GUI(ShapeRenderer shapeRenderer, OrthographicCamera camera) {
        this.shapeRenderer = shapeRenderer;
        this.camera = camera;
    }

    public void drawGUI() {
    }
}
</code>```

package com.mygdx.game;

public enum Type {
    SOLDIER, KING
}
```

<pre class="lang-java prettyprint-override"><code>package com.mygdx.game;

public class Player {
    private Color color;

    public Player() {
    }
}
</code>```

package com.mygdx.game;

public class King extends Piece {

    private Location location;
    private Type type = Type.KING;
    private Player player;

    public King(Player player, Location location) {
        super(player, location);
    }

    @Override
    public void draw() {
        // TODO Auto-generated method stub
    }

    @Override
    public void move() {
        // TODO Auto-generated method stub
    }

    @Override
    public void capture() {
        // TODO Auto-generated method stub
    }
}
```

<pre class="lang-java prettyprint-override"><code>package com.mygdx.game;

public class Location {
    private int x;
    private int y;

    public Location(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
</code>```

package com.mygdx.game;

import com.badlogic.gdx.scenes.scene2d.Actor;

public abstract class Piece extends Actor {
    private Location location;
    private Type type;
    private Player player;

    public Piece(Player player, Location location) {
        this.player = player;
        this.location = location;
    }

    public abstract void draw();

    public abstract void move();

    public abstract void capture();

    public void setLocation(Location location) {
        this.location = location;
    }

    public Location getLocation() {
        return this.location;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Type getType() {
        return this.type;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    public Player getPlayer() {
        return this.player;
    }
}
```

<pre class="lang-java prettyprint-override"><code>package com.mygdx.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.actions.MoveByAction;
import com.badlogic.gdx.scenes.scene2d.InputEvent;

public class Soldier extends Actor {
    private Location location;
    private Type type = Type.SOLDIER;
    private Player player;
    Sprite sprite = new Sprite(new Texture(Gdx.files.internal("black_solider.png")));

    public Soldier(Player player, Location location) {
        //super(player, location);
        setBounds(sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight());
        setTouchable(Touchable.enabled);

        addListener(new InputListener() {
            @Override
            public boolean keyDown(InputEvent event, int keycode) {
                if (keycode == Input.Keys.RIGHT) {
                    MoveByAction mba = new MoveByAction();
                    mba.setAmount(100f, 0f);
                    mba.setDuration(5f);

                    Soldier.this.addAction(mba);
                }
                return true;
            }
        });
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        sprite.draw(batch, parentAlpha);
    }

    @Override
    public void act(float delta) {
        super.act(delta);
    }

    //@Override
    public void move() {
        // TODO Auto-generated method stub
    }

    //@Override
    public void capture() {
        // TODO Auto-generated method stub
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    public Location getLocation() {
        return this.location;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Type getType() {
        return this.type;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    public Player getPlayer() {
        return this.player;
    }
}
</code>```

package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.ScreenViewport;

public class MyGdxGame extends ApplicationAdapter {
    Stage stage;
    private GUI gui;
    private ShapeRenderer shapeRenderer;
    private OrthographicCamera camera;

    float r_brown = (float) 163 / 255;
    float g_brown = (float) 102 / 255;
    float b_brown = (float) 46 / 255;

    float r_cream = (float) 240 / 255;
    float g_cream = (float) 187 / 255;
    float b_cream = (float) 108 / 255;

    @Override
    public void create() {
        ScreenViewport viewport = new ScreenViewport();
        stage = new Stage(viewport);
        Gdx.input.setInputProcessor(stage);

        shapeRenderer = new ShapeRenderer();
        camera = new OrthographicCamera();
        gui = new GUI(shapeRenderer, camera);

        Soldier piece1 = new Soldier(new Player(), new Location(400, 400));
        stage.addActor(piece1);
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        shapeRenderer.setProjectionMatrix(camera.combined);
        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if ((i % 2) == 0) {
                    if ((j % 2) == 0) {
                        shapeRenderer.setColor(r_brown, g_brown, b_brown, 1);
                        shapeRenderer.rect(100 * i, 100 * j, 100, 100);
                    } else {
                        shapeRenderer.setColor(r_cream, g_cream, b_cream, 1);
                        shapeRenderer.rect(100 * i, 100 * j, 100, 100);
                    }
                } else {
                    if ((j % 2) == 0) {

                        shapeRenderer.setColor(r_cream, g_cream, b_cream, 1);
                        shapeRenderer.rect(100 * i, 100 * j, 100, 100);
                    } else {
                        shapeRenderer.setColor(r_brown, g_brown, b_brown, 1);
                        shapeRenderer.rect(100 * i, 100 * j, 100, 100);
                    }
                }
            }
        }

        shapeRenderer.end();
        camera.update();

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();

        /*
        Piece[][] pieces = new Piece[8][8];
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                Piece currentPiece = pieces[i][j];
                currentPiece.draw();
            }
        }
        */
    }
    @Override
    public void dispose() {
        shapeRenderer.dispose();
    }
}
```

答:
A few quick and superficial pointers:

You seem to have multiple challenges and problems. Focus on them one at a time if you can, dividing and conquering them one by one.

If you are doing this for the sake of learning and you are very new to programming, be very careful about not having a large scope for the project. Set a very modest goal for what you want to be able to do with the project, and once you have accomplished that, you can add an additional goal. Iteratively continuing. This is very risk-resilient, because you start from a relatively easy point and go from there. The drawback with this is that you may have to do a fair amount of work, because one design early one that was suitable then may not be suitable for later work, and this may require a rewrite and redesign to a smaller or larger degree. Once you get more experienced, planning and seeking to design early on can be very, very helpful, especially if you know that some important aspects are going to be important later and the design you choose early on will impact these - but again, this is once you are more experienced.

Consider what things you would like the game to be able to have, like AI (state-space-search), graphics, saving/loading, the player using a GUI to move around, etc. And then pick the few things that you consider both easy and most nice to have. If you are new, don't require it to be a cohesive whole, you can always take that on later as a more ambitious goal once you have more experience, have learned more, thought more about things, etc. Again, be very, very modest with your goals and scope, and get some experience and just learn.

ContentLicense: CC BY-SA 4.0

Title: Struggling to structure libgdx project

Body:
I know this question might get taken down but I'm going to ask it anyway.

I've been trying to make a draughts game in Java using Libgdx; I've been using Stage2D as well.

I don't know how to structure the project as I plan on having separate classes for the board, game, players, pieces and GUI. Also, I have written some code to draw a board, however, it doesn't seem to work with Stage2D.

I still want to figure this out myself, as I want to learn from this project. So, please do not give too much away.

However, I don't know how to draw the board or start this project.

All the resources and tutorials I have found online have been very unclear. I don't really know what to do.

package com.mygdx.game;

public enum Color {
    BLACK, WHITE
}

package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.scenes.scene2d.Stage;

public class GUI {
    float r_brown = (float) 163 / 255;
    float g_brown = (float) 102 / 255;
    float b_brown = (float) 46 / 255;

    float r_cream = (float) 240 / 255;
    float g_cream = (float) 187 / 255;
    float b_cream = (float) 108 / 255;

    private ShapeRenderer shapeRenderer;
    private OrthographicCamera camera;

    public GUI(ShapeRenderer shapeRenderer, OrthographicCamera camera) {
        this.shapeRenderer = shapeRenderer;
        this.camera = camera;
    }

    public void drawGUI() {
    }
}

package com.mygdx.game;

public enum Type {
    SOLDIER, KING
}

package com.mygdx.game;

public class Player {
    private Color color;

    public Player() {
    }
}

package com.mygdx.game;

public class King extends Piece {

    private Location location;
    private Type type = Type.KING;
    private Player player;

    public King(Player player, Location location) {
        super(player, location);
    }

    @Override
    public void draw() {
        // TODO Auto-generated method stub
    }

    @Override
    public void move() {
        // TODO Auto-generated method stub
    }

    @Override
    public void capture() {
        // TODO Auto-generated method stub
    }
}

package com.mygdx.game;

public class Location {
    private int x;
    private int y;

    public Location(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

package com.mygdx.game;

import com.badlogic.gdx.scenes.scene2d.Actor;

public abstract class Piece extends Actor {
    private Location location;
    private Type type;
    private Player player;

    public Piece(Player player, Location location) {
        this.player = player;
        this.location = location;
    }

    public abstract void draw();

    public abstract void move();

    public abstract void capture();

    public void setLocation(Location location) {
        this.location = location;
    }

    public Location getLocation() {
        return this.location;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Type getType() {
        return this.type;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    public Player getPlayer() {
        return this.player;
    }
}

package com.mygdx.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.actions.MoveByAction;
import com.badlogic.gdx.scenes.scene2d.InputEvent;

public class Soldier extends Actor {
    private Location location;
    private Type type = Type.SOLDIER;
    private Player player;
    Sprite sprite = new Sprite(new Texture(Gdx.files.internal("black_solider.png")));

    public Soldier(Player player, Location location) {
        //super(player, location);
        setBounds(sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight());
        setTouchable(Touchable.enabled);

        addListener(new InputListener() {
            @Override
            public boolean keyDown(InputEvent event, int keycode) {
                if (keycode == Input.Keys.RIGHT) {
                    MoveByAction mba = new MoveByAction();
                    mba.setAmount(100f, 0f);
                    mba.setDuration(5f);

                    Soldier.this.addAction(mba);
                }
                return true;
            }
        });
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        sprite.draw(batch, parentAlpha);
    }

    @Override
    public void act(float delta) {
        super.act(delta);
    }

    //@Override
    public void move() {
        // TODO Auto-generated method stub
    }

    //@Override
    public void capture() {
        // TODO Auto-generated method stub
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    public Location getLocation() {
        return this.location;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Type getType() {
        return this.type;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    public Player getPlayer() {
        return this.player;
    }
}

package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.ScreenViewport;

public class MyGdxGame extends ApplicationAdapter {
    Stage stage;
    private GUI gui;
    private ShapeRenderer shapeRenderer;
    private OrthographicCamera camera;

    float r_brown = (float) 163 / 255;
    float g_brown = (float) 102 / 255;
    float b_brown = (float) 46 / 255;

    float r_cream = (float) 240 / 255;
    float g_cream = (float) 187 / 255;
    float b_cream = (float) 108 / 255;

    @Override
    public void create() {
        ScreenViewport viewport = new ScreenViewport();
        stage = new Stage(viewport);
        Gdx.input.setInputProcessor(stage);

        shapeRenderer = new ShapeRenderer();
        camera = new OrthographicCamera();
        gui = new GUI(shapeRenderer, camera);

        Soldier piece1 = new Soldier(new Player(), new Location(400, 400));
        stage.addActor(piece1);
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        shapeRenderer.setProjectionMatrix(camera.combined);
        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if ((i % 2) == 0) {
                    if ((j % 2) == 0) {
                        shapeRenderer.setColor(r_brown, g_brown, b_brown, 1);
                        shapeRenderer.rect(100 * i, 100 * j, 100, 100);
                    } else {
                        shapeRenderer.setColor(r_cream, g_cream, b_cream, 1);
                        shapeRenderer.rect(100 * i, 100 * j, 100, 100);
                    }
                } else {
                    if ((j % 2) == 0) {

                        shapeRenderer.setColor(r_cream, g_cream, b_cream, 1);
                        shapeRenderer.rect(100 * i, 100 * j, 100, 100);
                    } else {
                        shapeRenderer.setColor(r_brown, g_brown, b_brown, 1);
                        shapeRenderer.rect(100 * i, 100 * j, 100, 100);
                    }
                }
            }
        }

        shapeRenderer.end();
        camera.update();

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();

        /*
        Piece[][] pieces = new Piece[8][8];
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                Piece currentPiece = pieces[i][j];
                currentPiece.draw();
            }
        }
        */
    }
    @Override
    public void dispose() {
        shapeRenderer.dispose();
    }
}


问:
What is the terminal command to view hidden folders in a git repo on VSCode?
I am attempting to view my .git directory on VSCode by entering the command to show hidden files. I understand that on a Mac, this command is: la

I've read that on Windows, the equivalent command is: ls -la

However, after entering this to the VSCode terminal I am faced with the following error:

What am I doing wrong ?

答:
@siddart:
You are unfortunately incorrect on how you show hidden (dotfiles) files in the terminal/command line on macOS. In order to access hidden files/folders on macOS it is actually ls and if you want to find hidden files/folders on macOS, then you use: $ ls -a

Next, you are referring to PowerShell as compared to just the Command Prompt. cmd

Be aware: There is a difference in the commands and arguments in Powershell as compared to the Command Prompt.

So with that all taken care of, the actual way to do it in Windows via Command Prompt should be exactly the same as it should be in the VS Code terminal.

The folks over at Minitool show 4 different ways to show hidden files from their example, I'll only show you the one from the CMD Prompt.

How to Show Hidden Files Windows 10 with CMD

You can open Command Prompt in Windows 10 to show hidden files with attrib command.

Detailed steps are as follows:

Step 1. Press Windows + R, type cmd, and press Ctrl + Shift + Enter to open elevated Command Prompt in your Windows 10 computer.

Step 2. Then you can type this command line: attrib -h -r -s /s /d E:\*.*, and hit Enter to unhide the files and folders in drive E. You should replace the drive letter with the exact drive letter of your computer. You can open This PC to check the drive letters of your computer hard drive partitions.

```<code>C:\Windows\system32>attrib -h -r -s /s /d E:\*.*
</code>```

Show hidden files cmd

To help you better understand this attrib command, below is the explanation of each part of the command line.

–h: It clears the Hidden file attribute to show hidden files.

–r: It clears the Read-only file attribute to allow you modify the file after it shows.

–s: It clears the System file attribute.

/s: It applies attrib and any command-line options to matching files in the current directory and all of its subdirectories.

/d: It applies attrib and any command-line options to directories.

@Siddart I hope that answers your question.

git visual-studio-code hidden-files commamd-prompt windows terminal attrib-command macos shell bash

Body:
@siddart:
You are unfortunately incorrect on how you show hidden (dotfiles) files in the terminal/command line on macOS. In order to access hidden files/folders on macOS it is actually ls and if you want to find hidden files/folders on macOS, then you use: $ ls -a

Next, you are referring to PowerShell as compared to just the Command Prompt. cmd

Be aware: There is a difference in the commands and arguments in Powershell as compared to the Command Prompt.

So with that all taken care of, the actual way to do it in Windows via Command Prompt should be exactly the same as it should be in the VS Code terminal.

The folks over at Minitool show 4 different ways to show hidden files from their example, I'll only show you the one from the CMD Prompt.

How to Show Hidden Files Windows 10 with CMD

You can open Command Prompt in Windows 10 to show hidden files with attrib command.

Detailed steps are as follows:

Step 1. Press Windows + R, type cmd, and press Ctrl + Shift + Enter to open elevated Command Prompt in your Windows 10 computer.

Step 2. Then you can type this command line: attrib -h -r -s /s /d E:\*.*, and hit Enter to unhide the files and folders in drive E. You should replace the drive letter with the exact drive letter of your computer. You can open This PC to check the drive letters of your computer hard drive partitions.

C:\Windows\system32>attrib -h -r -s /s /d E:\*.*

Show hidden files cmd

To help you better understand this attrib command, below is the explanation of each part of the command line.

–h: It clears the Hidden file attribute to show hidden files.

–r: It clears the Read-only file attribute to allow you modify the file after it shows.

–s: It clears the System file attribute.

/s: It applies attrib and any command-line options to matching files in the current directory and all of its subdirectories.

/d: It applies attrib and any command-line options to directories.

@Siddart I hope that answers your question.

git visual-studio-code hidden-files commamd-prompt windows terminal attrib-command macos shell bash


问:
How to share data between fragments and activities in android
I am new to android.

Can anyone please tell me if it is possible to share data between activities and fragments using java interfaces. I have studied OOP but I am still stuck in interfaces and abstracts classes. I think if I implement a class on many activities, I will be able to share data like passing data from one activity and getting it from another.

Am I right about it? Please help me

答:
Android has standards for setting and getting data in activities and fragments

To send data between activities

```<code>Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("YOUR_INT", 1);
b.putString("YOUR_STRING", "Hello");
intent.putExtras(b);
startActivity(intent);
</code>```

To send data to a fragment from an activity

```<code>// Declare a static method on your fragment 'New Instance'
public static MyFragment newInstance(int yourInt, String yourString) {
    MyFragment myFragment = new MyFragment();

    Bundle args = new Bundle();
    args.putInt("YOUR_INT_KEY", yourInt);
    args.putString("YOUR_STRING_KEY", yourString);
    myFragment.setArguments(args);

    return myFragment;
}

// Get the data inside your fragment
getArguments().getInt("YOUR_INT_KEY", 0); //Default value is zero if no int was found

// Instantiate your fragment wherever
MyFragment f = MyFragment.newInstance(1, "Hello");

</code>```

Body:
Android has standards for setting and getting data in activities and fragments

To send data between activities

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("YOUR_INT", 1);
b.putString("YOUR_STRING", "Hello");
intent.putExtras(b);
startActivity(intent);

To send data to a fragment from an activity

// Declare a static method on your fragment 'New Instance'
public static MyFragment newInstance(int yourInt, String yourString) {
    MyFragment myFragment = new MyFragment();

    Bundle args = new Bundle();
    args.putInt("YOUR_INT_KEY", yourInt);
    args.putString("YOUR_STRING_KEY", yourString);
    myFragment.setArguments(args);

    return myFragment;
}

// Get the data inside your fragment
getArguments().getInt("YOUR_INT_KEY", 0); //Default value is zero if no int was found

// Instantiate your fragment wherever
MyFragment f = MyFragment.newInstance(1, "Hello");


问:
Java8 stream with nested objects
So I'm new to Java8.  I've read about streams, but most examples are very basic.  I was wondering how it'd be done with nested objects.  Here is an example from my code:

```<code>for (Gas gas : gases) {
  resourceNodes.add(gas.getRefinery().unit());
}
</code>```

It seems like I should be able to one-line this with a stream, but I can't quite figure it out.  Could someone provide an answer with a stream.  Is there a way to use :: syntax with nested methods too?

Edit:
To clarify the example, getRefinery() returns an object of type: UnitInPool, whose method unit() returns an object of type: Unit.  resourceNodes is an ArrayList of Unit.

答:
Welcome to the SO community. I hope the following helps.</p>

```<code>List<Unit> resourceNodes = gases.stream() // open a stream
.map(gas -> gas.getRefinery()) // convert to UnitInPool
.filter(unitInPool -> Objects.nonNull(unitInPool)) // null check to avoid NPE
.map(unip -> unip.getUnit()) // convert to Unit
.collect(Collectors.toList()) // collect all the values in a List
</code>```

Title: Java8 stream with nested objects

Body:
So I'm new to Java8.  I've read about streams, but most examples are very basic.  I was wondering how it'd be done with nested objects.  Here is an example from my code:

for (Gas gas : gases) {
  resourceNodes.add(gas.getRefinery().unit());
}

It seems like I should be able to one-line this with a stream, but I can't quite figure it out.  Could someone provide an answer with a stream.  Is there a way to use :: syntax with nested methods too?

Edit:
To clarify the example, getRefinery() returns an object of type: UnitInPool, whose method unit() returns an object of type: Unit.  resourceNodes is an ArrayList of Unit.

Body:
Welcome to the SO community. I hope the following helps.

List<Unit> resourceNodes = gases.stream() // open a stream
.map(gas -> gas.getRefinery()) // convert to UnitInPool
.filter(unitInPool -> Objects.nonNull(unitInPool)) // null check to avoid NPE
.map(unip -> unip.getUnit()) // convert to Unit
.collect(Collectors.toList()) // collect all the values in a List


问:
update issue ORA-01036: illegal variable name/number
im trying to update but this error is not being able to solve through many solutions i saw on similar errors
im using oracle sql for database

Find the below detail

答:
From the cx_Oracle manual section Using Bind Variables:

A bind variable is a colon-prefixed identifier or numeral. For
  example, there are two bind variables (dept_id and dept_name) in this
  SQL statement:

```<code>sql = """insert into departments (department_id, department_name)
          values (:dept_id, :dept_name)"""
cursor.execute(sql, [280, "Facility"])
</code>```

You are using '?', which are not supported by Oracle's SQL.

Body:
From the cx_Oracle manual section Using Bind Variables:

A bind variable is a colon-prefixed identifier or numeral. For
  example, there are two bind variables (dept_id and dept_name) in this
  SQL statement:

sql = """insert into departments (department_id, department_name)
          values (:dept_id, :dept_name)"""
cursor.execute(sql, [280, "Facility"])

You are using '?', which are not supported by Oracle's SQL.


问:
Finding 6648031207514 ' s largest prime factor
this is my first question here.

I have been solving eulerproject.net questions and after getting a correct answer for the given input
I wanted to try different ones to check whether my code was working properly. Seems like it doesn't.

Largest prime factor should be 1137193159 but I get 79. Of course because of the upper limit I have put
here. However, if I increase the upper limit even a little my code gets super slow.

This is the function I have used for finding the largest prime factor

```<code>def largest_prime_factor(n) :

upper_limit = math.trunc((n**0.5))

while(1) :

    for num in range(upper_limit, 2, -1) :
        if n % num == 0 :
            if(isPrime(num)) :
                return num
        else :
            pass

    if(isPrime(n)) :
        return n
</code>```

Here is the isprime method

```<code>## taken from : https://stackoverflow.com/questions/15285534/isprime-function-for-python-language
def isPrime(n):
if n==2 or n==3: return True
if n%2==0 or n<2: return False
for i in range(3, int(n**0.5)+1, 2):   # only odd numbers
    if n%i==0:
        return False

return True
</code>```

Thanks in advance

答:
Fixes to software

The Largest prime factor can be greater than sqrt(n).  Software only returns up to sqrt(n)

incorrect range 'range(upper_limit, 2, -1) :' should be for num in range(upper_limit, 1, -1) : since stop point is exclusive

Should not have while loop around for loop

No need to check if the number is prime after for loop

Issue

Above Fixes Code, but Remaining Issue is algorithm complexity will be O(n) since

O(sqrt(n)) size of for loop

O(sqrt(n)) to run is_prime in each loop

1&2 makes complexity O(n)

Refactored Code

```<code>import math

def largest_prime_factor(n) :

  upper_limit = math.trunc((n**0.5))

  for num in range(upper_limit, 1, -1) : # use 1 for lower limit
      if n % num == 0 :
          if(isPrime(num)) :
              return max(num, n // num)  # to include values above sqrt(n)

  #if(isPrime(n)) :
  return n  # We know it's prime since no divisors in for loop

def isPrime(n):
  if n==2 or n==3: return True
  if n%2==0 or n<2: return False
  for i in range(3, int(n**0.5)+1, 2):   # only odd numbers
      if n%i==0:
          return False

  return True
</code>```

Usage

```<code>print(largest_prime_factor(1137193159 )) # Output: 1137193159
# Timing (using timeit):  0.01357 seconds per calculation
</code>```

Better Algorithm (closer to O(sqrt(n)*log(n)) Time Complexity

Reference

Advantage

Sieve of Erastosenes is better for a batch of numbers --O(n log log n) to find primes in range, then log (n) per number. This wold be O(n*log(n)) for a single number.

Current algorithm is better for a single number--no setup, so O(sqrt(n)*log(n)) per number.

A function to find largest prime factor

def max_prime_factor(n):

```<code># Initialize the maximum prime factor
# variable with the lowest one
maxPrime = -1

# Remove factors of two
while n % 2 == 0:
  max_prime = 2
  n //= 2

# Removed all factors of two so n is odd
# For loop size sqrt(n) / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
  while n % i == 0:
                  # O(log(n)) divisors
    max_prime = i # i must be prime since all
                  # the lower prime divisors
                  # of n have been factored out
    n //= i

# Check if
# n is a prime number
if n > 2:
  max_prime = n

return max_prime
</code>```

Comparison

Timing for n = 1137193159

max_prime_factor: .0061 seconds

largest_prime_factor: 0.01357 seconds

Thus: ~2X improvement for this case over the original code

Body:
this is my first question here.

I have been solving eulerproject.net questions and after getting a correct answer for the given input
I wanted to try different ones to check whether my code was working properly. Seems like it doesn't.

Largest prime factor should be 1137193159 but I get 79. Of course because of the upper limit I have put
here. However, if I increase the upper limit even a little my code gets super slow.

This is the function I have used for finding the largest prime factor

def largest_prime_factor(n) :

upper_limit = math.trunc((n**0.5))

while(1) :

    for num in range(upper_limit, 2, -1) :
        if n % num == 0 :
            if(isPrime(num)) :
                return num
        else :
            pass

    if(isPrime(n)) :
        return n

Here is the isprime method

## taken from : https://stackoverflow.com/questions/15285534/isprime-function-for-python-language
def isPrime(n):
if n==2 or n==3: return True
if n%2==0 or n<2: return False
for i in range(3, int(n**0.5)+1, 2):   # only odd numbers
    if n%i==0:
        return False

return True

Thanks in advance

Body:
Fixes to software

The Largest prime factor can be greater than sqrt(n).  Software only returns up to sqrt(n)

incorrect range 'range(upper_limit, 2, -1) :' should be for num in range(upper_limit, 1, -1) : since stop point is exclusive

Should not have while loop around for loop

No need to check if the number is prime after for loop

Issue

Above Fixes Code, but Remaining Issue is algorithm complexity will be O(n) since

O(sqrt(n)) size of for loop

O(sqrt(n)) to run is_prime in each loop

1&2 makes complexity O(n)

Refactored Code

import math

def largest_prime_factor(n) :

  upper_limit = math.trunc((n**0.5))

  for num in range(upper_limit, 1, -1) : # use 1 for lower limit
      if n % num == 0 :
          if(isPrime(num)) :
              return max(num, n // num)  # to include values above sqrt(n)

  #if(isPrime(n)) :
  return n  # We know it's prime since no divisors in for loop

def isPrime(n):
  if n==2 or n==3: return True
  if n%2==0 or n<2: return False
  for i in range(3, int(n**0.5)+1, 2):   # only odd numbers
      if n%i==0:
          return False

  return True

Usage

print(largest_prime_factor(1137193159 )) # Output: 1137193159
# Timing (using timeit):  0.01357 seconds per calculation

Better Algorithm (closer to O(sqrt(n)*log(n)) Time Complexity

Reference

Advantage

Sieve of Erastosenes is better for a batch of numbers --O(n log log n) to find primes in range, then log (n) per number. This wold be O(n*log(n)) for a single number.

Current algorithm is better for a single number--no setup, so O(sqrt(n)*log(n)) per number.

A function to find largest prime factor

def max_prime_factor(n):

# Initialize the maximum prime factor
# variable with the lowest one
maxPrime = -1

# Remove factors of two
while n % 2 == 0:
  max_prime = 2
  n //= 2

# Removed all factors of two so n is odd
# For loop size sqrt(n) / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
  while n % i == 0:
                  # O(log(n)) divisors
    max_prime = i # i must be prime since all
                  # the lower prime divisors
                  # of n have been factored out
    n //= i

# Check if
# n is a prime number
if n > 2:
  max_prime = n

return max_prime

Comparison

Timing for n = 1137193159

max_prime_factor: .0061 seconds

largest_prime_factor: 0.01357 seconds

Thus: ~2X improvement for this case over the original code


问:
Error drawable and color don't change in textInputLayout
So I'm using a textInputLayout and all I need to do is set a custom drawable for the error icon. Here's my layout and dependency

```<code>    implementation 'com.google.android.material:material:1.2.0-beta01'
</code>```

```<code>    <com.google.android.material.textfield.TextInputLayout
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="@dimen/text_field_height"
        android:layout_margin="@dimen/activity_margin"
        android:hint="@string/insert_name_hint"
        app:boxBackgroundColor="@color/transparent"
        app:boxCornerRadiusBottomEnd="@dimen/text_field_corner"
        app:boxCornerRadiusBottomStart="@dimen/text_field_corner"
        app:boxCornerRadiusTopEnd="@dimen/text_field_corner"
        app:boxCornerRadiusTopStart="@dimen/text_field_corner"
        app:errorEnabled="true"
        app:errorTextColor="?colorAccent"
        app:errorIconDrawable="@drawable/ic_alert_black_24dp"
        app:errorIconTint="?colorAccent"
        app:errorContentDescription="@string/insert_name_hint"
        app:boxStrokeErrorColor="@color/gray"
        app:startIconDrawable="@drawable/ic_cool_black_24dp"
        app:startIconTint="@color/gray"
        app:hintAnimationEnabled="true"
        app:hintTextColor="?colorAccent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/nameEvent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:imeOptions="actionDone"
            android:maxLength="30"
            android:padding="0dp"
            android:textAlignment="center"
            android:textCursorDrawable="@null"
            android:inputType="textCapSentences"/>

    </com.google.android.material.textfield.TextInputLayout>
</code>```

Basically, the drawable and the tints don't work, the default icon and color are used. The rest works as it should. I'm not setting anything programmatically.

答:
Well, the problem was kinda basic, but i found out after a while.
It's not a layout-level problem, but an error management problem. The error must be set on the Input Layout and not on the Input EditText. So here's the difference (i also had to add an id to the Input Layout of course):

Before

```<code>customView.nameEvent.error = getString(R.string.invalid_value_name)
</code>```

After

```<code>customView.nameEventLayout.error = getString(R.string.invalid_value_name)
</code>```

Yep, is that simple. But i think this could be a common error, so i hope this answer can help somebody out there.

Body:
So I'm using a textInputLayout and all I need to do is set a custom drawable for the error icon. Here's my layout and dependency

    implementation 'com.google.android.material:material:1.2.0-beta01'

    <com.google.android.material.textfield.TextInputLayout
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="@dimen/text_field_height"
        android:layout_margin="@dimen/activity_margin"
        android:hint="@string/insert_name_hint"
        app:boxBackgroundColor="@color/transparent"
        app:boxCornerRadiusBottomEnd="@dimen/text_field_corner"
        app:boxCornerRadiusBottomStart="@dimen/text_field_corner"
        app:boxCornerRadiusTopEnd="@dimen/text_field_corner"
        app:boxCornerRadiusTopStart="@dimen/text_field_corner"
        app:errorEnabled="true"
        app:errorTextColor="?colorAccent"
        app:errorIconDrawable="@drawable/ic_alert_black_24dp"
        app:errorIconTint="?colorAccent"
        app:errorContentDescription="@string/insert_name_hint"
        app:boxStrokeErrorColor="@color/gray"
        app:startIconDrawable="@drawable/ic_cool_black_24dp"
        app:startIconTint="@color/gray"
        app:hintAnimationEnabled="true"
        app:hintTextColor="?colorAccent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/nameEvent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:imeOptions="actionDone"
            android:maxLength="30"
            android:padding="0dp"
            android:textAlignment="center"
            android:textCursorDrawable="@null"
            android:inputType="textCapSentences"/>

    </com.google.android.material.textfield.TextInputLayout>

Basically, the drawable and the tints don't work, the default icon and color are used. The rest works as it should. I'm not setting anything programmatically.

Body:
Well, the problem was kinda basic, but i found out after a while.
It's not a layout-level problem, but an error management problem. The error must be set on the Input Layout and not on the Input EditText. So here's the difference (i also had to add an id to the Input Layout of course):

Before

customView.nameEvent.error = getString(R.string.invalid_value_name)

After

customView.nameEventLayout.error = getString(R.string.invalid_value_name)

Yep, is that simple. But i think this could be a common error, so i hope this answer can help somebody out there.


问:
Install a list of software via apt using a list variable
While it's possible to install a list of software the following way:

```<code>- name: Install what I want
  apt:
    name:
      - docker
      - nmap
</code>```

Is it also possible to use a variable that contains a list of software names instead? Like so:

```<code>vars:
  my_list:
    - docker
    - nmap

- name: Install what I want
  apt:
    name: "{{ my_list }}"
</code>```

答:
Yes. It's possible. name is "A list of package names". Both versions of the code are equivalent.

vars:
  my_list:
    - docker
    - nmap
tasks:
  - name: Install what I want
    apt:
      name: "{{ my_list }}"
```

<p><hr>
It's also possible to use a loop. But, this is less efficient.</p>

<pre class="lang-yaml prettyprint-override"><code>vars:
  my_list:
    - docker
    - map
tasks:
  - name: Install what I want
    apt:
      name: "{{ item }}"
    loop: "{{ my_list }}"
</code>```

Body:
While it's possible to install a list of software the following way:

- name: Install what I want
  apt:
    name:
      - docker
      - nmap

Is it also possible to use a variable that contains a list of software names instead? Like so:

vars:
  my_list:
    - docker
    - nmap

- name: Install what I want
  apt:
    name: "{{ my_list }}"

Body:
Yes. It's possible. name is "A list of package names". Both versions of the code are equivalent.

vars:
  my_list:
    - docker
    - nmap
tasks:
  - name: Install what I want
    apt:
      name: "{{ my_list }}"

It's also possible to use a loop. But, this is less efficient.

vars:
  my_list:
    - docker
    - map
tasks:
  - name: Install what I want
    apt:
      name: "{{ item }}"
    loop: "{{ my_list }}"


问:
How to pass variable name from a file and use that variable in script in unix
I have a config file in unix as

```<code>Variable_name:sequences:Status
ABC:1234:/path/txt

and I have a script in unix as

$ABC="select * from table"
</code>```

I want to pass the variable name from file and use the variable in script with the value in script.

so I need to run script like

```<code>for i in /path/file_config;
 $Variable=ABC
 echo $variable # need result "select* from table"
</code>```

Please help me in this

答:
Adding a slight improvement to Shawn's response above:</p>

```<code>for Variable_name in `awk -F: '{ print $1 }' /path/file_config`; do
Variable=$Variable_name
echo ${!Variable}
done
</code>```

Body:
I have a config file in unix as

Variable_name:sequences:Status
ABC:1234:/path/txt

and I have a script in unix as

$ABC="select * from table"

I want to pass the variable name from file and use the variable in script with the value in script.

so I need to run script like

for i in /path/file_config;
 $Variable=ABC
 echo $variable # need result "select* from table"

Please help me in this

Body:
Adding a slight improvement to Shawn's response above:

for Variable_name in `awk -F: '{ print $1 }' /path/file_config`; do
Variable=$Variable_name
echo ${!Variable}
done


问:
Typescript property as string, how do I get the interface
Why do I get this error? How do I give languages an interface when its a object literal in another external module?

Element implicitly has an any type because expression of type string can't be used to index type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.

No index signature with a parameter of type string was found on type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.ts(7053)

export const languages = {
  en: {
    title: "English"
  },
  es: {
    title: "Español"
  },
  fi: {
    title: "Suomalainen"
  }
}
```

<pre class="lang-js prettyprint-override"><code>import React from 'react';
import { languages } from './utils/languageData'

interface IProps {
  lang: string
}

function LanguageSelect(props: IProps) {
  const { lang } = props

  const getText = (langId: string, propVal: string): string => {
    const result = languages[langId][propVal]
    const txt = result ? 'error' : result
    return txt
  }

  return (
    <div className="LanguageSelect" data-test="languageSelect-box">
      <div className="languageArea">{getText(lang, 'title')}</div>
    </div>
  );
}

export default LanguageSelect;
</code>```

答:
You should declare it as a dictionary type

```<code>interface LangTitle {
    title: string;
}

export const languages: { [id: string] : LangTitle } = {
    en: {
       title: "English"
    },
    es: {
       title: "Español"
    },
    fi: {
       title: "Suomalainen"
    }
};
</code>```

And access it like this

const result = languages[langId].title;

Body:
Why do I get this error? How do I give languages an interface when its a object literal in another external module?

Element implicitly has an any type because expression of type string can't be used to index type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.

No index signature with a parameter of type string was found on type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.ts(7053)

export const languages = {
  en: {
    title: "English"
  },
  es: {
    title: "Español"
  },
  fi: {
    title: "Suomalainen"
  }
}

import React from 'react';
import { languages } from './utils/languageData'

interface IProps {
  lang: string
}

function LanguageSelect(props: IProps) {
  const { lang } = props

  const getText = (langId: string, propVal: string): string => {
    const result = languages[langId][propVal]
    const txt = result ? 'error' : result
    return txt
  }

  return (

{getText(lang, 'title')}

  );
}

export default LanguageSelect;

Body:
You should declare it as a dictionary type

interface LangTitle {
    title: string;
}

export const languages: { [id: string] : LangTitle } = {
    en: {
       title: "English"
    },
    es: {
       title: "Español"
    },
    fi: {
       title: "Suomalainen"
    }
};

And access it like this

const result = languages[langId].title;


问:
Unable to set up gitlab ci for golang
Below is the before_script for my gitlab golang ci project:

```<code>before_script:
  - git config --global url."git@gitlab.com:".insteadOf "https://gitlab.com/"
  - apt-get update -qq
  - apt-get install -qq git
  - 'which ssh-agent || ( apt-get install -qq openssh-client )'
  - eval $(ssh-agent -s)
  - ssh-add <(echo "$SSH_PRIVATE_KEY")
  - mkdir ~/.ssh
  - ssh-keyscan -t rsa devsb01 >> ~/.ssh/known_hosts
  - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
  - git remote set-url origin git@gitlab.com/<gitlabusername>/projectName.git
  - mkdir -p /go/src/gitlab.com/projectName /go/src/_/builds
  - cp -r $CI_PROJECT_DIR /go/src/gitlab.com/projectName
  - ls $CI_PROJECT_DIR
  - echo $PWD && ls
  - make dep
</code>```

here the Makefile for dep target is as below:

```<code>dep:
    cd src;go get -v -d ./...;
</code>```

but the ci recognizes the import incorrectly as below and fails:

The issue is that go get somehow is trying to clone the projectname/src.git which doesnt exist.

moving the fileUploader and the test to the src directory solves the issue but moving them to a new controller directory within the src directory fails

答:
try removing this

git config --global url."git@gitlab.com:".insteadOf "https://gitlab.com/"

and all things related to the SSH keys

and add this line

echo -e "machine gitlab.com\nlogin gitlab-ci-token\npassword ${CI_JOB_TOKEN}" > ~/.netrc

the .netrc will allow you the access to the private repo, for gitlab CI you do not need to handle ssh keys.

Title: Unable to set up gitlab ci for golang

Body:
Below is the before_script for my gitlab golang ci project:

before_script:
  - git config --global url."git@gitlab.com:".insteadOf "https://gitlab.com/"
  - apt-get update -qq
  - apt-get install -qq git
  - 'which ssh-agent || ( apt-get install -qq openssh-client )'
  - eval $(ssh-agent -s)
  - ssh-add <(echo "$SSH_PRIVATE_KEY")
  - mkdir ~/.ssh
  - ssh-keyscan -t rsa devsb01 >> ~/.ssh/known_hosts
  - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
  - git remote set-url origin git@gitlab.com/<gitlabusername>/projectName.git
  - mkdir -p /go/src/gitlab.com/projectName /go/src/_/builds
  - cp -r $CI_PROJECT_DIR /go/src/gitlab.com/projectName
  - ls $CI_PROJECT_DIR
  - echo $PWD && ls
  - make dep

here the Makefile for dep target is as below:

dep:
    cd src;go get -v -d ./...;

but the ci recognizes the import incorrectly as below and fails:

The issue is that go get somehow is trying to clone the projectname/src.git which doesnt exist.

moving the fileUploader and the test to the src directory solves the issue but moving them to a new controller directory within the src directory fails


问:
Form unicode character from label
I have a simple syntax related question that I would be grateful if someone could answer. So I currently have character labels in a string format: '0941'.

To print out unicode characters in Python, I can just use the command:

```<code>print(u'\u0941')
</code>```

Now, my question is how can I convert the label I have ('0941') into the unicode readable format (u'\u0941')?

Thank you so much!

Title: Form unicode character from label

Body:
I have a simple syntax related question that I would be grateful if someone could answer. So I currently have character labels in a string format: '0941'.

To print out unicode characters in Python, I can just use the command:

print(u'\u0941')

Now, my question is how can I convert the label I have ('0941') into the unicode readable format (u'\u0941')?

Thank you so much!

Body:
>>> chr(int('0941',16)) == '\u0941'
True


问:
Insert data form Excel to Access 2010
I am looking for a solution to inserting data from Excel into Access 2010. The Data in Excel are in a form. After filling in the form, VBA in Excel will insert data to the Access table as a new record.

I don't want to use function in Access - import from Excel.

I don't want to store data in Excel - object table.

I looked at several topics, but none were what I was looking for. Could somebody help me with this?

答:
You may Refer to  https://stackoverflow.com/a/61950934/12289278</p>

```<code>Sub ImportJEData()
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath
Dim x As Long
Dim var
Dim PayIDnxtRow As Long

'add error handling
On Error GoTo errHandler:

'Variables for file path and last row of data
dbPath = Sheets("Update Version").Range("b1").Value
Set var = Sheets("JE FORM").Range("F14")

PayIDnxtRow = Sheets("MAX").Range("c1").Value

'Initialise the collection class variable
Set cnn = New ADODB.Connection

'Create the ADODB recordset object.
'Set rst = New ADODB.Recordset 'assign memory to the recordset

'Connection class is equipped with a —method— named Open
'—-4 aguments—- ConnectionString, UserID, Password, Options
'ConnectionString formula—-Key1=Value1;Key2=Value2;Key_n=Value_n;
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
'two primary providers used in ADO SQLOLEDB —-Microsoft.JET.OLEDB.4.0 —-Microsoft.ACE.OLEDB.12.0
'OLE stands for Object Linking and Embedding, Database

Do
On Error Resume Next 'reset Err.obj.

     'Get the Max ID +1
    Set rst = Nothing
    Set rst = New ADODB.Recordset 'assign memory to the recordset
    SQL = "SELECT Max(ApNumber)+1 FROM PayVoucherID "
    rst.Open SQL, cnn

    'Check if the recordset is empty.
    'Copy Recordset to the Temporary Cell
    Sheets("MAX").Range("A2").CopyFromRecordset rst

    'Insert the Data to Database And Check If no Errors
    Sql2 = "INSERT INTO PayVoucherID(ApNumber)Values('" & Sheets("MAX").Range("A2") & "') "
    cnn.Execute Sql2

Loop Until (Err.Number = 0)

xlFilepath = Application.ThisWorkbook.FullName

SSql = "INSERT INTO PaypaymentID(Apnumber) " & _
"SELECT * FROM [Excel 12.0 Macro;HDR=YES;DATABASE=" & xlFilepath & "].[MAX$G1:G15000] where APNumber > 1"

cnn.Execute SSql

 Set rst = Nothing
Set rst = New ADODB.Recordset 'assign memory to the recordset

 SQL = "Select PayID From PayPaymentID where APNumber = " & _
Sheets("LEDGERTEMPFORM").Range("B8") & " order by PayID "

rst.Open SQL, cnn
Sheets("PaySeries").Range("B2").CopyFromRecordset rst

rst.Close
' Close the connection
cnn.Close
'clear memory
Set rst = Nothing
Set cnn = Nothing

'communicate with the user
'MsgBox " The data has been successfully sent to the access database"

'Update the sheet
Application.ScreenUpdating = True

On Error GoTo 0
Exit Sub
errHandler:

'clear memory
Set rst = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export_Data"
End Sub

</code>```

Title: Insert data form Excel to Access 2010

Body:
You may Refer to  https://stackoverflow.com/a/61950934/12289278

Sub ImportJEData()
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath
Dim x As Long
Dim var
Dim PayIDnxtRow As Long

'add error handling
On Error GoTo errHandler:

'Variables for file path and last row of data
dbPath = Sheets("Update Version").Range("b1").Value
Set var = Sheets("JE FORM").Range("F14")

PayIDnxtRow = Sheets("MAX").Range("c1").Value

'Initialise the collection class variable
Set cnn = New ADODB.Connection

'Create the ADODB recordset object.
'Set rst = New ADODB.Recordset 'assign memory to the recordset

'Connection class is equipped with a —method— named Open
'—-4 aguments—- ConnectionString, UserID, Password, Options
'ConnectionString formula—-Key1=Value1;Key2=Value2;Key_n=Value_n;
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
'two primary providers used in ADO SQLOLEDB —-Microsoft.JET.OLEDB.4.0 —-Microsoft.ACE.OLEDB.12.0
'OLE stands for Object Linking and Embedding, Database

Do
On Error Resume Next 'reset Err.obj.

     'Get the Max ID +1
    Set rst = Nothing
    Set rst = New ADODB.Recordset 'assign memory to the recordset
    SQL = "SELECT Max(ApNumber)+1 FROM PayVoucherID "
    rst.Open SQL, cnn

    'Check if the recordset is empty.
    'Copy Recordset to the Temporary Cell
    Sheets("MAX").Range("A2").CopyFromRecordset rst

    'Insert the Data to Database And Check If no Errors
    Sql2 = "INSERT INTO PayVoucherID(ApNumber)Values('" & Sheets("MAX").Range("A2") & "') "
    cnn.Execute Sql2

Loop Until (Err.Number = 0)

xlFilepath = Application.ThisWorkbook.FullName

SSql = "INSERT INTO PaypaymentID(Apnumber) " & _
"SELECT * FROM [Excel 12.0 Macro;HDR=YES;DATABASE=" & xlFilepath & "].[MAX$G1:G15000] where APNumber > 1"

cnn.Execute SSql

 Set rst = Nothing
Set rst = New ADODB.Recordset 'assign memory to the recordset

 SQL = "Select PayID From PayPaymentID where APNumber = " & _
Sheets("LEDGERTEMPFORM").Range("B8") & " order by PayID "

rst.Open SQL, cnn
Sheets("PaySeries").Range("B2").CopyFromRecordset rst

rst.Close
' Close the connection
cnn.Close
'clear memory
Set rst = Nothing
Set cnn = Nothing

'communicate with the user
'MsgBox " The data has been successfully sent to the access database"

'Update the sheet
Application.ScreenUpdating = True

On Error GoTo 0
Exit Sub
errHandler:

'clear memory
Set rst = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export_Data"
End Sub


问:
Will modifications to a function's return value in the finally block take effect?
Consider the following code:

```<code> int dummy() {
     int x = 0;
     try {
        x = x + 1;
        throw new Exception();
     } catch (Exception e) {
       x = x + 2;
       return x;
     } finally {
      x = x + 4;
 }
</code>```

I need to "predict" the behaviour of this method without programming it. My question is, what will the return value be?

My guess would be that when an exception occurs, the finally block will be realized, so the value of x will be 4. But I think the value will not be returned. And if no exception occurs, the value will be 2 and it will be returned.

I'm a complete beginner (less than 3 months) in programming so I might be missing something.

答:
First, your int x is declared at 0.

You enter the try block and x becomes 1.

An Exception is thrown, hence the control moves to the catch block.

Here, x gets 2 more and goes to 3, then the value 3 is ready to be returned.

However, the execution continues to execute the finally block and x = x + 4 -> 7 but this doesn't change your return value since when you return an int you're passing its value, not the reference of the variable x.

If you want to know more, I'm sure who assigned you this puzzle will be glad to help!

Body:
Consider the following code:

 int dummy() {
     int x = 0;
     try {
        x = x + 1;
        throw new Exception();
     } catch (Exception e) {
       x = x + 2;
       return x;
     } finally {
      x = x + 4;
 }

I need to "predict" the behaviour of this method without programming it. My question is, what will the return value be?

My guess would be that when an exception occurs, the finally block will be realized, so the value of x will be 4. But I think the value will not be returned. And if no exception occurs, the value will be 2 and it will be returned.

I'm a complete beginner (less than 3 months) in programming so I might be missing something.


问:
NSString init or alloc error?
I have this interface:

```<code> #import <Foundation/Foundation.h>
 @interface Cards : NSObject {  NSString* effect;   NSString* image;   }
-(NSString*) effect;
-(NSString*) image;
-(void) setEffect: (NSString*) effect2;
-(void) setImage: (NSString*) image2;

@end
</code>```

And this implementation:

```<code>#import "Cards.h"
@implementation Cards
-(NSString*) effect
{
    return [effect autorelease];
}
-(NSString*) image
{
    return [image autorelease];
}
-(void) setEffect: (NSString*) effect2
{
  effect = [[NSString alloc]initWithString:effect2];
}
-(void) setImage: (NSString*) image2
{
  image = [[NSString alloc]initWithString:@""];
}
-(void) dealloc
{
    [effect release];
    [image release];
    [super dealloc];
}
@end
</code>```

Now if I make a Cards object such as
Cards* card
and then I run the metod setEffect like so:
[card setEffect:@""];
It compiles but gives me a runtime error. Anyone know why? Thanks in advance!

答:
In your getter methods, you are returning an autoreleased object which may have never been allocated to begin with. In other words, you are only allocating the objects in your setter. If you want your objects to be returned autoreleased, you have to allocate them first, and then return them autoreleased.

You may be better off to create properties for each ivar and have them retained and released by the class. You would still need to allocate them, if they have not been allocated, which you may want to override the getter to do. Something like this.

```<code>-(NSString *)effect {
    if (!effect) {
        effect = [[NSString alloc] init];
    }
return effect;
</code>```

in your header you would have

```<code>NSString *effect;
</code>```

and then the property

```<code>@property(nonatomic, retain) NSString *effect;
</code>```

then in the implementation you would synthesize

```<code>@synthesize effect;
</code>```

and release in your -(void)dealloc

```<code>[effect release];
</code>```

This way after you make a Card class you can call things like

```<code>card.effect = @"Whatever goes in the effect property";

//assuming card is a Card object
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Title: NSString init or alloc error?

Body:
I have this interface:

 #import <Foundation/Foundation.h>
 @interface Cards : NSObject {  NSString* effect;   NSString* image;   }
-(NSString*) effect;
-(NSString*) image;
-(void) setEffect: (NSString*) effect2;
-(void) setImage: (NSString*) image2;

@end

And this implementation:

#import "Cards.h"
@implementation Cards
-(NSString*) effect
{
    return [effect autorelease];
}
-(NSString*) image
{
    return [image autorelease];
}
-(void) setEffect: (NSString*) effect2
{
  effect = [[NSString alloc]initWithString:effect2];
}
-(void) setImage: (NSString*) image2
{
  image = [[NSString alloc]initWithString:@""];
}
-(void) dealloc
{
    [effect release];
    [image release];
    [super dealloc];
}
@end

Now if I make a Cards object such as
Cards* card
and then I run the metod setEffect like so:
[card setEffect:@""];
It compiles but gives me a runtime error. Anyone know why? Thanks in advance!

Body:
In your getter methods, you are returning an autoreleased object which may have never been allocated to begin with. In other words, you are only allocating the objects in your setter. If you want your objects to be returned autoreleased, you have to allocate them first, and then return them autoreleased.

You may be better off to create properties for each ivar and have them retained and released by the class. You would still need to allocate them, if they have not been allocated, which you may want to override the getter to do. Something like this.

-(NSString *)effect {
    if (!effect) {
        effect = [[NSString alloc] init];
    }
return effect;

in your header you would have

NSString *effect;

and then the property

@property(nonatomic, retain) NSString *effect;

then in the implementation you would synthesize

@synthesize effect;

and release in your -(void)dealloc

[effect release];

This way after you make a Card class you can call things like

card.effect = @"Whatever goes in the effect property";

//assuming card is a Card object

Hope this helps.


问:
iOS 8 Custom Keyboard: Changing the height without warning 'Unable to simultaneously satisfy constraints...'
There are several SO answers about how to change Custom Keyboard height. Some of them work for example here but those that work lead to constrains conflict error printed to console output:

```<code>Unable to simultaneously satisfy constraints...
Will attempt to recover by breaking constraint...
</code>```

Here is my very simple keyboard controller that sets custom keyboard height (is Swift):

```<code>class KeyboardViewController: UIInputViewController {
    private var heightConstraint: NSLayoutConstraint?
    private var dummyView: UIView = UIView()

    override func updateViewConstraints() {
        super.updateViewConstraints()

        if self.view.frame.size.width == 0 || self.view.frame.size.height == 0 || heightConstraint == nil {
            return
        }
        inputView.removeConstraint(heightConstraint!)
        heightConstraint!.constant = UIInterfaceOrientationIsLandscape(self.interfaceOrientation) ? 180 : 200
        inputView.addConstraint(heightConstraint!)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.dummyView.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.view.addSubview(self.dummyView)

        view.addConstraint(NSLayoutConstraint(item: self.dummyView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: self.dummyView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0))

        heightConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 0.0)
    }
}
</code>```

This produces the annoying output error that my constrain heightConstraint that I added in updateViewConstraints is in conflict with constrain identified as UIView-Encapsulated-Layout-Height.

I tried to remove conflicting constant (UIView-Encapsulated-Layout-Height) in updateViewConstraints as follows:

```<code>let defaultHeightConst = inputView.constraints().filter() {c in (c as? NSLayoutConstraint)?.identifier == "UIView-Encapsulated-Layout-Height"}.first as? NSLayoutConstraint
if defaultHeightConst != nil {
    inputView.removeConstraint(defaultHeightConst!
}
</code>```

This did not help, the output warning is still there. How do I solve this? Specifically, what can I do to get rid of the output error message?

答:
This warning is still a problem in iOS 13.

It appears because the view of the keyboard extension (KeyboardViewController’s view property) translates autoresizing mask into constraints.

What you want is removing the automatically generated height constraint by calling:

view.translatesAutoresizingMaskIntoConstraints = false
```

<p>Nevertheless, this is not enough: you have to replace the important generated constraints.</p>

<p>I did that in the <code>viewWillAppear</code> function, as the parent view exists at this moment. I use the <code>constraintHaveBeenAdded</code> property to avoid to add several times the same constraints, as the function can be called repeatedly.</p>

<pre class="lang-swift prettyprint-override"><code>class KeyboardViewController: UIInputViewController {

  private var constraintsHaveBeenAdded = false

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    initKeyboardConstraints()
  }

  private func initKeyboardConstraints() {
    if constraintsHaveBeenAdded { return }
    guard let superview = view.superview else { return }
    view.translatesAutoresizingMaskIntoConstraints = false
    view.leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
    view.bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
    view.rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
    view.heightAnchor.constraint(equalToConstant: 250.0).isActive = true
    constraintsHaveBeenAdded = true
  }

}
</code>```

You can even remove the height constraint and let the subviews constraint decide of the keyboard height.

Body:
There are several SO answers about how to change Custom Keyboard height. Some of them work for example here but those that work lead to constrains conflict error printed to console output:

Unable to simultaneously satisfy constraints...
Will attempt to recover by breaking constraint...

Here is my very simple keyboard controller that sets custom keyboard height (is Swift):

class KeyboardViewController: UIInputViewController {
    private var heightConstraint: NSLayoutConstraint?
    private var dummyView: UIView = UIView()

    override func updateViewConstraints() {
        super.updateViewConstraints()

        if self.view.frame.size.width == 0 || self.view.frame.size.height == 0 || heightConstraint == nil {
            return
        }
        inputView.removeConstraint(heightConstraint!)
        heightConstraint!.constant = UIInterfaceOrientationIsLandscape(self.interfaceOrientation) ? 180 : 200
        inputView.addConstraint(heightConstraint!)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.dummyView.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.view.addSubview(self.dummyView)

        view.addConstraint(NSLayoutConstraint(item: self.dummyView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: self.dummyView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0))

        heightConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 0.0)
    }
}

This produces the annoying output error that my constrain heightConstraint that I added in updateViewConstraints is in conflict with constrain identified as UIView-Encapsulated-Layout-Height.

I tried to remove conflicting constant (UIView-Encapsulated-Layout-Height) in updateViewConstraints as follows:

let defaultHeightConst = inputView.constraints().filter() {c in (c as? NSLayoutConstraint)?.identifier == "UIView-Encapsulated-Layout-Height"}.first as? NSLayoutConstraint
if defaultHeightConst != nil {
    inputView.removeConstraint(defaultHeightConst!
}

This did not help, the output warning is still there. How do I solve this? Specifically, what can I do to get rid of the output error message?

Body:
This warning is still a problem in iOS 13.

It appears because the view of the keyboard extension (KeyboardViewController’s view property) translates autoresizing mask into constraints.

What you want is removing the automatically generated height constraint by calling:

view.translatesAutoresizingMaskIntoConstraints = false

Nevertheless, this is not enough: you have to replace the important generated constraints.

I did that in the viewWillAppear function, as the parent view exists at this moment. I use the constraintHaveBeenAdded property to avoid to add several times the same constraints, as the function can be called repeatedly.

class KeyboardViewController: UIInputViewController {

  private var constraintsHaveBeenAdded = false

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    initKeyboardConstraints()
  }

  private func initKeyboardConstraints() {
    if constraintsHaveBeenAdded { return }
    guard let superview = view.superview else { return }
    view.translatesAutoresizingMaskIntoConstraints = false
    view.leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
    view.bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
    view.rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
    view.heightAnchor.constraint(equalToConstant: 250.0).isActive = true
    constraintsHaveBeenAdded = true
  }

}

You can even remove the height constraint and let the subviews constraint decide of the keyboard height.


问:
Is it possible to run containers on android devices?
I’m a mobile developer and recently adept at using containers with docker. I’m developing a container architecture for my graduate project. One of the modules of this architecture would need to be run on an android device. But I could not find information on how to run a container on an android device. It could be something simple like an alpine image with python.

Can anyone tell me if there is a possibility to run a container on an android device with docker, or even kubernetes?

答:
It is possible to use it for running docker on an android device using an application like termux or userland to install a qemu package.

The best way is to use alpine linux terminal, an android app available on github.

This alpine term app has a QEMU to run like alpine ISO. All things are automated
and this works with x86_64 kernel on any android.

Some android phones have a KVM kernel so this device can run faster alpine term

Also my friends made a video on a YouTube channel to run docker on any android phone without root.


问:
How to read a file content in Native File System API
I am trying to read the content of the XML file. Probably this is basic JS stuff, but I seem can't make it work.

I am using Chrome's experimental Native File System API to read folders in folder:

```<code>const opts = {type: 'open-directory'};
handle = await window.chooseFileSystemEntries(opts);
const entries = await handle.getEntries();
...
</code>```

Then, later on in the code I am entering one of the folders from the main directory and trying to read the file in it. The file system strucure is like this:

```<code>Directory > subdirectory > file
</code>```

and the second part of the code looks like this:

```<code>var subdirHandle = await handle.getDirectory(oneOfTheFolders);
var xmlFile = await subdirHandle.getFile('subject.xml');
xmlDoc = domParser.parseFromString(xmlFile, "text/xml");
parsedNumber = document.evaluate(myXpathFce('nodeInXML'), xmlDoc, null, XPathResult.ANY_TYPE, null).iterateNext();
if(parsedNumber.childNodes.length >0){
...
</code>```

I believe the issue is here var xmlFile = await subdirHandle.getFile('subject.xml'); with the file reading. If I loaded the file straight from the Input and used FileReader(), I was able to get the content and parse it, but with the 'directory' approach I am getting null (for the evaluated document) like this Uncaught (in promise) TypeError: Cannot read property 'childNodes' of null

Edit here is what I get in console for the xmlFile variable. I just need to get the content (XML in text format) from this

答:
I noticed you're saving the File object in the xmlFile variable and passing it directly into the parseFromString method.

You cannot parse a document object from a File object directly. You should first read the string from the File object using a FileReader. You can read the string from a File object with the await keyword using the readFileAsync function below:

```<code>function readFileAsync(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.onerror = reject;
    reader.readAsText(file);
  })
}

var file = await handle.getFile();
var text = await readFileAsync(file);
var xmlDoc = domParser.parseFromString(text, "text/xml");
</code>```

Body:
I am trying to read the content of the XML file. Probably this is basic JS stuff, but I seem can't make it work.

I am using Chrome's experimental Native File System API to read folders in folder:

const opts = {type: 'open-directory'};
handle = await window.chooseFileSystemEntries(opts);
const entries = await handle.getEntries();
...

Then, later on in the code I am entering one of the folders from the main directory and trying to read the file in it. The file system strucure is like this:

Directory > subdirectory > file

and the second part of the code looks like this:

var subdirHandle = await handle.getDirectory(oneOfTheFolders);
var xmlFile = await subdirHandle.getFile('subject.xml');
xmlDoc = domParser.parseFromString(xmlFile, "text/xml");
parsedNumber = document.evaluate(myXpathFce('nodeInXML'), xmlDoc, null, XPathResult.ANY_TYPE, null).iterateNext();
if(parsedNumber.childNodes.length >0){
...

I believe the issue is here var xmlFile = await subdirHandle.getFile('subject.xml'); with the file reading. If I loaded the file straight from the Input and used FileReader(), I was able to get the content and parse it, but with the 'directory' approach I am getting null (for the evaluated document) like this Uncaught (in promise) TypeError: Cannot read property 'childNodes' of null

Edit here is what I get in console for the xmlFile variable. I just need to get the content (XML in text format) from this

Body:
I noticed you're saving the File object in the xmlFile variable and passing it directly into the parseFromString method.

You cannot parse a document object from a File object directly. You should first read the string from the File object using a FileReader. You can read the string from a File object with the await keyword using the readFileAsync function below:

function readFileAsync(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.onerror = reject;
    reader.readAsText(file);
  })
}

var file = await handle.getFile();
var text = await readFileAsync(file);
var xmlDoc = domParser.parseFromString(text, "text/xml");


问:
Issue assigning variable in blackjack 'hit or stay' function. Looping incorrectly?
I'm new to programming. I'm trying to create a 'hit or stay' function in a simple blackjack game taking user input in a try/except/else statement, which is also nested inside a while loop checking to make sure the user input is either 'h' or 's'. The problem is that the variable is never assigned to the user input. Here's what I have:

```<code>def hit_or_stay(deck,hand):
    global playing
    x = '' # just holds input for hit/stay

    while x !='h' and x !='s':
        try:
            x = input('HIT or STAY? (h/s): ').lower
        except:
            print("Please enter h to hit or s to stay." )
        else:
            break
    if x == 'h':
        print("You have chosen to hit.")
        hit(deck,hand)
    elif x == 's':
        print("You have chosen to stay.")
        playing = False
    else:
        print(f"x equals {x}")
</code>```

The program always just returns the 'else' statement at the end, so I know x is not properly taking the user input. What am I doing wrong?

答:
lower is a function you need to call like so. You also don't need the else in the while loop.

def hit_or_stay(deck,hand):
    global playing
    x = '' # just holds input for hit/stay

    while x !='h' and x !='s':
        try:
            x = input('HIT or STAY? (h/s): ').lower()
        except:
            print("Please enter h to hit or s to stay." )
    if x == 'h':
        print("You have chosen to hit.")
        hit(deck,hand)
    elif x == 's':
        print("You have chosen to stay.")
        playing = False
    else:
        print(f"x equals {x}")
```

<p>I'm not sure what behaviour you want by having the <code>try-except</code> block inside the while loop. The only exception that line of code is likely to throw is if a user attempts to quit the program by pressing Ctrl+C. Your code catches this and continues to tell the user to enter h or s. This is not typically good behaviour - better to not include the try-except.</p>

<pre class="lang-py prettyprint-override"><code>def hit_or_stay(deck,hand):
    global playing
    x = '' # just holds input for hit/stay

    while x !='h' and x !='s':
        x = input('HIT or STAY? (h/s): ').lower()
    if x == 'h':
        print("You have chosen to hit.")
        hit(deck,hand)
    elif x == 's':
        print("You have chosen to stay.")
        playing = False
    else:
        print(f"x equals {x}")
</code>```

Body:
I'm new to programming. I'm trying to create a 'hit or stay' function in a simple blackjack game taking user input in a try/except/else statement, which is also nested inside a while loop checking to make sure the user input is either 'h' or 's'. The problem is that the variable is never assigned to the user input. Here's what I have:

def hit_or_stay(deck,hand):
    global playing
    x = '' # just holds input for hit/stay

    while x !='h' and x !='s':
        try:
            x = input('HIT or STAY? (h/s): ').lower
        except:
            print("Please enter h to hit or s to stay." )
        else:
            break
    if x == 'h':
        print("You have chosen to hit.")
        hit(deck,hand)
    elif x == 's':
        print("You have chosen to stay.")
        playing = False
    else:
        print(f"x equals {x}")

The program always just returns the 'else' statement at the end, so I know x is not properly taking the user input. What am I doing wrong?

Body:
lower is a function you need to call like so. You also don't need the else in the while loop.

def hit_or_stay(deck,hand):
    global playing
    x = '' # just holds input for hit/stay

    while x !='h' and x !='s':
        try:
            x = input('HIT or STAY? (h/s): ').lower()
        except:
            print("Please enter h to hit or s to stay." )
    if x == 'h':
        print("You have chosen to hit.")
        hit(deck,hand)
    elif x == 's':
        print("You have chosen to stay.")
        playing = False
    else:
        print(f"x equals {x}")

I'm not sure what behaviour you want by having the try-except block inside the while loop. The only exception that line of code is likely to throw is if a user attempts to quit the program by pressing Ctrl+C. Your code catches this and continues to tell the user to enter h or s. This is not typically good behaviour - better to not include the try-except.

def hit_or_stay(deck,hand):
    global playing
    x = '' # just holds input for hit/stay

    while x !='h' and x !='s':
        x = input('HIT or STAY? (h/s): ').lower()
    if x == 'h':
        print("You have chosen to hit.")
        hit(deck,hand)
    elif x == 's':
        print("You have chosen to stay.")
        playing = False
    else:
        print(f"x equals {x}")