Thursday, April 1, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to check if Google ReCaptcha is v2 or v3 on Server Side

Posted: 01 Apr 2021 12:29 PM PDT

I have a Web API that receives google recaptcha response and site key for server side verification on authentication.

I'd like to validate the version of recaptcha used to store this param as local statistic. There are a lot of different sites connecting to my API, so I want to store used version (v2 or v3) of Google ReCaptcha.

Is there any way? I would not like to create different routes or ask then to tell me by a parameter. Once it may not be true or both routes could be used by any version.

How to write an ImmutableList<Number> to a file?

Posted: 01 Apr 2021 12:29 PM PDT

This should be pretty simple, but it takes about a minute to write about 40 MB. There's got to be a better way. I imagine there's a lot of hangup on casting the Number to a double, but I'm not sure if that's where the problem lies. What's the fastest way to write an ImmutableList<Number> to a binary file of doubles?

public static void multiDoubleToImgFastForSO(String outFilename, ImmutableList<ImmutableList<Number>> arrays) {          FileOutputStream fos = null;          DataOutputStream dos = null;                    try {              fos = new FileOutputStream(outFilename);              dos = new DataOutputStream(fos);                            for (ImmutableList<Number> array : arrays) {                                    for (Number number : array) {                      dos.writeDouble(number.doubleValue());                  }              }                            dos.close();              fos.close();          } catch(Exception e) {              e.printStackTrace();          }      }  

User defined function for extracting gender from string excel data

Posted: 01 Apr 2021 12:28 PM PDT

I have an excel file with 100,000 rows of patient data including one column that contains patient information in a descriptive text. This text contains gender information as 'male' and 'female'. Some text does not have any gender information. For this I am interested in obtaining an 'na'.

I am trying to use a python user defined function for this data to extract gender by integrating python and excel using xlwings.

I wrote the following function which works within Thonny shell for python.

import xlwings as xw  import regex as re    @xw.func  def gender(x):      if re.search(r'\bfemale\b',x):          print('female')      elif re.search(r'\bmale\b',x):          print('male')      else:          print('na')  

But when I use it in excel, it gives me #NAME? error. I have the excel workbook and python files in the same folder with the same names without any '-' in the names. The import functions work for xlwings and I can run other sample functions. I removed extra spaces from all strings using vba code for replacing vbLf.

I am not sure what I am doing wrong. Please let me know if you need more information.

Thanks

How to get layer execution time on an AI model saved as .pth file?

Posted: 01 Apr 2021 12:28 PM PDT

I'm trying to run a Resnet-like image classification model on a CPU, and want to know the breakdown of time it takes to run each layer of the model.

The issue I'm facing is the github link https://github.com/facebookresearch/semi-supervised-ImageNet1K-models has the model saved as a .pth file. It is very large (100s of MB), and I don't know exactly how it differs from pytorch except it's binary. I load the model from this file using the following script. But I don't see a way to modify the model or insert the t = time.time() variables/statements in between model layers to break down the time in each layer.

Questions:

  1. Would running the model in the following script give a correct estimate of end-to-end time (t2-t1) it takes to run the model on the CPU, or would it also include pytorch compilation time?

  2. How to insert time statements between consecutive layers to get a breakdown?

  3. There is no inference/training script at the github link and only has the .pth file. So how exactly is one supposed to run inference or training? How to insert additional layers between consecutive layers of the .pth model and save them?

#!/usr/bin/env python  import torch torchvision time    model=torch.hub.load('facebookresearch/semi-supervised-ImageNet1K-models', 'resnext50_32x4d_swsl', force_reload=False)  in = torch.randn(1, 3, 224, 224)  t1 = time.time()  out = model.forward(in)  t2 = time.time()  ```**strong text**  

Rename File according to file path and Save as a CSV File

Posted: 01 Apr 2021 12:28 PM PDT

I want to be able to rename the file to the fifth file number then add on -TMP-AD-IFI-REV12

The file path only changes for the fifth file for new jobs (the bolded part) R:\3.0 Projects\2.0 Current Projects\2021 JOBS\ 999111-DO-Customer-Description \2.0 Estimate\2.7 Final Estimates\999111import-TMP-IFI-REV12.CSV

Such as for this example it will become 999111import-TMP-IFI-REV12

The file is to create a copy of the xlsm then saves it as a CSV

