Tuesday, April 20, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


No HTTP response from private Docker registry container when connecting from host machine

Posted: 20 Apr 2021 08:29 AM PDT

I am trying to create a locally accessible Docker private registry using the official image located at: https://hub.docker.com/_/registry

I am on a Debian 10 (Buster) VPS. I followed the official instructions: https://docs.docker.com/registry/deploying/#run-a-local-registry

Started the container using:

docker run -d -p 5000:5000 --restart=always --name registry registry:2  

Tried to tag and push an image:

docker pull ubuntu:16.04  docker tag ubuntu:16.04 localhost:5000/my-ubuntu  docker push localhost:5000/my-ubuntu  

The last command gives the following error:

Get http://localhost:5000/v2/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)  

I am indeed unable to receive an HTTP response from the registry using curl as well. The registry seems to close the connection after a few seconds. Howewer, the connection does happen.

me@my-vps:~$ curl -v http://127.0.0.1:5000/v2  * Expire in 0 ms for 6 (transfer 0x5602a82d8fb0)  *   Trying 127.0.0.1...  * TCP_NODELAY set  * Expire in 200 ms for 4 (transfer 0x5602a82d8fb0)  * Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)  > GET /v2 HTTP/1.1  > Host: 127.0.0.1:5000  > User-Agent: curl/7.64.0  > Accept: */*  >  * Recv failure: Connection reset by peer  * Closing connection 0  curl: (56) Recv failure: Connection reset by peer  

The registry container's port seems to be correctly binded:

me@my-vps:~$ sudo docker ps  CONTAINER ID   IMAGE                         COMMAND                  CREATED         STATUS          PORTS                                       NAMES  e09e106fa953   registry:2                    "/entrypoint.sh /etc…"   5 minutes ago   Up 5 minutes    0.0.0.0:5000->5000/tcp, :::5000->5000/tcp   registry  

The weirdest thing is that when i try to access the registry from another machine, using my VPS's domain or IP address, everything is working.

PS C:\Users\Me> curl http://my-vps-domain:5000/v2      StatusCode        : 200  StatusDescription : OK  Content           : {}  RawContent        : HTTP/1.1 200 OK                      Docker-Distribution-Api-Version: registry/2.0                      X-Content-Type-Options: nosniff                      Content-Length: 2                      Content-Type: application/json; charset=utf-8                      Date: Tue, 20 Apr 2021 15:17:58 GMT                      ...  Forms             : {}  Headers           : {[Docker-Distribution-Api-Version, registry/2.0], [X-Content-Type-Options, nosniff],                      [Content-Length, 2], [Content-Type, application/json; charset=utf-8]...}  Images            : {}  InputFields       : {}  Links             : {}  ParsedHtml        : mshtml.HTMLDocumentClass  RawContentLength  : 2  

