问:
Full-Width E-mail Template?
I recently received an e-mail that appears full-width on IOS G-Mail App:

https://ibb.co/FBd03XH

When trying to recreate, it always looks like this:

https://ibb.co/kMY0FLm

Edit: Added code

```<code><div role="article" style="background-color:#000">
    <table role="presentation" style="width:100%;border:none;border-spacing:0">
      <tr>
        <td align="center" style="padding:0">
  <table role="presentation" style="width:94%;max-width:600px;border:none;border-spacing:0;text-align:left;font-family:system-ui;font-size:16px;line-height:22px;color:#fff">
            <tr>
            </tr>
            <tr>
              <td>
                <h1 style="margin-top:0;margin-bottom:16px;font-size:26px;line-height:32px;font-weight:bold;letter-spacing:-0.02em">Welcome to our responsive email!</h1>
                <p style="margin:0">Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tempus adipiscing felis, sit amet blandit ipsum volutpat sed. Morbi porttitor, <a href="http://www.example.com/" style="color:#e50d70;text-decoration:underline">eget accumsan dictum</a>, nisi libero ultricies ipsum, in posuere mauris neque at erat.</p>
              </td>
            </tr>
            <tr>
              <td style="padding:0;font-size:24px;line-height:28px;font-weight:bold">
                <a href="http://www.example.com/" style="text-decoration:none"><img src="https://assets.codepen.io/210284/1200x800-2.png" width="600" alt="" style="width:100%;height:auto;border:none;text-decoration:none;color:#363636"></a>
              </td>
            </tr>
            <tr>
              <td style="padding:35px 30px 11px 30px;font-size:0;background-color:#ffffff;border-bottom:1px solid #f0f0f5">

                <div class="col-sml" style="width:100%;max-width:145px;vertical-align:top;text-align:left;font-family:system-ui;font-size:14px;color:#363636">
                  <img src="https://assets.codepen.io/210284/icon.png" width="115" alt="" style="width:115px;max-width:80%;margin-bottom:20px">
                </div>

                <div class="col-lge" style="width:100%;max-width:395px;vertical-align:top;padding-bottom:20px;font-family:system-ui;font-size:16px;line-height:22px;color:#363636">
                  <p style="margin-top:0;margin-bottom:12px">Nullam mollis sapien vel cursus fermentum. Integer porttitor augue id ligula facilisis pharetra. In eu ex et elit ultricies ornare nec ac ex. Mauris sapien massa, placerat non venenatis et, tincidunt eget leo.</p>
                  <p style="margin-top:0;margin-bottom:18px">Nam non ante risus. Vestibulum vitae eleifend nisl, quis vehicula justo. Integer viverra efficitur pharetra. Nullam eget erat nibh.</p>
                  <p style="margin:0"><a href="https://example.com/" style="background: #ff3884;text-decoration: none;padding: 10px 25px;color: #ffffff;border-radius: 4px"><span style="font-weight:bold">Claim yours now</span></a></p>
                </div>

              </td>
            </tr>
            <tr>
              <td style="padding:30px;font-size:24px;line-height:28px;font-weight:bold;background-color:#ffffff;border-bottom:1px solid #f0f0f5">
                <a href="http://www.example.com/" style="text-decoration:none"><img src="https://assets.codepen.io/210284/1200x800-1.png" width="540" alt="" style="width:100%;height:auto;border:none;text-decoration:none;color:#363636"></a>
              </td>
            </tr>
            <tr>
              <td style="padding:30px;background-color:#ffffff">
                <p style="margin:0">Duis sit amet accumsan nibh, varius tincidunt lectus. Quisque commodo, nulla ac feugiat cursus, arcu orci condimentum tellus, vel placerat libero sapien et libero. Suspendisse auctor vel orci nec finibus.</p>
              </td>
            </tr>
            <tr>
              <td style="padding:30px;text-align:center;font-size:12px;background-color:#404040;color:#cccccc">
                <p style="margin:0 0 8px 0"><a href="http://www.facebook.com/" style="text-decoration:none"><img src="https://assets.codepen.io/210284/facebook_1.png" width="40" height="40" alt="f" style="color:#cccccc"></a> <a href="http://www.twitter.com/" style="text-decoration:none"><img src="https://assets.codepen.io/210284/twitter_1.png" width="40" height="40" alt="t" style="color:#cccccc"></a></p>
                <p style="margin:0;font-size:14px;line-height:20px">® Someone, Somewhere 2021<br><a class="unsub" href="http://www.example.com/" style="color:#cccccc;text-decoration:underline">Unsubscribe instantly</a></p>
              </td>
            </tr>
          </table>

        </td>
      </tr>
    </table>
  </div>
</code>```

Title: Full-Width E-mail Template?

Body:
I recently received an e-mail that appears full-width on IOS G-Mail App:

https://ibb.co/FBd03XH

When trying to recreate, it always looks like this:

https://ibb.co/kMY0FLm

Edit: Added code

Welcome to our responsive email!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tempus adipiscing felis, sit amet blandit ipsum volutpat sed. Morbi porttitor, eget accumsan dictum, nisi libero ultricies ipsum, in posuere mauris neque at erat.

Nullam mollis sapien vel cursus fermentum. Integer porttitor augue id ligula facilisis pharetra. In eu ex et elit ultricies ornare nec ac ex. Mauris sapien massa, placerat non venenatis et, tincidunt eget leo.

Nam non ante risus. Vestibulum vitae eleifend nisl, quis vehicula justo. Integer viverra efficitur pharetra. Nullam eget erat nibh.

Claim yours now

Duis sit amet accumsan nibh, varius tincidunt lectus. Quisque commodo, nulla ac feugiat cursus, arcu orci condimentum tellus, vel placerat libero sapien et libero. Suspendisse auctor vel orci nec finibus.

® Someone, Somewhere 2021
Unsubscribe instantly


来源: stackexchange

问:
Remove Commas in CSV without adding extra columns
I have this script intended to remove "extra commas" within a string in a CSV.

@echo off & setlocal EnableDelayedExpansion

echo Removing commas from FILE CSV file...
type nul > "H:\CONVERT_CSV.csv"
for /F "delims=" %%i in ('type "H:\FILE.csv"') do (
    set row=%%i
    set row=!row:"=!
    echo.!row!>> "H:\CONVERT_CSV.csv"
)
```
<p>But my script, instead of removing the comma, it adds an extra field within that record.</p>
<p>I know the problem sits in the <code>set row!row"=!</code> line, but I can not figure out what.</p>
<p>Please help</p>
<p>Example</p>
<p>From this:</p>
```Column A,Column B
Now,All,2
Then,After
```
<p>To this:</p>
```Column A,Column B
Now,All 2
Then,After

EDIT: EXTRA INFO:
 the csv has:

123 ,the time, "Gone, For good", 2023

Then it should become:
123 ,the time, "Gone For good", 2023
```

ContentLicense: CC BY-SA 4.0

Body:
I have this script intended to remove "extra commas" within a string in a CSV.

@echo off & setlocal EnableDelayedExpansion

echo Removing commas from FILE CSV file...
type nul > "H:\CONVERT_CSV.csv"
for /F "delims=" %%i in ('type "H:\FILE.csv"') do (
    set row=%%i
    set row=!row:"=!
    echo.!row!>> "H:\CONVERT_CSV.csv"
)

But my script, instead of removing the comma, it adds an extra field within that record.

I know the problem sits in the set row!row"=! line, but I can not figure out what.

Please help

Example

From this:

Column A,Column B
Now,All,2
Then,After

To this:

Column A,Column B
Now,All 2
Then,After

EDIT: EXTRA INFO:
 the csv has:

123 ,the time, "Gone, For good", 2023

Then it should become:
123 ,the time, "Gone For good", 2023


问:
Quasar iOS build - need podfile
I have a web project based on quasar framework. I am also wrapping it in mobile apps. Android app building is fine. But when I try to build the ios app using the command "quasar build -m capacitor -T ios", it asks for a POD file.

✖ Updating iOS native dependencies with "pod install" (may take several minutes): ENOENT: no such file or directory, open '/Users/me/myapp/quasar/src-capacitor/ios/App/Podfile'

How do I get or create this file?

Title: Quasar iOS build - need podfile


问:
Unexpected sort order on postgres left outer join
Background

I'm using Postgres 11 and pgAdmin4 v5.2.  The problem I describe below is on my dev machine which has both the postgres server and pgAdmin client.

Questions I've looked at on SO that deal with incorrect ordering seem related to collation-related issues with ordering of text fields, whereas my problem is on an integer field.

Setup

I have a table norm_plans that contains ~5k records.

```<code>Column   | Type
---------------------------------
canon_id | integer
name     | character varying(200)
...
other fields
</code>```

canon_id is autopopulated using a sequence.

I've created a new table norm_plans_cmp as a copy of norm_plans (CREATE TABLE norm_plans_cmp AS TABLE norm_plans WITH DATA;)

I next insert some new records into norm_plans and update some existing records (fields other than canon_id.

The new records increment the sequence and are assigned canon_id values as expected.

I now want to compare norm_plans against norm_plans_cmp so I perform a left outer join:

select a.*, b.*
from norm_plans a
left outer join norm_plans_cmp b
on a.canon_id = b.canon_id
order by a.canon_id
```

Problem

I would expect records to be sorted by canon_id.  This holds true from 1-2000, but after 2,000 I get canon_ids from 5,001 to 5,111 (which is the last canon_id) and then it again picks up from 2,001.  I'm viewing this data from pgAdmin, see screenshot 1 below showing the shift from 2,000 to 5,001, and screenshot 2 showing the transition again from 5,111 back to 2,001.

Additional observations

While incorrect, the ordering seems consistent.  Running the query multiple times results in the same (incorrect) ordering.

Despite my question title, I'm not totally sure the left join has anything to do with this.
Running SELECT * ... ORDER BY canon_id on norm_plans or norm_plans_cmp alone also result in incorrect ordering, albeit at different points in the order.

Answers to this SO question suggest index corruption may be a contributing problem, but I have no indexes on either norm_plans or norm_plans_cmp (canon_id is not defined as a PK).

At this point, I'm stumped!

Body:
Background

I'm using Postgres 11 and pgAdmin4 v5.2.  The problem I describe below is on my dev machine which has both the postgres server and pgAdmin client.

Questions I've looked at on SO that deal with incorrect ordering seem related to collation-related issues with ordering of text fields, whereas my problem is on an integer field.

Setup

I have a table norm_plans that contains ~5k records.

Column   | Type
---------------------------------
canon_id | integer
name     | character varying(200)
...
other fields

canon_id is autopopulated using a sequence.

I've created a new table norm_plans_cmp as a copy of norm_plans (CREATE TABLE norm_plans_cmp AS TABLE norm_plans WITH DATA;)

