Thursday, March 3, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to create a dictionary of string and delegate in C#

Posted: 03 Mar 2022 05:14 AM PST

In C#, I have a dictionary as below: var myActionDictionary = new Dictionary<string, Action();

myActionDictionary.add("Test1", Test1Method);

where it will run a method that takes string as a parameter and returns void when I invoke it.

private void Test1Method(string text) { return null;}

How do I change create a dictionary so that it runs a method and returns a string?

var myDelegateDictionary = new Dictionary<string, ???();

myDelegateDictionary.add("Test2", Test2Method);

private string Test2Method(string text) { return text;}

What do I write for ??? and how do I declare a delegate? thanks

How to match my dext with an USB device in DriverKit?

Posted: 03 Mar 2022 05:14 AM PST

I am writing a driverkit extension whose goal is to block USB devices, such as flash drives. As a starting point, I chose example project at https://developer.apple.com/documentation/driverkit/communicating_between_a_driverkit_extension_and_a_client_app?language=objc

In effort not to disable a keyboard or a mouse, firstly I am trying to match my dext with a single concrete USB drive, whose vendorId I found in the registry (being aware of hexa to decimal conversions). The problem is that when the flash drive is plugged in, the system doesn't match my dext and continues with the system one.

What's wrong? Is a provisioning profile required for this? Is it even possible to match any device this way?

Driver's entitlement file:

<?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">  <plist version="1.0">  <dict>      <key>com.apple.security.app-sandbox</key>      <true/>      <key>com.apple.developer.driverkit</key>      <true/>      <key>com.apple.developer.driverkit.transport.usb</key>      <array>          <dict>              <key>idVendor</key>              <integer>9128</integer>          </dict>      </array>  </dict>  </plist>  

Info.plist:

<?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">  <plist version="1.0">  <dict>      <key>CFBundleDevelopmentRegion</key>      <string>$(DEVELOPMENT_LANGUAGE)</string>      <key>CFBundleExecutable</key>      <string>$(EXECUTABLE_NAME)</string>      <key>CFBundleIdentifier</key>      <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>      <key>CFBundleInfoDictionaryVersion</key>      <string>6.0</string>      <key>CFBundleName</key>      <string>$(PRODUCT_NAME)</string>      <key>CFBundlePackageType</key>      <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>      <key>CFBundleShortVersionString</key>      <string>1.0</string>      <key>CFBundleVersion</key>      <string>1</string>      <key>IOKitPersonalities</key>      <dict>          <key>DeviceControlDriver</key>          <dict>              <key>idVendor</key>              <integer>9128</integer>              <key>CFBundleIdentifier</key>              <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>              <key>CFBundleIdentifierKernel</key>              <string>com.apple.kpi.iokit</string>              <key>IOClass</key>              <string>IOUserService</string>              <key>IOProviderClass</key>              <string>IOUSBHostDevice</string>              <key>IOUserClass</key>              <string>DeviceControlDriver</string>              <key>IOUserServerName</key>              <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>              <key>UserClientProperties</key>              <dict>                  <key>IOClass</key>                  <string>IOUserUserClient</string>                  <key>IOUserClass</key>                  <string>DeviceControlDriver</string>              </dict>          </dict>      </dict>      <key>OSBundleUsageDescription</key>      <string></string>  </dict>  </plist>  

AudioLibrary's and their own Targets

Posted: 03 Mar 2022 05:14 AM PST

Please help me with choice. I am interested in writing Audio Software with low-latency using C++. I want my app be cross-platform Linux, MacOS, Windows and it would be very cool if IOS and Android also. I have some candidates, such as JUCE framework, SDL2(audio), PortAudio. I don't want to use naked OS API's like CoreAudio,because it OS depending. Thanks. and if you have another libraries please feel free to enumerate them too.

I tried to find information, but in general there isn't any info about direct comparison of both technologies.

Please can you write the answer describing the most popular libraries for c++ and like their main purpose and so on.

How do I log an error thrown by the metamask browser extension?

Posted: 03 Mar 2022 05:14 AM PST

I'm trying to catch an error on Metamask before having to pay gas fees for the transaction and have the error message come to me. When the wallet pops up, the following error is displayed in the console but I'm not able to catch it anywhere. Here's a screenshot of what's popping up in the browser console.

Would love some clarity on the same, thanks.

scipy optimization according to the experimental curve

Posted: 03 Mar 2022 05:14 AM PST

