unity – How to implement camera movement with mouse in new Input System?

I am transitioning to the new movement system and am having trouble figuring out how to move the camera when a mouse button is pressed and held.

Here’s how I did it before:

private void Update()
{
    // Get the position of the mouse when a middle click occurs
    if (Input.GetMouseButtonDown(2))
    {
        _dragOrigin = cam.ScreenToWorldPoint(Input.mousePosition);
    }

    // If the MMB is still held down, calculate the distance and move the camera
    if (Input.GetMouseButton(2))
    {
        Vector3 difference = _dragOrigin - cam.ScreenToWorldPoint(Input.mousePosition);
        cam.transform.position += difference;
    }
}

I have tried doing something similar in the new input system but it doesn’t work:

public void OnMMB(InputAction.CallbackContext context)
{
    if (context.phase != InputActionPhase.Started)
    {
        // Get the position of the mouse when a middle click occurs
        dragOrigin = cam.ScreenToWorldPoint(Mouse.current.position.ReadValue());
    }
    else
    {
        // If the MMB is still held down, calculate the distance and move the camera
        Vector2 newPosition = cam.ScreenToWorldPoint(Mouse.current.position.ReadValue());
        Vector3 difference = dragOrigin - newPosition;
        cam.transform.position += difference;
    }
}

Here is how I set this up inside the Input editor:
Image

The Action Type of the action is Button.

sql server – How can we implement “A student can enroll in up to 4 units in a semester “

I have a practice problem on Database implementation and am confused. For this database, I need to store enrollment information on students. Information such as which units a student has enrolled into. The relationship between Units and Students is such that a student can enroll in up to 4 units per semester but a unit can be enrolled into by many students. My problem is, how can I implement this limitation of a student enrolling in up to only 4 units per semester in mysql using either CHECKs or triggers?

If it was one to many relationship between Student and Units that would have been straight forward but here we have a one to four(?) relationship?

dnd 5e – What are some ways one might implement a more story-driven spell/skill acquisition?

The mechanics and the narrative are separate

Mechanically a player ‘goes shopping in the PHB for new skills’ but narratively, they have been practising these skills possibly from the get go. All you need to do, if you (and your players) care, is get your players to roleplay this.

For example during a long rest my wizard (currently level 6) spends time playing around with the components for arcane eye and polymorph, which are the spells I am going to learn next level. Some players know what I am doing and why and others don’t, but I like the idea that my wizard is learning as he goes.

One of the other players spends time practising certain fighting abilities.

One thing I have found however is that some players don’t think ahead enough, so have no idea what abilities they will get at next level, let alone try and plan how they ‘learn’ then, others don’t care, and others find the explanations of practice boring, and quite possibly needlessly repetitive.

If you are looking for a game where you have to go and see a trainer to learn new skills then you can implement that, or more likely find a different game, because that isn’t really what D&D is about, but generally you need to separate the mechanics from the narrative around how they work.

The easiest way to do this is keep prompting your players ‘how did you learn that’ and let them come up with the explanations. In my experience your view on how skills just ‘appear’ is because you have taken a literal reading of the rules, but it is imagination that turns that into a game, you don’t need to add new rules.

If you do want to add new rules, then you are probably better off looking for a different game rather than trying to redo some of the key rules in D&D.

How can I create a custom 3D model format and implement it with OpenGL?

I want to create a 3D model format which would be easy for me to use and implement it into my game using C++

If it may be necessary, I use Visual Studio Code and Manjaro KDE Linux.

complexity theory – How to implement a Turing Machine that calculates log base 2 of n where n is a natural number and output in a unary format?

How would you construct a Turing Machine that calculates log2(n)?

The process must take in an input such as 4 and output the result in a unary format such as a 11 (11 = 2 in unary)?

In the final output tape, the tape should only contain blank symbols followed by a consecutive number of 1’s from the final head position.

Many Thanks

angular 2+ – Is it a good practice to restrict refresh , reload & back navigation of a browser(In some special cases only) ? If yes how can we implement that?

The user can’t be navigated to the previous page when we click on back navigation. In some cases, we are able to navigate when the page is refreshed/reloaded. need to restrict to a couple of pages, not throughout the app.
Actually, I’m using this

        constructor( private location: LocationStrategy){
history.pushState(null, null, window.location.href);  
this.location.onPopState(() => {
  history.pushState(null, null, window.location.href);
});  
}

domain driven design – How to implement authorization that needs to be done in the same transaction as aggregate method runs in (DDD)?

Generally most of the authorization in the system is done in authorization layer which then calls commands/queries from application layer, which call methods on domain aggregates. However there are several cases when authorization has to be done in same transaction where aggregate method is executed and this authorization requires some info/fields from aggregate that is going to be modified (for example user can edit only his own posts – we know if post belongs to user only after reading it from storage/db).

