Wednesday, August 18, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to get all dependencies of Spring configuration class?

Posted: 18 Aug 2021 09:01 AM PDT

So I was trying to extend a configuration class to expose the id of my models, like this:

ExposeIdCofiguration.java

@Configuration  public class ExposeIdConfiguration extends RepositoryRestConfiguration{        public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {          config.exposeIdsFor(Book.class);      }  }  

But Eclipse give me this error:

Implicit super constructor RepositoryRestConfiguration() is undefined for default constructor. Must define an explicit constructor  

Eclipse then made me add a constructor to the class, and it no longer gives me error. Like this:

  @Configuration  public class ExposeIdConfiguration extends RepositoryRestConfiguration{            public ExposeIdConfiguration(              ProjectionDefinitionConfiguration projectionConfiguration,              MetadataConfiguration metadataConfiguration,               EnumTranslationConfiguration enumTranslationConfiguration) {          super(projectionConfiguration, metadataConfiguration, enumTranslationConfiguration);                }        public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {          config.exposeIdsFor(Book.class);      }  }    

But when I run this, Spring Boot gives me this:

Parameter 0 of constructor in com.myapps.libraryapp_db.ExposeIdConfiguration required a bean of type 'org.springframework.data.rest.core.config.ProjectionDefinitionConfiguration' that could not be found.  

After researching, it seems that Spring Boot normally autoconfigure this for you, but when you do it manually, you have to inject the constructor dependency on your own.

So my question is if there are any of those constructor parameter objects (like ProjectionDefinitionConfiguration) being created by Spring Boot, and if so, how can I auto-inject them.

Cheer!

OpenCV(4.1.1) Error: Assertion failed (!_src.empty()) in cvtColor C++

Posted: 18 Aug 2021 09:01 AM PDT

Hello I am facing the following error

OpenCV(4.1.1) Error: Assertion failed (!_src.empty()) in cvtColor.

Here is my code, I have tried changing the file path of my images and even using random images downloaded online but with no success. I have also tried reinstalling OpenCV and looking for help elswhere but no one can tell me what the issue is. Sorry if this question is broad in scope but I am stuck until this is fixed.

This code should simulate a human attention system as described in Itti & Koch's bottom-up Saccadic model. The following feature maps are currently implemented: -DoG edge detection -Fovea (bias for central field targets) -Familiarity (bias for targets that haven't been observed often)