Sub OverwriteData_In_CSV()    Dim CSVfile  ***CSVfile = ThisWorkbook.Sheets("DataFeed").Cells("N1")***  ` ^ needs to be rewritten to properly save with new name.  Dim ws As Worksheet    Set ws = ThisWorkbook.Sheets("Foundation Budget Template")    '    Application.ScreenUpdating = False    ws.Select  ws.Copy  Application.DisplayAlerts = False  ActiveWorkbook.SaveAs Filename:=CSVfile, FileFormat:=xlCSV, local:=True  Application.DisplayAlerts = True  ActiveWorkbook.Close False  Application.ScreenUpdating = True    '  End Sub    
Function getName(pf): getName = Split(Mid(pf, InStrRev(pf, "\") + 1), ".")(0): End Function      Sub Test()    MsgBox getName(ActiveWorkbook.FullName)    End Sub  

Event Hub vs Apache Kafka review

Posted: 01 Apr 2021 12:28 PM PDT

We are planning on implementing either Azure Event Hub with Apache Spark or Apache Kafka with Apache Spark.

I understand the benefits or Kafka include its open source (free), whereas Azure Event Hub is easy to manage as its a PaaS. However, can someone let me know what are the other major factors the you would choose one streaming platform over another?

Diam at UNdirected graph with matrix

Posted: 01 Apr 2021 12:28 PM PDT

i have code that create a graph with symmetrical matrix (because it is an undirected graph). like this for exmple: enter image description here

somone can help me build a function in cpp that get a matrix like this and find the DIAM (the longest travel)?

int find_diam(int **matrix_graph, int NumOfVertex)........  

how to automatically scale uiOutput() when sidebar collapses in Shiny

Posted: 01 Apr 2021 12:28 PM PDT

I have a toggle switch which collapses the sidebar panel; however, when I do that, the datatable in uiOutput() doesn't stretch accordingly. I don't know what argument I am missing. I have changed the renderDatatable() arguments but nothing changed. Also, if possible, how can I change the render so that the datatable takes entire whitespace regardless of sidebard being collapsed?

library(shiny)  library(shinythemes)  library(shinyjs)  library(shinyWidgets)  #ui.r  ui <- fluidPage(    theme=shinytheme("flatly") ,      useShinyjs(),        dropdownButton(            tags$h3("Toggle"),            materialSwitch(inputId = "toggleSidebar",label = "Hide Table? ",                     value = TRUE, status = "success"),            circle = TRUE, status = "info",      icon = icon("gear"), width = "300px",            tooltip = tooltipOptions(title = "Choose for more options!")    ),            # Sidebar layout with input and output definitions     sidebarLayout(      div( id ="Sidebar",      # Sidebar panel for inputs      sidebarPanel(        uiOutput("rad")      )),            # Main panel for displaying outputs      mainPanel(        uiOutput("tabers")      )    )  )  #server.r    server <- function(input, output) {        data_sets <- list(NULL, iris, mtcars, ToothGrowth)            observeEvent(input$toggleSidebar, {      shinyjs::toggle(id = "Sidebar", condition = input$toggleSidebar)    })        output$rad<-renderUI({      radioButtons("radio", label = "",                   choices = list("Navigation" = 1, "Iris" = 2, "Mtcars" = 3,"ToothGrowth" = 4),                    selected = character(0))    })        output$tabers<- renderUI({      if(is.null(input$radio)) {        tabsetPanel(          id="tabC",          type = "tabs",          tabPanel("Welcome!")        )      }      else if(input$radio==1){        tabsetPanel(          id="tabA",          type = "tabs",          tabPanel("Navigation...")        )      }      else if(input$radio==2){        tabsetPanel(          id="tabA",          type = "tabs",          tabPanel("Data", DT::renderDataTable({ data_sets[[as.integer(input$radio)]]}, filter = 'top',                                                options = list(scrollX = TRUE, lengthChange = TRUE, widthChange= TRUE))),          tabPanel("Summary",renderPrint({ summary(data_sets[[as.integer(input$radio)]]) }) ),          tabPanel("etc.")        )       }      else if(input$radio==3){        tabsetPanel(          id="tabA",          type = "tabs",          tabPanel("Data", DT::renderDataTable({ data_sets[[as.integer(input$radio)]]}, filter = 'top',                                                options = list(scrollX = TRUE, lengthChange = TRUE, widthChange= TRUE))),          #tabPanel("Plot" ),          tabPanel("etc.")        )       }      else if(input$radio==4){        tabsetPanel(          id="tabA",          type = "tabs",          tabPanel("Navigation", DT::renderDataTable({ data_sets[[as.integer(input$radio)]]}, filter = 'top',                                                      options = list(scrollX = TRUE, lengthChange = TRUE, widthChange= TRUE))),          tabPanel("Summary",renderPrint({ summary(data_sets[[as.integer(input$radio)]]) }) ),          tabPanel("etc.")        )      }      # Left last else in here but should not get called as is      else{        tabsetPanel(          id="tabC",          type = "tabs",          tabPanel("Global"),          tabPanel("Performance" )        )       }    })  }    shinyApp(ui, server)    

enter image description here enter image description here

I was wondering if I can get some assistance with that, please!

How do I update the weather information within my layout in pysimplegui and show it every time I press 'refresh' within my window?

Posted: 01 Apr 2021 12:29 PM PDT

I'm trying to connect my 'refresh' button to my columns/layout to be able to produce updated weather results every time I press the button. I'm having a hard time creating a function out of updating these results too as my code seems to always 'be out of reach' to what's in the function. Here's my code:

from bs4 import BeautifulSoup as Soup  from urllib.request import urlopen as uReq  import PySimpleGUI as sg  import requests  import os  import time    my_url = 'https://forecast.weather.gov/MapClick.php?lat=41.279&lon=-72.8717'  uClient = uReq(my_url)  page_html = uClient.read()  uClient.close()    page_Soup = Soup(page_html, 'html.parser')  days = page_Soup.findAll("li", {"class": "forecast-tombstone"})      sg.theme('DarkBlue1')    day_titles = [day.img['title'].split(':')[0] for day in days]    day_imgs = [day.img['src'] for day in days]    os.chdir(r'C:\Users\Konrad\PycharmProjects\pythonProject\weather')  weather_images = []  for day in day_imgs:  image = 'https://forecast.weather.gov/{}'.format(day) file_name = str(image.split('.gov/'[1].replace('/', '').replace('?', '').replace('&', '').replace('=', ''))    weather_images.append(file_name)  r = requests.get(image)    with open(file_name, 'wb') as f:      f.write(r.content)    day_shorts = [str(day.find('p', {'class': 'short-desc'}))              .replace('<p class="short-desc">', '')              .replace('<br/>', ' ')              .rstrip('</p>') for day in days]    day_temps = [str(day.find('p', {'class': 'temp temp-high'}) or              day.find('p', {'class': 'temp temp-low'}))              .replace('<p class="temp temp-low">', '')              .replace('<p class="temp temp-high">', '')              .replace('<span style="color: #000000; font-weight:normal;">', '')              .replace('</span>', '')              .rstrip('</p>') for day in days]    columns = [      [sg.Text(day_title, size=(10, 0), pad=(7, 0), justification='c') for day_title in day_titles],      [sg.Image(r'C:\Users\Konrad\PycharmProjects\pythonProject\weather\{}'.format(file_name), key='day_image-') for file_name in weather_images],      [sg.Text(day_short, size=(10, 0), pad=(7, 0), justification='c') for day_short in day_shorts],      [sg.Text(day_temp, size=(10, 0), pad=(7, 0), justification='c') for day_temp in day_temps]  ]    columns += [[sg.Button('Refresh', key='-REFRESH-', bind_return_key=True), sg.Button('Exit', key='Exit-')]]    window = sg.Window('Weather', columns, alpha_channel=.8, no_titlebar=True, grab_anywhere=True, finalize=True, location=(3000, 450))    while True:      event, values = window.read()      if event is None or event == '-Exit-':          break      if event == '-REFRESH-':          event, values = window.read()    window.close()  

Regular expression to validate a name

Posted: 01 Apr 2021 12:29 PM PDT

I'm trying to create a regex that satisfies the following:

  • The length of the name should be between 2 and 30 characters (both inclusive)
  • The name can contain only alphabets and spaces
  • The first character of each word of the name should be an upper case alphabet
  • Each word should be separated by a space
  • The name should not start or end with a space
  • Special characters should not be allowed

Here's what I got so far:

^[A-Z][a-zA-z ]{1,29}$  

If I put a [^ ] at the end, it allows a special character.

Ruby - How to get elements of an array as comma separated strings?

Posted: 01 Apr 2021 12:29 PM PDT

I would like to get I18n.available_locales as "en", "fr", "de" so that I can use it in start_with?(values). Is there a way to achieve this? I would like to check if the request.path starts with locale. Thanks in advance.

How to convert python project to exe file [closed]

Posted: 01 Apr 2021 12:28 PM PDT

Hello I have a project here I want to convert it to .exe but its gave me some errors please help me to improve and fix it

https://github.com/maryus1991/myfirstapp

Passing in context variables to form

Posted: 01 Apr 2021 12:28 PM PDT

I want to pass in the parent_username variable in the below view function to the LevelTestModelForm, so that I could fill in one of the form inputs as that variable automatically. Here is the view:

def LevelTestView(request, pk):      parent_username = User.objects.get(pk=pk).username      form = LevelTestModelForm()      if request.method == "POST":          form = LevelTestModelForm(request.POST)          if form.is_valid():              form.save()              return reverse("profile-page")      context = {          "form": form      }      return render(request, "leads/leveltest.html", context)  

All I want is that the user can submit this form without having to input the parent_username. I honestly don't want the field to even show up on the form, but just add it automatically when the user submits the form. I hope you guys could help. Thanks a lot.

HTML multi-file input to get directory

Posted: 01 Apr 2021 12:29 PM PDT

I have this HTML input field:

<input    name="folderInput"    type="file"    id="folderInput"    webkitdirectory    directory    multiple    onchange="selectFolder();"  />  

It's a folder input, where you can select a folder and the code can get the files.

But when I get the files on a function, it returns me the full path of every file.

Actual behaviour (example) If the user introduced:

  • folder called foo which contains a file text.txt
  • and a folder called bar wich contains a file fooboar.txt

the code returns me this:

(fullpath)/foo/text.txt  (fullpath)/bar/foobar.txt  

How could I get the (fullpath)?

How can I get the path of the folder that the user has chosen?

type 'String' is not a subtype of type 'Map<String, dynamic>'

Posted: 01 Apr 2021 12:28 PM PDT

I am trying to retreive data from FirestoreFirebase but get this exception. Registering users and saving data to Firestore works well. I am new to programming and will be grateful for any suggestions

This is a method I use to set and fetch data

  import 'package:flutter/material.dart';  import 'package:firebase_auth/firebase_auth.dart';  import 'package:cloud_firestore/cloud_firestore.dart';    class MyProvider extends ChangeNotifier {    Map<String, dynamic> _names = {};      String name(String key) => _names[key];      void setName(String key, String newString) {      _names[key] = newString;      var firebaseUser = FirebaseAuth.instance.currentUser;      FirebaseFirestore.instance          .collection('Notes')          .doc(firebaseUser.uid)          .set(_names);    }      void fetchData() {      FirebaseFirestore.instance          .collection('Notes')          .doc('4igqxvELvzSvbYSqDre6eHlq29Y2')          .get()          .then((DocumentSnapshot documentSnapshot) {        if (documentSnapshot.exists) {          var data = documentSnapshot.data();          // print('Document data: ${data}');            _names = data['Sunday'];        } else {          print('The document does not exist on the database');        }      });    }  }    

This is Planner Screen where I want to see data from Firestore

  import 'package:flutter/material.dart';  import 'package:flutter/rendering.dart';  import 'package:my_planner_app/widgets/my_provider.dart';  import 'file:///C:/Users/krisk/AndroidStudioProjects/planner_app/lib/widgets/weekday_card.dart';  import 'package:provider/provider.dart';    class PlannerScreen extends StatefulWidget {    static const String id = 'planner_screen';      @override    _PlannerScreenState createState() => _PlannerScreenState();  }    class _PlannerScreenState extends State<PlannerScreen> {      Widget build(BuildContext context) {      Provider.of<MyProvider>(context, listen: false)          .fetchData();      var size = MediaQuery.of(context).size;        final double itemHeight = (size.height - 24) / 2;      final double itemWidth = size.width / 2;      return Scaffold(        backgroundColor: Color(0xFFcf9e9f),        body: Container(          child: GridView(            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(              crossAxisCount: 3,              childAspectRatio: (itemWidth / itemHeight),            ),            children: <Widget>[              WeekDayCard(                text: '',              ),              WeekDayCard(text: 'Monday' ),              WeekDayCard(text: 'Tuesday'),              WeekDayCard(text: 'Wednesday'),              WeekDayCard(text: 'Thursday'),              WeekDayCard(text: 'Friday'),              WeekDayCard(text: 'Saturday'),              WeekDayCard(text: 'Sunday'),              WeekDayCard(text: 'Notes'),            ],          ),        ),      );    }  }  

This is associated WeekDayCard widget

  import 'package:flutter/material.dart';  import 'package:my_planner_app/screens/addPlan_screen.dart';  import 'package:provider/provider.dart';  import 'package:my_planner_app/widgets/my_provider.dart';    class WeekDayCard extends StatefulWidget {    WeekDayCard({@required this.text, this.name});    final String name;    final String text;      @override    _WeekDayCardState createState() => _WeekDayCardState();  }    class _WeekDayCardState extends State<WeekDayCard> {    @override        Widget build(BuildContext context) {      return Consumer<MyProvider>(builder: (context, myProvider, child) {        return Card(          color: Color(0xFFFEEFCD),          elevation: 10,          child: Column(            children: [              Text(widget.text),              Text(Provider.of<MyProvider>(context).name(widget.text) ?? ''      ),              Expanded(                child: InkWell(                  onTap: () {                    showModalBottomSheet(                      backgroundColor: Color(0xFFFEEFCD),                      context: context,                      builder: (context) => AddPlanScreen(weekdayName: widget.text),                    );                  },                ),              ),            ],          ),        );      });    }  }    

This is associated AddPlanScreen

  import 'package:flutter/material.dart';  import 'package:provider/provider.dart';  import 'package:my_planner_app/widgets/my_provider.dart';    class AddPlanScreen extends StatefulWidget {    final String weekdayName;    const AddPlanScreen({Key key, this.weekdayName}) : super(key: key);      @override    _AddPlanScreenState createState() => _AddPlanScreenState();  }    class _AddPlanScreenState extends State<AddPlanScreen> {    String name;    @override    Widget build(BuildContext context) {      return Column(        children: [          Expanded(            child: TextFormField(              onChanged: (text) {                name = text;              },              decoration: InputDecoration(                border: InputBorder.none,              ),              minLines: 10,              maxLines: 30,              autocorrect: false,            ),          ),          FlatButton(            onPressed: () {              Provider.of<MyProvider>(context, listen: false)                  .setName(widget.weekdayName, name);              Navigator.pop(context);            },            color: Colors.blue,          ),        ],      );    }  }    

How do I make it so that if there is no term 'Short Long Term Debt' in the dataframe then short_long_term_debt = 0, but if there is use the final line

Posted: 01 Apr 2021 12:28 PM PDT

import pandas_datareader.data as web  import pandas as pd  import datetime  import requests  pd.set_option('display.max_rows', 500)  pd.set_option('display.max_columns', 500)  pd.set_option('display.width', 150)  ticker = yf.Ticker("ATVI")      financials = ticker.financials.T  balance = ticker.balance_sheet.T    interest_expense = financials['Interest Expense']['2020'].iloc[0]    if not balance['Short Long Term Debt']:     short_long_term_debt = 0    short_long_term_debt = balance['Short Long Term Debt']['2020'].iloc[0]      ---------------------------------------------------------------------------  

KeyError Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2897 try: -> 2898 return self._engine.get_loc(casted_key) 2899 except KeyError as err:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'Short Long Term Debt'

The above exception was the direct cause of the following exception:

KeyError Traceback (most recent call last) 2 frames /usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2898 return self._engine.get_loc(casted_key) 2899 except KeyError as err: -> 2900 raise KeyError(key) from err 2901 2902 if tolerance is not None:

KeyError: 'Short Long Term Debt'

Can't get searchBook method for specific donor

Posted: 01 Apr 2021 12:29 PM PDT

This program's goal is input book's title, donor, number of chapters, and location. From there, the user puts their input for this following prompt: "For search enter donor's name: ________". I am able to get all that information as an output. However, i cannot seem to figure out how to narrow down the results to just ONE donor. Instead, my program prints out all of the donor's listed in the entries. I have listed my program thus far below as well as my sample out and my desired output.

Thank you!

 package Books;    import java.util.Scanner;    public class Books {                      String title;          String donatedBy;          int numChapters;          String bookLocation;            void Book(){                title="ava Programming";                donatedBy="James Bond";                numChapters=25;                            bookLocation = "A-007";            }            Books(String title, String donatedBy, int numChapters, String bookLocation){                 this.title=title;               this.donatedBy=donatedBy;               this.bookLocation=bookLocation;                 if(numChapters<1){                   this.numChapters=25;                  }                  else{                      this.numChapters=numChapters;                  }              }              public String getTitle() {                  return title;              }              public String getDonatedBy() {                  return donatedBy;              }              public int getNumChapters() {                  return numChapters;              }              public void setDonatedBy(String donatedBy) {                  this.donatedBy = donatedBy;              }              public void setNumChapters(int numChapters) {                  this.numChapters = numChapters;              }              public void setTitle(String title) {                  this.title = title;              }              public String getLocation() {                  return bookLocation;              }              public void printDetails(){                  System.out.print("Title: \t"+title+" \nDonor: \t"+donatedBy+" \nChapters: "+numChapters + "\nLocation: " + bookLocation);              }              public static void main(String[] args) {                  Scanner scanner = new Scanner(System.in);                  System.out.print("Enter number of Books: ");                  int num = scanner.nextInt();                  scanner.nextLine();                  Books[] books = new Books[num];                    for (int i = 0; i < num; i++) {                      System.out.print("Enter the title: ");                      String title = scanner.nextLine();                      System.out.print("Enter the donor: ");                      String donor = scanner.nextLine();                      System.out.print("Enter the number of chapters: ");                      int chaps = scanner.nextInt();                      System.out.print("Enter the book location: ");                      String bookLocation = scanner.nextLine();                                            scanner.nextLine();                      books[i] =new Books(title, donor, chaps, bookLocation);                  }                                    boolean flag=false;                    for(int i=0; i<books.length;i++){                      Books b=books[i];                      System.out.print("\n\nBook "+(i+1)+": \n");                      b.printDetails();                                            if (b.getDonatedBy().equals("Daisy")){                          flag=true;                      }                     }                    if (flag){                      System.out.println("\nTask Complete. ");                  }                  scanner.close();              }      }  

Sample Output:

Enter number of Books: 3  Enter the title: Concrete Mathematics  Enter the donor: Donald Knuth  Enter the number of chapters: 12  Enter the book location: A-101  Enter the title: Auto Repair for Dummies  Enter the donor: Daisy  Enter the number of chapters: 16  Enter the book location: A-707  Enter the title: Is your Cat Trying to Kill You?  Enter the donor: Daisy  Enter the number of chapters: 35  Enter the book location: B-007      Book 1:   Title:  Concrete Mathematics   Donor:  Donald Knuth   Chapters: 12  Location:     Book 2:   Title:  Auto Repair for Dummies   Donor:  Daisy   Chapters: 16  Location:     Book 3:   Title:  Is your Cat Trying to Kill You?   Donor:  Daisy   Chapters: 35  Location:   Task Complete.   

Desired Output:

Enter number of Books: 3  Enter the title: Concrete Mathematics  Enter the donor: Donald Knuth  Enter the number of chapters: 12  Enter the book location: A-101  Enter the title: Auto Repair for Dummies  Enter the donor: Daisy  Enter the number of chapters: 16  Enter the book location: A-707  Enter the title: Is your Cat Trying to Kill You?  Enter the donor: Daisy  Enter the number of chapters: 35  Enter the book location: B-007    For search enter donor's name: Daisy     Book 2:   Title:  Auto Repair for Dummies   Donor:  Daisy   Chapters: 16  Location:     Book 3:   Title:  Is your Cat Trying to Kill You?   Donor:  Daisy   Chapters: 35  Location:   Task Complete.   

Calling default constructor from another constructor

Posted: 01 Apr 2021 12:28 PM PDT

I am supposed to create a triangle object using 3 points given by the user, and if the triangle isn't legal then create the default one. Is this a "legal" way to create the default one using the default method, or is this a weird scenario that isn't a way people do things?

public class Triangle    private Point _point1;  private Point _point2;  private Point _point3;    public Triangle()  {      _point1 = new Point(1,0);      _point2 = new Point(-1,0);      _point3 = new Point(0,1);  }    public Triangle(Point point1,Point point2,Point point3)  {      if (isLegal(point1,point2,point3))          {          _point1 = new Point(point1);          _point2 = new Point(point2);          _point3 = new Point(point3);          }      else          new Triangle();  }  

'LiveData' requires that 'User' inherit from 'LiveObject'

Posted: 01 Apr 2021 12:28 PM PDT

My project uses Swift 5.1 and I am experiencing difficulties running my unit tests with some Swift generics.

I have the code below with some type aliases and functions:

final class User: LiveObject { //... }  
func loadAllUsers(_ database: Database) -> LiveData<User> {    database.objects(User.self)  }  

Database:

typealias Object = LiveObject  func objects<T>(_ type: T.Type) -> LiveData<T> where T: Object {    realm.objects(type)  }  

LiveData and LiveObject are type aliases or extension of Realms types:

public typealias LiveData<T> = RealmSwift.Results<T> where T: LiveObject //[1. Requirement specified as 'T' : 'LiveObject' [with T = User]]  public typealias LiveList<T> = RealmSwift.List<T> where T: LiveObject    open class LiveObject: RealmSwift.Object { //... }  

But when calling the code below:

let users: LiveData<User> = loadAllUsers(database)  

I get this error: 'LiveData' requires that 'User' inherit from 'LiveObject'.

I really don't know what is happening, the code compiles fine the main application, the problem only happens when I run the XCTest. All the functions above are also called in the main application. I don't understand why the compiler cannot detect that User inherits LiveObject` when running the XCTest.

