Saturday, January 15, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Pimoroni Enviro - Indoor Monitor: Trouble with the Python library

Posted: 15 Jan 2022 08:46 AM PST

I just got a Raspberry Pi Zero 2W for Christmas along with a Pimoroni Enviro - Indoor Monitor (Not to be confused with the Pimoroni Enviro+)

I soldered in the header myself and then connected all the peripherals. But then I got to the Python library section.

Using Pimoroni's instruction (https://learn.pimoroni.com/article/getting-started-with-enviro-plus) I downloaded the Python library and rebooted my Rasberry Pi.

But when I get down to the "Running the Examples" section I type in python weather.py and when I hit Return to comes back with:

Traceback (most recent call last):    File "weather.py, line 4, in <module>      from bme280 import BME280  ImportError: No module named bme280  

I am doing all this in the terminal. There seems to be a section in the U"Using the Python Library" section later in the article that says to import this bme280 but that does not work for me either.

What am I doing wrong and how do I fix it?

Pandas plot multiple lines against date

Posted: 15 Jan 2022 08:46 AM PST

I have the following dataframe: <class 'pandas.core.frame.DataFrame'>

RangeIndex: 1642 entries, 0 to 1641  Data columns (total 13 columns):   #   Column            Non-Null Count  Dtype           ---  ------            --------------  -----            0   Date              1642 non-null   datetime64[ns]   1   Volgnr            1642 non-null   int64            2   account           1642 non-null   object           3   Rentedatum        1642 non-null   datetime64[ns]   4   Bedrag            1642 non-null   float64          5   Balance           1642 non-null   float64          6   tegenrekening     906 non-null    object           7   Code              1642 non-null   object           8   Naam tegenpartij  1642 non-null   object           9   description       1642 non-null   object           10  category          1642 non-null   object           11  Grootboek         1578 non-null   object           12  Kleinboek         1578 non-null   object          dtypes: datetime64[ns](2), float64(2), int64(1), object(8)  memory usage: 166.9+ KB  

'account' has 5 different account numbers which like so: NL00ABCD0123456789

I want two different graphs but I'm already stuck with the first one i.e. I want to see the balance over time for the 5 accounts

In line with other question on this forum I tried:

pd.options.plotting.backend="plotly"  df.set_index('Date', inplace=True)  df.groupby('account')['balance'].plot(legend=True)  

But got the following error:

TypeError: line() got an unexpected keyword argument 'legend'  

What is going wrong here?

For later: If that is solved I want the X-axis to be weeks or months instead of the absolute date so some aggregation will be necessary

Session information sharing on different subdomains

Posted: 15 Jan 2022 08:46 AM PST

I am sharing sessions between two subdomains and I can see the member's information in their different subdomains. If the member logs out, all subdomains are logged out. All is good so far.

However, for example, a.example.com the form information is POSTed to b.example.com. This form information is saved in the database, but the member's ID is not registered. No information is registered to the database with the member. What could be the reason for this?

ini_set('session.cookie_domain',  substr($_SERVER['SERVER_NAME'], strpos($_SERVER['SERVER_NAME'], "."), 100));  setcookie("MID", $_SESSION['uID'], 60 * 60 * 24 * 100, '/', '.example.com');  session_set_cookie_params(60 * 60 * 24 * 100, '/', '.example.com', false, false);  ini_set('session.save_path', $pathStorageMembers . 'sessions');  ini_set('session.cookie_lifetime', 60 * 60 * 24 * 100);  ini_set('session.gc_maxlifetime', 60 * 60 * 24 * 100);  session_start();  

Unable to modify Authorized Domain in firebase auth

Posted: 15 Jan 2022 08:46 AM PST

I am new to firebase and wanted to update the Authorized domains for the authentication, but I am unable to nor delete the or modify the domains. Am I missing something?

How can I invalidate a sound

Posted: 15 Jan 2022 08:45 AM PST

I got some code and I want to be able to press a button and that sound that is going off to stop.

 let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")      player = try! AVAudioPlayer(contentsOf: url!)      player.play()  

Gradle dependency downloads but packages aren't available in project

Posted: 15 Jan 2022 08:45 AM PST

I published a small library of mine to a free maven hosting service, and am using that package in another project. I've done this before without issue but something isn't working this time.

Gradle finds the file just fine, and downloads it I assume. Any change to the URL, package name, or version, and Gradle throws the "can't find the dep in any of these places" error.

However, any import of the packages in this JAR error, saying it can't find the package. IntelliJ, when I refresh gradle deps, also doesn't show my library in the "External Libraries" section.

Here's my gradle.build for the project I'm using the library in:

repositories {      mavenLocal()      mavenCentral()        maven { url = 'https://repo.repsy.io/mvn/viveleroi/tileowner' }  }    group = project.property("group")  version = project.property("version")  targetCompatibility = sourceCompatibility = JavaVersion.VERSION_17    dependencies {      implementation 'network.darkhelmet.tileowner:tileowner:1.0.0'  }      compileJava {      options.compilerArgs += ["-parameters"]      options.fork = true      options.forkOptions.executable = 'javac'  }  

I've downloaded the published jar of my library from that repository, unzipped it, and have confirmed all files are in there as expected.

