2021-07-31

Laravel Search by 3 values get nothing

I have a bunch of columns in a table what I need is to filter the table using few parameters using laravel Eloquent ORM.

For example companyName, StartDate. what I have tried is below

$objFetch = OpenOrder::where('companyName', $request->majorCompanies)
    ->orwhereBetween(
        'StartDate',
        array($request->startDate_start, $request->startDate_end)
    )
    ->orderby('id', 'desc')->get();

return response()->json([
    'success' => true,
    'objects' => $objFetch
]);


  "objects": [
                {
                   "company": "aa",
                   "StartDate": 2/24/2021,
                },
                {
                   "company": "aa"
                   "StartDate": 2/25/2021,
                },
                {
                   "company": "aa",
                   "StartDate": 4/15/2021,
                },
                {
                   "company": "bb",
                   "StartDate": 4/18/2021,
                },
                {
                   "company": "bb",
                   "StartDate": 2/24/2021,
                },
    
            ]

the answer should output the information given by the user for example: if the user select company aa and date between 2/24/2021,2/30/2021 output should be

"objects": [
                {
                   "company": "aa",
                   "StartDate": 2/24/2021,
                },
                {
                   "company": "aa"
                   "StartDate": 2/25/2021,
                },
                {
                   "company": "bb",
                   "StartDate": 2/24/2021,
                },
    
            ]

write your answers to solve this issue



from Recent Questions - Stack Overflow https://ift.tt/3lc6mh5
https://ift.tt/eA8V8J

How i can generate login link with FishStick API?

The library i used https://www.npmjs.com/package/fortnite-api-manager I know that it's possible to generate login link with only one command with using discord.js but as you can see it requires 3 values.

let accountId = 'Your Account Id'
let deviceId = 'Your Device Id'
let secret = 'Your Secret'

let config = {
  'accountId':accountId,
  'deviceId':deviceId,
  'secret':secret
};

So, how to generate login link without account, device ids and secret?



from Recent Questions - Stack Overflow https://ift.tt/2ViP7j9
https://ift.tt/eA8V8J

Sign PDF in a valid way

How can I sign a PDF in a valid way? I already have a valid pfx file, but when I sign the pdf file with the node-sign lib, acrobat points the signature as not valid. It tells that I need to get the timestamp from an authority server... I'm willing to use any coding language.



from Recent Questions - Stack Overflow https://ift.tt/3fbiuew
https://ift.tt/eA8V8J

Completing input statments with beatifulsoup, xml and json

Hey guys do you know how can I enter values to the input statements in this webpage with beautifulsoup, xml or json? Here is the webpage code:

document.write(cab_pag("MANIFIESTOS DE EXPORTACION MARITIMO")) Esta opción permite consultar información de los conocimientos de embarque (B/L) por año y número de manifiesto de exportación. Se muestra los siguientes datos generales: fecha de zarpe, matrícula de la nave, número de viaje y los siguientes datos de cada conocimiento; puerto de destino, número de conocimiento, número de detalle, peso recibido, bultos recibidos, consignatario. Ingrese el Año y Número de Manifiesto :  - -

from Recent Questions - Stack Overflow https://ift.tt/3ldT8jH
https://ift.tt/eA8V8J

Converting data from PuTTY to YAML file

I have some data that I can accesss through a Linux command in PuTTY, but I need to convert this data into a .yaml file. The format of the data is as follows:

_name: Bob
age: '15'
___

_name: Alex
age: '17'
___

And so on. How can I parse through this data to create a .yaml file with {'key':'value'} for each person's name being the key and age being the value. So far, I've thought of converting this data to a text file and then using a for loop to parse through the "_name" and "age" text values, but I'm not sure where this would lead me. Any thoughts?



from Recent Questions - Stack Overflow https://ift.tt/3fctl7M
https://ift.tt/eA8V8J

What is the difference between transmission and transmission-daemon?

I have watched some tutorials on how to install torrent program on raspberry.

I have seen somebody installs like this:

sudo apt install transmission

Someone installs it like this:

sudo apt install transmission-daemon


from Recent Questions - Stack Overflow https://ift.tt/3ldT7MF
https://ift.tt/eA8V8J

Python Code in the terminal instead of Output VSCode

So I'm new to programming and have used PyCharm. I have gotten Mosh Hamedani's course and saw that whatever code he executes is shown in its output window NEATLY. My code is jumbled up with stupid commands which are telling me the location of the file etc. How can I make ONLY MY EXECUTED CODE show up in the output or terminal? I just want to get rid of those Windows PowerShell etc stuff. The highlighted part is the code I ran and want only that to be shown and nothing else??

Highlighted code is my run code



from Recent Questions - Stack Overflow https://ift.tt/3ygshaC
https://ift.tt/eA8V8J

How to add javascript into php?

Here is my js code

<script>
function myform() {
    var n = document.getElementById("name").value;

    if (n == "") {
        document.getElementById("username").innerHTML = "Please enter your name";
        return false;
    }
    if (!isNaN(n)) {
        document.getElementById("username").innerHTML = "Please enter valid name";
        return false;
    }
}
</script>

How to write this js code into php

m trying all code in echo but not working plz help

after php echo using

    echo'<script>
function myform() {
    var n = document.getElementById("name").value;

    if (n == "") {
        document.getElementById("username").innerHTML = "Please enter your name";
        return false;
    }
    if (!isNaN(n)) {
        document.getElementById("username").innerHTML = "Please enter valid name";
        return false;
    }
}
</script>';

thankyou



from Recent Questions - Stack Overflow https://ift.tt/3iYHgzu
https://ift.tt/eA8V8J

Can I use different selection comparisons based on a passed value in SQL?

I wasn't really sure of the best wording for the question but here is my dilemma:

I am passing a value to a sql query as @district. This value may be the exact district but it also has the possibility of being a value that should create a set of multiple districts. So if I pass '002' I want the where clause to say I.Offense_Tract = @district. If I pass 'Other' I want the where clause to say I.Offense_Tract in (). What I am trying to do is something like:

AND
CASE
   WHEN @district = "Other" THEN I.Offense_Tract in ('BAR','COL','GER','MEM','MIL','JAIL','JAILEAST','SCCC','1USD','2USD')
ELSE I.Offense_Tract = @district
END

But this doesn't work. The problem, restated, is if the value passed is anything other than 'Other', I just want it to be =. If 'Other' is passed, I want it to be IN.



from Recent Questions - Stack Overflow https://ift.tt/3C1CYjk
https://ift.tt/eA8V8J

How to drop the all the 1's in a correlation matrix

I'm trying to change/eliminate the 1's that run diagonally in a correlation matrix so that when I take the average of the rows of the correlation matrix, the 1s don't affect the mean of each of the rows.

Let's say I have the dataset,

A B C D E F 45 49 49 65 65 45 60 62 63 80 80 60 80 82 83 100 100 80 80 100 123 122 120 80 39 52 43 60 50 65 58 64 58 80 65 80 78 84 78 109 85 100 78 130 111 130 85 100 78 104 78 159 115 100 44 48 65 50 64 43 59 63 80 65 80 58 79 83 100 85 105 78 79 103 120 135 115 78 45 30 35 20 20 45 50 20 55 25 25 30 60 45 50 90 80 70

When I do dfcorr = df.corr() dfcorr, I get

   A            B           C           D          E           F

A 1.000000 0.842125 0.834808 0.832773 0.844158 0.806787 B 0.842125 1.000000 0.847606 0.907595 0.818668 0.863645 C 0.834808 0.847606 1.000000 0.718199 0.804671 0.582033 D 0.832773 0.907595 0.718199 1.000000 0.884236 0.878421 E 0.844158 0.818668 0.804671 0.884236 1.000000 0.718668 F 0.806787 0.863645 0.582033 0.878421 0.718668 1.000000

I want all the 1's to be dropped so that if I want to take the mean of each of the rows, the 1's won't affect them.



from Recent Questions - Stack Overflow https://ift.tt/3idyTRx
https://ift.tt/eA8V8J

NAT router with ebpf/XDP

I'm trying to achieve a simple NAT (just swap dest and src IP of the packet) using XDP so I can just process the packet once I receive it on an interface and send it back to the sender through another interface, but it seems I missed something and would be grateful for tips and advice. Note that I'm not sure I understand the underlying mechanisms of networking protocols or Linux networking - I'm working on improving that xD. Anyway here's the code I'm using.

struct in_addr ipaddr;
int ifindex = 3;
uint8_t tmp_mac[ETH_ALEN] = {/* mac address of the second interface */};

// Here I'm supposed to have a decision function to decide which IP to be translated to what
// ipaddr.s_addr = (in_addr_t) bpf_map_lookup_elem(&ip_nat, &ip->daddr);

// Change the source MAC to the MAC of forwarding back interface
memcpy(eth->h_source, tmp_mac, ETH_ALEN);
// Change the destination to the same interface address from the packet sender
memcpy(eth->h_dest, eth->h_source, ETH_ALEN);

// Swap IP addresses
memcpy(&ipaddr, &ip->saddr, sizeof(ipaddr));
memcpy(&ip->saddr, &ip->daddr, sizeof(ipaddr));
memcpy(&ip->daddr, &ipaddr, sizeof(ipaddr));

// Send the packet to forwarding interface
return bpf_redirect(ifindex, 0);

I'm using Scapy to generate TCP packets from a machine to another, but unfortunately I route the packets back. I tried the xdp_tutorial but I couldn't see what I'm missing - noop flag is up xD.



from Recent Questions - Stack Overflow https://ift.tt/3zUJcjq
https://ift.tt/eA8V8J

Perfectly rectangular DIV wrapper in CSS [duplicate]

How can I make div image wrapper, which will be rectangular? It must have same width and height, but without setting it... Here is what I have:

.wrapper{
  background-color: red;
  width: fit-content;
  height: fit-content;
  padding: 30px;
  
}
<div class="wrapper">
  <img src="https://cdn2.iconfinder.com/data/icons/bitsies/128/Magnifier-128.png" />
  
</div>

If you inspect that "wrapper" div in devtools, you will see, that it has dimensions 128x132 px (+padding) instead of 128x128 px as it only wraps that 128x128 px image. Why it adds 4px on height and how can I get rid of it? I need perfectly rectangular wrapper and I don't want to manually set dimensions or use Javascript...

Thanks!



from Recent Questions - Stack Overflow https://ift.tt/3fgMIMW
https://ift.tt/eA8V8J

How to define custom themes in vue.js using typescript?