Error log:

enter image description here

I believe it's a problem with overloaded functions and objc. Is that correct?

Edit 1: Removing the types from the function sorted most of the issues (but why?).

Thanks!

Use of StrLoc nested into a macro in uninstall mode

Posted: 01 Apr 2021 12:28 PM PDT

I'm not an expert user of NSIS... while compiling a script I receive the following error:

!insertmacro: FUNCTION_STRING_StrLoc_Call  Call must be used with function names starting with "un." in the uninstall section.  

While uninstall, the following function is called:

Function un.Uninstall  ; some code    ${un.GetMsOfficeVersion} $R0    ; some code  FunctionEnd  

In turn, the following peace of code is called too:

!macro GetMsOfficeVersion  ; some code    StrCpy $R0 0  loop:      ClearErrors      EnumRegValue $R1 HKCU "Microsoft\Office\16.0\Common\Licensing\LastKnownC2RProductReleaseId" $R0      IfErrors done      IntOp $R0 $R0 + 1      ReadRegStr $R2 HKCU "Microsoft\Office\16.0\Common\Licensing\LastKnownC2RProductReleaseId" $R1      ${StrLoc} $R1 "$R2" "365" ">"          StrCmp $R1 "" +3 0          ;+3 if substring is not found          StrCpy $R1 "16.0"          Goto found      ${StrLoc} $R1 "$R2" "2019" ">"          StrCmp $R1 "" loop 0        ;loop if substring is not found          StrCpy $R1 "16.0"          Goto found  done:    ; other code  !macroend    !macro _GetMsOfficeVersion Result      ${CallArtificialFunction} GetMsOfficeVersion      Pop "${Result}"  !macroend    ; Insert function as an installer and uninstaller function.  !define GetMsOfficeVersion "!insertmacro _GetMsOfficeVersion"  !define un.GetMsOfficeVersion "!insertmacro _GetMsOfficeVersion"  