Here's the build.gradle of my library project:

import org.apache.tools.ant.filters.ReplaceTokens    buildscript {      dependencies {          classpath group: 'com.github.rodionmoiseev.gradle.plugins', name: 'idea-utils', version: '0.2'      }  }    plugins {      id "com.github.johnrengelman.shadow" version "7.0.0"      id "xyz.jpenilla.run-paper" version "1.0.6"      id 'maven-publish'  }    apply plugin: 'java'  apply plugin: 'idea'  apply plugin: 'idea-utils'  apply plugin: 'checkstyle'    processResources {      filter ReplaceTokens, tokens: [          "apiversion": project.property("apiversion"),          "version"   : project.property("version")      ]  }    repositories {      mavenLocal()      mavenCentral()        maven { url = "https://repo.aikar.co/content/groups/aikar/" }      maven { url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' }  }    group = project.property("group")  version = project.property("version")  targetCompatibility = sourceCompatibility = JavaVersion.VERSION_17    dependencies {      compileOnly 'org.spigotmc:spigot-api:1.18-R0.1-SNAPSHOT'      implementation 'co.aikar:acf-bukkit:0.5.0-SNAPSHOT'  }    compileJava {      options.compilerArgs += ["-parameters"]      options.fork = true      options.forkOptions.executable = 'javac'  }    jar {      actions = []      dependsOn = []      dependsOn('shadowJar')  }    shadowJar {      relocate 'co.aikar.commands', 'network.darkhelmet.tileowner.acf'      relocate 'co.aikar.locales', 'network.darkhelmet.tileowner.locales'  }    publishing {      publications {          shadow(MavenPublication) { publication ->              project.shadow.component(publication)          }      }        repositories {          maven {              name = 'repsy'              url = 'https://repo.repsy.io/mvn/viveleroi/tileowner'              credentials(PasswordCredentials)          }      }  }  

javascript XMLHttpRequest needs controller?

Posted: 15 Jan 2022 08:45 AM PST

Spring Boot 2.6.2
Java 11
Thymeleaf

directory

My goal is to load navbar.html through javascript when categoryTest.html is opened.
First of all, I add this code to categoryTest.html

        <nav class="navbar" includeHTML="navbar.html">          </nav>  

And there is the function I wrote

    function includeHTML() {          var z, i, elmnt, file, xhttp;            z = document.getElementsByTagName("*");            for (i = 0; i < z.length; i++) {              elmnt = z[i];                file = elmnt.getAttribute("includeHTML");                if (file) {                  xhttp = new XMLHttpRequest();                  xhttp.onreadystatechange = function() {                      if (this.readyState == 4) {                          if (this.status == 200) {elmnt.innerHTML = this.responseText;}                          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}                      }                  }                  xhttp.open("GET", file, true);                  xhttp.send();                  return;              }          }      }  

Whenever I start the server and see the result, xhttp.send() is the problem.

But once I add this method to my controller, it works well.

    @GetMapping("/navbar.html")      public ModelAndView navbar(){          ModelAndView modelAndView = new ModelAndView("navbar");          return modelAndView;      }  

Idk why this method is required for this process.

can any one solve it with (switch ) [closed]

Posted: 15 Jan 2022 08:45 AM PST

Write a rogram that clculates parking fees for a multilevel parking garage. Ask whether the driver is in a car or a truck. Charge the driver $2.00 for the first hour, $3.00 for the second, and $5.00 for more than 2 hours. If it is a truck, add $1.00 to the total fee.

How to run a Vercel serverless function in a static HTML file?

Posted: 15 Jan 2022 08:44 AM PST

I have the following project directory:

a_vercel_test  |  +--- index.html  |  +--- pages       |       +--- api            |            +--- index.js  

I ran vercel dev inside the folder to get it running. When I go to localhost:3000, I can find the contents of the index.html file properly rendered. For the record, the index.html file looks like this:

<!DOCTYPE html>  <html>  <head>      <title>A Vercel Test</title>  </head>  <body>      <h1>A Vercel Test</h1>  </body>  </html>  

The index.js file looks like this:

// pages/api/index.js'    export default function handler(req, res) {    console.log('Running Function');  }  

Now what I want to do is run this as a serverless function when the HTML file is loaded. The reason I want to do this is that I want to query some data in this function (using env db secrets), and pass it to my file for rendering. Is this actually possible to do using such bare bones setup on Vercel? And if so, how do I do this? Most examples in the docs are related to next.js, and are also a bit confusing to be honest. I would love to be able to keep everything really light and static.

Asp.net web forms post async - Goes to sleep mode

Posted: 15 Jan 2022 08:44 AM PST

I am using a library for communicate with a crypto api.
In Console Application every thing is ok about async post.
But in webforms it goes to sleep and nothing happens!
Just loading mode.
Here is the method :

private async Task<WebCallResult<T>> PostAsync<T>(string url, object obj = null, CancellationToken cancellationToken = default(CancellationToken))  {      using (var client = GetHttpClient())      {          var data = JsonConvert.SerializeObject(obj ?? new object());          var response = await client.PostAsync($"{url}", new StringContent(data, Encoding.UTF8, "application/json"), cancellationToken);          var content = await response.Content.ReadAsStringAsync();            // Return          return this.EvaluateResponse<T>(response, content);      }  }  

In line var response = web site goes to loading mode.
No error - Nothing - Just Loading.
How can i fix this problem in webforms?
In Console Application it is working fine.
Maybe i should change something in Web.config!!!
Here is the library

Why does the last "system.out.println" have "unreachable-code" error? - Much appreciated

Posted: 15 Jan 2022 08:45 AM PST

I have already found out a way to fix it but I can't understand what is the problems of the code below, can you guys explain it to me, it will be much appreciated.

public class demo {  Scanner sc = new Scanner(System.in);  String gender = "";    public void abc() {      while (true) {          System.out.println("Press 1. To set gender to MALE");          System.out.println("Press 2. To set gender to FEMALE");          System.out.println("Press 3. To set gender to UNKNOWN");          int a = sc.nextInt();          switch (a) {          case 1:              gender = "MALE";              System.out.println(gender);              break;          case 2:              gender = "FEMALE";              System.out.println(gender);              break;          case 3:              gender = "UNKNOWN";              System.out.println(gender);              break;          default:              System.out.println("Wrong Number --- Care to retype it");            } // for        } // while      System.out.println(gender); // unreachable code    }  }  

SQL (Custom) Unique Constraint for a set of rows

Posted: 15 Jan 2022 08:45 AM PST

How to create a ( may be custom) unique constraint for a particular no.of rows.

I have table data as below

enter image description here

I want my itemFK column to be Unique for same productionsessionKey value. i.e for all yellow (101) itemFK should be Unique and for all blue (102) itemFK should be unique. Else they can be duplicate.

Adding an object to a list Python OOP

Posted: 15 Jan 2022 08:46 AM PST

I'm new to python OOP. I'm trying to create a method that gets user's input (book name, author and genre), creates a book Object and adds it to a list only if such a book doesn't exist. Initially, I wanted to use __eq__ but couldn't find a way to make it work...

Here my code:

class Book:  def __init__(self, book_name, author_name, genre):      self.book_name = book_name      self.author_name = author_name      self.genre = genre      self.booksList=[]    def __eq__(self, other):      if (self.book_name == other.book_name):          return True      else:           return False        def __str__(self):      return f"The book {self.book_name} written by {self.author_name} is {self.genre}"    def addBook(self, book_name, author_name, genre):      if book_name not in self.booksList:        self.booksList.append(book_name)        print("success")      else:          print("Book already exists")  
while True:      option=input("choose an operation:\n \n")             if option not in ['1','2','3','4','5','6','7','8']:              print("Please enter a valid operation")        if (option=="1"):                    book_name=input ('Enter book name:')                    author_name = input ('Enter author name:')                    genre= input ('Enter genre:')                    new_book=Book(book_name, author_name, genre)                    new_book.addBook(book_name, author_name, genre)                              #option2        elif (option=="2"):                    pass```  

curl: (35) gnutls_handshake() failed Error after messing up with Nginx Conf file

Posted: 15 Jan 2022 08:46 AM PST

Today I decided to clean up my VPS which had so many unused certificates. I removed these certificates and also deleted some of the entries that had references to it in various '.conf' and '.tmpl' files for Nginx.

Sadly after doing all this, when I curl to my site, I get the following error:

curl: (35) gnutls_handshake() failed: The TLS connection was non-properly terminated.  

My website is not working anymore. :(

Back tracking my steps, I remembered that while deleting references to old certificates, I messed up my nginx tmpl file, specifically the file:

/etc/nginx/templates/ssl.tmpl  

I played around with this file which now looks like the following:

# ssl on;  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;    # Fix 'The Logjam Attack'.  # ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5;  # ssl_prefer_server_ciphers on;  # ssl_dhparam /etc/ssl/dh2048_param.pem;  

I could not recollect how the old file looks.

Any help? I'm out of luck. Don't know what to do.

How can I run a script in Google Drive, which is in G: drive from Python, which is installed in C: drive (Windows 10)?

Posted: 15 Jan 2022 08:46 AM PST

I have a shared .py script stored in a shared folder in google drive, which for our work machines is mounted on G:. It needs to be run using python, which is installed on C:.

I can see G: in file explorer, however I cannot cd to it from command prompt and I do not think I run the script using python "path-to-script.py" if the script is in a different drive, although I am happy to be proven wrong here.

Is there a way I can let local Python installs access this shared folder? Unfortunately, using git instead of Google Drive is not an option.

Here's what my command prompt would normally look like when I run a script:

C:WINDOWS\System32> python ~\scripts\shared_scripts.py  

But since the script lives in G:, not C:, I can't navigate to its location. I hope that makes sense.

Enable button when edit text and checkbox are are fill and vice versa

Posted: 15 Jan 2022 08:46 AM PST

Basically, I want to enable the button when both edit text and checkbox are fill if any one of not fill then disable the button in android with java

Using column name as part of foreign key relationship

Posted: 15 Jan 2022 08:46 AM PST

As part of the application I am building I want to store the values of all dropdowns in a single table, where all table/column combinations that represent a dropdown will be able to reference it.

Something like the below:

CREATE TABLE dropdown_def  (      id int,      table_id int,      field_name TEXT,      value TEXT,      PRIMARY KEY (id),      UNIQUE (table_id, field_name, value)  );    INSERT INTO test1.dropdowns (id, table_id, field_name, value)  VALUES (1, 1, 'status', 'active');    CREATE TABLE clients   (      id int,      table_id int,      status TEXT,     FOREIGN KEY (table_id, 'status', status)           REFERENCES dropdowns (table_id, field_name, value)  );  

I tried the above but with no surprise it seems you cannot use the actual column name as part of the foreign key constraint.

Is there any other way of using the column identifier in a FK?

how to create conditional list in ansible task

Posted: 15 Jan 2022 08:46 AM PST

If possible I would like to combine the two tasks below into a single task. Rather than use the when conditional, is there some way to add the last two list items under subject_alt_name (second task) only when item.0.sans is defined? These two tasks are otherwise identical.

I did try some additional filters for those lines to default/omit them, but then I ended up with errors that the list could not be parsed. I also explored the possibility of an inline template, but I cannot tell if that is supported in this context. A templating solution seems ideal to me... I think that technique could be useful in many other scenarios.

The full playbook is pretty short, so I can post that if it would be helpful for additional context.

- name: generate endpoint CSR - no custom sans    when: item.0.sans is undefined    community.crypto.openssl_csr:      common_name: "{{item.0.name}}.{{item.1}}"      path: "{{endpoint_artifact_dir}}/{{item.1}}//CSRs/{{item.0.name}}.{{item.1}}.pem"      privatekey_path: "{{endpoint_artifact_dir}}/{{item.1}}/keys/{{item.0.name}}.{{item.1}}.pem"      subject_alt_name:        - "DNS:{{item.0.name}}.{{item.1}}"        - "DNS:{{item.0.name}}"        - "IP:127.0.0.1"    with_nested:      - "{{endpoints}}"      - "{{domains}}"    - name: generate endpoint CSR - with custom sans    when: item.0.sans is defined    community.crypto.openssl_csr:      common_name: "{{item.0.name}}.{{item.1}}"      path: "{{endpoint_artifact_dir}}/{{item.1}}/CSRs/{{item.0.name}}.{{item.1}}.pem"      privatekey_path: "{{endpoint_artifact_dir}}/{{item.1}}/keys/{{item.0.name}}.{{item.1}}.pem"      subject_alt_name:        - "DNS:{{item.0.name}}.{{item.1}}"        - "DNS:{{item.0.name}}"        - "IP:127.0.0.1"        - "{{ item.0.sans | join(',') | replace(',', '.' + item.1 + ', ') + '.' + item.1 }}"        - "{{ item.0.sans | join(',') }}"    with_nested:      - "{{endpoints}}"      - "{{domains}}"  

Django rest framework user model referring to several other model

Posted: 15 Jan 2022 08:45 AM PST

I have a couple of models like:

class Organization(models.Model):     id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)     ....    class Customer(models.Model):         id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)         ....    class Supplier(models.Model):     id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)     ....  

Each model have their own one or more users, I created a user model like this:

class User(AbstractBaseUser, PermissionsMixin):    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)    email_address = models.EmailField(max_length=255, unique=True)    name = models.CharField(max_length=255)  

My question is how can I create a relationship between User and Organization, Customer, Supplier...? I found one solution like:

class User(AbstractBaseUser, PermissionsMixin):    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)    email_address = models.EmailField(max_length=255, unique=True)    name = models.CharField(max_length=255)    organization = models.ForeignKey(Organization)    customer = models.ForeignKey(Organization)    supplier = models.ForeignKey(Supplier)  

Which I did not like to do because I have several models that have their users. Another way I found is GenericForeignKey Relationship but also not a very good solution. One of the reasons for this is I have more models to implement similar relationships which becomes very complicated. Can anyone suggest an elegant solution for this? Thanks in advance!

kotlin lazy toString

Posted: 15 Jan 2022 08:46 AM PST

Let's say I have a toString method that takes a long time to return a result but its value won't change once it's computed. The best we have come up with is this (thanks @Tenfour04 for the comment):

class MyClass {      private val _toString: String by lazy {          /** something that takes a while to compute**/      }      override fun toString() = _toString  }  

but it's not perfect because the class still has to implement an extra _toString property.

Ideally I am looking for some sort of delegation of the method, like I did for the property... but I can't create an interface with toString and delegate its implementation because it's a method of Any.

Using variables in a for loop

Posted: 15 Jan 2022 08:45 AM PST

I understand the magic of the setlocal enabledelayedexpansion; this brought me one step further but I am still not completely happy. I am now able to assign the filename to a !loop variable!, but I fail to use that variable subseqently. I try to get the filename without the extension. There must be something else that I am unaware of.

This is my coding now:

::process all files in directory  setlocal enabledelayedexpansion    for %%f in (C:\windows\*.ico) do (        echo F=%%f      set myname=%%f      echo.N=!myname!      call :strlen myLen "!myname!"      echo.myLen=!myLen!        set /A L=myLen-3 + 1      set str=!myname!      echo.str1=!str! L=!L!      set str=!str:~0,!L! !    <-Remove extension from filename      echo.str2=!str!          <-This does not work!  

)

Here is the output of my call :

 F=C:\windows\AnyWeb Print.ico   N=C:\windows\AnyWeb Print.ico   Strlen C:\windows\AnyWeb Print.ico   myLen=25   str1=C:\windows\AnyWeb Print.ico L=23   str2=L       <--- what went wrong ????  

When one of my column in dataframe is nested list, how should i transform it to multi-dimensional np.array?

Posted: 15 Jan 2022 08:46 AM PST

I have the following data frame.

test = {      "a": [[[1,2],[3,4]],[[1,2],[3,4]]],      "b": [[[1,2],[3,6]],[[1,2],[3,4]]]  }    df = pd.DataFrame(test)  df  
a b
0 [[1,2],[3,4]] [[1,2],[3,6]]
1 [[1,2],[3,4]] [[1,2],[3,4]]

For example, I want to transform the first column to a numpy array with shape (2,2,2). If I use the following code, i will get a array with shape (2,) instead of (2,2,2)

df['a'].apply(np.asarray).values  

How can I get the array with shape (2,2,2)?

Extending SigninManager<User> throws errors upon injection

Posted: 15 Jan 2022 08:46 AM PST

public class SignInService : SignInManager<User>, ISignInService  {      public SignInService(UserManager<User> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<User> claimsFactory,           IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<User>> logger, IAuthenticationSchemeProvider schemes, IUserConfirmation<User> userConfirmation)           : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes)      {      }  }  

The above code throws no errors upon compilation. In fact the website has no issues until I try to activate a control upon which SignInService is called.

I have tried injecting each parameter individually from SignInService and the controller always resolves them all, however if I try to resolve ISignInService then it crashes.

To rule out the obvious, I have mapped the injection in startup and tested it without extending the SignInManager.

I've been doing a lot of research around this and I have found that the error that I am getting usually means mismatch of libraries and this is kind of where I'm a little lost how to move forward to resolve this.

I have this signin service in a standalone identity project and that project has the following packages:

Microsoft.AspNetCore.Identity 2.2.0

Microsoft.Extensions.Identity.Stores 6.0.1

When I look at packages there are no more updates available for me. The project is also configured for .NET 6.0 framework. <TargetFramework>net6.0</TargetFramework>

The more I read it sounds like there is a version that is past 2.2 but I can't find packages for it and not really sure how to resolve this error.

MyProject.Service.SignInService..ctor(UserManager userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory claimsFactory, IOptions optionsAccessor, ILogger<SignInManager> logger, IAuthenticationSchemeProvider schemes) in SignInService.cs

System.RuntimeMethodHandle.InvokeMethod(object target, ref Span arguments, Signature sig, bool constructor, bool wrapExceptions) System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(ServiceCallSite callSite, TArgument argument) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope) Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine+<>c__DisplayClass2_0.b__0(ServiceProviderEngineScope scope) Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired) lambda_method27(Closure , IServiceProvider , object[] ) Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass7_0.b__0(ControllerContext controllerContext) Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass6_0.g__CreateController|0(ControllerContext controllerContext) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker) Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