Good afternoon . My name is Artemy. tell me how to determine the unknown parameters in the calculated curve, using scipy optimization, having an experimental curve at the input. ''' import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit from math import pi

def func(a,b,c):  return -a/(2*np.tan(c*(pi/2)))+np.sqrt(b+(a**2)/(4*np.tan((c)*(pi/2))))      file=experimental curve in .txt file  pd_file=pd.read_csv(file, sep="\s+",header=None,names=['frequence', 'chi_strich_strich'],           skiprows=1)  xdata=pd_file['frequence']  ydata=pd_file['y']  popt, pcov = curve_fit(func, xdata, ydata, p0=[0.6,1], maxfev=500000000)  print('popt',popt)  

'''

Problem while creating DataProc Cluster: Component ranger failed to activate post-hdfs

Posted: 03 Mar 2022 05:14 AM PST

I am working in a Dataproc cluster setup to test all the features. I have created a cluster template and I've been using the creation command almost every day, but this week it stopped working. The error printed is:

ERROR: (gcloud.dataproc.clusters.create) Operation [projects/cluster_name/regions/us-central1/operations/number] failed: Failed to initialize node cluster_name-m: Component ranger failed to activate post-hdfs See output in: gs://cluster_bucket/google-cloud-dataproc-metainfo/number/cluster_name-m/dataproc-post-hdfs-startup-script_output.  

When I see the output that the message print, the error found is:

<13>Mar  3 12:22:59 google-dataproc-startup[15744]: <13>Mar  3 12:22:59 post-hdfs-activate-component-ranger[15786]: ERROR: Error CREATEing SolrCore 'ranger_audits': Unable to create core [ranger_audits] Caused by: Java heap space  <13>Mar  3 12:22:59 google-dataproc-startup[15744]: <13>Mar  3 12:22:59 post-hdfs-activate-component-ranger[15786]:  <13>Mar  3 12:22:59 google-dataproc-startup[15744]: <13>Mar  3 12:22:59 post-hdfs-activate-component-ranger[15786]: + exit_code=1  <13>Mar  3 12:22:59 google-dataproc-startup[15744]: <13>Mar  3 12:22:59 post-hdfs-activate-component-ranger[15786]: + [[ 1 -ne 0 ]]  <13>Mar  3 12:22:59 google-dataproc-startup[15744]: <13>Mar  3 12:22:59 post-hdfs-activate-component-ranger[15786]: + echo 1  <13>Mar  3 12:22:59 google-dataproc-startup[15744]: <13>Mar  3 12:22:59 post-hdfs-activate-component-ranger[15786]: + log_and_fail ranger 'Component ranger failed to activate post-hdfs'  

The creation command that I ran is:

gcloud dataproc clusters create cluster_name \    --bucket cluster_bucket \    --region us-central1 \    --subnet subnet_dataproc \    --zone us-central1-c \    --master-machine-type n1-standard-8 \    --master-boot-disk-size 500 \    --num-workers 2 \    --worker-machine-type n1-standard-8 \    --worker-boot-disk-size 1000 \    --image-version 2.0.29-debian10 \    --optional-components ZEPPELIN,RANGER,SOLR \    --autoscaling-policy=autoscale_rule \    --properties="dataproc:ranger.kms.key.uri=projects/gcp-project/locations/global/keyRings/kbs-dataproc-keyring/cryptoKeys/kbs-dataproc-key,dataproc:ranger.admin.password.uri=gs://cluster_bucket/kerberos-root-principal-password.encrypted,hive:hive.metastore.warehouse.dir=gs://cluster_bucket/user/hive/warehouse,dataproc:solr.gcs.path=gs://cluster_bucket/solr2,dataproc:ranger.cloud-sql.instance.connection.name=gcp-project:us-central1:ranger-metadata,dataproc:ranger.cloud-sql.root.password.uri=gs://cluster_bucket/ranger-root-mysql-password.encrypted" \    --kerberos-root-principal-password-uri=gs://cluster_bucket/kerberos-root-principal-password.encrypted \    --kerberos-kms-key=projects/gcp-project/locations/global/keyRings/kbs-dataproc-keyring/cryptoKeys/kbs-dataproc-key \    --project gcp-project \    --enable-component-gateway \    --initialization-actions gs://goog-dataproc-initialization-actions-us-central1/cloud-sql-proxy/cloud-sql-proxy.sh,gs://cluster_bucket/hue.sh,gs://goog-dataproc-initialization-actions-us-central1/livy/livy.sh,gs://goog-dataproc-initialization-actions-us-central1/sqoop/sqoop.sh \    --metadata livy-timeout-session='4h' \    --metadata "hive-metastore-instance=gcp-project:us-central1:hive-metastore" \    --metadata "kms-key-uri=projects/gcp-project/locations/global/keyRings/kbs-dataproc-keyring/cryptoKeys/kbs-dataproc-key" \    --metadata "db-admin-password-uri=gs://cluster_bucket/hive-root-mysql-password.encrypted" \    --metadata "db-hive-password-uri=gs://cluster_bucket/hive-mysql-password.encrypted" \    --scopes=default,sql-admin  