I am trying to change the colours of a Vue template (uses vuetify) that I am using but after pouring over the docs for a day I am not sure what else I can try.

My main file:

//src/main.ts

import '@babel/polyfill';
// Import Component hooks before component definitions
import './component-hooks';
import Vue from 'vue';
// import './plugins/vuetify';
import './plugins/vee-validate';
import App from './App.vue';
import router from './router';
import store from '@/store';
import './registerServiceWorker';
import 'vuetify/dist/vuetify.min.css';
import Vuetify from 'vuetify';

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount('#app');

the vuetify plugin file:

//src/plugins/vuetify.ts

import Vue from 'vue';
import Vuetify from 'vuetify';

Vue.use(Vuetify, {
  theme: {
      themes: {
          light: {
            primary: '#17242d', 
          },
          dark: {
            primary: '#17242d',
        },
      },
    },
});

I tried many variations of defining different themes in the vuetify.ts file but nothing changes the colours in of any component that references (for example) "primary".

Other people seemed to have success with my approach: https://forum.vuejs.org/t/vuetify-how-to-add-a-custom-color-theme-after-create-the-project/40241/2

Am I missing something? Where should I look next?



from Recent Questions - Stack Overflow https://ift.tt/3ygr8jk
https://ift.tt/eA8V8J

Virtual Bug with CPP

I'm having some issues with C++ using it with binary tests, i'm learning binary search trees, i'm getting these erros, note : i didn't code the functions, i'm first trying to compile it with random returns.

:\msys64\mingw64\bin\g++.exe -g "C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL Árvore Binária\main.cpp" -o "C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL Árvore Binária\testVpl.exe" -lgtest -std=c++20
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp: In member function 'virtual void ArvoreBinariaBuscaTest_Inicializacao_Test::TestBody()':
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp:6:49: error: invalid new-expression of abstract class type 'MinhaArvoreDeBuscaBinaria<int>'
    6 |     ArvoreDeBuscaBinaria<int>* const arvore{new MinhaArvoreDeBuscaBinaria<int>};
      |                                                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp:2:
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\MinhaArvoreDeBuscaBinaria.hpp:14:7: note:   because the following virtual functions are pure within 'MinhaArvoreDeBuscaBinaria<int>':
   14 | class MinhaArvoreDeBuscaBinaria : public ArvoreDeBuscaBinaria<T>
      |       ^~~~~~~~~~~~~~~~~~~~~~~~~
In file included from C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\MinhaArvoreDeBuscaBinaria.hpp:4,
                 from C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp:2:
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\ArvoreDeBuscaBinaria.hpp:30:18: note:     'bool ArvoreDeBuscaBinaria<T>::vazia() const [with T = int]'
   30 |     virtual bool vazia() const = 0;
      |                  ^~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\ArvoreDeBuscaBinaria.hpp:36:17: note:     'int ArvoreDeBuscaBinaria<T>::quantidade() const [with T = int]'
   36 |     virtual int quantidade() const = 0;
      |                 ^~~~~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\ArvoreDeBuscaBinaria.hpp:43:18: note:     'bool ArvoreDeBuscaBinaria<T>::contem(T) const [with T = int]'
   43 |     virtual bool contem(T chave) const = 0;
      |                  ^~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\ArvoreDeBuscaBinaria.hpp:50:32: note:     'std::optional<int> ArvoreDeBuscaBinaria<T>::altura(T) const [with T = int]'
   50 |     virtual std::optional<int> altura(T chave) const = 0;
      |                                ^~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\ArvoreDeBuscaBinaria.hpp:70:30: note:     'std::optional<_Tp> ArvoreDeBuscaBinaria<T>::filhoEsquerdaDe(T) const [with T = int]'
   70 |     virtual std::optional<T> filhoEsquerdaDe(T chave) const = 0;
      |                              ^~~~~~~~~~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\ArvoreDeBuscaBinaria.hpp:77:30: note:     'std::optional<_Tp> ArvoreDeBuscaBinaria<T>::filhoDireitaDe(T) const [with T = int]'
   77 |     virtual std::optional<T> filhoDireitaDe(T chave) const = 0;
      |                              ^~~~~~~~~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\ArvoreDeBuscaBinaria.hpp:83:40: note:     'ListaEncadeadaAbstrata<T>* ArvoreDeBuscaBinaria<T>::emOrdem() const [with T = int]'
   83 |     virtual ListaEncadeadaAbstrata<T>* emOrdem() const = 0;
      |                                        ^~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\ArvoreDeBuscaBinaria.hpp:89:40: note:     'ListaEncadeadaAbstrata<T>* ArvoreDeBuscaBinaria<T>::preOrdem() const [with T = int]'
   89 |     virtual ListaEncadeadaAbstrata<T>* preOrdem() const = 0;
      |                                        ^~~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\ArvoreDeBuscaBinaria.hpp:95:40: note:     'ListaEncadeadaAbstrata<T>* ArvoreDeBuscaBinaria<T>::posOrdem() const [with T = int]'
   95 |     virtual ListaEncadeadaAbstrata<T>* posOrdem() const = 0;
      |                                        ^~~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp: In member function 'virtual void ArvoreBinariaBuscaTest_PreOrdem_Test::TestBody()':
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp:36:49: error: invalid new-expression of abstract class type 'MinhaArvoreDeBuscaBinaria<int>'
   36 |     ArvoreDeBuscaBinaria<int>* const arvore{new MinhaArvoreDeBuscaBinaria<int>};
      |                                                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp: In member function 'virtual void ArvoreBinariaBuscaTest_EmOrdem_Test::TestBody()':
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp:53:49: error: invalid new-expression of abstract class type 'MinhaArvoreDeBuscaBinaria<int>'
   53 |     ArvoreDeBuscaBinaria<int>* const arvore{new MinhaArvoreDeBuscaBinaria<int>};
      |                                                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp: In member function 'virtual void ArvoreBinariaBuscaTest_PosOrdem_Test::TestBody()':
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp:70:49: error: invalid new-expression of abstract class type 'MinhaArvoreDeBuscaBinaria<int>'
   70 |     ArvoreDeBuscaBinaria<int>* const arvore{new MinhaArvoreDeBuscaBinaria<int>};
      |                                                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp: In member function 'virtual void ArvoreBinariaBuscaTest_Insercao_Test::TestBody()':
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp:87:49: error: invalid new-expression of abstract class type 'MinhaArvoreDeBuscaBinaria<int>'
   87 |     ArvoreDeBuscaBinaria<int>* const arvore{new MinhaArvoreDeBuscaBinaria<int>};
      |                                                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp: In member function 'virtual void ArvoreBinariaBuscaTest_Remocao_Test::TestBody()':
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp:135:43: error: invalid new-expression of abstract class type 'MinhaArvoreDeBuscaBinaria<int>'
  135 |     ArvoreDeBuscaBinaria<int>* arvore{new MinhaArvoreDeBuscaBinaria<int>};
      |                                           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\Saint\Dropbox\PC\Documents\UFSC\Estrutura de Dados\VPL �rvore Bin�ria\main.cpp:183:18: error: invalid new-expression of abstract class type 'MinhaArvoreDeBuscaBinaria<int>'
  183 |     arvore = new MinhaArvoreDeBuscaBinaria<int>;
      |                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These are my errors

these are the files

The hpp file

#define ARVORE_DE_BUSCA_BINARIA_HPP

#include "MinhaListaEncadeada.hpp"
#include <optional>

template<typename T>
struct Nodo
{
    T chave;
    int altura{0};
    Nodo* filhoEsquerda{nullptr};
    Nodo* filhoDireita{nullptr};
};

template<typename T>
class ArvoreDeBuscaBinaria
{
protected:
    Nodo<T>* _raiz;

public:
    ArvoreDeBuscaBinaria();
    virtual ~ArvoreDeBuscaBinaria();

    /**
     * @brief Verifica se a arvore esta vazia
     * @return Verdade se a arvore esta vazia.
     */
    virtual bool vazia() const = 0;
    
    /**
     * @brief Retornar quantidade de chaves na arvore
     * @return Numero natural que representa a quantidade de chaves na arvore
     */
    virtual int quantidade() const = 0;
    
    /**
     * @brief Verifica se a arvore contem uma chave
     * @param chave chave a ser procurada na arvore
     * @return Verdade se a arvore contem a chave
     */
    virtual bool contem(T chave) const = 0;
    
    /**
     * @brief Retorna a altura da (sub)arvore
     * @param chave chave que é raiz da (sub)arvore cuja altura queremos. Se chave é nula, retorna a altura da arvore.
     * @return Numero inteiro representando a altura da (subarvore). Se chave nao esta na arvore, retorna std::nullopt
     */
    virtual std::optional<int> altura(T chave) const = 0;

    /**
     * @brief Insere uma chave na arvore
     * @param chave chave a ser inserida
     */        
    virtual void inserir(T chave) = 0;

    /**
     * @brief Remove uma chave da arvore
     * @param chave chave a removida
     * @return Retorna a chave removida ou nullptr se a chave nao esta na arvore
     */        
    virtual void remover(T chave) = 0;

    /**
     * @brief Busca a chave do filho a esquerda de uma (sub)arvore
     * @param chave chave da arvore que eh pai do filho a esquerda
     * @return Chave do filho a esquerda. Se chave nao esta na arvore, retorna std::nullopt
     */
    virtual std::optional<T> filhoEsquerdaDe(T chave) const = 0;

    /**
     * @brief Busca a chave do filho a direita de uma (sub)arvore
     * @param chave chave da arvore que eh pai do filho a direita
     * @return Chave do filho a direita. Se chave nao esta na arvore, retorna nullptr
     */        
    virtual std::optional<T> filhoDireitaDe(T chave) const = 0;

    /**
     * @brief Lista chaves visitando a arvore em ordem
     * @return Lista encadeada contendo as chaves em ordem. 
     */
    virtual ListaEncadeadaAbstrata<T>* emOrdem() const = 0;

    /**
     * @brief Lista chaves visitando a arvore em pre-ordem
     * @return Lista encadeada contendo as chaves em pre-ordem. 
     */
    virtual ListaEncadeadaAbstrata<T>* preOrdem() const = 0;

    /**
     * @brief Lista chaves visitando a arvore em pos-ordem
     * @return Lista encadeada contendo as chaves em pos ordem. 
     */
    virtual ListaEncadeadaAbstrata<T>* posOrdem() const = 0;
};

