Sunday, November 21, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Aggregate with respect to condition

Posted: 21 Nov 2021 07:56 AM PST

I face the following problem. I have a dataset that I simplify this way

df <- tibble(ID_1=c("a","a", "a","a", "a", "b", "b", "b", "b"), ID_2 = c("a","b", "c","d", "e", "b", "a", "c", "d"),                other= c(1, "bu", 34, 3, 5, 6, "jud", 82, 9), exchange=c(1, 13, 34, 3, 5, 6, 8, 82, 9),                goods=c("wood","wood", "wood","wood", "wood", "steel", "steel", "steel", "steel"))  df  

We have exchanges between multiple countries that have different IDs. I want to sum all the exchanges between country A and country B. Between country A and country C. etc. the goods exchanged. That is, in the end, I'd like to have

ID_1 // ID_2 // Sum_exchangeAB
ID_1 // ID_3 // Sum_exchangeBC
....
ID_n // ID_n // Sumexchangenn

How can I do that in Dplyr? I tried group_by (ID_1, ID_2) then aggregate. Or summarise.

Thank you for your help, much appreciated!!

How do I generate a darker color from a css hex color code?

Posted: 21 Nov 2021 07:56 AM PST

I don't want to use div:hover { filter: brightness(1.2) } although this would work, it only works on hover.

I'm looking to darken a color for a background-color value.

Eliminate the text

Posted: 21 Nov 2021 07:56 AM PST

can help how to eliminate the data below, just want to show the graph only, not the text, but unfortunately, the text shows up. The graph show

Question about List of Objects in dart Language (Flutter)

Posted: 21 Nov 2021 07:56 AM PST

Question About List of Objects in dart (Flutter)

Hello


class Cartoon { . .

}

List<Cartoon> L1 = [];    ….  ...  List<Cartoon> L2 = [];  

I define below a new list L2 containing objects from List L1 meeting some condition