#include <iostream>  #include <opencv2/core/core.hpp>  #include <opencv2/highgui/highgui.hpp>  #include <opencv2/imgproc/imgproc.hpp>  #include <fstream>  #include <math.h>  #include <string>  #include "opencv2/imgcodecs/legacy/constants_c.h"  #include "opencv2/imgproc/types_c.h"  #include <sys/types.h>  #include "opencv2/calib3d.hpp"    using namespace std;  using namespace cv;    Mat DoGFilter(Mat src, int k, int g);    //Default feature map weights  static int ColourWeight    = 60 ; //Saturation and Brightness  static int DoGHighWeight    = 60 ; //Groups of edges in a small area  static int DoGLowWeight     = 30 ; //DoG edge detection  static int FamiliarWeight = 5  ; //Familiarity of the target, how much has the owl focused on this before  static int foveaWeight    = 50 ; //Distance from fovea (center)    String ImagePath = "C:\task3image\image.jpg";    int main(int argc, char *argv[])  {      //==========================================Initialize Variables=================================      Mat Left = imread(ImagePath);      Mat LeftDisplay;      Left.copyTo(LeftDisplay);      Mat LeftGrey;      cvtColor(Left, LeftGrey, COLOR_BGR2GRAY);      Mat familiar(Left.size(),CV_8U,Scalar(255));      Point Gaze(Left.size().width/2,Left.size().height/2);        while (1){//Main processing loop            // ======================================CALCULATE FEATURE MAPS ====================================          //============================================DoG low bandpass Map==================================          Mat DoGLow = DoGFilter(LeftGrey,3,51);          Mat DoGLow8;          normalize(DoGLow, DoGLow8, 0, 255, CV_MINMAX, CV_8U);          imshow("DoG Low", DoGLow8);            //=================================================Fovea Map========================================          //Local Feature Map  - implements FOVEA as a bias to the saliency map to central targets, rather than peripheral targets          Mat fovea(Left.size(),CV_8U,Scalar(0));          circle(fovea, Gaze, 150, 255, -1);          cv::blur(fovea, fovea, Size(301,301));          fovea.convertTo(fovea, CV_32FC1);          fovea*=foveaWeight;            //====================================Combine maps into saliency map================================          //Convert 8-bit Mat to 32bit floating point          DoGLow.convertTo(DoGLow, CV_32FC1);          DoGLow*=DoGLowWeight;          Mat familiarFloat;          familiar.convertTo(familiarFloat, CV_32FC1);            // Linear combination of feature maps to create a salience map          Mat Salience=cv::Mat(Left.size(),CV_32FC1,0.0); // init map          add(Salience,DoGLow,Salience);          add(Salience,fovea,Salience);            Salience=Salience.mul(familiarFloat);          normalize(Salience, Salience, 0, 255, CV_MINMAX, CV_32FC1);            //imshow("SalienceNew",Salience);          //=====================================Find & Move to Most Salient Target=========================================          double minVal; double maxVal; Point minLoc;          minMaxLoc(Salience, &minVal, &maxVal, &minLoc, &Gaze);            //Draw gaze path on screen          static Point GazeOld=Gaze;          line(LeftDisplay,Gaze,GazeOld,Scalar(0,255,255));          circle(LeftDisplay,GazeOld,5,Scalar(0,255,255),-1);          circle(LeftDisplay,Gaze,5,Scalar(0,0,255),-1);          GazeOld=Gaze;            // Update Familarity Map //          // Familiar map to inhibit salient targets once observed (this is a global map)          Mat familiarNew=familiar.clone();          circle(familiarNew, Gaze, 60, 0, -1);          cv::blur(familiarNew, familiarNew, Size(151,151)); //Blur used to save on processing          normalize(familiarNew, familiarNew, 0, 255, CV_MINMAX, CV_8U);          addWeighted(familiarNew, (static_cast<double>(FamiliarWeight)/100), familiar, (100-static_cast<double>(FamiliarWeight))/100, 0, familiar);          imshow("Familiar",familiar);            //=================================Convert Saliency into Heat Map=====================================          //this is just for visuals          Mat SalienceHSVnorm;          Salience.convertTo(Salience, CV_8UC1);          normalize(Salience, SalienceHSVnorm, 130, 255, CV_MINMAX, CV_8U);          normalize(Salience, Salience, 0, 255, CV_MINMAX, CV_8U);          Mat SalienceHSV;          cvtColor(Left, SalienceHSV, COLOR_BGR2HSV);            for(int y=0;y<Left.size().height;y++){              for(int x=0; x<Left.size().width;x++){                  SalienceHSV.at<Vec3b>(y,x)=Vec3b(255-SalienceHSVnorm.at<uchar>(y,x),255,255);              }          }          cvtColor(SalienceHSV, SalienceHSV, COLOR_HSV2BGR);              //=======================================Update Global View===========================================          imshow("LeftDisplay",LeftDisplay);          imshow("SalienceHSV",SalienceHSV);            //=========================================Control Window for feature weights =============================================          //cout<<"Control Window"<<endl;          namedWindow("Control", WINDOW_AUTOSIZE);          createTrackbar("LowFreq"  , "Control", &DoGLowWeight  , 100);          createTrackbar("FamiliarW", "Control", &FamiliarWeight, 100);          createTrackbar("foveaW"   , "Control", &foveaWeight   , 100);            waitKey(10);      }  }    // create DoG bandpass filter, with g being odd always and above 91 for low pass, and >9 for high pass  // k is normally 3 or 5  Mat DoGFilter(Mat src, int k, int g){      Mat srcC;      src.convertTo(srcC,CV_32FC1);      Mat g1, g2;      GaussianBlur(srcC, g1, Size(g,g), 0);      GaussianBlur(srcC, g2, Size(g*k,g*k), 0);      srcC = (g1 - g2)*2;      return srcC;    }  

Pester 5 default output way to long stacktrace

Posted: 18 Aug 2021 09:01 AM PDT

I just started using pester but recognized some weird behaviour when a test fails. I wrote this really basic pester script with 2 tests, one passing, one failing.

BasicPester.tests.ps1

Describe 'Basic Pester Tests' {    It 'A test that should be true' {      $true | Should -Be $true    }    It 'A test that should fail' {      $false | Should -Be $true    }  }  

I would assume the default ouput should look like this:

Starting discovery in 1 files.  Discovery found 2 tests in 17ms.  Running tests.  [-] Basic Pester Tests.A test that should fail 9ms (7ms|2ms)   Expected $true, but got $false.   at $false | Should -Be $true, C:\Code\work\pester_demo\BasicPester.tests.ps1:6  Tests completed in 214ms  Tests Passed: 1, Failed: 1, Skipped: 0 NotRun: 0  

But actually it outputs way longer stacktrace and somehow in german(my system language):