template<typename T>
ArvoreDeBuscaBinaria<T>::ArvoreDeBuscaBinaria():
    _raiz{} // instancia _raiz com nullptr. Equivalente a _raiz{nullptr}
{}

template<typename T>
ArvoreDeBuscaBinaria<T>::~ArvoreDeBuscaBinaria() = default; //atribui destrutor padrao do C++.

#endif

That is my file, i didn't finish to code, but everytime i try to write i keep getting the same error.

#define MINHAARVOREDEBUSCABINARIA_HPP

#include "ArvoreDeBuscaBinaria.hpp"
#include <cassert>
#include <utility>

/**
 * @brief Representa uma árvore binária de busca.
 * 
 * @tparam T O tipo de dado guardado na árvore.
 */
template<typename T>
class MinhaArvoreDeBuscaBinaria : public ArvoreDeBuscaBinaria<T>
{
    bool vazia()
    {
      if (ArvoreDeBuscaBinaria<T>::raiz == nullptr)
      {
        return true;
      }
      else return false;
    };

    int quantidade() 
    {
       return 5;
    };

    bool contem(T chave)
    {
        return true;
    }

    std::optional<int> altura(T chave)
    {
         return 5;
    };

    void inserir(T chave)
    {
      Nodo<T> * novo_nodo = new Nodo<T>();
      novo_nodo->chave = chave;
      novo_nodo->filhoDireita = nullptr;
      novo_nodo->filhoEsquerda = nullptr;

      Nodo<T>* raiz_da_arvore = ArvoreDeBuscaBinaria<T>::_raiz; //Pegando a raiz da árvore binária
      if(raiz_da_arvore == NULL)
      {
        raiz_da_arvore = novo_nodo;
      }
      

    };

    void remover(T chave)
    {

    };

    std::optional<int> filhoEsquerdaDe(T chave)
    {
      return 5;
    };

   std::optional<int> filhoDireitaDe(T chave)
    {
       return 5;
    };

    ListaEncadeadaAbstrata<T>* emOrdem() 
    {

    };

    ListaEncadeadaAbstrata<T>* preOrdem() 
    {

    };

    ListaEncadeadaAbstrata<T>* posOrdem()
    {

    };
};

#endif

These are the binary tests. i should not change it.

#include "MinhaArvoreDeBuscaBinaria.hpp"

TEST(ArvoreBinariaBuscaTest, Inicializacao)
{
    ArvoreDeBuscaBinaria<int>* const arvore{new MinhaArvoreDeBuscaBinaria<int>};

    ASSERT_TRUE(arvore->vazia());
    ASSERT_EQ(arvore->quantidade(), 0);

    ASSERT_TRUE(!arvore->contem(1));
    ASSERT_TRUE(!arvore->altura(1));
    ASSERT_TRUE(!arvore->filhoEsquerdaDe(1));
    ASSERT_TRUE(!arvore->filhoDireitaDe(1));
    
    ListaEncadeadaAbstrata<int>* lista{arvore->emOrdem()};
    ASSERT_TRUE(lista != nullptr);
    ASSERT_TRUE(lista->estaVazia());
    delete lista;

    lista = arvore->preOrdem();
    ASSERT_TRUE(lista != nullptr);
    ASSERT_TRUE(lista->estaVazia());
    delete lista;

    lista = arvore->posOrdem();
    ASSERT_TRUE(lista != nullptr);
    ASSERT_TRUE(lista->estaVazia());
    delete lista;
    
    delete arvore;
}

TEST(ArvoreBinariaBuscaTest, PreOrdem)
{
    ArvoreDeBuscaBinaria<int>* const arvore{new MinhaArvoreDeBuscaBinaria<int>};

    for (int const e : {5, 3, 7, 2, 4, 6, 9})
        arvore->inserir(e);

    ListaEncadeadaAbstrata<int>* const lista{arvore->preOrdem()};

    for (int const e : {5, 3, 2, 4, 7, 6, 9})
        ASSERT_EQ(lista->retiraDoInicio(), e);

    delete lista;

    delete arvore;
}

TEST(ArvoreBinariaBuscaTest, EmOrdem)
{
    ArvoreDeBuscaBinaria<int>* const arvore{new MinhaArvoreDeBuscaBinaria<int>};

    for (int const e : {5, 3, 7, 2, 4, 6, 9})
        arvore->inserir(e);

    ListaEncadeadaAbstrata<int>* const lista{arvore->emOrdem()};

    for (int const e : {2, 3, 4, 5, 6, 7, 9})
        ASSERT_EQ(lista->retiraDoInicio(), e);

    delete lista;

    delete arvore;
}

TEST(ArvoreBinariaBuscaTest, PosOrdem)
{
    ArvoreDeBuscaBinaria<int>* const arvore{new MinhaArvoreDeBuscaBinaria<int>};

    for (int const e : {5, 3, 7, 2, 4, 6, 9})
        arvore->inserir(e);

    ListaEncadeadaAbstrata<int>* const lista{arvore->posOrdem()};

    for (int const e : {2, 4, 3, 6, 9, 7, 5})
        ASSERT_EQ(lista->retiraDoInicio(), e);

    delete lista;

    delete arvore;
}

TEST(ArvoreBinariaBuscaTest, Insercao)
{
    ArvoreDeBuscaBinaria<int>* const arvore{new MinhaArvoreDeBuscaBinaria<int>};

    for (int const e : {5, 3, 7, 2, 4, 6, 9})
        arvore->inserir(e);

    ASSERT_TRUE(!arvore->vazia());
    ASSERT_EQ(arvore->quantidade(), 7);

    ASSERT_TRUE(arvore->contem(5));
    ASSERT_EQ(*arvore->altura(5), 2);
    ASSERT_EQ(*arvore->filhoDireitaDe(5), 7);
    ASSERT_EQ(*arvore->filhoEsquerdaDe(5), 3);

    ASSERT_TRUE(arvore->contem(3));
    ASSERT_EQ(*arvore->altura(3), 1);
    ASSERT_EQ(*arvore->filhoDireitaDe(3), 4);
    ASSERT_EQ(*arvore->filhoEsquerdaDe(3), 2);

    ASSERT_TRUE(arvore->contem(7));
    ASSERT_EQ(*arvore->altura(7), 1);
    ASSERT_EQ(*arvore->filhoDireitaDe(7), 9);
    ASSERT_EQ(*arvore->filhoEsquerdaDe(7), 6);

    ASSERT_TRUE(arvore->contem(2));
    ASSERT_EQ(*arvore->altura(2), 0);
    ASSERT_TRUE(!arvore->filhoDireitaDe(2));
    ASSERT_TRUE(!arvore->filhoEsquerdaDe(2));

    ASSERT_TRUE(arvore->contem(4));
    ASSERT_EQ(*arvore->altura(4), 0);
    ASSERT_TRUE(!arvore->filhoDireitaDe(4));
    ASSERT_TRUE(!arvore->filhoEsquerdaDe(4));

    ASSERT_TRUE(arvore->contem(6));
    ASSERT_EQ(*arvore->altura(6), 0);
    ASSERT_TRUE(!arvore->filhoDireitaDe(6));
    ASSERT_TRUE(!arvore->filhoEsquerdaDe(6));

    ASSERT_TRUE(arvore->contem(9));
    ASSERT_EQ(*arvore->altura(9), 0);
    ASSERT_TRUE(!arvore->filhoDireitaDe(9));
    ASSERT_TRUE(!arvore->filhoEsquerdaDe(9));

    delete arvore;  
}

TEST(ArvoreBinariaBuscaTest, Remocao)
{
    ArvoreDeBuscaBinaria<int>* arvore{new MinhaArvoreDeBuscaBinaria<int>};

    for (int const e : {5, 3, 7, 2, 4, 6, 9})
        arvore->inserir(e);

    //Testa remover folha
    arvore->remover(9);
    ASSERT_TRUE(!arvore->contem(9));
    ASSERT_EQ(arvore->quantidade(), 6);
    ASSERT_TRUE(!arvore->filhoDireitaDe(7));
    
    //Testa remover folha
    arvore->remover(6);
    ASSERT_TRUE(!arvore->contem(6));
    ASSERT_EQ(arvore->quantidade(), 5);
    ASSERT_TRUE(!arvore->filhoDireitaDe(7));
    ASSERT_TRUE(!arvore->filhoEsquerdaDe(7));
    
    //Testa remover raiz
    arvore->inserir(6);
    arvore->inserir(9);
    arvore->remover(5);
    ASSERT_TRUE(!arvore->contem(5));
    ASSERT_EQ(arvore->quantidade(), 6);
    ASSERT_EQ(*arvore->filhoDireitaDe(6), 7);
    ASSERT_EQ(*arvore->filhoEsquerdaDe(6), 3);
    ASSERT_EQ(*arvore->filhoDireitaDe(7), 9);
    ASSERT_TRUE(!arvore->filhoEsquerdaDe(7));

    //Testa remover nodo com filhoDireita sem descendente a esquerda
    arvore->inserir(5);
    ASSERT_EQ(*arvore->filhoDireitaDe(4), 5);
    ASSERT_EQ(*arvore->altura(6), 3);
    ASSERT_EQ(*arvore->altura(4), 1);
    arvore->remover(3);
    ASSERT_TRUE(!arvore->contem(3));
    ASSERT_EQ(arvore->quantidade(), 6);
    ASSERT_EQ(*arvore->filhoEsquerdaDe(6), 4);
    ASSERT_EQ(*arvore->filhoDireitaDe(6), 7);
    ASSERT_EQ(*arvore->altura(6), 2);

    ASSERT_EQ(*arvore->filhoDireitaDe(4), 5);
    ASSERT_EQ(*arvore->filhoEsquerdaDe(4), 2);

    delete arvore;

    // Testa esvaziar a árvore.

    arvore = new MinhaArvoreDeBuscaBinaria<int>;

    for (int const e : {3, 2, 4})
        arvore->inserir(e);

    ASSERT_EQ(arvore->quantidade(), 3);

    for (int const e : {3, 2, 4})
        arvore->remover(e);

    ASSERT_EQ(arvore->quantidade(), 0);

    // Testa remover item não contido na árvore.

    arvore->inserir(2);
    ASSERT_TRUE(arvore->contem(2));
    ASSERT_EQ(arvore->quantidade(), 1);

    arvore->remover(3);
    ASSERT_TRUE(arvore->contem(2));
    ASSERT_EQ(arvore->quantidade(), 1);

    delete arvore;
}

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


