Saturday, April 24, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Multiple route path with loop-free

Posted: 24 Apr 2021 08:23 AM PDT

I am using k shortest path to find k path,each path is loop free.

But i combine k path by using flow entry and group entry and that have loop.

How to find multiple path without loop?

Is there a way to Log-Out from all applications using Terminal in Android?

Posted: 24 Apr 2021 08:22 AM PDT

Lets say you have control over an Android Device remotely (NOT-ROOTED), using a reserse shell, and you want to log-out from all already logged in Applications. I don't care about which applications, If there is a way to FORCE it to Log-Out from everything. Any help?

PIC32MX340F128L

Posted: 24 Apr 2021 08:22 AM PDT

The MPC_READ in appendix A is a function of C code, which uses PIC32MX340F128L. The C code information shows below. • MPC_READ is called every millisecond • UART communication o Baud rate is 55555 o Transmits 9 bits, no parity, and one stop bit o Polarity is inverted Please answer the following questions to complete the C code information. Question 1

Explain associated Data declarations-0x92

Question 2

Explain associated Data declarations-0x93

Question 3

Explain associated Data declarations-0x94

Question 4

Please draw a flowchart of MPC_READ.

Appendix A

unsigned char MPC_Read(void) { static unsigned long data;

static short Arg = 0;      //number of elements or meters   static char Length = 0;   //number of bytes in the data stream  static unsigned short nn, pp;  static unsigned short state = LIMBO; //192=global, 193=element, 194=meter  unsigned char busy;    if (U1STA & 1)   {      LED1_ON      busy = 1;  }      else   {      LED1_OFF      busy = 0;      return;  }    while (U1STA & 1)   {      if ((U1STA & 2) > 0) U1STA &= ~2;  //reset overflow error      data = U1RXREG;       if (data >= 0x100)      {          if (data == SCALE) state = SCALE;          else if (data == ELEMENT) state = ELEMENT;           else if (data == METER) state = METER;           else state = LIMBO;          nn = 0;      }      else       {          switch(nn)          {              case 0: Arg = data;                       nn++;                      break;              case 1: Arg += data << 8;                       nn++;                      break;              case 2: Length = data;                      nn++;                      pp = 0;                      break;             default: nn = 4;                         }           if (nn >= 4)          {              if (state == SCALE)              {                  switch(pp)                  {                      case 0: SerialNumber = data;                              break;                                  case 1: SerialNumber += data << 8;                              break;                      case 2: SerialNumber += data << 16;                              break;                      case 3: SerialNumber += data << 24;                              break;                      case 4: VoltageM = data;                              break;                      case 5: VoltageM += data << 8;                               break;                          case 6: VoltageD = data;                               break;                      case 7: VoltageD += data << 8;                              break;                      case 8: CurrentM = data;                              break;                          case 9: CurrentM += data << 8;                              break;                      case 10:CurrentD = data;                              break;                          case 11:CurrentD += data << 8;                              break;                                  case 12:PowerM = data;                              break;                      case 13:PowerM += data << 8;                              break;                      case 14:PowerD= data;                              break;                      case 15:PowerD += data << 8;                              break;                      case 16:ShiftM = data;                              break;                      case 17:ShiftM += data << 8;                              break;                      case 18:ShiftD = data;                              break;                      case 19:ShiftD += data << 8;                              break;                      case 20:Nelements = data;                              break;                      case 21:Nmeters = data;                              break;                      case 22:Model = data;                              break;                                                  case 23:Model += data << 8;                              state = LIMBO;                              break;                  }                  pp++;              }              else if (state == ELEMENT)              {                  switch(pp)                  {                      case 0: Voltage[Arg] = data;                              break;                      case 1: Voltage[Arg] += data << 8;                              break;                      case 2: Current[Arg] = data;                              break;                      case 3: Current[Arg] += data << 8;                              break;                      case 4: Power[Arg] = data;                              break;                      case 5: Power[Arg] += data << 8;                              break;                      case 6: VoltAmp[Arg] = data;                              break;                      case 7: VoltAmp[Arg] += data << 8;                              break;                      case 8: Var[Arg] = data;                              break;                      case 9:    Var[Arg] += data << 8;                              break;                      case 10:PowerFactor[Arg] = data;                              break;                      case 11:PowerFactor[Arg] += data << 8;                              break;                      case 14:ElementToPhase[Arg] = data;                              break;                      case 15:ElementToMeter[Arg] = data;                              state = LIMBO;                              break;                  }                  pp++;                                          }              else if (state == METER)              {                  switch(pp)                  {                      case 0: WH_Count[Arg] = data;                              break;                      case 1: WH_Count[Arg] += data << 8;                              break;                      case 2: WH_Count[Arg] += data << 16;                              break;                      case 3: WH_Count[Arg] += data << 24;                              break;                      case 4: VAH_Count[Arg] = data;                              break;                      case 5: VAH_Count[Arg] += data << 8;                              break;                      case 6: VAH_Count[Arg] += data << 16;                              break;                      case 7: VAH_Count[Arg] += data << 24;                              break;                      case 8: VARH_Count[Arg] = data;                              break;                      case 9: VARH_Count[Arg] += data << 8;                              break;                      case 10:VARH_Count[Arg] += data << 16;                              break;                      case 11:VARH_Count[Arg] += data << 24;                              break;                      case 14:DeciWattPerCount = data;                              break;                      case 15:DeciWattPerCount += data << 8;                              break;                      case 16:Frequency = data;                              break;                      case 17:Frequency += data << 8;                              break;                      case 21:state = LIMBO;                              break;                  }                  pp++;              }          }                  }      //U1TXREG = data;    // resend for testing purposes. Not otherwise functional          }      return busy;                      

}