List<Cartoon> L2 = [];  L2.clear();    for (Cartoon  _thisObjet in L1) {   if (_thisObjet.xxx == yyyy) { //     L2.add(_thisObjet);   }  }  

I check with the debugger that anytime I modify a member Value in an Object L2 , the member is is also modified in member of. original Object in List L1.

This is not expected result

In my mind I was thinking these 2 Lists should be independent ,So if someone has an explanation, I would be grateful

Is there anyway i can manually accept someone in my web?

Posted: 21 Nov 2021 07:55 AM PST

I am developing a webpage but the problem is that i want a certain amount of people to join but in a way i can invite them or accept them(like discord or google meet)manually. let me give you an example: the user enters my web then he/she tries to log in or sign up then i recieve a message with the username (this is for preventing names like "fwordgamer232" or "XxnwordxX") and a button that i click to give permission to sign up. Any thoughts?

Using VPC Endpoint for DynamoDB with Amazon.DynamoDBv2

Posted: 21 Nov 2021 07:55 AM PST

I have a .Net core app hosted on Elastic beanstalk currently using DynamoDB with AWSSDK.DynamoDBv2 package and from what i understand, connection to dynamodb will happen over public internet unless i use the dynamodb vpc gateway endpoint.

How can i specific the vpc endpoint while using AWSSDK.DynamoDBv2 package ?

How to get C to ignore spaces in scanf?

Posted: 21 Nov 2021 07:55 AM PST

I am working on a program that takes in a 32 digit number and inputs it into an array. However, this 32 digit number includes spaces in between certain numbers for example, the number: 11000010111110100000000000000000 could be typed as 1 10000101 11110100000000000000000.
When the latter is used, the program would not work. Is there a way for me to get C to ignore the spaces?
This is my code:

int arr[32];  char number[33] = {};  printf("Enter \n");  scanf("%34s", number); // This will scan max 32 characters  printf("\n");  for (int i = 0; i < 32; i++)  {      {      arr[i] = number[i] - '0';      }    }  

How can I convert My vanilla JS code into mousetrap.js

Posted: 21 Nov 2021 07:55 AM PST

I am trying to create a keyboard shortcut which enables the shortcuts for the specific element or button and can be updated as per user needs, there is an existing library for shortcuts that I want to use here is a mousetrap.js There is two-part one is a list of keyboard shortcuts and the second is two select the keys for updating in a bootstrap modal popup

Keyboard Shortcuts

      const defaultOptions = {          apply: {            keyEvent: 's',            hasShift: 0,            hasAlt: 1,            hasControl: 0,            selector: 'joomla-toolbar-button button.button-apply',          },          new: {            keyEvent: 'n',            hasShift: 0,            hasAlt: 1,            hasControl: 0,            selector: 'joomla-toolbar-button button.button-new',          },          save: {            keyEvent: 'w',            hasShift: 0,            hasAlt: 1,            hasControl: 0,            selector: 'joomla-toolbar-button button.button-save',          },          saveNew: {            keyEvent: 'n',            hasShift: 1,            hasAlt: 1,            hasControl: 0,            selector: 'joomla-toolbar-button button.button-save-new',          },          help: {            keyEvent: 'x',            hasShift: 0,            hasAlt: 1,            hasControl: 0,            selector: 'joomla-toolbar-button button.button-help',          },          cancel: {            keyEvent: 'q',            hasShift: 0,            hasAlt: 1,            hasControl: 0,            selector: 'joomla-toolbar-button button.button-cancel',          },          copy: {            keyEvent: 'c',            hasShift: 1,            hasAlt: 1,            hasControl: 0,            selector: 'joomla-toolbar-button button.button-button-copy',          },          article: {            keyEvent: 'a',            hasShift: 0,            hasAlt: 1,            hasControl: 1,            selector: 'joomla-editor-option~article_modal',          },          contact: {            keyEvent: 'c',            hasShift: 0,            hasAlt: 1,            hasControl: 1,            selector: 'joomla-editor-option~contact_modal',          },          fields: {            keyEvent: 'f',            hasShift: 0,            hasAlt: 1,            hasControl: 1,            selector: 'joomla-editor-option~fields_modal',          },          image: {            keyEvent: 'i',            hasShift: 0,            hasAlt: 1,            hasControl: 1,            selector: 'joomla-editor-option~image_modal',          },          menu: {            keyEvent: 'm',            hasShift: 0,            hasAlt: 1,            hasControl: 1,            selector: 'joomla-editor-option~menu_modal',          },          module: {            keyEvent: 'm',            hasShift: 1,            hasAlt: 1,            hasControl: 1,            selector: 'joomla-editor-option~module_modal',          },          pagebreak: {            keyEvent: 'p',            hasShift: 0,            hasAlt: 1,            hasControl: 1,            selector: 'joomla-editor-option~pagebreak_modal',          },          readmore: {            keyEvent: 'r',            hasShift: 0,            hasAlt: 1,            hasControl: 1,            selector: 'joomla-editor-option~read_more',          },        };        const phpOptions = Joomla.getOptions('joomla-shortcut-keys');        this.bootstrapModals = Joomla.getOptions('bootstrap.modal');        this.options = { ...defaultOptions, ...phpOptions };        this.handleKeyPressEvent = this.handleKeyPressEvent.bind(this);        document.addEventListener('keydown', this.handleKeyPressEvent, false);        if (window && window.tinyMCE) {          window.tinyMCE.activeEditor.on('keydown', (e) => {            this.handleKeyPressEvent(e);          });        }      }          execCommand(event, selector, prevent) {        if (          selector.includes('joomla-editor-option')          && Joomla.getOptions('editor') === 'tinymce'        ) {          // Editor Option          const selectorArr = selector.split('~');          if (selectorArr[1] !== undefined) {            if (selectorArr[1] !== 'read_more') {              Object.entries(this.bootstrapModals).forEach((eModal) => {                  if (eModal.includes(selectorArr[1])) {                    const modalElement = document.getElementById(                      eModal.replace('#', ''),                    );                    if (modalElement) {                      window.bootstrap.Modal.getInstance(modalElement).show(                        modalElement,                      );                    }                  }                });            }          }          event.preventDefault();        } else {          const actionBtn = document.querySelector(selector);          if (actionBtn) {            if (prevent) {              event.preventDefault();            }            actionBtn.click();          }        }      }          handleKeyPressEvent(e) {        Object.keys(this.options).forEach((action) => {          // check for meta+shift+alt+ctrl key          const { keyEvent } = this.options[action];          const altKey = this.options[action].hasAlt;          const shiftKey = this.options[action].hasShift;          const ctrlKey = this.options[action].hasControl;            if (              (Number(altKey) === 0              || (Number(altKey) === 1                && (navigator.platform.match('Mac') ? e.metaKey : e.altKey)))            && (Number(shiftKey) === 0 || (Number(shiftKey) === 1 && e.shiftKey))            && (Number(ctrlKey) === 0 || (Number(ctrlKey) === 1 && e.ctrlKey))            && e.key.toLowerCase() === keyEvent          ) {            this.execCommand(e, this.options[action].selector);          }        });      }    }  

Key Select

this.setModalAttributes = this.setModalAttributes.bind(this);          this.handleKeyCombinationkeyUpEvent = this.handleKeyCombinationkeyUpEvent.bind(this);          this.initialiseKeySelectModal = this.initialiseKeySelectModal.bind(this);          this.handleSaveCombinationkeyUpEvent = this.handleSaveCombinationkeyUpEvent.bind(this);          document.addEventListener('DOMContentLoaded',this.initialiseKeySelectModal);          const keySelectBtns = document.getElementsByClassName("keySelectBtn");          for(let x = 0; x < keySelectBtns.length; x+=1) {              keySelectBtns[x].addEventListener("click",this.handleKeySelectClickEvent,false);          }      }      initialiseKeySelectModal() {          const modalDiv = document.createElement("div");          this.setModalAttributes(modalDiv, {"class": "modal fade", "id": "keySelectModal", "tabindex": "-1", "role": "dialog", "aria-labelledby": "keySelectModalLabel", "aria-hidden": "true"});          modalDiv.innerHTML = '<div class="modal-dialog modal-dialog-centered" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="keySelectModalLabel">'+Joomla.getOptions('set_shorcut_text')+'</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><div class="p-3"><p>'+Joomla.getOptions('current_combination_text')+': <span id="currentKeyCombination"></span></p><div class="form-group"><input type="hidden" id="current_KeyEvent" value="" /><input type="hidden" id="current_keyValue" value="" /><input type="hidden" id="current_hasControl" value="0" /><input type="hidden" id="current_hasShift" value="0" /><input type="hidden" id="current_hasAlt" value="0" /></div><p>'+Joomla.getOptions('new_combination_text')+': <span id="newKeyCombination"></span></p></div></div><div class="modal-footer"><button type="button" class="btn btn-primary" data-bs-dismiss="modal" aria-label="Close">'+Joomla.getOptions('cancel_button_text')+'</button><button type="button" class="btn btn-success" id="saveKeyCombination">'+Joomla.getOptions('save_button_text')+'</button></div></div></div>';          document.body.appendChild(modalDiv);          const keySelectModal = document.getElementById("keySelectModal");          Joomla.initialiseModal(keySelectModal);          keySelectModal.addEventListener('keydown', this.handleKeyDownEvent, false);          keySelectModal.addEventListener('keyup', this.handleKeyCombinationkeyUpEvent, false);          const saveKeyCombination = document.getElementById("saveKeyCombination");          saveKeyCombination.addEventListener('click', this.handleSaveCombinationkeyUpEvent, false);      }      setModalAttributes(element, attrs) {          Object.entries(attrs).forEach(([key, value]) => element.setAttribute(key, value));      }      handleKeySelectClickEvent(e){          e.preventDefault();          document.getElementById("currentKeyCombination").textContent = this.textContent;          document.getElementById("newKeyCombination").textContent = "";          document.getElementById("current_KeyEvent").value = this.getAttribute("data-class");          const keySelectModal = document.getElementById("keySelectModal");          window.bootstrap.Modal.getInstance(keySelectModal).show(keySelectModal);      }      handleKeyCombinationkeyUpEvent(e){          if(e.keyCode >= 65 && e.keyCode <= 90){              let keyValue = e.key;              keyValue = keyValue.toUpperCase();              document.getElementById("current_hasControl").value = 0;              document.getElementById("current_hasShift").value = 0;              document.getElementById("current_hasAlt").value = 0;              const newKeySelectCombination = [];              if(e.ctrlKey){                  newKeySelectCombination.push("CTRL");                  document.getElementById("current_hasControl").value = 1;              }              if(e.shiftKey){                  newKeySelectCombination.push("SHIFT");                  document.getElementById("current_hasShift").value = 1;              }              if(e.metaKey || e.altKey){                  if(navigator.platform.match('Mac')){                      newKeySelectCombination.push("META");                  }                  else{                      newKeySelectCombination.push("ALT");                      document.getElementById("current_hasAlt").value = 1;                  }              }              newKeySelectCombination.push(keyValue);              const newKeySelect = newKeySelectCombination.join(' + ');              document.getElementById("newKeyCombination").textContent = newKeySelect;              document.getElementById("current_keyValue").value = keyValue.toLowerCase();          }      }      handleSaveCombinationkeyUpEvent(e){          e.preventDefault();          const keySelectModal = document.getElementById("keySelectModal");          if(document.getElementById("newKeyCombination").textContent){              const currentKeyEventVal = document.getElementById("current_KeyEvent").value;              document.getElementById(`jform_params_${currentKeyEventVal}_keyEvent`).value = document.getElementById("current_keyValue").value;              document.getElementById(`jform_params_${currentKeyEventVal}_hasControl`).value = document.getElementById("current_hasControl").value;              document.getElementById(`jform_params_${currentKeyEventVal}_hasShift`).value = document.getElementById("current_hasShift").value;              document.getElementById(`jform_params_${currentKeyEventVal}_hasAlt`).value = document.getElementById("current_hasAlt").value;              document.getElementById(`jform_params_${currentKeyEventVal}_keySelect_btn`).textContent = document.getElementById("newKeyCombination").textContent;              document.getElementById(`jform_params_${currentKeyEventVal}_keySelect`).value = document.getElementById("newKeyCombination").textContent;          }          window.bootstrap.Modal.getInstance(keySelectModal).hide();      }  }  

Cannot decode UTF-8 buffer to desired data structure

Posted: 21 Nov 2021 07:55 AM PST

Before marking this question as a duplicate , I must state that I am aware of the other posts that transform a buffer in an array of buffers (I have been trying virtually every thread's comments on this , but is not what Im looking for).

I am using Node's child process to run a python script .The script returns a list in the form of :

[["a","21","67"],["b","22","69"]]  

As per the Node child process docs , the result is UTF8 encoded. The problem is that whenever I try with textDecoder :

const response=new TextDecoder(data).decode(data);  

or with regex:

var response = data.toString()  var ressult= a.match(/\d+/g);  

None of them (and many variations of them that I have tried) works as I expect. Ultimately , I just want to get a javascript array ( [["a","21","67"],["b","22","69"]] ) so that I can perform functions on it(or , in other words, the list returned from the python script).Thank you !

Small graph with seaborn.distplot in Kaggle

Posted: 21 Nov 2021 07:55 AM PST

Coding in Python on Kaggle, I switched from distplot to displot. After this migration, the graph plot I get is pretty small and not fitting anymore the screen.

enter image description here

Do you know how to fix it and why I am getting this behaviour?

Route page inside a routed page [React]

Posted: 21 Nov 2021 07:55 AM PST

I have a problem regarding the routing in React.
I have created a Form page. It can be accessed using http://localhost:3000/insert But I couldn't figure out what URL should I enter if I put <Form /> in the home.js

In app.js:

function App() {     return (      <Router>        <div className="App">          <Switch>              <Route exact path="/">              <Home />            </Route>               <Route exact path="/insert">              <Form />            </Route>            </Switch>        </div>      </Router>  );  }  }  

In home.js

......     <Switch>     <Route exact path="/insert1">     <Form />     </Route>                </Switch>    ......  

I have tried http://localhost:3000/insert1 but it won't load. I only see an empty page.

ValueError: not enough image data

Posted: 21 Nov 2021 07:55 AM PST

I am getting the above error when I pass the image to my model, below are the steps which I performed before I pass it to the model.

success,frame = camera.read()  grayImage = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)  blackAndWhiteImage = cv2.threshold(grayImage, 90, 255, cv2.THRESH_BINARY_INV)  