I know that it's something related to Ranger/Solr setup, but I don't know how to increase this heap size without creating an alternative initialization script or creating a custom machine image. If you have any idea of how to solve this or need more information about my setup please let me know.

how to create the expected array with given input?

Posted: 03 Mar 2022 05:14 AM PST

Input: {1,1,2,3,3,4}(array can be dynamic) expected output:{{1,1},{2},{3,3},{4}}

I created a 2d array and iterated the input using 'for' loop but got stuck after that.

Exception fixing docBase for context - Error thrown but Successfull deployment

Posted: 03 Mar 2022 05:13 AM PST

I have built a docker image based on tomcat base image and copying the MyExample.war file to tomcat/webapp folder in my custom dockerFile and built an image. It successfully deploys the war file and is able to run on my system with docker.

But when i deploy the same image in kubernetes server. It deploys the application successfully. And the pod becomes up. But i see an error in the log as below.

{"type":"log", "level":"ERROR", "time":"2022-03-03T12:18:38.081Z", "message":"Exception fixing docBase for context [/MyExample]"}  

This error is not seen when i run it in local docker on my system, where as only on kubernetes cluster when i deploy it i see this error. But Application is deployed successfully after the error and i'm able to access the services. Also the time taken for tomcat to initialize and deploy the application is more than 5 minutes. Where as in local docker it is in seconds. DOn't know if this error is causing this delay. Any help will be appreciated.

Bootstrap modal is not working properly in angular 9

Posted: 03 Mar 2022 05:13 AM PST

Hi I have lot of bootstrap modals in my project,Suddenly all of them having issues like fade screen is coming while opening any bootstrap modal .Please help meThis is fade screen coming while opening modal

Bot cannot grant itself MANAGE_ROLES without administrator?

Posted: 03 Mar 2022 05:13 AM PST

I have a bot that creates a channel and edits its permissions. This cannot be done without MANAGE_ROLES (manage permissions), but it cannot grant itself this permission without administrator. I can't see anything in the docs saying that this would be the case. However, removing this from the permission overwrites or leaving it in and giving it admin fixes the issue.

The bot has ALL permissions except admin, is at the ABSOLUTE top of the hierarchy, and I've narrowed it down to just being MANAGE_ROLES that sets off the permission error without admin.

How to add references in dot net project

Posted: 03 Mar 2022 05:13 AM PST

I have a simple project mentioned below. Can somebody tell me how can I reference my classLibrary1 in classLibrary2, I right-clicked and tried adding reference but that isn't working since I am not able to use the method of classLibrary2 in classLibrary1 (I am inheriting the class of classLibrary1 in classLibrary2 as well)

Why am I not able to see the References folder in classLibrary1 and classLibrary2?

Project screenShot

Is there an R function to multiply select columns by a constant?

Posted: 03 Mar 2022 05:13 AM PST

I am a newcomer to R. I am working with a dataframe called control with 406 columns. I would like to multiply the 6th until the 395th column with a constant value, 0.9616. Is there a function with which I could do this?

Thanks!

How to add two shop pages?

Posted: 03 Mar 2022 05:13 AM PST

How can we add two separate shop pages on one wordpress website?

Where both pages will display different set of products and will have different filters.

Unhandled Exception: MissingPluginException(No implemen tation found for method login on channel app.meedu/flutter_facebook_auth)

Posted: 03 Mar 2022 05:14 AM PST

I'm getting the following error when I'm tring to sign in with facebook on android device by my flutter app :

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method login on channel app.meedu/flutter_facebook_auth) E/flutter (29705): #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:175:7) E/flutter (29705): E/flutter (29705): #1 FacebookAuthPlatformImplementation.login (package:flutter_facebook_auth_platform_interface/src/facebook_auth_implementation.dart:34:22) E/flutter (29705):

Golang: Not able to fetch balance of Ethereum account in ganache

Posted: 03 Mar 2022 05:14 AM PST

I am running ganache inside docker like -

docker run -p 8545:8545 --name ganache -v $HOME/ganache/chaindata:/var/ganache/chaindata trufflesuite/ganache-cli --db /var/ganache/chaindata --accounts 5 --debug  

and it is running successfully (console output) -