I next insert some new records into norm_plans and update some existing records (fields other than canon_id.

The new records increment the sequence and are assigned canon_id values as expected.

I now want to compare norm_plans against norm_plans_cmp so I perform a left outer join:

select a.*, b.*
from norm_plans a
left outer join norm_plans_cmp b
on a.canon_id = b.canon_id
order by a.canon_id

Problem

I would expect records to be sorted by canon_id.  This holds true from 1-2000, but after 2,000 I get canon_ids from 5,001 to 5,111 (which is the last canon_id) and then it again picks up from 2,001.  I'm viewing this data from pgAdmin, see screenshot 1 below showing the shift from 2,000 to 5,001, and screenshot 2 showing the transition again from 5,111 back to 2,001.

Additional observations

While incorrect, the ordering seems consistent.  Running the query multiple times results in the same (incorrect) ordering.

Despite my question title, I'm not totally sure the left join has anything to do with this.
Running SELECT * ... ORDER BY canon_id on norm_plans or norm_plans_cmp alone also result in incorrect ordering, albeit at different points in the order.

Answers to this SO question suggest index corruption may be a contributing problem, but I have no indexes on either norm_plans or norm_plans_cmp (canon_id is not defined as a PK).

At this point, I'm stumped!


问:
Wmi Query having column data type as CIM_SINT8,CIM_SINT64
I see various CIM types defined here which are basically data type of WMI class data member. The instance of class gets retuned when WQL query is made from Wbemtest utility.
I am looking for WMI system class which has data member of type CIM_SINT8,CIM_SINT64. The aim is to find out are these data types defined just for completeness or some system classes are making use it. Any pointers/clarification would be helpful.

Thanks,


问:
ion slide with cards animation
I have following code to swipe cards. Now I want to swipe the cards like Tinder.

How can I implement this in Angular with Ionic?

`<ion-content>
<ion-slides [options]="{ slidesPerView: true, loop: true,  preloadImages: true,
lazy: false}">
<ion-slide *ngFor="let card of cards" >

```<code>  <ion-icon name="arrow-back"></ion-icon>

  <ion-card >
    <ion-img  [src]="card.img" alt="The Wisconsin State Capitol building in Madison, WI at night"></ion-img>
    <ion-card-header>
      <ion-card-title>{{card.title}}</ion-card-title>
      <ion-card-subtitle>{{card.description}}</ion-card-subtitle>
    </ion-card-header>

  </ion-card>

  <ion-icon name="arrow-forward"></ion-icon>

</ion-slide>
</code>```

</ion-slides>

</ion-content>`

I want to have a Tinder Swipe in Angular and Ionic

Title: ion slide with cards animation

Body:
I have following code to swipe cards. Now I want to swipe the cards like Tinder.

How can I implement this in Angular with Ionic?

`<ion-content>
<ion-slides [options]="{ slidesPerView: true, loop: true,  preloadImages: true,
lazy: false}">
<ion-slide *ngFor="let card of cards" >

  <ion-icon name="arrow-back"></ion-icon>

  <ion-card >
    <ion-img  [src]="card.img" alt="The Wisconsin State Capitol building in Madison, WI at night"></ion-img>
    <ion-card-header>
      <ion-card-title>{{card.title}}</ion-card-title>
      <ion-card-subtitle>{{card.description}}</ion-card-subtitle>
    </ion-card-header>

  </ion-card>

  <ion-icon name="arrow-forward"></ion-icon>

</ion-slide>

</ion-slides>

</ion-content>`

I want to have a Tinder Swipe in Angular and Ionic


问:
Simple dynamic questionnaire creator design in MongoDB?
I've been researching and trying to learn how to create a dynamic survey builder architecture in Mongo by reading through the documentation and searching online for a while, but I'm still having trouble understanding how to do it. So, I was hoping I could receive some guidance from the community here. As I'm just starting to dive deep in the database design and architecture so my experience is quite limited here.

What I'm trying to do is to create a survey builder where the user can create surveys and each survey have a title, questions and a fk to the organization that is supposed to fill in the survey.   Some questions can be imported from a list of standardised questions that are statically typed into the database and the user can choose to import as many standardised questions as they wish (For example, there is a question set that contains some questions related to a specific ISO certificate and there's another the contains some questions that are related to a totally different iso certificate so If the user chose the two question sets then supposedly all of the questions in the two sets will be transferred to their survey). The standarised questions have a default answer input type (yes/no, dropdown, text block). However, after the questions are imported into the user's survey and they can override the input type to different one and the change will be reflected on their survey only the original set will not be touched.

I'm having a trouble in thinking about how to handle the dynamic answer inputs where each question can have a dynamic answer option set by the user. Also, how to link the each answer type to its perspective question type. (For example, question 1 the user chose the answer to be yes/no so the answer should a boolean however, question 2 is dropdown so the answer should be an option, etc)

I'll try and use a simplified version of the Mongo models to better illustrate what I'm trying to do (Some of the models or not completed yet):

I tried to implement something like what was explained above. However, I can't wrap my head around how to handle the dynamic answer types where each user can edit the question answer type dynamically.


问:
Why does adding a repository in GitHub Desktop locally not show my pull requests
So I have a GitHub Enterprise account. On GitHub Desktop when I clone my repository from the server it goes under Enterprise and I can see the list of branches and Pull requests as shown below.

If I simply add an existing repository from my local machine onto GitHub Desktop, then it goes under Other and now I can't see the option for showing me my pull requests.

I don't want to have to reclone all my repo because that just seems silly but is there a way I can still see if there's any pull request from my repo that I simply added in from my local machine?


问:
I got the Error in `arrange()` message, how to solve it?
res_prim = output$res

df_age = res_prim %>%

```<code>dplyr::select(taxon, ends_with("age"))
</code>```

df_fig_age = df_age %>%

```<code>filter(df_age == 1) %>%
</code>```

```<code>arrange(desc(lfc_age)) %>%
</code>```

```<code>mutate(direct = ifelse(lfc_age > 0, "Positive LFC", "Negative LFC"))
</code>```

Error in arrange():
! Problem with the implicit transmute() step.
✖ Problem while computing ..1 = lfc_age.
Caused by error in mask$eval_all_mutate():
! object 'lfc_age' not found
Run rlang::last_error() to see where the error occurred.

rlang::last_error()
Error: object 'rlang::last_error()' not found
rlang::last_error()
<error/rlang_error>
Error in arrange():
! Problem with the implicit transmute() step.
✖ Problem while computing ..1 = lfc_age.
Caused by error in mask$eval_all_mutate():
! object 'lfc_age' not found

Backtrace:

... %>% ...

base::.handleSimpleError(...)

dplyr (local) h(simpleError(msg, call))
Run rlang::last_trace() to see the full context.

I get the above error messages and not sure how to fix it. Please let me know what to do to get rid of the error.

Thank you very much, PAR

Looked in the internet but could not find an answer

Body:
res_prim = output$res

df_age = res_prim %>%

dplyr::select(taxon, ends_with("age"))

df_fig_age = df_age %>%

filter(df_age == 1) %>%

arrange(desc(lfc_age)) %>%

mutate(direct = ifelse(lfc_age > 0, "Positive LFC", "Negative LFC"))

Error in arrange():
! Problem with the implicit transmute() step.
✖ Problem while computing ..1 = lfc_age.
Caused by error in mask$eval_all_mutate():
! object 'lfc_age' not found
Run rlang::last_error() to see where the error occurred.

rlang::last_error()
Error: object 'rlang::last_error()' not found
rlang::last_error()
<error/rlang_error>
Error in arrange():
! Problem with the implicit transmute() step.
✖ Problem while computing ..1 = lfc_age.
Caused by error in mask$eval_all_mutate():
! object 'lfc_age' not found

Backtrace:

... %>% ...

base::.handleSimpleError(...)

dplyr (local) h(simpleError(msg, call))
Run rlang::last_trace() to see the full context.

I get the above error messages and not sure how to fix it. Please let me know what to do to get rid of the error.

Thank you very much, PAR

Looked in the internet but could not find an answer


问:
How to remove the Google Sign In button backgroud?
I'm creating a auth form with Google Auth but, the button have an background that I don't know how to remove.

Here is my renderButton code:

google.accounts.id.renderButton(
    document.getElementById("buttonDiv"),
    {
      theme: "filled_black",
      locale: i18n.locale.value,
      shape: "square",
      logo_alignment: "left",
      text: "continue_with",
      type: "standard",
      size: "large",
    }
  );
```

Here is the output:
Google Button Output

I tried to create css rules to remove that background but nothing work, the button is rendered into a iframe and, the css that I write can't access this scope.

Body:
I'm creating a auth form with Google Auth but, the button have an background that I don't know how to remove.

Here is my renderButton code:

google.accounts.id.renderButton(
    document.getElementById("buttonDiv"),
    {
      theme: "filled_black",
      locale: i18n.locale.value,
      shape: "square",
      logo_alignment: "left",
      text: "continue_with",
      type: "standard",
      size: "large",
    }
  );

Here is the output:
Google Button Output

I tried to create css rules to remove that background but nothing work, the button is rendered into a iframe and, the css that I write can't access this scope.


问:
Cannot locate ABD.exe file for Emulator
I believe the issue with my emulator is it is not finding my adb, and when I try to find it by running

```<code>which adb
</code>```

I get /Users/$USER/Library/Android/sdk/platform-tools/adb

The unfortunate thing is, the emulator wants a file from my finder, not just a route. When I search my finder, my $USER directory HAS no Library directory inside of it. I also checked my Macintosh/Library directory, but inside of there, there is no Android subdirectory.
Where can I find this? I have no idea where to find this, and evidently my emulator does not either

Title: Cannot locate ABD.exe file for Emulator

Body:
I believe the issue with my emulator is it is not finding my adb, and when I try to find it by running

which adb

I get /Users/$USER/Library/Android/sdk/platform-tools/adb

The unfortunate thing is, the emulator wants a file from my finder, not just a route. When I search my finder, my $USER directory HAS no Library directory inside of it. I also checked my Macintosh/Library directory, but inside of there, there is no Android subdirectory.
Where can I find this? I have no idea where to find this, and evidently my emulator does not either


问:
get the current date for iframe url in PHP
This is my code. I want to pass today's date inside a url in an iframe. but when I load the page the url does not take today's date</p>
```<code><html>
<title>HTML with PHP</title>
<style>
body {
margin: 0px;
}
</style>
<body>
<?php
$date = date("Y-m-d");
echo '<iframe align="center" width="100%" height="100%" src="http://mypage.com/doc.php?date=$date" frameborder="yes" scrolling="yes" name="iframe" id="iframe"> </iframe>';
?>
</body>
</html>
</code>```

Body:
This is my code. I want to pass today's date inside a url in an iframe. but when I load the page the url does not take today's date

<title>HTML with PHP</title>

<?php
$date = date("Y-m-d");
echo ' ';
?>


问:
Build angular app in docker throws error "Could not find the '@angular-devkit/build-angular:browser'"
Having this Dockerfile

```<code>#stage 1
FROM node:14.17.6 AS build

RUN apt-get update

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /usr/src/apps/epb/hms-front-end

ENV PATH /usr/src/apps/epb/hms-front-end/node_modules/.bin:$PATH

RUN npm i -g @angular/cli@14.2.10

COPY package*.json ./

RUN npm i

COPY . .

RUN ng build --configuration production

#stage 2
FROM nginx:alpine

COPY --from=build /usr/src/apps/epb/hms-front-end/dist/hms-frontEnd/ /usr/share/nginx/html

