Sunday, August 1, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


What's the best way to send kubernetes audit logs to aws dynamodb table?

Posted: 01 Aug 2021 08:24 AM PDT

I understand the webhook backend described here:https://kubernetes.io/docs/tasks/debug-application-cluster/audit/ but since the logs are already being streamed to EFK, I needed some hook in there which can send a filtered set of logs to dynamodb table, I think that will be non-intrusive and avoid any performance imapacts. And I want this as real-time as possible.

Why I can't embed my website into another my website in iframe?

Posted: 01 Aug 2021 08:24 AM PDT

I have two websites. The problem is when I tried to embed my website one this website into my website two this website by iframe I got this (support.google.com refused to connect.) error imagemessage. I have tried so much to find out a solution but got nothing.

<iframe src="http://aman.freecluster.eu/" title="my portfolio" height="500px" width="100%"></iframe>  

How can I plot points on a specific area of the circle using forceRadial in d3js?

Posted: 01 Aug 2021 08:23 AM PDT

I want to reorder the plotted points in this chart programmatically: https://observablehq.com/d/3767f25ea9d12b81

Such as that the:

  • blue points are in the upper left quarter of the circle
  • green points are in the upper right quarter of the circle
  • red points are in the bottom right quarter of the circle
  • blue points are in the bottom left quarter of the circle

The radius of each points is set correctly, I am using this code to achieve this:

var simulation = d3      .forceSimulation(techData)      //.force("charge", d3.forceManyBody().strength(5))      //.force("center", d3.forceCenter(0, 0))      .force(        "r",        d3.forceRadial(function (d) {          if (d.ring === "Adopt") {            return d3.randomUniform(20, 90)();          } else if (d.ring === "Trial") {            return d3.randomUniform(120, 170)();          } else if (d.ring === "Assess") {            return d3.randomUniform(190, 240)();          } else if (d.ring === "Hold") {            return d3.randomUniform(270, 290)();          }        })      )      .force("collision", d3.forceCollide().radius(10).iterations(2))      .on("tick", ticked);  

I couldn't find any possibility to filter or limit the distribution of points to a specific radial area. I am grateful for any idea or suggestion that helps me to solve this.

Code blocks keyboard shorcut conflits found.After clicking ok the software is not opening

Posted: 01 Aug 2021 08:23 AM PDT

Keyboard shortcut conflicts found. Use Settings/Editor/Keyboard Shortcuts to resolve conflicts. Conflicting menu items:'Edit/Previous call tip'&'File/Print...' Both using shortcut:'Ctrl-P'(IDs[658][-31840])

Not able to authenticate a service account with Google API PHP Client

Posted: 01 Aug 2021 08:23 AM PDT

I am new to this so I took cue from various official documentations to create a service account etc and use PHP client for Google API to make HTTP requests by using the credentials JSON for that service account.