I know that the issue is because of the call to ${StrLoc} function. It should be different in install mode and uninstall mode respectively, that is ${StrLoc} and ${un.StrLoc} accordingly, but I don't know how to do it using this code structure

Any help would be very appreciated... thanks in advance

MYSQL store procedure replace multiple results into one parameter: Result consisted of more than one row

Posted: 01 Apr 2021 12:29 PM PDT

I have to write a store procedure MYSQL to get data from tables to send a notification for all customers about exchange rate every day with a notification template.

  1. CUSTOMER
customerCode | name | nationCode  0000001      | A    | VNM  0000002      | B    | CNH  
  1. SYSTEM_NATION
id | nationCode | ccy  1  | VNM         | VND  2  | CNH         | CNY  
  1. EXCHANGE_RATE
id | ccyFrom | ccyTo | rate   1 |  JPY     | VND  | 0.1  2 |  JPY     | CNY  | 0.3  

4.NOTIFICATION_TOKEN

id | customerCode | tokenId   1  | 0000001      | tokenExample1  2  | 0000002      | tokenExample2  

Now I want to get the data to send a daily rate notification for each customer corresponding to nationCode of them with a text form like this:

  Exchange rate: 1 JPY = {noti}exchangeRate{noti} {noti}varNotiCCYTo{noti}.  