Ganache CLI v6.12.2 (ganache-core: 2.13.2)  (node:1) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.  (Use `node --trace-deprecation ...` to show where the warning was created)    Available Accounts  ==================  (0) 0x34AbDD7a9b5aA00d548e3171d0a11Bb78CF56269 (100 ETH)  (1) 0x0B2cb7f1F1027b0D48C3ba2845FDA555fe221212 (100 ETH)  (2) 0x302321AdBe2896457AC23dc812EA3aDc18f75Ba5 (100 ETH)  (3) 0xAcF0cf4c1aD00F86A21b741ebF2aA09Ec40d8Fe0 (100 ETH)  (4) 0xCa3FD3b3cFF3257287975139C98f4B9251C6B115 (100 ETH)    Private Keys  ==================  (0) 0xa43d5fb2220e02d0ac380cfb34471c4b2e7985aea5570cfc684c9615f542c6ec  (1) 0x76185217e854d1fa8dc745d7b0cdf94a847eca3a32099f8778bd88c81c033df6  (2) 0x8a59f0dd31294191ac1af3713dcf1a9c70d889cfbd507b692737513bc28cb09b  (3) 0x98bac50cda613433beaa8de64035fe26ab04164d1a1ecc4416dec0df87596d6c  (4) 0xd2f6b771fa6e8115cbfaa5a89733f805b37e69d30f59df9f2dab1c4c9d0e6066    HD Wallet  ==================  Mnemonic:      afraid midnight march route census blanket mule senior almost collect gas math  Base HD Path:  m/44'/60'/0'/0/{account_index}    Gas Price  ==================  20000000000    Gas Limit  ==================  6721975    Call Gas Limit  ==================  9007199254740991    Listening on 0.0.0.0:8545  

and using go-ethereum client to connect to ganache like -

package main    import (      "context"      "fmt"      "github.com/ethereum/go-ethereum/common"      "github.com/ethereum/go-ethereum/ethclient"  )    func panicOnError(err error) {      if err != nil {          panic(err)      }  }    func main() {      conn, err := ethclient.Dial("http://127.0.0.1:8545")      panicOnError(err)      balance, err := conn.BalanceAt(context.Background(), common.HexToAddress("0x34AbDD7a9b5aA00d548e3171d0a11Bb78CF56269"), nil)      panicOnError(err)      fmt.Println(balance)  }  

Upon running above code, it is connecting and calling eth_getBalance (checked ganache logs) successfully but output of this code is always 0 ie. somehow it is not able to get the balance.

However if I run ganache using its app image, my code is working correctly.

Need help in identifying and fixing issues when running ganache inside docker.

Thanks

Morra - Odds and Even

Posted: 03 Mar 2022 05:13 AM PST

Im writing a code that evolves the computer and I entering numbers and added them together to see who wins. There are three problems:

  • Problem 1: When I try to recall the 'main()' function the 'game()' wont appear.

  • Problem 2: I can't seem to run the code forever until user decides to stop.

  • Problem 3: The point system isn't accurate enough.

Any help would be grateful.

Here's the code:

#include <stdio.h>  #include <stdlib.h>  #include <time.h>        int human_fingers;      int comp_fingers;      int menu_choice;      int answer;      int count = 1;      int point1 = 0, point2 = 0;      int total;         void intro() {      printf("Welcome to Morra - Odds and Even!\n\n");      printf("The rules of the game are pretty simple\n");      printf("You and the computer will pick a side each round\n");      printf("You must enter a number and the total sum will determine the winner!\n\n");  }    void example() {      printf("You picked even, by default the computer will be odd this round\n");      printf("You entered 3 and the computer entered 5\n");      printf("3 + 5 = 8, so you win because you choose even!\n");  }    void game() {      while(count < 7)           {          count = count + 1;               printf("Enter a number to choose a side:\n");      printf("Even [1] / Odd [2]\n");           scanf("%d", &menu_choice);           while((menu_choice<1) || (menu_choice>2)){      printf("Invalid entry, please Enter 1-2: ");      scanf("%d",&menu_choice);}                if(menu_choice == 1)      {          printf("The computer will be odd this turn\n");          printf("\nPlease enter an number (1-10)\n");          scanf("%d", &human_fingers);                   while((human_fingers<1) || (human_fingers>10)){          printf("Invalid entry, please enter 1-10:");          scanf("%d",&human_fingers);}                     printf("Computer is choosing a number....\n");                   srand(time(NULL));          comp_fingers = rand() % 10 + 1;                            printf("You: %d\n", human_fingers);          printf("Computer: %d\n", comp_fingers);                   int result;                   result = human_fingers + comp_fingers;          printf("Total is %d\n", result);                   total = result % 2;                   if(total == 0)          {          printf("This turn goes to You!\n\n");          printf("You: %d\n", point1 + 1);          printf("Computer: %d\n\n", point2 + 0 );          point1++;          }          else          {          printf("This turn goes to Computer!\n\n");          printf("You: %d\n", point1 + 0 );          printf("Computer: %d\n\n", point2 + 1);          point2++;          }                                     }           if(menu_choice == 2)      {          printf("The computer will be even this turn\n");          printf("\nPlease enter an number (1-10)\n");          scanf("%d", &human_fingers);                 while((human_fingers<1) || (human_fingers>10)){          printf("Invalid entry, please enter 1-10:");          scanf("%d",&human_fingers);}                   printf("Computer is choosing a number...\n");                   srand(time(NULL));          comp_fingers = rand() % 10 + 1;                            printf("You: %d\n", human_fingers);          printf("Computer: %d\n", comp_fingers);                   int result;                   result = human_fingers + comp_fingers;          printf("Total is %d\n", result);                   total = result % 1;                   if(total == 0)          {          printf("This turn goes to Computer!\n\n");          printf("You: %d\n", point1 + 0);          printf("Computer: %d\n\n", point2 + 1);          point1++;          }          else          {          printf("This turn goes to You!\n\n");          printf("You: %d\n", point1 + 1);          printf("Computer: %d\n\n", point2 + 0 );          point2++;          }                          }                }        if(point1 > point2)      printf("You won, you beat the computer!\n");      else      printf("Unlucky the computer won!\n");  }      void end(){      printf("Game has ended!\n");              }            int main()  {                intro();           printf("Would you like an example to demostrate?\n");      printf("Yes [1] / No [2]\n");      scanf("%d", &answer);           if( answer == 1 )      {   example();          printf("\n\n");           game();      }      else      {   printf("\n\n");          game();               }                     end();            printf("Would you like play another game?\n");      printf("Yes [1] / No [2]\n");      scanf("%d", &answer);      if( answer == 1)      {          main();      }      else {      printf("Thanks for playing MORRA - ODDS AND EVEN.");      }                          return 0;  }  

