8 – How to check if custom variation field is null in twig?

I would like to know how to check if a custom variation field has content in a twig template (commerce-product.html.twig with variations injected). I have tried with some filters and conditions but without success. I need to hide some html markup if the field is empty. For example:

{% if product.variation_field_mycustomfield is not empty %}
<div class="mycustomclass">My custom field: {{ product.variation_field_mycustomfield }}</div>
{% endif %}  

My products have some variations that users can select from a list. When this select changes, the product information must change, and some variations of the same product could have this field empty or not.

postgresql – Will Postgres use a multi-column index when setting multiple colums not null?

Typically, when I set a column not null, if it doesn’t have an index then I add it first, so that postgres can (hopefully) use the index while doing the table scan while locking the table, so that the table is locked for a shorter amount of time.

I want to set several columns not null, like so:

alter table foos
  alter column bar1 set not null
  alter column bar2 set not null
  alter column bar3 set not null
  alter column bar4 set not null;

If I make a multicolumn index for these columns, will postgres use it when scanning the locked table before making this alteration?

CREATE INDEX CONCURRENTLY my_index on foos (bar1, bar2, bar3, bar4);

What if I made a partial index on IS NULL (or, IS NOT NULL)

CREATE INDEX CONCURRENTLY my_index on foos (bar1, bar2, bar3, bar4) where bar1 is null and bar2 is null and bar3 is null and bar4 is null;

magento2 – Megento 2 Left joining two tables, if null default to 0

Title self esplicative, but when I perform the join, then add field to select then make the expression I get an error.

$this->getCollection()->getSelect()
        ->joinLeft(
            (
                "transaction" => $this->getCollection()->getTable("transaction_table")
            ),
            "(transaction.supplier_id = main_table.supplier_id)",
            (
                'transaction_id' => 'entity_id',
                'amount' => 'amount',
                'date' => 'date'
            )
        )
        ->joinInner(
            (
                'supplier' => $this->getCollection()->getTable('supplier_table')
            ),
            "(supplier.entity_id = main_table.supplier_id)",
            (
                'business_name' => 'business_name'
            )
        );
$this->getCollection()
        ->addFieldToSelect(new Zend_Db_Expr("CASE WHEN amount is NULL THEN 0 ELSE amount END AS amount_sum"))
        ->addFieldToSelect(new Zend_Db_Expr("CASE WHEN date is NULL THEN main_table.start_date ELSE date END AS date"));
$this->getCollection()->getSelect()
        ->columns(('current_amount' => new Zend_Db_Expr('SUM(amount_sum)')))
        ->group('main_table.entity_id');

But I get the following error:

SQLSTATE(42S22): Column not found: 1054 Unknown column 'amount_sum' in 'field list', query was: SELECT CASE WHEN amount is NULL THEN 0 ELSE amount END AS amount_sum, CASE WHEN date is NULL THEN main_table.start_date ELSE date END AS date, `transaction`.`entity_id` AS `transaction_id`, `transaction`.`amount`, `transaction`.`date`, `supplier`.`business_name`, SUM(amount_sum) AS `current_amount` FROM `objective_table` AS `main_table` LEFT JOIN `transaction_table` AS `transaction` ON (transaction.supplier_id = main_table.supplier_id) INNER JOIN `supplier_table` AS `supplier` ON (supplier.entity_id = main_table.supplier_id) GROUP BY `main_table`.`entity_id` LIMIT 20

Suggestions? I’m going crazy

java – Sessão da Servlet retornando null

Eu estou com problemas ao pegar um id de login e armazena-lo numa sessao dentro de uma servlet para usar em relacionamento de Consulta com Usuario, a sessão retorna null para min.

LoginServlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
       try (PrintWriter out = response.getWriter()) {


        String nome=request.getParameter("txtNome");
        String senha=request.getParameter("txtSenha");


        if((!nome.equals(""))&&(!senha.equals("")))   
     {
          Usuario usuario=new Usuario();   

          usuario.setNome(nome);
          usuario.setSenha(senha);

          UsuarioDAO userDAO = new UsuarioDAO();    
          Usuario resultado =userDAO.login(usuario);



          if(resultado==null)
          {

           response.sendRedirect("./Login.html");
          } 
          else
          {
           HttpSession sessaoUsuario = request.getSession();
           sessaoUsuario.setAttribute("usuario", resultado);


           response.sendRedirect("ConsultaServlet");   
          }




     }else{
         response.sendRedirect("PaginaPrincipal.html");
     }

    }  
    }