And I expected

Customer 0000001

Exchange rate: 1 JPY = 0.1 VND.  

Customer 0000002

Exchange rate: 1 JPY = 0.3 CNY.  

I have store procedure to get data from tables I have mentioned above

DELIMITER $$  USE `gojp`$$  CREATE PROCEDURE `NotiGetExchangeRateEveryDay`()    DECLARE     varNotiBODY nVarchar (9000);  DECLARE     varNotiCCYTo nvarchar(3);  DECLARE     varNotiExchangeRate Numeric (30,2);    ###########################  #IMPORTANT: when I call this procedure, it responses         #Error Code: 1172. Result consisted of more than one row    #I think problem in this query:     *select ex.ccyTo, ex.rate into varNotiCCYTo, varNotiExchangeRate from CUSTOMER cus  inner join SYSTEM_NATION sys on cus.nationCode= sys.nationCode   inner join EXCHANGE_RATE ex on ex.ccyTo = sys.ccy;*  ##########################    set varNotiBODY = (SELECT REPLACE(varNotiBODY, '{noti}exchangeRate{noti}', ifnull(varNotiExchangeRate,'')) from dual);  set varNotiBODY = (SELECT REPLACE(varNotiBODY, '{noti}varNotiCCYTo{noti}', ifnull(varNotiCCYTo,'')) from dual);      After that I want to insert all this table to get list of notification was sent.  INSERT INTO `gojp`.`NOTIFICATION_QUEUE`   (`customerCode`,  `deviceID`,  `ntfBody`,  `createdDate`  )   select   noti.customerCode,   noti.tokenId,   varNotiBODY,   now()  from NOTIFICATION_TOKEN noti   inner join CUSTOMER cus on noti.customerCode = cus.customerCode;    END$$  DELIMITER ;    