Starting discovery in 1 files.  Discovery found 2 tests in 17ms.  Running tests.  [-] Basic Pester Tests.A test that should fail 9ms (7ms|2ms)   Expected $true, but got $false.   at $false | Should -Be $true, C:\Code\work\pester_demo\BasicPester.tests.ps1:6   bei Invoke-Assertion, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 8078   bei Should<End>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 8016   bei <ScriptBlock>, C:\Code\work\pester_demo\BasicPester.tests.ps1: Zeile 6   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 1988   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 1949   bei Invoke-ScriptBlock, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 2110   bei Invoke-TestItem, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 1184   bei Invoke-Block, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 826   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 881   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 1988   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 1949   bei Invoke-ScriptBlock, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 2113   bei Invoke-Block, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 928   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 881   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 1988   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 1949   bei Invoke-ScriptBlock, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 2113   bei Invoke-Block, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 928   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 1662   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.ps1: Zeile 3   bei <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 3154   bei Invoke-InNewScriptScope, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 3161   bei Run-Test, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 1665   bei Invoke-Test, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 2465   bei Invoke-Pester<End>, C:\Program Files\WindowsPowerShell\Modules\pester\5.3.0\Pester.psm1: Zeile 5225   bei <ScriptBlock>, <Keine Datei>: Zeile 1  Tests completed in 214ms  Tests Passed: 1, Failed: 1, Skipped: 0 NotRun: 0  

I'm using Pester 5.3.0 on Windows 10 with Powershell 5.1. Am I doing anything wrong?

Vue component does not show

Posted: 18 Aug 2021 09:01 AM PDT

I am a beginner in Vue.js and in web development in general. I was following the vuejs guide here.

I was wondering when I was creating a vue component by Vue.component(NameOfComponent, {...}) and adding it to my HTML like this <NameOfComponent></NameofComponent>, the component did not show.

Like in the example below. The first argument of Vue.component is TodoItem which is the name of the component. When I added it as <TodoItem></TodoItem>, it did not show and there is an error: [Vue warn]: Unknown custom element: <todoitem> - did you register the component correctly? For recursive components, make sure to provide the "name" option. But <todo-item></todo-item> or even <todo-Item></todo-Item> showed.

Why? What name/naming convention should I use? Thank you!

Vue.component('TodoItem', {    template: '<li>This is a todo</li>'  })    const app = new Vue({    el: '#app',  })
<!DOCTYPE html>  <html>  <head>    <meta charset='utf-8'>    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>    <title>Vue docs</title>  </head>  <body>    <div id='app'>      <ol>        <TodoItem></TodoItem>      </ol>    </div>      <script src='main.js'></script>  </body>      </html>

How to build a module for Swift from Objective-C++ sources

Posted: 18 Aug 2021 09:01 AM PDT

How to build a module for swift, if all of my sources for this module are in Objective-C++ (which is a bridge for C++ code)? I want to use only CLI tools, not Xcode.

I tried to use swiftc -emit-module but it requires only swift sources, while I have only Objective-C++ and a C++ static library, which should be connected with Swift.

How to pass published values between view models?

Posted: 18 Aug 2021 09:01 AM PDT

I'm trying to pass on a published value from one view model to another (i.e. child view model need access to source and be able to manipulate value). I bet it is simple, however, I can't seem to find the "correct" way of doing within the MVVM pattern.

I've tried using @Bindings, Binding<Value>. I managed to get it work with @EnvironmentObject, but that means the view has to handle it because I can't pass it on to view model where the logic should be (ultimately I want to manipulate the data stream in the child view model using Combine). What have I missed?

I have simplified the situation with the following playground code:

import SwiftUI  import PlaygroundSupport    class InitialViewModel: ObservableObject {      @Published var selectedPerson: Person = Person(firstName: "", surname: "")  }    struct InitialView: View {      @StateObject var viewModel = InitialViewModel()        var body: some View {          ButtonView(selectedPerson: Published(wrappedValue: viewModel.selectedPerson) )            SelectedPersonView(selectedPerson: Published(wrappedValue: viewModel.selectedPerson))      }  }    class ButtonViewModel: ObservableObject {      @Published var selectedPerson: Person        init(selectedPerson: Published<Person>) {          self._selectedPerson = selectedPerson      }        func toggleSelectedPerson() {          if selectedPerson.firstName.isEmpty {              selectedPerson = Person(firstName: "Boris", surname: "Johnson")          } else {              selectedPerson = Person(firstName: "", surname: "")          }      }  }    struct ButtonView: View {      @ObservedObject var viewModel: ButtonViewModel        init(selectedPerson: Published<Person>) {          self._viewModel = ObservedObject(wrappedValue: ButtonViewModel(selectedPerson: selectedPerson))      }        var body: some View {          Button(action: { viewModel.toggleSelectedPerson()} ) {              Text("Press to select person")          }      }  }    class SelectedPersonViewModel: ObservableObject {      @Published var selectedPerson: Person        init(selectedPerson: Published<Person>) {          self._selectedPerson = selectedPerson      }  }    struct SelectedPersonView: View {      @ObservedObject var viewModel: SelectedPersonViewModel        init(selectedPerson: Published<Person>) {          self._viewModel = ObservedObject(wrappedValue: SelectedPersonViewModel(selectedPerson: selectedPerson))      }        var body: some View {          if viewModel.selectedPerson.firstName.isEmpty {              Text("No person selected yet")          } else {              Text("Person \(viewModel.selectedPerson.firstName) selected!")          }      }  }    struct Person {      let firstName: String      let surname: String  }    let view = InitialView()  PlaygroundPage.current.setLiveView(view)  

