8 – Missing form state values after adding submit function

I added a submit function in the form_alter hook when inserting a node:

$form('actions')('save_as_draft') = (
  '#type' => 'submit',
  '#value' => t('Save as Draft'),
  '#submit' => ('save_as_draft'),
  '#limit_validation_errors' => (),
);

In the save_as_draft() function, I want to get the address value from the form state, but there are no values (except for the additional submit button).

function save_as_draft(&$form, DrupalCoreFormFormStateInterface $form_state) {
  var_dump($form_state->getValue('field_address'));                      // outputs NULL
  var_dump($form_state->get('field_address'));                           // outputs NULL 
  var_dump($form('field_address')('widget')(0)('value')('#value'));      // outputs 'Address value'
  var_dump(array_keys($form_state->getValues())); // outputs { (0)=>  "save_as_draft" (1)=> "op" }
}

How can I get the form_state values in this alternative submit function without validating the whole form?

Is there another way of retrieving the form values instead of digging through the widget arrays?

c# – Supplying application state to a resuming Hangfire background job

If this is better suited for StackOverflow let me know and I’ll head over there… I think it belongs here though.

I’m writing an ASP.NET Core REST API that returns 201s and 202s after kicking off long running asynchronous jobs using Hangfire. If the jobs fail mid way Hangfire will pick things back up, run retries, etc. Obviously in order to do so, it needs to know some state.

Hangfire recommends that the arguments to background jobs remain “small and simple“, and that if a background job needs some more complicated object to write the ID to a database.

My background jobs need several API keys, passwords, some not so easy to serialize objects, and some YAML files loaded as config via an internal common configuration library. Because of the sensitivity of these data, I would rather not write them to the database. The options I see here are two:

  1. Pass each and every piece of the larger objects as arguments to the Hangfire job and let Hangfire serialize them to its DB. For sensitive arguments like API keys and passwords, first encrypt them using some cert bundled with the app. The background job will have to decrypt them using the same cert after fetching them from the database when it begins running.
  2. Set the objects to some public static property in a public static class at startup. The background job can just refer to that when it needs. For example:
// Startup code simplified for the sake of the example
{
    var envConfigs = new EnvironmentConfiguration( ... a bunch of random stuff ... );
    service.AddSingleton(envConfigs);
    EnvironmentConfiguration.Instance = envConfigs;
}


// Hangfire job

{    
    var result = BusinessLogicDoerMethod(EnvironmentConfiguration.Instance.BusinessLogicInformation);
}

Option 1 is annoying because we have to pass a lot of arguments, and also have to deal with the encrypt / decrypt logic.

Option 2 is probably fine, the danger I see here is if one background job mutates the EnvironmentConfiguration object, the other jobs and the rest of the app will also see that mutation. However, I can easily solve this problem by simply not doing that.

javascript – React js – Atualizar uma lista/array do componente Pai através do state do componente Filho

Boa noite, sou novo em React, venho da programação Java/C# e estou com bastante dificuldade em entender coisas que talves sejam simples em React js. Minha questão é o seguinte, preciso atualizar uma lista contida no meu componente pai Employee através do meu componente filho Form quando clico no botão salvar, no qual este executa a função save() atualizando o estado do filho. Esta mesma lista do pai irei usar no componente Table. Segue o código:

COMPONENTE PAI

import React from "react";
import Main from "../templates/Main";
import Form from "./Form";
import Table from "./Table";

const headerProps = {
  title: "Employés",
  subtitle:
    "Inscription des employés: Inclusion, Listage, Édition, Suppression",
};

const employeeProps = {
  employeesList: (
    {
      lastName: "Pierini",
      name: "Alex",
      birthday: "1985-08-28",
      title: "Programmeur",
    },
    {
      lastName: "Ferreira",
      name: "Pedro",
      birthday: "1988-05-07",
      title: "Vendeur",
    },
    {
      lastName: "Pelela",
      name: "Tiago",
      birthday: "1982-03-14",
      title: "Infographiste",
    },
  ),
};

export default class Employee extends React.Component {
  constructor(props) {
    super(props);
    this.state = { ...employeeProps };
  }

