Sunday, February 27, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to select from joined table

Posted: 27 Feb 2022 03:20 AM PST

I have table with Orders. each order has a list of Products (another table). Each product has Promotion with name. I want to get a list of promotions names from orders not older than 12 months but without repeats. How should my sql look like?

Virtual dog fence with ImageAI

Posted: 27 Feb 2022 03:20 AM PST

I'd like to detect when my dog sets foot in the lawn.

I have a fixed camera that streams a live video of my backyard, including the lawn. With the help of ImageAi I was able to quickly create code that tracks my dog in the video.

I'm wondering how should I detect when the dog actually sets foot in the lawn, as opposed to just roaming about the backyard. At this moment, my naive approach is to create a polygon that traces the contour of the lawn in the video feed, and see if the tracked dog's bounding box is mostly within this lawn polygon.

Any advice?

Why are nested loops considered as IN-EFFICIENT and BAD DESIGN and in code? What is the better alternative of nested loops?

Posted: 27 Feb 2022 03:20 AM PST

So I've written some java code, which converts a phone number (123456789) to corresponding English words (one two three four five six seven eight nine).

This java program also identifies the DOUBLE and TRIPLE consecutive occurrences of the numbers. In such a case, the first occurrence will be read as an individual number, followed by a "double" or "triple" occurrence of a number. For example, the number "1 2 222" will be read as "ONE TWO TRIPLE TWO".

public class DigitToWord {        public static Map<String, String> map;        static {          Map<String, String> result = new HashMap<>();          result.put("0", "zero");          result.put("1", "one");          result.put("2", "two");          result.put("3", "three");          result.put("4", "four");          result.put("5", "five");          result.put("6", "six");          result.put("7", "seven");          result.put("8", "eight");          result.put("9", "nine");          map = result;      }          public static String convertNumberToWords(String n) {          String result = "";          for(int i=0; i<n.length(); i++) {              String w = Character.toString(n.charAt(i));              String d = map.get(w) + " ";              if( (i < n.length()-2)  &&  ((Character.toString(n.charAt(i+1)).equals(w))  &&  (Character.toString(n.charAt(i+2)).equals(w))) ) {                  result = result + d + "double " + d;                  i += 2;              } else if( (i < n.length()-1)  &&  (Character.toString(n.charAt(i+1)).equals(w)) ) {                  result = result + " double " + d;                  i += 1;              } else {                  result = result + d;              }          }          return result;      }  }  

Here are the problems I believe are worth discussing:

Question 1. Why is this considered a bad design, due to these nested loops (especially for production code)? What is the better alternative to nested loops?

Question 2. How do we make this code scalable, If we add more functionality to this program?

The explanation for Q2: For instance, if there are FOUR consecutive numbers, print 'quadruple'. If FIVE consecutive numbers, print 'quintuple'. If SIX consecutive numbers, print 'sextuplet'.

PS: My naive approach, to solve Q2 is: to write another function to print 'quadruple', a separate function to print 'quintuple', another function to print 'sextuplet', and so on. This approach sounds pretty old-fashioned and ineffective though I'm open to your feedback and suggestions which I believe might help me improve.

Asymptote compiled on Git Bash gives Cygwin Error

Posted: 27 Feb 2022 03:19 AM PST

I recently installed Asymptote 2.78 and GhostScript 9.55 (as the MikTeX installation on Windows screws them both). I also deleted the old MikTeX packages. I wanted to compile a LaTeX file with asymptote code in it. When I compile it, MikTeX again downloads the old Asymptote (which I then delete) and produces a *.asy file. I have the asymptote exe here: C:\Program Files\Asymptote\asy.exe. When I run it on my *.asy (on GIT BASH), it produces the follwing error:

  0 [main] asy (5248) C:\Program Files\Asymptote\asy.exe: *** fatal error - cygheap base    mismatch detected - 0x180349408/0x180346408.    This problem is probably due to using incompatible versions of the cygwin DLL.    Search for cygwin1.dll using the Windows Start->Find/Search facility    and delete all but the most recent version.  The most recent version *should*    reside in x:\cygwin\bin, where 'x' is the drive on which you have    installed the cygwin distribution.  Rebooting is also suggested if you    are unable to find another cygwin DLL.  

Now here's the funny bit: I have not installed Cygwin on my Windows machine whatsoever. I even searched my computer using the Everything Search engine. There is no other cygwin1.dll. But there are some other cygwins belonging to Git. When I run the stuff from Windows Command Prompt, it works (even when I do not delete the MikTeX asy)! This is when I do latexmk -pdf *.tex on cmd prompt. I do not understand what is going on. Please help!!

Python 'ascii' codec can't encode character '\u05e5'

