Categories
discuss

Java Snake Game avoiding using Thread.sleep

I made my first game in Java – Snake, it’s main loop looks like this

while (true)
    {
        long start = System.nanoTime();
        model.eUpdate();
        if (model.hasElapsedCycle())
        {
            model.updateGame();
        }
        view.refresh();
        long delta = (System.nanoTime() - start) / 1000000L;
        if (delta < model.getFrameTime())
        {
            try
            {
                Thread.sleep(model.getFrameTime() - delta);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

But in my project’s requirments there is a responsivity point, so I need to change the Thread.sleep() into something else, but I have no idea how to do this in an easy way. Thanks in advance for any advice.

Answer

I’ve done a simple game or two with Java and to handle the main game loop I’ve used a Swing Timer. The timer will allow you to set an ActionListener to be fired after a provided delay has elapsed. The in-between delay would be derived from your frame rate. The most basic usage would look like:

Timer timer = new Timer(delay, listener);
timer.start();

This would set the initial and in-between delays to the same value. You could also set them to be different values if needed like so:

Timer timer = new Timer(delay, listener);
timer.setInitialDelay(0);
timer.start();

In the above example, the listener will fire ASAP after starting and with a delay in-between thereafter.

Categories
discuss

ConstraintLayout vs “Traditional” Layouts

I am just wondering when to choose the CoordinatorLayout over “Traditional” Layouts or are they (or at least some of them) going to be deprecated?

The question ConstraintLayout vs CoordinatorLayout already showed me that the CoordinatorLayout still has its right of existence.
I’d imagine that the FrameLayout is still a better choice than the ConstraintLayout when there is only one child View.

But what’s about the other Layouts?

I am personally so accustomed to writing layouts by hand in xml so transitioning to the ConstraintLayout is very hard for me. Furthermore answers to this questions would really interest me:

Does the ConstraintLayout have better performance then a nested Layout? If it is the case, at which point does this occur (which level of nesting)?

Answer

I am just wondering when to choose the CoordinatorLayout over
“Traditional” Layouts or are they (or at least some of them) going to
be deprecated?

So ConstraintLayout is useful, but (for now) it is not required for Android app development, any
more than LinearLayout and RelativeLayout are. And, because ConstraintLayout is a
library, you will need to take some additional steps to add it to your project (com.android.support.constraint:constraint-layout artifact in your
dependencies closure of your module’s build.gradle file), and it
adds ~100KB to the size of your Android app.

I am personally so accustomed to writing layouts by hand in xml so
transitioning to the ConstraintLayout is very hard for me.

Drag and drop GUI builder

Google is trying to make life easier to developers and make they work faster and more productive so they continue improving drag-drop GUI builder. However drag-and-drop gestures, the developer is only
providing you with X/Y coordinates of a widget, based on where the developer
releases the mouse button and completes the drop.
With LinearLayout adding widgets is easy. With RelativeLayout is difficult for GUI bulder to handle drag-drop and probably you will have to dig inside the XML code to get things done.
ConstraintLayout was created with GUI building in mind, to make it a bit easier to
infer the right rules based upon where the developer happens to drop a widget.

Recomputing size and position

Changing the details of a widget often cause
the sizes to have to be recomputed. For example nne change in TextView might
cause that whole hierarchy to go through re-size/re-position work. If you have container inside container which is inside another container etc., means that parents re-size/re-position their children and that can be very
expensive for deep hierarchies.
So

Does the ConstraintLayout have better performance then a nested
Layout?

Yes, ConstraintLayout is being designed with performance in mind, trying to eliminate
as many pass scenarios as possible and by trying to eliminate the need for
deeply-nested view hierarchies.

Huh,

for more you can take a look in a book about android development from CommonsWare.
There using ConstraintLayout is explained in more details with comparation examples with another containers like LinearLayout, RelativeLayout etc. Really anatomy of android development.

Categories
discuss

AWS SDK can’t add Lambda as target to Cloudwatch event

I am developing an application where I need to schedule a task, so I am using AWS Lambda for it.However, the scheduled time is dynamic, since it depends on the user request, it can’t be scheduled using AWS Console, so I use AWS Javascript SDK to schedule it. This is the flow:

  1. Create a CloudWatch Rule (this is successful, I can see the rule being created in the console
  2. Add permission to the policy of lambda, so that cloudwatch event can invoke it (Lambda function code is same for all request, so I created a lambda function in AWS Console instead of using SDK)
  3. Add target to the rule created in Step 1 (this step fails). The error i get is RoleArn is not supported for target arn:aws:lambda:eu-west-1:629429065286:function:prebook.

Below is the Node.js code I wrote

schedule_aws_lambda: function(booking_id, cronTimeIST, callback){
      var event = new AWS.CloudWatchEvents({
        accessKeyId: accessKeyId,
        secretAccessKey: secretAccessKey,
        region: 'eu-west-1'
      });

      var lambda = new AWS.Lambda({
        accessKeyId: accessKeyId,
        secretAccessKey: secretAccessKey,
        region: 'eu-west-1'
      });

      var year = cronTimeIST.utc().year();
      var month = cronTimeIST.utc().month() + 1;
      var date = cronTimeIST.utc().date();
      var hour = cronTimeIST.utc().hour();
      var minute = cronTimeIST.utc().minute();
      var cronExpression = "cron(" + minute + " "+ hour + " " + date + " " + month + " ? " + year +")";
      var hour_minute = cronTimeIST.format("HH_mm");
      var ruleParams = {
        Name: 'brodcast_' + booking_id + '_' + hour_minute,
        Description: 'prebook brodcast for ' + booking_id + '_' + hour_minute,
        ScheduleExpression: cronExpression, 
        RoleArn: 'arn:aws:iam::629429065286:role/service-role/prebook_lambda_role',
        State: 'ENABLED',
      };
      event.putRule(ruleParams).promise()
      .then(data => {
        var lambdaPermission = {
          FunctionName: 'arn:aws:lambda:eu-west-1:629429065286:function:prebook',
          StatementId: 'brodcast_' + booking_id + '_' + hour_minute,
          Action: 'lambda:*',
          Principal: 'events.amazonaws.com', 
        };
        return lambda.addPermission(lambdaPermission).promise();
      })
      .then(data => {
        var targetParams = {
          Rule: ruleParams.Name,
          Targets: [
            {
              Id: 'default',
              Arn: 'arn:aws:lambda:eu-west-1:629429065286:function:prebook',
              RoleArn: ruleParams.RoleArn,
              Input: JSON.stringify({booking_id: booking_id})
            }
          ]
        };
        return event.putTargets(targetParams).promise();
      })
      .then(data => {
        callback(null, data);
      })
      .catch(err => {
        callback(err)
      });  
    }

I know it has to do something with the Role which doesn’t have some permission, I can’t figure out the exact cause, I have given the following access for the role enter image description here

And this is the policy document

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    },
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

Basically, I want to attach many triggers(the trigger time is not known to me it depends on user request) to the lambda function, however, lambda function code is same for all.

Answer

Try removing the RoleArn property. If you are adding permissions to the Lambda function to allow CloudWatch events to invoke it, you don’t need it.

In the function policy, make sure you add the SourceArn of the event.

Categories
discuss

Stateless React components with controlled input

Currently to make controlled inputs work inside Stateless React components I am wrapping the stateless component inside a Sate full component.

For example,

const InputComponent = (props) => {
  return (
    <input value={props.name} onChange={props.handleChange} />
  );
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Tekeste'
    };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({
      name: event.target.value
    });
  }
  render() {
    return (
      <InputComponent name={this.state.name} handleChange={this.handleChange} />
    );
  }
}

What I would like to know is a couple of things.

  1. Is this a good pattern?
  2. If not how can I achieve my goal i.e to have controlled inputs inside stateless components.

Answer

Since the InputComponent receives its value and the callback to modify it from its parent, it’s a controlled input without a state. It’s a perfectly good pattern, you can also make it even simpler using ES7 class properties like this:

class App extends React.Component {
  state = {
    name: 'Tekeste'
  };

  handleChange = (event) => {
    this.setState({
      name: event.target.value
    });
  }

  render() {
    return (
      <InputComponent name={this.state.name} handleChange={this.handleChange} />
    );
  }
}

If you’re using create-react-app, it’s already supported out-of-the-box.

Also, you can rename the props of controlled input to value and onChange as they are more conventionally used.

Categories
discuss

Does module.exports in node js create a shallow copy or deep copy of the exported objects or functions?

For example,

If I have 2 modules try1.js and try2.js

try1.js
   module.exports.msg = "hello world";

try2.js
   try1 = require('./try1');
   try1.msg = "changed message";

Does the change in the contents of msg made in try2.js affect try value of msg in try1.js?

Answer

There is no copy at all made. module.exports is an object and that object is shared directly. If you modify properties on that object, then all who have loaded that module will see those changes.

Does the change in the contents of msg made in try2.js affect try value of msg in try1.js?

Yes, it does. There are no copies. The exports object is shared directly. Any changes you make to that exported object will be seen by all who are using that module.

FYI, a module could use Object.freeze(module.exports) to prevent changes to that object after the desired properties are added.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..