API -> controller (authorization) -> command/query -> aggregate.method()

Here is how example command looks like:

import _ from 'lodash';
import * as di from '@/framework/di';
import * as app from '@/framework/application';
import { ConferenceRepositoryImplMemory, Conference } from './../../../infrastructure/repositories/conference-repository-impl-memory';

interface UpdateConferencePayload {
  conference_guid: string;
  name: string;
  short_name: string;
  website_url: string;
}

@di.perResolutionChain()
export class UpdateConferenceCommand extends app.Command<UpdateConferencePayload, void> {

  constructor(
    private readonly conferenceRepository: ConferenceRepositoryImplMemory,
  ) {
    super();
  }

  public async execute(payload: UpdateConferencePayload) {
    const conference = await this.conferenceRepository.getByGuid(payload.conference_guid);
    conference.changeName(_.pick(payload, ('name', 'short_name')));
    conference.changeWebsite(_.pick(payload, ('website_url')));
    this.conferenceRepository.update(conference);
    await this.conferenceRepository.saveChanges();
  }
}

I think it can be done in several ways:

  1. make command/query to take extra argument in addition to payload for example “checkIfPostBelongToUser(postOwnerGuid)” and then call it (with proper aggregate field) just after reading aggregate from db but before invoking aggregate method. However I think this is bad for testing the command because you have to test authorization in addition to command “behaviour”. Also it’s possible that same command could be called by moderator for example who can edit others posts or by internal system which does not have to be authorized at all. It would be possible to make this extra authorization command param optional though…

  2. another option is to instead of one command “editPost()” make two commands “editOwnPost(…, userGuid)”, “editPost()”. Former one would throw exception if post aggregate read from storage has incorrect ownerGuid. In this case authorization could be done in authorization layer (if user is moderator then editPost().execute() else editOwnPost().execute. However I am not sure it this is a way to go because it’s defining something between authorization and business logic on command level… also commands don’t match domain logic and it feels like it should be done on domain level instead but again putting authorization to domain level is not a good thing AFAIK.

  3. the last option I can think of is to start transaction in which command runs before command is executed, read aggregate, check it’s fields (owner for example) and then if it’s ok execute command. Thanks to dependency injection it would not require duplicated reads from storage etc, and command would be completely separated from authorization. In such case command controller would look like this:

import _ from 'lodash';
import * as di from '@/framework/di';
import * as app from '@/framework/application';
import { ConferenceRepositoryImplMemory, Conference } from './../../../infrastructure/repositories/conference-repository-impl-memory';

interface UpdateConferencePayload {
  conference_guid: string;
  name: string;
  short_name: string;
  website_url: string;
}

@di.perResolutionChain()
export class UpdateConferenceCommandController {

  constructor(
    private readonly conferenceRepository: ConferenceRepositoryImplMemory,
    private readonly updateConferenceCommand: UpdateConferenceCommand,
  ) {
    super();
  }

  public async execute(payload: UpdateConferencePayload) {
    const conference = await this.conferenceRepository.getByGuid(payload.conference_guid);
    if (conference.something) {
      throw AuthorizationError();
    }
    await this.updateConferenceCommand.execute(payload);
  }
}

I like last option the most because it makes authorization and application layers separate, however it also requires authorization level code to actually init transaction and read aggregate before the command itself is executed.

Which option (if any) will be best, I mean according to some DDD/other desing principles?

algorithm – Implement the merge functionality for 2048 using JavaScript

I am trying to implement the game 2048 using JavaScript. I am using a two-dimensional array to represent the board. For each row, it is represented using an array of integers.

Here I am focused on implementing the merge left functionality i.e. the merge that happens after the user hits left on their keyboard.

Here are a set of test cases that I came up with

const array1 = (2, 2, 2, 0) //  (4,2,0,0)
const array2 = (2, 2, 2, 2) // (4,4,0,0)
const array3 = (2, 0, 0, 2) // (4,0,0,0)
const array4 = (2, 2, 4, 16) // (4,4,16,0)

The commented part is the expected results after merge left happened.

Here is my attempt

const arrays = (
  (2, 2, 2, 0), //  (4,2,0,0)
  (2, 2, 2, 2), // (4,4,0,0)
  (2, 0, 0, 2), // (4,0,0,0)
  (2, 2, 4, 16) // (4,4,16,0)
);

function mergeLeft(array) {
  let startIndex = 0
  let endIndex = 1
  while (endIndex < array.length) {
    if (array(startIndex) === array(endIndex)) {
      array(startIndex) = array(startIndex) + array(endIndex)
      array(endIndex) = 0
      startIndex++
    }
    endIndex++
  }
  return shift(array, 'left')
}

function shift(array, dir) {
  if (dir === 'left') {
    for (let i = 0; i < array.length - 1; i++) {
      if (array(i) === 0) {
        (array(i), array(i + 1)) = (array(i + 1), array(i))
      }
    }
  }
  // omitting when dir === 'right', 'up', 'down' etc.
  return array
}

arrays.forEach(a => console.log(mergeLeft(a)));

So the idea here is that I merged the array and then shift the non-zero items to the left.

My current solution is buggy for this particular case – when the array is (2, 2, 2, 2), the output is (4,2,2,0) when the expected output is (4,4,0,0)

I know that my implementation is not elegant either. So I would love to see how this can be implemented in a (much) better way.

9 – Implement an API to use HTTP extensions like CalDAV

I solved this.
I added method to the route and @Method({‘PROPFIND’}) to the source (I am not sure if this is needed for Symfony).

class DavController extends ControllerBase {

/**     
 * @Method({"PROPFIND"})       
 */
 public function dav() {
     //Get the data, fill into xml twig

        $response = new Response();
        $xml = Drupal::service('renderer')->renderRoot($build);
        $response->setContent($xml);
        $response->headers->set('Content-Type', 'application/xml');

        return $response
 }

module_name.routing.yml (this seems to be mandatory):

    entity.dav_controller.dav:
        path: 'path/to/dav/enpoint'
        methods: (PROPFIND)
        defaults:
            _controller: 'DrupalpathtoDavController::dav'
            _title: 'my_title'
        requirements: 
            _permission: 'access content'

This works in 8 and 9.

Note that this does not involve the Drupal REST API. This is supposed to be an own implementation and won’t solve the issue for anyone who wants to use REST API to answer to such methods. I am not experienced enough with Drupal to explain if and how one could configure REST API to accept HTTP methods not listed in the REST API documentation. Maybe one could extend own controllers from the REST API, but I didn’t inquire into how to do that.

8 – How to implement stateless authentication

I’m having a big problem with Drupal 8, I want Drupal to trust a downstream reverse proxy that performs authentication against a third party provider, then passes a JWT in a X_ID_TOKEN header.

As I didn’t find any module that behaves as an authentication provider that trusts HTTP headers to authenticate the user, I developed a provider myself which is implemented as follows:

public function applies(Request $request) {
  // If you return TRUE and the method Authentication logic fails,
  // you will get out from Drupal navigation if you are logged in.
  $trusted_host = "127.0.0.1";
  $headers = $request->server->getHeaders();
  $server_addr = $request->server->get('SERVER_ADDR');
  return ($server_addr == $trusted_host) && $headers && $headers('X_ID_TOKEN');
}

public function authenticate(Request $request) {
  $headers = $request->server->getHeaders();
  $jwt_token = explode('.', $headers('X_ID_TOKEN'));
  $user_data = json_decode(base64_decode($jwt_token(1)), true);
  if(!$user_data && !$user_data('email')){
    return NULL;
  }
  $users = Drupal::entityTypeManager()->getStorage('user')
    ->loadByProperties(('mail' => $user_data('email')));
  $user = reset($users);
  if ($user) {
    $uid = $user->id();
    $rids = $user->getRoles();
    $account = User::load($uid);
    return $account;
  }else{
    /** @var DrupaluserEntityUser $account */
    $account = User::create((
      'name' => $this->generate_username($user_data),
      'pass' => user_password(),
      'mail' => $user_data('email'),
      'init' => $user_data('email'),
      'status' => 1,
    ));
    $account->save();
    // Store the newly created account.
    $this->save_user_info($account, $user_data);
    return $account;
  }
  return NULL;
}

Then the service is registered like this:

services:
  authentication.trust_openid_auth:
    class: Drupaltrust_openid_authAuthenticationProviderOpenIDAuth
    tags:
      - { name: authentication_provider, provider_id: open_idauth, priority: 0, global: TRUE }

This sort of works, but the pages we are rendering contain user personal data, and they are being cached by some Drupal internal cache. This cache is “per user” thanks to the native Drupal session cookie.

Problem: this cookie seems to be randomly set (when it’s not there it randomly appears when navigating). When the session cookie is not set, the cache is global and results in rendering a page that contains the personal information of the last user that successfully rendered the page (not necessarily the current user!)

I have read that the session cookie starts existing when data is attached to the PHP session, which I’m not in control of.

I’m pretty lost at this point, the two solution I thought of are:

  • Tell Drupal to trust a remote Cookie (set by the downstream reverse proxy) as the session Cookie, this cookie would contain the user’s JWT
  • Force the Drupal session Cookie even if there is no data attached to the session, just to contextualize the cache

The first solution would be ideal but I’m not sure how to achieve it. Any help on this would be welcome!