</code>```

at the ng build phase it throws this error:
"
Error: Could not find the '@angular-devkit/build-angular:browser' builder's node package.
"

I've also tried running "RUN npm i @angular-devkit/build-angular" but same error.

Body:
Having this Dockerfile

#stage 1
FROM node:14.17.6 AS build

RUN apt-get update

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /usr/src/apps/epb/hms-front-end

ENV PATH /usr/src/apps/epb/hms-front-end/node_modules/.bin:$PATH

RUN npm i -g @angular/cli@14.2.10

COPY package*.json ./

RUN npm i

COPY . .

RUN ng build --configuration production

#stage 2
FROM nginx:alpine

COPY --from=build /usr/src/apps/epb/hms-front-end/dist/hms-frontEnd/ /usr/share/nginx/html

at the ng build phase it throws this error:
"
Error: Could not find the '@angular-devkit/build-angular:browser' builder's node package.
"

I've also tried running "RUN npm i @angular-devkit/build-angular" but same error.


问:
Add Text, a Button, and Colored Background to Window in Swift
I've used the following Swift 5.6 code to create a simple titled onboarding window. This is the only Swift file I'm using, and this code is not part of an Xcode project or app. I want this file to run in the Terminal and create a window. This code works, but the window simply appears with the title "Onboarding." I want to add some text to the window, make the window bigger, give it a colored background, and create a "Done" button that closes the window. What could I add to this code to add text, a colored background, change the size, and add the close button?

```<code>//
//  Onboarding.swift
//
//
//  Created by Nicholas on 1/10/23.
//

import Foundation
import Cocoa

let nsapp = NSApplication.shared
let appName = ProcessInfo.processInfo.processName
let window = NSWindow.init(contentRect:NSMakeRect(0, 0, 200, 200),
                           styleMask:.titled,backing:NSWindow.BackingStoreType.buffered,defer:false)
window.cascadeTopLeft(from:NSMakePoint(20,20))
window.title = appName;
window.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps:true)
NSApp.run()

</code>```

I've tried searching the Internet, but I can't find anything that doesn't involve using an Xcode project, multiple files, or Info.plist.

This is my window right now:

Body:
I've used the following Swift 5.6 code to create a simple titled onboarding window. This is the only Swift file I'm using, and this code is not part of an Xcode project or app. I want this file to run in the Terminal and create a window. This code works, but the window simply appears with the title "Onboarding." I want to add some text to the window, make the window bigger, give it a colored background, and create a "Done" button that closes the window. What could I add to this code to add text, a colored background, change the size, and add the close button?

//
//  Onboarding.swift
//
//
//  Created by Nicholas on 1/10/23.
//

import Foundation
import Cocoa

let nsapp = NSApplication.shared
let appName = ProcessInfo.processInfo.processName
let window = NSWindow.init(contentRect:NSMakeRect(0, 0, 200, 200),
                           styleMask:.titled,backing:NSWindow.BackingStoreType.buffered,defer:false)
window.cascadeTopLeft(from:NSMakePoint(20,20))
window.title = appName;
window.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps:true)
NSApp.run()

I've tried searching the Internet, but I can't find anything that doesn't involve using an Xcode project, multiple files, or Info.plist.

This is my window right now:


问:
ConvergenceWarning: Liblinear failed to converge, increase the number of iterations. warnings.warn(
I am trying to use Grid-Search-Cross-Validation to find the best value of hyperparameter C. I did split the data set into two subsets contains 50% of the Mnist 784, and used only one of the two subsets with 60% and 40% for training and testing respectively.

```<code>from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split, GridSearchCV

from sklearn.preprocessing import StandardScaler

from sklearn.svm import LinearSVC

import numpy as np

mnist = fetch_openml('mnist_784')
X, y = mnist['data'], mnist['target']

X_1, X_2, y_1, y_2 = train_test_split(X, y, test_size=0.5, random_state=0)

X_train, X_test, y_train, y_test = train_test_split(X_1, y_1, test_size=0.4)

scaler = StandardScaler()

X_train_scaled = scaler.fit_transform(X_train)

X_test_scaled = scaler.transform(X_test)

svm = LinearSVC(dual=False, max_iter=10000)

param_grid = {'C': [10, 5, 1, 0.5, 0.1, 0.05, 0.01, 0.005, 0.001]}

grid = GridSearchCV(svm, param_grid, scoring='accuracy')

grid.fit(X_train_scaled, y_train)

print("Best value of C:", grid.best_params_['C'])

accuracy = grid.score(X_test_scaled, y_test)

print("Test accuracy:", accuracy)
</code>```

I have tried everything without any progress.
I tried minimizing the data and then normalizing it, also tried to increase the max_iter=10000 and 15000.

Body:
I am trying to use Grid-Search-Cross-Validation to find the best value of hyperparameter C. I did split the data set into two subsets contains 50% of the Mnist 784, and used only one of the two subsets with 60% and 40% for training and testing respectively.

from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split, GridSearchCV

from sklearn.preprocessing import StandardScaler

from sklearn.svm import LinearSVC

import numpy as np

mnist = fetch_openml('mnist_784')
X, y = mnist['data'], mnist['target']

X_1, X_2, y_1, y_2 = train_test_split(X, y, test_size=0.5, random_state=0)

X_train, X_test, y_train, y_test = train_test_split(X_1, y_1, test_size=0.4)

scaler = StandardScaler()

X_train_scaled = scaler.fit_transform(X_train)

X_test_scaled = scaler.transform(X_test)

svm = LinearSVC(dual=False, max_iter=10000)

param_grid = {'C': [10, 5, 1, 0.5, 0.1, 0.05, 0.01, 0.005, 0.001]}

grid = GridSearchCV(svm, param_grid, scoring='accuracy')

grid.fit(X_train_scaled, y_train)

print("Best value of C:", grid.best_params_['C'])

accuracy = grid.score(X_test_scaled, y_test)

print("Test accuracy:", accuracy)

I have tried everything without any progress.
I tried minimizing the data and then normalizing it, also tried to increase the max_iter=10000 and 15000.


问:
using rstudioapi in devtools tests
I'm making a package which contains a function that calls rstudioapi::jobRunScript(), and I would like to to be able to write tests for this function that can be run normally by devtools::test(). The package is only intended for use during interactive RStudio sessions.

Here's a minimal reprex:

After calling usethis::create_package() to initialize my package, and then usethis::use_r("rstudio") to create R/rstudio.R, I put:

```<code>foo_rstudio <- function(...) {

  script.file <- tempfile()
  write("print('hello')", file = script.file)
  rstudioapi::jobRunScript(
    path = script.file,
    name = "foo",
    importEnv = FALSE,
    exportEnv = "R_GlobalEnv"
  )
}
</code>```

I then call use_test() to make an accompanying test file, in which I put:

```<code>test_that("foo works", {
  foo_rstudio()
})
</code>```

I then run devtools::test() and get:

I think I understand the basic problem here: devtools runs a separate R session for the tests, and that session doesn't have access to RStudio. I see here that rstudioapi can work inside child R sessions, but seemingly only those "normally launched by RStudio."

I'd really like to use devtools to test my function as I develop it. I suppose I could modify my function to accept an argument passed from the test code which will simply run the job in the R session itself or in some other kind of child R process, instead of an RStudio job, but then I'm not actually testing the normal intended functionality, and if there's an issue which is specific to the rstudioapi::jobRunScript() call and which could occur during normal use, then my tests wouldn't be able to pick it up.

Is there a way to initialize an RStudio process from within a devtools::test() session, or some other solution here?

Title: using rstudioapi in devtools tests

Body:
I'm making a package which contains a function that calls rstudioapi::jobRunScript(), and I would like to to be able to write tests for this function that can be run normally by devtools::test(). The package is only intended for use during interactive RStudio sessions.

Here's a minimal reprex:

After calling usethis::create_package() to initialize my package, and then usethis::use_r("rstudio") to create R/rstudio.R, I put:

foo_rstudio <- function(...) {

  script.file <- tempfile()
  write("print('hello')", file = script.file)
  rstudioapi::jobRunScript(
    path = script.file,
    name = "foo",
    importEnv = FALSE,
    exportEnv = "R_GlobalEnv"
  )
}

I then call use_test() to make an accompanying test file, in which I put:

test_that("foo works", {
  foo_rstudio()
})

I then run devtools::test() and get:

I think I understand the basic problem here: devtools runs a separate R session for the tests, and that session doesn't have access to RStudio. I see here that rstudioapi can work inside child R sessions, but seemingly only those "normally launched by RStudio."

I'd really like to use devtools to test my function as I develop it. I suppose I could modify my function to accept an argument passed from the test code which will simply run the job in the R session itself or in some other kind of child R process, instead of an RStudio job, but then I'm not actually testing the normal intended functionality, and if there's an issue which is specific to the rstudioapi::jobRunScript() call and which could occur during normal use, then my tests wouldn't be able to pick it up.

Is there a way to initialize an RStudio process from within a devtools::test() session, or some other solution here?


问:
Socket.io cannot get a 101 response on Apache server only on localhost
I've been developing a web application using socket.io with Angular 2 NodeJs and Apache, on localhost everything works fine, but when I deploy my app and test it on the server I cannot get a 101 response, when the app starts a http request is made automatically by socket.io library that returns a socket id, but then it send another request that supposed to return a 101 response as ocurred on localhost but instead it returns a 400 bad request, I've been struggling with this error and I honestly don't know how to solved it after many tries configuring the virtualhost on my server I almost give up.

This is on localhost:

https://i.stack.imgur.com/PxLEN.png

and this is on my server:

https://i.stack.imgur.com/SKUqH.jpg

https://i.stack.imgur.com/10eMz.jpg

https://i.stack.imgur.com/dok4n.jpg

https://i.stack.imgur.com/KXdf5.jpg

This is my vistualhost config.

     ProxyPass               /sck-srv http://localhost:3007/sck-srv
     ProxyPassReverse        /sck-srv http://localhost:3007/sck-srv
     ProxyPass                      /sck-srv ws://127.0.0.1:3007 retry=0 keepalive=On
     ProxyPassReverse        /sck-srv ws://127.0.0.1:3007 retry=0

VirtualHost port 443

I appreciate your help


问:
Custom JSON API search using operator "site"
I need to check several hundred websites/pages a day for the presence of a Google index, in fact, I need an imitation of site:something.com. I use Custom Search JSON API
`

```<code>$search_query = http_build_query(
      array(
          "key" => $api_key,
          "cx" => $search_id,
          "q" => "site:".$link,
          "num" => "10",
          "safe" => "off"
      )
  );

  $json = file_get_contents("https://www.googleapis.com/customsearch/v1?" . $search_query);
  $data = json_decode($json, true);
</code>```

`

and often in the response it shows that there are no results, although the site is in the index. Checked "handles" through Google itself.

What could be the problem/error?

if you send the query "q" => "site:mysite.com" through the script, then there are no results in the response (variable and items in the response), but if site:mysite.com is entered in the search string, then the site is found.

tested through
https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list?apix=true&apix_params=%7B%22cx%22%3A%22df93080fceb189de3%22%2C%22q%22%3A%22site%3Ahttps%3A%2F%2Fonodo.org%2Fvisualizations%2F208836%22%2C%22safe%22%3A%22off%22%7D

expected 1 result but API returned 0 results

Body:
I need to check several hundred websites/pages a day for the presence of a Google index, in fact, I need an imitation of site:something.com. I use Custom Search JSON API
`