Posted: 27 Feb 2022 03:19 AM PST

In python I have:

ssdpDiscover = ('M-SEARCH * HTTP/1.1\r\n' + 'HOST: ' + sys.argv[          1] + ':1900\r\n' + 'MAN: "ssdp:discover"\r\n' + 'MX: 1\r\n' + 'ST: ssdp:all\r\n' + '\r\n')  sock.sendto(ssdpDiscover.encode('ASCII'), (sys.argv[1], 1900))  

where

sys.argv[1] is 172.23.86.31  

When I run my program on macOS it works fine, I tried another Ubuntu machine and got:

[Expert]# python3 'my_file'.py 172.23.86.31  Traceback (most recent call last):    File "my_file", line 42, in <module>      sock.sendto(ssdpDiscover.encode('ASCII'), (sys.argv[1], 1900))  UnicodeEncodeError: 'ascii' codec can't encode character '\u05e5' in position 30: ordinal not in range(128)  

Why I understand what the error means I don't understand what '\u05e5' it's talking about and why it works in one machine and not the other...

Discarding Value of OUT Parameter of Procedure in Postgresql

Posted: 27 Feb 2022 03:19 AM PST

Is there anyway to ignore the OUT parameter of a procedure?

I have a simple example procedure.

CREATE PROCEDURE my_proc(              OUT o_result TEXT,               OUT o_error TEXT,               p_status TEXT)      LANGUAGE plpgsql  AS  $$  BEGIN      p_status = 'do something with this';      o_result = FALSE;      o_error= 'error message here';  END;  $$;  

I always need to o_result out but only sometimes need the error message depending on the situation.

When calling the procedure I have to assign o_error to a variable or I get a SQL error (procedure not found). I've tried using NULL as the outbound variable when I call the procedure but that results in a different SQL error.

Is there anyway to ignore the o_error parameter when writing the CALL line, without having to assign a variable to it. Not a major issue just trying to remove some varaibles if not needed.

How to prevent dark mode inverting background images?

Posted: 27 Feb 2022 03:19 AM PST

I have a background image which gets inverted when a device is in dark-mode.

 #header {           position: relative;           background-image: url("../../images/backgroundimage.png");           background-size: cover;           background-position: center center;           background-attachment: fixed;           color: #fff;           text-align: center;           padding: 7.5em 0 2em 0;           cursor: default;       }  

When using

   filter: invert(0);   

it is not preventing the background image from getting inverted. Actually my whole webpage is already in dark colors. Could I force the dark mode to stop at all? If not, how can I prevent the image from getting inverted?

RestClient and thread locking

Posted: 27 Feb 2022 03:19 AM PST

Using Delphi 10.4

Using the tool REST Debugger, called an API, And got compoents.

Calling the Componets with

begin    writeln('starting');      RESTRequest1.Execute; writeln('finieshed 1');      RESTRequest2.Execute; writeln('finieshed 2');      RESTRequest3.Execute; writeln('finieshed 3');    writeln('Done.');    end;  

when i debug the code

and in the Execute there is a line

  // Eventhandlers AFTER Observers    HandleEvent(DoAfterExecute);  

which leads to the procedure:

class procedure TThread.Synchronize(const AThread: TThread; AMethod: TThreadMethod);  var    LSynchronize: TSynchronizeRecord;  begin    LSynchronize.Init(AThread, AMethod);    Synchronize(@LSynchronize); // <--- here  end;  

and the code locks.

I think its a dead lock, however I don't know what is locked.

the setup is a Thread in console application.

Download := TDownload.Create(nil);  // Simulate service start.  Download.ServiceStart(Download, MyDummyBoolean);  readln;  // On exit, destroy the service object.  FreeAndNil(DownloadInvoices);  

The Documentation of RestClient is lacking. What it is locked? or How to identify the locking procedure?

Heroku Discord Bot Offline

Posted: 27 Feb 2022 03:19 AM PST

Apparently I have followed every step here and I haven't encountered any issues in the build logs although my bot is offline. Any fix?

vhdl advanced counter with load test bench fails

Posted: 27 Feb 2022 03:19 AM PST

I have been given a counter built with mux and flip flop. The counter has enable and load in order to start counting from a specific value and not only from 0.This is counter's image.

the code for all the implementation is as follows:

mux2to1:

library ieee;  use ieee.std_logic_1164.all;    entity mux2to1 is      port(in1, in2, sel: in std_logic;           output: out std_logic);  end entity;    architecture bahavioral of mux2to1 is      begin          process(in1, in2, sel)              begin                  case sel is                      when '0' => output <= in1;                      when others => output <= in2;                  end case;          end process;  end architecture;  

d flip flop:

library ieee;  use ieee.std_logic_1164.all;    entity dff is      port(d, clock, reset: in std_logic;           q: out std_logic);  end entity;    architecture behavioral of dff is      begin          process(clock, reset)              begin                  if rising_edge(clock) then                      if reset = '1' then                          q <= '0';                      else                          q <= d;                      end if;                  end if;          end process;  end architecture;  

counter:

library ieee;  use ieee.std_logic_1164.all;    entity counter is      port(clock, reset, load, enable: in std_logic;           d: in std_logic_vector(3 downto 0);           a: out std_logic_vector(3 downto 0);           carry: out std_logic);  end entity;    architecture structural of counter is      component mux2to1          port(in1, in2, sel: in std_logic;               output: out std_logic);      end component;        component dff          port(d, clock, reset: in std_logic;               q: out std_logic);      end component;        signal xor_out, and_out, q_out, mux_out: std_logic_vector(3 downto 0);        begin          block00: mux2to1 port map(in1 => xor_out(0), in2 => d(0), sel => load, output => mux_out(0));          block01: mux2to1 port map(in1 => xor_out(1), in2 => d(1), sel => load, output => mux_out(1));          block02: mux2to1 port map(in1 => xor_out(2), in2 => d(2), sel => load, output => mux_out(2));          block03: mux2to1 port map(in1 => xor_out(3), in2 => d(3), sel => load, output => mux_out(3));          block04: dff port map (d => mux_out(0), clock => clock, reset => reset, Q => Q_out(0));          block05: dff port map (d => mux_out(1), clock => clock, reset => reset, Q => Q_out(1));          block06: dff port map (d => mux_out(2), clock => clock, reset => reset, Q => Q_out(2));          block07: dff port map (d => mux_out(3), clock => clock, reset => reset, Q => Q_out(3));          xor_out(0) <= q_out(0) xor enable;          xor_out(1) <= q_out(1) xor and_out(0);          xor_out(2) <= q_out(2) xor and_out(1);          xor_out(3) <= q_out(3) xor and_out(2);          and_out(0) <= enable and q_out(0);          and_out(1) <= and_out(0) and q_out(1);          and_out(2) <= and_out(1) and q_out(2);          and_out(3) <= and_out(2) and q_out(3);          carry <= and_out(3);          a <= q_out;            end architecture;  

testbench that I have write:

library ieee;  use ieee.std_logic_1164.all;    entity counter_tb is  end entity;    architecture counter_tb_arch of counter_tb is      component counter          port(clock, reset, load, enable: in std_logic;               d: in std_logic_vector(3 downto 0);               a: out std_logic_vector(3 downto 0);               carry: out std_logic);      end component;        signal clock_tb, reset_tb, load_tb, enable_tb: std_logic;      signal d_tb: std_logic_vector(3 downto 0);      signal a_tb: std_logic_vector(3 downto 0);      signal carry_tb: std_logic;        begin            dut: counter port map(clock => clock_tb,                                reset => reset_tb,                                 load => load_tb,                                 enable => enable_tb,                                 d => d_tb,                                 a => a_tb,                                 carry => carry_tb);            reset_stim: process              begin                  reset_tb <= '1'; wait for 20 ns;                  reset_tb <= '0'; wait;           end process;            clock_stim: process              begin                  clock_tb <= '0'; wait for 20 ns;                  clock_tb <= '1'; wait for 20 ns;          end process;            enable_stim: process              begin                  enable_tb <= '0'; wait for 50 ns;                  enable_tb <= '1'; wait;          end process;            load_stim: process              begin                  load_tb <= '0'; wait;          end process;      end architecture;  

And here is the image of the wave: wave image

Cannot render LaTeX in VScode Jupyter Notebook

Posted: 27 Feb 2022 03:19 AM PST

I have homework in VScode Jupyter Notebook but I get a lot of ParseError in it when displaying the LateX. The error is

ParseError: kaTeX parse error:Undefined control sequence.  

for example one of the Markdown cells is