I want to get data about exchange rate of each customer then replace into {noti}exchangeRate{noti}. However, it returns multiple results so I cannot insert into only one param.

So, anyone can give me a solution for this?

Pandas new column using a existing column and a dictionary

Posted: 01 Apr 2021 12:28 PM PDT

I have a data frame that looks like:

df = pd.DataFrame({"user_id" : ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],                     "score" : [0, 100, 50, 0, 25, 50, 100, 0, 7, 20],                    "valval" : ["va2.3", "va1.1", "va2.1", "va2.2", "va1.2",                               "va1.1", "va2.1", "va1.2", "va1.2", "va1.3"]})       

print(df)

     | user_id | score | valval   --------------------------------   0   |     a   |    0  | va2.3     1   |     b   |  100  | va1.1     2   |     c   |   50  | va2.1     3   |     d   |    0  | va2.2     4   |     e   |   25  | va1.2     5   |     f   |   50  | va1.1     6   |     g   |  100  | va2.1     7   |     h   |    0  | va1.2     8   |     i   |    7  | va1.2     9   |     j   |   20  | va1.3      

I also have a dictionary that looks like:

dic_t = { "key1" : ["va1.1", "va1.2", "va1.3"], "key2" : ["va2.1", "va2.2", "va2.3"]}  

