Wednesday, January 12, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to remove � unicode block in string with python?

Posted: 12 Jan 2022 03:08 AM PST

how to remove the unknown � unicode block in json string using python:

"U+FFFD � REPLACEMENT CHARACTER used to replace an unknown, unrecognized, or unrepresentable character"

How to run a SC Orchestrator runbook for each data in a CSV file?

Posted: 12 Jan 2022 03:08 AM PST

I have a CSV file with a list of users that need to be created. However, depending on a specific parameter of the user the process of its creation is different. Here is the format of my csv file:

enter image description here

I was thinking on creating a runbook like this:

enter image description here

My Run .Net Script, retrieves all the information from the file and stores the users in different variables depending on their Type:

$typeA = Import-CSV -Path "[path]" | Where-Object Type -eq "A"  $typeB = Import-CSV -Path "[path]" | Where-Object Type -eq "B"  

Then the variable will be sent through Published Data to their respective Runbook to be created.

My question is, is there a way to run the runbooks Create User Type A and Create User Type, for each user? The problem that I keep running into is that the type of the variable is an Object[] and Orchestrator only passes String[] type.

I hope my issue made sense. I'm open to respond to any question in case of doubt.

how to use Application.WorksheetFunction.CountA to count sheets from 1 to 31

Posted: 12 Jan 2022 03:08 AM PST

need help with that > i try to use how to use Application.WorksheetFunction.CountA to count sheets from 1 to 31

i can't do it .. any help

that what i try :

number = Application.WorksheetFunction.CountA(Worksheets("1:31"))

thanks for any help

Which tree strategy to choose that saves sibling position?

Posted: 12 Jan 2022 03:08 AM PST

Within a node, when the position of the children matters, which tree pattern (Adjacency List, Materialized Path, Nested Set, Closure Table, etc...) adopt to store and fetch the whole tree ordered by these positions? Which is the best in terms of ease of use and performances?

Example

Given these hierarchical data:

root  ├─ 1. Node 1  │  ├─ 1. Node 1.1  │  └─ 2. Node 1.2  └─ 2. Node 2     ├─ 1. Node 2.1     └─ 2. Node 2.2  

I want to be able to switch the position of the given nodes Node 1.1 and Node 1.2 and store the new result. Then the updated tree fetched should be:

root  ├─ 1. Node 1  │  ├─ 1. Node 1.2 // Updated  │  └─ 2. Node 1.1 // Updated  └─ 2. Node 2     ├─ 1. Node 2.1     └─ 2. Node 2.2  

SonarQube-scan-action cannot find out the files

Posted: 12 Jan 2022 03:08 AM PST

I set up self-hosted runners on EKS, and I am using "SonarSource/sonarcloud-github-action@master" in Github Actions. I face the issue that sonarcloud-github-action cannot find out "Project code" in correct path. If i am using the Runner hosted by github, SonarQube find the files. The configuration is exact the same. Even I use -Dsonar.projectKey to pass the project key, there is no files which SonarQube can scan.

name: SonarQube Scan    on:    push:      branches:        - feat/self-host-sonarqube    jobs:    sonarqube:      # runs-on: ubuntu-latest      runs-on: [self-hosted, Linux, X64, sonarqube]      steps:        -           run: echo $GITHUB_WORKSPACE        -           name: checkout current branch          uses: actions/checkout@v2          with:            fetch-depth: 0        -           run: pwd && ls -l && cat sonar-project.properties        -           name: SonarQube Scan          uses: sonarsource/sonarqube-scan-action@master          # with:           #   projectBaseDir: .          #   args: >          #     -Dsonar.projectKey=project-key          #     -Dsonar.javascript.lcov.reportPaths=coverage/*.info          #     -Dsonar.inclusions=src/**/*          #     -Dsonar.exclusions=**/__test__,**/*.test.ts,**/*.test.tsx          env:            SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}            SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}    

enter image description here

get original position of x and y after transform of UIView in swift

Posted: 12 Jan 2022 03:08 AM PST