UsuarioDao

 public Usuario login(Usuario usuario) {

        EntityManager em = new ConnectionFactory().getConnection();
        try {

           String nome=usuario.getNome();
           String senha=usuario.getSenha();

            em.getTransaction().begin();
            Usuario consulta = (Usuario) em.createQuery("select c from Usuario c where nome=:nome and senha=:senha").setParameter("nome",nome).setParameter("senha",senha).getSingleResult();
            em.getTransaction().commit();

             return consulta;

        } catch (NoResultException e) {
            System.err.println(e);
            em.getTransaction().rollback();
            return null;

        } finally {
          em.close();

        }

    }

SalvaConsultaServlet

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            String data = request.getParameter("txtData");
            String horario = request.getParameter("txtHorario");
            String nomeMedico = request.getParameter("txtNomeMedico");
            String especialidade = request.getParameter("txtEspecialidade");


            if ((!data.equals("")) && (!horario.equals("")) && (!nomeMedico.equals("")) && (!especialidade.equals(""))) {

                 ConsultaDAO conDAO = new ConsultaDAO();
                 Usuario usuario =(Usuario) request.getAttribute("usuario");
                 usuario.getId();
                 out.println(usuario);


                 Consulta con = new Consulta();


                con.setConsultaData(data);
                con.setHorarioConsulta(horario);
                con.setNomeMedico(nomeMedico);
                con.setEspecialidade(especialidade);
                con.setValorConsulta(50);
                con.setUsuario(usuario);



                conDAO.save(con);

                   response.sendRedirect("ConsultaServlet");
            } else {
                   response.sendRedirect("MarcarConsultaServlet");
            }

        }
    }

Diferenciar Null e 0 em C

existe alguma forma de diferenciar NULL e 0 de uma variável em C? Pois pelo que percebi, da forma que estou fazendo, ele não consegue diferir, segue o código de exemplo:

”’

int i = NULL;

if(i == NULL) //o retorno será true

if(i == 0) //o retorno será true

”’

mysql – How to check if staff member has end date with a Null value

I have a database that records employees tasks throughout the organisation and when they finish etc., I need to identify if each employee, has at least one row with a null value in either finish.

Basically – show me any employee_no that does not have at least one row with a null value in column Finish.

There can be more than one null value but as long as there’s one.

Sample database:

enter image description here

java – Fremdschlüssel in DB immer Null

Ich habe diesen Fehler im Frühjahr erhalten: Geben Sie hier die Bildbeschreibung ein, wenn ich versuche, zwei Tabellenentitäten zu verbinden.
Und der Fremdschlüssel ist in DB immer Null. Warum?
Meine Entitätsklassen – Aufgabe, ListeExecJob.
Bitte hilf mir

Aufgabe:

@SuppressWarnings("serial")
@Entity
@Table(name ="task")
public class Task implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;


@Column(name = "nom_job", length = 20,nullable = false)
private String nom_job;

@Column(name = "type_commande", length = 20,nullable = false)
private String type_commande;

@Column(name = "description", length = 100, nullable = false)
private String description;

@Column(name = "script", length = 100, nullable = false)
private String script;

@JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
@Column(name = "date_execution")
private Date date_execution;

 @Column(name = "active")
 private boolean  active;

 @ManyToOne
 @JoinColumn(name="id_liste")
 private ListeExecJob liste;


public ListeExecJob getListe() {
return liste;
}
public void setListe(ListeExecJob liste) {
this.liste = liste;
 }


public Integer getId() {
    return id;
}
public void setId(Integer id) {
    this.id = id;
}
public String getNom_job() {
    return nom_job;
}
public void setNom_job(String nom_job) {
    this.nom_job = nom_job;
}
public String getType_commande() {
    return type_commande;
}
public void setType_commande(String type_commande) {
    this.type_commande = type_commande;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getScript() {
    return script;
}
public void setScript(String script) {
    this.script = script;
}
public Date getDate_execution() {
    return date_execution;
}
public void setDate_execution(Date date_execution) {
    this.date_execution = date_execution;
}

public boolean getActive() {
    return active;
}
public void setActive(boolean  active) {
    this.active = active;
}



public Task() {

}
public Task(Integer id, String nom_job, String type_commande, String description, String script,
        Date date_execution, boolean  active) {
    super();
    this.id=id;
    this.nom_job = nom_job;
    this.type_commande = type_commande;
    this.description = description;
    this.script = script;
   this.date_execution = date_execution;
    this.active=active ;

 }

}

ListeExecJob.java
     ____________________________________________________

@SuppressWarnings("serial")
@Entity
@Table(name ="liste")
@JsonIgnoreProperties(
    value = {"dateCreation"},
    allowGetters = true
 ) 
public class ListeExecJob implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "idListe")
private int idListe;