So blackAndWhiteImage is used in model.predict(). I tried np.expand_dims(blackAndWhiteImage, axis=0) and Image.fromarray(blackAndWhiteImage, 'RGB') but none of these is working.

Is there something which I'm missing here?

enter image description here

Product filtering by jQuery and PHP

Posted: 21 Nov 2021 07:54 AM PST

I have some checkboxes. By clicking on any of them, the request will be sent to the PHP page by Ajax.

Clicking on any checkbox will only display the information of one checkbox.

I want all the filters to be done when I select a few checkboxes.

I tried to store the data in the array but failed.

index page code :

<?php              $sql_cheak_tedad25 = "SELECT * FROM tbl_property_values WHERE property_id='$id1' ";              $sql_cheak_tedad22 = mysqli_query($conn, $sql_cheak_tedad25);              while($sql_cheak_tedad32=mysqli_fetch_assoc($sql_cheak_tedad22)){                  echo'                  <div class="form-check">                    <input class="form-check-input" type="checkbox" value="'.$sql_cheak_tedad32['p_id'].'" id="flexCheckChecked'.$sql_cheak_tedad32['p_id'].'">                    <label class="form-check-label" for="flexCheckChecked'.$sql_cheak_tedad32['p_id'].'">                      '.$sql_cheak_tedad32['item_name'].'                    </label>                  </div>                  ';                  echo'                      <script>                                  $( document ).ready(function() {                              $("#flexCheckChecked'.$sql_cheak_tedad32['p_id'].'").click(function(){                                                                          if ($("#flexCheckChecked'.$sql_cheak_tedad32['p_id'].'").is(":checked") == true)                                   {                                                                                                           var anso'.$sql_cheak_tedad32['p_id'].'=$("#flexCheckChecked'.$sql_cheak_tedad32['p_id'].'").val();                                        $.ajax({                                      type: "POST",                                      url: "index1get.php",                                      data: {k1:anso'.$sql_cheak_tedad32['p_id'].'},                                      beforeSend: function (html) {                                                                                },                                      success: function(response) {                                          $("#briefinfo").html(response);                                            }                                  });                                                                     }                                                                });                          });                      </script>                  ';              }                             ?>  

select page code :

<?php      require_once("config.php");      $pid=array($_POST['k1']);      $sql_cheak_tedad = "SELECT * FROM tbl_productselectmodel WHERE idmodelproduct IN (" . implode(",", array_map("intval", $pid)) . ")";      $sql_cheak_tedad2 = mysqli_query($conn, $sql_cheak_tedad);      while($sql_cheak_tedad3=mysqli_fetch_assoc($sql_cheak_tedad2)){                    $idproduct=$sql_cheak_tedad3['idproduct'];          $sql_cheak_tedad88 = "SELECT * FROM tbl_product WHERE id_product='$idproduct' ";          $sql_cheak_tedad99 = mysqli_query($conn, $sql_cheak_tedad88);          while($sql_cheak_tedad100=mysqli_fetch_assoc($sql_cheak_tedad99)){          echo'<div class="alert alert-success">'.$sql_cheak_tedad100['name_product'].'</div>';          }                }  ?>  

enter image description here

Unquoting metric name in custom function

Posted: 21 Nov 2021 07:56 AM PST