I've created CustomView which is equal to UIView. Nothing did in subclass. When I add that customView's instance to ViewController run time I need to apply rotate and scale transformation which I did via PinchGesture and RotateGesture.
Here is my code for pinch and rotate gesture handling.

@objc func handlePinchGestureOnSticker(_ sender: UIPinchGestureRecognizer) {          guard let gestureView = sender.view else {              return          }          gestureView.transform = gestureView.transform.scaledBy(              x: sender.scale,              y: sender.scale          )          sender.scale = 1  }        @objc func handleRotateGestureOnSticker(_ sender: UIRotationGestureRecognizer) {      guard let gestureView = sender.view else {          return      }            gestureView.transform = gestureView.transform.rotated(          by: sender.rotation      )      sender.rotation = 0  }  

Here is my question, How can I get original position of X and Y after apply transformation? UIView's transformation screenshot You can check in hierarchy debug view, displayed in blue circle is original position of X and Y, which is denoted by Xcode as position marked in green circle.

I've followed this solution but it not giving correct result

Looping through tagged resources in Python

Posted: 12 Jan 2022 03:08 AM PST

Basically Im trying to target clusters based on their tag. In the code below I can target the cluster with the tag 'AutoOn' and 'true' However if I have one other cluster with tags how can I also include that in my script so I can also start it up? Is it another if statement? Im a noob to Python but have created this script that successfully targets the first cluster

# Step one: get all DB clusters.      response = rds_client.describe_db_clusters(          MaxRecords=100      )        # Make an empty list for cluster info storage.      clusters = [] # empty list of no items.        # Get the initial results.      clusters.append(response['DBClusters'])        # If 'Marker' is present in the response, we have more to get.      while 'Marker' in response:          old_marker = response['Marker']          response = rds_client.describe_db_clusters(              MaxRecords=100,              Marker = old_marker          )          clusters.append(response['DBClusters'])          # Cycles back up to repeat the pagination.        for cluster in clusters:          for test in cluster:                              for tag in test['TagList']:                  if tag['Key'] == "AutoOn":                      if tag['Value'] == "true":                                                    continue                                   # move to the next record.            # Stop the instance.          rds_client.start_db_cluster(              DBClusterIdentifier=test['DBClusterIdentifier']          )```  

In Jetpack Compose Vector Image is not working with Android 5.0

Posted: 12 Jan 2022 03:08 AM PST

I am trying to import a vector like so:

    Image(          modifier = Modifier,          painter = painterResource(id = R.drawable.intro_svg_1),          contentDescription = ""      )  

It looks like it works in all versions of android except Android 5.0 (API level 21).

Following is is the error log:

2022-01-12 12:58:26.627 20063-20063/app.erpflow E/AndroidRuntime: FATAL EXCEPTION: main      Process: app.erpflow, PID: 20063      android.content.res.Resources$NotFoundException: Resource ID #0x7f0700a1          at android.content.res.Resources.getValue(Resources.java:1457)          at androidx.compose.ui.res.PainterResources_androidKt.painterResource(PainterResources.android.kt:61)          at app.erpflow.screens.set_up_activity.page1.Screen1Kt.Screen1(Screen1.kt:31)          at app.erpflow.screens.set_up_activity.ViewPagerIntroKt$ViewPagerIntro$1$1.invoke(ViewPagerIntro.kt:54)          at app.erpflow.screens.set_up_activity.ViewPagerIntroKt$ViewPagerIntro$1$1.invoke(ViewPagerIntro.kt:51)          at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:135)          at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)          at com.google.accompanist.pager.Pager$Pager$7$1$1.invoke(Pager.kt:326)          at com.google.accompanist.pager.Pager$Pager$7$1$1.invoke(Pager.kt:315)          at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:135)          at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)          at androidx.compose.foundation.lazy.list.LazyListScopeImpl$items$1$1.invoke(LazyListScopeImpl.kt:41)          at androidx.compose.foundation.lazy.list.LazyListScopeImpl$items$1$1.invoke(LazyListScopeImpl.kt:41)          at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)          at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)          at androidx.compose.runtime.CompositionLocalKt.CompositionLocalProvider(CompositionLocal.kt:228)          at androidx.compose.runtime.saveable.SaveableStateHolderImpl.SaveableStateProvider(SaveableStateHolder.kt:84)          at androidx.compose.foundation.lazy.layout.LazyLayoutItemContentFactory$CachedItemContent$content$1.invoke(LazyLayoutItemContentFactory.kt:103)          at androidx.compose.foundation.lazy.layout.LazyLayoutItemContentFactory$CachedItemContent$content$1.invoke(LazyLayoutItemContentFactory.kt:94)          at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)          at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)          at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2$1$1.invoke(SubcomposeLayout.kt:251)          at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2$1$1.invoke(SubcomposeLayout.kt:251)          at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)          at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)          at androidx.compose.runtime.ComposerKt.invokeComposable(Composer.kt:3337)          at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:2582)          at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:2571)          at androidx.compose.runtime.SnapshotStateKt__DerivedStateKt.observeDerivedStateRecalculations(DerivedState.kt:247)          at androidx.compose.runtime.SnapshotStateKt.observeDerivedStateRecalculations(Unknown Source)          at androidx.compose.runtime.ComposerImpl.doCompose(Composer.kt:2571)          at androidx.compose.runtime.ComposerImpl.composeContent$runtime_release(Composer.kt:2522)          at androidx.compose.runtime.CompositionImpl.composeContent(Composition.kt:478)          at androidx.compose.runtime.Recomposer.composeInitial$runtime_release(Recomposer.kt:748)          at androidx.compose.runtime.ComposerImpl$CompositionContextImpl.composeInitial$runtime_release(Composer.kt:2987)          at androidx.compose.runtime.CompositionImpl.setContent(Composition.kt:433)          at androidx.compose.ui.layout.SubcomposeLayoutState.subcomposeInto(SubcomposeLayout.kt:269)          at androidx.compose.ui.layout.SubcomposeLayoutState.access$subcomposeInto(SubcomposeLayout.kt:154)          at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2.invoke(SubcomposeLayout.kt:244)          at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2.invoke(SubcomposeLayout.kt:241)          at androidx.compose.runtime.snapshots.SnapshotStateObserver.withNoObservations(SnapshotStateObserver.kt:142)          at androidx  

Is there a workaround or shall I make it .png? In that case it works fine but I would prefer .svg for a crisper image.

How to get Newvalue in next line

Posted: 12 Jan 2022 03:08 AM PST

I have a drop down list in excel and a mutiple choice code. But the new values doenst show in a new line with normal excel settings and vbCrLf doesn't work. The new value has to be in the same cell but in a new line. thanks in advance

If InStr(1, Oldvalue, Newvalue) = 0 Then              Target.Value = Oldvalue & " ," & Newvalue  

Limit concurrent requests to php in Apache

Posted: 12 Jan 2022 03:08 AM PST

Config is following:

<VirtualHost 127.0.0.1:80>  ServerName 127.0.0.1  ServerAlias *  ...  <FilesMatch \.php$>  SetHandler "proxy:unix:/run/php.sock|fcgi://localhost"  </FilesMatch>  </VirtualHost>  

I want to limit number of concurrent requests to 10 per host in php. For example host1.example.com 10 host2.example.net 10

But only for .php, other requests not counted. How to achieve this with mod_qos or other module for Apache? I have not found examples in howtos on this subject.

Is it possible to create referring column / foreign keys in same table

Posted: 12 Jan 2022 03:08 AM PST

I hope I explain this as clear as needed. I would like to create a column referring to a different column in the same table, while both these columns aren't PK's and the first(existing column) isn't a FK yet, just a column. The second one does not exist. The table already exist and has data.

Existing situation example:
TABLE Equipment
PK 'EquipmentID'
Column 'External ID' (nvarchar(50) null)

Desired situation example:
TABLE Equipment
PK EquipmentID
Column 'ExternalID' (nvarchar(50) null)
Column 'Partof 'ExternalID''

Thanks in advance!

Lambda is not working on text column to create new column