@Column(name = "status")
private String status;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "date_creation")
@CreatedDate
private Date date_creation;

@JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
@JoinColumn(name = "date_execution")
private Date date_execution;

@JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
@Column(name = "fin_execution")
private Date fin_execution;

@JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
@Column(name = "next_execution")
private Date next_execution;


@OneToMany(mappedBy="liste",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JsonIgnore
 private List task;


public int getIdListe() {
    return idListe;
}

public void setIdListe(int idListe) {
    this.idListe = idListe;
}


public Date getDate_creation() {
    return date_creation;
}

public void setDate_creation(Date date_creation) {
    this.date_creation = date_creation;
}

public Date getDate_execution() {
    return date_execution;
}

public void setDate_execution(Date date_execution) {
    this.date_execution = date_execution;
}

public Date getFin_execution() {
    return fin_execution;
}

public void setFin_execution(Date fin_execution) {
    this.fin_execution = fin_execution;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

@JsonIgnore
public List getTask() {

    if (task == null) {
        task = new ArrayList<>();
    }


    return this.task;
    }
 public void addTask(Task task) {
    getTask().add((Task) task);
    ((Task) task).setListe(this);
  }

 public void removeTask(Task task) {
    getTask().remove(task);
    task.setListe(null);
}


@JsonSetter
public void setTask(List task) {
    this.task = task;
}


public ListeExecJob() {

}

public ListeExecJob(int idListe, String status, Date date_creation, Date date_execution, Date b 
   fin_execution,
        Date next_execution) {
    super();
    this.idListe = idListe;
    this.status = status;
    this.date_creation = date_creation;
    this.date_execution = date_execution;
    this.fin_execution = fin_execution;
    this.next_execution = next_execution;
    }
  }

Aufgabendienst

@Service
@Transactional(propagation= Propagation.SUPPORTS)
@Primary
public class TaskService {

@Autowired
private TaskRepository repository;

@Autowired
private ListeExecJobService service;

@Autowired
public TaskService(TaskRepository repository) {
    super();
    this.repository = repository;
}

public List listAllTask(){
    return repository.findAll();
}
public Task addTask(Task task){

    ListeExecJob ab = service.getByreferenece(task.getListe().getIdListe());

    ab.addTask(task);
     return repository.save(task);

  /* task.setListe(ab);
     System.out.println(task.getListe().getIdListe());
    ab.addTask(task);*/
}

public Task updateTask(Integer id , Task task){
    Task job1 = new Task();
    job1 = task;
    job1.setId(id);
    return addTask(job1);
  }
  public void deleteTask(Integer id){
    repository.deleteById(id);
  }
  public Task getByreferenece(Integer id){
     return repository.findById(id).isPresent()? repository.findById(id).get():null;
  }
 }

ListeExecJobService

 @Service
 @Transactional
 @Primary
 public class ListeExecJobService {

@Autowired
private ListeExecJobRepository SJIRepos;

@Autowired
public ListeExecJobService(ListeExecJobRepository SJIRepos) {
    super();
    this.SJIRepos = SJIRepos;
}

 public List listAllListeExecJob(){
        return SJIRepos.findAll();
    }
    public ListeExecJob addListeExecJob(ListeExecJob SJI){
       return SJIRepos.save(SJI);
    }
    public ListeExecJob getByreferenece(Integer idListe){
        return SJIRepos.findById(idListe).isPresent()? SJIRepos.findById(idListe).get():null;

    }
    public void deleteListeExecJob(Integer idListe){
        SJIRepos.deleteById(idListe);
    }


    public ListeExecJob updateListeExecJob(Integer idListe , ListeExecJob sji){
    ListeExecJob sji01 = new ListeExecJob();
    sji01 = sji;
    sji01.setIdListe(idListe);
    return addListeExecJob(sji01);
   }

   public void deleteById(Integer idListe) {
    SJIRepos.deleteById(idListe);
    }

   }

asp.net mvc – Object reference not set as an instance of an object. Image was null

I am trying to edit data records in a catalog. This catalog offers the possibility to upload an image, but is not a mandatory field. The problem is that when editing the data record, regardless of whether an image is already stored in this data record or not, an error message is displayed if I do not select an image from the input. It is as if it were a mandatory field.

The mistake is this …

Object reference not set as an instance of an object. Image was null.

I'm supposed to go to the image stored on the server, but I don't know how to do it.

I have the following in the controller building …

public ActionResult Update(int id)
{
    if (Session("Usuario") == null)
    {
        return RedirectToAction("Index", "Login");
    }
    else
    {
        ObtenerEdificio resp = obj.catEdificioObtener(id);
        return View(resp);
    }
}

(HttpPost)
    public ActionResult Update(ObtenerEdificio vm, HttpPostedFileBase Imagen)
    {
        byte() fileBytes = new byte(Imagen.InputStream.Length);
        int byteCount = Imagen.InputStream.Read(fileBytes, 0, (int)Imagen.InputStream.Length);
        string fileContent = Convert.ToBase64String(fileBytes);

        ActualizaEdificio entrada = new ActualizaEdificio();
        entrada.IdEdificio = vm.IdEdificio;
        entrada.Descripcion = vm.Descripcion;
        entrada.Imagen = fileContent;

        RespuestaGeneral resp = obj.catEdificioActualiza(entrada);

        ViewBag.successMessage = resp.Mensaje;

        return RedirectToAction("Index", "Edificios");
    }

I have the following in my View Update …

@using (Html.BeginForm("Update", "Edificios", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.HiddenFor(d => d.IdEdificio)
    
@Html.ValidationMessageFor(m => m.Descripcion, "", new { @class = "ml-2", style = "color:red" }) @Html.TextBoxFor(m => m.Descripcion, "", new { @type = "text", @class = "form-control ml-5", style = "width:92%" })
}

I hope you understand me and can support me with my problem. thank you

Javascript – Access to the fetch from origin & # 39; null & # 39; was blocked by the CORS directive:

hola estoy passando de subir un video a giphy mediante la api pero siempre obtengo estos errores, alguien sabe queifican:

(no se si la cabecera esta bien escrita)
Gracias por la ayuda

mis_guifos.html: 1 Access to the retrieval at & # 39; http: //upload.giphy.com/v1/gifs/? & api_key = x58Cq33OnTiwdQ7gRoG1bsCNVFJdEX1d & # 39; from origin & # 39; null & # 39; was blocked by the CORS directive: The response to the preflight request was not forwarded. Control check: Redirection is not permitted for a preflight request.

mis_guifos.js: 245 POST http://upload.giphy.com/v1/gifs/?&api_key=x58Cq33OnTiwdQ7gRoG1bsCNVFJdEX1d net :: ERR_FAILED

mis_guifos.js: 248 Not caught (as promised) TypeError: Failed to get

  btn_upload_gif.addEventListener("click", function(){
                var new_header = new Headers();
                var options = {
                    method: "POST",
                    mode: "cors",
                    headers: new_header,
                    cache: "default",
                    body: file,
                    headers: {
                        "content-type": "video/ogg"
                    }
                    
                }
                
              
                async function uploading_gif(url){
                    let gif_file = await fetch(url, options);
                    let gif_file_json = await gif_file.json();
                    console.log(gif_file_json);
                }
              
                uploading_gif(`http://upload.giphy.com/v1/gifs/?&api_key=x58Cq33OnTiwdQ7gRoG1bsCNVFJdEX1d`);
            });

C # – The conditional formatting of the property in bold is null in Epplus.Core 1.5.4

I have an Excel that serves as a "template" for downloading data. This template contains 2 columns (A and B). A contains information such as name, ID and address (everything is displayed on a different line), z To identify the type, the user enters the type of this line in column B.
In this way, a conditional Excel format is applied.

So far so good, the font, the colors, etc. However, if the conditional format is printed in bold, this property is not copied because it is always set to zero.

You need the generated Excel to have the conditional formats in bold.

I use Net Core 2.2 y EPPlus.Core 1.5.4

Here are the dates:
This is the data

These are the conditional formats I want to use:
These are the conditional formats that I want to use

Example of the format in bold:
Format example in bold

I tried to copy property by property (Style.Font, Style.Fill ..) but nothing can be saved as zero.

    private void ApplyingConditionalFormatting(ExcelWorksheet worksheetBase, ExcelWorksheet worksheetNew)
    {
        var baseConditional = worksheetBase.ConditionalFormatting;
        var newConditional = worksheetNew.ConditionalFormatting;

        foreach (var aux in baseConditional)
        {
            ExcelConditionalFormattingExpression condition = aux as ExcelConditionalFormattingExpression;
            var cfRule = newConditional.AddExpression(new ExcelAddress("A1:A13"));
            cfRule.Formula = "$B1=="T"";
            cfRule.Formula = condition.Formula;
            cfRule.Style.Fill = condition.Style.Fill;
            cfRule.Style.Font = condition.Style.Font; // Aquí, viene a null la propiedad Bold
            cfRule.Style.Border = condition.Style.Border;
            cfRule.Style.NumberFormat = condition.Style.NumberFormat;
        }
    }

I hope it is enough to see if someone had the same problem and managed to fix it.
Thank you!