I'm creating a custom function to make charting data easier but am running into issues with the processing phase. I've checked the below link and many others but it does not answer my question:

Error: unexpected '}' in "}"

When running the below function, I continue to get the following error: Error: unexpected '}' in "}":

 test<-function(df, kpi){     df<- df %>% mutate(week= lubridate::floor_date(date, unit= 'week', week_start = 1))     trended<- df %>%      pivot_longer(cols= -c('date', 'week'), names_to = 'metric', values_to= 'value') %>%      filter(str_detect(metric, kpi)) %>%     group_by(week) %>%     summarise(!!kpi= mean(value))    return(trended)  }  

I'm trying to use the name of the kpi to name the new variable that I am averaging. I know the function is fine because the below version runs without issue, but when I try to use !! or as.name(), I get the above error. See clean version without a variable name and dummy data below:

test<-function(df, kpi){    df<- df %>% mutate(week= lubridate::floor_date(date, unit= 'week', week_start = 1))     trended<- df %>%      pivot_longer(cols= -c('date', 'week'), names_to = 'metric', values_to= 'value') %>%      filter(str_detect(metric, kpi)) %>%     group_by(week) %>%     summarise(mean(value))   return(trended)  }    df<- tibble(date= seq.Date(from= as.Date('2021-01-01'), to= as.Date('2021-01-31'), by = 1), x= (1:31), y= (31:1))  

I dont know javascript and need assistance with a html navbar function

Posted: 21 Nov 2021 07:56 AM PST

So here is the code

what is worng with it? it should trigger a block if I click on this block (burger) the nav-active function should be triggered. Here is the css part:

const navSlide = () => {      const burger = document.querySelector('.burger');      const nav = document.querySelectorAll('.nav-links');        burger.addEventListener('click',()=>{          nav.classList.toggle('nav-active');      });  }    navSlide();    .nav-active{      transform: translate(0%);  }  

I added the javascript file at the end of my html file:

<script src="../static/java_file.js"></script>  

Error while kill process with QProcess::execute()

Posted: 21 Nov 2021 07:56 AM PST

I've some problems with killing a process using taskkill.

My code:

QStringList args;  args << "/F";  args << "/IM testApp.exe";  QProcess::execute("taskkill", args); //Should be 'taskkill /IM testApp.exe /F'  

Output (translated from german):

ERROR: Invalid argument - "/IM testApp.exe".  Type "TASKKILL /?" to show the syntax.  

erase() in list does not work in c++ on MacOS. What is bash: line 1: 88225 Segmentation fault: 11?

Posted: 21 Nov 2021 07:56 AM PST

#include <iostream>  #include <list>  using namespace std;      int main () {      list<int> mylist;      list<int>::iterator it;        for(int i=1;i<6;i++){          mylist.push_back(i);      }      for (it=mylist.begin(); it!=mylist.end(); ++it)      cout << ' ' << *it;      cout<<endl;        for(it=mylist.begin(); it!=mylist.end();it++){          if((*it)==2){              mylist.erase(it);              mylist.insert(it,9);              break;          }      }            for (it=mylist.begin(); it!=mylist.end(); ++it)      cout << ' ' << *it;      cout<<endl;      return 0;  }  

It seems that mylist.erase(it) is not working because when I delete it, the program works.

The output for the above program is

1 2 3 4 5 bash: line 1: 88370 Segmentation fault: 11 "/Users/alimtleuliyev/Desktop/quiadratic" [Finished in 441ms with exit code 139]

json_encode() returns false when I pass it non-ascii characters

Posted: 21 Nov 2021 07:54 AM PST

When I run the following code json_encode() returns false (error). Does anyone know why?

$r = json_encode(chr(128));  var_dump($r);  

The result is:

bool(false)  

Random characters in 2d array C

Posted: 21 Nov 2021 07:55 AM PST

Hello I'm trying to make a program in C that will generate an 2d array with random characters, but two columns must still be empty (filled with space). but when I run the program I get more characters than lines, which is a problem since there can be as many characters as lines :

https://i-stack-imgur-com.translate.goog/Fvg9c.png?_x_tr_sl=en&_x_tr_tl=sk&_x_tr_hl=sk&_x_tr_pto=nui,sc

Thank you for your response

#include <stdio.h>  #include <stdio.h>  #include <stdlib.h>  #include "ballsortpuzzle.h" in this file I have declaration this function    void generator(const int rows, const int columns, char field[rows][columns]){   srand ( time(NULL) );      char characters[] = {'#', '@', '^', '*', '%', '+', '~', '?', '-', '/'};      int randomCol  = rand() % columns;      int q = randomCol;     while( q == randomCol){     q = rand() % columns;     }       for( int i = 0 ;  i < rows ; i++){       for( int k = 0; k < columns; k++){          int randomChar =rand() % 4;          int thisChar = characters[randomChar];          if(k == randomCol ){           field[i][k] = ' ';          }          else{          field[i][k] = thisChar;          }        }     }       for( int a = 0; a < rows; a++){        for(int l = 0 ; l <  columns; l++) {          printf("%c " , field[a][l]);      }      printf("\n");     }  }  

MAIN.c

#include <stdio.h>  #include <stdlib.h>  #include "ballsortpuzzle.h"    int main(){   char field[10][10];   generator(4,6,field);  }  

ballsortpuzzle.h

#include <stdbool.h>    #define BLANK ' '    void game_field(const int rows, const int columns, char field[rows][columns]);    bool check(const int rows, const int columns, char field[rows][columns]);        void down_possible(const int rows, const int columns, char field[rows][columns], int x, int y);      void generator(const int rows, const int columns, char field[rows][columns]);    

Javascript IF/ELSE - Shorten function

Posted: 21 Nov 2021 07:56 AM PST

I am playing around with the JavaScript IF/ELSE to understand better how it works. As an exercise I took the following working hours of a shop:

  • 6AM to 6PM = Open
  • 6PM to 6AM = Closed

then I created a function that returns the word 'Open' or 'Closed' based on the 2 values "time" and "period".

function shopHours(time,period) {  if (time === 6 && period === 'AM') {  return 'Open';  } else if (time === 6 && period === 'AM') {  return 'Open';  } else if (time === 7 && period === 'AM') {  return 'Open';  } else if (time === 8 && period === 'AM') {  return 'Open';  } else if (time === 9 && period === 'AM') {  return 'Open';  } else if (time === 10 && period === 'AM') {  return 'Open';  } else if (time === 11 && period === 'AM') {  return 'Open';  } else if (time === 12 && period === 'PM') {  return 'Open';  } else if (time === 1 && period === 'PM') {  return 'Open';  } else if (time === 2 && period === 'PM') {  return 'Open';  } else if (time === 3 && period === 'PM') {  return 'Open';  } else if (time === 4 && period === 'PM') {  return 'Open';  } else if (time === 5 && period === 'PM') {  return 'Open';  } else {  return 'Closed';}   }