Posted: 12 Jan 2022 03:08 AM PST

enter image description here

I'm trying to add a column with lambda but it doesn't seem to work. What I want is to create a new column called "flag_risk_and_sentiment" that will take a binary value. if sentiment == "NEG" and flag_risk == 1 , then it should return 1 , else 0. That's my attempt:

df["flag_risk_and_sentiment"] = df.apply(lambda row : 1 if row["sentiment"] == "NEG" and row["flag_risk"] == 1 else 0)  

However I get this message :

KeyError: 'sentiment'  

Any idea why?

Assign values of array 1 to array 2 in such a way that no value should repeat using PHP

Posted: 12 Jan 2022 03:08 AM PST

I have 2 arrays as given below

$nodes = [2,1,3,4];  $values = [5,4,3,2];  

I am trying to find a way to assign a value from $values array to any key from the $nodes array in such a way that no value should repeat in the same loop.

Example:-

N["2"] = 5  N["1"] = 4  N["3"] = 3  N["4"] = 2    N["2"] = 5  N["1"] = 4  N["3"] = 2  N["4"] = 3    N["2"] = 4  N["1"] = 5  N["3"] = 3  N["4"] = 2    N["2"] = 4  N["1"] = 5  N["3"] = 2  N["4"] = 3  

This way as many combinations as possible, I have tried many ways but could not able to figure it out.

The following thing should not happen

N["2"] = 4  N["1"] = 5  N["3"] = 2  N["4"] = 2  // the value "2" already assigned to N["3"]  

How to add style only to specific column based on its id using React Table

Posted: 12 Jan 2022 03:08 AM PST

I cannot figure out how to style specific column based on its id using React Table. I need to add to <span> a margin-left only to the column when columnSorted state is true. For now it works for all columns, whichever column I press the prop is added to all columns.

const [columnSorted, isColumnSorted] = useState<boolean>(false);    <StyledThead>    {headerGroups.map((group, idx) => (      <StyledTableHeadRow key={idx} {...group.getHeaderGroupProps()}>        {group.headers.map((column, idx) => {          return (            <StyledTableHeader key={idx} isSorted={column.isSorted} key={column.id} {...column.getHeaderProps({})}>              <div                style={{                  display: 'flex',                  flexDirection: 'row',                  alignItems: 'center',                }}              >                <div onClick={() => isColumnSorted(!column.isSortedDesc ? 'true' : 'false')}>                  <span                    {...column.getHeaderProps(column.getSortByToggleProps(), {                      className: column.collapse ? 'collapse' : '',                    })}                  >                    {column.render('Header')}                  </span>                  <span>                    {column.isSorted ? column.isSortedDesc ? <StyledArrowDownwardIcon /> : <StyledArrowUpwardIcon /> : ''}                  </span>                </div>                <span                  style={{                    marginLeft: columnSorted && '12px',                  }}                >                  {columnsCount > 5 ? (                    <StyledHeaderDivFlex>{column.canFilter ? column.render('Filter') : null}</StyledHeaderDivFlex>                  ) : (                    <StyledHeaderDivBlock>{column.canFilter ? column.render('Filter') : null}</StyledHeaderDivBlock>                  )}                </span>              </div>            </StyledTableHeader>          );        })}      </StyledTableHeadRow>    ))}  </StyledThead>;  

And below You can see how implementation of few columns looks like:

const columns: any[] = [    {      Header: useTranslationFunc('Status'),      accessor: 'state',      collapse: true,      disableSortBy: true,      Cell: (props: CellValue) => <RenderTrainStatus statusType={props.cell.value} />,      Filter: MultiCheckBoxColumnFilter,      filter: multiSelectFilterFunction,    },    {      Header: useTranslationFunc('Nr składu'),      accessor: 'trainId',      collapse: true,      Cell: (props: CellValue) => <div>{props.cell.value}</div>,      Filter: MultiCheckBoxColumnFilter,      filter: multiSelectFilterFunction,    },  ];  

I was going through the docs but didn't find the answer.

What is date format for 07th November 2021?

