c# – DRY-ing up state machine transitions

I’m making a game in Unity and I’ve made a hierarchical state machine to handle different player states.
I have however noticed that some states, like for example InAirState which triggers every time player is in air, have the same piece of code in other, adjacent states, which trigger the change. Something like

if (!Player.IsOnGround && !Player.IsOnWall)

This same if shows up in 3 different, adjacent states, but this is not the sole condition for this particular state. I have a concept of AbilityStates which pertain to player abilities, and these states do not call StateMachine.ChangeState until they are done performing.

This repetition can be, and was, cause of numerous bugs because I’d change the conditions in some states and not in others. I want to avoid this but I am not sure how to proceed.

I thought that maybe I could have the condition as part of the state as some CanChange method and use that within StateMachine.ChangeState to check whether or not the state can be changed to given state. That idea fell apart when I noticed that the condition can’t always be the same. It needs to be different for some cases.

So now I know that I need a way to specify, for each state, what states it can transition to and what are the conditions, as well a way to somehow reuse those conditions. This is where I am stuck. I am unsure what pattern would fit here to make the whole thing DRY and flexible at the same time.

I’ve looked at some other state machine implementations but I couldn’t find any that tackle this particular problem, or at least they’ve seemed not to as the examples were really simple.

Can anyone help me with some ideas on how to tackle this problem?

taxonomy terms – Is there anyway create relationship for filter criteria which has vocabularies( state, city and location) in views – Drupal 8

list of available Vocabularies in my content type.

  • Country(Term: US)
  • State (Terms: CA , CO, DE.. etc)
  • City (Terms:Fremont, Irwin, Los Angeles, Monument etc..)
  • Location(Terms: All loacations)

I’m trying to create a view for published content result which uses above vocabularies. I need to expose filters to the users where I added above vocabulary fields. How to create a relationship to select particular state->city-> location
(For ex: State(CA)->City(Fremont)->location(xxx-fremont))

Below is the example filter. Please help.

enter image description here

react.js – Data state filter on toggle by categories

Here is a simple react app that will list some dummy data and can be filtered by categories (in this case, by user ID) by toggling the button on/off.


import React, { useContext, useState } from "react";
import DataContext from "../../context/dataContext";
import "./FilterBtn.css";

