reactjs – ES LINT Warning:- Function declared in a loop contains unsafe references to variable(s) ‘randomColor’, how do I remove this warning?

    //pick random color from existing palettes
    const allColors = this.props.palettes.map(p => p.colors).flat();
    let rand;
    let randomColor = "";
    let isDuplicateColor = true;
    while (isDuplicateColor) {
      rand = Math.floor(Math.random() * allColors.length);
      randomColor = allColors(rand);
      isDuplicateColor = this.state.colors.some(
        color => color.name === randomColor.name
      );
    }
    this.setState({ colors: (...this.state.colors, randomColor) });
  }

this part of the code is giving me the warning “Function declared in a loop contains unsafe references to variable(s) ‘randomColor'” which I have to resolve inorder to deploy

programming practices – When should a method depend on a data source and NOT have it declared as a parameter?

I was assigned a code review to one of my colleagues.
I posed the following, which I wanted to share here in order to hear whether I am right or wrong.

Consider the following code snippet:

public void DoSomethingWithList()
{
   var list = AnotherClass.GetList();
   var itemsToRemove = list.Where(...);
   list.Remove(itemsToRemove);
   .
   .
   .
}

I argue that the method above should have list declared as a dependency (in other words, declared as a parameter in the method’s signature). Why ? To follow the Single Responsibility principle, and/or for testing purposes. (I think this is the case for an external class call, but even if GetList was a private method inside the same class, I would still claim the same – even if the sole motif would be code clarity (call it “purpose clarity“).

My colleague says this is not so. Having to call this function every time always passing the same parameter is cumbersome.

I obviously understand that as a developer, but I insisted that the “software engineering principles aimed at code maintainability” should prevail over “developer laziness” (myself included !)

I do understand there are no bulletproof rules, but nevertheless that they
should only be broken for a very good reason.

I wonder whether I am wrong. And if am I not, which other aspects I did not mention should have been.

oracle 12c – PLS-00302: component ‘START_LOADING_JAR’ must be declared while running loadjava

I have to load a fatjar into an Oracle 19c database. I have to use a static method of a class of this jar in a database trigger or function. Some older schemas are from the time we would run Oracle 12c, and I should use an old schema for testing. I don’t know if that’s relevant informatoin.

I run following command:

./loadjava -prependjarnames -schema MY_SCHEMA -user MYUSER/MYUSER@hostname:port/SID -jarsasdbobjects /home/myuser/myfatjar.jar

I get following error:

Error while creating jar MY_SCHEMA.ROOT/home/myuser/myfatjar.jar
    ORA-06550: Zeile 1, Spalte 89:
PLS-00302: component 'START_LOADING_JAR' must be declared
ORA-06550: Zeile 1, Spalte 72:
PL/SQL: Statement ignored

Error while creating jar MY_SCHEMA.ROOT/home/myuser/myfatjar.jar
    ORA-06550: Zeile 1, Spalte 25:
PLS-00302:component 'START_LOADING_JAR' must be declared
ORA-06550: Zeile 1, Spalte 8:
PL/SQL: Statement ignored

The following operations failed
    jar MY_SCHEMA.ROOT/home/myuser/myfatjar.jar: creation (createFailed)
exiting  : Failures occurred during processing

When I run the command with -verbose:

./loadjava -verbose -prependjarnames -schema MY_SCHEMA -user MYUSER/MYUSER@hostname:port/SID -jarsasdbobjects /home/myuser/myfatjar.jar

I just get a huge list with errors:

identical: org/springframework/cache/jcache/interceptor/CacheRemoveOperation
identical: org/springframework/cache/jcache/interceptor/CacheResolverAdapter
identical: org/springframework/cache/jcache/interceptor/DefaultCacheKeyInvocationContext
identical: org/springframework/cache/jcache/interceptor/JCacheAspectSupport$CacheOperationInvokerAdapter
identical: org/springframework/cache/jcache/interceptor/JCacheOperation
identical: org/springframework/cache/jcache/interceptor/CachePutInterceptor

The jar uses Spring, IBM ICU Library (which I also so in the huge list) and testng.

Unfortunetaly I can’t wrap my head around this error and have no clue what the reason could be.

Please note that I had to modify the commands to hide projekt internals. Im unshure if the MY_SCHEMA.ROOT... in MY_SCHEMA.ROOT/home/myuser/myfatjar.jarreally the schema is.

javascript – When should a variable be declared?

I hope this is the right place for asking this type of question. If not please direct me to the right place.

So we have quiet a big TypeScript codebase at work, where each method resides in its own file. Now in a lot of those methods the variables are often declared all together at the top/beginnng of the method.

I was discussing with some principal developers that it would be better to declare them only when they’re really needed. Because in some cases those variables are used only if some conditions are met. So my point is to avoid executing a bunch of methods to set those variables when they’re eventually not needed at all.

Here an example to illustrate my point, keep in mind that this is a very simple example and in some cases we have multiple conditions and more variables.:

Simplified method how it currently is:

namespace some.namespace {

  export async function FunctionName (Toolbar : example.Toolbar) : Promise<void> {

    const Form         : example.Form       = Toolbar.window.getForm("example");
    const WindowCaller : example.Window     = (Toolbar.window.caller as example.Window);
    const DSO          : example.DataSource = WindowCaller.getDataSource("example");
    const ElementID    : number             = DSO.getCurrentRecord()("example");
    const DynSelect    : example.DynSelect  = Form.getDynSelect("example");
    
    const ExampleEnum      : typeof example.ExampleEnum      = example.ExampleEnum;  
    const OtherExampleEnum : typeof example.OtherExampleEnum = example.OtherExampleEnum;     
    
    if (!Form.validate()) return;

    const Parameter : any = {
      prop_one : ElementID,
      prop_two : DynSelect.value
    };
  
    const Response = await SomeServerCall(Parameter);

    Form.window.close();

    if (Response.someBoolean) {
      DisplayMessage(ExampleEnum.SOMETHING, OtherExampleEnum.SOMETHING );
    }
  };
}

In the example above a bunch of variables are defined and not used before if (!Form.validate()) return; which could stop the execution of the method there. Also the enums are used only in the last if statement.

So what I suggested was to write our code like this, where we declare our variables only when they’re actually needed:

My suggestion

namespace some.namespace {

  export async function FunctionName (Toolbar : example.Toolbar) : Promise<void> {

    const Form : example.Form = Toolbar.window.getForm("example");   
    
    if (!Form.validate()) return;

    const WindowCaller : example.Window     = (Toolbar.window.caller as example.Window);
    const DSO          : example.DataSource = WindowCaller.getDataSource("example");
    const ElementID    : number             = DSO.getCurrentRecord()("example");
    const DynSelect    : example.DynSelect  = Form.getDynSelect("example");

    const Parameter : any = {
      prop_one : ElementID,
      prop_two : DynSelect.value
    };
  
    const Response = await SomeServerCall(Parameter);

    Form.window.close();

    if (Response.someBoolean) {
      const ExampleEnum      : typeof example.ExampleEnum      = example.ExampleEnum;  
      const OtherExampleEnum : typeof example.OtherExampleEnum = example.OtherExampleEnum;  
      DisplayMessage(ExampleEnum.SOMETHING, OtherExampleEnum.SOMETHING );
    }
      
  };
}

Some arguments of the PD’s were that the code is less readable like this and if we want to do this we need to add some scopes, for example with an else after the first if. But I don’t really see the difference regarding the overall concept of defining variables only if they’re needed.


Wouldn’t my sggestion be better for performance, memory etc.? Especially when taking into account that some of those early called methods could also be async. Also calling fewer methods means fewer risks that something goes wrong in one of those methods (even if it shouldn’t). Also regarding the readability I prefer to see the definitions where they’re needed.

So what do you guys think? Am I splitting hairs here?

osr – Can a translation of a text declared as OGC be declared as Product Identity?

When translating something, you become the author of a derivate of a work, but not the sole author. As you are not the sole author, the joint copyright in the derivate rests within the original author and you – but you are still bound by the OGL.

However, you only got the license to make your derivate by the OGL 1.0a. The OGL says, that all derivate work, especially translations, need to be under OGL license in paragraph 2. Since your translation is a derivate work, not a free-standing work or your own product identity, you need to release your translation under OGL license. Your translation is OGC, and you can’t make it Product Identity yourself, and in fact, you may not even use any Product identity in your translation! To use the Product Identity of someone, you need to license that material differently – and any and all names and characters automatically are in this category. So you can’t just translate someone’s adventure.

Everything else you have to release under OGL. If it was OGC, it has to stay OGC. If it was Product Identity, you can’t touch it without a separate license. The only person that can re-declare something Product Identity would be the original author, but they had chosen OGC instead. You can’t change that.

The relevant parts of the OGL 1.0a are (emphasis mine):

  1. Definitions:

(a)”Contributors” means the copyright and/or trademark owners who have contributed Open Game Content;

(b)”Derivative Material” means copyrighted material including derivative works and translations (including into other computer languages), potation, modification, correction, addition, extension, upgrade, improvement, compilation, abridgment or other form in which an existing work may be recast, transformed or adapted;

(c) “Distribute” means to reproduce, license, rent, lease, sell, broadcast, publicly display, transmit or otherwise distribute;

(d)”Open Game Content” means the game mechanic and includes the methods, procedures, processes and routines to the extent such content does not embody the Product Identity and is an enhancement over the prior art and any additional content clearly identified as Open Game Content by the Contributor, and means any work covered by this License, including translations and derivative works under copyright law, but specifically excludes Product Identity.

(e) “Product Identity” means product and product line names, logos and identifying marks including trade dress; artifacts; creatures characters; stories, storylines, plots, thematic elements, dialogue, incidents, language, artwork, symbols, designs, depictions, likenesses, formats, poses, concepts, themes and graphic, photographic and other visual or audio representations; names and descriptions of characters, spells, enchantments, personalities, teams, personas, likenesses and special abilities; places, locations, environments, creatures, equipment, magical or supernatural abilities or effects, logos, symbols, or graphic designs; and any other trademark or registered trademark clearly identified as Product identity by the owner of the Product Identity, and which specifically excludes the Open Game Content;

(f) “Trademark” means the logos, names, mark, sign, motto, designs that are used by a Contributor to identify itself or its products or the associated products contributed to the Open Game License by the Contributor

(g) “Use”, “Used” or “Using” means to use, Distribute, copy, edit, format, modify, translate and otherwise create Derivative Material of Open Game Content.

  1. The License:

This License applies to any Open Game Content that contains a notice indicating that the Open Game Content may only be Used under and in terms of this License. You must affix such a notice to any Open Game Content that you Use. No terms may be added to or subtracted from this License except as described by the License itself. No other terms or conditions may be applied to any Open Game Content distributed using this License.

  1. Use of Product Identity:

You agree not to Use any Product Identity, including as an indication as to compatibility, except as expressly licensed in another, independent Agreement with the owner of each element of that Product Identity.

osr – Can I copy verbatim text of a game declared as Open Game Content under the OGL License?

I am not a lawyer, I am certainly not your lawyer, and I have not examined the details of your specific case. This answer is meant to be educational, based on my understanding as someone who has worked under the OGL (but not as someone who has been responsible for ensuring the OGL compliance of our work). Especially if your motivation is primarily profit, you may wish to speak with a lawyer before pursuing this, as otherwise you will be assuming the risks associated with your actions (e.g. in the event that I am wrong about anything).

That out of the way, here’s my understanding:

You can copy the full text of Open Game Content, verbatim, freely or for profit. This much I am pretty confident in—there are a lot of copies of Open Game Content out there that are not associated with the original copyright holder. E.g. d20pfsrd.com hosts Open Game Content from Pathfinder by Paizo, but is unaffiliated with Paizo. There has even, at times, been some tensions between the two, but Paizo hasn’t claimed that d20pfsrd.com is not allowed to host the Open Game Content that it does. And Pathfinder 1e itself is based on Open Game Content from Wizards of the Coast, and despite Pathfinder being the primary competition for D&D, Wizards hasn’t sued Paizo over selling Pathfinder. So copying the full, verbatim text of Open Game Content should be no problem, nor should selling it.

However, I believe you are limited in that any “derivative work” you create from Open Game Content will also be Open Game Content. That means anyone can take what you make and upload it on a website for free, even if you would prefer people buy it from you, potentially limiting your sales.

(Realistically, with piracy being as prevalent as it is, anyone choosing to pay you for your work is basically volunteering to do so regardless. Even if your work is entirely original and cannot be copied or distributed legally by anyone, it still will be. So it might not make that much difference.)

The exceptions here are Product Identity, which can cover a fair few things—characters, spells, items, and similar elements can be declared Product Identity and then would have to be left out of any legal copy of your work. Artwork and other graphical elements are likewise usually Product Identity, so people couldn’t legally just put your entire PDF up online, even if all of the text is Open Game Content.

Luckily for you, Product Identity can include “trade dress,” which I believe would include the design of your cards. Therefore it’s unlikely that anyone could directly copy your work here—and may mean your product will have value in the marketplace.

javascript – Mapping values. Should a single use variable be declared as a variable at all?

Where I have, let us say an object, that I will only use once, what is considered general best practice in terms of declaring it as var vs. simply putting the object directly into the method it will be used in? I’m thinking this is going to come down to “which do you think is more readable”, but given my lack of experience thought I’d see if there was a consensus.

This came about when looking at the following code:

      var aiPersonalities = model.aiPersonalities();

      var newPersonalities = {
        qCasual: {
          ai_path: "/pa/q_casual",
          display_name: "!LOC:Q-Casual",
          metal_drain_check: 0.64,
          energy_drain_check: 0.77,
          metal_demand_check: 0.95,
          energy_demand_check: 0.92,
          micro_type: 0,
          go_for_the_kill: false,
          priority_scout_metal_spots: true,
          enable_commander_danger_responses: false,
          neural_data_mod: 2,
          adv_eco_mod: 0.5,
          adv_eco_mod_alone: 0,
          factory_build_delay_min: 0,
          factory_build_delay_max: 12,
          per_expansion_delay: 60,
          personality_tags: ("queller"),
          min_basic_fabbers: 10,
          min_advanced_fabbers: 3,
        },
        // imagine another 11 objects of the same size here
      };

      var baseline = aiPersonalities.Absurd;

      newPersonalities = _.mapValues(
        newPersonalities,
        function (personality, name) {
          var result = _.assign(_.clone(baseline), personality);
          result.name = name;
          return result;
        }
      );

      _.assign(aiPersonalities, newPersonalities);

      model.aiPersonalities.valueHasMutated();

This could be written in a way which removes aiPersonalities, baseline, and avoids newPersonalities referencing itself:

      var newPersonalities = _.mapValues(
        {
          qCasual: {
            ai_path: "/pa/q_casual",
            display_name: "!LOC:Q-Casual",
            metal_drain_check: 0.64,
            energy_drain_check: 0.77,
            metal_demand_check: 0.95,
            energy_demand_check: 0.92,
            micro_type: 0,
            go_for_the_kill: false,
            priority_scout_metal_spots: true,
            enable_commander_danger_responses: false,
            neural_data_mod: 2,
            adv_eco_mod: 0.5,
            adv_eco_mod_alone: 0,
            factory_build_delay_min: 0,
            factory_build_delay_max: 12,
            per_expansion_delay: 60,
            personality_tags: ("queller"),
            min_basic_fabbers: 10,
            min_advanced_fabbers: 3,
          },
        // imagine another 11 objects of the same size here
        },
        function (personality, name) {
          var result = _.assign(
            _.clone(model.aiPersonalities().Absurd),
            personality
          );
          result.name = name;
          return result;
        }
      );

      _.assign(model.aiPersonalities(), newPersonalities);

      model.aiPersonalities.valueHasMutated();

I’m just interested in how people would approach this. My instinct is that aiPersonalities and baseline could be ditched, per approach 2, but that keeping the initial declaration of the newPersonalities object may make it easier to see what the _.mapValues bit is doing.

There aren’t any style guidelines or anything, this is a purely me project.

java – Optional int parameter ‘id’ is present but cannot be translated into a null value due to being declared as a primitive type

me encuentro con un error que no sé por donde cogerlo. Estoy realizando un api/rest de android studio (RetroFit) con SpringBoot (como servidor).
Resulta que me encuentro con este error:

 Optional int parameter 'id' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.

Expongo retrofit interface:

 @PUT("editPlayer{id}")
    Call<PlayerDto> editPlayer(@Body PlayerDto player, @Path("id") int id);

Expongo llamada al servidor:

Settings.RESPONSE_CLIENT.getService()
.editPlayer(editedPlayer, 53)
.enqueue(new Callback<PlayerDto>() {
   @Override
   public void onResponse(Call<PlayerDto> call, Response<PlayerDto> response) {
      editedPlayer = response.body();
      typeError = 0;
   }

   @Override
   public void onFailure(Call<PlayerDto> call, Throwable t) {
      Log.e("Error: ", t.getMessage());
      typeError = 2;
   }
});

Expongo servidor Controller:

@PutMapping("/editPlayer{id}")
    public Player editPlayer(@RequestBody Player player, @Param("id") int id) {
        return service.editPlayer(player.getUsername(), id);
    }

Expongo servidor PlayerService:

public Player editPlayer(String username, int id) {

        repoPlayer.editUserNamePlayer(username, id);
        Optional<Player> player = repoPlayer.findById(id);

        return player.get();
    }

Expongo IPlayerRepository, aunque solo es la “Query” :

@Modifying
    @Query("UPDATE Player p SET p.username= :username WHERE p.id= :id")
    public void editUserNamePlayer(@Param("username")String username, @Param("id") Integer id);

Realizo pruebas con Insomnia y no tengo ningún problema adjunto imagen:
imagen de captura test insomnia put api/rest

Pero no tengo manera de enviar la id desde android studio, parece que se le envia “null”.
Ni ingresandolo a mano ni recogiendolo por parámetro.

Necesito ayuda, muchas gracias de antemano.

c++ – warning: ‘struct task_struct’ “Declared inside parameter list will not be visible outside of this definition or declaration”

I have the following piece of code:

File sched.h

   #include <stats.h>
   truct task_struct {
       ...
       struct stats stat;
   };

File stats.h*

   #include <sched.h>
   struct stats
   {
   ...
   };

   void initStats (struct task_struct* tsk);

When I try to compile it gives me the following warning

warning: ‘struct task_struct’ declared inside parameter list will not be visible outside of this definition or declaration
17 | void initStats (struct task_struct* tsk);

I have seen similar questions posted, but I have not been able to fix the problem. I was wondering if the problem was because both files include each other. Any help would be appreciated : ).

air travel – Do disposable contact lenses need to be declared as “liquids”?

(this should be a comment, but i don’t have enough reputation, sorry about that)

Also be aware that some companies, like Ryanair don’t allow you to take contact lenses in your checked baggage:

You must not include in Checked Baggage money, jewellery, precious metals, keys, cameras, computers, medicines, spectacles, sunglasses, contact lenses, watches, mobile phones, personal electronic devices, negotiable papers, securities, cigarettes, tobacco or tobacco products or other valuables, business documents, passports and other identification documents or samples.