$\newcommand{\vect}[1]{{\mathbf{\boldsymbol{{#1}}}}}$  This is the vector $\vect{x}$.  

and the jupyter cannot render it I guess? (I am not very familar with LateX) and will get the following error parse error

Dart Flutter sliderShow textFormField values ​on each page stay the same

Posted: 27 Feb 2022 03:18 AM PST

I have such an application:

enter image description here

The application purpose is to query whether the word entered in the textFormField corresponds to the meaning I keep in the list. This is a language app. The above screen is the test part.

I give the person a word and ask him to write it in Turkish.

But there is a problem here. I am using CarouselSlider for testing. Each slider screen has a textFormField. But every time I change the page, the value in the textFormField from the previous page remains.

Example:

Slider page 1:

enter image description here

Slider page 2:

enter image description here


The "Kontrol et" button is querying the correctness of the entered word.

I want the textFormField to be reset and empty on every page change. How can I do that?


Codes:

import 'package:flutter/material.dart';  import 'package:carousel_slider/carousel_slider.dart';  import 'package:getwidget/getwidget.dart';    class selamlasma_test1 extends StatelessWidget {    final CarouselController _controller = CarouselController();    final myController = TextEditingController();    List<wordAndMeaning> wordsList = [      wordAndMeaning("Hello", "Merhaba", false),      wordAndMeaning("What's up?", "Naber?", false),      wordAndMeaning("How are you?", "Nasılsın?", false),      wordAndMeaning("Good morning", "Günaydın", false),      wordAndMeaning("Good night", "İyi geceler", false),      ];    @override    Widget build(BuildContext context) {      return Scaffold(        appBar: AppBar(          backgroundColor: Colors.amber[500],          bottomOpacity: 0,          leading: IconButton(            icon: Icon(Icons.arrow_back_ios),            onPressed: () {              Navigator.pop(context);            },          ),          title: Text("Selamlama Testi 1", style: TextStyle(fontSize: 25),),        ),          body: Builder(builder: (context) {          final double height = MediaQuery.of(context).size.height;          return Column(            children: [              CarouselSlider(                carouselController: _controller,                options: CarouselOptions(                  height: height - 86.8,                  viewportFraction: 1.0,                  enlargeCenterPage: false,                ),                items: wordsList.map((wordAndMeaning word) {                  return Builder(                    builder: (BuildContext context) {                      return Container(                        width: MediaQuery.of(context).size.width,                        decoration: BoxDecoration(color: Colors.amber),                        child: Row(                          mainAxisAlignment: MainAxisAlignment.center,                          mainAxisSize: MainAxisSize.min,                          children: [                            Expanded(                              child: Column(                                mainAxisSize: MainAxisSize.min,                                children: [                                  Padding(                                    padding: EdgeInsets.all(15),                                    child: TextFormField( // <<<<!!!!!!!!                                      decoration: InputDecoration(                                        border: OutlineInputBorder(),                                        labelText: '"' + word.word + '"' + " Türkçesi", floatingLabelStyle: TextStyle(fontSize: 23),                                        prefix: Padding(                                          padding: EdgeInsets.only(left: 5, right: 10),                                          child: Icon(Icons.translate),                                        ),                                        labelStyle: TextStyle(                                          fontSize: 20,                                          fontWeight: FontWeight.bold,                                                                                  ),                                      ),                                      style: TextStyle(                                        fontSize: 20,                                        fontWeight: FontWeight.bold,                                      ),                                      controller: myController,                                      onChanged: (value) {                                                                              },                                    ),                                  ),                                  GFButton(                                    padding: EdgeInsets.only(left: 20, right: 20),                                    size: 45,                                    text: "Kontrol et", textStyle: TextStyle(fontSize: 25),                                    onPressed: () {                                       //eğer bir değer girilmemişse:                                      if (myController.text == "") {                                        Scaffold.of(context).showSnackBar(SnackBar(                                          content: Text("Lütfen bir değer giriniz!"),                                          duration: Duration(seconds: 2),                                        ),                                        );                                      }                                      if (myController.text.toLowerCase() == word.meaning.toLowerCase()) {                                        print("Doğru");                                      }                                    },                                  ),                                ],                              ),                            ),                            const SizedBox(                              width: 10,                            ),                                                      ],                        ),                      );                    },                  );                }).toList(),              ),            ],          );        }) ,      );    }  }    class wordAndMeaning {    String word;    String meaning;    bool showMeaning;      wordAndMeaning(this.word, this.meaning, this.showMeaning);  }  

Thanks in advance for the help.

Model Validation using C# & RestSharp (Selenium project)

Posted: 27 Feb 2022 03:18 AM PST

I'm using C# & Restsharp in order to create HTTP calls to one of our API's. I'm struggling with the Response retrieved by the API. I'd like to validate the model structure but didn't find any decent way of doing that on my side (handling the response).

For instance, I have a DTO object as the follow:

public class User  {      public string FirstName { get; set; }      public string LastName { get; set; }      public string PhoneNumber { get; set; }  }  

Sometimes, the Response object can include only the FirstName, without having the LastName and PhoneNumber at all and sometimes it might include more properties (Country, PostalCode etc...). I should validate that the User model only includes the above (FirstName, LastName and PhoneNumber). Nothing more, and nothing that is missing.

What's the best approach of doing that?

Join Operation - Python

Posted: 27 Feb 2022 03:19 AM PST

How to use inner join operation properly in Python? I have two dataframe that I need to combine using join. Here is the source code:

player = ['Player1','Player5','Player6']  power = ['Punch','Kick','Elbow']  title = ['Game1','Game5','Game6']  df3 = pd.DataFrame({'Player':player,'Power':power,'Title':title},index=['L1','L2','L3'])  df3    player = ['Player1','Player5','Player6']  power = ['Punch','Kick','Elbow']  title = ['Game1','Game5','Game6']  df4 = pd.DataFrame({'Player':player,'Power':power,'Title':title},index=['L1','L2','L3'])  df4    df3.join(df4, how='inner')  

Below is the error I am getting when running on to this code: [1]: https://i.stack.imgur.com/NdEY2.png

identify groups with few observations in paneldata models (stata)

Posted: 27 Feb 2022 03:20 AM PST

How can I identify groups with few observations in panel-data models?

I estimated using xtlogit several random effects models. On average I have 26 obs per group but some groups only record 1 observation. I want to identify them and exclude them from the models... any suggestion how? My panel data is set using: xtset countrycode year

Python "Replace" from central file

Posted: 27 Feb 2022 03:18 AM PST

I am trying to extend the replace function. Instead of doing the replacements on individual lines or individual commands, I would like to use the replacements from a central text file.

The text file would have the structure 'papa', 'papi 'dog', 'dogo 'cat', 'kitten etc.

Is this possible? I can't find any help Googling. But it could well be that I do not know the right terms or can not formulate.

How to access object properties before inizialization in JavaScript/ Typescript?

Posted: 27 Feb 2022 03:20 AM PST

I need to create a "Themes" object, which should contain all the themes with the colors I need for an app. I would like to use some of its variables to change its others. For example, having the "disabled" property set to the text color of the object + some opacity. I tried to achieve this by using this.variableName in template literals strings but I get an error saying I can't access it before initialization. Is there any way to achieve this without having to copy-paste the text each time manually?

Code sample:

const Themes = {      Dark: {          isDark: true,          BackgroundColors: {            primary: '#622BFF',            page: '#080246',            floating: '#1C1A70',            error: '#FF004F',            warning: '#FCE35E',            success: '#2ACF58',            /*I thought adding ${this.variableName} would have worked               but unfortunately it didn't            */            menu: `                    linear-gradient(                      180deg,                      ${this.Dark.BackgroundColors.floating} 0%,                       rgba(242, 24, 155, 0.9) 12%,                        ${this.Dark.BackgroundColors.floating} 100%                    )                  `,                      },          ContentColors: {            shared: '#622BFF',            text: '#FFFFFF',            //adding 99 for opacity            disabled: `${this.Dark.ContentColors.text}99`,            inverted: `${this.Dark.BackgroundColors.page}`,          },        },        Light:{            ......        }  }  

SQL statement timing out on large data set

Posted: 27 Feb 2022 03:19 AM PST

Trying to complete a web process, I'm getting the error canceling statement due to statement timeout. Debugging the codebase it turns out that the below query is timing out due to large data set. I appreciate any suggestions on how to increase the below query performance.

select userid, max(recent_activity_date) recent_activity_date   from (        SELECT id AS userid,          recent_logged_in AS recent_activity_date        FROM user        WHERE recent_logged_in > now() - cast('10 days' AS INTERVAL)        UNION        SELECT userid AS userid, max(recentaccessed) AS recent_activity_date        FROM tokencreds        WHERE recentaccessed > now() - cast('10 days' AS INTERVAL)        GROUP BY userid  ) recent_activity     WHERE EXISTS(select 1 from user where id = userid and not deleted)     group by userid     order by userid;    

Index per table:

  • Table user: user_recent_logged_in on user (recent_logged_in)
  • Table tokencreds: tokencreds_userid_token on tokencreds (userid, token). tokencreds_userid_token is unique.

what is best approach to query based on navigation property with EntityFramework

Posted: 27 Feb 2022 03:20 AM PST

Consider these two classes:

class Invoice {      // some props ...       public virtual List<InvoiceStatusLog> StatusLogs { get; set; }  }    class StatusLogs {      public InvoiceStatus Status { get; set; }      public int InvoiceID { get; set; }      public virtual Invoice Invoice { get; set; }  }  

What I want is to get invoices by their last status witch is last StatusLog status. I can do something like this:

var invoices = repository.SelectList(c => (c.Date >= _fromDate && c.Date <= _toDate)               && (c.StatusLogs.OrderBy(l => l.CreateDate).Last().Status == InvoiceStatus.Paid || c.StatusLogs.OrderBy(l => l.CreateDate).Last().Status == InvoiceStatus.MinorPaid));  

However, I really don't think this would be good idea as matter of performance and coding (repeating some expression everywhere ).

I know I can write a function which generates an expression based on status and can use that expression in body of selectList(), but first we have various conditions based on status ( && ... || && && .. ) and cant be generalized, and second: again I don't believe something like:

c.StatusLogs.OrderBy(l => l.CreateDate).Last().Status == InvoiceStatus.MinorPaid  

would have good performance. I would appreciate any suggestion

How can I check for specific remote address before accepting a TCP connection in Omnet++ with INET?

Posted: 27 Feb 2022 03:19 AM PST

I'm currently having a problem with my module which uses TCP in Omnet++ with INET.

I have typical client-server scenario where a server is listening for clients. I'm trying to figure out how to have control over which remote IP is actually accepted.

Usually, if server is not listening for clients at all, following pattern can be observed:

Client -----[SYN]-----> Server  Client <---[RST+ACK]--- Server  

I want to check Client's IP address in order to decide if the server should respond with [SYN+ACK] or [RST+ACK].

My module implements interface TcpSocket::ReceiveQueueBasedCallback and callback method, which is invoked as first, is socketAvailable which happens after SYN+ACK is already sent.

Is there any way to do this? I'm working with pretty much the newest version of INET.

Thanks in advance

Export python output to password protected zip file?

Posted: 27 Feb 2022 03:20 AM PST

I'm on the last step of a program that I have been creating. I have to export the output of my python program as a password protected zip file (I have been following these instructions). I was looking to use the pyminizip package to do so, but it will not install on my mac. The following error message appears in my terminal:

error: subprocess-exited-with-error        × python setup.py bdist_wheel did not run successfully.    │ exit code: 1    ╰─> [13 lines of output]        running bdist_wheel        running build        running build_ext        building 'pyminizip' extension        creating build        creating build/temp.macosx-10.9-universal2-3.10        creating build/temp.macosx-10.9-universal2-3.10/src        creating build/temp.macosx-10.9-universal2-3.10/zlib-1.2.11        creating build/temp.macosx-10.9-universal2-3.10/zlib-1.2.11/contrib        creating build/temp.macosx-10.9-universal2-3.10/zlib-1.2.11/contrib/minizip        clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch arm64 -arch x86_64 -g -Isrc -Izlib-1.2.11 -Izlib-1.2.11/contrib/minizip -I/Library/Frameworks/Python.framework/Versions/3.10/include/python3.10 -c src/py_miniunz.c -o build/temp.macosx-10.9-universal2-3.10/src/py_miniunz.o        xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun        error: command '/usr/bin/clang' failed with exit code 1        [end of output]        note: This error originates from a subprocess, and is likely not a problem with pip.    ERROR: Failed building wheel for pyminizip    Running setup.py clean for pyminizip  Failed to build pyminizip  Installing collected packages: pyminizip    Running setup.py install for pyminizip ... error    error: subprocess-exited-with-error        × Running setup.py install for pyminizip did not run successfully.    │ exit code: 1    ╰─> [13 lines of output]        running install        running build        running build_ext        building 'pyminizip' extension        creating build        creating build/temp.macosx-10.9-universal2-3.10        creating build/temp.macosx-10.9-universal2-3.10/src        creating build/temp.macosx-10.9-universal2-3.10/zlib-1.2.11        creating build/temp.macosx-10.9-universal2-3.10/zlib-1.2.11/contrib        creating build/temp.macosx-10.9-universal2-3.10/zlib-1.2.11/contrib/minizip        clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch arm64 -arch x86_64 -g -Isrc -Izlib-1.2.11 -Izlib-1.2.11/contrib/minizip -I/Library/Frameworks/Python.framework/Versions/3.10/include/python3.10 -c src/py_miniunz.c -o build/temp.macosx-10.9-universal2-3.10/src/py_miniunz.o        xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun        error: command '/usr/bin/clang' failed with exit code 1        [end of output]        note: This error originates from a subprocess, and is likely not a problem with pip.  error: legacy-install-failure    × Encountered error while trying to install package.  ╰─> pyminizip  

Having no clue how to even deal with packages, I am a bit confused in terms of how to approach the issue. Is this because I have a mac, and if so, what other approach could I take to export my list as a password protected zip file?

Running airflow with docker-compose behind nginx proxy (using nginxproxy/nginx-proxy and nginxproxy/acme-companion)

Posted: 27 Feb 2022 03:18 AM PST

I am running airflow 2 with docker-compose (works great) but I cannot make it accessible behind a nginx proxy, using a combo of nginxproxy/nginx-proxy and nginxproxy/acme-companion.

Other projects work fine using that combo (meaning, that combo is working fine) but it seems that I need to change some airflow cfgs to make it work.

The airflow docker-compose includes the following:

x-airflow-common:    &airflow-common    build: ./airflow-docker/    environment:      AIRFLOW__WEBSERVER__BASE_URL: 'http://abc.def.com'      AIRFLOW__WEBSERVER__ENABLE_PROXY_FIX: 'true'    [...]  services:    [...]    airflow-webserver:      <<: *airflow-common      command: webserver      expose:        - "8080"      environment:        - VIRTUAL_HOST=abc.def.com        - LETSENCRYPT_HOST=abc.def.com        - LETSENCRYPT_EMAIL=some.email@def.com      networks:        - proxy_default # proxy_default is the docker network the nginx-proxy container runs in        - default      healthcheck:        test: ["CMD", "curl", "--fail", "http://localhost:8080/health"]        [...]      [...]    [...]    networks:    proxy_default:      external: true  

Airflow can be reached under the (successfully encrypted) address, but when one opens that url it results in the "Ooops! Something bad has happened." airflow error, more specifically a "sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: session" error, even though it works fine when not behind the proxy.

What am I missing?

Pandas: Read csv where all values are quoted and comma is used as decimal separator

Posted: 27 Feb 2022 03:19 AM PST

I am currently trying to import a csv file in pandas that has a less than perfect format, as all the values including numbers are quoted. The format looks like this:

Date;Type;Amount;Currency;Category;Person;Account;Counter Account;Group;Note  "19.02.17";"Expenses";"-36,37";"EUR";"Groceries";"";"Bank account";"";"";""  

Now, I have tried importing this using the following command:

import pandas    dtypes = {"Type":"string", "Amount": "float"}  table = pandas.read_csv("data.csv", delimiter = ";", decimal = ",", parse_dates = ["Date"], dtype = dtypes, quoting = 3)  

So I have basically been trying to tell pandas that the decimal separator is comma, that the field delimiter is semicolon, and that the column "Amount" should be parsed as floats. However, trying to parse the file, I still get the error message:

ValueError: could not convert string to float: '689,15'"  

I assume the combination of the quotes and the comma decimal separator somehow is too much for pandas, even though I think I have technically provided it with all the information it needs.

The file is an export from a third-party program, so unfortunately I have no influence on the format. Does anyone know how to get pandas to swallow this?

Bonus question: If I read this file without providing explicit data types, I don't get any columns of type "string" as I would have expected, but instead "object" is used. Why is that?

k8s cron job runs multi times

Posted: 27 Feb 2022 03:18 AM PST

I've the following cronjob which delete pods in specific namespace.

I run the job as-is but it seems that the job doesnt run for each 20 min, it runs every few (2-3) min , what I need is that on each 20 min the job will be start delete the pods in the specific namespace and then terminate , any idea what could be wrong here?

apiVersion: batch/v1  kind: CronJob  metadata:    name: restart  spec:    schedule: "*/20 * * * *"    concurrencyPolicy: Forbid    successfulJobsHistoryLimit: 0    failedJobsHistoryLimit: 0    jobTemplate:      spec:        backoffLimit: 0        template:          spec:            serviceAccountName: sa            restartPolicy: Never            containers:              - name: kubectl                image: bitnami/kubectl:1.22.3                command:                  - /bin/sh                  - -c                  - kubectl get pods -o name | while read -r POD; do kubectl delete "$POD"; sleep 30; done  

Im really not sure why this happen...

Maybe the delete of the pod collapse

how can i add a functionality ( with the framework .net ) in shopify?

Posted: 27 Feb 2022 03:18 AM PST

I has created eshop in shopify and I want to add a functionality ( with the framework .net ) in shopify but I don't know how....

I searched on the internet but I didn't find anything just I found this link from the ShopifySharp github but I didn't understand how to use it.

Who can help me?

https://github.com/nozzlegear/ShopifySharp

I can't figure out what exactly I'm doing wrong when trying to get array elements

Posted: 27 Feb 2022 03:19 AM PST

Sorry if there's too much code, I'm just afraid it won't make sense otherwise.

So I'm creating a currency converter with JS, React, Mobx and MVVM pattern. The idea is that I'm getting rates from API, and the output is cards with currency name, rate and fluctuation.

I'm stuck here. Apparently what I commented out doesn't work because I have many cards and I can't get data for all of them from the first card and I see the error "can't read property of undefined - currencyType)

export class CardViewModel {    public constructor(private store: ICardStore, public model: CurrencyCard) {      makeObservable(this);      this.pastRate()    }          @computed    public get ready(): boolean {      return !!this.store.cardsArray;    }      // @computed    // private get rates() {    //   if (!this.store.cardsArray) throw new Error('Rates must be defined');    //   return this.store.cardsArray!;    // }      @computed    public get currencyType(): string {      return this.model.currencyType      //return this.rates[0].currencyType    }      @computed    public get exchangeRate(): number {      return this.model.exchangeRate      //return +this.rates[0].exchangeRate.toFixed(2);    }  

So I tried to get the correct rate for each card from this.model - CurrencyCard, but this didn't work either.

export class CurrencyCard implements ICard {        public currencyType: string;        @observable      public exchangeRate: number;          public constructor(currencyType: string, exchangeRate: number) {          makeObservable(this);          this.exchangeRate = exchangeRate;          this.currencyType = currencyType;      }        @observable      public update (exchangeRate: number) {          this.exchangeRate = exchangeRate;      }  }  

So the thing is, I'm creating an array of cards in Store. And in CardViewModel I believe I need to get one rate for a card. Then I pass this data to Card where the output is one card with the correct data. And then I'm creating a CardListViewModel and a CardList to output a list of cards.

CARDSTORE

  @computed    public get recentRates(): CurrencyCard[] {      return this.cardsArray = [...this.ratesMap.values()]    }      private async getRates() {      const rates = await this.api.loadRates();      runInAction(() => {        Object.entries(rates).forEach((rate) => {          if (this.ratesMap.has(rate[0])) {            this.ratesMap.get(rate[0])!.update(rate[1]);          } else {            let newCard = new CurrencyCard(rate[0], rate[1]);            this.ratesMap.set(rate[0], newCard);          }        });          });    }  }  

So when I try to output one card, it requires that there's a prop card inside the in App.tsx, and creates one card but with the data I pass (like <Card card={new CurrencyCard('blabla', 50)}

interface Props {    card: CurrencyCard  }    export const Card: React.FC<Props> = observer((props) => {    const { card } = props;    const currencyCardStore = DiContainer.get(ICardStore);    const viewModel = useMemo(() => new CardViewModel(currencyCardStore, card), [currencyCardStore, card]);      if (!viewModel.ready) return null;        return (          <CardView           currencyType={viewModel.currencyType}           exchangeRate={viewModel.exchangeRate}          change={viewModel.fluctuation}          />      )  });  

And when I try to output CardList, nothing happens and I have no errors in terminal or console.

export const CardList = observer(() => {    const currencyCardStore = DiContainer.get(ICardStore);    const viewModel = useMemo(() => new CardListViewModel(currencyCardStore), [currencyCardStore]);      if (!viewModel.ready) return null;      return (<div className={styles.currencyContainer}>      {viewModel.cards.map(card => <Card key={card.currencyType} card={card} />)}</div>)    });  

I would really appreciate some help because I'm stuck and just very tired already.

How to viewed bookin.php on cpdeigniter 4

Posted: 27 Feb 2022 03:19 AM PST

I'm calling the file called booking.php with Codeigniter 4, but I'm getting an error. Although I add the following lines to Home Controller, the page does not appear, where am I going wrong?

public function booking()  {  $this->load->view('Partials/home/head');  $this->load->view('Home/booking');  $this->load->view('Partials/home/foot');  }  

I'm calling the booking.php file, but it gives an error. as sitename.com/booking

public function index()  {  echoview('Partials/home/head');  echoview('Home/index');  echoview('Partials/home/foot');  }  

but I can call index.php as above. Again, I can't call a different /urly like /booking /contact etc

How to redirect Homepage to another page when user login

Posted: 27 Feb 2022 03:19 AM PST

I have a wordpress that users can register and become a member, and how do I get my homepage https://sample.com redirected to the settings page https://sample.com/setting for example. so when the user login, they cannot access the homepage which is https://sample.com

starting a node.js page on localhost - the site can't be reached

Posted: 27 Feb 2022 03:20 AM PST

I'm on Chrome / Windows 7 and trying to make my first node.js steps using this tutorial:

https://www.w3schools.com/nodejs/nodejs_get_started.asp

So myfirst.js is:

var http = require('http');    http.createServer(function (req, res) {    res.writeHead(200, {'Content-Type': 'text/html'});    res.end('Hello World!');  }).listen(8080);  

Going on http://localhost:8080/ I'm getting the error:

This site can't be reached localhost refused to connect.  Try:    Checking the connection  Checking the proxy and the firewall  ERR_CONNECTION_REFUSED  

Firewall is completely off.

Any help?

How to check if an element exists in DOM or not in JavaScript

Posted: 27 Feb 2022 03:19 AM PST

I removed an element from DOM with this code :

box1.parentNode.removeChild(box1);  

How can I check if box1 is in the DOM or not.

I want this because if I'll try to remove it from the DOM again, this will cause an error.

No comments:

Post a Comment