System.MissingMethodException: Method not found: 'Void Microsoft.AspNetCore.Identity.SignInManager1..ctor(Microsoft.AspNetCore.Identity.UserManager1<!0>, Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory1<!0>, Microsoft.Extensions.Options.IOptions1<Microsoft.AspNetCore.Identity.IdentityOptions>, Microsoft.Extensions.Logging.ILogger1<Microsoft.AspNetCore.Identity.SignInManager1<!0>>, Microsoft.AspNetCore.Authentication.IAuthenticationSchemeProvider)'. at MyProject.Service.SignInService..ctor(UserManager1 userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory1 claimsFactory, IOptions1 optionsAccessor, ILogger1 logger, IAuthenticationSchemeProvider schemes) at System.RuntimeMethodHandle.InvokeMethod(Object target, Span1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions) at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.b__0(ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired) at lambda_method27(Closure , IServiceProvider , Object[] ) at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.b__0(ControllerContext controllerContext) at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.g__CreateController|0(ControllerContext controllerContext) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

How to throw NoHandlerFoundException if path param is not Long in springboot

Posted: 15 Jan 2022 08:46 AM PST

Currently, there is a GetMapping like follows

 @GetMapping(value = "/{id}")      public ResponseEntity<Dog> getTrainById(@PathVariable Long id) {      Dog dog= animalService.getAnimalById(id);      return new ResponseEntity<>(Dog , HttpStatus.OK);   }  