In essence, when I press the button, the selectedPerson property should be updated and the view should update accordingly.

is it possible to refresh a perticular div tag on page orentation change using javascript or jquery?

Posted: 18 Aug 2021 09:00 AM PDT

actually i have dropdown on my site and when i am rotating device from landscape to portrait and again from portrait to landscape the div class is not refreshing .

is there any way to update the particular section content or div tag using javascript or jquery .

i also have tried many ways like this

 $( "#dropdown" ).load(location.reload + " #dropdown" );

Moving Grouped Shapes in A3 equivalent sheets to complete a flow- Excel VBA

Posted: 18 Aug 2021 09:00 AM PDT

I am automating a flow diagram for a complete vehicle Program.

I am using VBA to create shapes that have all the details of Assemblies and components then grouping them. The flow has these components coming from main stations and substations. For simplification, all the mainline components are named as the First line of operations (FLOT), any components being referenced to FLOT are SLOT and similarly TLOT.

Part 1 is being manufactured at one station in the mainline and then transferred to the next station for manufacturing Part 2 which needs part 1. Part 2 may get any part being manufactured as SLOT and coming to the mainline, using two or more substations. In the flow, the arrow direction shows this. SLOT would go to the referenced FLOT and similarly, TLOT will go to the referenced SLOT.

How to proceed with placing these so that flow would be as per the input? The solution: I am grouping all shapes and arrows in a group and then try moving them in the A3 equivalent sheet. To create shapes I am using the point where rows and columns headings are meeting as (0,0).

As input, the name of the component and its referenced component is known. All the other information like supplier tool orientation is there.

Apache Beam: maintaining state in distributed KV table

Posted: 18 Aug 2021 09:00 AM PDT

I'm trying to better understand Beam computation model and to check if my problem is solvable within this model.

Suppose I have a stream of events,

class Event {      public int userId;      public int score;  }  

I want to build pipeline that:

  • reads stream of my events
  • maintains distributed KV table (we might use Apache Cassandra or any other similar system)
    • key is userId
    • value is maximum score for user

I've read about stateful processing and as far as I understand it's easy to maintain maximum score for user inside StatefulParDo. But how such state is stored is beam implementation detail and this state is not available outside StatefulParDo function.

Is it possible to keep such state in well defined format in some sort of KV storage available for external consumers (readers outside of my pipeline)?

pywinauto how to find more properties

Posted: 18 Aug 2021 09:00 AM PDT

im trying to do gui automation windows with pywinauto, python(pycharm) on some software i open software input username & password everything works fine after login the software new window is open with many option (tabs, treeMenu, etc) i print all the identifiers (print_control_identifiers()) but its not find all (even not half of the software features) for example when i do right click on something (to open menu) i cant find the identifiers (properties) to control the element also when i move tabs in the software and open new window when i click on something images for example:

enter image description here

enter image description here

how can i find every time all the elements in other tabs / window / menu / context menu. Basically all the elements in the software?

How to convert datetime format 2021-08-17T22:42:00.000Z to Date Format YYYY-MM-DD in Google Sheets

Posted: 18 Aug 2021 09:00 AM PDT

I have a script inputting dates in Date/Time format in my Google Sheet as a string as follows:

2021-08-17T22:42:00.000Z

I need to do some date calculations on this column and need the date in format YYYY-MM-DD without the Time information. Is there a way to convert the above string to date?

Thanks in advance for the help!!

Double pointer to a contiguous 2D array memory location issue

Posted: 18 Aug 2021 09:00 AM PDT

I have the following code in C language and can't figure out why exception (memory access violation) is being thrown. Can anyone help! In my understanding using the double pointer I should be able to access the array via indexing since it is contiguous.

