Tuesday, December 28, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Printf print whitespace depending on space taken by other printed values

Posted: 28 Dec 2021 11:22 AM PST

I'm doing a small RPG-textbased game in c, as an introductory exercise for C.

So, I'm doing some prints and also printing some integers inside those prints.

Currently, my very simple example looks like this (this is just with hardcoded values for sake of the example):

int myHealth = 200;  int monsterhealth = 200;  printf("       | You    |  Monster  | \n");  printf("Health | %d    | %d       | \n", myHealth, monsterhealth);  

Which prints to this:

       | You    |  Monster  |   Health | 200    | 200       |   

But if the number instead only has one digit, like 1, then it has the simple issue that the text becomes a little bit offset, like this:

   | You    |  Monster  |   

Health | 1 | 1 |

This seems like a very simple issue, and I guess I could solve it by not having tables in this way, but now I got a little stubborn.

What is the cleanest way of adding some padding to a string when the integer doesnt take up as much space?

Use and access a Mongodb Realm in separate Library Project Xamarin & AutoFac

Posted: 28 Dec 2021 11:22 AM PST

I have a small simple app that I have been working on for quite a while. It needs a small in the cloud DB and sync would be nice. After looking at several possible ways of doing this I stumbled on Realm with sync to MongoDB atlas. Just seems perfect. Authentication, etc. I have used AutoFac for my DI containers and there is where the problems started. I get a Fody error. I was using a routine for registering all the containers in the assembly which worked like a lead pipe sync until I added Realm. I think if I can create a separate library project and don't use AutoFac and use it from the Xamarin project done deal. My problem with that is I am kind of lost on how to untangle the GitHub example to achieve that? Any help is appreciated.

Error while adding static IP in terraform vsphere_virtual_machine

Posted: 28 Dec 2021 11:21 AM PST

I am trying to add a vmware machine using vsphere, getting below error. I have followed this document. Terraform Document. Variable ipaddress is defined in the var file. If I remove ip related lines, There are no errors. I am using latest version of terraform. Its a windows box.

 resource "vsphere_custom_attribute" "attribute1" {    name                = "contact"    managed_object_type = "VirtualMachine"  }    resource "vsphere_custom_attribute" "attribute2" {    name                = "application"    managed_object_type = "VirtualMachine"  }    resource "vsphere_virtual_machine" "vm" {      name             = var.name      resource_pool_id = var.resource_pool_id      datastore_id     = var.datastore_id      host_system_id   = var.host_system_id      folder = var.folder      cpu_hot_add_enabled = "true"      enable_disk_uuid = "true"      enable_logging  = "true"      sata_controller_count = 1      scsi_type = "lsilogic-sas"          wait_for_guest_net_timeout = 5      wait_for_guest_ip_timeout  = 0      wait_for_guest_net_routable = true               num_cpus = 2      memory   = 4096      memory_hot_add_enabled = "true"      network_interface {      network_id = data.vsphere_network.network.id      ipv4_address = var.ipaddress      ipv4_netmask = "24"      ipv4_gateway = "172.16.16.1"    }            disk {      label            = "disk0"      size             = var.disksize      thin_provisioned = "false"      eagerly_scrub    = "true"      keep_on_remove   = "true"    }      cdrom {      client_device = true     }      custom_attributes = {      "${resource.vsphere_custom_attribute.attribute1.id}" = var.contact      "${resource.vsphere_custom_attribute.attribute2.id}" = var.application    }  }   

Getting below error. variable ipaddress in defined.