  addEmployee(employeesList) {
    console.log("Ajoutée");

    this.setState({ employeesList: employeesList });
  }

  editEmployee() {
    console.log("Modifier");
  }

  deleteEmployee() {
    console.log("Supprimer");
  }

  render() {
    return (
      <Main {...headerProps}>
        <Form {...employeeProps} callbackParent={(employeesList) => this.addEmployee(employeesList)} />
        <Table
          {...employeeProps}
          editEmployee={() => this.editEmployee()}
          deleteEmployee={() => this.deleteEmployee()}
        />
      </Main>
    );
  }
}

COMPONENTE FILHO

import React from "react";
import Button from "../Button";

const initialState = {
  employee: {
    lastName: "",
    name: "",
    birthday: "",
    title: "",
  },
};

export default class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = { ...initialState, ...props };
  }

  handleInputChange(event) {
    const employee = { ...this.state.employee };
    employee(event.target.name) = event.target.value;
    this.setState({ employee });
  }

  save() {          
    this.setState(
      function (state) {
        return {
          employeesList: (...state.employeesList, { ...state.employee }),
          employee: initialState.employee,
        };
      },
      (state) => this.props.callbackParent && this.props.callbackParent(state)
    );
  }

  clear() {
    this.setState({ employee: initialState.employee });
  }

  render() {    
    return (
      <div>
        <form>
          <label>Nom</label> <br />
          <input
            type="text"
            name="lastName"
            value={this.state.employee.lastName}
            onChange={(event) => this.handleInputChange(event)}
          />
          <br />
          <label>Prénom</label> <br />
          <input
            type="text"
            name="name"
            value={this.state.employee.name}
            onChange={(event) => this.handleInputChange(event)}
          />
          <br />
          <label>Date de Naissance</label> <br />
          <input
            type="date"
            name="birthday"
            value={this.state.employee.birthday}
            onChange={(event) => this.handleInputChange(event)}
          />
          <br />
          <label>Titre</label> <br />
          <select
            name="title"
            value={this.state.employee.title}
            onChange={(event) => this.handleInputChange(event)}
          >
            <option value="DEFAULT"></option>
            <option value="Infographiste">Infographiste</option>
            <option value="Programmeur">Programmeur</option>
            <option value="Vendeur">Vendeur</option>
          </select>
          <br />
        </form>
        <Button
          handleClick={() => this.save()}
          // handleClick={this.props.callbackParent({ ...this.state.employee })}
          label="Enregistrer"
        />
        <Button handleClick={() => this.clear()} label="Annuler" />
        <hr />
      </div>
    );
  }
}

performance – Game of Life state calculation in javascript

I’ve created a Life implementation in javascript with the goal to be as fast as possible, with the rendering I’m satisfied (see picture bellow), hovever the next state calculation is really slow and I’m out of ideas how to speed it up even more.

Rendering

Screenshot of the game
Screenshot of the game
I can get 700FPS+ when rendering a total population of 6,986,628

I achieved this by using regl for rendering and moving the calculation of the visible cells to a separate thread (spawned a web worker dedicated for this). I think this doesn’t need any optimization, maybe the way I calculate the visible cells.

The way I calculate visible cells

onmessage = function (e) {
    var visibleCells = ();
    for (const x of e.data.grid.keys()) {
        if (x < -(e.data.offsets.X+1)) continue; //Continue until reaches the visible part
        if (x > -e.data.offsets.X+e.data.width) break; //Stop after leaving visible part 
        for (const y of e.data.grid.get(x).keys()) {
            if (y < e.data.offsets.Y-1) continue;
            if (y > e.data.offsets.Y+e.data.height) break;
            visibleCells.push((x, y));
        }
    }
    this.postMessage({result: visibleCells})
}

Representing the “universe”

I had some ideas on how to represent the Life universe but I stick with the last option as it turned out to be the best performing. (Note that this implementation does not restrict the space so it is an infinite grid)

1.1 Using 2D array as cellState = grid(x)(y);

Since we are dealing with an infinite grid this can’t be used

1.2 Using 2D array as grid((x,y),(x1,x2),…)