$search_query = http_build_query(
      array(
          "key" => $api_key,
          "cx" => $search_id,
          "q" => "site:".$link,
          "num" => "10",
          "safe" => "off"
      )
  );

  $json = file_get_contents("https://www.googleapis.com/customsearch/v1?" . $search_query);
  $data = json_decode($json, true);

`

and often in the response it shows that there are no results, although the site is in the index. Checked "handles" through Google itself.

What could be the problem/error?

if you send the query "q" => "site:mysite.com" through the script, then there are no results in the response (variable and items in the response), but if site:mysite.com is entered in the search string, then the site is found.

tested through
https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list?apix=true&apix_params=%7B%22cx%22%3A%22df93080fceb189de3%22%2C%22q%22%3A%22site%3Ahttps%3A%2F%2Fonodo.org%2Fvisualizations%2F208836%22%2C%22safe%22%3A%22off%22%7D

expected 1 result but API returned 0 results


问:
SQL query to create feed file with special format
I create a sql query to create a feed file, my issue is that the file have a header and detail. The studen ID is the header and the classes are the detail

```<code>Select st.student_id, st.academics_year, st.academic_term, cl.class, cl.schedule, cl.days
from student_term st
left join on classes cl on cl.year = st.academic_year and cl.term=st.academics_term
</code>```

My query results :

```<code>12345 2022 spring mat01, 08:00 to 09:00 TW
12345 2022 spring fin101, 10:00 to 11:00 MF
12345 2022 spring bio101, 14:00 to 15:00 MF
</code>```

What I need :

```<code>12345
mat01, 08:00 to 09:00 TW
fin101, 10:00 to 11:00 MF
bio101, 14:00 to 15:00 MF

    result
seq type  linetex
1    0    12345
1    0    45678
1    0    98765
1    1    mat131  08:00 to 09:00
1    1    lit131  08:00 to 09:00
1    1    bio131  09:00 to 10:00
</code>```

Body:
I create a sql query to create a feed file, my issue is that the file have a header and detail. The studen ID is the header and the classes are the detail

Select st.student_id, st.academics_year, st.academic_term, cl.class, cl.schedule, cl.days
from student_term st
left join on classes cl on cl.year = st.academic_year and cl.term=st.academics_term

My query results :

12345 2022 spring mat01, 08:00 to 09:00 TW
12345 2022 spring fin101, 10:00 to 11:00 MF
12345 2022 spring bio101, 14:00 to 15:00 MF

What I need :

12345
mat01, 08:00 to 09:00 TW
fin101, 10:00 to 11:00 MF
bio101, 14:00 to 15:00 MF

    result
seq type  linetex
1    0    12345
1    0    45678
1    0    98765
1    1    mat131  08:00 to 09:00
1    1    lit131  08:00 to 09:00
1    1    bio131  09:00 to 10:00


问:
Torch's transformer for generation / inference
Here are a few questions related to Transformers masks in pytorch.

My model will need to be auto-regressive. I understand that this is possible. In the original paper and here, is is well discussed that "
The normal Transformer decoder is autoregressive at inference time and non-autoregressive at training time."

My model will have a very specific type of generation pattern, which does not really exist in the literature: during training, the whole input and output sequences are known. But during generation, I will use each output (a choice of direction) to prepare the next input point (a small patch of image at this coordinate), starting from a random patch. This is similar to the image below, but the inputs would be some function of y; x(^y<t>). This was easy to do using RNNs. I am not sure how to translate this to Transformers, using the description of masks in the doc or in this answer.

I'm a bit lost concerning the masks:

At each iteration of the generation process, I only know one more input point than output point.  My guess is that I could maybe use src_mask = torch.triu([...], diagonal=1)?

The target given as input to the decoder is usually shifted. Here too, for the first src (a patch), the input to the decoder should be some type of "start of sequence" token. However, I work with continuous values (real-value coordinates), not with dictionaries of words, as we always see in every example. My guess is that instead I could maybe use tgt_mask = torch.triu([...], diagonal=0), meaning that at the first step, the mask will simply be False?

Considering my specific needs, I will prepare my own loop to infer each point one after the other. I know that there are examples on the web, but they run the whole sequence only to get the last point. Memory is as challenge for me. Is there a way that I can use torch's model to output only the last point at each iteration? I saw something about it in huggingface, where they return the hidden state, but no example on how to use them, and also, so far, I was using the torch.nn.modules.transformer, I am a little more familiar. Is is possible using torch's rnn modules?

Thank you!


问:
Sequelize seed error: ECONNREFUSED 127.0.0.1:5432 using docker with postgreSQL
I'm trying to seed my PostgreSQL database in a docker container with my express.js app, using sequelize.

docker-compose:

```<code>version: '3'
services:
  app:
    build: .
    ports:
      - 3001:3001
    environment:
      DATABASE_URL: ${DATABASE_URL}
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_HOST: ${POSTGRES_HOST}
      POSTGRES_PORT: ${POSTGRES_PORT}
    links:
      - db
  db:
    image: postgres:14.2
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_HOST: ${POSTGRES_HOST}
    ports:
      - 5432:5432

</code>```

Dockerfile:

```<code>FROM node:18
WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

CMD ["npm", "start"]
</code>```

config.js

```<code>module.exports = {
  development: {
    username: process.env.POSTGRES_USER,
    password: process.env.POSTGRES_PASSWORD,
    database: process.env.POSTGRES_DB,
    host: process.env.POSTGRES_HOST,
    port: process.env.POSTGRES_PORT,
    dialect: 'postgres',
  },

  test: {
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.POSTGRES_HOST,
    port: process.env.DB_PORT,
    dialect: 'postgres',
  },

  production: {
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.POSTGRES_HOST,
    port: process.env.DB_PORT,
    dialect: 'postgres',
  },
}
</code>```

.sequelizerc

```<code>const path = require('path');

module.exports = {
  config: path.resolve('./config', 'config.js'),
  'models-path': path.resolve('./database/models'),
  'seeders-path': path.resolve('./database/seeders'),
  'migrations-path': path.resolve('./database/migrations'),
};
</code>```

.env

```<code>POSTGRES_USER=user
POSTGRES_PASSWORD=password
POSTGRES_DB=db
POSTGRES_HOST=db
POSTGRES_PORT=5432
DATABASE_URL="postgres://user:password@db:5432/db"
</code>```

models/index.js

```<code>const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const { DataTypes } = require('sequelize')
const { execSync } = require('child_process')

const basename = path.basename(__filename)

const sequelize = new Sequelize(process.env.DATABASE_URL, {
  dialect: 'postgres',
  timezone: '-03:00',
  sync: { alter: { drop: true } },
})

const models = { sequelize, Sequelize }

fs.readdirSync(__dirname)
  .filter((file) => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js')
  .forEach((file) => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes)
    models[model.name] = model
  })

Object.keys(models).forEach((modelName) => {
  models[modelName].associate?.(models)
})

if (process.env.DEVELOPMENT === 'TRUE' && process.env.CREATE_DROP === 'TRUE') {
  (async () => {
    await sequelize.sync()
    if (process.env.WILL_SEED === 'TRUE') {
      try {
        console.log(execSync('npx sequelize-cli db:seed --seed seed.js', { encoding: 'utf-8' }))
      } catch (err) {
        console.log(err)
      }
    }
  })()
}

module.exports = models
</code>```

My folder structure

The sync() method of sequelize is executed, the database and tables are created, but when the npx sequelize-cli db:seed --seed seed.js command runs, the following error occurs:
ERROR: connect ECONNREFUSED 127.0.0.1:5432. It appears that it's trying to connect with localhost, but the host env variable is set to the service's name db.

Body:
I'm trying to seed my PostgreSQL database in a docker container with my express.js app, using sequelize.

docker-compose:

version: '3'
services:
  app:
    build: .
    ports:
      - 3001:3001
    environment:
      DATABASE_URL: ${DATABASE_URL}
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_HOST: ${POSTGRES_HOST}
      POSTGRES_PORT: ${POSTGRES_PORT}
    links:
      - db
  db:
    image: postgres:14.2
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_HOST: ${POSTGRES_HOST}
    ports:
      - 5432:5432

Dockerfile:

FROM node:18
WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

CMD ["npm", "start"]

config.js

module.exports = {
  development: {
    username: process.env.POSTGRES_USER,
    password: process.env.POSTGRES_PASSWORD,
    database: process.env.POSTGRES_DB,
    host: process.env.POSTGRES_HOST,
    port: process.env.POSTGRES_PORT,
    dialect: 'postgres',
  },

  test: {
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.POSTGRES_HOST,
    port: process.env.DB_PORT,
    dialect: 'postgres',
  },

  production: {
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.POSTGRES_HOST,
    port: process.env.DB_PORT,
    dialect: 'postgres',
  },
}

.sequelizerc

const path = require('path');

module.exports = {
  config: path.resolve('./config', 'config.js'),
  'models-path': path.resolve('./database/models'),
  'seeders-path': path.resolve('./database/seeders'),
  'migrations-path': path.resolve('./database/migrations'),
};

.env

POSTGRES_USER=user
POSTGRES_PASSWORD=password
POSTGRES_DB=db
POSTGRES_HOST=db
POSTGRES_PORT=5432
DATABASE_URL="postgres://user:password@db:5432/db"

models/index.js

const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const { DataTypes } = require('sequelize')
const { execSync } = require('child_process')

const basename = path.basename(__filename)

const sequelize = new Sequelize(process.env.DATABASE_URL, {
  dialect: 'postgres',
  timezone: '-03:00',
  sync: { alter: { drop: true } },
})

const models = { sequelize, Sequelize }

fs.readdirSync(__dirname)
  .filter((file) => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js')
  .forEach((file) => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes)
    models[model.name] = model
  })

Object.keys(models).forEach((modelName) => {
  models[modelName].associate?.(models)
})

if (process.env.DEVELOPMENT === 'TRUE' && process.env.CREATE_DROP === 'TRUE') {
  (async () => {
    await sequelize.sync()
    if (process.env.WILL_SEED === 'TRUE') {
      try {
        console.log(execSync('npx sequelize-cli db:seed --seed seed.js', { encoding: 'utf-8' }))
      } catch (err) {
        console.log(err)
      }
    }
  })()
}

module.exports = models

My folder structure

The sync() method of sequelize is executed, the database and tables are created, but when the npx sequelize-cli db:seed --seed seed.js command runs, the following error occurs:
ERROR: connect ECONNREFUSED 127.0.0.1:5432. It appears that it's trying to connect with localhost, but the host env variable is set to the service's name db.


问:
How to secure access to a REST api in conjunction with a jwt/bearer token?
I have a scenario and need advice on how to proceed.
I have built a service that acts as a middleman between multiple front end applications and other backend applications. The reason for this design is that there needs to be some calls made from the frontend that cannot speak directly to some of the backend apps (for various reasons) thus the middleman service was created.

MM = middleman service for brevity.
FEA = frontend apps
BES = backend services

Right now the FEA's gain access the the MM by passing encrypted credentials over a POST request and the MM returns a signed JWT and then the FEA's use the bearer token return to make subsequent calls into the MM to then access the BES's.

The silly part is that anyone who gains access to the Bearer token can make calls to the MM.

Is there a way to ensure that the calls comin in from any FEA's to the MM are further locked down so that not just anyone with the Bearer token can continue to then make requests to the BEA's via the MM?

I have CORS in place that only allow specific origins.

Thanks.


问:
How do I send product data from sub domain to main and order data visa versa
How do I send product data from sub domain to main and order data visa versa in wordpress?</p>


问:
Clickable Components within Parallax Layer with React-Spring not working?
I am trying to build a nav bar into one of my Parallax Layers in react using React Spring. The nav bar buttons are not clickable, and I am confused as to why. I have been searching around for a while, but am not able to find documentation on how to get components to function within Parallax Layers. Thanks!

my nav bar component
`