now if someone accesses http://localhost:8080/api/animal/1, it returns the animal.

But I need to throw NoHandlerFoundException if someone accesses this endpoint without a Long variable as a path parameter, that means like this http://localhost:8080/api/animal/asdsad

IF anyone can tell me way to achieve this, that would be much appreciated

Also I have global exception handling like follows

@ControllerAdvice  public class DemoExceptionHandler extends ResponseEntityExceptionHandler {    @ExceptionHandler(EntityNotFoundException.class)  public ResponseEntity<GenericResponse> customHandleNotFound(Exception ex, WebRequest request)   {      return new ResponseEntity<>(new GenericResponse(ex.getMessage(), null), HttpStatus.NOT_FOUND);  }    @Override  protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex,   HttpHeaders headers, HttpStatus status, WebRequest request) {      return new ResponseEntity<>(new GenericResponse("invalid endpoint", null), HttpStatus.METHOD_NOT_ALLOWED);  }  

}

Login Page redirect is missing port - OpenIddict/MSIdentity & Blazor on nginx production server

Posted: 15 Jan 2022 08:46 AM PST

I'm working on a Blazor project (asp.net core hosted) that is published on a Linux host, with Nginx which is working as a web server and proxy to redirect calls to my domain with a specific port to my application. (https://example:9999 => localhost:10000 for example)