uint8_t array_double[4][15];  uint8_t *single_ptr = array_double;  uint8_t **double_ptr = &single_ptr;  uint8_t value;    value = double_ptr[0][14]; // this works  value = double_ptr[1][0]; // throws an exception    

RxJS - Finalize not firing

Posted: 18 Aug 2021 09:01 AM PDT

For a logout request, I want to dispatch the same actions when the request is successful as well as when it fails. For this, I thought about using the finalize() operator.

However, it seems I can't get it working, as it appears to never get executed.

The effect:

    /**       * When the user logs out :       * Try to delete its push token       * Clear user       */      logout$ = createEffect(() =>          this.actions$.pipe(              ofType(ClassicAuthActions.logout),              switchMap(action => this.api.logout().pipe(                  map(() => ClassicAuthActions.logoutDidSuccess()),                  catchError(err => of(ClassicAuthActions.logoutDidFail())),                  finalize(() => of(                      ClassicAuthActions.deleteUserCommunicationToken(),                      ClassicAuthActions.clearUser(action.redirect)                  )),              ))          )      );  

Maybe I'm using the of() operator incorrectly?

I'm rather new to RxJS so any help would be appreciated.

Replacing Logical Operators in R

Posted: 18 Aug 2021 09:01 AM PDT

A missing value (NA) is one whose value is unknown. Hence, for logical operators in R, if any missing exists it will never return TRUE or FALSE, only NA. However, I would like to change such behavior so instead of returning NA it returns FALSE. See the example below.

1 > 2  FALSE    1 > NA  NA  

When asking if 1 > NA I want the result to be FALSE instead of NA. To accomplish that, I had to write the following function using Rcpp and replace the R > for its new version that uses the Rcpp function called RcppOP.