How to add shadow to fixed column and fixed row using the UICollectionViewLayout for presenting the tabular data in Swift?

Posted: 03 Mar 2022 05:14 AM PST

I want shadow to be there on first fixed column and first fixed row only and when I do scrolling horizontally and vertically.

Problem using lambda expression to be integrated using quad from mpmath

Posted: 03 Mar 2022 05:14 AM PST

I am trying to integrate an oscillatory expression with mpmath quad. The integral only has one variable but I need to evaluate it in a 2D space. I need the resulting function from the integral along kx to be evaluated for a group of coordinated in x and y that defined a plane. That's why I evaluate integral (x,y) as a test in a single point of that 2D array.

This is the code I am using:

import numpy as np  from numpy.lib.scimath import sqrt  from mpmath import *  import matplotlib.pyplot as plt  mp.dps = 15    f = 8500  rho = 1.225   c0 = 343   Omega = 2*np.pi*f    k = Omega/c0   Z = -426       integrandReal = lambda kx, x, y: np.real(((2*sqrt(k**2 - kx**2)*Z)/(sqrt(k**2 - kx**2)*Z + Omega*rho))*((np.exp(1j*(kx*x + sqrt(k**2 - kx**2)*y)))/(sqrt(k**2 - kx**2))))  integrandImag = lambda kx, x, y: np.imag(((2*sqrt(k**2 - kx**2)*Z)/(sqrt(k**2 - kx**2)*Z + Omega*rho))*((np.exp(1j*(kx*x + sqrt(k**2 - kx**2)*y)))/(sqrt(k**2 - kx**2))))    integral = lambda x, y: quad(integrandReal, [-100*k, 100*k], maxdegree=10)[0]  + 1j*quad(integrandImag, [-100*k, 100*k], maxdegree=10)[0]  G = integral(0.1,0.1)  

I am getting the following errors when I try to evaluate the integral in an arbitrary point:

Traceback (most recent call last):      File "<ipython-input-87-901e6e5dc630>", line 1, in <module>      integral(1,1)      File "/d/dfg/Documents/ImpedanceModel/GreenImpedance.py", line 55, in <lambda>      integral = lambda x, y: quad(integrandReal, [-100*k, 100*k], maxdegree=10)[0]  + 1j*quad(integrandImag, [-100*k, 100*k], maxdegree=10)[0]      File "/opt/tools/anaconda/2020.11/lib/python3.8/site-packages/mpmath/calculus/quadrature.py", line 742, in quad      v, err = rule.summation(f, points[0], prec, epsilon, m, verbose)      File "/opt/tools/anaconda/2020.11/lib/python3.8/site-packages/mpmath/calculus/quadrature.py", line 232, in summation      results.append(self.sum_next(f, nodes, degree, prec, results, verbose))      File "/opt/tools/anaconda/2020.11/lib/python3.8/site-packages/mpmath/calculus/quadrature.py", line 304, in sum_next      S += self.ctx.fdot((w,f(x)) for (x,w) in nodes)      File "/opt/tools/anaconda/2020.11/lib/python3.8/site-packages/mpmath/ctx_mp_python.py", line 944, in fdot      for a, b in A:      File "/opt/tools/anaconda/2020.11/lib/python3.8/site-packages/mpmath/calculus/quadrature.py", line 304, in <genexpr>      S += self.ctx.fdot((w,f(x)) for (x,w) in nodes)    TypeError: <lambda>() missing 2 required positional arguments: 'x' and 'y'  