Everything works fine. However, I would like to be able to shorten the code as it looks too confusing.

I then tried the following:

function shopHours(time,period) {  if(time <= 6 && period === 'AM') {  return 'Closed';  } else if (time >= 6 && period === 'PM') {  return 'Closed';  } else if (time === 12 && period === 'PM') {  return 'Open';  } else {  return 'Open';}  }

The second code works fine too and is much shorter however there is a problem that I am not sure how to solve. When the time and period are set to 12 and PM, the result should be 'closed' but I am not sure how to implement this.

I have tried to add the following code but it seems that would not solve this problem.

 else if (time === 12 && period === 'AM') {  return 'Closed';  }  

I will be very grateful to anyone that will spend a bit of his time to take a look at this question.

Thank you!

How to check if discord channel is still in cooldown

Posted: 21 Nov 2021 07:56 AM PST

I have an issue with sending messages to a discord channel.

If the channel is in timeout due to discord channel cooldown, then the channel.send(msg) function will block. Is there any way to find the remaining time the cooldown has left or check if the send() function will be executed without blocking, before the actual function call?

# this.channels is an array of objects type discord.TextChannel, API reference: https://discordpy.readthedocs.io/en/stable/api.html#textchannel  for l_channel in this.channels:      await l_channel.send(l_msg.text) # Blocks if channel is in cooldown due to slow mode, any way to check before sending?      await asyncio.sleep(2)  

React Router Dom Link to from sub route to other app route

Posted: 21 Nov 2021 07:56 AM PST

I'm new to react & react router dom v5, also my english is bad. Thank you in advance for helping me.

my problem: I have 2 Main Routes in my App.js route

import { Suspense } from 'react';  import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'    /* Pges */  import AdminContainer from './Pages/Admin/AdminContainer';  import PublicContainer from './Pages/Public/PublicContainer';  import NotFound from './Pages/NotFound'  import AuthContainer from './Pages/Auth/AuthContainer';    /* Protected Route */    /* Helpers */    function App() {    console.log("APP")    return (      <Suspense fallback={(<p>Loading</p>)}>        <Router>          <Switch>            <Route path="/auth" component={AuthContainer} />            <Route path="/admin" component={AdminContainer} />            <Route path="/*" component={PublicContainer} />            <Route path="*" component={NotFound} />          </Switch>        </Router>      </Suspense>      )    }  export default App;    

the authcontainer have 2 sub routes "/signin" "/signup"

import React from "react";  import {    BrowserRouter as Router,    Switch,    Route,    withRouter  } from "react-router-dom";    // PAGES  import Signin from "../Auth/Signin";  import Signup from "../Auth/Signup";    const AuthContainer = () => {    console.log("AUTH")    return (      <div>        <Router>          <Switch>            <Route exact path="/auth" component={Signin}/>            <Route exact path="/auth/signin" component={Signin}/>            <Route exact path="/auth/signup" component={Signup}/>          </Switch>        </Router>      </div>    );  };    export default withRouter(AuthContainer);    

then the my publiccontainer have 3 sub routes "/" "/product" "/mycart"

/* Dependencies */  import { Route, Switch, BrowserRouter as Router } from 'react-router-dom'    /* Components */  import Header from "../../Components/Header"  import Products from "./Products"  import Home from "./Home"  import UserProfile from "../User/AccountProfile"    import MyCart from '../Public/MyCart'    const PublicContainer = () => {      console.log("PUBLIC")      return (          <div>              <Router>                  <Header />                  <Switch>                      <Route exact path='/' render={(props) => <Home />} />                      <Route exact path='/products' render={(props) => <Products />} />                      <Route exact path='/mycart' render={(props) => <MyCart isAuth={false} />} />                  </Switch>                 </Router>          </div>      )  }    export default PublicContainer  

the my cart component will only render if isAuth is true, else it will redirect to "/auth/signin"

import React from 'react'  import { Redirect } from 'react-router'    const MyCart = ({isAuth}) => {      if(!isAuth)          return (<Redirect  from='*' to='/auth/signin'></Redirect>)      return (          <div>              my cart          </div>      )  }    export default MyCart  

The problem is, its trying to redirect to "/auth/signin" but it is still in the "/" page enter image description here

When i hit reload it finally redirect to "/auth/signin"enter image description here

How can i fix this issue, I really appreciate your help

UPDATE

this is overview of my planned routes enter image description here

By the way i think when the mycart isAuth is false then it tries to Link to /auth/signin which causes the link in the top url to correctly point to auth signin, but after that it only checks the routes of the publiccontainer instead of checking the app routes enter image description here

But when i reload it, it start searching the correct route from the app.js routes which return the expected route & page which is the sign in

enter image description here

Create new record based upon the presence of a record with Rails

Posted: 21 Nov 2021 07:55 AM PST

I've got a rails app that has two models: address and delivery, where address has_many :deliveries and delivery belongs_to :address.

I'm attempting to create a means by which a single POST request can search to find a matching address in the addresses table using parameters provided in the request, if a match is found create a new delivery. If no address is found, then error the request.

Here's what I have so far (not functional, but hoping I'm close(ish)):

Controller

   class DeliveriesController < ApplicationController    before_action :confirm_address, only: %i[ create edit update ]    protect_from_forgery with: :null_session, if: Proc.new {|c| c.request.format.json? }        def index    render json: Delivery.all   end      def create    # Delivery.address_id = Address.find_by(numeric: params[:numeric], street_name: params[:street])      # @address_of_delivery = Delivery.includes(:address).where(numeric: params[:numeric], street_name: params[:street_name], city: params[:city], state: params[:state], zip: params[:zip])      delivery = Delivery.new(delivery_params)    # @confirmed_address.id = self.address_id      puts 'putting'    # puts @address_of_delivery        if delivery.save      render json: {status: 'Awesome!', data: delivery}, status: :ok    else      render json: {status: 'Boo!', data: delivery.errors}, status: :unprocessable_entity    end  end     private      def delivery_params      params.permit(:company, :numeric, :street_name, :city, :state, :zip)    end          def confirm_address      @confirmed_address = Address.find_by(numeric: params[:numeric], street_name: params[:street_name], city: params[:city], state: params[:state], zip: params[:zip])                if @confirmed_address.present?           puts "found one!"        else          puts "NO DICE"          # self.address_id = confirmed_address.id    end    end  