library("Rcpp")  RcppOP <- function(x, y, op) {    # op == 1: greater than    # op == 2: greater than or equals    # op == 3: less than    # op == 4: less than or equals    # op == 5: equals    # op == 6: different    n <- max(length(x), length(y))    nx <- length(x)    ny <- length(y)    if (nx == ny) {      x1 <- x;      y1 <- y;    } else if (nx %% ny == 0) {      x1 <- rep_len(x, n);      y1 <- rep_len(y, n);    } else if (ny %% nx == 0) {      x1 <- rep_len(x, n);      y1 <- rep_len(y, n);    } else {      warning("longer object length is not a multiple of shorter object length")      x1 <- rep_len(x, n);      y1 <- rep_len(y, n);    }    cppFunction('LogicalVector opFun(NumericVector x, NumericVector y, int op, int n) {    LogicalVector out(n);    if (op == 1) {      for (int i = 0; i < n; ++i) {        out[i] = x[i] > y[i];      }    }    if (op == 2) {      for (int i = 0; i < n; ++i) {        out[i] = x[i] >= y[i];      }    }    if (op == 3) {      for (int i = 0; i < n; ++i) {        out[i] = x[i] < y[i];      }    }    if (op == 4) {      for (int i = 0; i < n; ++i) {        out[i] = x[i] <= y[i];      }    }    if (op == 5) {      for (int i = 0; i < n; ++i) {        out[i] = x[i] == y[i];      }    }    if (op == 6) {      for (int i = 0; i < n; ++i) {        out[i] = x[i] != y[i];      }    }    return out;    }')    opFun(x1, y1, op, n)  }    # greater than  `>` <- function(x, y) {    RcppOP(x,  y, 1)  }  

Now, if I run 1 > NA it will return FALSE.

I am not an Rcpp expert and I wonder if someone could give me some feedback and help to improve it. Or let me know if this behavior can be changed without replacing the current R logical operators.

Thank you.

How to properly iterate over option class elements?

Posted: 18 Aug 2021 09:00 AM PDT

Suppose there are three option html classes:

  • options: option1, option2 and option3.

Would be great to iterate document.querySelector() over each option, something like:

while option in options:      document.querySelector(option)   else:      break      console.log("just executed all the html class options")  

What is the best way to iterate over a single instruction (document.querySelector())?

Replace the number by average of adjacent values

Posted: 18 Aug 2021 09:00 AM PDT

I have the following data:

data = [[1,2,-10,4,5],[-10,2,3,4,5],[1,2,3,4,-10],[1,2,-10,-10,5],             [-10,-10,3,4,5],[1,2,3,-10,-10]]  

My aim is to replace all the -10 by taking the average of the prices before and after the -10. If the adjacent values are not valid data like in [1,2,-10,-10,5], I'll need to replace with the value before.

For example, the first -10 would become 2 and the second will be the average of the replaced number 2 and 5.

I have the following code but are there anyways to optimise and shorten the code?

Thanks for the help

def clear_missingdata(data):      repeat = 0      for i in range(len(data)):          if(data[i] == -10):              right = -10              left = -10              if(i + 1 < len(data)):                  right = data[i + 1]              if(i - 1 >= 0):                  left = data[i - 1]              if(right != -10 and left != -10):                  data[i] = (right + left)/2              elif(right and left != -10):                  data[i] = right and left              elif(right == -10):                  repeat += 1          if(i != 0 and repeat > 0):              i = i - 1              right = -10              left = -10               if(i + 1 < len(data)):                  right = data[i + 1]              if(i - 1 >= 0):                  left = data[i - 1]              if(right != -10 and left != -10):                  data[i] = (right + left)/2              elif(right and left != -10):                  data[i] = right and left              repeat = 0      return(data)  

Expected output:

[1,2,3,4,5],[2,2,3,4,5],[1,2,3,4,4],[1,2,2,3.5,5],[3,3,3,4,5],[1,2,3,3,3]  

Hashicorp packer: How to init instance on first run?

Posted: 18 Aug 2021 09:00 AM PDT

I use Hashicorp Packer to create an AWS ubuntu image. And I need to perform some initialization of instance on first run. I know I can create a script that will run once. But I would like to know is there any out of the box solution since I can find nothing about this in documentation.

How to log the request url when an error occurs in asp net core?

Posted: 18 Aug 2021 09:00 AM PDT

Why does this code only gets executed when no error has occurred?

app.Use(async (context, next) => {      Console.WriteLine(context.RequestAborted.IsCancellationRequested);        if(context.Response.StatusCode < 200 || context.Response.StatusCode > 299) {          Console.WriteLine();          Console.WriteLine(context.Request.Method);          Console.WriteLine(context.Request.Path);      }            await next.Invoke();  });  

Is there an easy way to log the url and optionally body of the request when an unhandled exception occurs?

Google Sheets Highlight Duplicates But in Different Colors?

Posted: 18 Aug 2021 09:00 AM PDT

We want to create a file where we highlight duplicates values between 3 columns but the catch is that the colors are randomized or at least programmed to show different ones. I know we can assign specific colors from the conditional formatting tab but the idea is to make it randomized and have different colors with no specific criteria, so each color shows a unique set of duplicates.

If this is possible thru script editor then knowing a script for it would be much appreciated.

Attached is a manual depiction of the outcome. We have two duplicates highlighted in column A and they are colored differently.

Thank you for any help!

Sample Outcome

Can't run a github project on my localhost (Warning: require(mvc\models\ProductModel.php): failed to open stream)

Posted: 18 Aug 2021 09:00 AM PDT

So I have a group project at our school and I stuck at executing our code that other friends of mine were successfully run it. I am using MacOs and MAMP and I did installed Composer, and PHP Mongod driver in my laptop.

Here is our git file: https://github.com/insectaerc/MVP_auctionmarket

Here is the error I got:

enter image description here

I read a lot of other threads too and I tried it all but nothing works. Can you guys please help me! Thank you very much!

@digijay: So here is the output of composer update when I use git clone enter image description here

Google Cloud Run or Cloud Function for one-time-task-job

Posted: 18 Aug 2021 09:00 AM PDT

We have startup script that will create monitoring alerts using Google APIs.

For this we created a postman collection where we have bundled all these calls and then we wish to run a shell script where we will use service account json file and call the postman collection

export GOOGLE_APPLICATION_CREDENTIALS=/home/abc/sac-5f63.json  export TOKEN=$(gcloud auth application-default print-access-token)  echo $TOKEN  echo "Running postman collection start"  newman run /home/abc/API.postman_collection.json  

We created a docker file for this task with required dependencies and gcloud sdk as base image.

Now, We also want to give provision to execute this one time job in Google Cloud to users. For this we are considering options such as Cloud Run, Cloud Function, App Engine. But, all these services expose an endpoint and then it has to be called and the the service will perform the action.

Our requirement is a one time activity so we don't want to keep a service running all the time. Also, this is not a node js, java, go application that these services support.

It is more like a one time job task, that should get trigger do it's job and then stop.

Does google cloud support such a use case. Basic hello world docker is an example of this kind of requirement that we have - https://hub.docker.com/_/hello-world

We tried cloud run but it expects a portNo to be present with out which it fails

Deployment failed
ERROR: (gcloud.run.deploy) Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.

Please share some thoughts.

thanks, Aakash

how to setup ssh and "ssh_config" file correctly [closed]

Posted: 18 Aug 2021 09:00 AM PDT

I have noticed while learning how to setup ssh that lots of stackoverflow posts referred to the file ssh config being inside of the folder ~/.ssh but when i look at the same folder in my macbook the files listed are:

created from my last ssh setup

someprivatekey  someprivatekey.pub  known_hosts  

now when i inspect the folder cd /etc/ssh/ then i can see the file ssh_config there.

Is it a normal behavior or should ssh file "ssh_config" always be located in "~/.ssh" folder and I have presumably a wrong configuration?

(Sorry if the post sound very elementary, i am learning how to use ssh)

Thanks

How to show keystrokes of dead keys in Visual Studio

Posted: 18 Aug 2021 09:01 AM PDT

In Visual Studio I want to use a character which is composed of a dead key plus another key.

I type this : ` + e -> è

VS takes it as : 96 + 101 -> 232 ( and only shows 232)

or in HEx : 0060 + 0065 -> 00e8 ( and only shows 00e8 )

My problem now is that I want to be able to have access to both input key strokes ( eg 96 / 101 ) not the combined. (232) . How do I do that?

In addition I need to be able to distinguish other dead keys like backspace, linefeed, etc.

Office.context.mailbox.item.addFileAttachmentAsync is inconsistent if item.saveAsync is called right after

Posted: 18 Aug 2021 09:01 AM PDT

Here is the code that reproduces the issue in Script Lab:

$("#run").click(run);  let callbackCount = 0;  function run()   {    for(let i=0; i<10; i++)    {      Office.context.mailbox.item.addFileAttachmentAsync("https://ow2.res.office365.com/owalanding/2021.4.9.04/images/outlook-icon.jpg", "test.jpg", () => { console.log(callbackCount++)});            // If the following line is commented, the issue will be resolved.       Office.context.mailbox.item.saveAsync((res) => { console.log(res) });    }  }  

The above code results in only two or three attachments getting attached to the compose pane. As mentioned in the code, this issue is resolved if item.saveAsync is not called in the loop.

Another point to be noted is that the callback for item.saveAsync runs only once instead of ten times.

This issue was reproduced on:

  • New Outlook for Mac v16.52 (21080101)
  • macOS Big Sur 11.5.1

This issue cannot be reproduced on Old Outlook for Mac. The attachment gets attached ten times, as expected, on Old Outlook for Mac.

Show quarter markers instead of years in JSCharting Gantt Chart

Posted: 18 Aug 2021 09:00 AM PDT

I am new to this JSCharting library and working with it to create a Gantt Chart. When I map my data on the chart, it slices the Y Axis based on years. I am trying to slice it based on 3 months intervals. Instead of 2021, 2022, 2023, I want to show Q1, Q2, Q3, Q4 for each year.

One quick and dirty solution I found is below, to create markers on Y Axis like this:

{       yAxis: {          markers: [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028].reduce(            (all: { label: { text: string; color: string }; value: string }[], year) => {              return [                ...all,                ...[1, 4, 7, 10].map((month) => ({                  label: {                    text: month === 1 ? "Q1" : month === 4 ? "Q2" : month === 7 ? "Q3" : "Q4",                    color: "#ddd",                  },                  color: "#ddd",                  value: `${month}/1/${year}`,                  legendEntry: {                    visible: false,                  },                })),              ];            },            []          ),        },  }  

However, when I do that, first line of data covers the quarter labels like so.

enter image description here

Is there a proper way to do this and show it in the bottom with along with years? I'd appreciate any help.

enter image description here

Service Fabric and ASP.NET Core Web Application

Posted: 18 Aug 2021 09:00 AM PDT

I am in the process of creating a new ASP.NET Core project and I wanted to base it on React. Naturally, I tried using the React starter template which works great when doing vanilla ASP.NET.

When I try and do the same with Service Fabric, I run into issues. Mainly, I am doing a Stateless ASP.NET Core Service Fabric application using the React template. When I run the application, I am faced with an exception page with the following message:

AggregateException: One or more errors occurred. (One or more errors occurred. (The NPM script 'start' exited without indicating that the create-react-app server was listening for requests. The error output was: Error: EPERM: operation not permitted, mkdir 'C:\Windows\system32\config\systemprofile\AppData\Roaming\npm'

Error: EPERM: operation not permitted, mkdir 'C:\Windows\system32\config\systemprofile\AppData\Roaming\npm'

))

The issues start at the Startup.cs class with the following code snippet:

app.UseSpa(spa =>  {      spa.Options.SourcePath = "ClientApp";        if (env.IsDevelopment())      {          spa.UseReactDevelopmentServer(npmScript: "start");      }  });  

I looked up the middleware myself and tried to dig in a bit deeper to see what was happening. I started with the ReactDevelopmentExtension class and went from there. I noticed that the NodeScriptRunner is starting its own process and I wonder if something in there is causing this to happen. I thought that the different hosting models (in-process and out-of-process) were at play here but honestly, I am not so sure.

Has anyone tried using these templates with Service Fabric and succeeded?

Can't install psycopg2 package through pip install on MacOS

Posted: 18 Aug 2021 09:00 AM PDT

I am working on a project for one of my lectures and I need to download the package psycopg2 in order to work with the postgresql database in use. Unfortunately, when I try to pip install psycopg2 the following error pops up:

ld: library not found for -lssl  clang: error: linker command failed with exit code 1 (use -v to see invocation)  error: command '/usr/bin/clang' failed with exit status 1  ld: library not found for -lssl  clang: error: linker command failed with exit code 1 (use -v to see invocation)  error: command '/usr/bin/clang' failed with exit status 1  

Does anyone know why this is happening? Thanks in advance!

RightToLeft Layout in DevComponents.DotNetBar.SuperGrid

Posted: 18 Aug 2021 09:00 AM PDT

I want to change RightToLeft Layout in DevComponents.DotNetBar.SuperGrid to Yes or true , but when I set the property to Yes the layout was not changed.

Here's my code:

dataGridView1.RightToLeft =  System.Windows.Forms.RightToLeft.Yes;  

How can I correctly set the RightToLeft property?

npm install gives error "can't find a package.json file"

Posted: 18 Aug 2021 09:00 AM PDT

npm install / npm install -g command is not working in Windows 7

Node.js is installed properly, node.js version is v0.10.28

Couldn't read dependencies
ENOENT, open '"filepath"\package.json'
This is most likely not a problem with npm itself.
npm can't find a package.json file in your current directory.

Photo

Non-breaking non-space in HTML

Posted: 18 Aug 2021 09:01 AM PDT

I have a bowling web application that allows pretty detailed frame-by-frame information entry. One thing it allows is tracking which pins were knocked down on each ball. To display this information, I make it look like a rack of pins:

o o o o   o o o    o o     o

Images are used to represent the pins. So, for the back row, I have four img tags, then a br tag. It works great... mostly. The problem is in small browsers, such as IEMobile. In this case, where there are may 10 or 11 columns in a table, and there may be a rack of pins in each column, Internet Explorer will try to shrink the column size to fit on the screen, and I end up with something like this:

o o o    o  o o o   o o    o

or

o o  o o  o o   o  o o   o

The structure is:

<tr>      <td>          <!-- some whitespace -->          <div class="..."><img .../><img .../><img .../><img .../><br/>...</div>          <!-- some whitespace -->      </td>  </tr>  

There is no whitespace inside the inner div. If you look at this page in a regular browser, it should display fine. If you look at it in IEMobile, it does not.

Any hints or suggestions? Maybe some sort of &nbsp; that doesn't actually add a space?


Follow-up/Summary

I have received and tried several good suggestions, including:

  • Dynamically generate the whole image on the server. It is a good solution, but doesn't really fit my need (hosted on GAE), and a bit more code than I'd like to write. These images could also be cached after the first generation.
  • Use CSS white-space declaration. It is a good standards-based solution, but it fails miserably in the IEMobile view.

What I ended up doing

*hangs head and mumbles something*

Yes, that's right, a transparent GIF at the top of the div, sized to the width I need. End code (simplified) looks like:

<table class="game">      <tr class="analysis leave">          <!-- ... -->          <td> <div class="smallpins"><img class="spacer" src="http://seasrc.th.net/gif/cleardot.gif" /><br/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/pinsmall.gif"/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/></div> </td>          <!-- ... -->      </tr>  </table>  

And CSS:

div.smallpins {      background: url(/img/lane.gif) repeat;      text-align: center;      padding: 0;      white-space: nowrap;  }  div.smallpins img {      width: 1em;      height: 1em;  }  div.smallpins img.spacer {      width: 4.5em;      height: 0px;  }  table.game tr.leave td{      padding: 0;      margin: 0;  }  table.game tr.leave .smallpins {      min-width: 4em;      white-space: nowrap;      background: none;  }  

P.S.: No, I will not be hotlinking someone else's clear dot in my final solution :)

1 comment:

  1. E-Techbytes: Recent Questions - Stack Overflow >>>>> Download Now

    >>>>> Download Full

    E-Techbytes: Recent Questions - Stack Overflow >>>>> Download LINK

    >>>>> Download Now

    E-Techbytes: Recent Questions - Stack Overflow >>>>> Download Full

    >>>>> Download LINK En

    ReplyDelete