I thought the error was because I wasn't defining the arguments in the integration as it has to be done with scipy.integrate.quad (as you can see in one of my last posts) but with mpmath I don't know what is generating this error.

Thanks in advance for any help!

Missing AWS Lambda trace data for X-Ray. Ensure Active Tracing is enabled and no subsegments are created outside the function handler

Posted: 03 Mar 2022 05:13 AM PST

I have a lambda function which has written in NodeTS.I enabled the active tracing I can see the xray trace every time I called the function. This Lambda function also publishes to an SNS. I want to invoke the function locally, I follow this serverless-local-invoke and choose the --path options. For this I used this command: yarn serverless invoke local --function new-order-from-sns --stage test --path 'root/src/functions/picking.json', It invoked successfully but in try catch block it throws me the error:

Missing AWS Lambda trace data for X-Ray. Ensure Active Tracing is enabled and no subsegments are created outside the function handler.","stackTrace":"Error: Missing AWS Lambda trace data for X-Ray. Ensure Active Tracing is enabled and no subsegments are created outside the function handler.\n at Object.contextMissingRuntimeError [as contextMissing]

I am not sure how to silent my error.

This is my lambda function

import middy from '@middy/core'  import { SNSEvent } from 'aws-lambda'  import * as AWSXRay from 'aws-xray-sdk'  import { groupBy, prop } from 'ramda'    import { MASKED_LOG_FIELD_NAMES } from '@/backend/products/src/constants/constants'  import { middySnsErrorHandler } from '@/backend/shared/middleware/middy-sns-error-handler'  import { middyCorrelationIds } from '@/backend/shared/middleware/wrapper/middy-correlation-ids'  import { Log, middyLogMask } from '@/shared/logging/shared-logger'    import { middyXRayEgressHttp } from '../../../shared/middleware/middy-x-ray-egress-http'  import { initializeOrderState } from '../data-sources/initialize-order-state'  import { IS_OFFLINE } from '../settings/settings'  import { Order } from '../types/order'  import { isPriceDeviationOverThreshold } from '../utils/orders-utils'    if (IS_OFFLINE) {    AWSXRay.setLogger(Logger('silent'))  }    // handler to process incoming orders and order changes from picking perspective  const checkForPriceDeviationsOnCapture = (orders: Order[]): void => {    try {      orders.forEach((order) => {        if (isPriceDeviationOverThreshold(order))          Log.warn('Order price estimate to captured sum deviation', { order })      })    } catch (error) {      Log.warn('Order price estimate to captured sum error', {}, error)    }  }    const initializeOrders = async (orders: Order[]): Promise<void> => {    Log.info('Initializing order state on order change', { orders })      try {      const ordersByStore = groupBy(prop('storeId'), orders)        console.log({ ordersByStore })        await Promise.all(Object.keys(ordersByStore).map((k) => initializeOrderState(ordersByStore[k])))    } catch (error) {      Log.error('Failed Initializing order state', error)    }  }    const parseOrdersFromSns = (event: SNSEvent): Order[] => {    try {      return event.Records.flatMap((r) => (JSON.parse(r.Sns.Message) as unknown) as Order[])    } catch (error) {      Log.error('New order from SNS failed at parsing orders', { event }, error)      return []    }  }    const handlerFn = async (event: SNSEvent): Promise<void> => {    const orders = parseOrdersFromSns(event)      console.log({ orders })      if (orders.length === 0) return    checkForPriceDeviationsOnCapture(orders)    await initializeOrders(orders)  }    export const handler = middy(handlerFn)    .use(middyLogMask({ maskedLogFieldNames: MASKED_LOG_FIELD_NAMES }))    .use(middyCorrelationIds())    .use(middyXRayEgressHttp())    .use(middySnsErrorHandler())

This is my middyXRayEgressHttp

import middy from '@middy/core'  import * as AWSXRay from 'aws-xray-sdk'  import http from 'http'  import https from 'https'    const middyXRayEgressHttp: middy.Middleware<never> = () => ({    before: async (): Promise<void> => {      if (process.env.IS_OFFLINE) return      AWSXRay.captureHTTPsGlobal(http, false)      AWSXRay.captureHTTPsGlobal(https, false)      AWSXRay.capturePromise()    },  })    export { middyXRayEgressHttp }

JFrame is frozen by using a JComboBox

Posted: 03 Mar 2022 05:13 AM PST