I whant a new column "keykey".
This column´s values have the key of the dictionary of their correponding value.

The result would look something like this:

     | user_id | score | valval | keykey   ----------------------------------------   0   |     a   |    0  | va2.3  | key2   1   |     b   |  100  | va1.1  | key1   2   |     c   |   50  | va2.1  | key2   3   |     d   |    0  | va2.2  | key2   4   |     e   |   25  | va1.2  | key1   5   |     f   |   50  | va1.1  | key1   6   |     g   |  100  | va2.1  | key2   7   |     h   |    0  | va1.2  | key1   8   |     i   |    7  | va1.2  | key1   9   |     j   |   20  | va1.3  | key1  

Increase the lock timeout with sqlite, and what is the default values?

Posted: 01 Apr 2021 12:27 PM PDT

Well known issue when many clients query on a sqlite database : database is locked
I would like to inclease the delay to wait (in ms) for lock release on linux, to get rid of this error.

From sqlite-command, I can use for example (4 sec):

sqlite> .timeout 4000  sqlite>  

I've started many processes which make select/insert/delete, and if I don't set this value with sqlite-command, I sometimes get :

sqlite> select * from items where code like '%30';  Error: database is locked  sqlite>   

So what is the default value for .timeout ?

In Perl 5.10 programs, I also get sometimes this error, despite the default value seems to be 30.000 (so 30 sec, not documented).
Did programs actually waited for 30 sec before this error ? If yes, this seems crasy, there is at least a little moment where the database is free even if many other processes are running on this database

my $dbh = DBI->connect($database,"","") or die "cannot connect $DBI::errstr";  my $to = $dbh->sqlite_busy_timeout(); # $to get the value 30000  

Thanks!

Add leading zeroes in custom function in Google Apps Script

Posted: 01 Apr 2021 12:27 PM PDT