```<code>function NavBar() {

    const clicked = () => {
        return(
            console.log('clicky clacky')
        )
    }

    return (
        <div>

            <nav className="layer">
                <button onClick={clicked} className="button">Daily Facts</button>
                <button onClick={clicked} className="button">Alien Town</button><button onClick={clicked} className="button">Another Dimension</button>
            </nav>
        </div>
    );
}

export default NavBar;
</code>```

my app component with all the parallax layers, the nav bar component is placed all the way at the bottom

```<code>
import { Parallax, ParallaxLayer } from "@react-spring/parallax";
import moon from "./pixil-layer-Moon.png"
import stars1 from "./pixil-layer-2.png"
import stars2 from "./pixil-layer-3.png"
import ufo from "./pixil-layer-4.png"
import planet from "./planet.png"
import { Link } from "react-router-dom"
import NavBar from "./NavBar";

function Homepage() {

    return (
        <div>
            <Parallax pages={4}>

                <ParallaxLayer
                    offset={0}
                    factor={4}
                    style={{
                        backgroundImage: `url(${moon})`,
                        backgroundSize: 'cover'
                    }}
                >
                </ParallaxLayer>

                <ParallaxLayer
                    offset={0}
                    factor={4}
                    speed={.5}
                    style={{
                        backgroundImage: `url(${planet})`,
                        backgroundSize: 'cover',
                    }}
                >
                </ParallaxLayer>

                <ParallaxLayer
                    offset={0}
                    speed={.5}
                    factor={3}
                    style={{
                        backgroundImage: `url(${stars1})`,
                        backgroundSize: 'cover'
                    }}
                >
                </ParallaxLayer>

                <ParallaxLayer
                    offset={0}
                    speed={2}
                    factor={4}
                    style={{
                        backgroundImage: `url(${stars2})`,
                        backgroundSize: 'cover'
                    }}
                >
                </ParallaxLayer>

                <ParallaxLayer
                    sticky={{ start: 0, end: 3 }}
                >
                    <img style={{ width: '1500px', height: 'auto' }} src={ufo} />
                </ParallaxLayer>

                <ParallaxLayer
                    offset={3}
                    speed={.5}
                >
                    <div className="text">
                        <h1>Space Is The Place!</h1>
                    </div>
                    <NavBar />
                </ParallaxLayer>
            </Parallax>
        </div>
    );
}

export default Homepage`
</code>```

Body:
I am trying to build a nav bar into one of my Parallax Layers in react using React Spring. The nav bar buttons are not clickable, and I am confused as to why. I have been searching around for a while, but am not able to find documentation on how to get components to function within Parallax Layers. Thanks!

my nav bar component
`

function NavBar() {

    const clicked = () => {
        return(
            console.log('clicky clacky')
        )
    }

    return (

                <button onClick={clicked} className="button">Daily Facts</button>
                <button onClick={clicked} className="button">Alien Town</button><button onClick={clicked} className="button">Another Dimension</button>

    );
}

export default NavBar;

my app component with all the parallax layers, the nav bar component is placed all the way at the bottom

import { Parallax, ParallaxLayer } from "@react-spring/parallax";
import moon from "./pixil-layer-Moon.png"
import stars1 from "./pixil-layer-2.png"
import stars2 from "./pixil-layer-3.png"
import ufo from "./pixil-layer-4.png"
import planet from "./planet.png"
import { Link } from "react-router-dom"
import NavBar from "./NavBar";

function Homepage() {

    return (

            <Parallax pages={4}>

                <ParallaxLayer
                    offset={0}
                    factor={4}
                    style={{
                        backgroundImage: `url(${moon})`,
                        backgroundSize: 'cover'
                    }}
                >
                </ParallaxLayer>

                <ParallaxLayer
                    offset={0}
                    factor={4}
                    speed={.5}
                    style={{
                        backgroundImage: `url(${planet})`,
                        backgroundSize: 'cover',
                    }}
                >
                </ParallaxLayer>

                <ParallaxLayer
                    offset={0}
                    speed={.5}
                    factor={3}
                    style={{
                        backgroundImage: `url(${stars1})`,
                        backgroundSize: 'cover'
                    }}
                >
                </ParallaxLayer>

                <ParallaxLayer
                    offset={0}
                    speed={2}
                    factor={4}
                    style={{
                        backgroundImage: `url(${stars2})`,
                        backgroundSize: 'cover'
                    }}
                >
                </ParallaxLayer>

                <ParallaxLayer
                    sticky={{ start: 0, end: 3 }}
                >

                </ParallaxLayer>

                <ParallaxLayer
                    offset={3}
                    speed={.5}
                >

Space Is The Place!

                    <NavBar />
                </ParallaxLayer>
            </Parallax>

    );
}

export default Homepage`


问:
Rust Scan function detailed usage explanation
This a code solution for the problem Delete and Earn, however, I fail to grasp the scan loop part.

The problem states the following.

```<code>You are given an integer array nums.You want to maximize the number of points you get by
 performing the following operation any number of times:

Pick any nums[i] and delete it to earn nums[i] points. Afterwards,
you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
Return the maximum number of points you can earn by applying the above operation some number of times.
</code>```
```<code>use std::collections::HashMap;
impl Solution {
    pub fn delete_and_earn(mut nums: Vec<i32>) -> i32 {
        let (min, max, counts) =
            nums.into_iter()
                .fold((0, 0, HashMap::new()), |(min, max, mut counts), n| {
                    *counts.entry(n).or_insert(0) += 1;
                    (min.min(n), max.max(n), counts)
        });;
        (min..=max)
            .filter_map(|n| counts.get(&n).map(|count| (n, count)))
            .scan((0, 0, 0), |(a, b, m),(n, count)| {
                let prev_max = *a.max(b);
                *a = if *m == n - 1 { *b } else { prev_max } + n * count;
                *b = prev_max;
                *m = n;

                Some(*a.max(b))
            })
            .last()
            .expect("invariant violation")
    }
}

</code>```

Body:
This a code solution for the problem Delete and Earn, however, I fail to grasp the scan loop part.

The problem states the following.

You are given an integer array nums.You want to maximize the number of points you get by
 performing the following operation any number of times:

Pick any nums[i] and delete it to earn nums[i] points. Afterwards,
you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
Return the maximum number of points you can earn by applying the above operation some number of times.

use std::collections::HashMap;
impl Solution {
    pub fn delete_and_earn(mut nums: Vec<i32>) -> i32 {
        let (min, max, counts) =
            nums.into_iter()
                .fold((0, 0, HashMap::new()), |(min, max, mut counts), n| {
                    *counts.entry(n).or_insert(0) += 1;
                    (min.min(n), max.max(n), counts)
        });;
        (min..=max)
            .filter_map(|n| counts.get(&n).map(|count| (n, count)))
            .scan((0, 0, 0), |(a, b, m),(n, count)| {
                let prev_max = *a.max(b);
                *a = if *m == n - 1 { *b } else { prev_max } + n * count;
                *b = prev_max;
                *m = n;

                Some(*a.max(b))
            })
            .last()
            .expect("invariant violation")
    }
}


问:
How can I access a directory outwith my programs with Flutter?
I am trying to list the files of a directory on Android through flutter, I am using file_picker to access it but it lists nothing even for a directory full of files.

I have tried opening a directory with files in it and printing it out:

void _pickDirectory() async {
  final path = await FilePicker.platform.getDirectoryPath();
  if (path == null) {
    print('Canceled');
  } else {
    final directory = Directory(path);
    final files = directory.listSync();
    print(files);
  }
}
```
<p>but it just prints out an empty array.
I've added</p>
<pre class="lang-xml prettyprint-override"><code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

to my android/app/src/main/AndroidManifest.xml and reinstalled the app but it still shows no files.

Any help is appreciated, thank you

Body:
I am trying to list the files of a directory on Android through flutter, I am using file_picker to access it but it lists nothing even for a directory full of files.

I have tried opening a directory with files in it and printing it out:

void _pickDirectory() async {
  final path = await FilePicker.platform.getDirectoryPath();
  if (path == null) {
    print('Canceled');
  } else {
    final directory = Directory(path);
    final files = directory.listSync();
    print(files);
  }
}

but it just prints out an empty array.
I've added

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

to my android/app/src/main/AndroidManifest.xml and reinstalled the app but it still shows no files.

Any help is appreciated, thank you


问:
How to Fix VSCode Syntax Highlighting for Variables Python
In VSCode, my syntax highlighting for variables occasionally disables. After experimentation, it seems to happen mostly when I'm working on WSL. I haven't found a solid way to recreate it, but I've noticed it happening (not all the time, but sometimes) when performing any action that would temporarily render the variable as plaintext/not a variable. For example, temporarily removing the "=" when defining the variable.

To fix it, I can restart/reload VSCode, but it just gets pretty inconvenient considering it happens once every 30 minutes, if not more often. My theme is Dark+ and it normally looks like the first image (blue highlighted variables), but whenever this bug happens, it looks like the second (unhighlighted; white text).

It also happens when defining functions. Not sure if it happens to anything else at this point.

I've tried resetting my VSCode, reinstalling all extensions, deleting the "Code" folder in %appdata%, as well as deleting ".vscode" in %userprofile%.

When I hover over the variable, it is still recognized as a variable; it just is not highlighted.

My extensions are:

C/C++

C#

Discord Presence

GitHub Pull Requests and Issues

gitignore

HTML CSS Support

isort

Jupyter

Jupyter Cell Tags

Jupyter Keymap

Jupyter Notebook Renderers

Jupyter Slide Show

Live Server

Pylance

Python

GitHub Codespaces

WSL

What it looks like when the bug happens

What it should look like


问:
AudioPlayer+Playback seek() doesn't preserve stopped/paused player status and always ends up playing. Expected behavior?
When I call seek(time) on a stopped AudioPlayer node, it seeks and then triggers the node to start playing.  Is this expected behavior?

Looking at the source for seek() it seems that this is the intent; but, I don't understand why this function would choose to ignore the player state going into the seek.

```<code>func seek(time seekTime: TimeInterval) {
        ...
        isSeeking = true
        playerNode.stop()

        playerNode.scheduleSegment(
            file,
            startingFrame: startFrame,
            frameCount: frameCount,
            at: nil,
            completionCallbackType: .dataPlayedBack
        ) { _ in
            self.internalCompletionHandler()
        }

        playerNode.play()
        status = .playing
        isSeeking = false
        timeBeforePlay = editStartTime - startTime
    }
</code>```

Is there another seek option that I haven't found?  Or, need I fork the repo and modify this to suit my needs?