I am trying to remove a component from a Frame once a JComboBox is selected. But when I select one of the boxes the whole Frame freezes and you can't do anything other then resize or move it.

        JFrame frame = new JFrame();          frame.setSize(800 , 800);          frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);          frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane() , BoxLayout.Y_AXIS));          Gui gui = new Gui();            JComboBox<ParabolaType> comboBox = new JComboBox<>(ParabolaType.values());          comboBox.addActionListener(e -> {              System.out.println("started");                frame.remove(frame.getComponents().length - 1);              frame.revalidate();                System.out.println("finished");          });            frame.add(gui);          frame.add(comboBox);  
started  finished  

It seems the EventQueue thread doesn't get stopped at all. Why is this happening?

How to load active class for link in react

Posted: 03 Mar 2022 05:13 AM PST

Created one simple tab for loading components, tabs are working fine but a "active" class loading for all Navlinks, on rendering. "active" class should load only for active tab. please help to fix this

import React, { useState } from 'react';  import { NavLink, Outlet } from "react-router-dom";      function SidenavSection(props) {  const [active, setActive] = useState("tab1")        return (          <div>                        <div >              <div sm="3" className='border sideNav'>              <NavLink to="" className="btn btn-link"    onClick={() => setActive("tab1")}>Overview</NavLink> <br/>              <NavLink to="" className="btn btn-link"  onClick={() => setActive("tab2")}>Align & Ratio</NavLink> <br/>              <NavLink to="" className="btn btn-link"    onClick={() => setActive("tab3")}>Avatar</NavLink> <br/>                           </div>                  <div sm="9" className='border'>                                         <div>                      {active === "tab1" && <div>section component 1</div>}                      {active === "tab2" && <div>section component 2</div>}                      {active === "tab3" && <div>section component 3</div>}                               </div>                  </div>              </div>           </div>      );  }    export default SidenavSection;  

screenshot output

enter image description here

How can I write rust's log::Record into Rust's ::csv::Writer in a single pass?

Posted: 03 Mar 2022 05:14 AM PST

The log function defined in Rust's Log trait accepts a Record parameter. As far as I can tell, in order to obtain the payload as a string, I need to do something like:

let mut s = String::new();  write!(s, "{}", record.args());  

The next step is to use Rust's ::csv::Writer:

let mut writer = ::csv::Writer::from_path("/path/to/csv");  writer.write_field(s);  // optionally write more fields  

What would be the simplest way to do that in a single pass?

How to get a list of months from created_at column (List of months having data in database)

Posted: 03 Mar 2022 05:14 AM PST

Suppose i have the column below:

02-03-2021  02-04-2021  02-04-2021  02-06-2021  02-08-2021  02-11-2021  

What i need is an array of the months sth like : [03,04,06,08,11]

Any thought of a good practice? Thanks in advance

Find records only all value are same in column otherwise return 0

Posted: 03 Mar 2022 05:14 AM PST

I have the following table

id name
1 Gaurav
1 Ram
1 Gaurav
1 Gaurav

From the above table I want to fetch records if name have same value as Gaurav. For example one row has name Ram so it should not return any thing. If all value is Gaurav then return id.

sys:1: ResourceWarning: unclosed socket <zmq.Socket(zmq.PUSH) at 0x7f8a5c016d60>

Posted: 03 Mar 2022 05:13 AM PST

I am running spyder in WSL on Ubuntu 18.04 LTS with XLaunch. When I run my code (no blank file, or anything), I get the following message in the console: runfile('/home/picky/Research/trans_CGM_Multiprobes.py', wdir='/home/picky/Research') 02-Mar-22 22:18:21: sys:1: ResourceWarning: unclosed socket <zmq.Socket(zmq.PUSH) at 0x7f8a492549a0>

What does this mean, and how can I fix it?

I running Python Version 3.9.7 [GCC 7.5.0], Spyder 5.1.5, Ubuntu 18.04 LTS on WSL, Qt 5.9.7, PyQT5 5.9.2

Code (irrelevant, since everytime I f5 to run file, this happens):

# -*- coding: utf-8 -*-  """  Author: Patrick  March 3rd 2022  """    import numpy as np  

which returns

In[32]:  """  Author: Patrick  March 3rd 2022  """    import numpy as np  02-Mar-22 22:35:41: sys:1: ResourceWarning: unclosed socket <zmq.Socket(zmq.PUSH) at 0x7f8a49238f40>  

How to extract kubernetes pod command execution result attributes

Posted: 03 Mar 2022 05:14 AM PST

I am connecting to pod via client-Go and I want to get the properties of the file directory