What i've tried so far:

  1. Forced IPv4 when using curl
  2. Used another host-binded port
  3. Used another container-binded port using environment variable called REGISTRY_HTTP_ADDR (https://docs.docker.com/registry/deploying/#customize-the-published-port).
  4. Tried with localhost, 127.0.0.1, [::1], i even tried with my public IP and domain and it still does not work.

The logs from the registry container after i tried docker push localhost:5000/my-ubuntu :

me@my-vps:~$ sudo docker logs registry  time="2021-04-20T15:21:27.482157366Z" level=warning msg="No HTTP secret provided - generated random secret. This may cause problems with uploads if multiple registries are behind a load-balancer. To provide a shared secret, fill in http.secret in the configuration file or set the REGISTRY_HTTP_SECRET environment variable." go.version=go1.11.2 instance.id=4fc8515d-ac59-4cc3-9ec3-d88202908971 service=registry version=v2.7.1  time="2021-04-20T15:21:27.48236043Z" level=info msg="redis not configured" go.version=go1.11.2 instance.id=4fc8515d-ac59-4cc3-9ec3-d88202908971 service=registry version=v2.7.1  time="2021-04-20T15:21:27.486053034Z" level=info msg="Starting upload purge in 40m0s" go.version=go1.11.2 instance.id=4fc8515d-ac59-4cc3-9ec3-d88202908971 service=registry version=v2.7.1  time="2021-04-20T15:21:27.494816825Z" level=info msg="using inmemory blob descriptor cache" go.version=go1.11.2 instance.id=4fc8515d-ac59-4cc3-9ec3-d88202908971 service=registry version=v2.7.1  time="2021-04-20T15:21:27.494990562Z" level=info msg="listening on [::]:5000" go.version=go1.11.2 instance.id=4fc8515d-ac59-4cc3-9ec3-d88202908971 service=registry version=v2.7.1  

So apparently, no error log or anything from within the container.

Also here are the listening connections from within the container:

me@my-vps:~$ sudo docker exec -it registry /bin/sh  / # netstat -paunt  Active Internet connections (servers and established)  Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name  tcp        0      0 :::5000                 :::*                    LISTEN      1/registry  

The issue seems very much to be network related, in my opinion. But i have no clue on how to fix it.

Thank you.

How do you print/inspect properties of an object in Ruby when none of these attempts work?

Posted: 20 Apr 2021 08:29 AM PDT

I'm trying to print the properties of an object (called $evm.object in the current scope). I know it has properties and methods I've used before and are documented, but I want to see what else is available (specifically I'm looking for a plural version of the 'default_value' property so I can use this object to set multiple values at once.)

I've tried:

require 'pp'    def log (s)    $evm.log(:info, "#{s}")  end    log("inspect pp the dialog object #{pp $evm.object}")  log("inspect public_methods the dialog object #{$evm.object.public_methods.sort}")  log("inspect to_json the dialog object #{$evm.object.to_json}")  log("inspect to_yaml the dialog object #{$evm.object.to_yaml}")  log("inspect instance_variables the dialog object #{$evm.object.instance_variables}")  log("inspect instance_variable_names the dialog object #{$evm.object.instance_variable_names}")  log("inspect instance_values the dialog object #{$evm.object.instance_values}")  log("inspect pretty_print the dialog object #{$evm.object.pretty_print($evm.object)}")  

Which prints:

[----] I, [2021-04-20T08:24:09.095960 #2701:102a4c38]  INFO -- : <AEMethod get_server_groups> inspect pp the dialog object /EXP/Dialog/VMWare/get_server_groups  [----] I, [2021-04-20T08:24:09.096652 #2701:102a4c38]  INFO -- : <AEMethod get_server_groups> inspect public_methods the dialog object [:!, :!=, :!~, :<=>, :==, :===, :=~, :__drbref, :__drburi, :__id__, :__send__, :_dump, :`, :acts_like?, :as_json, :blank?, :class, :clas  s_eval, :clone, :deep_dup, :define_singleton_method, :dup, :duplicable?, :enum_for, :eql?, :equal?, :extend, :freeze, :frozen?, :hash, :html_safe?, :in?, :instance_eval, :instance_exec, :instance_of?, :instance_values, :instance_variable_defined?, :instance_variable_get,   :instance_variable_names, :instance_variable_set, :instance_variables, :is_a?, :itself, :kind_of?, :method, :method_missing, :methods, :nil?, :object_id, :presence, :presence_in, :present?, :pretty_inspect, :pretty_print, :pretty_print_cycle, :pretty_print_inspect, :pre  tty_print_instance_variables, :private_methods, :protected_methods, :public_method, :public_methods, :public_send, :remove_instance_variable, :respond_to?, :send, :singleton_class, :singleton_method, :singleton_methods, :taint, :tainted?, :tap, :to_enum, :to_json, :to_pa  ram, :to_query, :to_yaml, :trust, :try, :try!, :untaint, :untrust, :untrusted?, :with_options, :yield_self]  [----] I, [2021-04-20T08:24:09.099348 #2701:102a4c38]  INFO -- : <AEMethod get_server_groups> inspect to_json the dialog object {"uri":"drbunix:///tmp/automation_engine20210420-2701-15mdml3","ref":252509280}  [----] I, [2021-04-20T08:24:09.101074 #2701:102a4c38]  INFO -- : <AEMethod get_server_groups> inspect to_yaml the dialog object --- !ruby/object:DRb::DRbObject  uri: drbunix:///tmp/automation_engine20210420-2701-15mdml3  ref: 252504960    [----] I, [2021-04-20T08:24:09.101589 #2701:102a4c38]  INFO -- : <AEMethod get_server_groups> inspect instance_variables the dialog object [:@uri, :@ref]  [----] I, [2021-04-20T08:24:09.102123 #2701:102a4c38]  INFO -- : <AEMethod get_server_groups> inspect instance_variable_names the dialog object ["@uri", "@ref"]  [----] I, [2021-04-20T08:24:09.102791 #2701:102a4c38]  INFO -- : <AEMethod get_server_groups> inspect instance_values the dialog object {"uri"=>"drbunix:///tmp/automation_engine20210420-2701-15mdml3", "ref"=>271171240}  [----] E, [2021-04-20T08:24:09.105232 #2701:10297b3c] ERROR -- : <AEMethod get_server_groups> The following error occurred during method evaluation:  [----] E, [2021-04-20T08:24:09.105535 #2701:10297b3c] ERROR -- : <AEMethod get_server_groups>   DRb::DRbRemoteError: undefined method `pp_object' for #<MiqAeMethodService::MiqAeServiceObject:0x0000000020535460> (NoMethodError)  

None of that is helpful except the public_methods. I'm baffled by the pp_object error since it gives a 'missing argument' error if I give it none. But the bottom line is how do I gain access to this object's properties?

Oh I should not forget to mention that I tried the usual .inspect method, but that just printed the uri and ref info that these other methods return.

Is there a way to resize and center a UWP app?

Posted: 20 Apr 2021 08:29 AM PDT

I am writing a small UWP app which is going to be launched from another app (the main app). I am hoping to decrease the window size of the UWP app.

I was able to change the window size by adding the code commented below into the App constructor. But I couldn't figure out how to make the UWP app center screen after I changed the window size. Any advices on making the UWP center screen is appreciated.

public App()  {      this.InitializeComponent();      this.Suspending += OnSuspending;      ApplicationView.PreferredLaunchViewSize = new Size(600, 400); //added code      ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize; //added code  }   

Create Google Analytics User-Id reporting view through Management API

Posted: 20 Apr 2021 08:28 AM PDT

The title says it all...

While I can create a user-id reporting view through the Visual Interface in GA, I was wondering if there's anyway for me to do it from the Management API

VBA to open Excel file based on cell value WITHIN that file

Posted: 20 Apr 2021 08:28 AM PDT

I've been looking all over the web for an answer to this question. I see many blogs and postings regarding opening an excel file based on a cell value NOT within that file.

My question: Is it possible to open a file based on a cell value within the file I am trying to open? Another way to word it: Can VBA search for a cell value within a file, that is not open, and then open that file if it finds that cell value?

Further Explanation:

I save reports from a system into a folder and these files being saved have a common name (Report, Report (1), Report (2), Report (3).....). However, the data within the reports are different. They all have a common cell (Cell A7) that designates what the report is for. I want to use VBA code to open one of these files based on its value in cell A7. Is this even possible?

Thank you in advanced for any direction here.

Customizing JQUERY/JAVASCRIPT and handling ajax xhr request and errors

Posted: 20 Apr 2021 08:28 AM PDT

For the first time today I used xhr request in my ajax method in order to upload an attach image

<script>              $(document).on('click', '#cancel', function () {                  swal.close()              });              $(document).on('click', '#submit', function (e) {                  e.preventDefault();                  swal.close();                  $.ajax({                      // Your server script to process the upload                      url: '{{route('client.transfer.post')}}',                      type: 'POST',                        // Form data                      data: new FormData($('form')[3]),                        // Tell jQuery not to process data or worry about content-type                      // You *must* include these options!                      cache: false,                      contentType: false,                      processData: false,                        // Custom XMLHttpRequest                      xhr: function (e) {                          if (e == '403'){                            }                          var myXhr = $.ajaxSettings.xhr();                          if (myXhr.upload) {                              // For handling the progress of the upload                              myXhr.upload.addEventListener('progress', function (e) {                                  if (e.lengthComputable) {                                      $('progress').attr({                                          value: e.loaded,                                          max: e.total,                                      });                                  }                              }, false);                          }                          return myXhr;                      },                      success: function (s) {                          $("#origin_error").empty().addClass('d-none');                          $("#destination_error").empty().addClass('d-none');                          $("#type_error").empty().addClass('d-none');                          $("#amount_error").empty().addClass('d-none');                          $("#transfer_date_error").empty().addClass('d-none');                          if (s.redirect) {                              window.location.href = s.redirect;                          }                      },                      error: function (e) {                          if (e.responseJSON.error) {                              $('html, body').animate({scrollTop: 0}, 1200);                              $("#response_errors").empty().addClass('d-none');                              $("#response_errors").removeClass('d-none').text(e.responseJSON.error);                          } else                              $("#response_errors").empty().addClass('d-none');                          if (e.responseJSON.errors.origin) {                              $("#origin_error").empty().addClass('d-none');                              $("#origin_error").removeClass('d-none').text(e.responseJSON.errors.origin[0]);                          } else {                              $("#origin_error").empty().addClass('d-none');                              if (e.responseJSON.errors.destination) {                                  $("#destination_error").empty().addClass('d-none');                                  $("#destination_error").removeClass('d-none').text(e.responseJSON.errors.destination[0]);                              } else {                                  $("#destination_error").empty().addClass('d-none');                                  if (e.responseJSON.errors.type) {                                      $("#type_error").empty().addClass('d-none');                                      $("#type_error").removeClass('d-none').text(e.responseJSON.errors.type[0]);                                  } else {                                      $("#type_error").empty().addClass('d-none');                                      if (e.responseJSON.errors.transfer_date) {                                          $("#transfer_date_error").empty().addClass('d-none');                                          $("#transfer_date_error").removeClass('d-none').text(e.responseJSON.errors.transfer_date[0]);                                          $(".type").val(1).trigger('change');                                      } else {                                          $("#transfer_date_error").empty().addClass('d-none');                                          if (e.responseJSON.errors.amount) {                                              $("#amount_error").empty().addClass('d-none');                                              $("#amount_error").removeClass('d-none').text(e.responseJSON.errors.amount[0]);                                          } else {                                              $("#amount_error").empty().addClass('d-none');                                              if (e.responseJSON.errors.img) {                                                  $("#file_error").empty().addClass('d-none');                                                  $("#file_error").removeClass('d-none').text(e.responseJSON.errors.img[0]);                                              }                                          }                                      }                                  }                              }                          }                      }                  });                  });  </script>  

As you see I get some json responses from back-end andinject them in view and set changes for errors. But this time with xhr request I can not handle and customize errors and the response throw like this:

enter image description here

PLEASE HELP ^__________^

Bigcommerce Checkout page edit

Posted: 20 Apr 2021 08:28 AM PDT

I am using Valult theme in bigcommerce and want to edit checkout page because i want to rename the a button. I went through all the files but there was no html check i found a tag {{{ checkout.checkout_content }}} in checkout page which is rending that part containing button. There is no file with contains the tag html. This content is rendered in Inspect element but when i view the source of page the content is not present there.

I tried to change the name of button with JS/JQ but it is not working because that Tag part wont comes in Source file but somehow it is present in inspect element.

How can it edit the Button name now ?

How should I convert numbers in a column to the same format style in Python?

Posted: 20 Apr 2021 08:28 AM PDT

I have two columns Lat and Long in a data frame. I try to convert these strings into float but I have the following error: ValueError: Unable to parse string "𝟒" at position 61754

I've noticed that in my data frame I have numbers written in different styles, even in bold text. I'm wondering if there is a way to convert the numbers in the same style.

Thank you in advance for your help!

Color CollapsingToolbarLayout after scrolling

Posted: 20 Apr 2021 08:28 AM PDT

I have a NestedScrollView, witch inside it has 3 block of layout, the first with a white background, the second gray and the last black. I would like that when my CollapsingToolbarLayout touches one block, it change his contentScrim color.

Now I'm implementing like this

scrollview.setOnScrollChangeListener { _, _, scrollY, _, oldScrollY ->              if(scrollY > 1400 && oldScrollY < 1400){                  reveal(collapsing_toolbar_layout, R.color.background)                  toolbar_name.setTextColor(ResourcesCompat.getColor(resources, android.R.color.black, null))                  back_icon.imageTintList = ResourcesCompat.getColorStateList(resources, android.R.color.black, null)              }              if(scrollY > 4755 && oldScrollY < 4755){                  reveal(collapsing_toolbar_layout, R.color.lightBlack)                  toolbar_name.setTextColor(ResourcesCompat.getColor(resources, android.R.color.white, null))                  back_icon.imageTintList = ResourcesCompat.getColorStateList(resources, android.R.color.white, null)              }              if(oldScrollY > 4755 && scrollY < 4755){                  reveal(collapsing_toolbar_layout, R.color.background)                  toolbar_name.setTextColor(ResourcesCompat.getColor(resources, android.R.color.black, null))                  back_icon.imageTintList = ResourcesCompat.getColorStateList(resources, android.R.color.black, null)              }              if(oldScrollY > 1400 && scrollY < 1400){                  reveal(collapsing_toolbar_layout, R.color.colorPrimary)                  toolbar_name.setTextColor(ResourcesCompat.getColor(resources, android.R.color.white, null))                  back_icon.imageTintList = ResourcesCompat.getColorStateList(resources, android.R.color.white, null)              }          }  

but the problem is that not all the phones reach the blocks at that value, some a little bit earlier, other a little bit later. How can I manage to do this with all smartphone?

2 similar Haskell functions using do notation return same result but one is called many more times

Posted: 20 Apr 2021 08:28 AM PDT

nextState :: IO Int -> IO Int -- 0 1 0 2 0 1 0  nextState stateIO = do    value <- stateIO    putStrLn $ "Current state: " ++ show value    fmap (+1) stateIO    nextState' :: IO Int -> IO Int -- 0 1 2  nextState' stateIO = do    value <- stateIO    putStrLn $ "Current state: " ++ show value    return $ value + 1    main :: IO ()  main = do    let startStateIO = return 0 :: IO Int    let states = iterate nextState' startStateIO -- Use nextState or nextState'    stateInt <- states !! 3    print stateInt -- 3 in both cases  

This Haskell code has 2 functions which both seemingly have identical behavior. However, printing calls shows that nextState is being called a lot more times than nextState'. I had a larger project where this was an issue and I couldn't figure out how to convert that function so that it was called the minimum number of times so I couldn't fix it.

Why does this happen and how can I prevent it in a less simple example?

Note that fmap (+1) in my actual project is just a function from IO a -> IO a, not fmap (a -> a) - the whole thing works in terms of IO, not modifying the values inside using (a->a)

Filter using lodash

Posted: 20 Apr 2021 08:28 AM PDT

I want to add element to array if there is no element with the same type and format. I did it with for loop, but it looks bad.

for (i = 0; i < this.model.array.length; i++) {        const selectedElement = this.model.array[ i ]        if (selectedElement.value.format === item.value.format && selectedElement.value.type === item.value.type) {          this.model.array.splice(i, 1)          this.model.array.push(item)          break        }        if (i === this.model.array.length - 1) {          this.model.array.push(item)        }      }  

Could you tell me how can I do this lodash filter? I tried something like this:

let filter = _.filter(this.model.array, function (o) {        return ((o.value.type !== item.value.type) && (o.value.format !== item.value.format)) })  

but it does not work, it returns 0 array every time. My idea was to filter these elements (but it's just one) which type and format is the same as items and then push something using this filtered array. Or maybe there is another way how can I add elements if condition is met?

Item looks like this: enter image description here

Python 3.10 match/case with constants

Posted: 20 Apr 2021 08:28 AM PDT

I tried to replace an if/elif/elif/.../else code block with the shorter match/case from Python 3.10. I have three constants defined and want to do something different for each one, so my code looks roughly like this:

>>> const_a = 1  >>> const_b = 2  >>> const_c = 3  >>> interface = const_b  # example  >>> match interface:  ...     case const_a:  ...             print("case a")  ...     case const_b:  ...             print("case b")  ...     case const_c:  ...             print("case c")  

However, when running this code, there will be an Exception:

File "<stdin>", line 2  SyntaxError: name capture 'const_a' makes remaining patterns unreachable  

What am I doing wrong?

How to Make Function using OOP

Posted: 20 Apr 2021 08:28 AM PDT

Anyone can help me to make function using OOP? How to be able to make the function of finding the average of height of students with OOP?

class Person  {      //data members      private:          string name;          int age;          int height;          float weight;         //member functions      public:          void setPerson(string n, int a, int h, float w)          {              name=n;              age=a;              height=h;              weight=w;          }          void setName(string n) { name=n; }          void setAge(int a) { age=a; }          void setHeight(int h) { height=h; }          void setWeight(int w) { weight=w; }             string getName() {return name;}          int getAge() {return age;}          int getHeight() {return height;}          float getWeight() {return weight;}     };     int main()  {      Person p[100];      int x;      cin >> x;      string name;      int age;      int height;      float weight;         for(int i=0; i<x; i++)      {          cin >> name >> age >> height >> weight;          p[i].setName(name);          p[i].setAge(age);          p[i].setHeight(height);          p[i].setWeight(weight);      }        ..............  

my input are :

3 (number of person)

jason 20 185 70.50 (name age height weight)

emma 19 165 55.55

yerry 25 164 65.10

output :

171.33

Use Cookies for Authentication in Azure - React Web App

Posted: 20 Apr 2021 08:28 AM PDT

I'm trying to migrate my React-Web-Application from a normal webserver to an Azure Wep-App. The Application is supposed to login to my backend via email+password. This works. The backend sends a response with a authentication-token, which used to be saved in the cookies. The token is in the response, but it doesnt get saved. It doesn't throw any error or warning, neither on the browser, nor frontend logs, nor backend logs. I am not sure what to do, I have no clue where to start debugging. Maybe I'm using the whole Azure thing wrong?

This is the code of the backend where it compares mail & password with database and sends a token if everything is good:

async (      req: ValidatedRequest<AuthenticateRequest>,      res: Response<AuthenticateResponse>,      next: NextFunction    ): Promise<void> => {      try {        const mail = req.validData.mail;        const password = req.validData.password;        const user = await User.findByEmail(mail);        if (user !== null && await user.comparePassword(password)) {          const userRole = user.association;          // create the token          const token = issueToken(userRole, user._id);                    res.cookie("cookieToken", token, {httpOnly: false});          res.send({ user: await transformUser(user), token, });        }        else {          throw new ErrorGeneric(errorCodes.ERROR_ACCOUNT_NOT_FOUND);        }      }      catch (error) {        next(error);      }    }

Any ideas or help is appreciated. :)

Sincerly

Convert uint32_t to double between 0 and 1

Posted: 20 Apr 2021 08:29 AM PDT

I have a shamefully naive question: What is the best way to convert a uint32_t to a double between 0 and 1?

My naive way is

double myconvert(uint32_t a)  {      double n = static_cast<double>(std::numeric_limits<uint32_t>::max() - std::numeric_limits<uint32_t>::min());      return static_cast<double>(a) / n;  }  

But I was wondering if there is a better way?

can grpc use protobuf of older version?

Posted: 20 Apr 2021 08:28 AM PDT

I'm trying to build the compile environment of .proto files for grpc on my macbook. My current local protobuf version is 3.11.4 in my iOS project, but the latest grpc direct to protobuf 3.15.8. I have customized my protobuf code for some reason, so I don't want to upgrade it, and so does the compile environment.

my question is: can I keep my local old version protobuf(3.11.4) environment while install grpc environment at the same time?

When I use pod install to generate xx.pbobjc.h xx.pbobjc.m xx.pbrpc.h xx.pbrpc.m, it shows an error in the file

#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.  

'brew install grpc' dependent the latest protobuf(3.15.8), I guess I should clone grpc down and build the environment by myself and so I did, but it seems grpc doesn't link with my old protobuf when I try to generate code from .proto file, can anybody tell me how to make it happen? Have I make this clear? please tell me if i don't

Jest HTML coverage report showing inconsistent information

Posted: 20 Apr 2021 08:28 AM PDT

I just updated Jest to latest version and now the HTML report is showing some red lines (meaning that they are not covered) but in the left it shows the green box telling me that those lines are executed (and I know that they are executed).

An example on what I'm talking about

Before the update, this (and others) line were considered as covered by the reporter.

Am I missing something?

How do elements of a Union define eachother?

Posted: 20 Apr 2021 08:28 AM PDT

I was looking at a tutorial on unions in c. At the end of the tutorial there was an exercise regarding unions. I do not understand how the solution code works.

Exercise:

Create a union that stores an array of 21 characters and 6 ints (6 since 21 / 4 == 5, but 5 * 4 == 20 so you need 1 more for the purpose of this exercise), you will set the integers to 6 given values and then print out the character array both as a series of chars and as a string.

#include <stdio.h>    union hiddenMessage {      int  ints[6];      char chars[21];  };    int main() {      union hiddenMessage intCharacters = {{1853169737, 1936876900, 1684955508, 1768838432, 561213039, 0}};        printf("[");      // only go to 18 because 1 byte is for the terminating 0 and we don't print the last in the loop      for(int i = 0; i < 19; ++i)          printf("%c, ", intCharacters.chars[i]);      printf("%c]\n", intCharacters.chars[19]);      printf("%s\n", intCharacters.chars);  }  

The output:

[I,  , u, n, d, e, r, s, t, a, n, d,  , U, n, i, o, n, s, !]  I understand Unions!  

It seems the values of intCharacters.ints defines the values of intCharacters.chars. Could someone elaborate on how this work?

Regex to get text between multiple newlines in Python

Posted: 20 Apr 2021 08:29 AM PDT

I am trying to split a text where it is between \n\n and \n, in that order. Take this string for example:

\n\nMy take on fruits.\n\nHealthy Fruits\nAn apple is a fruit and it\'s very good.\n\nPears are good as well. Bananas are very good too and healthy.\n\nSour Fruits\nOranges are on the sour side and contains a lot of vitamin C.\n\nGrapefruits are even more sour, if you can believe it.

My desired output is:

[('Healthy Fruits', "An apple is a fruit and it's very good.", 'Pears are good as well. Bananas are very good too and healthy.'), ('Sour Fruits', 'Oranges are on the sour side and contains a lot of vitamin C.', 'Grapefruits are even more sour, if you can believe it.')]

I want to parse like this because anything between \n\n and \n is the title and the rest is text under the title (So "Healthy Fruits" and "Sour Fruits" . Not sure if this is the best way to grab the titles and its text.

I put the ".chars" but I still have an array of characters

Posted: 20 Apr 2021 08:29 AM PDT

Like in the title. I put the ".chars" but I still have an array of characters,

look my terminal :

 1) caesar_cipher should echo Bfmy f xywnsl!       Failure/Error: expect(caesar_cipher("What a string!",5)).to eq("Bfmy f xywnsl!")           expected: "Bfmy f xywnsl!"              got: ["B", "m", "f", "y", " ", "f", " ", "x", "y", "w", "n", "s", "l", "!"]           (compared using ==)       # ./spec/caesar_cipher_spec.rb:5:in `block (2 levels) in <top (required)>'  

I don't understand why I have an array of characters, while I put the .chars after the string

My code :

def caesar_cipher(string, shift)      alphabet  = Array('a'..'z')      non_caps  = Hash[alphabet.zip(alphabet.rotate(shift))]            alphabet = Array('A'..'Z')      caps     = Hash[alphabet.zip(alphabet.rotate(shift))]            encrypter = non_caps.merge(caps)            string.chars.map { |c| encrypter.fetch(c, c) }  end  

Blinking Problem in My Open-gl C++ Project

Posted: 20 Apr 2021 08:28 AM PDT

in this project when i run it the display screen blinking so much:

screen blinking

the project is about drawing node and edges using open-gl but the nodes and display screen blinking disturbingly....

here is my code:

void iInitialize(int width=500, int height=500, char *title="My Project")  {      iScreenHeight = height;      iScreenWidth = width;        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB) ;      glutInitWindowSize(width , height ) ;      glutInitWindowPosition(0 ,0) ;      glutCreateWindow(title) ;      glClearColor( 1.0 , 1.0 , 0.0 , 1.0 ) ;      glMatrixMode( GL_PROJECTION) ;      glLoadIdentity() ;      glOrtho(0.0 , width , 0.0 , height , -1.0 , 1.0) ;        iClear();        glutDisplayFunc(displayFF) ;      glutKeyboardFunc(keyboardHandler1FF); //normal      glutSpecialFunc(keyboardHandler2FF); //special keys      glutMouseFunc(mouseHandlerFF);      glutMotionFunc(mouseMoveHandlerFF);      glutIdleFunc(animFF) ;        glutMainLoop() ;  }  

and the iClear() code is:

glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) ;  glMatrixMode(GL_MODELVIEW) ;  glClearColor(0,0,0,0);  glFlush();  

swapExactTokensForTokens Failed in my own smart contract

Posted: 20 Apr 2021 08:29 AM PDT

I am using sushiswap to transfer weth to dai. Everything goes fine when I use web3.js to call swapExactTokensForTokens directory. However, thing goes wrong when I try to include the swapExactTokensForTokens in IUniswapV2Router02.sol. My code runing on remix below:

pragma solidity ^0.6.6;    import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol";  import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/docs-v3.x/contracts/token/ERC20/IERC20.sol";    contract Arbitrage {            IUniswapV2Router02 public sushiRouter = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506);            event test (uint timestamp, uint amountIn, uint amountOut, address[] path, uint allowance, address sender);            function swapper(address token1, address token2) public  {          address[] memory path = new address[](2);          path[0] = token1;          path[1] = token2;          uint amountOut = 1 ether;          uint amountIn = sushiRouter.getAmountsIn(              amountOut,              path          )[0];                                        IERC20(token1).approve(address(sushiRouter), amountIn);                    uint allowed = IERC20(token1).allowance(msg.sender, address(sushiRouter));                    emit test(now+90, amountIn, amountOut, path, allowed, msg.sender);            sushiRouter.swapExactTokensForTokens(              amountIn,               amountOut,              path,               msg.sender,               now + 60          );      }  }  

The error message shows on Remix is

Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?  The execution failed due to an exception. Reverted  

error in Remix

I also use truffle + ganache-cli (folked from mainnet). The error shows on truffle console is

'StatusError: Transaction: 0xc3268028ed1eac5743194b293f95bb4efe95ced4e809a0bc3663e437e1330cfe exited with an error (status 0). \n' +      '     Please check that the transaction:\n' +      '     - satisfies all conditions set by Solidity `require` statements.\n' +      '     - does not trigger a Solidity `revert` statement.\n' +      '\n' +      '    at Object.receipt (/usr/local/lib/node_modules/truffle/build/webpack:/packages/contract/lib/handlers.js:128:1)\n' +      '    at runMicrotasks (<anonymous>)\n' +      '    at processTicksAndRejections (internal/process/task_queues.js:97:5)\n' +      '    at Function.start (/usr/local/lib/node_modules/truffle/build/webpack:/packages/contract/lib/override.js:49:1)'  

error on truffle

I believes things go wrong inside "sushiRouter.swapExactTokensForTokens()" because the code goes through with emitting the event successfully once I comment it out.

It will be very appreciate if anybody can let me know in which part I mess it up.

------ Some more information below -----

After removing the swapping section like below:

...  contract Arbitrage {            IUniswapV2Router02 public sushiRouter = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506);            event test (uint timestamp, uint amountIn, uint amountOut, address[] path, uint allowance, address sender);            function swapper(address token1, address token2) public  {          address[] memory path = new address[](2);          path[0] = token1;          path[1] = token2;          uint amountOut = 1 ether;          uint amountIn = sushiRouter.getAmountsIn(              amountOut,              path          )[0];                    IERC20(token1).approve(address(sushiRouter), amountIn);          IERC20(token2).approve(address(sushiRouter), amountOut);                    uint allowed = IERC20(token1).allowance(msg.sender, address(sushiRouter));                              emit test(now+90, amountIn, amountOut, path, allowed, msg.sender);      }  }  

The transaction gone through with following tx detail:

tx detail

---- 4/21 update ----

I might find some clues when I am trying error on my ganache forked mainnet.

Google says the cause of "TRANSFER_FROM_FAILED" is that sushiswap router contract does not have enough allowance to transfer the token. So I check again the allowance from my allowance in "test event". It is actually "0" event though I have done the approve.

enter image description here

WHY?? following line of code does not take effect?? Do I miss anything?

IERC20(token1).approve(address(sushiRouter), amountIn);  

read a csv file with specific pattern dynamically in pandas

Posted: 20 Apr 2021 08:29 AM PDT

I have some CSV files with its extension which keeps changes all the time.

  1. Active_Count_1618861363072
  2. Deposit_1618861402104
  3. Game_Type_Wise_Net_Sell_1618861383176
  4. Total_Count_1618861351976

I want to read these files automatically

df1=pd.read_csv('Active_count_'.csv)  df2=pd.read_csv('Deposit_'.csv)  df3=pd.read_csv('Game_Type_Wise_Net_Sell_'.csv)  df4=pd.read_csv('Total_Count_'.csv)  

I want this in such a way that I want to keep after the underscore dynamic and load the CSV files. Is there a way I can achieve this?

Calling a function within a function in Angular not work [closed]

Posted: 20 Apr 2021 08:28 AM PDT

I activate the function calatuteRoute which has a call to the distanceBetweenToPointByDrive function But for some reason it did not enter the distanceBetweenToPointByDrive function call But straight skips doing the rest of the functions in the function calatuteRoute Anyone know what how to solve the problem? I would appreciate solutions.

Attached is the code:

app.component.ts

calatuteRoute() {       setTimeout(() => {        this.distanceBetweenToPointByDrive(Destination.geometry.location.lat(),        Destination.geometry.location.lng(), this.arr[0].Lat_Destination, this.arr[0].Lng_Destination)              },3000)       //do more somthing..       }      distanceBetweenToPointByDrive(latExported: any, lngExported: any, LatDestination: any,                      LngDestination: any): calculationResult {      const resulte: calculationResult = {      distance: "",      time: ""       }    debugger      let pointX = new google.maps.LatLng(latExported, lngExported)      let pointY = new google.maps.LatLng(LatDestination, LngDestination)      const service = new google.maps.DistanceMatrixService();        service.getDistanceMatrix(      {      origins: [pointX],      destinations: [pointY],      travelMode: google.maps.TravelMode.DRIVING,      unitSystem: google.maps.UnitSystem.METRIC,      avoidHighways: false,      avoidTolls: false,    },    (response, status) => {        if (status !== "OK") {        alert("Error was: " + status);        return      } else {        const originList = response.originAddresses;        const destinationList = response.destinationAddresses;        for (let i = 0; i < originList.length; i++) {          const results = response.rows[i].elements;          for (let j = 0; j < results.length; j++) {             resulte.distance = results[j].distance.text;            resulte.time = results[j].duration.text;          }        }      }      return resulte;     }   );     return resulte;  }  

How to get values from custom configuration file in Nestjs with interface?

Posted: 20 Apr 2021 08:28 AM PDT

I'm trying to set up all of my configurations in one file in "config.ts", load it to ConfigService and then with config interfaces get values from it. So here is my config.ts that have ENV vars from my .env file and static variables.

UPD: Made repo with this example

import { Config } from './config.interface';    const config: Config = {    typeorm: {      type: 'postgres',      host: process.env.DB_HOST,      port: +process.env.DB_PORT,      username: process.env.DB_USERNAME,      password: process.env.DB_PASSWORD,      database: process.env.DB_NAME,      synchronize: process.env.NODE_ENV !== 'prod',      logging: true,      entities: [User, RefreshToken],    },  };    export default () => config;  

And here is my interfaces:

export interface Config {    typeorm: TypeOrmConfig;  }    export interface TypeOrmConfig {    type: string;    host: string;    port: number;    username: string;    password: string;    database: string;    synchronize: boolean;    logging: boolean;    entities: any[];  }  

The config is loaded to ConfigModule in app.module.ts

@Module({    imports: [      ConfigModule.forRoot({        isGlobal: true,        envFilePath: '.dev.env',        load: [config],      }),  }),  

For example I want to set up my TypeOrmModule with this setting. Based on NestJs documentation

TypeOrmModule.forRootAsync({        imports: [ConfigModule],        useFactory: async (configService: ConfigService) => {          const config = configService.get<TypeOrmConfig>('typeorm');          console.log(config);          return {            type: config.type,            host: config.host,            port: +config.port,            username: config.username,            password: config.password,            database: config.database,            synchronize: config.synchronize,            logging: config.logging,            entities: config.entities,          };        },        inject: [ConfigService],      }),  

Here is the problem. Static values from config is okay, but all my ENV vars is undefined. Here is console.log output:

{    type: 'postgres',    host: undefined,    port: NaN,    username: undefined,    password: undefined,    database: undefined,    synchronize: true,    logging: true,    entities: [      [class User extends CoreEntity],      [class RefreshToken extends CoreEntity]    ]  }  

I don't understand what's the problem with undefined ENV vars I would be grateful for any explanations and help

A-frame switching template causes sound (video?) to overlap

Posted: 20 Apr 2021 08:29 AM PDT

My actions (edited):

I'm using A-Frame and A-Frame template-component.
I use template-component to load templates from <script id="..."> tag like in example.

I want to change the template on the fly using the el.setAttribute analogically like in this example.

My template contains a <sky> element with video as a source.
I can load one template and it works like a charm. I can pause, play it, and so on.

The issue appears when I want to switch the template to a new one that is using the same video resource, or load a new one and then return to the first one.

now I have 2 sounds - one without sync to the video.

One video is displayed but a second sound plays in the background. I also can verify that the sound is not coming from the displayed video. I can still play/pause it and its sound plays over the one in the background.

edited
I want to be able to modify not only the <sky> element but also some others, that's why I wanted to use the template-component. Let's also say that I don't know what assets would be finally used and I don't want to use asset management system to load tens of Mb of videos/objects and others and suspend the user at a loading screen. As stated here:

The scene won't render or initialize until the browser fetches (or errors out) all the assets or the asset system reaches the timeout.

To clarify a little bit more my intention but still keeping it simple, I want the user to be able to change the scene by choosing a prefab (assuming 15Mb per video even with 6-7 assets it may almost reach 100Mb), or by uploading one.

My guess:

I think the old video is not disposed of entirely. I tried using the three.js .dispose() method on various elements/ materials/ video itself, but with no luck.
I also tried using <a-video> as a source, and also deleting the elements before switching, but with the same result.

Questions

  • How to properly remove elements loaded by template so that the video is not stored/ cached anywhere?
  • Can I somehow set the autoplay="false" or simmilar to <sky> video?
  • If my approach is entirely wrong, can you point me in the right direction?

Example:

function switchVideoToFirst() {    console.log("switching to first");    document.getElementById("skyVideoTemplate").setAttribute('template', 'src', "#firstVideo");  }    function switchVideoToSecond() {    console.log('switching to second');    document.getElementById("skyVideoTemplate").setAttribute('template', 'src', '#secondVideo');  }    function playVideo() {    document.getElementById("skyVideo").components.material.material.map.image.play();  }    function pauseVideo() {    document.getElementById("skyVideo").components.material.material.map.image.pause();  }
<!DOCTYPE html>    <head>    <meta charset="UTF-8">    <script src="https://cdnjs.cloudflare.com/ajax/libs/nunjucks/2.3.0/nunjucks.min.js"></script>    <script src="https://aframe.io/releases/1.1.0/aframe.min.js"></script>    <script src="https://unpkg.com/aframe-template-component@3.2.1/dist/aframe-template-component.min.js"></script>  </head>    <body>    <div style="width: 400px; height: 200px;">      <a-scene embedded>        <a-entity id="skyVideoTemplate" template="src: #"></a-entity>      </a-scene>    </div>    <button onclick="switchVideoToFirst()">switch video to first</button>    <button onclick="switchVideoToSecond()">switch video to second</button>    </br>    </br>    <button onclick="playVideo()">play</button>    <button onclick="pauseVideo()">Pause</button>  </body>    <script id="firstVideo" type='text/nunjucks'>    <a-sky id="skyVideo" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/f/fb/Hundra_knektars_marsch_p%C3%A5_Forum_Vulgaris.webm/Hundra_knektars_marsch_p%C3%A5_Forum_Vulgaris.webm.360p.vp9.webm">    </a-sky>    <a-box position="-1 1 -1" color="red"></a-box>  </script>    <script id="secondVideo" type='text/nunjucks'>    <a-sky id="skyVideo" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/f/fb/Hundra_knektars_marsch_p%C3%A5_Forum_Vulgaris.webm/Hundra_knektars_marsch_p%C3%A5_Forum_Vulgaris.webm.360p.vp9.webm">    </a-sky>    <a-sphere position="-1 1 -1" color="green"></a-sphere>  </script>

I know that I have the same video in both templates but this is deliberate to shorten the example. The issue is strictly related to reloading the same template, either by switching to diferent one and back, or by loading a new one with same video resource.

how to reproduce my issue:

  • press "switch the video to first" to load the first template.
  • press "switch video to second" to load the second template.
  • video is gone but the sound is still going.
  • This point may not work but if you wait long enough the second video will load and you will hear 2 sounds. Then the play/pause controlls will only work on one of them.

also I experienced this:

  • press "switch the video to first" to load the first template
  • pause the video
  • press "switch video to second" to load the second template
  • it may take a while of white screen
  • when the "second" video is loaded the "first" one is still displayed and paused but the new one starts to play its sound from the beginning. Then you should (or not, can't figure this one out) be able to play/pause the "first" video.

disclaimer
the 360 video used in the example is from this website and the author is Jan Ainali

Big Query - Adwords - AuthenticationError.NOT_ADS_USER

Posted: 20 Apr 2021 08:29 AM PDT

I am trying to set up a data extract in BigQuery to pull data from a Google Ads Account. But I keep getting Auth errors (AuthenticationError.NOT_ADS_USER) when the extract tries starting pulling data.

What did I do?-

Is there something that I missed, that I have to enable/accept/configure in order for Big query extract to be able to pull the data from Google Ads?

Thanks,

p.s I have another extract in the same big query account with a different Google Ads account that is working, I recall have followed the same steps.

Wrong output from Fibonacci implementation

Posted: 20 Apr 2021 08:29 AM PDT

The program is suppose to show you only the first 8 numbers from Fibonacci. When I try to run the code is not showing the right numbers it should be: [1 1 2 3 5 8 13 15]. But instead it's showing me a d on it: [ 1 1 2 3 5 8 d 15]. I have no idea why is this happening.



.data      first DB 1      second DB 1      current DB 0      firstIterator DB 0      secondIterator DB 0      array DB 0, 1, 2, 3, 4, 5, 6, 7       aux DB 0   .code  main proc      mov RBX, 0      lea RBX, array; direction of the array      dec RBX      mov AH, 0        firstLoop:           cmp firstIterator, 7          ja secondLoop; if not (firstIterator <= 7)  segundo loop            inc RBX            mov AL, 0          mov AL, first          mov byte ptr[RBX], AL            mov AH, [RBX]; the element will be saved here            mov AL, 0          ADD AL, first          ADD AL, second          mov current, AL; current = first + second            mov AL, 0          mov AL, second          mov first, AL; first = second            mov AL, 0          mov AL, current          mov second, AL; second = current                    inc firstIterator      loop firstLoop        secondLoop:          cmp secondIterator, 7          ja exit            mov AL, byte ptr[RBX]          mov aux, AL            dec RBX          inc secondIterator      loop secondLoop            exit:  main endp  end  

Azure Function Queue Trigger Connection - can I set this from a variable or specifically Azure Application Configuration?

Posted: 20 Apr 2021 08:29 AM PDT

As simple as I can put it, I have the following:

public async Task Run([QueueTrigger("order-new", Connection = "AzureWebJobsStorage")]string myQueueItem, ILogger log)  

Is there any way I can do something like:

 public async Task Run([QueueTrigger("order-new", Connection = _connection)]string myQueueItem, ILogger log)  

Where the Connection is passed in as a variable? I have access to the value in the constructor, it is from Azure Application Configuration service. I am just trying not to have to change settings in more than one place. Thank you.

Update: I have actually found a way to get the actual string (not a variable) into the method arguments, but the "Connection" input is interpreting it as a variable it needs to look for, not the literal string which is the connection itself.

Update #2: I think I have it figured out, will write it up when I get a chance (@baum-mit-augen actually deleted the post that led me there).

SQL ZOO List each continent and the name of the country that comes first alphabetically

Posted: 20 Apr 2021 08:28 AM PDT

Im confused why it could not be

Select x.continent, x.name  From world x  Where x.name <= ALL (select y.name from world y where x.name=y.name)  ORDER BY name  

Can anyone please explain to me why it has to be x.continent=y.continent and not x.name=y.name ?

Table

No comments:

Post a Comment