I'd like to create a custom function that does the same thing as Text(A1,"0000000"), but I have to do it in Google Apps Script because it will be incorporated into a more complicated custom function. Could anybody show me the correct way? Here is what I've been trying, and some derivations thereof:

 `/**   * Sets custom format as "0000000"   *   * @param {number} input The value to format.   * @return The input set to the new custom format   * @customfunction   */   function to_16ths(input) {   var n = input.setNumberFormat("0000000");   return n;   }   

React Router Routing three levels deep, Only works in App.js file

Posted: 01 Apr 2021 12:28 PM PDT

I am building a website with the following link structure:

  1. /blog
  2. /blog/post1
  3. /preview

The /blog url lists all the blog posts, the /blog/post1 shows the post in edit view and the preview button in the same edit view links to /preview url that shows the preview of the edited version. My initial idea was to use a /blog/post1/preview url but with the use of <Switch> it became complicated. It did not work because of the whole exact issue where I had to correctly match three urls that start with the same address. So I switched to /preview. Now, I can get the first to urls working but the /preview renders nothing on the screen. Is it because of where my <Link> and <Route> are defined in my app. I have following structure:

  <Switch>       <Route path='/blog'>         <Blog/>       </Route>     <Switch>  

in the main app.js

     <Route exact path='/blog'>         //div with some helper views like search bar       </Route>         //it is inside map function that renders a card view of many posts, post1 for simplicity       <Route path='/blog/post1'>         <PostEditor/>       </Route>  

in the main Post.js component

     <Route path='/preview'>         //Content       </Route>  

in the main PostEditor.js The PostEditor.js has the Link and Route tags in the same file but not others. Is it a reason that it renders nothing. When I move the Route tag from PostEditor, to App.js, everything works. Is it a nesting issue or something like that. I tried searching online but did not have much luck with multiple levels of nesting, usually it is two. Any help is greatly appreciated.
I am using react-router 5.2.0 and HashRouter as it works better with github

Update: I have added a sample sandbox to mimic my scenario. Why is the /preview link not rendering anything in this case? I would like to know what I am doing wrong in this case, cause I feel there is a knowledge gap about something about react-router that I am missing about creating Links and Routes at different level? Additionally, what would be the best alternative to handle what I am currently doing.


Code SandBox

Getting an fatal error when installing python package on EMR notebook: Python.h: No such file or directory

Posted: 01 Apr 2021 12:27 PM PDT

I need to install ahocorasick package on EMR notebook.

But when I call:

sc.install_pypi_package("pyahocorasick")  

I am getting an error:

common.h:15:10: fatal error: Python.h: No such file or directory       #include <Python.h>                ^~~~~~~~~~      compilation terminated.      error: command 'gcc' failed with exit status 1  

pandas installing without any problems.

I am getting the similar error when installing as a bootstrap action.

If I call:

%pip install pyahocorasick  

it is installing fine, but I can not import it.

I tried this approach: fatal error: Python.h: No such file or directory, python-Levenshtein install

But I can not find any way to run sudo from the notebook.

Edit:

I tried to install gcc on bootstrape stage with the following .sh file called on bootstrape stage:

sudo yum -y install gcc  sudo pip3 install pyahocorasick --user  

As a result I am getting an error:

Command "/usr/bin/python3 -u -c "import setuptools, tokenize;file='/mnt/tmp/pip-build-e2760aan/pyahocorasick/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-t39dq2bp-record/install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in /mnt/tmp/pip-build-e2760aan/pyahocorasick/

Is there a way to measure the time taken this algorithm takes to solve this Soduku Puzzle?

Posted: 01 Apr 2021 12:27 PM PDT

I have code to solve a sudoku puzzle using the Backtracking algorithm. I want to find out how long the Backtracking algorithm takes to solve the sudoku puzzle in seconds or milliseceonds using the python language.

My code is '''

As you can see I have attempted to time the solver function but it returns a number like 0.07027392299999846 which is not of the format required. I am requiring it to be in a clear readable format for humans to undestand. Such as minutes and seconds format.

What is the difference between MAUI and Uno Platform?

Posted: 01 Apr 2021 12:27 PM PDT

I'm a little confused. Can anyone explain exactly what the difference is between the two? When should we use MAUI and when UNO? As I realized, both can run on different platforms, so what is the reason for introducing two different technologies at the same time? Can they run on Windows 7? Or are they just limited to Windows 10? Can my WPF program run on Linux with these two technologies?

Logstash error : Failed to publish events caused by: write tcp YY.YY.YY.YY:40912->XX.XX.XX.XX:5044: write: connection reset by peer

Posted: 01 Apr 2021 12:28 PM PDT

I am using filebeat to push my logs to elasticsearch using logstash and the set up was working fine for me before. I am getting Failed to publish events error now.

filebeat       | 2020-06-20T06:26:03.832969730Z 2020-06-20T06:26:03.832Z    INFO    log/harvester.go:254    Harvester started for file: /logs/app-service.log  filebeat       | 2020-06-20T06:26:04.837664519Z 2020-06-20T06:26:04.837Z    ERROR   logstash/async.go:256   Failed to publish events caused by: write tcp YY.YY.YY.YY:40912->XX.XX.XX.XX:5044: write: connection reset by peer  filebeat       | 2020-06-20T06:26:05.970506599Z 2020-06-20T06:26:05.970Z    ERROR   pipeline/output.go:121  Failed to publish events: write tcp YY.YY.YY.YY:40912->XX.XX.XX.XX:5044: write: connection reset by peer  filebeat       | 2020-06-20T06:26:05.970749223Z 2020-06-20T06:26:05.970Z    INFO    pipeline/output.go:95   Connecting to backoff(async(tcp://xx.com:5044))  filebeat       | 2020-06-20T06:26:05.972790871Z 2020-06-20T06:26:05.972Z    INFO    pipeline/output.go:105  Connection to backoff(async(tcp://xx.com:5044)) established  

Logstash pipeline

02-beats-input.conf

input {    beats {      port => 5044    }  }  

10-syslog-filter.conf

filter {      json {          source => "message"      }  }  

30-elasticsearch-output.conf

output {    elasticsearch {      hosts => ["localhost:9200"]      manage_template => false      index => "index-%{+YYYY.MM.dd}"    }  }  

Filebeat configuration Sharing my filebeat config at /usr/share/filebeat/filebeat.yml

  filebeat.inputs:    - type: log      # Change to true to enable this input configuration.    enabled: true      # Paths that should be crawled and fetched. Glob based paths.    paths:      - /logs/*    #============================= Filebeat modules ===============================    filebeat.config.modules:    # Glob pattern for configuration loading    path: ${path.config}/modules.d/*.yml      # Set to true to enable config reloading    reload.enabled: false      # Period on which files under path should be checked for changes    #reload.period: 10s    #==================== Elasticsearch template setting ==========================    setup.template.settings:    index.number_of_shards: 3    #index.codec: best_compression    #_source.enabled: false    #============================== Kibana =====================================    # Starting with Beats version 6.0.0, the dashboards are loaded via the Kibana API.  # This requires a Kibana endpoint configuration.  setup.kibana:      # Kibana Host    # Scheme and port can be left out and will be set to the default (http and 5601)    # In case you specify and additional path, the scheme is required: http://localhost:5601/path    # IPv6 addresses should always be defined as: https://[2001:db8::1]:5601    #host: "localhost:5601"      # Kibana Space ID    # ID of the Kibana Space into which the dashboards should be loaded. By default,    # the Default Space will be used.    #space.id:    #----------------------------- Logstash output --------------------------------  output.logstash:    # The Logstash hosts    hosts: ["xx.com:5044"]      # Optional SSL. By default is off.    # List of root certificates for HTTPS server verifications    #ssl.certificate_authorities: ["/etc/pki/root/ca.pem"]      # Certificate for SSL client authentication    #ssl.certificate: "/etc/pki/client/cert.pem"      # Client Certificate Key    #ssl.key: "/etc/pki/client/cert.key"    #================================ Processors =====================================    # Configure processors to enhance or manipulate events generated by the beat.    processors:    - add_host_metadata: ~    - add_cloud_metadata: ~    

When I do telnet xx.xx 5044, this is the what I see in terminal

Trying X.X.X.X...  Connected to xx.xx.  Escape character is '^]'  

How many times a number appears in a numpy array

Posted: 01 Apr 2021 12:29 PM PDT

I need to find a way to count how many times each number from 0 to 9 appears in a random matrix created using np.random.randint()

import numpy as np  p = int(input("Length of matrix: "))  m = np.random.randint(0,9,(p,p))  print(m)  

For example if length of matrix = 4

  • [[3 4 6 5] [3 4 4 3] [4 2 4 8] [6 8 2 7]]

How many times does the number 4 appear? It should return 5.

No comments:

Post a Comment