But I am not sure what's going wrong, it just doesn't work ( for context I am trying to use the Indexing API - https://developers.google.com/search/apis/indexing-api/v3/prereqs#php )

require_once ABSPATH . '/googlelibraries/google-api-php-client/vendor/autoload.php';    $client = new Google_Client();  $serviceKeyFile = __DIR__ . '/daxxxxx-b1xxxxxxc8.json';  $client->setAuthConfig( $serviceKeyFile );  $client->useApplicationDefaultCredentials();    $client->setSubject( 'ixxxxxxxxn@gmail.com' );  $client->addScope('https://www.googleapis.com/auth/indexing');  $client->setAccessType('offline');  // $client->createApplicationDefaultCredentials();  // $client->setClientId( '10xxxxxxxxxxx' );  $endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';  

This is what I have, almost the same as the one on the example documentation, however, when I call $client->authorize() to get a Guzzle client authenticated to make request I see nothing, everything just becomes blank, no error, I was able to debug it later and the error goes like -

Fatal error: Uncaught Exception: Magic request methods require a URI and optional options array  in /var/www/html/googlelibraries/google-api-php-client/vendor/guzzlehttp/guzzle/src/Client.php on line 84  

I do not care if it authenticates or not, the problem right now is that authorize method itself it throwing an error and I don't know exactly what it is, there's no detailed guide on it that I would find. Any ideas?

Setting state inside React functional setState()

Posted: 01 Aug 2021 08:22 AM PDT

Is one allowed to call a setState inside the function passed into setState. for instance im trying to check for errors in user input and im calling the error checker function inside the setInpuForm, I know I can call the checkerror() from outside the setInputForm i.e inside the change handler, but out of curiosity, i decided to try it this way. But I discovered after typing the first character into the input field no changed but from the second entry up,its displayed. Also noticed inside the checkError i always get the previous value. What could be the reason for this

const errorChecker = (inputValue, element)=>{      //check for password error      if (element==='password') {      if (inputValue.length<=6) {          console.log('function error checker called')          setInputForm((form)=>{              console.log('after error check')              console.log(form.password.value)              return {                  ...form,                  [element]: {                      ...form[element],                      error: 'Password can not be less than 6'                  }              }          })      }   else {          setInputForm((form) => {              return {                  ...form,                  [element]: {                      ...form[element],                      error: ''                  }              }            })      }  }}    <Input key={inputForm[it].label} changed={(event)=>{                      const val = event.target.value                       setInputForm((form)=>{                          console.log(form.password.value)                          console.log('before error check')                          errorChecker(val, it)                           console.log('from set valuie')                          return {                              ...form,                              [it]: {                                  ...form[it],                                  value: val                              }                          }                       })                                            }}  

Can't deploy Cloud Functions because of "Unhandled error cleaning up build images"

Posted: 01 Aug 2021 08:22 AM PDT

I've deployed hundreds of function and this is the first time I encounter this issue. Simply, it stops deploying function process, saying:

Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at https://console.cloud.google.com/gcr/images/[project-name]/us/gcf

Question is what are those images I have to delete? Why? How can I solve it?

Azure DevOps YAML pipeline matrix strategy - [error]Unable to locate executable file: 'bash'

Posted: 01 Aug 2021 08:22 AM PDT

I have a pipeline where I want to build and push several docker images to ECR. Everything works fine if I use a task for each service without using a matrix, but I want to reduce the build time by parallel creating the tasks using a matrix with the variables each service needs:

name: Build Docker images and push to Registry    trigger:    tags:      include:      - '*'    pool:    vmImage: ubuntu-latest    variables:  - group: AWS  - name: DOCKER_REPOSITORY_URL    value: $(AWS_ACCOUNT_ID).dkr.ecr.$(AWS_REGION).amazonaws.com  strategy:    maxParallel: 8    matrix:      a-server:        service: a-server        path: somepath      b-server:        service: b-server        path: somepath      c-server:        service: c-server        path: somepath      d-server:        service: d-server        path: somepath      e-server:        service: e-server        path: somepath      f-server:        service: f-server        path: somepath      g-server:        service: g-server        path: somepath      h-server:        service: h-server        path: somepath    steps:    - script: |      aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com    env:      AWS_ACCESS_KEY_ID: $(AWS_ACCESS_KEY_ID)      AWS_SECRET_ACCESS_KEY: $(AWS_SECRET_ACCESS_KEY)      AWS_ACCOUNT_ID: $(AWS_ACCOUNT_ID)      AWS_REGION: $(AWS_REGION)    displayName: 'Login to AWS'    - task: PowerShell@2    displayName: Set last tag to variable    inputs:      targetType: 'inline'      script: |        $VERSION_TAG = git describe --tags (git rev-list --tags --max-count=1)        Write-Host("##vso[task.setvariable variable=VERSION_TAG]$VERSION_TAG")        Write-Host("##vso[build.addbuildtag]$VERSION_TAG")        Write-Host($VERSION_TAG)    - task: Docker@2    displayName: Build and Push    inputs:      command: buildAndPush      Dockerfile: $(path)/Dockerfile      buildContext: $(Build.Repository.LocalPath)      repository: $(DOCKER_REPOSITORY_URL)/organization/$(service)      tags: |        $(VERSION_TAG)  

Error:

Generating script.  Script contents:  aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com  ========================== Starting Command Output ===========================  ##[error]Unable to locate executable file: 'bash'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.    

I already went through several other posts with similar issues, but solutions, unfortunately, did not help and were not matrix-related.

Note: This error is not isolated to aws command, during my debug I also tried others, even sourcing the profile, but it fails with the same.

Symfony 5 - Translation from database

Posted: 01 Aug 2021 08:21 AM PDT

On my Symfony 5 website I use translations via yaml-files. Now I need to add imprint, GTC and privacy policy to the site. I thought it would be best to store these informations in the database for every language, but I can't figure out how to do it the Symfony way. I googled and I only found tutorials for Symfony 4 and tbh I have a hard time to understand the explanation in the Symfony docs. Maybe it's the language barrier, but I just draw blank reading it.

Could someone help me out and give me an example on how to do it or maybe a link to a tutorial for Symfony 5?

Or shall I check if the route called was e. g. impressum or imprint and render a twig file for the respective language?

Route to service when Authorization header OR session exists

Posted: 01 Aug 2021 08:21 AM PDT

I want to build a simple gateway, that checks Authorization header and validates the token in the Authorization Server (keycloak), or if it is missing - go to /login and set/use the session (then exchange it to token). Then it should redirect to resource service with Authorization header.
I use spring-cloud-starter-gateway and spring-boot-starter-oauth2-client. Solution is to write custom web filters for both validations, but maybe there is a possibility to not write custom GatewayFilters?

For now my application.yml:

spring:    cloud:      gateway:        default-filters:          - TokenRelay        routes:          - id: message-service            uri: http://127.0.0.1:8010            predicates:              - Path=/ping/**    security:      oauth2: (....)  

My security config:

@Configuration  @EnableWebFluxSecurity  class SecurityConfig {      @Bean      fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {          return http.authorizeExchange { exchanges: AuthorizeExchangeSpec -> exchanges.anyExchange().authenticated() }              .oauth2Login(Customizer.withDefaults())              .csrf().disable()              .build()      }  }  

Now the session works fine, but when I send a request with only the Authorization header, the InMemoryWebSessionStore rejects the match.

remove duplicate files in hdfs when using apache nifi

Posted: 01 Aug 2021 08:22 AM PDT

i want to import table from datawarehouse with databasequerytable processor in hdfs with puthdfs processor,but the problem when i check the directory in hdfs i find a lot of files with the same table example : datawarehouse:table 1 --> hdfs:file 1 --->table1,file 2--->table1 ... . so i want to remove the duplicated files ,my replicate factor is 2 (2 data node) so i should find just two files with the same table .but i find +1000 files. [this is my flow][1]

How do I calculate the age from dob using the format of month day, yyyy in java? ex. (March 2, 1999)

Posted: 01 Aug 2021 08:22 AM PDT

The current code below uses the yyyy-mm-dd format. However the input should look like this (March 2, 1999). How do I calculate it or convert it?

public class CalculateAgeJava8 {         public static void main(String[] args) {          System.out.print("Please enter date of birth: ");          Scanner scanner = new Scanner(System.in);          String input = scanner.nextLine();          scanner.close();             LocalDate dob = LocalDate.parse(input);          System.out.println("Age is:" + getAge(dob));      }         public static int getAge(LocalDate dob) {          LocalDate curDate = LocalDate.now();          return Period.between(dob, curDate).getYears();      }     }  

How to use extension on vs code

Posted: 01 Aug 2021 08:23 AM PDT

I am new to using vs code. I added the extension called beautify. But when I save a javascript file, it doesn't beautify my work, it only stay the same. Thanks!

How can I find the reason my tkinter is dead?

Posted: 01 Aug 2021 08:22 AM PDT

I'm trying to make a screen recording program with some interface. the recording works nice when it's played independently, but as soon as I put into a function and use as a button command, tkinter gets dead. there is no error message, nothing but a dead window. how can I figure this out? the code is:

import pyautogui  import cv2  import numpy as np  import keyboard  import time  from tkinter import*  from tkinter import messagebox    def record_stop():       keyboard.press_and_release('q')    def screenrec(): #recording program      resolution = (1920,1080)      codec = cv2.VideoWriter_fourcc(*'XVID')      filename = '{}.avi'.format(time.strftime('_%Y%m%d_%H%M%S'))      fps = 60.0      out = cv2.VideoWriter(filename, codec, fps, resolution)      messagebox.showinfo('info', 'Recording start.')        while True:          img = pyautogui.screenshot()           frame = np.array(img)           frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)             out.write(frame)               if cv2.waitKey(1) == ord('q'):             messagebox.showinfo('info', 'Recording stopped.')             break            out.release()      cv2.destroyAllWindows()      root = Tk()  root.resizable(False, False)  root.title('Record program')    btnframe = LabelFrame(root, text='Record')  btnframe.pack(fill='x', padx=5, pady=5)    btn_start = Button(btnframe, text='Start recording', width=10, command=screenrec)  btn_start.pack(side='left', padx=5, pady=5)    btn_stop = Button(btnframe, text='Stop recording', width=10, command=record_stop)  btn_stop.pack(side='right', pady=5, padx=5)    root.mainloop()  

Relationship laravel : count data

Posted: 01 Aug 2021 08:21 AM PDT

Model Category:

    public function product()      {          return $this->hasMany(products::class);      }  

Model product:

    public function category()      {          return $this->belongsTo(Category::class);      }  

I handle in controller:

$result = Category::select(['id', 'name'])              ->with(['product:category_id, status'])              ->where('order', 1)              ->get();  

Result when I print out raw data :

[    'id' => 1,    'name' => 'Hot'    'product' => [       'status' => 1,       'category_id' => 1     ]  ]  [     'id' => 2,     'name' => 'New'     'product' => [        'status' => 2,        'category_id' => 2     ]  ]  ..........  

I got the list of category id and name, and got the product data array based on relationship. In my product table, There is a status column with values ​​equal to 1,2,3.

Now I want to count how many status = 1 and how many status = [2, 3] through the product array I get using that relationship?

Following code is not reaching the else statement

Posted: 01 Aug 2021 08:24 AM PDT

Disclaimer: I'm new to programming, this is a simple exercise I'm doing so go easy on me.

The following code is not reaching (printing) the else statement. Any insight is much appreciated.

$number = '1120011';        // Decimal check      if($number[0] == '+' && $number[1] == '0'){          echo "Error: Can't assign a plus sign on a leading zero!";      // Leading zero check          } elseif($number[0] == '+' || $number[0] == '-'){          echo "Number is decimal";      // Binary check          } elseif (preg_match('~^[01]+$~', $number)) {          echo "Number is binary";      // Code not executing here. For e.g. $number = 1120011          } else {          "Number is non binary";      }  

Another question:

Why is the following 'if' not working properly (if I replace it in the code above). I guess it has something to do with bad usage of operators.

if($number[0] == '+' || $number[0] == '-' && $number[1] == '0')  

Thanks in advance! :)

Remember LazyColumn Scroll Position - Jetpack Compose

Posted: 01 Aug 2021 08:23 AM PDT

I'm trying to save/remember LazyColumn scroll position when I navigate away from one composable screen to another. Even if I pass a rememberLazyListState to a LazyColumn the scroll position is not saved after I get back to my first composable screen. Can someone help me out?

@ExperimentalMaterialApi  @Composable  fun DisplayTasks(      tasks: List<Task>,      navigateToTaskScreen: (Int) -> Unit  ) {      val listState = rememberLazyListState()        LazyColumn(state = listState) {          itemsIndexed(              items = tasks,              key = { _, task ->                  task.id              }          ) { _, task ->              LazyColumnItem(                  toDoTask = task,                  navigateToTaskScreen = navigateToTaskScreen              )          }      }  }  

How to write a lambda fuction that counts unique count of clients with a condition on other column in a pandas agg function

Posted: 01 Aug 2021 08:22 AM PDT

I am trying to calculate measures from an initial dataframe with some conditions. df is my initial dataframe. Here are the measures I need in a new dataframe but I don't know how to keep grouping by columns:

df['uniq_order_client'] = df[df['dau_order'] == 1].groupby(['date_diff','platform','l2'])['user_client_id'].nunique()    df['uniq_ps_client'] = df[df['dau_ps'] == 1].groupby(['date_diff','attributes_platform','l2'])['user_client_id'].nunique()                    df['view'] = df.groupby(['date_diff','platform','l2'])['view'].sum()    df['click'] = df.groupby(['date_diff','platform','l2'])['click'].sum()  

I am trying to write it this way but have no idea how to count one column and pass condition to another column in an agg pandas' function

agg_mult_df= df.groupby(       ['date_diff','platform','l2']   ).agg(       uniq_order_client=('clint_id','nunique')# pass a lambda function that counts unique number of clients only if views =1,       uniq_ps_client=('clint_id','nunique') #pass a lambda function that counts unique number of clients only if click =1,       all_view= ('view',   'sum'),       all_click= ('click',   'sum'),   ).reset_index()  

Could anyone help me to figure out the lambda part (I figured that would be the only option), please?

How to disconnect user from FTP in Windows FILE Explorer

Posted: 01 Aug 2021 08:23 AM PDT

I have an FTP server that supports both authenticated and anonymous access. I don't seem to be able to get Microsoft File Explorer to "forget" an authenticated user. If I open a file explorer window and access the FTP server anonymously with something like "ftp://my-ip-address" I get the expected behavior (the anonymous user is configured for read only access and this is what I see). If I log in as an authenticated user with something like ftp://me@my-ip-address I am able to browse the server but I get prompted for credentials if I attempt a read/write operation (I am then able to read/write to the FTP server after entering the correct credentials).

However if I close the window, Open a new window, and then access the FTP server with something like ftp://me@my-ip-address I am still able to perform read/write operations and the server log indicates the action was performed by "me". This works even if the connection has timed out.

I have gone into regedit and deleted all of the keys under Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\FTP\Accounts and the read/write still occurs for the user without asking for credentials.

What can I do to disconnect the connection and ensure that the credentials have not been saved (i.e. the user "me" will be asked for credentials if a read/write operation is attempted)

Android studio 'The activity must be exported or contain an intent-filter'

Posted: 01 Aug 2021 08:23 AM PDT

I wanted to show 'RealMainActivity.kt' to first main page, so I wrote below.

  <activity android:name=".RealMainActivity">          <intent-filter>              <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />          </intent-filter>      </activity>  

but there is still Error running 'app': The activity must be exported or contain an intent-filter. Do I need more other route settings here?

Below is all the code about 'AndroidManifest.xml'

<?xml version="1.0" encoding="utf-8"?>  

<application      android:allowBackup="true"      android:icon="@mipmap/ic_launcher"      android:label="@string/app_name"      android:roundIcon="@mipmap/ic_launcher_round"      android:supportsRtl="true"      android:theme="@style/Theme.Swu_guru">        <activity android:name=".WriteBorrow"/>      <activity android:name=".BorrowList"/>      <activity android:name=".BorrowInfo"/>      <activity android:name=".RegisterActivity"/>      <activity android:name=".RealMainActivity">          <intent-filter>              <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />          </intent-filter>      </activity>        <activity android:name=".MainActivity"/>    </application>  

Customize merge commit message in Azure DevOps doesn't really work

Posted: 01 Aug 2021 08:22 AM PDT

When completing a pull request in Azure DevOps, I do this:

enter image description here

But when I click on "complete merge", I see this:

enter image description here

What Gives?

How to open URL in flutter app with url_launcher?

Posted: 01 Aug 2021 08:23 AM PDT

I use the package url_launcher to open url, here is the code:

  Future <void> _openURL(String url) async{      if(await canLaunch(url)) {        await launch(            url,          forceSafariVC: false,          forceWebView: true,        );      }      else{        throw 'Cant open URL';      }    }      ListTile(                          title: Text('Google'),                          onTap: () {                            _openURL('https://www.google.de/');                          }),  

But no matter what url i want to open, i get the error 'Cant open URL'

How to set mocked instance variable of class in python?

Posted: 01 Aug 2021 08:21 AM PDT

I'm writing a unit test for MyProducer class which produces the message on kafka topic. logic of testing is just mock the constructor of MyProducer class and set the manually created producer object to the instance of MyProducer class and then just verify if library methods of confluent-kafka are getting called correctly or not. I'm stuck in setting the manually created producer object to MyProducer. How can we set the manually created object to instance variable of MyClass by mocking init?

# kafka_producer.py # actual code    class MyProducer(object):      def __init__(self, config: Dict[str, Any]={}):          self.producer = Producer(config)      def produce(self, *args, **kwargs):          pass    # test_kafka.py # testing           def get_producer(*args, **kwargs):      print(args,kwargs)      conf = {          "bootstrap.servers": 'localhost:9093'      }      producer = Producer(conf)      def produce(*args, **kwargs):      pass      class KafkaTest(unittest.TestCase):        def setUp(self):          pass        @mock.patch(          "utils.kafka_producer.MyProducer.__init__",      )      @mock.patch(          "confluent_kafka.Producer.produce",      )        def test_kafka_producer(self, produce, kafka_producer):            produce.side_effect = produce            kafka_producer.side_effect = get_producer            kafkaProducer = MyProducer(              {'bootstrap.servers': os.environ['KAFKA_BOOTSTRAP_SERVERS']}          )            kafkaProducer.produce(fake_kafka_topic, value='test_data')  

It is giving error: AttributeError on 'MyProducer' has no attribute 'producer'.

Nested class: how to access outer class property?

Posted: 01 Aug 2021 08:23 AM PDT

I'm building a UDP communication class, and I'm trying to add incoming messages to a queue. The problem is that I'm unable to access the parent class' queue member. Following is the applicable code, and notice the last line, which doesn't work, but is showing what I'm trying to do. I'm trying to add the message to the parent class' queue.

import socketserver  import threading, queue    class RsaServer:      messages = None  # set to a queue class in __init__            def __init__(self, host="localhost", port=9999):          self.host = host          self.port = port          self.messages = queue.SimpleQueue()           self.main_thread = threading.Thread(target=self._server_thread())                    def _server_thread(self):          with socketserver.UDPServer((self.host, self.port), self.UDPHandler) as server:              server.serve_forever()        class UDPHandler(socketserver.BaseRequestHandler):          """Used to handle incoming communications to the server"""          def handle(self):              # print(self.request)              data = self.request[0].strip()              socket = self.request[1]              # from_addr = self.client_address[0]              try:                  message = data.decode()              except UnicodeDecodeError:                  # print("Rcvd bad data from: {}".format(from_addr))                  pass              else:                  # add msg to the gueue                  messages.put(message)  

Jenkins Multibranch-Pipeline JobDSL can't specify github url

Posted: 01 Aug 2021 08:22 AM PDT

I'm creating a Multibranch Pipeline job with JobDSL , and I want to specify my github url , but it's not working.

The job which I created it display "https://github.com/jackson/multibranch-Pipeline.git" ,

not https://mycompanygithub.com/jackson/multibranch-Pipeline.git

Any idea how theses other parameters can be added in ?

or other solution

multibranchPipelineJob('Jenkins/Multibranch-Pipeline/GitHub_Basic') {      branchSources {          branchSource {              source {                  github {                      repositoryUrl('https://mycompanygithub.com')                      credentialsId('mycredentialsid')                      repoOwner('jackson')                      repository('multibranch-Pipeline.git')                      configuredByUrl(true)                      }                  }              }          }      }    

Group and Sum multi-dimensional array after unwinding elements

Posted: 01 Aug 2021 08:21 AM PDT

I have a multidimensional array below is my JSON data, I want the output mentioned below. Thanks for the help. I have tried two methods, 1. project with map there I am unable to group the data. 2. tried with unwind and group there unable to get the inside errorField array ("recordCount" : 73).

My JSON:

     [     {        "_id":{           "$oid":"60f5c60fbc43cb00965ac641"        },        "groupBy":{           "$oid":"60f5c60fbc43cb00965ac641"        },        "employer":{           "$oid":"60d0e4001a6ccd764cb26df4"        },        "parameters":{           "begin":"2020-01-01",           "end":"2020-12-31"        },        "recordCount":74,        "errorFields":[           {              "field":"employeeStatus",              "recordCount":62,              "errorDetails":[                 {                    "recordIds":[                       "10000986",                       "10000990",                       "10001020"                    ],                    "detail":"Active employees should not have term date. Termed employees should have term date.",                    "recordCount":3                 },                 {                    "recordIds":[                       "10001032"                    ],                    "detail":"Stale pay period data (no new check for over 30 days from queried end date)",                    "recordCount":1                 }              ]           },           {              "field":"ytdGrossWages.ytdTotalGrossWages",              "recordCount":8,              "errorDetails":[                 {                    "recordIds":[                       "10001211",                       "10001269",                       "10001328",                       "10001395"                    ],                    "detail":"YTD total does not equal sum of YTD wage buckets",                    "recordCount":4                 }              ]           }        ],        "timestamp":{           "$date":"2021-07-19T18:35:59.031Z"        },        "__v":0     },     {        "_id":{           "$oid":"60f5c615bc43cb00965ac647"        },        "groupBy":{           "$oid":"60f5c60fbc43cb00965ac641"        },        "employer":{           "$oid":"60d0e4001a6ccd764cb26df4"        },        "parameters":{           "begin":"2020-01-01",           "end":"2020-12-31"        },        "recordCount":11,        "errorFields":[           {              "field":"employeeStatus",              "recordCount":11,              "errorDetails":[                 {                    "recordIds":[                       "10003644",                       "10003680"                    ],                    "detail":"Active employees should not have term date. Termed employees should have term date.",                    "recordCount":2                 },                 {                    "recordIds":[                       "10003667",                       "10003694",                       "10003807",                       "10003789"                    ],                    "detail":"Stale pay period data (no new check for over 30 days from queried end date)",                    "recordCount":4                 }              ]           },           {              "field":"ssn",              "recordCount":2,              "errorDetails":[                 {                    "recordIds":[                       "10003667"                    ],                    "detail":"The ssn field is required.",                    "recordCount":1                 },                 {                    "recordIds":[                       "10003694"                    ],                    "detail":"The ssn must be 9 digits.",                    "recordCount":1                 }              ]           },           {              "field":"employeeHomeAddressCountry",              "recordCount":1,              "errorDetails":[                 {                    "recordIds":[                       "10003694"                    ],                    "detail":"The employeeHomeAddressCountry field is required.",                    "recordCount":1                 }              ]           }        ],        "timestamp":{           "$date":"2021-07-19T18:36:05.135Z"        },        "__v":0     }  ]  

I want output like this:

{      "_id" : ObjectId("60f5c60fbc43cb00965ac641"),      "errorFields" : [              {                      "field" : "employeeStatus",                      "recordCount" : 73,                      "errorDetails" : [                              {                                      "recordIds" : [                                              "10001032",                                              "10003667",                                              "10003694",                                              "10003807",                                              "10003789"                                      ],                                      "detail" : "Stale pay period data (no new check for over 30 days from queried end date)",                                      "recordCount" : 5                              },                              {                                      "recordIds" : [                                              "10000986",                                              "10000990",                                              "10001020",                                              "10001031",                                              "10001035"                                      ],                                      "detail" : "Active employees should not have term date. Termed employees should have term date.",                                      "recordCount" : 5                              }                      ]              },              {                      "field" : "ytdGrossWages.ytdTotalGrossWages",                      "recordCount" : 8,                      "errorDetails" : [                              {                                      "recordIds" : [                                              "10001211",                                              "10001269",                                              "10001328",                                              "10001395"                                      ],                                      "detail" : "YTD total does not equal sum of YTD wage buckets",                                      "recordCount" : 8                              }                      ]              },              {                      "field" : "ssn",                      "recordCount" : 2,                      "errorDetails" : [                              {                                      "recordIds" : [                                              "10003667"                                      ],                                      "detail" : "The ssn field is required.",                                      "recordCount" : 1                              },                              {                                      "recordIds" : [                                              "10003694"                                      ],                                      "detail" : "The ssn must be 9 digits.",                                      "recordCount" : 1                              }                      ]              },              {              "field":"employeeHomeAddressCountry",              "recordCount":1,              "errorDetails":[                 {                    "recordIds":[                       "10003694"                    ],                    "detail":"The employeeHomeAddressCountry field is required.",                    "recordCount":1                 }              ]           }      ]  

}

Here is the mycode method 1:

    db.collection.aggregate([    { $match: { groupBy: ObjectId("60f5c60fbc43cb00965ac641") } },    { "$project": {       "_id": "$groupBy",        "errorFields": { "$map": {        "input": "$errorFields",        "as": "ef",        "in": {            "field": "$$ef.field",          "recordCount": {              $sum:"$$ef.recordCount"          },          "errorDetails": { "$map": {            "input": "$$ef.errorDetails",            "as": "ed",            "in": {              "detail": "$$ed.detail",              "recordIds": { "$map": {                "input": "$$ed.recordIds",                "as": "ri",                "in": {                    $concat: [ "$$ri"]                }              }},              "recordCount": {                  $size:"$$ed.recordIds"              }            }          }}        }          }}    }}  ]).pretty()  

Here is the mycode method 2:

    db.collection.aggregate([    { $match: { groupBy: ObjectId("60f5c60fbc43cb00965ac641") } },    { $unwind: "$errorFields" },    { $unwind: "$errorFields.errorDetails" },    { $unwind: "$errorFields.errorDetails.recordIds" },    { "$group": {      "_id": {         "_id": "$groupBy",        "errorFields": {            "field": "$errorFields.field",          "errorDetails": {            "detail": "$errorFields.errorDetails.detail"          }        }      },      "recordIds": {         "$push" : "$errorFields.errorDetails.recordIds",      },      "Idscount": { $sum: 1 }    }},    { "$group": {      "_id": {         "_id": "$_id._id",        "errorFields": {          "field": "$_id.errorFields.field"        }      },      "errorDetails": {         "$push": {           "recordIds": "$recordIds",          "detail": "$_id.errorFields.errorDetails.detail",          "recordCount" : "$Idscount"         }      }    }},    { "$group": {      "_id": 0,      "errorFields": {            "$push": {          "field": "$_id.errorFields.field",          "recordCount": "$fieldCount",          "errorDetails": "$errorDetails"        }      }    }}  ]).pretty()  

NameError: name 'FaceDetector' is not defined

Posted: 01 Aug 2021 08:22 AM PDT

I was trying to run this code but it says

NameError                                 Traceback (most recent call last)  <ipython-input-5-49e303967177> in <module>        3         4 #Detector object created  ----> 5 fd=FaceDetector(frontal_cascade_path)    NameError: name 'FaceDetector' is not defined  

This is the code: -

#Frontal face of haar cascade loaded  frontal_cascade_path="../input/haarcascade-frontal-faces/haarcascade_frontalface_default.xml"    #Detector object created  fd=FaceDetector(frontal_cascade_path)  

How to get SHA1 code in new version of android studio 4.2?

Posted: 01 Aug 2021 08:23 AM PDT

Before this update we can get SHA1 code from Gradle but now it's look like it's changed.

enter image description here

No results from SendGrid email activity API

Posted: 01 Aug 2021 08:21 AM PDT

I'm using this documentation to try and receive bounce information from the SendGrid email activity API:

https://sendgrid.com/docs/for-developers/sending-email/getting-started-email-activity-api/#filter-by-bounced-emails

But it returns no results, despite having ~50 bounces showing on our dashboard (which are viewable from the "activity" section on the SendGrid web interface).

Request:

curl --request GET \   --url 'https://api.sendgrid.com/v3/messages?limit=100&query=status%3D%22bounced%22' \   --header 'authorization: Bearer <<TOKEN_REMOVED>>'  

Response:

{"messages":[]}

Obviously <<TOKEN_REMOVED>> is our actual token when I'm running it :)

Note - when I use the v3/suppression/bounces endpoint to return everything it works fine (responds with a huge JSON of bounces), however I'd like to be able to use the more flexible messages endpoint for querying a specific email etc.

curl --request GET \  --url https://api.sendgrid.com/v3/suppression/bounces \  --header 'accept: application/json' \  --header 'authorization: Bearer <<TOKEN_REMOVED>>' \   --header 'content-type: application/json' \  --data '{}' \  

How to count emoji in a text or string

Posted: 01 Aug 2021 08:21 AM PDT

How to count EMOJI in a string or text line and display the output, how many emoji are in the text line or string?

For example: "Hello 😀😁😂🤣😃😄😅 there"

The output should be: 7

No comments:

Post a Comment