Body:
When I call seek(time) on a stopped AudioPlayer node, it seeks and then triggers the node to start playing.  Is this expected behavior?

Looking at the source for seek() it seems that this is the intent; but, I don't understand why this function would choose to ignore the player state going into the seek.

func seek(time seekTime: TimeInterval) {
        ...
        isSeeking = true
        playerNode.stop()

        playerNode.scheduleSegment(
            file,
            startingFrame: startFrame,
            frameCount: frameCount,
            at: nil,
            completionCallbackType: .dataPlayedBack
        ) { _ in
            self.internalCompletionHandler()
        }

        playerNode.play()
        status = .playing
        isSeeking = false
        timeBeforePlay = editStartTime - startTime
    }

Is there another seek option that I haven't found?  Or, need I fork the repo and modify this to suit my needs?


问:
Difference between setting up Routes in Laravel vs API Gateway
I'm having some trouble determining the difference between Routing on a traditional web programming framework and API gateway. Let's say if I setup a Laravel web app and define routes in it as follows:

Route: GET `/area' -> Returns all hotels in a specific area

Route: GET '/hotel' -> Returns details of a specific hotel with ID

Route: POST '/hotel' -> Accepts JSON object (with Hotel details) and creates the hotel in my database

So basically, I have one API and three HTTP endpoints. Since this is defined in my programming language for my web app, why would I need an API gateway? What is the difference between defining routes in my programming language and creating routes on the API gateway? Are API gateways only used for serverless architectures?

Since my API won't be accessed by any other website, is an API key even necessary?

I tried creating routes in a serverless architecture and using Lambdas to resolve my APIs but I'm finding it difficult to understand why/when an API gateway becomes relevant.


问:
How to sync data between PostgreSQL primary and read-only archive replica
I want to setup PostgreSQL databases in a way that the one (primary) server receives data from multiple agents, does some post-processing and regularly syncs to read-only (archive) replica. The sync does not have to be real-time. The replica server is used to feed the processed data to other clients.

The idea is that the replica will keep a complete database in the historical sense but the primary will keep all data from all agents (before some aggregation etc).

The primary server would ideally keep only part of the database e.g. last month.

The more I think about it, the term replica is not correct here.

What I probably need is to setup a procedure (for the aggregation etc.) and as a last step send the resulted data the 'replica' and delete portion of the primary DB.

Is there a better term for my use case?


问:
How to create webpack 'bundle.js' with different websocket port for SpringBootTest
I'm running Spring Boot on the backend on port 8080 and a typescript application in the browser that needs to communicate with the server via WebSocket, also via http://localhost:8080

I also have a @SpringBootTest Selenium Integration Test to test the web app, but currently I am forced to shut down the running development server before running the Selenium Test, because otherwise the test complains that port 8080 is already in use.

I'm using frontend-maven-plugin to bundle the typescript code into bundle.js with webpack --mode production. bundle.js lives inside src/main/resources/static and contains a references to http://localhost:{port} for the websocket. the {port} number is currently replaced inside bundle.js thanks to an environment variable available to webpack during the build of bundle.js.

I'm using maven-surefire-plugin to run the @SpringBootTest.

Now, my question is, how can I have mvn package both:

create the regular bundle.js with port 8080 for use in both development and production,

AND at the same time run the SpringBootTest with port 8081 for both the server and the selenium browser/websocket?

Or, what alternative configuration would you choose to allow you to run the server on port 8080 during development, and sporadically also run the whole mvn clean package without needing to first shut down the development server to avoid getting an error that port 8080 is already in use?


问:
Github account login without SSH key or Two Factor Auth
I have Two-factor authentication enabled on my Github account so that an authentication code is sent to my phone and from there I can login with that code. However, I just got a new phone, and all of my two-factor authenticator (Google Authenticator) app data was cleared. To add back the github account to my Authenticator, I need a QR code only accessed by being logged into github.

I clicked on Recover my Account, verified my email with a temporary code, and got to step 2 which is...'Verify a device, SSH key or personal access token'. The only option the screen gives me is to verify via SSH. However, since I have a new laptop, my SSH key I just created isn't the one that is linked to my account in Github. I never saved any of the recovery codes either. Hopefully I'm not totally out of luck?


问:
How do I get Cors to work with JavaScript - fix?
I can submit successfully with cURL on Command Line and get a response. Not so with JavaScipt in a browser. I'm rusty on JavaScript but really need this to work with several pieces of selectable data and to submit with a voice audio sample which IBM says won't work with cURL, just JavaScript. No audio is submitted in this code below just to keep it simple. I have access to the Github SDK but haven't found an answer. Any help would be appreciated.

The working cURL code is:
curl -X POST -u "apikey:blahblahblah" --header "Content-Type: application/json; charset: utf-8" --header "Accept: audio/wav" --data "{\"text\":\"Hello world\"}" --output text.wav "https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/eace7388-5b0e-4111-a735-7c1364546698/v1/synthesize?voice=en-US_MichaelV3Voice"

With JavaScript:
I get this error code with or without Access-Control, or no-cors, or *, gives this error: "from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

I also get an Unauthorized error from IBM on user id, which is supposed to be there even though it isn't in cURL, but supposedly any variable will work.

This JavaScript submits a text to voice request to IBM Watson and returns audio. Don't laugh - here is my code:

```<code>    const myHeaders = new Headers();
        myHeaders.append('Content-Type', 'application/json');
        /*myHeaders.append('Access-Control-Allow-Origin', '*');*/
        myHeaders.append('customer_id', 'blah');
        myHeaders.append('Accept', 'audio/wav');
        myHeaders.append('charset', 'UTF-8');

    fetch('https://api.us-south.speech-to-text.watson.cloud.ibm.com/instances/v1/synthesize?voice=en-US_MichaelV3Voice'), {
      apikey: "blahblahblah",
      method: "POST",
      data: "{\"text\":\"Hello world\"}",
      output: "text.wav",
      headers: {myHeaders},
      };
</code>```

I've tried:
myHeaders.append('Access-Control-Allow-Origin', '*'); this is a wildcard
myHeaders.append('Access-Control-Allow-Origin', 'no-cors');
And leaving this access control header out

Body:
I can submit successfully with cURL on Command Line and get a response. Not so with JavaScipt in a browser. I'm rusty on JavaScript but really need this to work with several pieces of selectable data and to submit with a voice audio sample which IBM says won't work with cURL, just JavaScript. No audio is submitted in this code below just to keep it simple. I have access to the Github SDK but haven't found an answer. Any help would be appreciated.

The working cURL code is:
curl -X POST -u "apikey:blahblahblah" --header "Content-Type: application/json; charset: utf-8" --header "Accept: audio/wav" --data "{\"text\":\"Hello world\"}" --output text.wav "https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/eace7388-5b0e-4111-a735-7c1364546698/v1/synthesize?voice=en-US_MichaelV3Voice"

With JavaScript:
I get this error code with or without Access-Control, or no-cors, or *, gives this error: "from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

I also get an Unauthorized error from IBM on user id, which is supposed to be there even though it isn't in cURL, but supposedly any variable will work.

This JavaScript submits a text to voice request to IBM Watson and returns audio. Don't laugh - here is my code:

    const myHeaders = new Headers();
        myHeaders.append('Content-Type', 'application/json');
        /*myHeaders.append('Access-Control-Allow-Origin', '*');*/
        myHeaders.append('customer_id', 'blah');
        myHeaders.append('Accept', 'audio/wav');
        myHeaders.append('charset', 'UTF-8');

    fetch('https://api.us-south.speech-to-text.watson.cloud.ibm.com/instances/v1/synthesize?voice=en-US_MichaelV3Voice'), {
      apikey: "blahblahblah",
      method: "POST",
      data: "{\"text\":\"Hello world\"}",
      output: "text.wav",
      headers: {myHeaders},
      };

I've tried:
myHeaders.append('Access-Control-Allow-Origin', '*'); this is a wildcard
myHeaders.append('Access-Control-Allow-Origin', 'no-cors');
And leaving this access control header out


问:
Map one dataframe to other dataframe (pandas)
I would like to map the values in df1 dataframe to the df2 dataframe.

df:

id
name

1001
john

1002
amy

1003
jim

df2:

name
salary
department

john
2000
A

amy
3000
B

jim
4000
C

john
5000
D

jim
6000
E

amy
7000
F

Output should be like this ,df3:

name
id
salary
department

john
1001
2000
A

amy
1002
3000
B

jim
1003
4000
C

john
1001
5000
D

jim
1003
6000
E

amy
1002
7000
F


问:
How do I not call a function?
I think it's obvious that I just won't call it, but I am trying to create an exception if it returns "None". I have my code here:

```<code>    if self.config["data-validation"]["RULES"]["RULE_UNIQUE_VALIDATION"]["UNIQUE_VALIDATION"]:
        self.logger.info("******* RULE_UNIQUE_VALIDATION VALIDATION ENABLED ******* ")
        db_total_table_unique_count_dict={}
        s3_total_table_unique_count_dict={}
        db_total_table_unique_count_dict=self.getDBUniqueValueCounts(db_total_table_unique_count_dict)
        s3_total_table_unique_count_dict=self.getS3UniqueValueCounts(s3_total_table_unique_count_dict)
        ret_unique_counts=SourceValidation.findDiff(db_total_table_unique_count_dict,s3_total_table_unique_count_dict,"UNIQUE_COUNT_COMPARISON")
        ret_unique_counts['db_unique_counts']=db_total_table_unique_count_dict
        ret_unique_counts['s3_unique_counts']=s3_total_table_unique_count_dict
        data_validation={}
        data_validation.update({"VALIDATION_TYPE":"UNIQUE_COUNT"})
        data_validation.update({"DATABASE":db_name})
        data_validation.update({"RUN_TIMESTAMP":self.run_time_stamp})

        if ret_unique_counts is not None:

            if ret_unique_counts["UNIQUE_COUNT_COMPARISON"].get(self.table)["RESULT"]==False:
                data_validation.update({"TABLES": {list(ret_unique_counts["UNIQUE_COUNT_COMPARISON"].keys())[0]:{"NON_BATCH_VALIDATION":{"FAILED":not bool(ret_unique_counts["UNIQUE_COUNT_COMPARISON"][self.table]["RESULT"]),"FAILURE_MSG":"counts do not match DB UNIQUE COUNT: "+str(ret_unique_counts['db_unique_counts']) +" S3 UNIQUE COUNT: "+str(ret_unique_counts['s3_unique_counts'])}}}})
            else:
                data_validation.update({"TABLES": {list(ret_unique_counts["UNIQUE_COUNT_COMPARISON"].keys())[0]:{"NON_BATCH_VALIDATION":{"FAILED":not ret_unique_counts["UNIQUE_COUNT_COMPARISON"][self.table]["RESULT"],"FAILURE_MSG":"counts  match DB UNIQUE COUNT: "+str(ret_unique_counts['db_unique_counts']) +" S3 UNIQUE COUNT: "+str(ret_unique_counts['s3_unique_counts'])}}}})
                self.writeReportsToS3("UNIQUE_COUNT_COMPARISON",data_validation,"datavalidation/reporting/"+"UNIQUE_COUNT_COMPARISON"+"/"+key)

    else:
        self.logger.info("******* UNIQUE COUNT VALIDATION IS DISABLED ******* ")