As you can see from the controller, I've attempted several paths including using includes and join(not included in snippet), as well as trying to just hard code it.

Also tried to solve through the model, but had trouble accessing the params from the POST request:

class Delivery < ApplicationRecord      belongs_to :address        # accepts_nested_attributes_for :address      attribute :numeric      attribute :street_name      attribute :city      attribute :state       attribute :zip        before_validation :find_associated_address    def find_associated_address      Address.find_by(numeric: params[:numeric], street_name: params[:street])      puts 'working in model'  end    end  

Copy of the POST request for clarity:

Started POST "/deliveries" for ::1 at 2021-11-20 22:52:00 -0600  Processing by DeliveriesController#create as */*  Parameters: {"company"=>"slowcart", "numeric"=>"123", "street_name"=>"Any Street", "city"=>"NYC", "state"=>"NY", "zip"=>"010101"}  

I'm almost certainly making a stupid mistake, but can't find the right means to do what I want to do in the docs/broader web. Rails 6 application, btw.

Redux state being overwrite after changing another state

Posted: 21 Nov 2021 07:55 AM PST

I have a problem with Redux, when I change view and I make an API call to retrieve data, and I go back to my other view, the data is overwritten by "undefined", yet the two states have no incidence between them.

I have my actions and my reducers separated in two different files and they are well declared in my store which is coupled with redux-persist.

/screens/delivererNews.js

import React, { useCallback, useEffect } from 'react'  import { View, Text, FlatList, StyleSheet, ActivityIndicator } from 'react-native'  import { useDispatch, useSelector } from 'react-redux'  import { getNews } from '../../redux/action/deliverer/news'    const DeliverNews = () => {      const dispatch = useDispatch()        const getDeliverNews = useCallback((payload) => dispatch(getNews(payload)), [dispatch])        const token = useSelector(state => state.login.token)      const news = useSelector(state => state.news.list)      const pull_loading = useSelector(state => state.news.pull_loading)      const loading = useSelector(state => state.news.loading)        const onRefresh = () => {          getDeliverNews({ token, pull: true })      }        useEffect(() => {          getDeliverNews({ token, pull: false })      }, [])        return (          loading ? <ActivityIndicator style={{ flex: 1 }} size="small" color="#E95344" /> :                <View style={{ flex: 1 }}>                  <FlatList                      data={news}                      onRefresh={onRefresh}                      refreshing={pull_loading}                      renderItem={({ item }) => (                          <View style={local.container}>                              <Text style={local.title}>{item.title}</Text>                              <Text style={local.content}>{item.content}</Text>                          </View>                      )}                      keyExtractor={item => item.id}                  />              </View>      )  }    const local = StyleSheet.create({      container: {          flex: 1,          backgroundColor: 'white',          margin: 20,          shadowColor: 'grey',          shadowOffset: { width: 0, height: 0 },          shadowOpacity: 0.50,          shadowRadius: 11,          borderRadius: 10,      },      title: {          fontFamily: 'Fredoka One',          fontSize: 20,          color: '#424242',          marginHorizontal: 20,          marginVertical: 10,      },      content: {          fontFamily: 'Fredoka One',          fontSize: 17,          color: '#424242',          marginHorizontal: 20,          marginBottom: 20,      },  })    export default DeliverNews  

/screens/delivererProfil.js

import React, { useEffect, useCallback } from 'react'  import { View, Text, Image, StyleSheet } from 'react-native'  import CustomButton from '../../components/CustomButton';  import { reset } from '../../redux/action/deliverer/login';  import { useDispatch, useSelector } from 'react-redux';  import { getProfil } from '../../redux/action/deliverer/profil';    const DeliverProfil = ({ navigation }) => {      const dispatch = useDispatch()      const getDeliverProfil = useCallback((payload) => dispatch(getProfil(payload)), [dispatch])      const token = useSelector(state => state.login.token)      const user = useSelector(state => state.login.user)      const profil = useSelector(state => state.profil.infos)        useEffect(() => {          getDeliverProfil({ token: token, id: user.id })      }, [])        const telFormat = tel => {          if (!tel)              return null          var parse = tel.match(/.{1,2}/g);          var telFormatted = parse.join(" ");          return telFormatted      }          return (          <View style={local.container}>              <View style={{ alignItems: 'center' }}>                  <Image style={{ width: 90, height: 90, margin: 50 }} source={require('../../assets/img/da_logo.png')} />              </View>              <View style={local.fieldContainer}>                  <Image style={{ width: 22, height: 22 }} source={require('../../assets/img/person_red_icon.png')} />                  <Text style={local.textInfos}>{profil?.firstName + ' ' + profil?.lastName}</Text>              </View>              <View style={local.fieldContainer}>                  <Image style={{ width: 22, height: 24 }} source={require('../../assets/img/red_phone_icon.png')} />                  <Text style={local.textInfos}>{telFormat(profil?.tel)}</Text>              </View>              <View style={local.fieldContainer}>                  <Image style={{ width: 25, height: 25 }} source={require('../../assets/img/at_icon.png')} />                  <Text style={local.textInfos}>{profil?.email}</Text>              </View>              <View style={local.fieldContainer}>                  <Image style={{ width: 22, height: 30 }} source={require('../../assets/img/red_map_pin.png')} />                  <Text style={local.textInfos}>{profil?.city}</Text>              </View>              <CustomButton                  style={{ marginVertical: 30, marginHorizontal: 20 }}                  label="Déconnexion"                  backgroundColor={'#CD6561'}                  textColor={'white'}                  onPress={() => dispatch(reset())}              />            </View>      )  }    const local = StyleSheet.create({      container: {          backgroundColor: 'white',          margin: 20,          shadowColor: 'grey',          shadowOffset: { width: 0, height: 0 },          shadowOpacity: 0.50,          shadowRadius: 11,          borderRadius: 10,      },      textInfos: {          fontFamily: 'Fredoka One',          fontSize: 17,          color: '#5A5A5A',          marginLeft: 15,      },      fieldContainer: {          flexDirection: 'row',          alignItems: 'center',          marginBottom: 15,          marginHorizontal: 20,      }    })      export default DeliverProfil  

/actions/profil.js