I integrated OpenIddict (OAuth) for authorization since IdentityServer needs a custom license on the latest .net version.

The problem I currently face only happens on production, when OpenIddict redirects to the login page with the custom route parameters, the URL is missing the custom port I'm using on production. On localhost (Dev / local machine) the correct port is supplied https://localhost:7115, but on production, I'm redirected to https://example.com/Identity/Account/Login, instead of https://example.com:9999/Identity/Account/Login.

When I'm changing the URL manually everything works fine and I can correctly login to my application.

The OpenIddict Server settings:

builder.Services.AddDefaultIdentity<ApplicationUser>()  .AddRoles<IdentityRole>()  .AddEntityFrameworkStores<ApplicationDbContext>()  .AddDefaultTokenProviders();    builder.Services.Configure<IdentityOptions>(options =>  {      options.ClaimsIdentity.UserNameClaimType = OpenIddictConstants.Claims.Name;      options.ClaimsIdentity.UserIdClaimType = OpenIddictConstants.Claims.Subject;      options.ClaimsIdentity.RoleClaimType = OpenIddictConstants.Claims.Role;  });    builder.Services.AddQuartz(options =>  {      options.UseMicrosoftDependencyInjectionJobFactory();      options.UseSimpleTypeLoader();      options.UseInMemoryStore();  });    builder.Services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);    builder.Services.AddOpenIddict()  .AddCore(options =>  {      options.UseEntityFrameworkCore()          .UseDbContext<ApplicationDbContext>();      options.UseQuartz();  })  .AddServer(options =>  {      options.SetIssuer(new Uri(publicHostFullUrl));      options.SetAuthorizationEndpointUris(authorizationEndpoint)          .SetLogoutEndpointUris(logoutEndpoint)          .SetTokenEndpointUris(tokenEndpoint)          .SetUserinfoEndpointUris(userInfoEndpoint);      options.RegisterScopes(OpenIddictConstants.Scopes.Email, OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Roles);        options.AllowAuthorizationCodeFlow()          .AllowRefreshTokenFlow();      options.AddEncryptionCertificate(certificate)          .AddSigningCertificate(certificate);      }        options.UseAspNetCore()          .EnableAuthorizationEndpointPassthrough()          .EnableLogoutEndpointPassthrough()          .EnableStatusCodePagesIntegration()          .EnableTokenEndpointPassthrough();        options.AcceptAnonymousClients();      options.DisableScopeValidation();  })  .AddValidation(options =>  {      options.SetIssuer(new Uri(publicHostFullUrl));      options.UseLocalServer();      options.UseAspNetCore();  });  