from Recent Questions - Stack Overflow https://ift.tt/3ff5h4i
https://ift.tt/eA8V8J

Read remote image and return in request

I have some images on a CDN.

However for security reasons I need some images to be loaded from the same subdomain as the page.

module.exports = function relayImage(req, res) {
  https.get("https://cdn.mysite.com/foo.jpg", (resp) => {
    const dataBlocks = []
    resp.on('data', data => dataBlocks.push(data));
    resp.on('end', err => {
       if(err){
         console.error(err)
         res.end()
         return
       }
       res.set({
         'accept-ranges': "bytes",
         'cache-control': resp.headers['cache-control'],
         'content-type': resp.headers['content-type'],
         'content-length': resp.headers['content-length'],
       });
       dataBlocks.forEach(data => res.send(data))
    })
  })
}

For some reason this only returns the first 2% of the image top



from Recent Questions - Stack Overflow https://ift.tt/377o5Oo
https://ift.tt/eA8V8J

Defining the axis values in an R plot

I know this seems trivial, but for some reason I´m stuck and I cannot figure out how to solve it. I have checked for the solution but with no success.

My data ("coefs_PA") is like this

structure(list(year = c(1998, 1999, 2000, 2001, 2002, 2003, 
2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 
2015, 2016, 2017, 2018, 2019), estimate = c(0.111, 0.081, -0.106, 
2.571, 0.606, -0.234, 0.325, 0.891, 0.062, 0.37, -0.041, 0.09, 
0.436, 0.08, -0.973, 0.147, -0.116, 0.602, 0.385, 0.274, 0.118, 
0.682), sd = c(0, 0.488, 0.411, 1.282, 0.473, 0.447, 0.427, 0.52, 
0.477, 0.394, 0.384, 0.379, 0.404, 0.416, 0.43, 0.419, 0.464, 
0.788, 0.456, 0.451, 0.427, 0.467)), row.names = c(NA, -22L), class = "data.frame")

and with the following code

library(Hmisc)

plot(coefs_PA$year, coefs_PA$estimate, xaxt='n', yaxt="n", xlab=NA, ylab=NA, pch=17,
     ylim=c(min(coefs_PA$estimate - coefs_PA$sd), max((coefs_PA$estimate + coefs_PA$sd))))
with (data = coefs_PA, expr = errbar(year,estimate, estimate+sd, estimate-sd, add=T, cap=0))

axis(2, las=2, at = c(-1:4, 1))
minor.tick(nx = 0, ny = 2, tick.ratio = 0.7)
axis(1, at=coefs_PA$fecha)
title(ylab=expression("Logit (P"[p]*")"), line=1.6, cex.lab=1)
mtext(side=3, line=0.2, "Year", font=2, cex=1.0)

I get the following figure

enter image description here

I want the values of the x-axis to be 2000, 2005, 2010, 2015 and the remaining tick marks to be blank. I have tried to get it with this

axis(1, at=coefs_fechas_PA$fecha, labels= c(rep("",2), "2000", rep("",4), "2005", rep("",4), "2010", rep("",4), "2015", rep("",4))))

but it didn´t work.

Any hint will be more than welcome.



from Recent Questions - Stack Overflow https://ift.tt/377nZ9u
https://ift.tt/3rQv5sv

How to create menu items combining icon and text with vuetify 2.x?

I need to create a menu with some checked menu items. This is for toggle options.

The check icon should be shown and removed in front of the menu item when the item is clicked. Ideally, the menu should not close when the toggle menus are selected.

Making a dialog with switches would be inconvenient because it would require multiple clicks to perform the operation and the user wouldn't have a direct feedback on the effect. The toggle menu items modify the filtering rule of a displayed list.

My current code has the toggle menu items but there is no feedback for the user with check icons.

Not sure if checked menus are compatible with material design.

Edit: Adding an icon to a menu item is very simple.

          <v-list-item @click="maskZero">
            <v-list-item-title>
              
            </v-list-item-title>
            <v-list-item-icon v-bind:class="showWhenMaskZero">
              <v-icon> mdi-check </v-icon>
            </v-list-item-icon>
          </v-list-item>
  // . . .
  computed: {
    showWhenMaskZero() {
      return {
        "d-none": !this.$store.maskZero,
      };
    },
  },

What is not working is toggling its visibility. The showWhenMaskZero() function is only called the first time the menu is displayed.

How could I force an update of the menu content ?



from Recent Questions - Stack Overflow https://ift.tt/3j4uoYG
https://ift.tt/eA8V8J

Using script to search Gmail subject line for a cells value, then forward email

What I am attempting to do is to use some script to automate locating then forward to a specific email without having to switch over to Gmail to manually forward this on, However I cannot use the auto forward built into Gmail due to only certain emails needing to be sent, There are also multiple emails with the same reference number in the subject field unless I add in the constant then there is only one,

The emails subject get sent to me in the following format a unique reference number followed by hyphen then the constant (123456 - Constant),

Currently I am attempting to use the built in Gmail search via reference number + Constant, The reference number is stored in a google sheets cell, I have then been tagging on the "constant" within the script.

However despite using "" which to my understanding is for an exact match, this is forwarding multiple entries with different reference numbers,

Currently the code I am attempting to use is

function Search2() {

  var sheet   = SpreadsheetApp.getActiveSheet(); //gets sheet
  var row     = 1;
  var col     = 8;
  var REF = sheet.getRange(row, col).getValue(); //gets value of the unique reference number

  var threads = GmailApp.search('subject:"REF"+"CONSTANT"') //adds in the constant for the search
  for (var h = 0; h < threads.length; h++) {
    var messages = threads[h].getMessages();
    for (var i = 0; i < messages.length; i++) {
              Logger.log(messages[i].getSubject());
                messages[i].forward("EMAIL ADDRESS", {
          cc: "",
          bcc: ""
          });     
      
  }
}
}

My current line of thought is that there must be something not working correctly when I combine the reference and the constant causing it to not look for an exact match and returning closest matches.

Any assistance would be appreciated,

Update 30/07/2021 @ 18:46 - I did a bit of testing replacing the "REF" directly with the reference number works and returns 1 result forwarded, This leads my thought process to there is an issue with the REF variable pulling through the correct value.



from Recent Questions - Stack Overflow https://ift.tt/3lm5Eh4
https://ift.tt/eA8V8J

Integrating purchased bootstrap template in Reactjs, But js effects are not working

I have integrated my react-js with purchased Template, and design works perfectly, But effects which will be initiated from custom.js are not working. Like toggle dropdown on click, Setting current nav-item as active.

I just imported custom.js file to index.html

I am new to react-js, so need help from our community.

$("a.close").removeAttr("href").on('click', function(){
        function slideFade(elem) {
            var fadeOut = { opacity: 0, transition: 'opacity 0.5s' };
            elem.css(fadeOut).slideUp();
        }
        slideFade($(this).parent());
    });

    /*--------------------------------------------------*/
    /*  Notification Dropdowns
    /*--------------------------------------------------*/
    $(".header-notifications").each(function() {
        var userMenu = $(this);
        var userMenuTrigger = $(this).find('.header-notifications-trigger a');

        $(userMenuTrigger).on('click', function(event) {
            event.preventDefault();

            if ( $(this).closest(".header-notifications").is(".active") ) {
                close_user_dropdown();
            } else {
                close_user_dropdown();
                userMenu.addClass('active');
            }
        });
    });

    // Closing function
    function close_user_dropdown() {
        $('.header-notifications').removeClass("active");
    }

    // Closes notification dropdown on click outside the conatainer
    var mouse_is_inside = false;

    $( ".header-notifications" ).on( "mouseenter", function() {
      mouse_is_inside=true;
    });
    $( ".header-notifications" ).on( "mouseleave", function() {
      mouse_is_inside=false;
    });

    $("body").mouseup(function(){
        if(! mouse_is_inside) close_user_dropdown();
    });

    // Close with ESC
    $(document).keyup(function(e) { 
        if (e.keyCode == 27) {
            close_user_dropdown();
        }
    });