Storing only the living cell’s coordinate. This has the problem of possible duplicates. Also I ran some tests on jsbench.me and turned out that this is slower than the 2nd way (the next one).

2. Using an object

Setting an object’s properties to create the illusion of a 2D array. This somewhat worked, but had the problem of the overhead created by converting int to string and via versa, because object indexing uses strings as keys

//Defining grid
var grid = {};

//Creating a cell at (x;y)
if (grid(x) == undefined) grid(x) = {};
    grid(x)(y) = null;
    
//Killing a cell at (x;y)
delete grid(x)(y);
if (Object.keys(grid(x)).length == 0) delete grid(x);

3. Using Maps and Sets (current)

This way I can use integers as indexes and don’t have to deal with the possibility of a duplicate cell

//Defining grid
var grid = new Map();

//Creating a cell at (x;y)
if (!grid.has(x)) grid.set(x, new Set());
grid.get(x).add(y);
    
//Killing a cell at (x;y)
grid.get(x).delete(y);
if (grid.get(x).size == 0) grid.delete(x);

This is why I’m writing this question. I don’t know how to further improve performance here.
The code for calculating the next state

onmessage = function (e) {
    var newGrid = new Map();
    var sketch = new Map();
    var start = performance.now();
    for (var x of e.data.grid.keys()) {
        var col1 = x - 1, col3 = x + 1;
        if (!sketch.has(col1)) sketch.set(col1, new Set());
        if (!sketch.has(x)) sketch.set(x, new Set());
        if (!sketch.has(col3)) sketch.set(col3, new Set());
        for (var y of e.data.grid.get(x).keys()) {
            var row1 = y - 1, row3 = y + 1;
            sketch.get(col1).add(row1);
            sketch.get(col1).add(y);
            sketch.get(col1).add(row3);
            sketch.get(x).add(row1);
            sketch.get(x).add(row3);
            sketch.get(col3).add(row1);
            sketch.get(col3).add(y);
            sketch.get(col3).add(row3);
        }
    }

    for (var x of sketch.keys()) {
        for (var y of sketch.get(x).keys()) {
            //Count neighbours
            var c = 0;
            var col1 = x - 1, col3 = x + 1;
            var row1 = y - 1, row3 = y + 1;
            if (e.data.grid.has(col1)) {
                //1st col
                var col = e.data.grid.get(col1);
                c += col.has(row1)
                c += col.has(y)
                c += col.has(row3)
            }
            if (e.data.grid.has(x)) {
                //2nd col
                var col = e.data.grid.get(x);
                c += col.has(row1)
                c += col.has(row3)
            }
            if (e.data.grid.has(col3)) {
                //3rd col
                var col = e.data.grid.get(col3);
                c += col.has(row1)
                c += col.has(y)
                c += col.has(row3)
            }


            if (c == 3) { //If a cell has 3 neighbours it will live
                if (!newGrid.has(x)) newGrid.set(x, new Set());
                newGrid.get(x).add(y);
                continue;
            }
            //but if it has 2 neigbours it can only survive not born, so check if cell was alive
            if (c == 2 && (e.data.grid.has(x) && e.data.grid.get(x).has(y))) {
                if (!newGrid.has(x)) newGrid.set(x, new Set());
                newGrid.get(x).add(y);
            }
        }
    }

    postMessage({ result: newGrid, timeDelta: performance.now() - start });
}

When the worker recives the initial grid it creates two new grids: sketch this grid will contain potentional new cells (as of writing this I just noticed that I don’t add (x;y) to this grid just the neighbouring ones and it still works, I will look into this deeper after I finish writing), and newGrid which will contain the final result. This way I only loop throug the cells that maybe change state.

Current performance

+------------------------+-----------+--------+------+
| Population             | 6,986,628 | 64,691 | 3    |
+------------------------+-----------+--------+------+
| Iteration time (ms/i)  | 23925     | 212    | 0.16 |
+------------------------+-----------+--------+------+
| FPS (all cell visible) | 900+      | 70     | 60   |
+------------------------+-----------+--------+------+

Before you ask I don’t know why the fps greater if more cells are rendered, but if you know please write it down in a comment