</code>```

The error I am getting is:

```<code>    if ret_unique_counts["UNIQUE_COUNT_COMPARISON"].get(self.table)["RESULT"]==False:
TypeError: 'NoneType' object is not subscriptable
</code>```

So I basically want to not call the function "findDiff" if it returns "None". I'm not sure how to do that, so I thought I can continue my "if" statement if it returns "None" anyway, to skip over it by writing if ret_unique_counts is not None:. I tried that and it still throws the same error. I'm not sure what else to do. I don't want to take out "findDiff" because I have a list of tables it iterates through, but if one isn't there I want it to skip over it.

UPDATE--------------------------------------

I updated my code like this:

```<code>    if self.config["data-validation"]["RULES"]["RULE_UNIQUE_VALIDATION"]["UNIQUE_VALIDATION"]:
        self.logger.info("******* RULE_UNIQUE_VALIDATION VALIDATION ENABLED ******* ")
        db_total_table_unique_count_dict={}
        s3_total_table_unique_count_dict={}
        db_total_table_unique_count_dict=self.getDBUniqueValueCounts(db_total_table_unique_count_dict)
        s3_total_table_unique_count_dict=self.getS3UniqueValueCounts(s3_total_table_unique_count_dict)
        ret_unique_counts=SourceValidation.findDiff(db_total_table_unique_count_dict,s3_total_table_unique_count_dict,"UNIQUE_COUNT_COMPARISON")
        ret_unique_counts['db_unique_counts']=db_total_table_unique_count_dict
        ret_unique_counts['s3_unique_counts']=s3_total_table_unique_count_dict
        data_validation={}
        data_validation.update({"VALIDATION_TYPE":"UNIQUE_COUNT"})
        data_validation.update({"DATABASE":db_name})
        data_validation.update({"RUN_TIMESTAMP":self.run_time_stamp})
        if not ret_unique_counts:
            if ret_unique_counts["UNIQUE_COUNT_COMPARISON"].get(self.table)["RESULT"]==False:
                    data_validation.update({"TABLES": {list(ret_unique_counts["UNIQUE_COUNT_COMPARISON"].keys())[0]:{"NON_BATCH_VALIDATION":{"FAILED":not bool(ret_unique_counts["UNIQUE_COUNT_COMPARISON"][self.table]["RESULT"]),"FAILURE_MSG":"counts do not match DB UNIQUE COUNT: "+str(ret_unique_counts['db_unique_counts']) +" S3 UNIQUE COUNT: "+str(ret_unique_counts['s3_unique_counts'])}}}})
            else:
                data_validation.update({"TABLES": {list(ret_unique_counts["UNIQUE_COUNT_COMPARISON"].keys())[0]:{"NON_BATCH_VALIDATION":{"FAILED":not ret_unique_counts["UNIQUE_COUNT_COMPARISON"][self.table]["RESULT"],"FAILURE_MSG":"counts  match DB UNIQUE COUNT: "+str(ret_unique_counts['db_unique_counts']) +" S3 UNIQUE COUNT: "+str(ret_unique_counts['s3_unique_counts'])}}}})
            self.writeReportsToS3("UNIQUE_COUNT_COMPARISON",data_validation,"datavalidation/reporting/"+"UNIQUE_COUNT_COMPARISON"+"/"+key)

        else:
            self.logger.info("******* UNIQUE COUNT VALIDATION IS DISABLED ******* ")
</code>```

I just added if not ret_unique_counts in the "if" statement. It runs through each table listed in the dictionary, it skips over the table that's not listed like I want, but there is no file that is written to S3 even though the code runs all the way through without errors. I'm not sure where the issue is now, but I think I'm getting close.

Title: How do I not call a function?

Body:
I think it's obvious that I just won't call it, but I am trying to create an exception if it returns "None". I have my code here:

    if self.config["data-validation"]["RULES"]["RULE_UNIQUE_VALIDATION"]["UNIQUE_VALIDATION"]:
        self.logger.info("******* RULE_UNIQUE_VALIDATION VALIDATION ENABLED ******* ")
        db_total_table_unique_count_dict={}
        s3_total_table_unique_count_dict={}
        db_total_table_unique_count_dict=self.getDBUniqueValueCounts(db_total_table_unique_count_dict)
        s3_total_table_unique_count_dict=self.getS3UniqueValueCounts(s3_total_table_unique_count_dict)
        ret_unique_counts=SourceValidation.findDiff(db_total_table_unique_count_dict,s3_total_table_unique_count_dict,"UNIQUE_COUNT_COMPARISON")
        ret_unique_counts['db_unique_counts']=db_total_table_unique_count_dict
        ret_unique_counts['s3_unique_counts']=s3_total_table_unique_count_dict
        data_validation={}
        data_validation.update({"VALIDATION_TYPE":"UNIQUE_COUNT"})
        data_validation.update({"DATABASE":db_name})
        data_validation.update({"RUN_TIMESTAMP":self.run_time_stamp})

        if ret_unique_counts is not None:

            if ret_unique_counts["UNIQUE_COUNT_COMPARISON"].get(self.table)["RESULT"]==False:
                data_validation.update({"TABLES": {list(ret_unique_counts["UNIQUE_COUNT_COMPARISON"].keys())[0]:{"NON_BATCH_VALIDATION":{"FAILED":not bool(ret_unique_counts["UNIQUE_COUNT_COMPARISON"][self.table]["RESULT"]),"FAILURE_MSG":"counts do not match DB UNIQUE COUNT: "+str(ret_unique_counts['db_unique_counts']) +" S3 UNIQUE COUNT: "+str(ret_unique_counts['s3_unique_counts'])}}}})
            else:
                data_validation.update({"TABLES": {list(ret_unique_counts["UNIQUE_COUNT_COMPARISON"].keys())[0]:{"NON_BATCH_VALIDATION":{"FAILED":not ret_unique_counts["UNIQUE_COUNT_COMPARISON"][self.table]["RESULT"],"FAILURE_MSG":"counts  match DB UNIQUE COUNT: "+str(ret_unique_counts['db_unique_counts']) +" S3 UNIQUE COUNT: "+str(ret_unique_counts['s3_unique_counts'])}}}})
                self.writeReportsToS3("UNIQUE_COUNT_COMPARISON",data_validation,"datavalidation/reporting/"+"UNIQUE_COUNT_COMPARISON"+"/"+key)

    else:
        self.logger.info("******* UNIQUE COUNT VALIDATION IS DISABLED ******* ")

The error I am getting is:

    if ret_unique_counts["UNIQUE_COUNT_COMPARISON"].get(self.table)["RESULT"]==False:
TypeError: 'NoneType' object is not subscriptable

So I basically want to not call the function "findDiff" if it returns "None". I'm not sure how to do that, so I thought I can continue my "if" statement if it returns "None" anyway, to skip over it by writing if ret_unique_counts is not None:. I tried that and it still throws the same error. I'm not sure what else to do. I don't want to take out "findDiff" because I have a list of tables it iterates through, but if one isn't there I want it to skip over it.

UPDATE--------------------------------------

I updated my code like this:

    if self.config["data-validation"]["RULES"]["RULE_UNIQUE_VALIDATION"]["UNIQUE_VALIDATION"]:
        self.logger.info("******* RULE_UNIQUE_VALIDATION VALIDATION ENABLED ******* ")
        db_total_table_unique_count_dict={}
        s3_total_table_unique_count_dict={}
        db_total_table_unique_count_dict=self.getDBUniqueValueCounts(db_total_table_unique_count_dict)
        s3_total_table_unique_count_dict=self.getS3UniqueValueCounts(s3_total_table_unique_count_dict)
        ret_unique_counts=SourceValidation.findDiff(db_total_table_unique_count_dict,s3_total_table_unique_count_dict,"UNIQUE_COUNT_COMPARISON")
        ret_unique_counts['db_unique_counts']=db_total_table_unique_count_dict
        ret_unique_counts['s3_unique_counts']=s3_total_table_unique_count_dict
        data_validation={}
        data_validation.update({"VALIDATION_TYPE":"UNIQUE_COUNT"})
        data_validation.update({"DATABASE":db_name})
        data_validation.update({"RUN_TIMESTAMP":self.run_time_stamp})
        if not ret_unique_counts:
            if ret_unique_counts["UNIQUE_COUNT_COMPARISON"].get(self.table)["RESULT"]==False:
                    data_validation.update({"TABLES": {list(ret_unique_counts["UNIQUE_COUNT_COMPARISON"].keys())[0]:{"NON_BATCH_VALIDATION":{"FAILED":not bool(ret_unique_counts["UNIQUE_COUNT_COMPARISON"][self.table]["RESULT"]),"FAILURE_MSG":"counts do not match DB UNIQUE COUNT: "+str(ret_unique_counts['db_unique_counts']) +" S3 UNIQUE COUNT: "+str(ret_unique_counts['s3_unique_counts'])}}}})
            else:
                data_validation.update({"TABLES": {list(ret_unique_counts["UNIQUE_COUNT_COMPARISON"].keys())[0]:{"NON_BATCH_VALIDATION":{"FAILED":not ret_unique_counts["UNIQUE_COUNT_COMPARISON"][self.table]["RESULT"],"FAILURE_MSG":"counts  match DB UNIQUE COUNT: "+str(ret_unique_counts['db_unique_counts']) +" S3 UNIQUE COUNT: "+str(ret_unique_counts['s3_unique_counts'])}}}})
            self.writeReportsToS3("UNIQUE_COUNT_COMPARISON",data_validation,"datavalidation/reporting/"+"UNIQUE_COUNT_COMPARISON"+"/"+key)

        else:
            self.logger.info("******* UNIQUE COUNT VALIDATION IS DISABLED ******* ")

I just added if not ret_unique_counts in the "if" statement. It runs through each table listed in the dictionary, it skips over the table that's not listed like I want, but there is no file that is written to S3 even though the code runs all the way through without errors. I'm not sure where the issue is now, but I think I'm getting close.


问:
Long path Exception when in .net 4.8 class library but not in WIndows form app
Has anyone ever run into an issue with .net 4.8 (c#) throwing "too long path" errors like below when run from a class library project. The same line of code is working fine for me if I run it from a windows forms project.

the error is below
"The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters"

The code I'm using to get the error is pretty simple. StrPath is a valid path that is say 350 chars long. ("c:\<350 Char path and filename>")

```<code>string a = Path.GetDirectoryName(strPath);
</code>```

That's the simplest example, but it also happens when using any File or FileIO method like File and FileStream where I reference the long path.

Things I've tried

Most recommendations from https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN

setting the long path registry key

Including app manifest with settings to recognize long paths. (there were two different types of these I found on the net, neither worked)

prefixing with "\\?\"

Looked at what mscorlibs are being referenced by both the windows forms and the exe calling the class library dll. Both were identical and referenced 4.8 libs.

Both projects succeed when I use a shorter path than 260. So it is really a path len issue I think. It just seems to behave as if I'm using an older version of .net when run from the class library.

I call the class library from within a native C++ app (its a com interop). I can also get it to happen if I make a class library with that code into an nunit text fixture and call it from nunit-x86.exe. So the code would be as below for that. And fails when calling GetDirectoryName

```<code>using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Omtool.Properties;

using System.Diagnostics;
using System.IO;
using OmXceedInterop;