2021-12-28T19:10:04.4521432Z [31m│[0m [0m[1m[31mError: [0m[0m[1mUnsupported argument[0m  2021-12-28T19:10:04.4551386Z [31m│[0m [0m  2021-12-28T19:10:04.4596754Z [31m│[0m [0m[0m  on import.tf line 71, in resource "vsphere_virtual_machine" "vm":  2021-12-28T19:10:04.4600328Z [31m│[0m [0m  71:     [4mipv4_address[0m = var.ipaddress[0m  2021-12-28T19:10:04.4606602Z [31m│[0m [0m  2021-12-28T19:10:04.4629813Z [31m│[0m [0mAn argument named "ipv4_address" is not expected here.  2021-12-28T19:10:04.4702138Z [31m╵[0m[0m  2021-12-28T19:10:04.4715423Z [31m╷[0m[0m  2021-12-28T19:10:04.4733804Z [31m│[0m [0m[1m[31mError: [0m[0m[1mUnsupported argument[0m  2021-12-28T19:10:04.4739629Z [31m│[0m [0m  2021-12-28T19:10:04.4751172Z [31m│[0m [0m[0m  on import.tf line 72, in resource "vsphere_virtual_machine" "vm":  2021-12-28T19:10:04.4754267Z [31m│[0m [0m  72:     [4mipv4_netmask[0m = "24"[0m  2021-12-28T19:10:04.4770258Z [31m│[0m [0m  2021-12-28T19:10:04.4786616Z [31m│[0m [0mAn argument named "ipv4_netmask" is not expected here.  2021-12-28T19:10:04.4830785Z [31m╵[0m[0m  2021-12-28T19:10:04.4897742Z [31m╷[0m[0m  2021-12-28T19:10:04.4930515Z [31m│[0m [0m[1m[31mError: [0m[0m[1mUnsupported argument[0m  2021-12-28T19:10:04.5063714Z [31m│[0m [0m  2021-12-28T19:10:04.5081279Z [31m│[0m [0m[0m  on import.tf line 73, in resource "vsphere_virtual_machine" "vm":  2021-12-28T19:10:04.5163253Z [31m│[0m [0m  73:     [4mipv4_gateway[0m = "172.16.16.1"[0m  2021-12-28T19:10:04.5200702Z [31m│[0m [0m  2021-12-28T19:10:04.5206340Z [31m│[0m [0mAn argument named "ipv4_gateway" is not expected here.  2021-12-28T19:10:04.5223815Z [31m╵[0m[0m  2021-12-28T19:10:04.5279358Z ##[error]Error: The process 'C:\agent\_work\_tool\terraform\1.1.2\x64\terraform.exe' failed with exit code 1  2021-12-28T19:10:04.5298575Z ##[section]Finishing: Terraform : plan  

How do I make my program run faster to prevent it from crashing?

Posted: 28 Dec 2021 11:21 AM PST

I'm trying to create a 2D world where you can look around at the terrain. Soon I'll be turning the program into a similar game like Terraria. I've done a program just like this, but with much less objects and wanted to add more objects so that you could see more. The problem I'm having right now is everytime I run the program it crashes. I've tried using separate threads, but the program still crashed. Here is my current code...

  import javafx.application.Application;  import java.io.BufferedReader;  import java.io.BufferedWriter;  import java.io.ObjectOutputStream;  import java.io.ObjectInputStream;  import java.io.FileOutputStream;  import java.io.FileInputStream;  import javafx.scene.shape.Rectangle;  import javafx.scene.paint.Color;  import javafx.event.ActionEvent;  import javafx.event.EventHandler;  import javafx.animation.KeyFrame;  import javafx.animation.Timeline;  import javafx.scene.transform.Scale;  import javafx.stage.Stage;  import javafx.scene.Scene;  import javafx.scene.Group;  import javafx.util.Duration;    public class WorldGenerator extends Application  {      public static int cameraX = 0;      public static int cameraY = 0;      public static int RATIO = 150;      public static final int WORLD_HEIGHT = 10;      public static final int WORLD_WIDTH = 10;      public static double ORIGINAL_WIDTH;      public static double ORIGINAL_HEIGHT;      public static double BLOCK_RATIO;      public static int[][] blockMemory = new int[WORLD_WIDTH][WORLD_HEIGHT];      public static int[][] viewMemory;      public static Group MainGroup = new Group();      public static Scene MainScene = new Scene(MainGroup);      public void start(Stage stage){          for(int i = 0; i < WORLD_WIDTH; i++){              for(int k = 0; k < WORLD_HEIGHT; k++){                  blockMemory[i][k] = (int)(Math.random() * 2);              }          }                    stage.setScene(MainScene);          stage.setFullScreen(true);          stage.show();                    ORIGINAL_WIDTH = stage.getWidth();          ORIGINAL_HEIGHT = stage.getHeight();          BLOCK_RATIO = stage.getWidth() / RATIO;                    for(double i = 0; i < 10; i += .1){              if(stage.getWidth() % (BLOCK_RATIO + i) < .25 && stage.getHeight() % (BLOCK_RATIO + i) < .25){                  BLOCK_RATIO += i; break;              }          }                    viewMemory = new int[(int)(stage.getWidth() / BLOCK_RATIO - 1)][(int)(stage.getHeight() / BLOCK_RATIO - 1)];                    for(int i = 0; i < stage.getWidth() / BLOCK_RATIO; i++){              for(int k = 0; k < stage.getHeight() / BLOCK_RATIO; k++){                  Block block = new Block(i, k);              }          }                    MainGroup.getTransforms().add(new Scale(1, 1));          Thread thread = new Thread(new Runnable(){              @Override public void run(){                  for(int i = 0; i < ORIGINAL_WIDTH / BLOCK_RATIO - 1; i++){setView(i);}              }          });          thread.run();          Timeline time = new Timeline();          time.setCycleCount(Timeline.INDEFINITE);          KeyFrame frame = new KeyFrame(Duration.millis(1), new EventHandler<ActionEvent>(){              @Override public void handle(ActionEvent e){                  MainGroup.getTransforms().remove(0);                  MainGroup.getTransforms().add(new Scale(stage.getWidth() / ORIGINAL_WIDTH, stage.getHeight() / ORIGINAL_HEIGHT));              }          });          time.getKeyFrames().add(frame);          time.playFromStart();      }            public void setView(int x){          Thread thread = new Thread(new Runnable(){              @Override public void run(){                  Timeline time = new Timeline();                  time.setCycleCount(Timeline.INDEFINITE);                  KeyFrame frame = new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>(){                      @Override public void handle(ActionEvent e){                          for(int k = 0; k < ORIGINAL_HEIGHT / BLOCK_RATIO - 1; k++){                              try{                                  viewMemory[x][k] = blockMemory[x + cameraX][k + cameraY];                              } catch(IndexOutOfBoundsException ie){                                  try{                                      viewMemory[x][k] = 0;                                  } catch(IndexOutOfBoundsException ei){}                              }                          }                      }                  });                  time.getKeyFrames().add(frame);                  time.playFromStart();              }          });          thread.run();      }            class Block{          public Block(int x, int y){              Rectangle block = new Rectangle(BLOCK_RATIO * -.5, BLOCK_RATIO * -.5, BLOCK_RATIO, BLOCK_RATIO);              block.setFill(Color.WHITE);              block.setStroke(Color.BLACK);              block.setLayoutX(x * BLOCK_RATIO + (BLOCK_RATIO * .5));              block.setLayoutY(y * BLOCK_RATIO + (BLOCK_RATIO * .5));              MainGroup.getChildren().add(block);              Timeline time = new Timeline();              time.setCycleCount(Timeline.INDEFINITE);              KeyFrame frame = new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>(){                  @Override public void handle(ActionEvent e){                      try{                          switch(viewMemory[x][y]){                              case 0 : block.setFill(Color.WHITE); break;                              case 1 : block.setFill(Color.BLACK);                          }                      } catch (Exception ie){                          block.setFill(Color.WHITE);                      }                  }              });              time.getKeyFrames().add(frame);              time.playFromStart();          }      }  }    

How to feed an NN model with columns containing 2D data (list)

Posted: 28 Dec 2021 11:21 AM PST

enter image description here

The above image shows the columns of the dataset. The Syllables column is the dependent variable while all the other columns are independent variables.

def create_model():    model = Sequential()    model.add(Embedding(len(xtrain_dataset), 3, input_length=24))    model.add(LSTM(18, dropout=0.1))    model.add(Dense(12, activation='relu')),    model.add(Dense(9, activation='relu')),    model.add(Dense(1, activation="sigmoid"))      optimizer = Adam(learning_rate=0.01)      model.compile(optimizer=optimizer,              loss='binary_crossentropy',              metrics=['accuracy'])      return model  

it gives an error when run: ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).

Is there a way to feed the model with this dataset?

Thanks.

private_endpoint between two resource group services

Posted: 28 Dec 2021 11:21 AM PST

I have a container registry in azure which is implemented by terraform as you can see in the following code:

resource "azurerm_container_registry" "container_registry" {    name                = replace("${var.name}${var.namespace}", "-", "")    location            = var.location    resource_group_name = azurerm_resource_group.resource_group.name      sku = "Premium"      public_network_access_enabled = false      network_rule_set = [      {        default_action = "Deny"        ip_rule = []        virtual_network = [          for subnet_id in var.allowed_subnets : {            action    = "Allow"            subnet_id = subnet_id          }        ]      }    ]  }    

On the other side, I have a virtual machine with different resource groups. As I want to push created docker-images in the VM to the registry I want to have a private connection between these two. My terraform project is as below:

resource "azurerm_subnet" "subnet" {    name                = "${var.name}-${var.namespace}"    resource_group_name = azurerm_resource_group.resource_group.name      virtual_network_name = azurerm_virtual_network.virtual_network.name    address_prefixes     = ["10.0.1.0/24"]    service_endpoints    = ["Microsoft.ContainerRegistry"]      enforce_private_link_endpoint_network_policies = true  }    resource "azurerm_role_assignment" "role_assignment" {    scope                = data.terraform_remote_state.container_registry.outputs.container_registry_id    role_definition_name = "AcrPush"    principal_id         = azurerm_linux_virtual_machine.virtual_machine.identity[0].principal_id  }    resource "azurerm_private_endpoint" "private_endpoint" {    name                = "${var.name}-${var.namespace}"    location            = var.location    resource_group_name = azurerm_resource_group.resource_group.name    subnet_id           = azurerm_subnet.subnet.id      private_service_connection {      name                           = "container-private-connection"      subresource_names              = ["registry"]       private_connection_resource_id = data.terraform_remote_state.container_registry.outputs.container_registry_id      is_manual_connection           = false      }  }  

I suppose with private_endpoint I can have a safe connection for az acr login --name but it doesn't work and return 403. Could you please help me with this?

(I remove extra codes, like resource definition and vnet)

How to enable cors in web api 2.2 project

Posted: 28 Dec 2021 11:21 AM PST

Configured CORS on my web api project. But the preflight request receives 405. In other words HTTP OPTION is not allowed. Looks like cors is not enabled. I've seen examples with config.EnableCors(); but there is no App_Start/WebApiConfig.cs in this project template. What am I missing here?

Program.cs

var builder = WebApplication.CreateBuilder(args);    // Add services to the container.    builder.Services.AddControllers();    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle  builder.Services.AddEndpointsApiExplorer();  builder.Services.AddSwaggerGen();    var devCorsPolicy = "devCorsPolicy";  builder.Services.AddCors(options =>  {      options.AddPolicy(devCorsPolicy, builder => {          //builder.WithOrigins("http://localhost:800").AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();          builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();          //builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");          //builder.SetIsOriginAllowed(origin => true);      });  });      var app = builder.Build();    if (app.Environment.IsDevelopment())  {      app.UseSwagger();      app.UseSwaggerUI();      app.UseCors(devCorsPolicy);  }  else   {      app.UseHttpsRedirection();      app.UseAuthorization();      //app.UseCors(prodCorsPolicy);  }    app.MapControllers();    app.Run();    

Custom DXF Files - HATCH CIRCLE

Posted: 28 Dec 2021 11:21 AM PST

I am trying to make a simple dxf file for draw and hatch a circle using only ENTITIES SECTION, I have not managed to get the file to open, I am using Autocad 2007. Not including HATCH, only with CIRCLE, the following file works fine.

0 SECTION 2 ENTITIES 0 CIRCLE 8 0 10 520 20 23 40 6.4 0 ENDSEC 0 EOF

By including HATCH with your respective data, you no longer it works, errors come out. I suspect they are needed some additional data, I have done several trials, I have not gotten the file to open. For which I require I need the file to contain the minimum amount of data possible. If anyone knows how get it, in advance my eternal thanks

Nick

Creating objects with user input in c#

Posted: 28 Dec 2021 11:21 AM PST

I am just starting to learn c# and in order to solidify some of the concepts I learned I tried to make an ATM simulator. One of the functions that I would like to implement is that the user can create a new account with a custom name. I am creating instances of a class for every new account and I was wondering how I could do this with user input. For example, would it be possible to have something like this:

Data Jeff = new Data(cardNumber: "1234123412341234", pin: "123", balance: 100.00);

except with a custom name instead of Jeff?

If this is not possible, how could I name a new instance of the class every time the user wants to create a new account?

I hope this makes sense. Thank you for your help.

Setting up a JS file to get its function triggered

Posted: 28 Dec 2021 11:21 AM PST

I'm learning JavaScript and in a few scripts that I have come across I can see a reference to what seems like apis and then functions. For example:

      // Call the what3words        what3words.api          .gridSectionGeoJson({            southwest: {              lat: sw.lat,              lng: sw.lng            },            northeast: {              lat: ne.lat,              lng: ne.lng            }          })  

I've tried to replicate this by swapping this code out for my own version by doing the following:

  1. Remove what3words.js

  2. Include my own script file script.js in the headers for that page

  3. Include a function inside that file, such as this:

    function gridSectionGeoJson() { document.getElementById("demo").innerHTML = "Hello World!"; }

However this never gets triggered. How do I setup my script.js so that my function gets triggered by the code in the top snippet? I imagine that has to do with the reference to "what3words.api" that I need to somehow designate inside my own JS file to get it to trigger.

Pause Installation?

Posted: 28 Dec 2021 11:20 AM PST

In InnoSetup I am running another setup file using this code:

[Run]  Filename: "{app}\MySetup2.exe"; WorkingDir: "{app}"; Flags: waituntilterminated  

This setup file executes another setup file and closes it-self. But the InnoSetup does not wait for the second setup and goes to the Finish dialog.

How to pause the installation until this second setup is closed?

The post "https://stackoverflow.com/questions/10892452/inno-setup-exec-function-wait-for-a-limited-time" shows how to wait for the process. But how to apply this during installation?

How to create a publishing property wrapper that also caches

Posted: 28 Dec 2021 11:20 AM PST

I have a caching system that works. I have a property wrapper. Now I want to turn that into a property wrapper that publishes for use in a SwiftUI view but I can't work that out.

Here is my code for the property wrapper (that doesn't successfully publish). This was sort of taken from another answer on stack overflow, where I've defined an internal CurrentValueSubject that gets fired every time a new value is set to the wrappedValue:

import UIKit  import Combine    @propertyWrapper final class CachedPublisher<Value: Codable> {    enum Key: String, Codable {      case user    }      let key: Key    let cache: Cache<Key, Value>    private let defaultValue: Value    private var cancellables = Set<AnyCancellable>()    private lazy var subject = CurrentValueSubject<Value, Error>(wrappedValue)      var wrappedValue: Value {      get {        let value = cache[key]        return value ?? defaultValue      }      set {        cache[key] = newValue        subject.send(newValue)      }    }      var projectedValue: AnyPublisher<Value, Error> {      return subject.eraseToAnyPublisher()    }      init(      wrappedValue defaultValue: Value,      key: Key    ) {      self.key = key      self.defaultValue = defaultValue      if let cache = try? Cache<Key, Value>.retrieveFromDisk(withName: key.rawValue) {        self.cache = cache      } else {        cache = Cache<Key, Value>()      }    }  }    // MARK: - ExpressibleByNilLiteral  extension CachedPublisher where Value: ExpressibleByNilLiteral {    convenience init(key: Key) {      self.init(wrappedValue: nil, key: key)    }  }  

This is to be specified like this inside an ObservableObject:

@CachedPublisher(key: .user)  var user: User?  

Then I want to use it in a SwiftUI view so my view updates whenever user changes.

JOIN Query Flask SQLAlchemy Related Tables using relationships table

Posted: 28 Dec 2021 11:20 AM PST

I want to define two related tables which are student and mentor and their relationship has to be defined through a relationship table student_mentor on a database level. They have to be mapped to Flask app classes using Flask SQLAlchemy library. How can I relate the tables using Flask SQLAlchemy relationship and JOIN student and mentor tables during a query, (I neglected some fields of the tables).

The following are the classes of the models:

student:

class Student(db.Model, Serializer):    id = db.Column(db.Integer, primary_key=True)    #some columns...  

mentor:

class Mentor(db.Model, Serializer):    id = db.Column(db.Integer, primary_key=True)    #some columns...  

student_mentor

class StudentMentor(db.Model, Serializer):    student_id = db.Column(db.Integer) # id column of student table    mentor_id = db.Column(db.Integer) # id column of mentor table  

I am looking forward to achieve my goal with a query of this nature:

query:

students = Student.query.order_by(desc(Student.created_at)).join(Mentor).paginate(page=1, per_page=5, error_out=False)  

React Component Render Transitions with Vanilla CSS & Styled Components

Posted: 28 Dec 2021 11:20 AM PST

I am trying to figure out a way to add transitions whenever I render React components using vanilla CSS (within Styled Components). I know that there is a dependency called React Transition Group, but I hoping to avoid as many dependencies as possible.

I would like to add a vertical reveal transition to my mobile side menu that expands downward when clicking on the hamburger icon.

Here's an example of what I have thus far: Menu Picture

AWS Step Functions State Machine Result Selctor from SQS

Posted: 28 Dec 2021 11:20 AM PST

I am building my first simple AWS Step Function: Step 1: Read a message from SQS Step 2: Run a Redshift query

I have managed to setup my initial workflow & permissions to the resources. I am trying to format my

Here is my Result Selector code for the first step:

"ResultSelector": {          "startTime.$": "$.Body.startTime",          "endTime.$": "$.Body.endTime"        }  

Here is the error output:

{    "error": "States.Runtime",    "cause": "An error occurred while executing the state 'ReceiveMessage from SQS' (entered at the event id #2). The JSONPath '$.Body.startTime' specified for the field 'startTime.$' could not be found in the input '{\"Messages\":[{\"Body\":\"{\\\"startTime\\\": 12828373, \\\"endTime\\\": 12828374}\",\"Md5OfBody\":\"1ca004b811be50a7579f3a7e6affaeb1\",\"MessageId\":\"5b6b72d6-3fb7-451a-9053-26b72de32768\",\"ReceiptHandle\":\"AQEBjgttgZBNSuGZb0LFjo16Xc2+5uc48k9QPh9af4vTGy1xzb/BZZ6mBFx0FQ4ALWUoLfppWHIJbb7Zax2+Jv2dqekvLoCWWrdjasyrJnGfduXwsY20cPuW86kXz4RJfP4qbnyvWcV5Cb63u26XUE3S+3AqREo2BNwi01mI3ceYWxguXzgSgDIMg/07Lt5kBcNvB6qCIexQDMDgH91ZmmINLuX0j5gd3spHCmzBvFoQKv4PbLBS18PsC6vL1YLGxplZ+eVyzD3eoK/5AU0jqmI0l0vjn4qZCVf2iOupkwEmMe4V2AaEdxI1FJ9dSU8zPkqFhbB3na56eIXgIGwsTWs5WBvlHikTuyYjWNFn6r27qCVfwADGkENoXZG1++vRoRse9X3p5fNqqVNBL1NTBL3k3/hoxB7/A922PT0MTn7rm1I=\"}]}'"  }  

The problem is obvious: I am still not creating a proper result selector.

I have json formatted my input in Python:

message = {      'startTime': 12828373,      'endTime': 12828374  }    # Send message to SQS queue  response = sqs.send_message(      QueueUrl=queue_url,      DelaySeconds=10,      MessageBody=json.dumps(message)  )    

However, it seems that the step function is grabbing multiple messages. I am also not extracting the data correctly.

Please help with how the result selector should look to extract the startTime & endTime. Is there anything else I am missing or should be doing different?

Segmentation fault (core dumped) while trying to print numpy and pandas objects in python via cygwin

Posted: 28 Dec 2021 11:20 AM PST

I am simply trying to run python (interactively) in cygwin, but whenever I try to print out a numpy array or write a pandas dataframe to a csv file python prints out :

Segmentation fault (core dumped)  

To run numpy/pandas I installed with cygwin set-up.exe:

  • gcc-core
  • gcc-fortran
  • gcc-g++
  • python38
  • python38-cython
  • python38-devel
  • python38-numpy
  • python38-pip
  • python38-setuptools
  • python38-six
  • python38-wheel

I'd like to emphasize that python prints out the message, it's not an error message, apparently. The problem arises whenever I do something as simple as the following:

In cygwin terminal:

~ python3  >>> import numpy  >>> numpy.random.random(20)  

But it doesn't happen when I do this (printing the first element of the array):

~ python3  >>> import numpy  >>> numpy.random.random(20)[0]  

Nor when I do this (print another numpy.ndarray of integers):

~ python3  >>> import numpy  >>> numpy.random.ranint(1, 20, 100)  

I am unfortunately not an expert in any way. Any help or discussion is greatly appreciated you guys.

Thank you!

W3C Guidelines (website for blind people) [closed]

Posted: 28 Dec 2021 11:20 AM PST

I made a web site that can be used by people that are blind. I need to know if the site respects the guidelines of W3C.

Link of the web site: https://girapuglia.altervista.org/

TypeScript fails to get the type of the elements of an object correctly

Posted: 28 Dec 2021 11:21 AM PST

I am developing a React Native project with Expo. I have defined a function called setRoleColors that sets some colors based on the variable role.

export const setRoleColors = (role: string) => {    switch (role) {      case "student":        return { backgroundColor: Color.maroon.dark, color: "#fff" };      case "moderator":        return { backgroundColor:"#00ff00", color: "#000"};      case "user":        return { backgroundColor:"#0000ff", color: "#fff";    }  };  

I import the function setRoleColors into a component called UserRole.

import React from "react";  import { Text, View } from "react-native";    import { setRoleColors } from "../../services/SetRoleColors";    import styles from "./styles";    const UserRole: React.FC<{ role: string }> = ({ role }) => {    const { backgroundColor, color } = setRoleColors(role);      return (      <View style={{ ...styles.roleContainer, backgroundColor }}>        <Text style={{ ...styles.roleText, color }}>{role}</Text>      </View>    );  

Now, everything works perfectly fine, however VS Code underlines the two variables backgroundcolor and color in the line const { backgroundColor, color } = setRoleColors(role); and when I hover over them it shows a message telling me the following:

Property 'backgroundColor' does not exist on type'{backgroundColor: string; color: string} | undefined  Property 'color' does not exist on type'{backgroundColor: string; color: string} | undefined   

How can I convert string to JSON?

Posted: 28 Dec 2021 11:22 AM PST

I have a variable string like this:

"{\n \"Status\": \"OK\",\n \"TotalRows\": 200,\n \"Items\": [\n {\n \"CustomerId\": 123654,\n \"UserName\": \"VN\",\n \"FullName\": \"Vahid_Nouri\",\"Country\": \"United Kingdom\" }\n ]\n}"

and I want to save it as a json file in python. What should I do?

having issues applying flexbox

Posted: 28 Dec 2021 11:21 AM PST

I'm having some issues applying flexbox on a div.

here is the problem :

<div class="annual-plan">          <div class="icon">            <i class="fas fa-music"></i>          </div>          <div class="pricing">            <h3>Annual Plan</h3>            <span>$59.99/year</span>          </div>          <a href="#">Change</a>   </div>  

this whole code is wrapped in div with a class named content-section

i tried targeting it with css using the following :

.content-section .annual-plan .pricing{      display: flex;      flex-direction: column;      justify-content: space-between;  }  

but still doesn't take effect, and you can see no space between. enter image description here

I checked the dev tools of chrome and it's not overridden by any other code.

what did I do wrong and how can I fix it?

How do I connect to a SQL Server database from Power BI?

Posted: 28 Dec 2021 11:20 AM PST

I created some views in SQL Server and would like to use them for visualization in Power BI. Currently, I am trying to connect my Power BI to SQL Server. I keep getting an error in Power BI just after entering the server name. Any help will be appreciated. Thanks.

My SQL Server name:

My SQL server Name

Entering server into PowerBI: I tried DESKTOP-63CGS35\SQLEXPRESS as the username, it didn't work as well.

enter image description here

This is the error I get:

enter image description here

how to use while loop to check variable is empty or not in shell

Posted: 28 Dec 2021 11:21 AM PST

I am using following code to check whether variable is empty or not. using while loop because, i need to continue the loop till the variable is empty. The moment value comes in variable, while loop should come out.

 MR=""    while [ -z "$MR" ]                      do                         echo "in while loop"                        sleep 10s                        MR="hi"    done   

but for some reason, it is not at all executing. what is the reason?

EDIT 1

Sorry, my bad, by mistake i mentioned MR is an empty string. actually, it is an empty array.

MR=[]        while [ -z "$MR" ]                          do                             echo "in while loop"                            sleep 10s                            MR="hi"        done   

Does using an image transform significantly slow down training?

Posted: 28 Dec 2021 11:21 AM PST

I see image transforms used quite often by many deep learning researchers. They seem to be treated as if they are free GPU or CPU cycles.

Example:

transformations = transforms.Compose([          transforms.Resize(255),          transforms.CenterCrop(224),          transforms.ToTensor(),          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])      ])    train_set = datasets.ImageFolder(data_dir + "/train", transform = transformations)  

In this specific case would it not be infinitely better to process the images upfront and save them out for future use in some other format? I see this sometimes but extremely rarely.

Or am I wrong, and transformers on a GPU are just so fast it's not worth the extra code or hassle?

How can I detect if a word is present on a Chrome page using selenium (Python)?

Posted: 28 Dec 2021 11:20 AM PST

This is my code:

from selenium import webdriver

from selenium.webdriver.support.ui import Select

import random

import time

from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Chrome()

driver.get("https://www.ti.com/store/ti/en/p/product/?p=CD4040BE&keyMatch=CD4040BE")

time.sleep(1)

accept_and_proceed = driver.find_element_by_xpath('//*[@id="consent_prompt_submit"]') accept_and_proceed.click()

region = Select(driver.find_element_by_xpath('//*[@id="llc-cartpage-ship-to-country"]')) region.select_by_visible_text('Italy')

continue1 = driver.find_element_by_xpath('//*[@id="llc-cartpage-ship-to-continue"]') continue1.click()

On the website there is the word "Inventory". How can I detect if the word "Inventory" is present on the page? If it is present then print x and if it is not refresh the page until it will be

PostGIS compute orthogonal points at a given distance

Posted: 28 Dec 2021 11:21 AM PST

In PostGIS, I need to compute the 2 perpendicular points C and D at a given distance of a line so that it creates a perfect rectangle on the map. The projection WGS84. ABCD has to be anticlockwise like in the drawing below.

Any idea how to compte those 2 points?

enter image description here

Python asyncio issues

Posted: 28 Dec 2021 11:21 AM PST

I tested the following code with Ncat. It only sends a single message, then it does not send anything, and does not except. It is also not reading anything.

I have no idea what could be going on. There is no exception, and no data seems to be sent.

import asyncio      loop = asyncio.get_event_loop()    class Client:        def __init__(self):          self.writer = None          self.reader = None        async def connect(self, address, port):          reader, writer = await asyncio.open_connection(address, port)          self.reader = reader          self.writer = writer          print("connected!")        async def send(self, message):          print("writing " + message)          self.writer.write((message + '\n').encode())          await self.writer.drain()        async def receive(self):          print("receiving")          message = (self.reader.readuntil('\n'.encode())).decode()          return message        async def read_loop(self):          while True:              incoming = await self.receive()              print("remote: " + incoming)      async def main():      client = Client()      await client.connect("127.0.0.1", 31416)        loop.create_task(client.read_loop())        while True:          text = input("message: ")          await client.send(text)      loop.run_until_complete(main())  

how to update firestore database value correctly

Posted: 28 Dec 2021 11:20 AM PST

I am working to build basic shopping functions in my Flutter app.  I'm new to coding and Flutter.  When the user clicks the PlaceOrderPageContainer (button) to confirm check out the addOrderDetails() method is called which then updates the Firebase database. Everything is updating in Firestore Database correctly other than the Total Amount which is being added as zero regardless of the total amount in the shopping cart.  I have included the code for the PlaceOrderPaymentPage which is where I am attempting to update the database with the details of the shopping cart.  I also included the Shopping cart page where the user begins the checkout process by clicking on a floating action button and passing the total amount forward and the Address Page where a user selects an address and then moves forward to the PlaceOrderPayment page. I'm not getting any errors in the console but it's obvious my code isn't written correctly.  Any help will be greatly appreciated.  I can add any additional code if that will be helpful.

    class ShoppingCartPage extends StatefulWidget {    const ShoppingCartPage({Key? key}) : super(key: key);      @override    _ShoppingCartPageState createState() => _ShoppingCartPageState();  }    class _ShoppingCartPageState extends State<ShoppingCartPage> {    late double totalAmount;      @override    void initState() {      super.initState();      totalAmount = 0;      Provider.of<TotalAmountProvider>(        context,        listen: false,      ).display(0);    }      @override    Widget build(BuildContext context) {      return Consumer2<TotalAmountProvider, CartItemCounterProvider>(        builder: (context, amountProvider, cartProvider, c) {          return SafeArea(            child: Scaffold(              appBar: const ShoppingCartAppBar(),              floatingActionButton: FloatingActionButton.extended(                onPressed: () {                  if (ShoppingApp.sharedPreferences                          .getStringList(                            ShoppingApp.userCartList,                          )                          ?.length ==                      1) {                    Fluttertoast.showToast(msg: ToastString.cartEmpty);                  } else {                    Navigator.push(                      context,                      MaterialPageRoute(                        builder: (context) => AddressPage(                          totalAmount: totalAmount,                        ),                      ),                    );                  }                },                icon: const Icon(                  Icons.navigate_next,                ),                label: Text(                  ButtonString.checkOut.toUpperCase(),                ),              ),              body: CustomScrollView(                slivers: [                  SliverToBoxAdapter(                    child:                        Consumer2<TotalAmountProvider, CartItemCounterProvider>(                      builder: (context, amountProvider, cartProvider, c) {                        return Padding(                          padding: const EdgeInsets.all(8.0),                          child: Center(                            child: cartProvider.count == 0                                ? Container()                                : Text(                                    'Total Price: \$${amountProvider.totalAmount.toString()}',                                    style: Theme.of(context).textTheme.headline6,                                  ),                          ),                        );                      },                    ),                  ),                  StreamBuilder<QuerySnapshot>(                      stream: ShoppingApp.firestore                          .collection('items')                          .where('shortInfo',                              whereIn: ShoppingApp.sharedPreferences                                  .getStringList(ShoppingApp.userCartList))                          .snapshots(),                      builder: (context, AsyncSnapshot snapshot) {                        return !snapshot.hasData                            ? const AdaptiveCircularProgressSliver()                            : snapshot.data.docs.isEmpty                                ? const EmptyShoppingCartContainer()                                : SliverList(                                    delegate: SliverChildBuilderDelegate(                                      (context, index) {                                        ItemModel model = ItemModel.fromJson(                                          snapshot.data.docs[index].data(),                                        );                                        if (index == 0) {                                          totalAmount = 0;                                          // totalAmount = model.price! + totalAmount;                                        } else {                                          totalAmount =                                              model.price! + totalAmount;                                        }                                        if (snapshot.data?.docs.length - 1 ==                                            index) {                                          WidgetsBinding.instance!                                              .addPostFrameCallback((timeStamp) {                                            Provider.of<TotalAmountProvider>(                                                    context,                                                    listen: false)                                                .display(totalAmount);                                          });                                        }                                        return sourceInfo(                                          model,                                          context,                                          removeCartFunction: () =>                                              removeItemFromUserCart(                                            model.shortInfo as String,                                          ),                                        );                                      },                                      childCount: snapshot.hasData                                          ? snapshot.data?.docs.length                                          : 0,                                    ),                                  );                      }),                ],              ),            ),          );        },      );    }      Future<void> removeItemFromUserCart(      String shortInfoAsID,    ) async {      List<String>? tempCartList = ShoppingApp.sharedPreferences.getStringList(        ShoppingApp.userCartList,      );      tempCartList?.remove(shortInfoAsID);        await ShoppingApp.firestore          .collection(ShoppingApp.collectionUser)          .doc(ShoppingApp.sharedPreferences.getString(            ShoppingApp.userUID,          ))          .update({        ShoppingApp.userCartList: tempCartList,      }).then((value) {        Fluttertoast.showToast(          msg: ToastString.removeFromCart,        );        ShoppingApp.sharedPreferences.setStringList(          ShoppingApp.userCartList,          tempCartList as List<String>,        );          Provider.of<CartItemCounterProvider>(          context,          listen: false,        ).displayResult();          totalAmount = 0;      });    }  }    class AddressPage extends StatefulWidget {    const AddressPage({      Key? key,      required this.totalAmount,    }) : super(key: key);      final double totalAmount;      @override    _AddressPageState createState() => _AddressPageState();  }    class _AddressPageState extends State<AddressPage> {    @override    Widget build(BuildContext context) {      return SafeArea(        child: AdaptiveLayoutScaffold(          appBar: const AddressPageAppBar(),          floatingActionButton: const AddNewAddressFAB(),          landscapeBodyWidget: Container(),          portraitBodyWidget: Column(            crossAxisAlignment: CrossAxisAlignment.center,            mainAxisSize: MainAxisSize.min,            children: [              const AddressPageHeadline(                headlineText: ShoppingPageString.selectAddress,              ),              Consumer<AddressChangerProvider>(builder: (                context,                address,                c,              ) {                return Flexible(                  child: StreamBuilder<QuerySnapshot>(                      stream: ShoppingApp.firestore                          .collection(ShoppingApp.collectionUser)                          .doc(ShoppingApp.sharedPreferences                              .getString(ShoppingApp.userUID))                          .collection(ShoppingApp.subCollectionAddress)                          .snapshots(),                      builder: (context, snapshot) {                        return !snapshot.hasData                            ? const AdaptiveCircularProgressCenter()                            : snapshot.data!.docs.isEmpty                                ? const EmptyShippingAddressContainer()                                : ListView.builder(                                    itemCount: snapshot.data?.docs.length,                                    shrinkWrap: true,                                    itemBuilder: (context, index) {                                      return AddressCard(                                        addressID: snapshot.data?.docs[index].id                                            as String,                                        currentIndex: address.count,                                        model: AddressModel.fromJson(                                          snapshot.data?.docs[index].data()                                              as Map<String, dynamic>,                                        ),                                        totalAmount: widget.totalAmount,                                        value: index,                                      );                                    },                                  );                      }),                );              }),            ],          ),        ),      );    }  }    class AddressCard extends StatefulWidget {      const AddressCard({      Key? key,      required this.addressID,      required this.currentIndex,      required this.model,      required this.totalAmount,      required this.value,    }) : super(key: key);      final String addressID;    final int currentIndex;    final AddressModel model;    final double totalAmount;    final int value;      @override    _AddressCardState createState() => _AddressCardState();  }    class _AddressCardState extends State<AddressCard> {    @override    Widget build(BuildContext context) {      return AddressCardContainer(        onTap: () {          Provider.of<AddressChangerProvider>(            context,            listen: false,          ).displayResult(widget.value);        },        addressCardColumn: AddressCardColumn(          children: [            Row(              children: [                AddressCardRadioButton(                  groupValue: widget.currentIndex,                  onChanged: (value) {                    Provider.of<AddressChangerProvider>(                      context,                      listen: false,                    ).displayResult(                      value as int,                    );                  },                  value: widget.value,                ),                AddressCardContent(                  city: widget.model.city as String,                  fullName: widget.model.name as String,                  phoneNumber: widget.model.phoneNumber as String,                  postalCode: widget.model.postalCode as String,                  state: widget.model.state as String,                  streetAddress: widget.model.streetAddress as String,                ),              ],            ),            widget.value == Provider.of<AddressChangerProvider>(context).count                ? ShippingAddressProceedButton(                    onPressed: () {                      Navigator.push(                        context,                        MaterialPageRoute(                          builder: (                            context,                          ) =>                              PlaceOrderPaymentPage(                            addressID: widget.addressID,                            totalAmount: widget.totalAmount,                          ),                        ),                      );                    },                  )                : Container(),          ],        ),      );    }  }    class PlaceOrderPaymentPage extends StatefulWidget {    const PlaceOrderPaymentPage({      Key? key,      required this.addressID,      required this.totalAmount,    }) : super(key: key);      final String addressID;    final double totalAmount;      @override    _PlaceOrderPaymentPageState createState() => _PlaceOrderPaymentPageState();  }    class _PlaceOrderPaymentPageState extends State<PlaceOrderPaymentPage> {    @override    Widget build(BuildContext context) {      return AdaptiveLayoutScaffold(        appBar: const PlaceOrderPaymentPageAppBar(),        landscapeBodyWidget: Container(),        portraitBodyWidget: PlaceOrderPageContainer(          orderOnPressed: () => addOrderDetails(),        ),      );    }      void addOrderDetails() {      final time = DateTime.now().millisecondsSinceEpoch;        writeOrderDetailsForUser({        ShoppingApp.addressID: widget.addressID,        ShoppingApp.totalAmount: widget.totalAmount,        'orderBy': ShoppingApp.sharedPreferences.getString(          ShoppingApp.userUID,        ),        ShoppingApp.productID: ShoppingApp.sharedPreferences.getStringList(          ShoppingApp.userCartList,        ),        ShoppingApp.paymentDetails: ShoppingPageString.cashOnDelivery,        ShoppingApp.orderTime: time.toString(),        ShoppingApp.isSuccess: true,      });        writeOrderDetailsForAdmin({        ShoppingApp.addressID: widget.addressID,        ShoppingApp.totalAmount: widget.totalAmount,        'orderBy': ShoppingApp.sharedPreferences.getString(          ShoppingApp.userUID,        ),        ShoppingApp.productID: ShoppingApp.sharedPreferences.getStringList(          ShoppingApp.userCartList,        ),        ShoppingApp.paymentDetails: ShoppingPageString.cashOnDelivery,        ShoppingApp.orderTime: time.toString(),        ShoppingApp.isSuccess: true,      }).whenComplete(() => {            emptyCartNow(),          });    }      void emptyCartNow() {      ShoppingApp.sharedPreferences.setStringList(ShoppingApp.userCartList, [        'garbageValue',      ]);      List<String>? tempList = ShoppingApp.sharedPreferences.getStringList(        ShoppingApp.userCartList,      );        FirebaseFirestore.instance          .collection('users')          .doc(ShoppingApp.sharedPreferences.getString(            ShoppingApp.userUID,          ))          .update({        ShoppingApp.userCartList: tempList,      }).then((value) {        ShoppingApp.sharedPreferences.setStringList(          ShoppingApp.userCartList,          tempList as List<String>,        );        Provider.of<CartItemCounterProvider>(          context,          listen: false,        ).displayResult();      });      Fluttertoast.showToast(        msg: ToastString.orderPlacedSuccessfully,      );      Navigator.pushReplacement(        context,        MaterialPageRoute(          builder: (context) => const ShoppingPage(),        ),      );    }      Future<void> writeOrderDetailsForUser(      Map<String, dynamic> data,    ) async {      await ShoppingApp.firestore          .collection(ShoppingApp.collectionUser)          .doc(ShoppingApp.sharedPreferences.getString(ShoppingApp.userUID))          .collection(ShoppingApp.collectionOrders)          .doc(            ShoppingApp.sharedPreferences.getString(ShoppingApp.userUID)! +                data['orderTime'],          )          .set(data);    }      Future<void> writeOrderDetailsForAdmin(Map<String, dynamic> data) async {      await ShoppingApp.firestore          .collection(ShoppingApp.collectionOrders)          .doc(            ShoppingApp.sharedPreferences.getString(ShoppingApp.userUID)! +                data['orderTime'],          )          .set(data);    }  }  

The type implied by the yield expression must be assingable to

Posted: 28 Dec 2021 11:21 AM PST

yield* FirebaseFirestore.instance  

Is giving

The type 'Future<QuerySnapshot>' implied by the 'yield' expression must be assignable to 'Stream<QuerySnapshot>'

The class

  class SearchService {      Stream<QuerySnapshot> searchByName(        String searchField, BuildContext context) async* {       final uid = await TheProvider.of(context).auth.getCurrentUID();        yield* FirebaseFirestore.instance           .collection("userData")          .doc(uid)          .collection("Contacts")          .where('searchKey',              isEqualTo: searchField.substring(0, 1).toUpperCase())          .get();       }      }  

I'm quite sure why, does anyone know how one would go about rectifying this?

three.js distortion, color replacement on glb (gltf) models. Blue changes to green, and yellow changes to orange

Posted: 28 Dec 2021 11:20 AM PST

Distortion, color replacement on glb (gltf) models. Blue changes to green, and yellow changes to orange.
v106 three.js
v97 GLTFLoader.js

enter image description here

enter image description here

enter image description here

enter image description here

Converting a multi line string to an array in Ruby using line breaks as delimiters

Posted: 28 Dec 2021 11:20 AM PST

I would like to turn this string

"P07091 MMCNEFFEG    P06870 IVGGWECEQHS    SP0A8M0 VVPVADVLQGR    P01019 VIHNESTCEQ"  

into an array that looks like in ruby.

["P07091 MMCNEFFEG", "P06870 IVGGWECEQHS", "SP0A8M0 VVPVADVLQGR", "P01019 VIHNESTCEQ"]  

using split doesn't return what I would like because of the line breaks.

No comments:

Post a Comment