CastList<dynamic,String> is not an subtype of type String even after placing cast() flutter dart

Posted: 24 Apr 2021 08:22 AM PDT

Trying to parse json response, works fine with string, int type values. But getting error when having list as values even after placing cast(). Error image is placed at bottom

class ChennaiModel{    final int ra;    final String ci;    final bool lo;    final List<String> ab;      ChennaiModel({      this.ra,this.ci,this.lo,this.ab    });        factory ChennaiModel.fromJson(Map<String,dynamic>parsedjson){  var streetsFromJson  = parsedjson['streets'];   List<String> streetsList = streetsFromJson.cast<String>();      return new ChennaiModel(           ra:parsedjson['rank'],           ci:parsedjson['city'],           lo:parsedjson['love'],           ab:streetsList        );    }  }    Future<ChennaiModel> getchennai() async {    final response = await http.get(Uri.https('run.mocky.io','/v3/1496b5ef-873a-48db-9550-75195f2db3b4'));      if (response.statusCode == 200) {      // If the server did return a 200 OK response,      // then parse the JSON.      return ChennaiModel.fromJson(jsonDecode(response.body));    } else {      // If the server did not return a 200 OK response,      // then throw an exception.      throw Exception('Failed to load album');    }  }  

enter image description here

delphi android app "Update to billing library 3 before this date"

Posted: 24 Apr 2021 08:22 AM PDT

Just uploaded my app bundle and get this message:

We've detected that this app is using an old version of Google Play Billing. By 1 November 2021, all app updates must use billing library version 3 or newer. Update to billing library 3 before this date  

is there a way to update this library , I'm using delphi 10.4.2

Android Studio does not detect emulator with play store?

Posted: 24 Apr 2021 08:21 AM PDT

If I start an emulator without Play Store, my flutter project can be started on it however if it has Play Store then it does not find it. Even if I try to run the project with the flutter run command, it does not show the emulator although it is running.

Ethereum Node on a Ubuntu Machine, how to access from another device

Posted: 24 Apr 2021 08:21 AM PDT

I have been trying to access to a Ethereum Blockchain(setup on a Ubuntu machine) using another device. The way I setup the blockchain is as:

geth --datadir=/home/USERNAME/test/ --http --http.api web3,eth --http.addr 192.168.0.58 --http.port 5353 --port 30303  

In this case, everything seems to work and get the following statement:

HTTP server started                      endpoint=192.168.0.58:5353 prefix= cors=* vhosts=localhost  

To test the connection, I use web3.py library

from web3 import Web3  w3 = Web3(Web3.HTTPProvider("http://192.168.0.58:5353"))  w3.isConnected()  

And it returns True which is expected. But when I try to do the same process using another device and try to connect as such shown above, I cannot connect. I have already opened the port 5353 using the command sudo ufw allow 5353. Below is the result of sudo ufw status verbose:

Status: active  Logging: on (low)  Default: deny (incoming), allow (outgoing), disabled (routed)  New profiles: skip    To                         Action      From  --                         ------      ----  192.168.0.1 8545/tcp       ALLOW IN    Anywhere                    5353                       ALLOW IN    Anywhere                    5353/tcp                   ALLOW IN    Anywhere                    5353 (v6)                  ALLOW IN    Anywhere (v6)               5353/tcp (v6)              ALLOW IN    Anywhere (v6)     

My overall goal is to instantiate a geth on a Azure VM and connect to it using another Azure VM. Everything I explained above is using my own computer and I am trying to access it from a Azure VM. Any help is appreciated guys. Thanks

HAproxy vs ALB or any other load balancer which one to use?

Posted: 24 Apr 2021 08:21 AM PDT

We are looking to separate our blog platform to a separate ec2 server (In Nginx) for better performance and scalability.

Scenario is:

  1. Web request (www.example.com) -> Load Balancer/Route -> Current EC2 Server
  2. Blog request (www.example.com/blog) -> Load Balancer/Route -> New Separate EC2 Server for blog

Please help in this case what is the best option to use:

  1. Haproxy
  2. ALB - AWS
  3. Any other solution?

Also, is it possible to have the load balancer or routing mechanism in a different AWS region? We are currently hosted in AWS.

Thanks in Advance

Setting a description with quick.db

Posted: 24 Apr 2021 08:22 AM PDT

In my discord bot , I want all users to have a customizable profile. Whenever they run a command !profile or !p , the bot will display an embed with bio (which is like an introduction like "Hello World" or something) , custom embed color of their choice and other database information (.ie coins, energy etc.) . I want to make sure that whenever they run something like !desc Hello World , their profile embed will have the message Hello World, and if they run !desc Lorem another time, their custom embed's bio will be edited to Lorem and so on. I got them implement with simple db.get and db.set function using quick.db but the problem is whenever the user sets a description with more than one arguments like Hello World , it only appears on the embed as HelloWorld but not the actual correct one with spaces. I really want the embed to display exactly what the user sets its description (with spaces and stuffs ) but currently my code isn't capable of it. Please give it a look and point out where I should change!

const db = require("quick.db");  const Discord = require("discord.js");    module.exports = {    commands: ["description", "desc"],    minArgs: 1,    maxArgs: null,    expectedArgs: ["description to add"],      callback: (message, arguments, text) => {      var desc;      desc = arguments.join("");      let tester = db.get(`_desc${message.author.id}`);        if (!tester) {        db.set(`_desc${message.author.id}`, desc);      } else {        db.delete(`_desc${message.author.id}`), db.set(`_desc${message.author.id}`, desc);      }      console.log(desc);    },  };    

The above is the code for !desc and the below is the one for !profile.

const db = require("quick.db");  const Discord = require("discord.js");    module.exports = {    commands: ["profile", "p"],    alias: ["p"],    minArgs: 0,    maxArgs: null,      callback: async (message, arguments, text) => {      let target = message.mentions.members.first() || message.author;        const balance = db.get(`honey_${target.id}`);      const energy = db.get(`energy_${target.id}`);      var desc = db.get(`_desc${target.id}`);      if (desc === null) {        let desc = "this user have yet to set a description!";      }        const embed = new Discord.MessageEmbed()        .setTitle(`${target.tag}'s profile`)        .setColor("#ECB802")        .addFields(          { name: "Description", value: `${desc}`, inline: false },          {            name: "cards",            value: "1",            inline: true,            //to do          },          { name: "Gym battle record", value: "1/0", inline: true }, //to do          {            name: "Honey",            value: `${balance} :honey_pot:`,            inline: true,          },          {            name: "energy",            value: `${energy} :dizzy:`,            inline: true,          },        );        message.channel.send(embed);    },  };  

How to call a method of base class with same name method in derived class in python?

Posted: 24 Apr 2021 08:21 AM PDT

code:-

class Animal():                def __init__(self) -> None:          print("Animal Created")                              def eat(self):          print("Animal Eating")                class Dog(Animal):            def __init__(self) -> None:          # Animal.__init__(self)          print ("Dog Created")                def eat(self):          print("Dog Eating")        mydog = Dog()  mydog.eat()  

here when I call eat() method with mydog object it prints "Dog Eating", is there any way to call eat() method of base Animal class with mydog object, like is there something like this

mydog.Animal.eat() or mydog.eat(Animal)  

I don't want to use super(), cause then it will call eat() from child class also so it will print both statements "Animal eating" and "Dog eating", which I doesn't want, I want to call only one at a time.

MongoDB query that gets all unique users

Posted: 24 Apr 2021 08:22 AM PDT

I'm currently working with a MongoDB database. My problem is that I have many people with the same name, but they're different people and have different ages, birthplace, etc.

An example of the documents are:

{          "_id" : ObjectId("6072fee3145c156c123ce3"),          "Users" : [                  {                          "name" : "John Davies",                          "age" : NumberLong(35),                          "place_of_birth" : "Cardigan"                  },                  {                          "name" : "Edward Jones",                          "age" : "blank",                          "place_of_birth" : "Liverpool"                  },                  {                          "name" : "Daniel Rhys",                          "age" : NumberLong(63),                          "place_of_birth" : "Cardigan"                  },                  {                          "name" : " Evan Williams",                          "age" : NumberLong(61),                          "place_of_birth" : "Cardigan"                  },                  {                          "name" : "John Davies ",                          "age" : NumberLong(21),                          "place_of_birth" : "Cardigan"                  }          ]  }  {          "_id" : ObjectId("6072fee3145c156c321ef6"),          " Users " : [                  {                          "name" : "John Davies",                          "age" : NumberLong(35),                          "place_of_birth" : "Swansea"                  },                  {                          "name" : "Edward Jones",                          "age" : "blank",                          "place_of_birth" : "Liverpool"                  },                  {                          "name" : "Daniel Rhys ",                          "age" : NumberLong(63),                          "place_of_birth" : "Barry"                  },                  {                          "name" : "Evan Williams",                          "age" : NumberLong(61),                          "place_of_birth" : "Cardigan"                  },                  {                          "name" : "John Davies",                          "age" : NumberLong(21),                          "place_of_birth" : "Cardigan"                  }          ]  }  

So my goal is to query this data in order to get all the names accompanied with the age and birthplace of each unique person once.

So the output should contain (I'm only putting in a table to show more clearly what the query results should be):

Name Age Birth place
John Davies 35 Cardigan
Edward Jones Blank Liverpool
Daniel Rhys 63 Cardigan
Evan Williams 61 Cardigan
John Davies 21 Cardigan
Daniel Rhys 63 Barry
John Davies 35 Swansea

Any advice or guidance on the best approach would be really appreciated

React.js State not updating in Event Listener in useEffect Hook

Posted: 24 Apr 2021 08:23 AM PDT

So, What I'm trying to do is add an event listener to a button that when pressed takes the value of a state and console log it. But the logged value never updates even after the multiple setState calls.

const [seamValue, setSeamValue] = useState(20);    useEffect(()=>      const seamCarve = document.getElementById("process");            seamCarve.addEventListener('click',(e)=>{          console.log(seamValue)      })        },[]);    

And then there's the button that triggers it

        <div id="seamvalue">          <Typography variant="h6" align="center" >Seams Reduction:<span id="valueOfSeam"> {seamValue} </span></Typography>          </div>            <Button id="leftslider"           variant="contained" color="primary" onClick={() => seamValue-10>0?setSeamValue(seamValue - 10):setSeamValue(0)}>            <Typography >{"<"}</Typography>          </Button>            <Button id="rightslider"            variant="contained" color="primary" onClick={() => setSeamValue(seamValue + 10)}>            <Typography >{">"}</Typography>          </Button>            <Button id="process"           variant="contained" color="primary"  >            <Typography >Carve</Typography>          </Button>  

The value changes as I click on the sliders but when I press the Button with id="process" with an event listener associated with it, it only prints 20 even after updating the state.

After training the CNN model in TensorFlow when I predict i'm getting reverse results

Posted: 24 Apr 2021 08:22 AM PDT

I have two classes mask and not_mask when I give the picture of the image with the mask it's predicting no mask and not_mask image predicting mask.

img = image.load_img("mt.jpg", target_size=(150,150))  x=image.img_to_array(img) / 255  resized_img_np = np.expand_dims(x,axis=0)  prediction = model.predict(resized_img_np)  np.where(prediction>0, "Mask","Not_Mask")[classes][1]  [prediction][1]  

pic prediction

classes pic

Redimensioning bidimensional array gives error nº 9 "subindex out or range" in second iteration of loop: - Can't figure out the reason

Posted: 24 Apr 2021 08:22 AM PDT

This error is driving me crazy.

I followed all tutorials just in case but I can't figure out the reason my code is giving error nº9 in the line where I redim the array inside the loop. It is happenning in the second round of the loop.

Here is the code:

   Dim ar() As Variant     Dim cont As Integer     'Here goes some SQL and querying that works and does not matter for this post. The results are returned well.         cont = 0     Do Until rs.EOF      resul = rs!f1 & " " & rs!f2      'Error thrown in the second round of the loop in the following line:      ReDim Preserve ar(cont, 1)      ar(cont, 0) = rs!ID      ar(cont, 1) = resul      rs.MoveNext      cont = cont + 1  Loop  

I really can't figure out why is happening the error. The syntax is Ok as far as tutorials say. I wanted to create this bidimensional array so that I can attach it to a combobox.List in a userform.

Again, the recordset returned is ok, the problem seems to be the array at some point.

Haskell List comprehension: show even and double odd elements

Posted: 24 Apr 2021 08:23 AM PDT

I've been working on an assignment and I just can't get it to work.

I should write a function that takes a list of numbers and gives back a list that shows even numbers but doubles all odd numbers. (Basically the same list but with doubled odds).

doubleOdd :: [Integer] -> [Integer]  doubleOdd [] = []  doubleOdd a = [x*2 | x <- a, odd x]  

My problems are:

  1. I'm only allowed to use +, -, *, /, ==, /=, sum, mod, elem, maximum, odd, even
  2. I don't know how I get different conditions for the same value to work (like if x is even = x and in the same List Comprehension have: if x is odd = x*2)

So far I only got to print the even or the odd numbers, but never both.....

I hope someone can help me.

@ComponentScan for every package in project

Posted: 24 Apr 2021 08:22 AM PDT

Is it possible to let @ComponentScan work on whole Spring Boot project? Now when I create a new package, I need to add it into @ComponenScan annotation otherwise beans won't be found. If it's possible to allow to search everywhere in project can it cause performance problems or any other issues?

Example:  first component StorageRoom\backend\src\main\java\com.storeage (here is main class with @ComponentScan annotation)  second component StorageRoom\backend\src\main\java\security  third component StorageRoom\backend\src\main\java\component3  

World Server not loading

Posted: 24 Apr 2021 08:23 AM PDT

I completely install the source, I install the complete database, I configure it, I run authserver, I run it, then I run it on worldserver, it gives this error, it crashes

Could not prepare statements of the World database, see log for details.

This problem started 10 or 15 days ago. Before that, there was no problem. My server is running on vps

Is there a way to add more elements to a map in Python?

Posted: 24 Apr 2021 08:23 AM PDT

I am trying to add symptoms to the diseases in Python maps but I'm not able to add symptoms as it is giving an error. Is there a way to do it and also how do I take the input and then calculate the closest disease by using the symptoms that is input by the user?

This is the code:

diseases = {'Coronavirus':'fever', 'dry cough','tiredness',  'Common Cold': 'cough', 'cold',  'Heart Attack': 'pain', 'pressure', 'squeezing'}    symptoms = input("Please type your symptoms (If there are multiple then separate them by a ',') (Note: type all in small letters): ")    if symptoms == 'fever, dry cough, tiredness':      print("Your disease is Coronavirus or cornavirus! Deadly Disease: Yes")    if symptoms == 'cough, cold':      print("Your disease is Common cold, Deadly Disease: No, but must consult a doctor if sever.")  

How to initialize tuple of vectors out of a variadic template pack and list of objects which use the same template types?

Posted: 24 Apr 2021 08:22 AM PDT

Below is a simplified description of what I intend to do and the code with which I'm approaching it.

I have a structure TEmitter<Ts...> where Ts... is a list of components stored in a std::tuple inside of TEmitter.

Lets say there are two emitters:

 e1<A, B, C>   e2<A, B, C>  

I'd like to create a class EmitterMemory<Ts...> which takes an std::initializer_list<TEmitter<Ts...>> in the constructor, takes the components of each TEmitter apart, and puts them in std::vectors which are stored in a tuple, like:

EmitterMemory<A, B, C> {e1, e2}    (has a) stl::tuple          |-stl::vector<A> = [A(e1), A(e2)]          |-stl::vector<B> = [B(e1), B(e2)]          |-stl::vector<C> = [C(e1), C(e2)]  

Now in the code below I think I've managed to declare the class EmitterMemory correctly, I just don't know how to initialize the std::tuple<std::vector<Ts>...> out of the constructor parameter std::initializer_list<TEmitter<Ts...>>.

I'd need somehow to iterate through the components declared in variadic template Ts..., and for each of them invoke get<T>(TEmitter<Ts...>) and put the result inside the std::vector<T>.

Something that I'm manually doing in the 4 last lines of the main() function.

I'd need some help how to approach this, so it's done automatically in the class constructor. Can you tell me if it's feasible?

Code

#include <concepts>  #include <functional>  #include <iostream>    struct ComponentBase{};    template<typename T>  concept is_a_component = std::is_base_of_v<ComponentBase, T>;  template<typename ...T>  concept is_many_components = (is_a_component<T> && ...);    namespace components {      struct Position : ComponentBase {};      struct Shoot : ComponentBase {};      struct Active : ComponentBase {};      struct Emission : ComponentBase {};  }    struct EmitterBase {};  template<typename T>  concept is_an_emitter = std::is_base_of_v<EmitterBase, T>;    template<is_many_components... Ts>  class TEmitter : EmitterBase {          using Components = std::tuple<Ts...>;  public:      explicit TEmitter(int id) : id{id} {};      int id{0};          Components components = std::make_tuple(Ts()...);  };    template<is_a_component T>  auto &get(is_an_emitter auto &emitter) {      return std::get<T>(emitter.components);  }    struct EmitterMemoryBase {};    template<is_many_components... Ts>  class EmitterMemory : EmitterMemoryBase {      using TupleOfVectors = std::tuple<std::vector<Ts>...>;  public:      static constexpr std::size_t AmountComponents = sizeof...(Ts);      TupleOfVectors components;        EmitterMemory(std::initializer_list<TEmitter<Ts...>> emitters)          : components { std::make_tuple<>(std::vector<Ts>{}...) }           { };  };    template<typename ...Ts>  concept is_a_memory = std::is_base_of_v<EmitterMemoryBase, Ts...> ;    template<is_a_component T>  auto &get(is_a_memory auto &memory) {      return std::get<std::vector<T>>(memory.components);  }    int main () {      using namespace components;      auto e1 = TEmitter<Position, Shoot, Active>{1};      auto e2 = TEmitter<Position, Shoot, Active>{2};        auto &e1_position_component = get<Position>(e1);      auto &e2_position_component = get<Position>(e2);      auto memory = EmitterMemory<Position, Shoot, Active>({e1, e2});              auto &position_vector = get<Position>(memory);      position_vector.emplace_back(e1_position_component);      position_vector.emplace_back(e2_position_component);  }  

How to convert array of events into HH:mm format

Posted: 24 Apr 2021 08:22 AM PDT

I have an array with start and end called blockedTime. How can I convert these elements into HH:mm format? I have also seen how people use momentjs library, but whenever I tried to use it I didn't get the answer I wanted

   const BlockedTime = [      {          start: "2021-04-19T09:30:00.0",          end: "2021-04-19T10:00:00.0"      },      {          start: "2021-04-19T14:00:00.0",          end: "2021-04-19T14:30:00.0"      },      {          start: "2021-04-19T16:00:00.0",          end: "2021-04-19T16:30:00.0"      }    ]  

CORS issue in Chrome though Access-Control-Allow-Origin header is present

Posted: 24 Apr 2021 08:24 AM PDT

A developer added new DELETE blog endpoint, whose source code is based on the existing and working DELETE page endpoint. It works on his PC but it fails on my PC. The Chrome does not run the DELETE method because of allegedly missing CORS header.

The attached picture shows Chrome dev tools screenshots for three different OPTION + DELETE/POST requests. I have checked that OPTIONS is always run for DELETE page request and it returns a CORS header for localhost. The response is the same as for POST a picture or DELETE a page. I cannot see any difference and I cannot find an explanation.

Backend is written in NodeJS

This code works on my PC: https://github.com/literakl/mezinamiridici/blob/master/backend/src/handlers/pages/deletePage.js

module.exports = (app) => {    app.options('/v1/pages/:pageId', auth.cors);    app.delete('/v1/pages/:pageId', auth.required, auth.cms_admin, auth.cors, async (req, res) => {  

This code works on developer's Chrome and Firefox but fails on my Chrome or Edge https://github.com/literakl/mezinamiridici/blob/master/backend/src/handlers/items/deleteBlog.js

module.exports = (app) => {    app.options('/v1/blog/:blogId', auth.cors);        app.delete('/v1/blog/:blogId', auth.required, auth.cors, async (req, res) => {  

enter image description here

Frontend is written in Vue. The page with Delete button is loaded from http://localhost:8080/p/leos/b/wing-suit-2. OPTIONS returns:

Access-Control-Allow-Headers: Content-Type,Authorization  Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE  Access-Control-Allow-Origin: http://localhost:8080  

Blocked DELETE request contains these request headers:

Origin: http://localhost:8080  Referer: http://localhost:8080/  

So I assume that everything is set up correctly. Where is the issue please?

enter image description here

Update 1:

console log:

Access to XMLHttpRequest at 'http://localhost:3000/v1/blog/1f3j20k5qh' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How to reshape a dataframe from wide to long with columns that represent duplicated variables?

Posted: 24 Apr 2021 08:22 AM PDT

I have the following dataframe, I would like to 'transfer' the values of columns from v3 to v10 in the first two columns v1 and v2, respectively, since they are duplicated variables and their values belong to the first two variables (v1 and v2).

df <- data.frame(id = 1:5,                v1 = c("infection", "anxiety", "pain", "infection", "aspiration"),                v2 = c(31, 55, 33, 31, 24),                v3 = c("aspiration", NA, "ulcer", NA, "pain"),                v4 = c(26, NA, 43, NA, 20),                v5 = c("skin", NA, NA, NA, NA),                v6 = c(25, NA, NA, NA, NA),                v7 = c("ventilation", NA, NA, NA, NA),                v8 = c(8, NA, NA, NA, NA),                v9 = c("gas", NA, NA, NA, NA),                v10 = c(4, NA, NA, NA, NA))  

I would like to have as output this new df:

out <- data.frame(id = c(1,1,1,1,1,2,3,3,4,5,5),                v1 = c("infection", "aspiration", "skin", "ventilation", "gas", "anxiety", "pain", "ulcer", "infection", "aspiration", "pain"),                v2 = c(31, 26, 25, 8, 4, 55, 33, 43, 31, 24, 20))  

Thank you so much for your help!

kubernetes from a running pod, get only required elements via -o yaml

Posted: 24 Apr 2021 08:21 AM PDT

Generally in the kubernetes we can create definition files. for non-running and running pods, namespaces, deployments etc. If we generate yaml file for non running and non existing pods it create required defination file. However, if we have to get the defination file from running pod it also generates lots tags of live environment.

How to get only required elements while we generate yaml defination from a running pod

Is there any way if we can avoid getting below details after we generate pod yaml file from a running pod

For example if we see that after running below command it also generates lot of not required elements.

k get po nginxs14 -n=devs14 -o yaml>pod1.yaml    like:    metadata:    annotations:      kubectl.kubernetes.io/last-applied-configuration: |        {"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"creationTimestamp":null,"labels":{"run":"nginx"},"name":"nginxs14","namespace":"devs14"},"    creationTimestamp: "2021-04-24T11:09:56Z"    labels:      run: nginx    managedFields:    - apiVersion: v1      fieldsType: FieldsV1      fieldsV1:        f:metadata:          f:annotations:            .: {}            f:kubectl.kubernetes.io/last-applied-configuration: {}          f:labels:            .: {}            f:run: {}        f:spec:          f:containers:            k:{"name":"nginx"}:              .: {}              f:image: {}              f:imagePullPolicy: {}              f:name: {}              f:ports:                .: {}                k:{"containerPort":9080,"protocol":"TCP"}:                  .: {}                  f:containerPort: {}                  f:protocol: {}              f:readinessProbe:                .: {}                f:failureThreshold: {}                f:httpGet:                  .: {}                  f:path: {}                  f:port: {}                  f:scheme: {}                f:periodSeconds: {}                f:successThreshold: {}                f:timeoutSeconds: {}              f:resources: {}              f:terminationMessagePath: {}  f:terminationMessagePolicy: {}          f:dnsPolicy: {}          f:enableServiceLinks: {}          f:restartPolicy: {}          f:schedulerName: {}          f:securityContext: {}          f:terminationGracePeriodSeconds: {}      manager: kubectl-client-side-apply      operation: Update      time: "2021-04-24T11:09:56Z"    - apiVersion: v1      fieldsType: FieldsV1      fieldsV1:        f:status:          f:conditions:            k:{"type":"ContainersReady"}:              .: {}              f:lastProbeTime: {}              f:lastTransitionTime: {}              f:message: {}              f:reason: {}              f:status: {}              f:type: {}            k:{"type":"Initialized"}:              .: {}              f:lastProbeTime: {}              f:lastTransitionTime: {}              f:status: {}              f:type: {}            k:{"type":"Ready"}:              .: {}              f:lastProbeTime: {}              f:lastTransitionTime: {}              f:message: {}              f:reason: {}              f:status: {}              f:type: {}          f:containerStatuses: {}          f:hostIP: {}          f:phase: {}          f:podIP: {}          f:podIPs:            .: {}  

JsonConverterAttribute is not working for Deserialization in ASP.NET Core 3.1 / 5.0

Posted: 24 Apr 2021 08:22 AM PDT

I want set property names at runtime. I already achieve this for serialization.

For example. I have a simple model like as below:

[JsonConverter(typeof(DataModelConverter))]  public class DataModel  {      public string Name { get; set; }      public int Age { get; set; }  }  

And I have a simple DataModelConverter, that inherited from JsonConverter:

public class DataModelConverter : JsonConverter  {      public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)      {          Type type = value.GetType();            JObject jo = new JObject();            foreach (PropertyInfo prop in type.GetProperties())          {              jo.Add(prop.Name == "Name" ? "FullName" : prop.Name, new JValue(prop.GetValue(value)));          }            jo.WriteTo(writer);      }        public override bool CanRead      {          get { return false; }      }        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)      {          throw new NotImplementedException();      }        public override bool CanConvert(Type objectType)      {          return objectType == typeof(DataModel);      }  }  

And I have a simple controller like as below:

[Route("api/[controller]")]  [ApiController]  public class NewtonController : ControllerBase  {      public IEnumerable<DataModel> GetNewtonDatas([FromBody] DataModel input)      {          return new List<DataModel>()          {              new DataModel              {                  Name="Ramil",                  Age=25              },              new DataModel              {                  Name="Yusif",                  Age=26              }          };      }  }  

If I call this API, result will like as below (Showing FullName Instead of Name):

[     {         "FullName": "Ramil",         "Age": 25     },     {         "FullName": "Yusif",         "Age": 26     }  ]  

But I have a problem. This is not working for deserialization.

For example: If I call this API with this body, then Name will null.

{     "FullName":"Ramil"  }  

My attribute is not working for deserialization. I want set property name via attribute for deserialization at runtime .

I don't want use some middleware, I want to achieve this only by using the any attribute at runtime.

Thanks for help!

Dining philosophers synchronized by mutex and event

Posted: 24 Apr 2021 08:23 AM PDT

I'm trying to solve the dining philosophers problem with mutexes and events (it's a part of the task). Run time(total) and dining time(et_time) are set when the program is called. Thread should not change its state to E if the program has already run TOTAL ms. Thus, if, for example, thread has entered state E at time 950, and at the same time total = 1000 and et_time = 100, then it has the opportunity to complete the "eating", and the eating ends at time 1050. In this case, the total running time of the program should not exceed total + et_time ms.

In fact, i don't really understand how to use events in this case

This is what i've done so far

#include <string.h>  #include <stdlib.h>  #include <windows.h>  #include <time.h>    #define phil_num 5    time_t total;  time_t et_time;  time_t start;  time_t max_time;  volatile int phil_state[phil_num] = { 0 }; //0 - thinking; 1 - eating   volatile int phil_count = 0;  volatile int flag = 1;      HANDLE mutex;  HANDLE event;   HANDLE threads[phil_num];        DWORD WINAPI philosopher(void* param);  bool is_possible(int phil_id);  int get_time(time_t beg_tick);      DWORD WINAPI philosopher(void* param)  {      volatile int idx = ((char*)param - (char*)0) + 1;      while (1)      {                        if (get_time(start) >= total)                  return 0;                WaitForSingleObject(mutex, INFINITE);                if (is_possible(idx))               {                  //printf("thread %d has time %d \n", idx, get_time(start));                  if (get_time(start) + et_time > max_time || get_time(start) >= total)                  {                      //printf("thread %d has finished \n", idx);                       ReleaseMutex(mutex);                      return 0;                  }                  phil_count++;                  phil_state[idx - 1] = 1;//eat                  printf("%d:%d:T->E\n", get_time(start), idx);                  ReleaseMutex(mutex);                    Sleep(et_time);//ест                    WaitForSingleObject(mutex, INFINITE);                  printf("%d:%d:E->T\n", get_time(start), idx);                  phil_state[idx - 1] = 0;                  phil_count--;                  ReleaseMutex(mutex);                                      }              else                  ReleaseMutex(mutex);                          }  //printf("thread %d has finished \n", idx);      return 0;  }    //source\repos\phil\Debug\phil 50 10      int main(int argc, char* argv[])   {      if (argc !=3)      {          printf("ARGS ERROR \n");          return -1;      }            total = atoi(argv[1]);      et_time = atoi(argv[2]);        max_time = total + et_time;        memset(&threads, 0, sizeof(threads));      mutex = CreateMutex(NULL, FALSE, NULL);      event = CreateEvent(NULL, FALSE, TRUE, NULL);          for (int i = 0; i < phil_num; i++)          threads[i] = CreateThread(0, 0, philosopher, (void*)((char*)0 + i), 0, 0);        start = clock();      WaitForMultipleObjects(phil_num, threads, TRUE, INFINITE);        for (int i = 0; i < phil_num; i++)          CloseHandle(threads[i]);      CloseHandle(mutex);      CloseHandle(event);        return 0;    }    int get_time(time_t start)  {      return 1000 * ((double)clock() - (double)start) / (double)CLOCKS_PER_SEC;  }      bool is_possible(int phil_id)  {            if (phil_id == 1)      {          if (phil_state[1] == 0 && phil_state[4] == 0)              return 1;      }        else if (phil_id == 5)      {          if (phil_state[0] == 0 && phil_state[3] == 0)              return 1;      }        else if (phil_state[phil_id - 2] == 0 && phil_state[phil_id] == 0)          return 1;        return 0;  }  

Encrypt email messages when Amazon Simple Email Service Classic is used

Posted: 24 Apr 2021 08:23 AM PDT

I checked the official documentation for Amazon Simple Email Service Classic but I can find an answer for my question which connection type I can use SSL encryption in order to encrypt the e-mail content:

  • AWS SDKs
  • API requests
  • SMTP connection using JavaMail

The only solution for now is to use API request but in this case I don't see option to send web e-mail.

Can you guide me how I can solve this question?

Should I always use safeAreaView in react native?

Posted: 24 Apr 2021 08:23 AM PDT

I know that I always need to use <safeAreaView> to keep my content in the correct place of the screen in iOS.

Even I'm build an app just for Android, seems there isn't problem use <safeAreaView>, in case of I want to build the same app for the iOS platform.

My question is, am I wrong if I ALWAYS use <safeAreaView> to wrap all my content? Why would I use <View> if perhaps in the future I'll have to replace everything with <safeAreaView>?

combine two dictionaries into one, with elements from dict2 taking precedence

Posted: 24 Apr 2021 08:21 AM PDT

def combine_guests(guests1, guests2):    # Combine both dictionaries into one, with each key listed     # only once, and the value from guests1 taking precedence    Rorys_guests = { "Adam":2, "Brenda":3, "David":1, "Jose":3, "Charlotte":2, "Terry":1, "Robert":4}  Taylors_guests = { "David":4, "Nancy":1, "Robert":2, "Adam":1, "Samantha":3, "Chris":5}    print(combine_guests(Rorys_guests, Taylors_guests))  

Want this output

{"Adam": [2, 1], "Branda": 3, "David": [1, 4] ...}  

with value from guests1 i.e.Rorys_guests dict will take precedence first .i.e for Adam key value is [2,1]

Glossaries in Google Translate v3 API

Posted: 24 Apr 2021 08:22 AM PDT

How exactly is the support for glossaries via Google translate_v3beta1 API supposed to work? I've been searching for this information, but haven't found it. Should the terms in glossary simply override all other potential translations, or do they just add priority for translations in the glossary, but the engine can still use other translations if they "fit better" according to training data?

I've created a glossary using Python libraries (I've tried two different ways - from tsv using "language_pair" property and also from csv using "language_codes_set" property). Then I tried to use the glossary to override a translation of one term in a text string produced by a custom MT model (ie. without using a glossary, the engine translated a term one way and I tried to use the glossary to force it to use another translation for that term), but without success.

Now I'm not sure, if I made some mistake when creating or using the glossary (currently I don't know about any issue in my code), or if there is no mistake on my side, but based on the training data the engine simply used another translation. From experience with other platforms for custom machine translation I know, that some of them use glossaries to override the translations and some of them use them only to prioritize the glossary terms, but not totally override all other potential translations. Therefore I want to clarify this simple question first, before starting to search for other possible reasons, why my code doesn't work as expected.

Thank you in advance.

Can someone show me a simple working implementation of PagerSlidingTabStrip?

Posted: 24 Apr 2021 08:22 AM PDT

Here is the library: https://github.com/astuetz/PagerSlidingTabStrip I'm trying to implement it but my app keeps crashing on startup. I've tried to understand the sample app that is posted but don't think I'm doing something right. Here is my code:

MainActivity.java

        import android.graphics.Color;      import android.graphics.drawable.ColorDrawable;      import android.graphics.drawable.Drawable;      import android.graphics.drawable.LayerDrawable;      import android.graphics.drawable.TransitionDrawable;      import android.os.Build;      import android.os.Bundle;      import android.os.Handler;      import android.support.v4.app.Fragment;      import android.support.v4.app.FragmentActivity;      import android.support.v4.app.FragmentManager;      import android.support.v4.app.FragmentPagerAdapter;      import android.support.v4.view.ViewPager;      import android.util.TypedValue;      import android.view.Menu;      import android.view.MenuItem;      import android.view.View;        import com.astuetz.PagerSlidingTabStrip;          public class MainActivity extends FragmentActivity {            private final Handler handler = new Handler();            private PagerSlidingTabStrip tabs;          private ViewPager pager;          private MyPagerAdapter adapter;            @Override          protected void onCreate(Bundle savedInstanceState) {              super.onCreate(savedInstanceState);              setContentView(R.layout.activity_main);                tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);              pager = (ViewPager) findViewById(R.id.pager);              adapter = new MyPagerAdapter(getSupportFragmentManager());                pager.setAdapter(adapter);                tabs.setViewPager(pager);          }              @Override          public boolean onCreateOptionsMenu(Menu menu) {                // Inflate the menu; this adds items to the action bar if it is present.              getMenuInflater().inflate(R.menu.main, menu);              return true;          }            @Override          public boolean onOptionsItemSelected(MenuItem item) {              // Handle action bar item clicks here. The action bar will              // automatically handle clicks on the Home/Up button, so long              // as you specify a parent activity in AndroidManifest.xml.              int id = item.getItemId();              if (id == R.id.action_settings) {                  return true;              }              return super.onOptionsItemSelected(item);          }            @Override          protected void onSaveInstanceState(Bundle outState){              super.onSaveInstanceState(outState);          }          @Override          protected void onRestoreInstanceState(Bundle savedInstanceState){              super.onRestoreInstanceState(savedInstanceState);          }            private Drawable.Callback drawableCallback = new Drawable.Callback() {              @Override              public void invalidateDrawable(Drawable who) {                  getActionBar().setBackgroundDrawable(who);              }                @Override              public void scheduleDrawable(Drawable who, Runnable what, long when) {                  handler.postAtTime(what, when);              }                @Override              public void unscheduleDrawable(Drawable who, Runnable what) {                  handler.removeCallbacks(what);              }          };            public class MyPagerAdapter extends FragmentPagerAdapter{              private final String[] TITLES = {"T1","T2"};                public MyPagerAdapter(FragmentManager fm){                  super(fm);              }                public CharSequence getPageTitle(int position){                  return TITLES[position];              }              @Override              public Fragment getItem(int i) {                  return null;              }                @Override              public int getCount() {                  return TITLES.length;              }          }      }      

And here is acitivty_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:paddingLeft="@dimen/activity_horizontal_margin"      android:paddingRight="@dimen/activity_horizontal_margin"      android:paddingTop="@dimen/activity_vertical_margin"      android:paddingBottom="@dimen/activity_vertical_margin"      tools:context="edu.purdue.test.app.MainActivity">        <com.astuetz.PagerSlidingTabStrip          android:id="@+id/tabs"          android:layout_width="match_parent"          android:layout_height="48dip" />        <android.support.v4.view.ViewPager          android:id="@+id/pager"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:layout_below="@+id/tabs"          tools:context=".MainActivity" />      </RelativeLayout>  

No comments:

Post a Comment