using System.Windows.Forms;

namespace XceedTest
{
    [TestFixture]
    public class Class1
    {
        [Test]
        public void Test()
        {
            string strPath = "C:\\Kit\\BlahServer\\Work\\CompoundFile\\Xceed\\2a0bb008-397b-476a-8e89-96caa7a11319\\HLCUVL1221104974\\THIS_NAME_IS_TOO_FRACKING_LONG_TO_BE_IN_ANY_WAY_USEFUL_YOU_SHOULD_BE_A_FRACKING_SHAMED_OF_YOURSELF_HLCUVL1221104974_Container Inspection_NANDA TILES,SL-DOCUMENTO CONTENEDOR-NEXP-220199-STYLE ACCESS-FLOOR DECOR-BAYTOWN TX-NO.1001367035.pdf";
            int b = strPath.Length;
            string a = Path.GetDirectoryName(strPath);

        }
    }
}
</code>```

Again, the exact same lines of code work from the forms app but fail when called from the class library. There is something different about these two projects or perhaps the context under which they run that I'm just not understanding.

[EDIT]
It has to be the context. When I run my nunit class from the forms app, there is no path error. When I run that same assembly from nunit-x86.exe, I get the pathing error. It seems to depend on what's calling the class library as to whether I get the error or not

Body:
Has anyone ever run into an issue with .net 4.8 (c#) throwing "too long path" errors like below when run from a class library project. The same line of code is working fine for me if I run it from a windows forms project.

the error is below
"The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters"

The code I'm using to get the error is pretty simple. StrPath is a valid path that is say 350 chars long. ("c:\<350 Char path and filename>")

string a = Path.GetDirectoryName(strPath);

That's the simplest example, but it also happens when using any File or FileIO method like File and FileStream where I reference the long path.

Things I've tried

Most recommendations from https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN

setting the long path registry key

Including app manifest with settings to recognize long paths. (there were two different types of these I found on the net, neither worked)

prefixing with "\\?\"

Looked at what mscorlibs are being referenced by both the windows forms and the exe calling the class library dll. Both were identical and referenced 4.8 libs.

Both projects succeed when I use a shorter path than 260. So it is really a path len issue I think. It just seems to behave as if I'm using an older version of .net when run from the class library.

I call the class library from within a native C++ app (its a com interop). I can also get it to happen if I make a class library with that code into an nunit text fixture and call it from nunit-x86.exe. So the code would be as below for that. And fails when calling GetDirectoryName

using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Omtool.Properties;

using System.Diagnostics;
using System.IO;
using OmXceedInterop;

using System.Windows.Forms;

namespace XceedTest
{
    [TestFixture]
    public class Class1
    {
        [Test]
        public void Test()
        {
            string strPath = "C:\\Kit\\BlahServer\\Work\\CompoundFile\\Xceed\\2a0bb008-397b-476a-8e89-96caa7a11319\\HLCUVL1221104974\\THIS_NAME_IS_TOO_FRACKING_LONG_TO_BE_IN_ANY_WAY_USEFUL_YOU_SHOULD_BE_A_FRACKING_SHAMED_OF_YOURSELF_HLCUVL1221104974_Container Inspection_NANDA TILES,SL-DOCUMENTO CONTENEDOR-NEXP-220199-STYLE ACCESS-FLOOR DECOR-BAYTOWN TX-NO.1001367035.pdf";
            int b = strPath.Length;
            string a = Path.GetDirectoryName(strPath);

        }
    }
}

Again, the exact same lines of code work from the forms app but fail when called from the class library. There is something different about these two projects or perhaps the context under which they run that I'm just not understanding.

[EDIT]
It has to be the context. When I run my nunit class from the forms app, there is no path error. When I run that same assembly from nunit-x86.exe, I get the pathing error. It seems to depend on what's calling the class library as to whether I get the error or not


问:
Double embed collection form
I have three entities connected with ManyToOne relationship : Mission 1-n Project 1-n Task.

I need to create a new Mission with new Projects and new Tasks in a single double embed form.

The first embed form (adding Projects to Mission) works nicely but the second one (adding Tasks to Projects) keep saving the tasks only to the first project (no matter if I click on the "add task" button of the second project). I am definetly missing something with the prototype I guess, but I cannot figure it out..

```<code>{% extends 'base.html.twig' %}

{% macro printTaskRow(taskForm, index) %}
    <div class="js-task-item">
        <p>
            <strong>Task {{ index }}</strong>
            <a href="#" class="js-remove-task float-end">
                <span class="fa fa-close"></span>
            </a>
        </p>
        {{ form_row(taskForm.title) }}
        {{ form_row(taskForm.description) }}
    </div>
{% endmacro %}

{% macro printProjectRow(projectForm, index) %}
    <div class="js-project-item">
        <p>
            <strong>Project {{ index }}</strong>
            <a href="#" class="js-remove-project float-end">
                <span class="fa fa-close"></span>
            </a>
        </p>
        {{ form_row(projectForm.title) }}
        {{ form_row(projectForm.description) }}

        <h3 class="mt-6 mb-4">List of the associated tasks</h3>
        <div class="row">
            <div class="js-task-wrapper"
                 data-index="{{ projectForm.tasks|length > 0 ? projectForm.tasks|last.vars.name + 1 : 0 }}"
                 data-prototype="{{ _self.printTaskRow(projectForm.tasks.vars.prototype)|e('html_attr') }}"
            >
                {% for taskForm in projectForm.tasks %}
                    {{ _self.printTaskRow(taskForm, loop.index) }}
                {% endfor %}
                <a href="#" class="js-task-add">
                    <span class="fa fa-plus-circle"></span>
                    Add Another task
                </a>
            </div>
        </div>

    </div>
{% endmacro %}

{% block title %}New mission template{% endblock %}

{% block stylesheets %}
    <style>
        .js-project-item {
            background-color: lightblue;
            padding: 20px;
            margin-bottom: 40px;
            border-radius: 2px;
        }

        .js-task-item {
            background-color: lightcoral;
            padding: 20px;
            margin-bottom: 40px;
            border-radius: 2px;
        }

        li {
            list-style-type: none;
        }
    </style>
{% endblock %}

{% block body %}
    <h1>Create a new mission template</h1>
    <div class="mt-4">
        <h3 class="mt-6">The mission</h3>
        {{ form_start(missionForm, {'attr': {'novalidate': 'novalidate'}}) }}
            {{ form_row(missionForm.title) }}
            {{ form_row(missionForm.description) }}

            <h3 class="mt-6 mb-4">List of the associated projects</h3>
            <div class="js-project-wrapper"
                data-index="{{ missionForm.projects|length > 0 ? missionForm.projects|last.vars.name + 1 : 0 }}"
                data-prototype="{{ _self.printProjectRow(missionForm.projects.vars.prototype)|e('html_attr') }}"
            >
                {% for projectForm in missionForm.projects %}
                    {{ _self.printProjectRow(projectForm, loop.index) }}
                {% endfor %}
                <a href="#" class="js-project-add">
                    <span class="fa fa-plus-circle"></span>
                    Add Another project
                </a>
            </div>

            <div class="mt-6 d-grid gap-2">
                {{ form_widget(missionForm.save, { 'label': 'Create the mission', 'attr' : { 'class': 'btn-primary btn-lg' } }) }}
            </div>
        {{ form_end(missionForm) }}
    </div>
{% endblock %}

{% block javascripts %}
    <script>
        jQuery(document).ready(function() {

            var $projectWrapper = $('.js-project-wrapper');

            $projectWrapper.on('click', '.js-project-add', function(e) {
                e.preventDefault();
                // Get the data-prototype explained earlier
                var prototype = $projectWrapper.data('prototype');

                // get the new index
                var index = $projectWrapper.data('index');
                // Replace '__name__' in the prototype's HTML to
                // instead be a number based on how many items we have

                var newProjectForm = prototype.replace(/__name__/g, index);

                // increase the index with one for the next item
                $projectWrapper.data('index', index + 1);

                // Display the form in the page before the "new" link
                $(this).before(newProjectForm)
            });

            $projectWrapper.on('click', '.js-remove-project', function(e) {
                e.preventDefault();

                $(this).closest('.js-project-item')
                    .fadeOut()
                    .remove();
            });

            var $taskWrapper = $('.js-task-wrapper');

            $taskWrapper.on('click', '.js-task-add', function(e) {
                e.preventDefault();
                // Get the data-prototype explained earlier
                var prototype = $taskWrapper.data('prototype');

                // get the new index
                var index = $taskWrapper.data('index');
                // Replace '__name__' in the prototype's HTML to
                // instead be a number based on how many items we have

                var newTaskForm = prototype.replace(/__name__/g, index);

                // increase the index with one for the next item
                $taskWrapper.data('index', index + 1);

                // Display the form in the page before the "new" link
                $(this).before(newTaskForm)
            });

            $taskWrapper.on('click', '.js-remove-task', function(e) {
                e.preventDefault();

                $(this).closest('.js-task-item')
                    .fadeOut()
                    .remove();
            });
        });
    </script>
{% endblock %}
</code>```

Title: Double embed collection form

Body:
I have three entities connected with ManyToOne relationship : Mission 1-n Project 1-n Task.

I need to create a new Mission with new Projects and new Tasks in a single double embed form.

The first embed form (adding Projects to Mission) works nicely but the second one (adding Tasks to Projects) keep saving the tasks only to the first project (no matter if I click on the "add task" button of the second project). I am definetly missing something with the prototype I guess, but I cannot figure it out..

{% extends 'base.html.twig' %}

{% macro printTaskRow(taskForm, index) %}

            Task {{ index }}

        {{ form_row(taskForm.title) }}
        {{ form_row(taskForm.description) }}

{% endmacro %}

{% macro printProjectRow(projectForm, index) %}

            Project {{ index }}

        {{ form_row(projectForm.title) }}
        {{ form_row(projectForm.description) }}

List of the associated tasks

 0 ? projectForm.tasks|last.vars.name + 1 : 0 }}"
                 data-prototype="{{ _self.printTaskRow(projectForm.tasks.vars.prototype)|e('html_attr') }}"
            >
                {% for taskForm in projectForm.tasks %}
                    {{ _self.printTaskRow(taskForm, loop.index) }}
                {% endfor %}

                    Add Another task

{% endmacro %}

{% block title %}New mission template{% endblock %}

{% block stylesheets %}

{% endblock %}

{% block body %}

Create a new mission template

The mission

        {{ form_start(missionForm, {'attr': {'novalidate': 'novalidate'}}) }}
            {{ form_row(missionForm.title) }}
            {{ form_row(missionForm.description) }}

List of the associated projects

 0 ? missionForm.projects|last.vars.name + 1 : 0 }}"
                data-prototype="{{ _self.printProjectRow(missionForm.projects.vars.prototype)|e('html_attr') }}"
            >
                {% for projectForm in missionForm.projects %}
                    {{ _self.printProjectRow(projectForm, loop.index) }}
                {% endfor %}

                    Add Another project

                {{ form_widget(missionForm.save, { 'label': 'Create the mission', 'attr' : { 'class': 'btn-primary btn-lg' } }) }}

        {{ form_end(missionForm) }}

{% endblock %}

{% block javascripts %}

{% endblock %}