Posted: 12 Jan 2022 03:08 AM PST

I want the date format as 07th November 2021. Kindly let me know the format.

thanks in advance.

Is there any way to allow generate_otp_backup_codes using validate_and_consume_otp?

Posted: 12 Jan 2022 03:08 AM PST

I am using device-two-factor gem for otp generation in rails. I am using generate_otp_backup_code to a specific user for testing purpose which is generating otp successfully. validate_and_consume_otp allows otp created via generate_otp_secret whereas validate_and_consume_otp dosen't allow the backup code otp to login. Is there any way to allow generate_otp_backup_codes via validate_and_consume_otp?

tinfoil /devise-two-factor

gem 'devise-two-factor'

In user.rb

devise :two_factor_authenticatable, otp_secret_encryption_key:Rails.application.secrets.secret_key_base devise :two_factor_backupable, otp_backup_code_length: 6, otp_number_of_backup_codes: 10

To generate backup codes: codes = current_user.generate_otp_backup_codes! current_user.save!

How to get raw date string from date picker?

Posted: 12 Jan 2022 03:08 AM PST

I'm struggling for hours with this seemingly trivial issue.

I have a antd datepicker on my page.

Whenever I choose a date, instead of giving me the date I chose, it gives me a messy moment object, which I can't figure out how to read.

All I want is that when I choose "2020-01-18", it should give me precisely this string that the user chose, regardless of timezone, preferably in ISO format.

This is not a multi-national website. I just need a plain vanilla date so I can send it to the server, store in db, whatever.

Here are some of my trials, so far no luck:

var fltval = e;  if (isMoment(fltval)) {    var dat = fltval.toDate();    //dat.setUTCHours(0)    fltval = dat.toISOString(); // fltval.toISOString(false)      var a = dat.toUTCString();    //var b = dat.toLocaleString()  }  

It keeps on moving with a few hours, probably to compensate for some timezone bias

Thanks!

Transact SQL - Get first character every 5 characters of a variable length string

Posted: 12 Jan 2022 03:08 AM PST

I have a string that looks like the following

A1234B1234C1234

I would like to take the first character every 5 characters.

The result would be

ABC

The string length is variable so the length could be 5, 10 , 20 , 30 ect

Extract text between 2 similar or different strings separately in shell script

Posted: 12 Jan 2022 03:08 AM PST

I want to extract text between each ### separately to compare with a different file. Need to extract all CVE numbers for all docker images to compare from previous report. File looks as shown below. This is a snippet and it has more than 100 such lines. Need to do this via Shell Script. Kindly help.

### Vulnerabilities found in docker image alarm-integrator:22.0.0-150  | CVE  | X-ray Severity | Anchore Severity | Trivy Severity | TR   |  | :--- | :------------: | :--------------: | :------------: | :--- |  |[CVE-2020-29361](#221fbde4e2e4f3dd920622768262ee64c52d1e1384da790c4ba997ce4383925e)|||Important|  |[CVE-2021-35515](#898e82a9a616cf44385ca288fc73518c0a6a20c5e0aae74ed8cf4db9e36f25ce)|||High|    ### Vulnerabilities found in docker image br-agent:22.0.0-154  | CVE  | X-ray Severity | Anchore Severity | Trivy Severity | TR   |  | :--- | :------------: | :--------------: | :------------: | :--- |  |[CVE-2020-29361](#221fbde4e2e4f3dd920622768262ee64c52d1e1384da790c4ba997ce4383925e)|||Important|  |[CVE-2021-23214](#75eaa96ec256afa7bc6bc3445bab2e7c5a5750678b7cda792e3c690667eacd98)|||Important|  

I've tried something like this grep -oP '(?<=\"##\").*?(?=\"##\")' but it doesn't work.

Expected Output:

For alarm-integrator  CVE-2020-29361  CVE-2021-35515    For br-agent  CVE-2020-29361  CVE-2021-23214  

Why method in in mixin returns object Promise? [duplicate]

Posted: 12 Jan 2022 03:08 AM PST

In vuejs3 app I want to use common method, so I put it into mixin resources/js/appMixin.js as :

export default {        methods: {            async getBlockPage(page_slug) {              const response = await axios.post('/get_block_page', {slug: this.page_slug})              console.log('response.data.page::')              console.log(response.data.page) // In the browser console I see this valid page object returned                  return response.data.page;            }, // getBlockPage() {  

but calling this method in vue file :

mounted() {      this.about= this.getBlockPage("about");      console.log('AFTER this.about::') // I DO NOT this output      console.log(this.about)  },  

and outputting about var I see

"[object Promise]"  

Which is the valid way?

That question seems a bit specific then provided link, as method is inside of mixin...

Thanks in advance!

Get the final price with discount but only if column is not NULL. SQL

Posted: 12 Jan 2022 03:08 AM PST

I use these sql tables with these columns:

customers:

id name phone adress etc..
1234 Test Name Test Phone Test Adress etc data.

orders:

customerid orderid orderdate
1234 OR_1234 2022-1-1

orderitems: (in this table one customer can have multiple rows(items)

id orderid productid
1 OR_1234 P1

products:

productid productprice currency qty name weight
P1 10 USD 1 TEST 0.2 KG

So in this case if I want to get the FULL price from the order from customer I use this query:

SELECT sum( productprice ) as fullprice  FROM customers   inner join orders on orders.customerid = customers.id   inner join orderitems on orderitems.orderid = orders.orderid   inner join products on products.productid = orderitems.productid   WHERE customers.id = '1234'   

This query is working perfectly. But what if I want to add to this query a discount from discount table:

discount:

id name value status
1 Discount 1 valid

So I think I will need to create one more column in orders table with name for example: discount_code and if the discount_code column is not empty than subtract the discount value from productprice.

SELECT sum( productprice - discount.value ) as fullprice but how can I make this query? Thank you for help!

BTW I use MariaDB

Have a very nice day!

Reddit Notification Bot

Posted: 12 Jan 2022 03:07 AM PST

I am looking to create a bot for Reddit that looks at a single forum that I'm interested in and notifies me in real time every post that happens. I wanted to create this due to reddit notification system not being great and timing is off. How could I go about creating something like this? Thanks

Why Selenium headless mode give problems?

Posted: 12 Jan 2022 03:08 AM PST

I have problem running in headless mode with selenium. Here is the options i tried. I have tried all, some, combined, etc:

c = new ChromeOptions();          c.AddArguments(@"--myUser-data-dir=C:\Users\myUser\AppData\Local\Google\Chrome\User Data");      c.AddExcludedArgument("--enable-automation");      c.AcceptInsecureCertificates = true;      c.AddArguments("--ignore-certificate-errors");      c.AddArguments("--ignore-ssl-errors");      c.AddArgument("start-maximized");      c.AddArguments("--lang=en");      c.AddArguments("--disable-blink-features=AutomationControlled");      c.AddArguments("--headless");      c.AddArgument("--window-size=1200,900");      c.AddArgument("--disable-browser-side-navigation");      c.AddExtension(Path.GetFullPath(@"C:\\Plugins\\extension_4_41_0_0.crx"));      c.AddArguments("--allow-no-sandbox-job");      c.AddArguments("--disable - dev - shm - usage");      c.AddArguments("--disable-gpu");  

I also added some pics to show you my code so maybe its easier to understand: Chrome options part 1 Chrome options part 2 Problem part 1 Problem part 2

When sending embeds, should the last line be channel.send({ embeds: [exampleEmbed] })?

Posted: 12 Jan 2022 03:08 AM PST

I'm kind of stuck with this portion of the code. I'm currently coding a discord bot for a school project as well as personal use. The main purpose of the discord bot is to send embeds and casual commands where someone says "goodnight" and the bot will respond goodnight. For the goodnight part of the code, I have it pretty much written correctly, but how do I get it to respond by tagging the persons discord tag? such as instead of my current code being else if (message.content === 'goodnight'){ message.channel.send('Goodnight!'); How would I get it to say "Goodnight @discordtag"

Secondly, the embed portion of the code is what I'm struggling with the most. I'm pretty much following the guides on https://discordjs.guide as well as some youtube videos, but I seem to not be able to find the answer. I'm getting the error "channel.send({ embeds: [exampleEmbed] }); ^

TypeError: Cannot read properties of undefined (reading 'send')

My code for the example embed is:

const channel = client.channels.cache.get('912186200910102559')  const exampleEmbed = new MessageEmbed()          .setColor('#5104DB')          .setTitle("Boombap's Cookout Rules")          .setAuthor({ name: 'Rules', iconURL: 'https://gridfiti.com/wp-content/uploads/2021/04/Gridfiti_Blog_AnimeCars_NissanSilviaS13.jpg'})          .addFields(              { name: 'Rule 1', value: 'No racist, sexist or any type of hate speech towards other members.'},              { name: 'Rule 2', value: 'No scamming.'},              { name: 'Rule 3', value: 'No discussions of anything illegal, if you think it might be just do not mention it in the discord.'},              { name: 'Rule 4', value: 'No advertisements of other services.'}            )    channel.send({ embeds: [exampleEmbed] });  

How should work with student files in Python like this one?

Posted: 12 Jan 2022 03:08 AM PST

The first part includes 6 students with first and last names. The second part includes 3 lessons(java, c#, python). The third part shows which student has taken these courses. These three parts are separated with (#) and located in a text file(a.txt).

# a.txt     1 a aa  2 b bb   3 c cc  4 d dd   5 e ee  6 f ff   ###  1 java  2 c#   3 python   ###  1 2    1 3   1 5  2 1   2 2  2 4   2 6   3 3   3 5   3 4  3 1  

The output should be a list with the sample format, like this: output:

{      "java":["b_bb","c_cc","e_ee"],      "c#":["a_aa","b_bb","d_dd","f_ff"],      "python": ["c_cc","e_ee","d_dd","a_aa"]  }  

Google Cloud Data Catalog - Node JS Library giving Error: 5 NOT_FOUND: Project does not exist

Posted: 12 Jan 2022 03:08 AM PST

I am trying to use Nodejs Library for Google Cloud Data Catalog. For one project, it is working perfectly fine but for others it is giving me Project does not exist error, while I can see the project with that ID in GCP.

Example error received in application code

Error: 5 NOT_FOUND: Project "tech-mktg-wwc" does not exist.  

Project in GCP

here is a sample code that causes this error

const locationPath = datacatalog.locationPath('tech-mktg-wwc','us-central1');  const req = {parent: locationPath};  const [resp] = await datacatalog.listEntryGroups(req);  

Auth is happening via key generated for service account. I tried comparing roles/permissions for the working project with non-working one but couldn't find anything obvious. I am sure I must be missing something. Any help would be appreciated.

Thanks

Spring Boot, OAuth2 authentication is lost between requests

Posted: 12 Jan 2022 03:07 AM PST

I use spring security builtin oauth2 social login option, I implemented an OAuth2LoginSuccess class with the onAuthenticationSuccess method and inside of it I fetch the user the corresponds to the social id I got from the oauth:

CustomOAuth2User oAuth2User = (CustomOAuth2User) authentication.getPrincipal();  int sociald = oAuth2User.getAttribute("id");  User user = usersUtils.getUserBySocailId(socialId);  enter code here  // add the user details to the Auth  SecurityContextHolder.clearContext();  ((OAuth2AuthenticationToken) authentication).setDetails(user);  SecurityContextHolder.getContext().setAuthentication(authentication);  

If I debug inside the onAuthenticationSuccess I can see a valid auth with all the user details.

after the login I redirect to the home page and i send a auth get request to the server to check if there is a user logged in.

the problem is that 50% of the times the request is completed successfuly and the user can make authenticated requets.

but the other 50% i get redirected automaticly to Login page and when i check the log is see that Spring boot says that the user is unauthenticated and the auth is lost.

But in the onAuthenticationSuccess i can always see the correct auth.

My ApplicationSecurityConfig looks like this:

    http.csrf().disable().authorizeRequests()              .antMatchers("/login*", "/signin/**", "/signup/**", "/oauth2/**").permitAll()              .antMatchers(Constants.ADMIN_PREFIX + "/**").hasRole("ADMIN")              .antMatchers(Constants.AUTH_PREFIX + "/**").hasAnyRole("ADMIN", "USER")              .antMatchers(Constants.PUBLIC_PREFIX + "/**").permitAll()              .anyRequest().permitAll()              .and()              .exceptionHandling().authenticationEntryPoint(new UnauthenticatedRequestHandler())              .and()              .formLogin()              .passwordParameter("password")              .usernameParameter("email")              .loginPage("/Login")              .loginProcessingUrl("/loginSecure").permitAll().successHandler(new LoginSuccess()).failureHandler(new FailureSuccess())              .and()              .oauth2Login()              .loginPage("/Login")              .userInfoEndpoint()              .userService(oAuth2UserService)              .and()              .successHandler(new OAuth2LoginSuccess())              .and()              .rememberMe()              .rememberMeParameter("remember-me")              .tokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(21))  .userDetailsService(this.applicationUserService)              .and()              .logout()           .clearAuthentication(true).invalidateHttpSession(true).logoutSuccessUrl("/login")              .addLogoutHandler(new CustomLogOutHandler());  

And this is the function i check if the user is logged in:

   @GetMapping(Constants.AUTH_PREFIX + "/checkUserLogged")  public Integer checkUserLogged(Authentication authentication,HttpServletRequest request) {      try{          if (authentication != null) {              User (User) authentication.getDetails();              if (user == null) {                  return -1;              }              return user.getId();          }      }      catch (Exception e){          logger.warning(e.getLocalizedMessage());      }      return -1;  }  

but when the problem occur it dosen't get to run the controller because spring security return unauthrozed error before.

Thank you in advance for your help

Android Studio Emulator error "The emulator process for AVD was killed"

Posted: 12 Jan 2022 03:08 AM PST

This is the error I'm getting:

The emulator process for AVD Pixel_XL_API_30 was killed.

All virtual devices don't run. I've tried deleting the directory for them and then creating new ones.

Import msg file with outlook Web

Posted: 12 Jan 2022 03:08 AM PST

Is it possible to open a msg file with Outlook Web?

I have tried to upload the msg file to onenote, but i do not know how to put it into the Web Interface.

I just need a already prepared msg file from another person to save it as draft in my outlook web interface.

How to get Spring RabbitMQ to create a new Queue?

Posted: 12 Jan 2022 03:08 AM PST

In my (limited) experience with rabbit-mq, if you create a new listener for a queue that doesn't exist yet, the queue is automatically created. I'm trying to use the Spring AMQP project with rabbit-mq to set up a listener, and I'm getting an error instead. This is my xml config:

<rabbit:connection-factory id="rabbitConnectionFactory" host="172.16.45.1" username="test" password="password" />    <rabbit:listener-container connection-factory="rabbitConnectionFactory"  >      <rabbit:listener ref="testQueueListener" queue-names="test" />  </rabbit:listener-container>    <bean id="testQueueListener" class="com.levelsbeyond.rabbit.TestQueueListener">   </bean>  

I get this in my RabbitMq logs:

=ERROR REPORT==== 3-May-2013::23:17:24 ===  connection <0.1652.0>, channel 1 - soft error:  {amqp_error,not_found,"no queue 'test' in vhost '/'",'queue.declare'}  

And a similar error from AMQP:

2013-05-03 23:17:24,059 ERROR [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer] (SimpleAsyncTaskExecutor-1) - Consumer received fatal exception on startup  org.springframework.amqp.rabbit.listener.FatalListenerStartupException: Cannot prepare queue for listener. Either the queue doesn't exist or the broker will not allow us to use it.  

It would seem from the stack trace that the queue is getting created in a "passive" mode- Can anyone point out how I would create the queue not using the passive mode so I don't see this error? Or am I missing something else?

No comments:

Post a Comment