Attemts to optimize

Split work to CPUcores-2 workers

This was unusable, one iteration took minutes to compute on a ~700K population. I think because the object is copied to each worker so the overhead was much larger than using only one worker.

arizona – Can you travel on state highways through Navajo Nation land during the time of Covid restrictions?

Currently there is a curfew in the Navajo Nation due to the Covid-19 pandemic. In particular, from Saturday nights until Monday mornings in September there is a lockdown, and (I believe all the time right now) the Navajo Nation’s roads are closed to visitors. Does this mean that you can’t drive through the Navajo Nation on state highways traversing the reservation, such as 160? Does whether or not it is during the curfew make a difference? I’m not sure whether or not state highways count as Nation roads.

I’m not planning on stopping or leaving the state highway, I would just be traveling through.

usa – How can I find the fastest path by car to reach a US state from a given US location?

Stack Exchange Network


Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

javascript – Looking for feedback on a simple finite state machine for logging in with xstate

I have a sample React app that loads a username and password, and then randomly provides a login result on submission for the sake of example.

CodeSandbox: https://codesandbox.io/s/stack-xstate-login-review-brvuu

This state machine makes use of always to check and transition between states (e.g., when validating usernames, passwords, and the API data). I’m just not sure if this is the correct way to evaluate data given that the visualizer does not show the transition logic in a clear manner.

Visualizer: https://xstate.js.org/viz/?gist=b49d6fe8e8ab83a91ad5138ff6e71f29

Is there a better way to evaluate data than bootlegging the always conditionals (e.g., with actions perhaps?)?

And of course, if you have any other feedback about the construction of this state machine, I very much welcome your input!

Full state machine code:

import { Machine, assign } from "xstate";

const usernameStates = {
  initial: "idle",
  states: {
    idle: {},
    valid: {},
    invalid: {
      states: {
        empty: {}
      }
    },
    validating: {
      always: (
        // empty transition name auto-runs its actions on state entry
        { cond: "isUsernameEmpty", target: "invalid.empty" },
        { target: "valid" }
      )
    }
  }
};

const passwordStates = {
  initial: "idle",
  states: {
    idle: {},
    valid: {},
    invalid: {
      states: {
        empty: {}
      }
    },
    validating: {
      always: (
        // empty transition name auto-runs its actions on state entry
        { cond: "isPasswordEmpty", target: "invalid.empty" },
        { target: "valid" }
      )
    }
  }
};

export const LoginFormStateMachine = Machine(
  {
    id: "loginFormState",
    initial: "input",
    context: {
      values: {
        username: "",
        password: "",
        resultLogin: {}
      }
    },
    states: {
      input: {
        type: "parallel",
        on: {
          CHANGE: (
            {
              cond: "isUsername",
              actions: "cacheValue",
              target: "input.username.validating"
            },
            {
              cond: "isPassword",
              actions: "cacheValue",
              target: "input.password.validating"
            }
          ),
          CLEAR: { actions: "resetForm", target: "input" },
          SUBMIT: { target: "validatingUser" }
        },
        states: {
          username: { ...usernameStates },
          password: { ...passwordStates }
        }
      },

      validatingUser: {
        invoke: {
          src: (context) =>
            fetch(
              "https://fakerapi.it/api/v1/custom?random=boolean"
            ).then((res) => res.json()),
          onDone: {
            actions: "cacheLoginResult",
            target: "checking"
          },
          onError: { target: "error" }
        }
      },

      checking: {
        always: (
          { cond: "isRecordLegit", target: "success" },
          { cond: "isRecordNotLegit", target: "error.mismatchingRecord" }
        )
      },

      error: {
        states: {
          mismatchingRecord: { type: "final" }
        }
      },

      success: {
        type: "final"
      }
    }
  },
  {
    actions: {
      cacheValue: assign({
        values: (context, event) => ({
          ...context.values,
          (event.key): event.value
        })
      }),

      cacheLoginResult: assign({
        values: (context, event) => ({
          ...context.values,
          // this particular data structure is based on the result
          // of the fetch request on Line 82, go to that URL to
          // see how this function randomly provides a login result
          resultLogin: event.data.data(0).random
        })
      }),

      resetForm: assign({ values: (context) => ({}) })
    },

    guards: {
      isUsername: (context, event) => event.key === "username",
      isPassword: (context, event) => event.key === "password",

      isUsernameEmpty: (context) => context.values.username.length === 0,
      isPasswordEmpty: (context) => context.values.password.length === 0,

      isRecordLegit: (context, event) => context.values.resultLogin,
      isRecordNotLegit: (context, event) => !context.values.resultLogin
    }
  }
);