<!-- This is from My header.js from react render method -->

 <header id="header-container" className="fullwidth"> 
    <div id="header">
    <div className="container">
        
        <div className="left-side">
            
            <div id="logo">
            <img src={InspizyLogos} alt=""/>
                <a href="index.html">
                   
                    </a>
            </div>

            {/* <!-- Main Navigation --> */}
            <nav id="navigation">
                <ul id="responsive">

                    <li><a href="hzd" className="current">Home</a>
                        <ul className="dropdown-nav">
                            <li><a href="#">Home 1</a></li>
                            <li><a href="index-2.html">Home 2</a></li>
                            <li><a href="index-3.html">Home 3</a></li>
                        </ul>
                    </li>

                    <li><a href="#">Find Work</a>
                        <ul className="dropdown-nav">
                            <li><a href="#">Browse Jobs</a>
                                <ul className="dropdown-nav">
                                    <li><a href="jobs-list-layout-full-page-map.html">Full Page List + Map</a></li>
                                    <li><a href="jobs-grid-layout-full-page-map.html">Full Page Grid + Map</a></li>
                                    <li><a href="jobs-grid-layout-full-page.html">Full Page Grid</a></li>
                                    <li><a href="jobs-list-layout-1.html">List Layout 1</a></li>
                                    <li><a href="jobs-list-layout-2.html">List Layout 2</a></li>
                                    <li><a href="jobs-grid-layout.html">Grid Layout</a></li>
                                </ul>
                            </li>
                            <li><a href="#">Browse Tasks</a>
                                <ul className="dropdown-nav">
                                    <li><a href="tasks-list-layout-1.html">List Layout 1</a></li>
                                    <li><a href="tasks-list-layout-2.html">List Layout 2</a></li>
                                    <li><a href="tasks-grid-layout.html">Grid Layout</a></li>
                                    <li><a href="tasks-grid-layout-full-page.html">Full Page Grid</a></li>
                                </ul>
                            </li>
                            <li><a href="browse-companies.html">Browse Companies</a></li>
                            <li><a href="single-job-page.html">Job Page</a></li>
                            <li><a href="single-task-page.html">Task Page</a></li>
                            <li><a href="single-company-profile.html">Company Profile</a></li>
                        </ul>
                    </li>

                    <li><a href="#">For Employers</a>
                        <ul className="dropdown-nav">
                            <li><a href="#">Find a Freelancer</a>
                                <ul className="dropdown-nav">
                                    <li><a href="freelancers-grid-layout-full-page.html">Full Page Grid</a></li>
                                    <li><a href="freelancers-grid-layout.html">Grid Layout</a></li>
                                    <li><a href="freelancers-list-layout-1.html">List Layout 1</a></li>
                                    <li><a href="freelancers-list-layout-2.html">List Layout 2</a></li>
                                </ul>
                            </li>
                            <li><a href="single-freelancer-profile.html">Freelancer Profile</a></li>
                            <li><a href="dashboard-post-a-job.html">Post a Job</a></li>
                            <li><a href="dashboard-post-a-task.html">Post a Task</a></li>
                        </ul>
                    </li>

                    <li><a href="#">Dashboard</a>
                        <ul className="dropdown-nav">
                            <li><a href="dashboard.html">Dashboard</a></li>
                            <li><a href="dashboard-messages.html">Messages</a></li>
                            <li><a href="dashboard-bookmarks.html">Bookmarks</a></li>
                            <li><a href="dashboard-reviews.html">Reviews</a></li>
                            <li><a href="dashboard-manage-jobs.html">Jobs</a>
                                <ul className="dropdown-nav">
                                    <li><a href="dashboard-manage-jobs.html">Manage Jobs</a></li>
                                    <li><a href="dashboard-manage-candidates.html">Manage Candidates</a></li>
                                    <li><a href="dashboard-post-a-job.html">Post a Job</a></li>
                                </ul>
                            </li>
                            <li><a href="dashboard-manage-tasks.html">Tasks</a>
                                <ul className="dropdown-nav">
                                    <li><a href="dashboard-manage-tasks.html">Manage Tasks</a></li>
                                    <li><a href="dashboard-manage-bidders.html">Manage Bidders</a></li>
                                    <li><a href="dashboard-my-active-bids.html">My Active Bids</a></li>
                                    <li><a href="dashboard-post-a-task.html">Post a Task</a></li>
                                </ul>
                            </li>
                            <li><a href="dashboard-settings.html">Settings</a></li>
                        </ul>
                    </li>

                    <li><a href="#">Pages</a>
                        <ul className="dropdown-nav">
                            <li><a href="pages-blog.html">Blog</a></li>
                            <li><a href="pages-pricing-plans.html">Pricing Plans</a></li>
                            <li><a href="pages-checkout-page.html">Checkout Page</a></li>
                            <li><a href="pages-invoice-template.html">Invoice Template</a></li>
                            <li><a href="pages-user-interface-elements.html">User Interface Elements</a></li>
                            <li><a href="pages-icons-cheatsheet.html">Icons Cheatsheet</a></li>
                            <li><a href="pages-login.html">Login & Register</a></li>
                            <li><a href="pages-404.html">404 Page</a></li>
                            <li><a href="pages-contact.html">Contact</a></li>
                        </ul>
                    </li>

                </ul>
            </nav>
            <div className="clearfix"></div>
            {/* <!-- Main Navigation / End --> */}
            
        </div>
        {/* <!-- Left Side Content / End --> */}


        {/* <!-- Right Side Content / End --> */}
        <div className="right-side">

            {/* <!--  User Notifications --> */}
            <div className="header-widget hide-on-mobile">
                
                {/* <!-- Notifications --> */}
                <div className="header-notifications active">

                    {/* <!-- Trigger --> */}
                    <div className="header-notifications-trigger">
                        <a href="#"><i className="icon-feather-bell"></i><span>4</span></a>
                    </div>

                    {/* <!-- Dropdown --> */}
                    <div className="header-notifications-dropdown">

                        <div className="header-notifications-headline">
                            <h4>Notifications</h4>
                            <button className="mark-as-read ripple-effect-dark" title="Mark all as read" data-tippy-placement="left">
                                <i className="icon-feather-check-square"></i>
                            </button>
                        </div>

                        <div className="header-notifications-content">
                            <div className="header-notifications-scroll" data-simplebar>
                                <ul>
                                    {/* <!-- Notification --> */}
                                    <li className="notifications-not-read">
                                        <a href="dashboard-manage-candidates.html">
                                            <span className="notification-icon"><i className="icon-material-outline-group"></i></span>
                                            <span className="notification-text">
                                                <strong>Michael Shannah</strong> applied for a job <span className="color">Full Stack Software Engineer</span>
                                            </span>
                                        </a>
                                    </li>

                                    {/* <!-- Notification --> */}
                                    <li>
                                        <a href="dashboard-manage-bidders.html">
                                            <span className="notification-icon"><i className=" icon-material-outline-gavel"></i></span>
                                            <span className="notification-text">
                                                <strong>Gilbert Allanis</strong> placed a bid on your <span className="color">iOS App Development</span> project
                                            </span>
                                        </a>
                                    </li>

                                    {/* <!-- Notification --> */}
                                    <li>
                                        <a href="dashboard-manage-jobs.html">
                                            <span className="notification-icon"><i className="icon-material-outline-autorenew"></i></span>
                                            <span className="notification-text">
                                                Your job listing <span className="color">Full Stack PHP Developer</span> is expiring.
                                            </span>
                                        </a>
                                    </li>

                                    {/* <!-- Notification --> */}
                                    <li>
                                        <a href="dashboard-manage-candidates.html">
                                            <span className="notification-icon"><i className="icon-material-outline-group"></i></span>
                                            <span className="notification-text">
                                                <strong>Sindy Forrest</strong> applied for a job <span className="color">Full Stack Software Engineer</span>
                                            </span>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </div>

                    </div>

                </div>
                
                {/* <!-- Messages --> */}
                <div className="header-notifications">
                    <div className="header-notifications-trigger">
                        <a href="#"><i className="icon-feather-mail"></i><span>3</span></a>
                    </div>

                    {/* <!-- Dropdown --> */}
                    <div className="header-notifications-dropdown">

                        <div className="header-notifications-headline">
                            <h4>Messages</h4>
                            <button className="mark-as-read ripple-effect-dark" title="Mark all as read" data-tippy-placement="left">
                                <i className="icon-feather-check-square"></i>
                            </button>
                        </div>

                        <div className="header-notifications-content">
                            <div className="header-notifications-scroll" data-simplebar>
                                <ul>
                                    {/* <!-- Notification --> */}
                                    <li className="notifications-not-read">
                                        <a href="dashboard-messages.html">
                                            <span className="notification-avatar status-online"><img src="images/user-avatar-small-03.jpg" alt=""/></span>
                                            <div className="notification-text">
                                                <strong>David Peterson</strong>
                                                <p className="notification-msg-text">Thanks for reaching out. I'm quite busy right now on many...</p>
                                                <span className="color">4 hours ago</span>
                                            </div>
                                        </a>
                                    </li>

                                    {/* <!-- Notification --> */}
                                    <li className="notifications-not-read">
                                        <a href="dashboard-messages.html">
                                            <span className="notification-avatar status-offline"><img src="images/user-avatar-small-02.jpg" alt=""/></span>
                                            <div className="notification-text">
                                                <strong>Sindy Forest</strong>
                                                <p className="notification-msg-text">Hi Tom! Hate to break it to you, but I'm actually on vacation until...</p>
                                                <span className="color">Yesterday</span>
                                            </div>
                                        </a>
                                    </li>

                                    {/* <!-- Notification --> */}
                                    <li className="notifications-not-read">
                                        <a href="dashboard-messages.html">
                                            <span className="notification-avatar status-online"><img src="images/user-avatar-placeholder.png" alt=""/></span>
                                            <div className="notification-text">
                                                <strong>Marcin Kowalski</strong>
                                                <p className="notification-msg-text">I received payment. Thanks for cooperation!</p>
                                                <span className="color">Yesterday</span>
                                            </div>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </div>

                        <a href="dashboard-messages.html" className="header-notifications-button ripple-effect button-sliding-icon">View All Messages<i className="icon-material-outline-arrow-right-alt"></i></a>
                    </div>
                </div>

            </div>
            {/* <!--  User Notifications / End --> */}

            {/* <!-- User Menu --> */}
            <div className="header-widget">

                {/* <!-- Messages --> */}
                <div className="header-notifications user-menu">
                    <div className="header-notifications-trigger">
                        <a href="#">
                            <div className="user-avatar status-online"><img src="images/user-avatar-small-01.jpg" alt="" />
                                </div>
                                </a>
                    </div>

                    <div className="header-notifications-dropdown">

                        <div className="user-status">

                            <div className="user-details">
                                <div className="user-avatar status-online"><img src="images/user-avatar-small-01.jpg" alt=""/></div>
                                <div className="user-name">
                                    Tom Smith <span>Freelancer</span>
                                </div>
                            </div>
                            
                            <div className="status-switch" id="snackbar-user-status">
                                <label className="user-online current-status">Online</label>
                                <label className="user-invisible">Invisible</label>
                                <span className="status-indicator" aria-hidden="true"></span>
                            </div>  
                    </div>
                    
                    <ul className="user-menu-small-nav">
                        <li><a href="dashboard.html"><i className="icon-material-outline-dashboard"></i> Dashboard</a></li>
                        <li><a href="dashboard-settings.html"><i className="icon-material-outline-settings"></i> Settings</a></li>
                        <li><a href="index-logged-out.html"><i className="icon-material-outline-power-settings-new"></i> Logout</a></li>
                    </ul>

                    </div>
                </div>


            <span className="mmenu-trigger">
                <button className="hamburger hamburger--collapse" type="button">
                    <span className="hamburger-box">
                        <span className="hamburger-inner"></span>
                    </span>
                </button>
            </span>

        </div>
        {/* <!-- Right Side Content / End --> */}

    </div>
</div>
</div>

</header>
<div className="clearfix"></div>


from Recent Questions - Stack Overflow https://ift.tt/3lij51T
https://ift.tt/eA8V8J

KVO on SKView is not being called

I am trying to do KVO on an property of SKView but its not working.

I have tried it with .frame and it works like a charm, so why not also on .window ?

To clarify, I am using SpriteView in a SwiftUI app and I am trying to get the bounds of the View. What I am after is to get the following before the App starts;

print (self.convertPoint(fromView: .zero) ). When I use this in

override func didMove

I'll get Nan/NaN. However Apple Code Level Support said this about using SpriteView and getting the bounds of a view.

The reason you are receiving NaN is that you are calling these methods before the underlying SKView has been actually presented by SwiftUI, which is an event that you have no visibility into, and no way to call code when it happens.

However, when this event does occur, the SKScene’s view property will have it’s window set from nil to a UIWindow. Therefore, you could use KVO to observe when the window property is changed, and then make your calls to convertPoint once there is a non-nil window.