const FilterBtn = ({ category }) => {
  const { currentCategory, setCategory, filterData } = useContext(DataContext);

  const (isFilter, setIsFilter) = useState(false);

  /* The idea here is to toggle the filter by click and then send both category
     and isFilter in order to trigger the filter dispatch in State

  const onClick = () => {

    /* Not sure on how to properly make this work since setIsFilter is asynchronous
       and isFilter will still be false. I read that useEffect or useCallback could work
       but I am not sure if they are efficient at all.
    // setIsFilter(prevState => !prevState) also doesn't seem to work.


    /* This is to set the currentCategory in order to know which button is being clicked on
       and will apply the highlighted class on it if true

    if (currentCategory !== category) {
    } else {

    // Here I invert isFilter so that it will be sent to state as "true"
    filterData(category, !isFilter);

    /* Note that the toggle logic is still flawed, and will not toggle the data as expected if the
       toggle switch constantly between buttons

  return (
    // I need to know which category it is currently being toggled on in order to change the class
      className={currentCategory === category ? "highlighted" : ""}
      User {category}

export default FilterBtn;


import React, { useReducer } from "react";
import DataContext from "./dataContext";
import DataReducer from "./dataReducer";
import axios from "axios";
import types from "./types";


const DataState = ({ children }) => {
  const initialState = {
    data: (),
    currentCategory: null

  const (state, dispatch) = useReducer(DataReducer, initialState);

  // To set the currentCategory being clicked on

  const setCategory = (category) => {
      type: SET_CATEGORY,
      payload: category

  // The filter works by sending category parameter to the backend in order to filter the data and then send it back again to react
  // There is probably a way to filter without having to fire another request to backend

  const filterData = async (userId, filter) => {
    // Some simple logic in which filter will only trigger if category exists and filter is true

    if (userId && filter) {
      const res = await axios.get(

        type: FILTER_DATA,
        payload: res.data
    } else {
      // Get the localStorage data, which stores the initial unfiltered data

      const savedData = JSON.parse(localStorage.getItem("data"));

        type: GET_DATA,
        payload: savedData

  const fetchData = async () => {
    const res = await axios.get("https://jsonplaceholder.typicode.com/posts");

    // Save the unfiltered data in localStorage in order to be able to get them again if filter is false

    localStorage.setItem("data", JSON.stringify(res.data));

      type: GET_DATA,
      payload: res.data

  return (
        data: state.data,
        currentCategory: state.currentCategory

export default DataState;


import types from "./types";

export default (state, action) => {
  switch (action.type) {
    case GET_DATA:
      return {
        data: action.payload

    case FILTER_DATA:
      return {
        data: action.payload

    case SET_CATEGORY:
      return {
        currentCategory: action.payload
      return state;

I leveraged localStorage in order to implement this feature (save initial unfiltered data in localStorage during fetch, and get the data from localStorage when the toggle is off).
This code just feels like it can be improved.

Here is the working codesandbox:

visas – Does the United States Department of State issue any US record clearance letter?

I am a French citizen, US permanent resident, California resident, and currently located in California, US. I am applying for a visa: the visa application requires a letter of verification stating that the applicant has no criminal record. In my case, the embassy of the country I am applying the visa for is telling me that they accept the following two options to obtain the US record clearance letter:

  1. From the FBI
  2. From the State Department (a.k.a. United States Department of State)

I know how to do it for the FBI, but I couldn’t find information on how to get such a letter directly from the United States Department of State.

javascript – Should abilities have their state and functionality separated?

I’m developing a top-down game using Javascript and Canvas in an ECS architecture.

I’m wondering, which of these is better from a design / elegance point of view?

Method 1: Combining the ability function and its metadata into one object:

// in ability factory
createBlinkAbility() {
  return {
    cooldown: 5000,
    castTime: 1000,
    hotkey: "q",
    execute(entity: Entity, scene: Scene) {
      let position = entity.get(CT.Position);

      let level = scene.queryComponent(CT.Level);

      position.x = Helpers.randomInt(0, level.width);
      position.y = Helpers.randomInt(0, level.height);

function executeCurrentCast(entity: Entity, ability: Ability) {
  ability.execute(entity); // all abilities have an execute function

Method 2: Separating ability metadata from its function:

// in ability factory
createBlinkAbility() {
  return {
    type: "blink",
    cooldown: 5000,
    castTime: 1000,
    hotkey: "q"

// in ability factory
castBlink = (entity: Entity, scene: Scene) => {
  let position = entity.get(CT.Position);

  let level = scene.queryComponent(CT.Level);

  position.x = Helpers.randomInt(0, level.width);
  position.y = Helpers.randomInt(0, level.height);

function executeCurrentCast(entity: Entity, ability: Ability) {
  switch (ability.type) {
    case "bow": this.abilityFactory.castBow(entity); break;
    case "blink": this.abilityFactory.castBlink(entity); break;

I know in general in an ECS architecture it is wise to separate “state” from “actions”, but I’m not sure if this would also apply to things like abilities. It seems like it might be wise to maintain that separation, but the code seems like it might be “cleaner”, or shorter at least, in the former case.

Lastly, I’m not really concerned with the performance differences between these two approaches, but rather which is better from a design standpoint.

design – How to avoid repeating same states in a finite state machine implementation?

I have been implementing a finite state machine which basically ensures configuration of the external chip which communicates with my MCU via I2C. The skeleton of the configuration state machine looks like this:

enter image description here

Whereas the Configure Register N states are state machines in their own.
It is pretty simple state diagram but there is one complication. The chip can asynchronously generate a “fault” event which is signalized via assertion of the “fault” pin. State of the fault pin is read with the same period with which the state machine is executed. Service of the fault pin activation is based on another state machine. So the basic state diagram incorporating the fault pin activation service looks like this:

enter image description here

At first glance there are several repeating patterns in the state diagram. At first the state diagram for the register configuration and secondly the state diagram for fault pin activation handling. I would
like to exploit these patterns and avoid of repeating the same code at several places. Can anybody suggest me any solution?

java – return the number of times is state of bulb changed?

Today in an exam I faced a problem which is Toggled Switches(Hacker Earth) as it is an exam question So, I am unable to send the question or its link (exactly).

Problem: we have to print a number representing the number of times do bulb changed its state. The bulb is attached to the “n” number of switches. So the bulb will be in the “on” state only when half or more than half of the given n of switches to be “on”.

1 represents on state

0 for off respectively.

There is also a query that will be given to represent which switch has to be toggled ( change from on to off or vice-versa 1 ->0 or 0->1). So, by toggling may or may not the bulb state change. so we have to return the number of times it changed its state.


1 – number of test case

3 – number of switches (n)

1 1 0 – initial all n switches states

3 – number of switches to be toggled

3 2 1 -> (3 represents third switch i.e as index wise second in switches array.) switches that have to be toggled.


1 – number of times the bulb changed its state

initial array or switches state (1, 1, 0) as half or more than half switches are in on. hence bulb is in on state.
as per queries (3,2,1)

we have to toggle the 3 rd switch. As initially third is in off (1,1,0) after toggling it changes to on (1,1,1) present switches state. as all are in on position bulb is on. ( no changes in the state of the bulb)

Now, have to toggle 2 nd switch so (1,1,1) changes to (1,0,1) switches states as half switches are on the bulb is on. ( no changes in the state of the bulb)

Now, 1 st switch to be toggled. Hence (1,0,1) changes to (0,0,1). as not equal or more than half switches are in on states hence bulb is going to be off. ( now bulb state is changed)

Hence the output is one.

I wrote the answer to this I am only able to solve the sample test case. No hidden test case is got the right answer and some got time exceeds error. so totally 0 marks.

I am a beginner so please explain vividly where I am wrong what is wrong? how it can be efficient ?.

and my code is

    import java.util.*;
    public class Main{
        static Scanner scan = new Scanner(System.in);
        public static void main(String() args) {
        int test_cases = scan.nextInt();
        //number of switches
        int n  = scan.nextInt();
        // contains on / off positions of switches
        int () switches = new int(n);
        for(int i =0;i<n;i++)
        //number of queries 
        int q = scan.nextInt();
        //  starts at 1 i.e queries(0)=1 but represents switch index 1(queries representing switch position and tha position starts from 1)
        int () queries  = new int(q);
        for(int i =0;i<q;i++)
        int result  = toggled(n,switches,q,queries);
    static int toggled(int n,int switches(),int q,int queries()){
        return q;
        int result =0;
        //giving switch state on or off
        boolean initial = on(switches);
        //System.out.println("initial is "+initial);
        //to represent on or off for all toggle including initial
        boolean () states = new boolean(q+1);
        states(0) = initial;
        int count  = 0;
        //to represent index of states
        int state_count =1;
            if((switches(queries(count)-1) & 1 )== 1)
            switches(queries(count)-1) = 0;
            switches(queries(count)-1) = 1;
       //System.out.println("state_count is "+state_count);
       for(int i =1;i<state_count;i++){
           if(initial ^ states(i) )
               initial = states(i);
       return result;
    //method to evaluate whether to consider on or off ( to on(bulb) have to on atleast half of the switches)
    static boolean on(int arr()){
        int sum = 0;
        for(int i =0;i<arr.length;i++)
            return true;
            return false;

legal – Can I ask my home EU State for a duplicate licence if it has been taken by another Member State?

My Polish licence has been taken and suspended by France (where I currently reside) for 4 months.

I no longer plan to live in France, and would like to drive in my home State as well as other Member States (and abroad). According to the administrative and judiciary documents I got from France, I am “banned from driving on French territory for a period of 4 months”. I was told that to drive again (anywhere), I must change my licence to a French one.

Since I no longer plan to live in France, am I indeed obliged to change it into a French one? Additionally (and/or if not), am I allowed to drive in other EU Member States by requesting a duplicate of my licence in my home Member State (the Member State that issued my driving licence in the first place)?

domain driven design – DDD loophole when one aggregate operation depends on state of another aggregate

I have found interesting problem in DDD, which can be solved extremely simply without DDD, but with DDD looks huge.

Let’s say I have:
Category – AR (AggregateRoot)
Product – AR

Category can have multiple products and also a featured product, like this:

public class Category : AggregateRoot {
   public List<Product> Products { get; set; }
   public Product FeaturedProduct { get; set; }

Product have Name, Description and IsActive flag:

public class Product : AggregateRoot {
   public string Name { get; set; }
   public string Description { get; set; }
   public bool IsActive { get; set; }

Now the business rules are:

  1. Can not Set Inactive product as featured.
  2. Can not Deactivate product when set as featured.

Proposed solutions (none of them is proper from DDD perspective):

Option 1) Put this business rules to Command Handlers, but it my opinion this would be code-smell. I believe such business rules should be part of Domain (not application layer, and command handlers are application layer).

Option 2) Create CategoriesProductsDomainService and put logic that touches these 2 AR there, e.g.:

public void DeactivateProduct(int productId) {
   // load product from products_repository
   // call categories_repository to check if any category has this product as featured
   // deactivate product


public void DeactivateProduct(Product product, List<Category> categories_with_product_as_featured) {
   if (categories_with_product_as_featured.Any(x => x.FeaturedProduct.Id == product.Id)) {
      // return or throw validation error

but such approach removes business logic from Aggregate and place it in additional DomainService. Not sure if this is proper approach.

Option 3) When Deactivating product, dispatch a ProductDeactivatedDomainEvent and handle it in same transaction, and event handler can throw an exception if the business rules is not met.

This approach however have 3 drawbacks:

  • I don’t think DomainEvent should be used to validate transaction that just happened
  • throwing exception for something that is just validation error is a design-smell
  • it is not unit testable without mocks (DomainEventsDispatcher is part of infrastructure)

Final thoughts

Looks like Option 2) is the most DDD friendly so far. Nevertheless I see a danger here, that a lot of logic will be removed from Aggregates with new business rules.

reactjs – Iam trying to update the state “Experience” but I didn’t get updated value. please correct if my code is wrong

am trying to calculate the year of experience so I Initialized state “Experience = 0” and I initialized the current year to the “currentDt” state

    this.state = {
        CurrentDt : new Date().getFullYear(),
        DOJ : 0,
        Experience : 0

Getting user input for “DOJ” state and updating using setstate()

    GetJoiningDt = (event) =>{
    const DojValue = event.target.value;
           DOJ :DojValue

Below code for subtracting currentYear and DOJ year then trying to update “Experience” state by subtracted value`

    calculateExperience = ()=>{
    let a = this.state.CurrentDt;
    let b = this.state.DOJ;
    var ExpValue = a - b;        //2021-2015
    alert(ExpValue);             // 6
        Experience : ExpValue     //0

when I alert the value of “ExpValue” it shows value 6 but Inside setstate() its updating 0.