```

usability – How to decide which state is on and which is off in a checkbox

There’s a program that draws various types of horizontal lines that anchor to other horizontal objects that are usually a little bit tilted.

Some of the lines, by default, are completely horizontal, meaning they have no slope, even though the objects they are anchored to do. Some other lines, by default, get the same slope of the objects they are anchored to.

Although these are the defaults, it’s useful to override them in both cases. What would be better, to have a checkbox in the line properties saying “Allow diagonal”, or to have a checkbox saying “Force horizontal”? Why?

c# – Using Task.Run for a keep alive method / check connection state

An idea popped into my head the other day while considering a method to check the connection state of a device.

Typically I run a timer that fires every x seconds to ping the device get the connection state.

My thought was to just use Task.Run and let it keep firing without the need to set up a timer.

Something like:

using System.Net.NetworkInformation;
using System.Threading;

private Ping ping = new Ping();
private PingReply reply;

        void async Startup()
        {
            await Task.Run (() => GetConnectionState("192.168.1.1"));

        void GetConnectionState(string ipAddress)
        {
            Thread.Sleep(12000);
            reply = ping.Send(ipAddress);
            if (reply.Status == IPStatus.Success)
            {
                IsConnected = true;
            }
        }     

TIA for your thoughts.
Norm

reactjs – React Hooks Redux no puedo obtener el state correctamente

Estoy realizando una pequeña aplicación CRUD con react redux, una api nodejs, base mongodb.
tengo un problema al editar un ítem o mejor dicho al obtener dicho ítem para poder editarlo (aclaro la aplicación funciona obtener todos los ítems, eliminar un ítem e insertar un ítem). tengo el siguiente código:

EditarItem.js

...

const EditarItem = (props) => {     
   const dispatch = useDispatch();
   
    useEffect(()=>{
        const {id} = props.match.params;
        dispatch(mostrarItem(id));      
    },());

    const {item} = useSelector(state => state.items);
    
    const (values, setValues) = useState(item);

    const {nombre,propietario,_id} = values;
    

    const handleChangeForm = event => {
        setValues({ ...values, (event.target.name): event.target.value });
    };
...

Primero en “useEffect” llamo a la acción para obtener un solo ítem mediante su “id”.
después en “useSelector” obtengo el state (que puso el reducer <- mas abajo),
después ese ítem se lo asigno al useState para obtener cambiar los valores.
después le hago destructuring al arreglo y esos valores se los pongo “default” en los input
por ultimo la función para guardar los cambios en el arreglo.

Actions

...
export const mostrarItem = id => async dispatch=>{
    const respuesta = await axios.get(`${urlDB}/${id}`);
    dispatch({
        type:MOSTRAR_ITEM,
        payload:respuesta.data
    })
}
...

Reducer

...
const initialState = {
    items:(),
    item:()
}

export default function(state=initialState, action){
    switch (action.type) {
          case MOSTRAR_ITEM:        
        return{
            ...state,
            item: action.payload
        }               
        default:
            return state;
    }

...

En esta parte del reducer he visto que usan un solo state “items:()” yo le agregue “item:()” y es lo mas parecido a funcionar.

Cual es el problema ? me devuelve el “state” anterior es decir; doy click en “editar” al item 1 la primera vez que lo ejecuto me devuelve vacios todos los campos, regreso y le doy al item 2 y me devuelve los datos del item 1 y si regreso y le doy al item 3 me devuelve lo datos del item 2 y asi… siempre me devuelve el state anterior, supongo que el problema esta en el dispatch o en el useSelector pero no se jajaj

espero me puedan ayudar, de antemano gracias saludos