I have so far this:

override func didMove(to view: SKView) {
    observe.observe(object: view )
}

class Observer:SKScene {
    var kvoToken: NSKeyValueObservation?
    
    func observe(object: SKView) {
    kvoToken = object.observe(\.window , options: [ .new] ) { (object, change) in

        guard let value = change.newValue else { return }
        print("New value is: \(value)")
        print ("NEW", self.convertPoint(fromView: .zero) )
        
      }
    }
    
  deinit {
    kvoToken?.invalidate()
  }
}

I have also tried to add an observer like so :

NotificationCenter.default.addObserver(view.window, selector: #selector(test(_:)), name: NSNotification.Name(rawValue: "TestNotification"), object: nil)

The above doesn't seem to do anything. So I am kinda stuck, any help would be appreciated.



from Recent Questions - Stack Overflow https://ift.tt/3i9KPDM
https://ift.tt/eA8V8J

Why does the parallel command not work with backslashes when taking input from file?

Consider the following file saved as commands.txt

ls \
&& pwd

ls \
&& pwd

Now,

bash commands.txt

works as expected to give

LICENSE
/home/username/utilities
LICENSE
/home/username/utilities

but

parallel < commands.txt

gives the error

/bin/bash: -c: line 0: syntax error near unexpected token `&&'
/bin/bash: -c: line 0: `&& pwd'
ls: cannot access '\': No such file or directory
/bin/bash: -c: line 0: syntax error near unexpected token `&&'
/bin/bash: -c: line 0: `&& pwd

Why do multiple lines with the same command separated by \ not seem to work with parralel as such?



from Recent Questions - Stack Overflow https://ift.tt/2WEMRn6
https://ift.tt/eA8V8J

Opening a Sheet with buttons generated with a ForEach Loop

I have a view where a list of buttons is generated using a ForEach loop, the data is a list of email addresses for a given contact. The number of email addresses are variable. On pressing an email, I want to open a sheet showing a email view and pass the email address selected to sheet. I followed the answer to this question here that showed how to do sheets with a ForEach button loop, but I ran into a strange issue, when I add the .sheet call to my code, it makes the ForEach loop buttons all become button, and clicking on it opens the sheet, but always passes the last email address in the list to the sheet, am I missing something or is this a bug in swiftUI?

Edit: Based on feedback from Yrb (Thanks for the feedback BTW) I have edited it my code so its modular enough that you can run it without any editing

import SwiftUI
import UIKit
import MessageUI
import CoreLocation

struct TestEmailAddress { // --> We also have a Email Address struct as they can have labels and we want to display them
    var label: String
    var email: String
}

extension Int: Identifiable {
    public var id: Int {self}
}

struct MailView: UIViewControllerRepresentable {

@Binding var isShowing: Bool
@Binding var result: Result<MFMailComposeResult, Error>?
var recipients: [String]
var messageBody = ""

class Coordinator: NSObject, MFMailComposeViewControllerDelegate {

    @Binding var isShowing: Bool
    @Binding var result: Result<MFMailComposeResult, Error>?

    init(isShowing: Binding<Bool>,
         result: Binding<Result<MFMailComposeResult, Error>?>) {
        _isShowing = isShowing
        _result = result
    }

    func mailComposeController(_ controller: MFMailComposeViewController,
                               didFinishWith result: MFMailComposeResult,
                               error: Error?) {
        defer {
            isShowing = false
        }
        guard error == nil else {
            self.result = .failure(error!)
            return
        }
        self.result = .success(result)
    }
}

func makeCoordinator() -> Coordinator {
    return Coordinator(isShowing: $isShowing,
                       result: $result)
}

func makeUIViewController(context: UIViewControllerRepresentableContext<MailView>) -> MFMailComposeViewController {
    let vc = MFMailComposeViewController()
    vc.setToRecipients(recipients)
    vc.setMessageBody(messageBody, isHTML: true)
    vc.mailComposeDelegate = context.coordinator
    return vc
}

func updateUIViewController(_ uiViewController: MFMailComposeViewController,
                            context: UIViewControllerRepresentableContext<MailView>) {

}
}

struct RolodexMailViewTest: View {
    @State var testEmails: [TestEmailAddress]
    //Alert Stuff
    @State private var showAlert = false
    //Mail Stuff
    @State private var result: Result<MFMailComposeResult, Error>? = nil
    @State private var isShowingMailView = false
    @State private var selectedEmail: Int? = nil
    var body: some View {
        Section() {
            ForEach(0 ..<  self.testEmails.count) { email in // --> here, we display all the numbers we got
                if !MFMailComposeViewController.canSendMail() {
                    Button(action: { self.showAlert = true
                        self.selectedEmail = email
                    }) {
                        VStack(alignment: .leading, spacing: 5) {
                            Text(self.testEmails[email].label.isEmpty ? "Email" : self.testEmails[email].label)
                                .font(.system(.subheadline))
                                .foregroundColor(.secondary)
                            Text(self.testEmails[email].email)
                        }
                    }
                }
                else {
                    Button(action: { self.isShowingMailView = true
                            self.selectedEmail = email }) {
                        VStack(alignment: .leading, spacing: 5) {
                            Text(self.testEmails[email].label.isEmpty ? "Email" : self.testEmails[email].label)
                                .font(.system(.subheadline))
                                .foregroundColor(.secondary)
                            Text(self.testEmails[email].email)
                        }
                    }
                }
            }
        }
        .sheet(item: self.$selectedEmail) { selectedEmail in
            MailView(isShowing: self.$isShowingMailView, result: self.$result, recipients: [self.testEmails[selectedEmail].email], messageBody: "Hi \("John Q Test"),\r\n")
        }
        .alert(isPresented: $showAlert) { ()
            return Alert(title: Text("Unable to Send Mail"), message: Text("Please Setup Your Mail App"), dismissButton: .default(Text("Ok")))
        }
    }
}

let testEmailArray: [TestEmailAddress] = [TestEmailAddress(label: "Work", email: "johnqtest@work.com"), TestEmailAddress(label: "Home", email: "johnqtest@home.com")]

struct TestUIView_Previews: PreviewProvider {
    static var previews: some View {
        Form() {
            RolodexMailViewTest(testEmails: testEmailArray)
        }
    }
}

When the .sheet is commented in the buttons looks like this: View When .sheet is commented out

However as soon as you comment it out, it becomes one button like this: View When .sheet is included



from Recent Questions - Stack Overflow https://ift.tt/3j9LtjZ
https://ift.tt/eA8V8J

OprnGl in Python, moving camera in 3d [duplicate]

Am working on a simple 3d game to improve my python skills, however ran into a problem in moving the camera in 3d.

glRotatef(mouseMove[0]*0.1, 0.0, 1.0, 0.0) glRotatef(mouseMove[1]*0.1, 1.0, 0.0, 0.0)

when the above two operations are combined they create a warping effect. I think they need to be separated by poping/push the matrix to separate their effects on the player viewpoint. I've tried everything but have been unable to correct this. Full code below, if anyone can correct the obvious mistake I've made would be much appreciated. full code below.

while run:
    pygame.mouse.set_cursor((8,8),(0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE or event.key == pygame.K_RETURN:
                run = False
            if event.key == pygame.K_PAUSE or event.key == pygame.K_p:
                paused = not paused
                pygame.mouse.set_pos(displayCenter) 
        if not paused: 
            if event.type == pygame.MOUSEMOTION:
                mouseMove = [event.pos[i] - displayCenter[i] for i in range(2)]
            pygame.mouse.set_pos(displayCenter)    

    if not paused:
        # get keys
        keypress = pygame.key.get_pressed()
        # mouseMove = pygame.mouse.get_rel()

        glLoadIdentity()

        up_down_angle += mouseMove[1]*0.1
        glRotatef(up_down_angle, 1.0, 0.0, 0.0)

        # init the view matrix
        glPushMatrix()
        glLoadIdentity()   

        # apply the movment 
        if keypress[pygame.K_w]:
            glTranslatef(0,0, 5)

        if keypress[pygame.K_s]:
            glTranslatef(0,0, -5)       

        if keypress[pygame.K_d]:
            glTranslatef(-5,0,0)

        if keypress[pygame.K_a]:
            glTranslatef(5,0,0)

        if keypress[pygame.K_c]:
            glTranslatef(0,5,0)

        if keypress[pygame.K_x]:
            glTranslatef(0,-5,0)
  

        # apply the left and right rotation
        glRotatef(mouseMove[0]*0.1, 0.0, 1.0, 0.0)
        glRotatef(mouseMove[1]*0.1, 1.0, 0.0, 0.0)

        # multiply the current matrix by the get the new view matrix and store the final
        glMultMatrixf(viewMatrix)
        viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)

        # apply view matrix
        glPopMatrix()
        glMultMatrixf(viewMatrix)
 
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        draw_cross_hairs(screen)
        pygame.display.flip()
        pygame.time.wait(10)

pygame.quit()



from Recent Questions - Stack Overflow https://ift.tt/3zUnUSO
https://ift.tt/eA8V8J

2021-07-30

Why my "Certificate" object and "Ingress" both are creating Certificates?

Why my "Certificate" object and "Ingress" both are creating Certificates ?

apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: blog-app-crt
spec:
  secretName: blog-app-crt-sec
  issuerRef:
    kind: ClusterIssuer
    name: letsencrypt-prod
  commonName: blog.mydomain.com
  dnsNames:
    - blog.mydomain.com




apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    # Email address used for ACME registration
    email: myemailid@gmail.com
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      # Name of a secret used to store the ACME account private key
      name: letsencrypt-production-private-key
    # Add a single challenge solver, HTTP01 using nginx
    solvers:
    - http01:
        ingress:
          class: nginx


apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx                      
    nginx.ingress.kubernetes.io/rewrite-target: /$1         
    cert-manager.io/cluster-issuer: "letsencrypt-prod"       
    nginx.ingress.kubernetes.io/ssl-redirect: 'true'        

spec:
  tls:
    - hosts:                                                
        - blog.mydomain.com
      secretName: blog-app-crt-sec                      
      
  rules:                                                    
    - host: blog.mydomain.com                                         
      http:                                                 
        paths:                                              
          - pathType: Prefix
            path: "/?(.*)"                                    
            backend:
              service:
                name: app-1-endpoint
                port: 
                  number: 5000                            
          - pathType: Prefix
            path: "/tribute/?(.*)"
            backend:
              service:
                name: app-2-endpoint
                port: 
                  number: 5001

When I create above objects, it is creating 2 Certificate ojects, both pointing to same secret.

  1. blog-app-crt-sec
  2. blog-app-crt

How can I create Only 1 Certificate ? If I create only a ClusterIssuer without any custom certificate, then of course that will solve the issue, but I want to create a Custom certificate to control the renewal stuff.



from Recent Questions - Stack Overflow https://ift.tt/2WBzh3R
https://ift.tt/eA8V8J

Keep getting an error w, h = small_image.shape[:-1] AttributeError: 'NoneType' object has no attribute 'shape'

I have very little knowledge and am trying to learn python, and have been doing pretty well.

Until!

When trying to match the image's, I get w, h = small_image.shape[:2]

AttributeError: 'NoneType' object has no attribute 'shape'

I have the image in the correct path, but keep receiving the error above, have debugged it many times and searched all over the internet for a answer.

The only answer I found was check the path's which i have and they seem to be correct.

Please excuse how little knowledge I have. I am just trying to learn any pointers would be appreciated.

def __init__(self, handle=None):
        self._handle = handle
        self._item_memory = {}
        self._item_area = (525, 227, 80, 275)

def match_image(self, largeImg, smallImg, threshold=0.1, debug=False):
      
        method = cv2.TM_SQDIFF_NORMED

        # Read the images from the file
        small_image = cv2.imread(smallImg)
        large_image = cv2.imread(largeImg)
        w, h = small_image.shape[:2]

        result = cv2.matchTemplate(small_image, large_image, method)

        # We want the minimum squared difference
        mn, _, mnLoc, _ = cv2.minMaxLoc(result)

        if (mn >= threshold):
            return False

        # Extract the coordinates of our best match
        x, y = mnLoc

        if debug:
            # Draw the rectangle:
            # Get the size of the template. This is the same size as the match.
            trows, tcols = small_image.shape[:2]

            # Draw the rectangle on large_image
            cv2.rectangle(large_image, (x, y),
                          (x+tcols, y+trows), (0, 0, 255), 2)

            # Display the original image with the rectangle around the match.
            cv2.imshow('output', large_image)

            # The image is only displayed if we call this
            cv2.waitKey(0)

        # Return coordinates to center of match
        return (x + (w * 0.5), y + (h * 0.5))`

    def find_item(self, item_name, threshold=0.15, max_tries=1, recapture=True):

        self.set_active()
        tries = 0
        res = False
        while not res and tries < max_tries:
            tries += 1

            if tries > 1:
                # Wait 1 second before re-trying
                self.wait(0.5)
                recapture = True

            if recapture:
                self.mouse_out_of_area(self._item_area)
                self.screenshot('item_area.png', region=self._item_area)

            res = self.match_image(
                'item_area.png', ('items/' + item_name + '.png'), threshold)

        if res is not False:
            x, y = res
            offset_x, offset_y = self._item_area[:2]
            item_pos = (offset_x + x, offset_y + y)
            # Remember location
            self._item_memory[item_name] = item_pos
            return item_pos
        else:
            return False


from Recent Questions - Stack Overflow https://ift.tt/3ibPbdt
https://ift.tt/eA8V8J

Parse date in c# the same way as it works in javascript..?

I'm developing an electron application with typescript and another backend application with c#. Now i'm trying to parse data from .xlsx Files in my electron app (javascript), and almost the same kind of data trough an XML API from my c# application in the backend..

Now the thing is, the receiving data has a timestamp formatted like this:

2021-07-22T11:31:43Z

I don't even recognize this format (well i'm not having a P.h.D in date time formats.. who would want that anyways.. -.-)

Now, when i parse this date in javascript by doing this:

moment.locale('de')
const date = moment('2021-07-22T11:31:43Z', 'DD.MM.YYYY HH:mm:ss') // haha i'm not even using the correct format to parse this... moment still works magically
const myDate = date.format() // format without params will return ISO 8601, no fractional seconds
// myDate will be = "2021-07-22T11:31:43+02:00" - pure magic

See that? Javascript is automatically adding the timezone information of my personal computer i'm running the code with (and he adds this magic "+02:00" at the end..)

Now, i try to do the same thing with c#:

var timestampDate = DateTime.Parse("2021-07-22T11:31:43Z");
var myDate = timestampDate.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
// myDate will be = "2021-07-22T11:31:43.000Z"

Not even close! Well... i'm not mad at c# that he doesn't know what i want - i want the timezone information to be added from my local system (doesn't matter what the original was)...

The only thing that matters is - that both implementations are delivering the same value when the same input is given! How can i achieve this?

The only thing i know is: my JS implementation with moment is much more accurate than the c# one - why? Because if i save the data with this string "2021-07-22T11:31:43+02:00", i'll get the correct displaying value out in my Frontend (trough GraphQL) which is "11:31"..

If i test the same thing again with the data coming from c#, it will display "13:31"... which is totally wrong..

Any help very appreciated :)



from Recent Questions - Stack Overflow https://ift.tt/3BWYQww
https://ift.tt/eA8V8J

How do I get a unicode character from an id in a variable?

I'm attempting to go and generate a file with every Unicode variable. I have been able to get unicode up to U+FFFF, however I need to get it up to U+231F4. I've tried searching for answers, but none of them work when the symbol id is in a variable instead of just typed.

Right now, I have this:

for (int i = 0; i < 143860; i++) {
            System.out.println((char)i);
        }

Instead of going up to U+231F4, it instead goes up to U+FFFF, and loops in the document it is printing to. How do I make it go to higher Unicode IDs?



from Recent Questions - Stack Overflow https://ift.tt/2VlKHb7
https://ift.tt/eA8V8J

Break a array into n chunks with overlapping start element

Hi everyone I have the following problem, I need to split an array into n even chunks, but the first element of every array except the first is the last element of the previous array. The last array can have a smaller number of elements if there aren't enough elements.

Input:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Expected output n=3:

[[1, 2, 3, 4, 5], [5, 6, 8, 9, 10], [10, 11]]

I need a solution in javascript but feel free to submit other languages, I will translate it and submit the solution in js.

Thanks in advance have a great day :)

My not working attempt, I couldn't figure out how to start with desired chunk number so I used chunk size here with intention to figure out chunk size from chunk number later

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const range = 4;
const res = [array.slice(0, range)];

let start = range;
let end = range * 2;
while (true) {
  console.log(start, end);
  res.push(array.slice(start, end));
  start += range;
  end += range;
  if (start >= array.length) {
    break;
  }
}

console.log(res);


from Recent Questions - Stack Overflow https://ift.tt/379fLxy
https://ift.tt/eA8V8J

How to not print a line if it and the following line starts with the same pattern?

I have a file.fa:

>ABC
TGTGTGT
AGAGAGA
TGTAGTA
>BDC
>DTR
>EDF
AGAGGTG
AGTGACA
CAGTGAC

I want to keep the lines without ">", and lines with ">" only if the immediate following line does not have ">":

>ABC
TGTGTGT
AGAGAGA
TGTAGTA
>EDF
AGAGGTG
AGTGACA
CAGTGAC

Looking at the answer for this post, I see that awk '/^>/{x=$0} !/^>/{if(x){print x;x=0;}}' file.fa prints out the header lines (with '>') that I want:

>ABC
>EDF

but how do I also get the lines of text without '>'?



from Recent Questions - Stack Overflow https://ift.tt/375xMwM
https://ift.tt/eA8V8J

SQL query containing cursors and cross join taking too long to execute

I have below SQL query as part of a stored procedure in SQL Server. This is taking almost 20 minutes and sometimes more to run.

I tried to replace cursors with CTE (Common Table Expression) and have all the clustered and nonclustered indexes on the tables used in the below query.

After having all that, it is still taking too long to finish execution. Any help on making the below query execute faster would be highly appreciated. Thank you all in advance for your valuable suggestions and comments.

 DECLARE @GroupID as INT;  
 DECLARE @MyCursor as CURSOR;  
   
 SET @MyCursor = CURSOR FOR  
     SELECT GroupID  
     FROM dbo.ThesGroup  
   
 OPEN @MyCursor;  
 FETCH NEXT FROM @MyCursor INTO @GroupID;  
   
 WHILE @@FETCH_STATUS = 0  
 BEGIN  
     INSERT INTO dbo.PartTagRel (PartID, PartTagID, IsThesaurus)  
         SELECT Rel.PartID, E.PartTagID2 AS PartTagID, 1 AS IsThesaurus   
         FROM dbo.PartTagRel AS Rel 
         JOIN  
             (SELECT R1.PartTagID AS PartTagID1, R2.PartTagID AS PartTagID2 
              FROM   
                  (SELECT TT.PartTag, TT.PartTagID 
                   FROM dbo.ThesTag AS TT 
                   JOIN dbo.Thesaurus As Th ON Th.ThesTagID = TT.ThesTagID  
                   WHERE Th.ThesGroupID = @GroupID) AS R1  
              CROSS JOIN  
                  (SELECT TT.PartTag, TT.PartTagID 
                   FROM dbo.ThesTag AS TT 
                   JOIN dbo.Thesaurus AS Th ON Th.ThesTagID = TT.ThesTagID  
                   WHERE Th.ThesGroupID = @GroupID) AS R2  
              WHERE 
                  R1.PartTagID <> R2.PartTagID) AS E ON E.PartTagID1 = Rel.PartTagID  
                                                     AND NOT EXISTS (SELECT * 
                                                                     FROM dbo.PartTagRel 
                                                                     WHERE PartID = Rel.PartID AND PartTagID = E.PartTagID2)  
  
     FETCH NEXT FROM @MyCursor INTO @GroupID;  
END  
   
CLOSE @MyCursor;  
DEALLOCATE @MyCursor;


from Recent Questions - Stack Overflow https://ift.tt/3ycGKnL
https://ift.tt/eA8V8J

Redux-Toolkit query interceptor

I'm trying to build an interceptor for cases when the access token becomes invalid with RTK Query. I've built it by an example in the docs, so that is looks as follows:

const baseQuery = fetchBaseQuery({
    baseUrl: BASE_URL,
    prepareHeaders: (headers, { getState }) => {
        const {
            auth: {
                user: { accessToken },
            },
        } = getState() as RootState;
        if (accessToken) {
            headers.set('authorization', `Bearer ${accessToken}`);
        }
        return headers;
    },
});

const baseQueryWithReauth: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> = async (
    args,
    api,
    extraOptions
) => {
    let result = await baseQuery(args, api, extraOptions);

    if (result.error && result.error.status === 401) {
        const refreshResult = await baseQuery('token/refresh/', api, extraOptions);

        if (refreshResult.data) {
            api.dispatch(tokenUpdated({ accessToken: refreshResult.data as string }));

            // retry the initial query
            result = await baseQuery(args, api, extraOptions);
        } else {
            api.dispatch(logout());
        }
    }
    return result;
};

export const baseApi = createApi({
    reducerPath: 'baseApi',
    baseQuery: baseQueryWithReauth,
    endpoints: () => ({}),
});

The problem is that the token/refresh/ expects a POST request with a refresh token its body and I can't figure out how to rebuilt this line const refreshResult = await baseQuery('token/refresh/', api, extraOptions); for it to accept parameters and make POST request.



from Recent Questions - Stack Overflow https://ift.tt/3BX2Lte
https://ift.tt/eA8V8J

My python virus generation code has an issue

I am trying to write a code that will count how many viruses there are after some time. Specifically, the original virus will begin to multiply after 120 sec, then every 60 sec, and it's 'offspring' follow the same pattern. With this, I am trying to find how many viruses there are after 879 seconds. The code below should execute every one second, and count how many times it executes until it reaches 879 seconds, but I keep getting an error. Can anyone help? Thanks

import time

maxtime = 10 

Arr = []

def virus():
    virus_count = 0
    count_time = 0
    time.sleep(1)
    while True:
        virus_count += 1
        count_time +=1
    if count_time > maxtime:
        Arr.append(count)
        print('There are', Arr, 'viruses')
        
while True:
    virus()
    
virus()


from Recent Questions - Stack Overflow https://ift.tt/3zJQvdq
https://ift.tt/eA8V8J

Laravel eloquent relation ship empty using select

My code

$users = Classroom::with(['students.classrooms',
                          'students' => function ($query) use ($search, $validated, $user) {
                              $query->select('name', 
                                             'firstname', 
                                              'email', 
                                              'nickname', 
                                              'locale', 
                                              'timezone', 
                                              'classroom_user.created_at', 
                                              'avatar', 
                                              'lastConnection', 
                                              'level', 
                                              'level_ja', 
                                              'classroom_user.classroom_id', 
                                              'classroom_user.user_id',
                                             );                                                         
                    },
                ])
                    ->whereIn('id', $classroom_ids)
                    ->get()
                    ->pluck('students')
                    ->flatten();

                $users = $users->paginate(10);

Using the select method on "students" relation make "classrooms" empty in the result, but if I don't use the select method, classrooms is not empty.

My question

How to add students.classrooms relation in the select method in "students" relation?



from Recent Questions - Stack Overflow https://ift.tt/2USOq0h
https://ift.tt/eA8V8J

TCP SOCKET - Stratum Server Reply - OpenEthereumPool

When I connect stratum server over /dev/tcp/host/port, I send json and got the right reply.

[water@Swan /tmp]$ exec 5<>/dev/tcp/127.0.0.1/8008;
[water@Swan /tmp]$ echo '{"jsonrpc":"2.0","id":1,"method":"eth_submitLogin","params":["0x00000a..27e"]}' >&5;
[water@Swan /tmp]$ cat <&5
{"id":1,"jsonrpc":"2.0","result":true}

However, when I try golang, python, PHP... any socket language, it won't work, the programme halts there. I tried many ways socket_recv($socket, $msg, 1000, MSG_DONTWAIT); or

 while (!feof($fp)){
    stream_set_timeout($fp, 1);
    echo fgets($fp, 1024);
}
    reply := make([]byte, 1024)

    _, err = conn.Read(reply)
    if err != nil {
        println("Write to server failed:", err.Error())
        os.Exit(1)
    }

    println("reply from server=", string(reply))

    conn.Close()

no of them seemed to work, but they all work on other TCP servers.

How can I get correct the Stratum TCP REPLY over the programme?

-- added full PHP

<?php

$a = array(
  "id" => 1,
  "jsonrpc" =>  "2.0",
  "method" => "eth_submitLogin",
  "params" => ["0x00000a006459...e"]
);

/*
$a = array(
"id" => 1, "jsonrpc" => "2.0", "method" => "eth_getWork"
);
*/

$b = json_encode($a);
$lb = strlen($b);
$h = "xk.com";

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$conn = socket_connect($socket, $h, 8008);
socket_set_nonblock($socket);

var_dump(socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR));

$w = socket_write($socket, $b, $lb);
var_dump($socket, $conn, $w);

sleep(2);
socket_recv($socket, $msg, 1000, MSG_DONTWAIT);
$err = socket_last_error($socket);
var_dump(socket_strerror($err));
socket_close($socket);
var_dump($msg);


from Recent Questions - Stack Overflow https://ift.tt/3ledMjM
https://ift.tt/eA8V8J

How to deserialize a Laravel Eloquent model, i.e. reverse toArray(), attributesToArray() or toJson()?

Laravel serialization documentation describes in detail how to get array / JSON representation of Eloquent models.

However, it doesn't currently say a word about reversing this: getting Eloquent models out of arrays / JSON.

How do I do this? Thanks!



from Recent Questions - Stack Overflow https://ift.tt/37etR0x
https://ift.tt/eA8V8J

Conditionally run CMake's CHECK_TYPE_SIZE

Is there a way to conditionally run CMake's CHECK_TYPE_SIZE command? CHECK_TYPE_SIZE is great for figuring out what the size of a struct is, but the problem is that over time someone might modify the header file with the struct to add new fields. Seems like it's an accident waiting to happen when someone updates the struct but forgets (or doesn't know to) blow away the CMake cache. Yes, you could put a note next to the struct to do a cache wipe if updated, but that doesn't really help when you have a multi-person project and someone else updated the header file.

I tried to do an unset(HAS_MYVAR CACHE) but that didn't seem to work as the function doesn't appear to be re-run. Any ideas?

CODE:

CHECK_TYPE_SIZE("my_struct_t" MY_STRUCT_SIZE)
message("Struct size is ${MY_STRUCT_SIZE})
$ cmake -S . -B /tmp/test
...
Struct size is 40
...

$ cd /tmp/test
$ make 
... (no message output) [expected]
$ <mod stuct size>
$ make
...
$ <Check size of ${MY_STRUCT_SIZE} - not changed>


from Recent Questions - Stack Overflow https://ift.tt/3j4bKA2
https://ift.tt/eA8V8J

Adding specific weights to edges through dictionary

I have two dictionaries of nodes with edges like below:

all_nodes_edges = {20101: (20102, 20201), 20102: (20101, 20103), 20103: (20102, 20104)}
nodes_with_weights =  {20101: 20201, 20119: 20219, 20201: (20301, 20101)}

I've created the graph and default weights for all the edges in the graph with the below code:

g = nx.Graph(all_nodes_edges)
nx.set_edge_attributes(g, 1, 'weight')

I'm trying to use the nodes_with_weights dict to create weights of 2 on specific edges. How do I achieve this?. Do I have to loop through the dictionary or can I just use a specific nx function?

Sorry kinda new to graphs.



from Recent Questions - Stack Overflow https://ift.tt/3BYG0Fo
https://ift.tt/eA8V8J

Can't to group by any rows from join

I have some tables and I joined them. But I need to count duplicate value in dl.order_guid and when group by, I have error Invalid expression in the select list (not contained in either an aggregate function or the GROUP BY clause). What am I doing wrong?

EDITED: I need to take all field by from, and show it. but when I'm trying to take, I have null or error

    Select guid.order_guid, count(*) from (
select dl.order_guid, dn.docnumber, dn.operdate,spa.date_from,spa.date_till, lda.akcia_num,dn.balance_kod,lda.parent_id,lda.parent_baseid, dn.otsr as otrs_now, sd.otsr as otsr_f1, sd.otsrf2 as otsr_f2,count(*)
      from table1 lda
      left join table2 dn on dn.id in (1,2) and dn.baseid=3
      left join table3 sd on sd.kod_dk = dn.dk_to
      left join table4 dl on  dl.docrecno=lda.parent_id and dl.baseid=lda.parent_baseid
      left join table5 spa on spa.id=lda.akcia_num
      where lda.akcia_num=573  and lda.parent_id in (1,2) and lda.parent_baseid= 3
) guid
      group by dl.order_guid
      having count(*)>1


from Recent Questions - Stack Overflow https://ift.tt/3xcnDsO
https://ift.tt/eA8V8J

Input value changes after clicking in another div with Jquery mask and vue

I'm trying to use the jquery mask and vue plugin, my code:

HTML:

<div class="mb-2">
    <label class="form-label">Salary</label>
        <input v-model="newEmployeeSalary" class="form-control moneyMask" id="employeeSalary" required>
</div>

JS:

$(document).ready(function($){
    $('.money').mask('000.000.000.000.000,00', {reverse: true});
});

The problem is that the inputed value changes after clicking in another div. Example :

Here I'm adding a money value, and the mask works perfectly:

The value is 2.000,0

Then, here I just clicked on the next input of the form and the Salary input mask breaks:

Values chagnes

My vue code:

data() {
    return {
      newContractTotalValue: '',
    }
},

I noticed that if I remove the v-model the error dissapers, but I need to use it. Can someone help me with that ?, I really have no idea what to do



from Recent Questions - Stack Overflow https://ift.tt/3BSEjce
https://ift.tt/2V60Cut

Loop through range over cells after each cell is copied print a sheet

I have made a sheet so someone can record some references for a pallet and a product code. I would the like them to be able to print this as a label I've made on another sheet when they have finished inputting all the data.

I need some code that allow me too loop through a range ("B5:last row") on sheet ("In (New)") and every time it finds a Ref it will copy the values from B(whatever) and the C value next to it and paste it on my label Sheet ("label") in the range ("K17:L17") then print the label out of the default printer.



from Recent Questions - Stack Overflow https://ift.tt/377rRHt
https://ift.tt/eA8V8J

Using scikit-learn NMF with ONE precomputed basis vector

I am using scikit-learn NMF to decompose a matrix I have to 2-4 bases/factors.

I have only 1 factor which I know/want to anchor, namely I know W(1) and I want to use that knowledge in my factorization process. Is that possible?

I know I can use scikit-learn NMF with a fixed H or W matrix (see this question and answer) in case I have the entire matrix fixed. But what if I only have one basis/factor fixed? Is that technically possible to achieve with this function?



from Recent Questions - Stack Overflow https://ift.tt/3777XMP
https://ift.tt/eA8V8J