func GetPodFiles(c *gin.Context)  {      client, _ := Init.ClusterID(c)      path := c.DefaultQuery("path", "/")      cmd := []string{          "sh",          "-c",          fmt.Sprintf("ls -l %s", path),      }      config, _ := Init.ClusterCfg(c)      req := client.CoreV1().RESTClient().Post().          Resource("pods").          Name("nacos-0").          Namespace("default").SubResource("exec").Param("container", "nacos")      req.VersionedParams(          &v1.PodExecOptions{              Command: cmd,              Stdin:   false,              Stdout:  true,              Stderr:  true,              TTY:     false,          },          scheme.ParameterCodec,      )        var stdout, stderr bytes.Buffer      exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())      if err != nil {          response.FailWithMessage(response.InternalServerError, err.Error(), c)          return      }      err = exec.Stream(remotecommand.StreamOptions{          Stdin:  nil,          Stdout: &stdout,          Stderr: &stderr,      })      if err != nil {          response.FailWithMessage(response.InternalServerError, "Error obtaining file", c)          return      }        fmt.Println(stdout.String())  }  

Execution Result Output

total 0  lrwxrwxrwx   1 root root   7 Jun  1  2018 bin -> usr/bin  drwxr-xr-x   5 root root 360 Feb 16 16:39 dev  lrwxrwxrwx   1 root root   8 Jun  1  2018 sbin -> usr/sbin  drwxr-xr-x   2 root root   6 Apr 11  2018 srv  

Expect the result

"data": [          {              "perm": "drwxr-xr-x",              "mod_time": "2022-03-02 15:02:15",              "kind": "d",              "name": "temp",              "size": ""          },  ]  

Is there a good way or a golang third-party library to handle it. Please let me know. Thank you

Omit region from S3 pre-signed URL in aws-sdk-go-v2

Posted: 03 Mar 2022 05:13 AM PST

Recently I migrated a code base from aws-sdk-go v1 to v2. But I noticed a difference that it seems isn't described on the migration guide, the pre-signed URL generated between v1 and v2 has changed:

  • v1: https://s3.amazonaws.com/<bucket>/<path>
  • v2: https://s3.<region>.amazonaws.com/<bucket>/<path>

After some research, I found another Slack thread mentioning that v2 now uses sig4 which includes the region into the URL (here).

My problem is that I need to use the old hostname version without the region because of a legacy code that depends on s3.amazonaws.com hostname matching. So, I was hoping if there is any way to omit the region addition into the pre-signed URL in aws-sdk-go-v2.

Here is the code I am using to generate the S3 pre-signed URL:

input := &s3.GetObjectInput{      Bucket: aws.String(bucket),      Key:    aws.String(key),  }    psClient := s3.NewPresignClient(c.s3Client, s3.WithPresignExpires(expires))    res, _ := psClient.PresignGetObject(ctx, input)    res.URL    

How to get the client id which is trying to bind my service in Android

Posted: 03 Mar 2022 05:13 AM PST

I have read thread in the below link. But this is too old and many said in various possiblities. How to get application package name or UID which is trying to bind my service from onBind function?

I have altered the question according to my need. I have a bound service in an application and two clients will bind to my service using bindservice. when applications are tried to bind this service I want to know which application is trying to bind my service in onBind function?

Is there any better possible ways in latest Android version to get the application name or UID which is trying to bind my service in onBind function?

Coin Class HW assignment

Posted: 03 Mar 2022 05:14 AM PST

So I am doing a Coin Flip Class program for class, and this code straight from the book is giving me errors in Pycharm and VSC. I have reread this 10 times and can not find the error to get the program to run. Trying to figure out if I am missing something, or the example source code is off.

  import random      # The Coin Class simulates a coin that can be flipped    class coin:      def __init__(self):          side.up = 'Heads'        # Side up data attribute w/ heads        # The Toss generates a random number in      # the range of 0 - 1. If the number is 0, then side up is heads, otherwise side up is tails        def toss(self):            if random.randint(0, 1) == 0:              self.sideup = 'Heads'          else:              self.sideup = 'Tails'        # The get_sideup method returns the value referenced by sideup        def get_sideup(self):          return self.sideup        # The main function      def main():      # create an object from the coin class      my_coin = coin()        # Display that side facing up      print('This side is up:', my_coin.get_sideup())        # Toss Coin      print('I am tossing the coin . . .')      my_coin.toss()        # Display the side of the coin that is facing up      print('This side is up:', my_coin.get_sideup())        # Call the main function  main()  ``  

What is the limit of character to use in alt=“text” of img tag in html [duplicate]

Posted: 03 Mar 2022 05:13 AM PST

Please tell me if there is any any specific number of characters that can be entered in an alt attribute of the HTML img tag.

Is there a limit that should be kept in mind, for example, based on what screen readers support?

No comments:

Post a Comment