import Request from '../../../axiosConfig';    export const GET_PROFIL_SUCCESS = 'GET_NEWS_SUCCESS'  export const GET_PROFIL_FAILURE = 'GET_NEWS_FAILURE'  export const LOADING = 'LOADING'  export const RESET_LOADING = 'RESET_LOADING'    function loading() {      return {          type: LOADING,      }  }    function resetLoading() {      return {          type: RESET_LOADING,      }  }    function getProfilSuccess(profil) {      return {          type: GET_PROFIL_SUCCESS,          profil: profil,      }  }    function getProfilFailure(error) {      return {          type: GET_PROFIL_FAILURE,          error,      }  }    export function getProfil(payload) {      return async dispatch => {          dispatch(loading())          await Request("/deliverer/" + payload.id, "get", null, payload.token)              .then(function (response) {                  dispatch(resetLoading())                  dispatch(getProfilSuccess(response.data))                  console.log("SUCCESS")              })              .catch((error) => {                      dispatch(resetLoading())                      dispatch(getProfilFailure(error))              });      }  }  

/reducers/profil.js

import { GET_PROFIL_SUCCESS, GET_PROFIL_FAILURE, LOADING, RESET_LOADING } from '../../action/deliverer/profil'    export const _INITIAL_STATE_ = {      loading: false,  }    export default function (state = _INITIAL_STATE_, action) {      switch (action.type) {          case RESET_LOADING: {              return {                  ...state,                  loading: false,              }          }          case LOADING:              return {                  ...state,                  loading: true,                  error: null              }          case GET_PROFIL_SUCCESS:              return {                  ...state,                  loading: false,                  profil: action.profil              }          case GET_PROFIL_FAILURE:              return {                  ...state,                  loading: false,                  error: action.error,              }          default:              return state      }  }    

/actions/news.js

import Request from '../../../axiosConfig';    export const GET_NEWS_SUCCESS = 'GET_NEWS_SUCCESS'  export const GET_NEWS_FAILURE = 'GET_NEWS_FAILURE'  export const LOADING = 'LOADING'  export const PULL_LOADING = 'PULL_LOADING'  export const RESET_LOADING = 'RESET_LOADING'  export const RESET_PULL_LOADING = 'RESET_PULL_LOADING'    function loading() {      return {          type: LOADING,      }  }    function pullLoading() {      return {          type: PULL_LOADING,      }  }    function resetLoading() {      return {          type: RESET_LOADING,      }  }    function pullResetLoading() {      return {          type: RESET_PULL_LOADING,      }  }    function getNewsSuccess(news) {      return {          type: GET_NEWS_SUCCESS,          news: news,      }  }    function getNewsFailure(error) {      return {          type: GET_NEWS_FAILURE,          error,      }  }    export function getNews(payload) {      return async dispatch => {          payload.pull ? dispatch(pullLoading()) : dispatch(loading())          await Request("/deliverer/news", "get", null, payload.token)              .then(function (response) {                  payload.pull ? dispatch(pullResetLoading()) : dispatch(resetLoading())                  dispatch(getNewsSuccess(response.data))                  console.log("SUCCESS")              })              .catch((error) => {                  if (error.response) {                      dispatch(resetLoading())                      dispatch(getNewsFailure(error.response))                  } else if (error.request) {                      dispatch(resetLoading())                      dispatch(getNewsFailure(error.request))                  } else {                      dispatch(resetLoading())                      dispatch(getNewsFailure(error.message))                  }                  dispatch(resetLoading(error.config))                  dispatch(getNewsFailure(error.config))              });      }  }  

/reducers/news.js

import { GET_NEWS_SUCCESS, GET_NEWS_FAILURE, LOADING, PULL_LOADING, RESET_LOADING, RESET_PULL_LOADING } from '../../action/deliverer/news'    export const _INITIAL_STATE_ = {      loading: false,      pull_loading: false,  }    export default function (state = _INITIAL_STATE_, action) {      switch (action.type) {          case RESET_LOADING: {              return {                  ...state,                  loading: false,              }          }          case RESET_PULL_LOADING: {              return {                  ...state,                  pull_loading: false,              }          }          case LOADING:              return {                  ...state,                  loading: true,                  error: null              }          case PULL_LOADING:              return {                  ...state,                  update_loading: true,              }          case GET_NEWS_SUCCESS:              return {                  ...state,                  loading: false,                  list: action.news              }          case GET_NEWS_FAILURE:              return {                  ...state,                  loading: false,                  error: action.error,              }          default:              return state      }  }  

/reducers.js

import { combineReducers } from 'redux'  import { persistReducer } from 'redux-persist'  import AsyncStorage from '@react-native-async-storage/async-storage'    import kitorder from './student/kitorder'  import kittracking from './student/kittracking'  import article from './student/article'  import login from './deliverer/login'  import notif from './deliverer/notif'  import news from './deliverer/news'  import profil from './deliverer/profil'    const rootPersistConfig = {      key: 'root',      storage: AsyncStorage,  }    const rootReducer = combineReducers({ kitorder, kittracking, article, login, notif, news, profil })    export const persistedReducer = persistReducer(rootPersistConfig, rootReducer)  

To illustrate the problem here is the behavior in action

To illustrate the problem here is the behavior in action

How to Log in F# in a functional way using NLog

Posted: 21 Nov 2021 07:55 AM PST

I have been looking at logging options and settled on NLog and logging to a database

I am fairly new to functional programming and have come from a background in C# OOP.