The Client settings:

builder.Services.AddOidcAuthentication(options =>  {      options.ProviderOptions.ClientId = clientId;      options.ProviderOptions.Authority = $"{builder.HostEnvironment.BaseAddress}";      options.ProviderOptions.ResponseType = "code";      options.ProviderOptions.ResponseMode = "query";      options.AuthenticationPaths.RemoteRegisterPath = $"{builder.HostEnvironment.BaseAddress}Identity/Account/Register";      options.AuthenticationPaths.LogInCallbackPath = $"{builder.HostEnvironment.BaseAddress}/Identity/Account/Login";      options.AuthenticationPaths.LogInPath = $"{builder.HostEnvironment.BaseAddress}/Identity/Account/Login";  });  

My Authorization Controller action where I return the ChallengeResult to the Login Page:

[HttpGet("~/connect/authorize")]  [HttpPost("~/connect/authorize")]  [IgnoreAntiforgeryToken]  public async Task<IActionResult> Authorize()  {      if (request.HasPrompt(Prompts.Login))      {          var prompt = string.Join(" ", request.GetPrompts().Remove(Prompts.Login));          var parameters = Request.HasFormContentType ? Request.Form.Where(parameter => parameter.Key != Parameters.Prompt).ToList() : Request.Query.Where(parameter => parameter.Key != Parameters.Prompt).ToList();          parameters.Add(KeyValuePair.Create(Parameters.Prompt, new StringValues(prompt)));          return Challenge(              authenticationSchemes: IdentityConstants.ApplicationScheme,              properties: new AuthenticationProperties              {                  RedirectUri = Request.PathBase + Request.Path + QueryString.Create(parameters)              });      }        var result = await HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme);      if (!result.Succeeded || (request.MaxAge != null && result.Properties?.IssuedUtc != null &&                                DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value)))      {          if (request.HasPrompt(Prompts.None))          {              return Forbid(                  authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,                  properties: new AuthenticationProperties(new Dictionary<string, string>                  {                      [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired,                      [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in."                  }!));          }                        return Challenge(              authenticationSchemes: IdentityConstants.ApplicationScheme,              properties: new AuthenticationProperties              {                  RedirectUri = Request.PathBase + Request.Path + QueryString.Create(                       Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())              });      }        var user = await _userManager.GetUserAsync(result.Principal) ??                 throw new InvalidOperationException("The user details cannot be retrieved.");        var application = await _applicationManager.FindByClientIdAsync(request.ClientId!) ??                        throw new InvalidOperationException("Details concerning the calling client application cannot be found.");        var authorizations = await _authorizationManager.FindAsync(          subject: await _userManager.GetUserIdAsync(user),          client: (await _applicationManager.GetIdAsync(application))!,          status: Statuses.Valid,          type: AuthorizationTypes.Permanent,          scopes: request.GetScopes()).ToListAsync();        switch (await _applicationManager.GetConsentTypeAsync(application))      {          case ConsentTypes.External when !authorizations.Any():              return Forbid(                  authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,                  properties: new AuthenticationProperties(new Dictionary<string, string>                  {                      [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,                      [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =                          "The logged in user is not allowed to access this client application."                  }!));            case ConsentTypes.Implicit:          case ConsentTypes.External when authorizations.Any():          case ConsentTypes.Explicit when authorizations.Any() && !request.HasPrompt(Prompts.Consent):              var principal = await _signInManager.CreateUserPrincipalAsync(user);              principal.SetScopes(request.GetScopes());              principal.SetResources(await _scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync());                var authorization = authorizations.LastOrDefault();              if (authorization == null)              {                  authorization = await _authorizationManager.CreateAsync(                      principal: principal,                      subject: await _userManager.GetUserIdAsync(user),                      client: (await _applicationManager.GetIdAsync(application))!,                      type: AuthorizationTypes.Permanent,                      scopes: principal.GetScopes());              }                principal.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization));                foreach (var claim in principal.Claims)              {                  claim.SetDestinations(GetDestinations(claim, principal));              }                return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);            case ConsentTypes.Explicit when request.HasPrompt(Prompts.None):          case ConsentTypes.Systematic when request.HasPrompt(Prompts.None):              return Forbid(                  authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,                  properties: new AuthenticationProperties(new Dictionary<string, string>                  {                      [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,                      [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =                          "Interactive user consent is required."                  }!));            default:              return View(new AuthorizeViewModel              {                  ApplicationName = await _applicationManager.GetDisplayNameAsync(application),                  Scope = request.Scope              });      }  }    [Authorize, FormValueRequired("submit.Accept")]  [HttpPost("~/connect/authorize"), ValidateAntiForgeryToken]  public async Task<IActionResult> Accept()  {      var request = HttpContext.GetOpenIddictServerRequest() ??                    throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");        var user = await _userManager.GetUserAsync(User) ??                 throw new InvalidOperationException("The user details cannot be retrieved.");        var application = await _applicationManager.FindByClientIdAsync(request.ClientId!) ??                        throw new InvalidOperationException("Details concerning the calling client application cannot be found.");        var authorizations = await _authorizationManager.FindAsync(          subject: await _userManager.GetUserIdAsync(user),          client: (await _applicationManager.GetIdAsync(application))!,          status: Statuses.Valid,          type: AuthorizationTypes.Permanent,          scopes: request.GetScopes()).ToListAsync();        if (!authorizations.Any() && await _applicationManager.HasConsentTypeAsync(application, ConsentTypes.External))      {          return Forbid(              authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,              properties: new AuthenticationProperties(new Dictionary<string, string>              {                  [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,                  [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =                      "The logged in user is not allowed to access this client application."              }!));      }        var principal = await _signInManager.CreateUserPrincipalAsync(user);        principal.SetScopes(request.GetScopes());      principal.SetResources(await _scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync());        var authorization = authorizations.LastOrDefault();      if (authorization == null)      {          authorization = await _authorizationManager.CreateAsync(              principal: principal,              subject: await _userManager.GetUserIdAsync(user),              client: (await _applicationManager.GetIdAsync(application))!,              type: AuthorizationTypes.Permanent,              scopes: principal.GetScopes());      }        principal.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization));        foreach (var claim in principal.Claims)      {          claim.SetDestinations(GetDestinations(claim, principal));      }        return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);  }  

Elsa workflow designer drag and drop not work

Posted: 15 Jan 2022 08:45 AM PST

I have a problem with the drag & drop when I use the designer. I tried to add a "Fork-Join" but I can't connect the Branches with the Join. When I try to drag them, it moves the whole workflow. What am I doing wrong?

Can I use Prism for WinUI 3 apps?

Posted: 15 Jan 2022 08:46 AM PST

I'd like to use Prism in a WinUI 3 app, and I saw the Prism v8.1 release.

Additionally Prism 8.1 offers a new Prism.Uno.WInUI platform target for those wishing to build either native WinUI3, or Cross Platform WinUI 3 apps with Uno Platform.

I'm confused about Uno. I'm not using Uno, can I still use Prism in a WinUI 3 app without using Uno?

If yes, which packages do I need to install and in which projects? (I'd like to use DryIoc)

I guess Prism.DryIoc.Uno.WinUI must be added to the WinUI 3 app project.

But what about the other packages for using Prism?

c# webcal:link in Outlook “internet calendar subscription" produce multiple instances of outlook calendars in outlook.exe

Posted: 15 Jan 2022 08:45 AM PST

I'm working with

  • Windows 10 Professional 64-bit (21H1)
  • MS Office 2013
  • VS 2019 (v16.11.3)

I'm try to read a subscribed webcal - calendar with C#. Every time OpenSharedFolder(webCalString) is executed, the process starts with a small window saying "Connecting to Web server …", then the Microsoft Outlook.exe user interface is opened and a new instance of this calendar is created under "My Calendars". The problem does not occur if Outlook has been opened prior to starting my C# program.

My code is simple, it uses Microsoft.Office.Interop.Outlook. I added a reference to MS Office 15.0 Object library 2.7 (15.0.5363.1000):

using System;  using System.Windows.Forms;  using Outlook = Microsoft.Office.Interop.Outlook;    …    string webCalString = "webcal://koenigstein.mein-abfallkalender.de/ical.ics?sid=26035&cd=inline&ft=noalarm&fp=next_1000&wids=657,919,661,658,656,659,660,662,663&uid=46006&pwid=3ade10b890&cid=94";    // initially set to NULL  Microsoft.Office.Interop.Outlook.Application oApp = null;  Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;  Microsoft.Office.Interop.Outlook.Folder CalendarFolderAbo = null;     oApp = new Microsoft.Office.Interop.Outlook.Application();    mapiNamespace = oApp.GetNamespace("MAPI"); ;    // these 2 lines are necessary, otherwise OpenSharedFolder("webcal") does not work (why???)  Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;  CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);    **// the following line opens outlook.exe, shows the User Interface of MS- Outlook, and always produces a new instance of this subscribed calendar under "My Calendars"**  CalendarFolderAbo = mapiNamespace.OpenSharedFolder(webCalString) as Outlook.Folder;  

Getting an error when using the image_to_osd method with pytesseract

Posted: 15 Jan 2022 08:45 AM PST

Here's my code:

import pytesseract  import cv2  from PIL import Image    pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"      def main():      original = cv2.imread('D_Testing.png', 0)      # binary thresh it at value 100. It is now a black and white image      ret, original = cv2.threshold(original, 100, 255, cv2.THRESH_BINARY)      text = pytesseract.image_to_string(original, config='--psm 10')      print(text)      print(pytesseract.image_to_osd(Image.open('D_Testing.png')))      if __name__ == "__main__":      main()  

For the first out put I get what I need which is the letter D

D  

Which is intended, but when it tries to do the second print statement it spits out this.

Traceback (most recent call last):    File "C:/Users/Me/Documents/Python/OpenCV/OpenCV_WokringTest/PytesseractAttempt.py", line 18, in <module>      main()    File "C:/Users/Me/Documents/Python/OpenCV/OpenCV_WokringTest/PytesseractAttempt.py", line 14, in main      print(pytesseract.image_to_osd(Image.open('D_Testing.png')))    File "C:\Users\Me\Documents\Python\OpenCV\OpenCV_WokringTest\venv\lib\site-packages\pytesseract\pytesseract.py", line 402, in image_to_osd      }[output_type]()    File "C:\Users\Me\Documents\Python\OpenCV\OpenCV_WokringTest\venv\lib\site-packages\pytesseract\pytesseract.py", line 401, in <lambda>      Output.STRING: lambda: run_and_get_output(*args),    File "C:\Users\Me\Documents\Python\OpenCV\OpenCV_WokringTest\venv\lib\site-packages\pytesseract\pytesseract.py", line 218, in run_and_get_output      run_tesseract(**kwargs)    File "C:\Users\Me\Documents\Python\OpenCV\OpenCV_WokringTest\venv\lib\site-packages\pytesseract\pytesseract.py", line 194, in run_tesseract      raise TesseractError(status_code, get_errors(error_string))  pytesseract.pytesseract.TesseractError: (1, 'Tesseract Open Source OCR Engine v4.0.0.20181030 with Leptonica Warning: Invalid resolution 0 dpi. Using 70 instead. Too few characters. Skipping this page Warning. Invalid resolution 0 dpi. Using 70 instead. Too few characters. Skipping this page Error during processing.').   

I am not sure what to do. I can't really find too much about this error online. Also I am not sure what to do. The goal is simply to get it spit out the orientation of my letter. Thank you for all helpful comment in advance!

Is there a "null coalescing" operator in JavaScript?

Posted: 15 Jan 2022 08:45 AM PST

Is there a null coalescing operator in Javascript?

For example, in C#, I can do this:

String someString = null;  var whatIWant = someString ?? "Cookies!";  

The best approximation I can figure out for Javascript is using the conditional operator:

var someString = null;  var whatIWant = someString ? someString : 'Cookies!';  

Which is sorta icky IMHO. Can I do better?

No comments:

Post a Comment