Should my classes have separate constructors just for unit testing?

I like to write classes with two constructors: a primary constructor used in production code, and a default constructor just for unit tests. I do this because the the primary constructor creates other concrete dependencies that consume external resources. I can’t do all that in a unit test.

So my classes look like this:

public class DoesSomething : BaseClass {     private Foo _thingINeed;     private Bar _otherThingINeed;     private ExternalResource _another;      public DoesSomething()     {         // Empty constructor for unit tests     }      public DoesSomething(string someUrl, string someThingElse, string blarg)     {          _thingINeed = new Foo(someUrl);          _otherThingINeed = Foo.CreateBar(blarg);          _another = BlargFactory.MakeBlarg(_thingINeed, _otherThingINeed.GetConfigurationValue("important");     } } 

The comment inside the default constructor is real. I started putting that there after someone asked what it was for. I think they already knew what it was for and they were just messing with me.

You’re probably wondering how it’s possible to create and test an instance of the class if it has other dependencies that it needs in production, but my default constructor doesn’t create them.

I mostly work around that by making most of my methods public. The method called from production code calls other public methods, most of which don’t use all of those dependencies. They communicate with each other by storing their results in fields. One method stores its results in a field, and the next method reads them. To make sure all the methods get called in order I call them all from the base class.

That way I can write tests for all those methods separately. I can’t test everything, but this gets me most of the way. We have high standards which include 85% unit test coverage. (“Real” constructors are excluded from code coverage since they can’t be tested.)

Anyway, my question really isn’t about that. I just want to know if it’s a good idea to have a separate constructor for unit tests. I think it’s a great pattern. In fact, I require other developers to copy and paste my classes and use them as a template.

What is the practical limit to how many object classes you can detect with Faster RCNN?

I am trying to follow this tutorial where the Faster-RCNN-Inception-V2-COCO model from TensorFlow’s model zoo is used to detect playing cards. I was wondering what is the practical limit to the number of object classes that I could use this to detect, specifically what I would want to do is to detect every letter in the English language(distinguish capital and lowercase from each other), number and mathematical symbol. Would this model work with that many different classes?

Also If I want to detect some words, would it make sense to label all characters that make up a word and also label the word(assuming there are only a few important words I want to actually detect).

How can I wrap other model classes in one class neatly?

I made a wrapper, and recently I’ve reflected about what is a poor design decision in my opinion, however, I’m not sure what would be the better alternative.

Currently, my wrapper works like this (names changed):

    import wrapper     api = wrapper.Api(params...)     # fetch fetches data from the API     objects = wrapper.model.fetch(api, params...)     # get_special might be only relevant to a certain object type     other_objects = wrapper.other_model.get_special(api, params...) 

Obviously, passing the API as a parameter isn’t very oop-y, and regardless it just looks bad. I considered just putting all of those classes in the API class, but I don’t think that’s a good idea, either. What would be a better design choice?

Thanks in advance 😀

Restructuring PHP application classes

I’m trying to modernize a very old PHP application for a customer to keep its code base up with modern coding standards. I am permitted to restructure things a bit, but dumping the entire app and switching to an existing framework is not yet an option. I just need some general tips on how best to restructure the application classes.

Right now, the parent script calls the base application, which extends the database class. Smarty is being used as the template rendering engine, but it is not integrated with the base application. The parent script calls on Smarty separately. This customer’s app includes a lot of complicated processes that are often coded repeatedly throughout various parent scripts, but really need to be in their own custom classes as part of the app structure.

The whole thing seems backwards from how I understand PHP applications to be coded today. What would be effective way of restructuring the classes neatly, keeping the app extendable and a bit more “DRY”?

enter image description here

Como comparar dois valores de duas classes diferentes no django

Olá, sou novo no django e tenho o seguinte problema, tenho duas classes no django uma delas é :

class Apps(models.Model): id = models.UUIDField(db_column='ID', primary_key=True)  # Field name made lowercase. name = models.CharField(db_column='Name', max_length=255)  # Field name made lowercase. appid = models.CharField(db_column='AppId', max_length=500, blank=True, null=True)  # Field name made lowercase. publishtime = models.DateTimeField(db_column='PublishTime')  # Field name made lowercase. published = models.BooleanField(db_column='Published')  # Field name made   class Meta:     managed = False     db_table = 'Apps' 

E a outra é essa :

class Executionresults(models.Model): id = models.UUIDField(db_column='ID', primary_key=True)  # Field name made lowercase. taskid = models.UUIDField(db_column='TaskID')  # Field name made lowercase. executionid = models.UUIDField(db_column='ExecutionID')  # Field name made lowercase. appid = models.UUIDField(db_column='AppID')  # Field name made lowercase. executingnodeid = models.UUIDField(db_column='ExecutingNodeID')  # Field name made lowercase. status = models.IntegerField(db_column='Status')  # Field name made 

Gostaria de saber como comparar dois valores, se o “appid” da tabela “Apps” for igual ao “appid” da tabela “Executionresults” ele tem que me retornar o “name” da tabela “Apps”.

Tentei fazer isso no direto no index.html, porem sem sucesso.