How would I implement logging in a functional way in F#?
Do I

  • Create the logger at the top level and just pass it in to every function as I go
  • Access the logger through a static method as needed ( obviously there would be some overhead to instantiating a logger each time - but maybe that's not a big deal )
  • Something else?

I want to avoid using a commercial logging option just because my projects are quite small.

Thanks for your time.

How to detect the text in Image using opencv and save result in CSV Format

Posted: 21 Nov 2021 07:56 AM PST

Hello Everyone I have the image in which the data is shown in notepad. I want to crop the notepad area, detect the text row-wise and save the result in CSV format I have tried the following but it does not give good results.

Input image

# Load the libraries  import cv2  import pytesseract    # Load the image  img = cv2.imread("/content/20211026_095828.jpg")    # Convert it to the gray-scale  gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)    # OCR detection  d = pytesseract.image_to_data(gry, config="--psm 6", output_type=pytesseract.Output.DICT)    # Get ROI part from the detection  n_boxes = len(d['level'])    # For each detected part  for i in range(n_boxes):        # Get the localized region      (x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])        # Draw rectangle to the detected region      cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 1)        # Crop the image      crp = gry[y:y+h, x:x+w]        # OCR      txt = pytesseract.image_to_string(crp, config="--psm 6")      print(txt)  plt.imshow(img)  

Any guidance here would be very helpful.

android how to avoid close of Toolbar's SearchView EditText line on UI update?

Posted: 21 Nov 2021 07:55 AM PST

I have a SearchView in my Toolbar for a RecyclerView list of CardViews and they are saved in a Room database. I filter the list with search text via the SearchView and then left-swipe one of the returned Cards to delete it from the database. The UI updates properly to show any remaining filtered CardViews.

Problem is when I click "x", the close button that I set up to the right of the search EditText line. The filtered list disappears correctly after the left-swipe to delete the filtered card and the UI updates the new list of the remaining CardViews in the database correctly. However, during the update of the UI, the search EditText line and the "X" close button are destroyed and the Toolbar returns to showing the default state for the SearchView that I set up, which is to show the search icon as iconified.

However, I would like to keep the search EditText line open, clear the search text and keep the "x" close button to the right of the EdixtText line after the UI is updated.

I tried adding the below code snippets to the mSearchView, the searchItem and the mSearchEditText variables, to try to re-open the search EditText line after the UI update, with no luck:

.setIconified(false);

.performClick();

.expandActionView();

.requestFocus();

I also put the ViewModel update for the Room database in a background thread with an ExecutorService and then tried to update the UI and clear the search EditText line on the main thread, after the background thread had completed. But the search icon as iconified was still returned.

So what am I missing? How can I achieve?

MainActivity.java    @Override  public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.mainactiv_menu, menu);      searchItem = menu.findItem(R.id.action_search);      menu.findItem(R.id.action_search).setVisible(false);        if (cardsAdapter != null && cardsAdapter.getItemCount() > 0) {          menu.findItem(R.id.action_search).setVisible(true);      }        SearchManager searchManager = (SearchManager)      MainActivity.this.getSystemService(Context.SEARCH_SERVICE);        if (searchItem != null) {            mSearchView = (SearchView) searchItem.getActionView();          mSearchView.setOnQueryTextFocusChangeListener(new SearchViewFocusListener(searchItem));          if (mSearchView != null) {                mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));              mSearchEditText = mSearchView.findViewById(androidx.appcompat.R.id.search_src_text);              mSearchEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);              mSearchEditText.setMaxLines(1);              ImageView closeButton = mSearchView.findViewById(R.id.search_close_btn);              closeButton.setOnClickListener(v -> {                    // gets the data from the Room database.                  mQuickcardViewModel.loadFullList();                    // reload the database data in to the RecyclerView Adapter.  This destroys                   // the search EditText line for the SearchView and also destroys the "x" close                   //  button and the search icon re-appears.                   cardsAdapter.reloadFullList(mQuickcards);                    // Clear the current search text so the member can enter different search text.                  // This is not working as the UI shows the search icon as iconified.                  mSearchView.setQuery("",false);              });      mainactiv_menu.xml    <?xml version="1.0" encoding="utf-8"?>    <menu      xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      xmlns:tools="http://schemas.android.com/tools"      tools:context=".MainActivity">        <item android:id="@+id/action_search"          android:title="@string/search_title"          android:icon="@drawable/ic_action_search"          app:actionViewClass="androidx.appcompat.widget.SearchView"          android:orderInCategory="1"          app:showAsAction="always|collapseActionView"  />        <item android:id="@+id/action_new"          android:title="@string/action_new"          android:icon="@drawable/ic_action_new"          tools:targetApi="o"          android:tooltipText="Add a quickcard"          android:orderInCategory="2"          app:showAsAction="always"  />          <item android:id="@+id/action_overflow"          android:title="@string/action_overflow"          android:icon="@drawable/ic_action_overflow"          android:orderInCategory="3"          app:showAsAction="always" >            <menu>                            <item                  android:id="@+id/number_of_cards"                  android:title=""                  app:showAsAction="always" />            </menu>        </item>    </menu>  

define a failure horizon based on serial number and failure label

Posted: 21 Nov 2021 07:55 AM PST

I wanted to re-label the healthy label (0) to failure label (1) 3 days before the actual failure (1) like what they did in the attached link: Reference link. It worked well for the equal time length but did not work for the variable length. That is, all serial number must fail in the same day which doesn't make sense. For the sample dataset, we see that serial C failed in January 5, 2014, A failed in January 6, and A failed in January 7. I want to relabel the re-label the healthy label (0) to failure label (1) 3 days before the actual failure (1) for the serial number C, and for the other serial numbers as well. I appreciate your time. Thanks!

My code:

import pandas as pd  import numpy as np  import datetime  from datetime import date, timedelta  df = pd.read_excel('/content/failure.xlsx')   df['date'] = pd.to_datetime(df['date'])  df = df.sort_values(by="date")  d = datetime.timedelta(days = 3)  a = []  for ind in df.index:    if df['failure'][ind] == 1:      sdate = df['date'][ind] - d      edate = df['date'][ind]      delta = edate - sdate       for i in range(delta.days + 1):        day = sdate + timedelta(days=i)        a.append(day)  mylist = list(dict.fromkeys(a))  mylist = pd.to_datetime(mylist,format='%y/%m/%d')  new_value = 1  for ind in df.index:    for item in mylist:      if df['date'][ind].date() ==  pd.to_datetime(item).date():         df['failure'][ind] = 1  

enter image description here

Databricks - is not empty but it's not a Delta table

Posted: 21 Nov 2021 07:56 AM PST

I run a query on Databricks:

DROP TABLE IF EXISTS dublicates_hotels;  CREATE TABLE IF NOT EXISTS dublicates_hotels  ...  

I'm trying to understand why I receive the following error:

Error in SQL statement: AnalysisException: Cannot create table ('default.dublicates_hotels'). The associated location ('dbfs:/user/hive/warehouse/dublicates_hotels') is not empty but it's not a Delta table

I already found a way how to solve it (by removing it manually):

dbutils.fs.rm('.../dublicates_hotels',recurse=True)  

But I can't understand why it's still keeping the table? Even though that I created a new cluster (terminated the previous one) and I'm running this query with a new cluster attached.

Anyone can help me to understand that?

the <script> tag with the jQuery library reference must be inside <head> or <body> tag? [duplicate]

Posted: 21 Nov 2021 07:56 AM PST

Possible Duplicate:
Where should I put tags in HTML markup?

I always thought that it's better to put it in the head (maybe because it is loaded first in the head and also to group all the scripts in the head for easy reading), but I found several examples over Internet (Bootstrap documentation, ASP.NET MVC 4, etc.) where the script tag with the reference to jQuery (</ script>) is inserted into the body:

<!DOCTYPE html>  <html>    <head>      <title>Bootstrap 101 Template</title>      <!-- Bootstrap -->      <link href="css/bootstrap.min.css" rel="stylesheet">  </head>    <body>      <h1>Hello, World!</h1>      <script src="http://code.jquery.com/jquery-latest.js"></script>      <script src="js/bootstrap.min.js"></script>  </body>    </html>  

What's the best practice?

No comments:

Post a Comment