                  <table class="table table-striped up">                         <thead>                             <tr>                                 <th scope="col">#</th>                                 <th scope="col">Task ID</th>                                 <th scope="col">Inicio</th>                                 <th scope="col">Fim</th>                                 <th scope="col">Nome App</th>                                 <th scope="col">status</th>                              </tr>                         </thead>                         <tbody>                              {% for exe in executionresults %}                             {% for app in apps %}                             <tr>                                 <th scope="row"></th>                                 <td>{{ exe.taskid }}</td>                                 <td>{{ exe.starttime }}</td>                                 <td>{{ exe.stoptime }}</td>                                  {% if exe.appid == app.targetappid %}                                     <td>{{ return app.name }}</td>                                 {%endif%}                                   {% if exe.status == 1 %}                                     <td style="text-align: center;"class="alert alert-danger" role="alert">Desencadeado <i class="fa fa-check" style="font-size:16px"></i></td>                                  {%elif exe.status == 2 %}                                 <td style="text-align: center;"class="alert alert-success" role="alert">Iniciado <i class="fa fa-check" style="font-size:16px"></i></td>                                  {%elif exe.status == 3 %}                                 <td style="text-align: center;"class="alert alert-success" role="alert">Na fila <i class="fa fa-check" style="font-size:16px"></i></td>                                  {%elif exe.status == 4 %}                                 <td style="text-align: center; "class="alert alert-warning" role="alert">Abortar iniciado <i class="fa fa-exclamation" style="font-size:20px"></i></td>                                  {%elif exe.status == 5 %}                                 <td style="text-align: center; "class="alert alert-warning" role="alert">Abortando <i class="fa fa-exclamation" style="font-size:20px"></i></td>                                  {%elif exe.status == 6 %}                                 <td style="text-align: center;"class="alert alert-danger" role="alert">Abortado <i class="  fa fa-close" style="font-size:20px"></i></td>                                  {% elif exe.status == 7 %}                                   <td style="text-align: center;"class="alert alert-success" role="alert">Finalizado com sucesso  <i class="fa fa-check" style="font-size:16px"></i></td>                                  {%elif exe.status == 8 %}                                 <td style="text-align: center;"class="alert alert-danger" role="alert">Falha! <i class="    fa fa-close" style="font-size:20px"></i></td>                                  {%elif exe.status == 9 %}                                 <td style="text-align: center; "class="alert alert-warning" role="alert">Pulou <i class="fa fa fa-exclamation" style="font-size:20px"></i></td>                                  {%elif exe.status == 10 %}                                 <td style="text-align: center;"class="alert alert-danger" role="alert">Tente novamente <i class="fa fa-close" style="font-size:20px"></i></td>                                  {%elif exe.status == 11 %}                                 <td style="text-align: center;"class="alert alert-danger" role="alert">Erro! <i class="     fa fa-close" style="font-size:20px"></i></td>                                  {%elif exe.status == 12 %}                                 <td style="text-align: center;"class="alert alert-danger" role="alert">Restabelecer <i class="  fa fa-close" style="font-size:20px"></i></td>                                  {%else%}                                 <td>{{ exe.status }}</td>                                 {%endif%}                                    </tr>                             {% endfor %}                             {% endfor %}                         </tbody>                     </table> 

Meu objetivo final é trazer as tasks da tabela Executionresults, porem nessa tabela não mostra o nome do app, e eu preciso mostrar para o usuário, portanto preciso fazer essa união de tabelas.

What are the official, WotC-published classes and subclasses in 5e?

There aren’t too many published materials that contain official classes (classes here meaning sub-classes and archetypes included) but they are scattered resources.

What are the official, 1st-party, WotC-published classes and which resources are they found in?

For the purposes of this question “unofficial”, playtest material such as Unearthed Arcana is excluded and will be asked as a separate question.


Related questions:

  • What are the playable D&D races in 5e?
  • Where do I find the "official" rules for D&D 5e?
  • Is it necessary to purchase all the D&D 5th books to have access to all character classes etc.? (even though the answer to this linked question just happens to more-or-less answer this question, they are different questions)

and meta discussion and approval for this question here.

Python/Django Classes Autogeneration

1. Django Project Structure:

djangoproject

djangoproject     ...     schema.py app1     ...     schema.py     models.py app2     ...     schema.py     models.py app3     ...     schema.py     models.py appN     ...     schema.py     models.py 

2. Each application models.py module:

class ModelA(model.Models):     # model's definition  class ModelB(model.Models):     # model's definition      ...  class ModelN(model.Models):     # model's definition 

Each application also has a schema.py module containing classes which use models in their Meta’ classes:

3. Application’s schema.py module:

# app1 Schema module  class ClassA_Type(ParentTypeClass):     class Meta:         model = ModelA   class ClassN_Type(ParentTypeClass):     class Meta:         model = ModelN   class Query(ParentQuery):     modelA_single = QueryFieldCreator(ClassA_Type)     modelA_plural = QueryListCreator(ClassA_Type)      modelN_single = QueryFieldCreator(ClassN_Type)     modelN_plural = QueryListCreator(ClassN_Type)      def resolve_modelA_single(self, *args, **kwargs):         return SomeQuerySetSingle(*args, **kwargs)      def resolve_modelA_plural(self, *args, **kwargs):         return SomeQuerySetPlural(*args, **kwargs) 

4. Schemas collecting

All schema.py modules of applications are collected within djangoproject/schema.py module as arguments of Query class.

5. Schemas Interconnection

Thereby for each application interconnection between elements looks like this:

enter image description here

enter image description here

Problem:

There are a lot of applications and models in them within this Django project. And sometimes new models or even apps can be created.

The problem is to organize creation of application’s Query classes with all internals (Meta, properties, methods) to include them into djangoproject.schema automatically.

Questions

I know that for doing this I need to:

  1. Iterate over all models within my apps

  2. Use some kind of design patterns to generate application’s schema.py module with its Query class.

  3. Collect applications’ schemas in djangoproject.schema module

Could you please tell me some development methods, patterns and practices to accomplish this task?

How to append options and classes into a custom attribute in Twig?

In our twig template we have a need to wrap certain fields with a Link field. In the existing twig template there already exist an attributes variable (accessed by adding attributes), but we have a need to have a custom one. Couldn’t find any documentation on if you can pass options and attributes from one field to a custom twig attribute.

Is there a way to append all options and classes from a field’s attributes into a custom attribute in a Twig template without any hook_preproceess_hook?

Existing node--article.html.twig

<section {{ attributes }}>   <div>{{ content.body }}</div>   <div>{{ content.field_subtitle }}</div>   <div>{{ content.field_category }}</div>   {{ content.field_link }} /* has its own options and attributes */ </section> 

Desired output

/* pass the options and attributes from field_link into the a_attr */ /* This did not result in what we wanted */ {% set a_attr = create_attribute(content.field_link.0['#attributes']) %} <a href="{{ content.field_link.0['#url'] }}" {{ attributes }}>   <div>{{ content.body }}</div>   <div>{{ content.field_subtitle }}</div>   <div>{{ content.field_category }}</div>   <div> {{ content.field_link.0['#title'] }} </div> </a> 

Design pattern for similar classes that require different implementations

There could be a common or best practice for this scenario, but I am unfamiliar with it. However, it could very easily be a matter of subjective opinion on how one wants to implement their classes. Either way I am hopefuly to get some opinion from the spectrum of class designers here.

I am currently working on a project that allows users to generate files for data visualization.

The library will support two file types that are formatted differently (binary and XML). Due to this, I am left with a dilemma on how I want to control class instantiation and API access:

  1. Create a separate class for each file type and visualization type
  2. Create a separate class for each visualization type and load with methods for each file type
  3. (Not demonstrated) The inverse of Option 2

Option 1:

class Base:     # Stuff class F1V1(Base):     # Methods specific to file and visualization type one class F1V2(Base):     # Methods specific to file type one and visualization type two class F1V3(Base):     # Methods specific to file type one and visualization type three class F2V1(Base):     # Same logic as before but for file type two class F2V2(Base):     # ... class F2V3(Base):     # ... 

Here a user of the library would call their direct class to perform operations specific to it without the need of setting keyword parameters to determine what it does (e.g. fv = F1V2())

What is great about this way is that its explicit, a user knows exactly what file and visualization type they are working with. But I think its cumbersome and not extensible in the event I want to add more file or visualization types; forcing me to write a new class for each possible combination.

Option 2:

class Base:     # Stuff class V1(Base):     def __init__(self, ftype_1=True)         self.ftype_1 = ftype_1     def write(self):         if self.ftype_1:             # Write method specific to file type one         # Write method specific to file type two     # Assume 3 methods for each operation     # One method such as `write()`     # One method for each of the file types class V2(Base):     # Same logic as before class V3(Base):     # ... 

What I don’t like about this method is that I now have to define multiple methods for each class that execute based upon keywords provided at construction (i.e. fv = V2(ftype_1=False)). Ideally, what I would like is to supply a keyword argument that then determines which of the methods should belong to that class. For example:

fv = V2() # Only contains methods to file type one operations fv = V2(ftype_1=False) # Only contains methods to file type two operations 

As shown, there is nothing that prevents the following:

fv = V2() # Set for file type one fv.write_ftype_2() # Will produce an invalid file type formatting 

I am not sure of a way where I can dynamically bind/remove methods based upon keyword arguments. It would be great if I could simply write all the methods for each file type within each visualization type, then remove methods that are not relevant to the class anymore. Im not sure if this is even advisable, I can already think of a scenario like so:

def write(self):     if self.ftype_1:         # Write method specific to file type one     elif self.type_2:         # ...     else:         # ... 

If I dynamically removed methods from a class based upon keyword arguments, what would the point of the conditions be if say the first one held?

Summary:

So which is a common or best practice? Which can be improved? Or am I missing another way?

An ideal example would be (in my mind):

fv = Hexagons(ftype='.abc', flat=True, area=3) fv.insert(data) fv.write(data) # Specifically writes for file types of '.abc' 

I suppose I could make Hexagons() return a subclass via __new__ but I think that might be unclear as to what is happening. To call Hexagons() but receive a ABCHexagons object could lead to confusion when users inspect the code base.

A factory method is ideal for this, but that is simply class instantiation. But each visualization type may have a variety of different keyword parameters that may not apply to the others. Rather, my issue lies with how to define them in the code base which ultimately leads to solving how to expose them to users.

Ring isomorphism between $H^*(G_n(\Bbb F^\infty); R)$ and Ring of characteristic classes

Definitions: Define the following map: let $ k \in H^m(G_n(\Bbb F^\infty ), R)$ , and $ \xi= (E,B,p)$ then define $ k(\xi) = g^*(k) \in H^m(B,R)$ , where $ g$ is the induced map from the bundle map $ (F,g):\xi \rightarrow \gamma_n$ , $ \gamma_n$ being the canonical bundle over $ G_n(\Bbb F^\infty)$ , the Grassmanian.

This is well defined by lemma below.


By lemma again that $ k$ induces a natural in the set of $ n$ -vector bundle isomorphism class. Hence $ k$ defines a natural transformation $ Vect_n(-)$ to $ H^m(-,R)$ . This is by defintion, a characteristic class of degree $ m$ , this set is denoted $ \Lambda_m$

We have the ring of characteristic calsses: $ \Lambda := \bigoplus \Lambda_m$ . The addition structure: if $ c_i \in \Lambda_k$ , $ (c_1+c_2)(B)=c_1(B)+c_2(B)$ . the ring structure: if $ c_i \in \Lambda_{n_i}$ , then we define $ (c_1 \cdot c_2)(B) = c_1(B) \cup c_2(B) \in \Lambda_{n_1+n_2}$ .


Lemma: For each vector bundle $ \xi$ there is a bunlde morphism $ (F,g): \xi \rightarrow \gamma_n$ unique upto bundle homotopy, where $ \gamma_n=(E,G_n(\Bbb F^\infty), \pi)$ is the Grassmanian bundle.


Now we come to the main statement

The map $ H^*(G_n(\Bbb F^\infty), R) \rightarrow \Lambda$ , $ k$ mapping to the natural transformation it induces is a ring isomorphism.

How does one show this map is injective?


Reference: it is claimed, Theorem 3.3, pg 19 that this is clear. I don’t see why.