问:
Uncaught ReferenceError: require is not defined in Electron Js when using require() in html page
I'm new to Electron Js and I am trying to make a custom titlebar as a project. I made the titlebar in a html page called nav.html and imported it in index.html (the main page)

nav.html :

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <title>Document</title>

    <style>
      * {
        margin: 0;
        padding: 0;
      }
      button {
        margin: 0;
        padding: 0;
        border: none;
        outline: none;
        background-color: transparent;
        height: 35px;
      }
      .header {
        background-color: black;
        color: white;
        overflow: hidden;
      }
#title {
        width: 80%;
        -webkit-app-region: drag;
        -webkit-user-select: none;
        user-select: none;
      }
      svg.restore {
        fill: rgb(255, 255, 255) !important;
        width: 15px;
        height: 15px;
        padding: 10px 14px;
      }
      svg.restore:hover {
        fill: rgb(255, 255, 255) !important;
        background-color: #5e5e5e !important;
      }

      button.minimize {
        padding: 3.5px 16px;
        color: white;
      }
      button.minimize:hover {
        background-color: #5e5e5e !important;
      }

      .maximize {
        cursor: default;
        fill: white;
        padding: 10px 14px;
        height: 15px;
        width: 15px;
        display: none;
      }
      .maximize:hover {
        background-color: #5e5e5e !important;
        color: white;
      }

      button.close {
        padding: 3.3px 14px;
        color: white;
      }
      button.close:hover {
        background-color: red !important;
      }
    </style>
  </head>
  <body>
<div
      class="header"
      style="display: flex; align-items: center; justify-content: space-between;"
    >
      <div id="title"></div>
      <div style="display: flex; align-items: center; justify-content: center;">
        <button
          style="font-size: 25px; cursor: default"
          class="minimize"
          id="minimize"
        >
          -
        </button>
        <button>
          <svg
            width="25px"
            height="25px"
            viewBox="0 0 512 512"
            xmlns="http://www.w3.org/2000/svg"
            style="cursor: default"
            class="restore"
            id="restore"
          >
            <path
              d="M352,153H40.247a24.028,24.028,0,0,0-24,24V458a24.028,24.028,0,0,0,24,24H352a24.028,24.028,0,0,0,24-24V177A24.028,24.028,0,0,0,352,153Zm-8,32v45.22H48.247V185ZM48.247,450V262.22H344V450Z"
              class="ci-primary"
            />
            <path
              d="M472,32H152a24.028,24.028,0,0,0-24,24v65h32V64H464V339.143H408v32h64a24.028,24.028,0,0,0,24-24V56A24.028,24.028,0,0,0,472,32Z"
              class="ci-primary"
            />
          </svg>

          <svg
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            class="maximize"
            id="maximize"
          >
            <path
              d="M896 85.333333H128a42.666667 42.666667 0 0 0-42.666667 42.666667v768a42.666667 42.666667 0 0 0 42.666667 42.666667h768a42.666667 42.666667 0 0 0 42.666667-42.666667V128a42.666667 42.666667 0 0 0-42.666667-42.666667z m-42.666667 768H170.666667V426.666667h682.666666z m0-512H170.666667V170.666667h682.666666z"
            />
          </svg>
        </button>
        <button
          style="font-size: 25px; cursor: default"
          class="close"
          id="close"
        >
          ×
        </button>
      </div>
    </div>
    <script>
      document.getElementById("title").innerHTML = document.title;
      // ipc connection between main.js and nav.html buttons to mainpulate the function of the window asynchronously
      const { ipcRenderer } = require("electron");
      const ipc = ipcRenderer;

      const restore = document.querySelector("#restore");
      const maximize = document.querySelector("#maximize");
      const minimize = document.querySelector("#minimize");
      const closeBtn = document.querySelector("#close");

      // close the window
      closeBtn.onclick = function(){
        ipc.send("closeApp");
        console.log('mama earth');
      }
      restore.onclick = function () {
        maximize.style.display = "block";
        restore.style.display = "none";
      };
      maximize.onclick = function () {
        restore.style.display = "block";
        maximize.style.display = "none";
      };
    </script>
  </body>
</html>

</code>```

I have added inline styles as well as style tag and script tag in the same html document

Problem comes when I am not able to use require('electron') in a script tag. I am trying to make the top window buttons and using the ipcRenderer to process them to main.js.

Main.js :

```<code>const { app, BrowserWindow , ipcMain} = require('electron')
const path = require('path')
const ipc = ipcMain

function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 700,
    center: true,
    minHeight: 700,
    minWidth: 1200,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation : true,
      devTools: true,
      preload: path.join(__dirname, 'preload.js'),
    }
  })

  win.loadFile('index.html')

  //close window function
  ipc.on('closeApp', () => {
    console.log('app is closed')
    win.close()
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
</code>```

I have just added the index.html and preload.js for no confussion :

index.html :

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <title>Home</title>

    <link rel="stylesheet" href="style.css" />

    <script src="main.js"></script>

</head>
<body>
    <iframe id="nav-placeholder" src="nav.html" width="100%" style="border: none;height: 35px !important;" loading="eager"></iframe>
    <a href="nav.html">Go to nav page</a>
</body>
</html>
</code>```

Preload.js :

```<code>window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector, text) => {
      const element = document.getElementById(selector)
      if (element) element.innerText = text
    }

    for (const type of ['chrome', 'node', 'electron']) {
      replaceText(`${type}-version`, process.versions[type])
    }
  })
</code>```

I tried using require JS but I had no idea how to do it. If anyone has an answer to it or can guide me through the error it would be highly appreciatable!

Thank you in advance!

答:
@Dony is right, in today's Electron world, using require in the HTML page is a big no no. (disclaimer, I wrote the blog post that he's linking to).

I'm curious reading your question, are you looking to create a navigation or a menu? If it's a menu, then Electron has support to do this natively through the Menu class.

You ask a really great question, because setting this up in a secure way requires some communication between the renderer and main processes. My template uses this pattern within the menu to update the app's language, alongside this package.

I unfortunately don't have enough time to thoroughly go into detail at this moment, but will suggest you first take a peak at whether it may be a menu you are looking to add your functionality to. If it is, I hope some of my repository's files can direct you in the place where you can see how to set up the link between the js and the html file within an Electron application.

I'm also currently in the process of writing an "Ultimate Electron guide" that would cover these topics in a thorough blog post. I estimate it's many weeks out as I intend to go in great detail to explain Electron concepts such as this one. It'll be up on https://www.debugandrelease.com/ when I post it (subscribe if you'd like an email when it goes out).

Body:
I'm new to Electron Js and I am trying to make a custom titlebar as a project. I made the titlebar in a html page called nav.html and imported it in index.html (the main page)

nav.html :

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <title>Document</title>

        <button
          style="font-size: 25px; cursor: default"
          class="minimize"
          id="minimize"
        >
          -
        </button>
        <button>
          <svg
            width="25px"
            height="25px"
            viewBox="0 0 512 512"
            xmlns="http://www.w3.org/2000/svg"
            style="cursor: default"
            class="restore"
            id="restore"
          >
            <path
              d="M352,153H40.247a24.028,24.028,0,0,0-24,24V458a24.028,24.028,0,0,0,24,24H352a24.028,24.028,0,0,0,24-24V177A24.028,24.028,0,0,0,352,153Zm-8,32v45.22H48.247V185ZM48.247,450V262.22H344V450Z"
              class="ci-primary"
            />
            <path
              d="M472,32H152a24.028,24.028,0,0,0-24,24v65h32V64H464V339.143H408v32h64a24.028,24.028,0,0,0,24-24V56A24.028,24.028,0,0,0,472,32Z"
              class="ci-primary"
            />
          </svg>

          <svg
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            class="maximize"
            id="maximize"
          >
            <path
              d="M896 85.333333H128a42.666667 42.666667 0 0 0-42.666667 42.666667v768a42.666667 42.666667 0 0 0 42.666667 42.666667h768a42.666667 42.666667 0 0 0 42.666667-42.666667V128a42.666667 42.666667 0 0 0-42.666667-42.666667z m-42.666667 768H170.666667V426.666667h682.666666z m0-512H170.666667V170.666667h682.666666z"
            />
          </svg>
        </button>
        <button
          style="font-size: 25px; cursor: default"
          class="close"
          id="close"
        >
          ×
        </button>

I have added inline styles as well as style tag and script tag in the same html document

Problem comes when I am not able to use require('electron') in a script tag. I am trying to make the top window buttons and using the ipcRenderer to process them to main.js.

Main.js :

const { app, BrowserWindow , ipcMain} = require('electron')
const path = require('path')
const ipc = ipcMain

function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 700,
    center: true,
    minHeight: 700,
    minWidth: 1200,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation : true,
      devTools: true,
      preload: path.join(__dirname, 'preload.js'),
    }
  })

  win.loadFile('index.html')

  //close window function
  ipc.on('closeApp', () => {
    console.log('app is closed')
    win.close()
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

I have just added the index.html and preload.js for no confussion :

index.html :

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <title>Home</title>

    <link rel="stylesheet" href="style.css" />

    Go to nav page

Preload.js :

window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector, text) => {
      const element = document.getElementById(selector)
      if (element) element.innerText = text
    }

    for (const type of ['chrome', 'node', 'electron']) {
      replaceText(`${type}-version`, process.versions[type])
    }
  })

I tried using require JS but I had no idea how to do it. If anyone has an answer to it or can guide me through the error it would be highly appreciatable!

Thank you in advance!


来源: stackexchange

问:
Chrome truncate div with text when use transform function
Possible that I found a Chrome bug, on Safari everything works fine.

I did online example, when you click text "Click here" waiting and click again, when text back to start position you can see blink on this text.

Hard to explain but I did video. I know when scrollbar is smaller this bug is fixed but I need found way to resolve this with long site (one page site)

Online example with possibly chrome bug: https://codesandbox.io/s/test3-800cu

Video on chrome (bug)

Video on safari (fine)

答:
Chances are, Chrome is trying to be "smart" and avoid rendering text that will lie outside the bounds when transformed. However that has the counterproductive effect of unnecessarily clipping the text.

For scenarios like this, use the will-change to hint the browser at what potentially will need to be repainted/recomposited:

```<code>.test {
  transition: transform 1.5s;

  /* Hint browser that transform property will be changed */
  will-change: transform;
}
</code>```

This resolves the issue on Chrome. Do note that you should treat will-change as an emergency escape hatch for quirky rendering bugs that could benefit from browser optimising the rendering process beforehand. Do not apply it willy-nilly to a large subset of elements, as that significantly degrades performances of the browser.

You can also force the browser to composite the layer with a different (read: dated) strategy, by simply applying transform: translate3d(0,0,0); to the root state. This probably only useful if you also want to support browsers that do not have will-change support, but has CSS 3D transform support.

```<code>.test {
  transition: transform 1.5s;

  /* NOT RECOMMENDED: Force browser to move element to composition layer */
  transform: translate3d(0,0,0);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Chances are, Chrome is trying to be "smart" and avoid rendering text that will lie outside the bounds when transformed. However that has the counterproductive effect of unnecessarily clipping the text.

For scenarios like this, use the will-change to hint the browser at what potentially will need to be repainted/recomposited:

.test {
  transition: transform 1.5s;

  /* Hint browser that transform property will be changed */
  will-change: transform;
}

This resolves the issue on Chrome. Do note that you should treat will-change as an emergency escape hatch for quirky rendering bugs that could benefit from browser optimising the rendering process beforehand. Do not apply it willy-nilly to a large subset of elements, as that significantly degrades performances of the browser.

You can also force the browser to composite the layer with a different (read: dated) strategy, by simply applying transform: translate3d(0,0,0); to the root state. This probably only useful if you also want to support browsers that do not have will-change support, but has CSS 3D transform support.

.test {
  transition: transform 1.5s;

  /* NOT RECOMMENDED: Force browser to move element to composition layer */
  transform: translate3d(0,0,0);
}


问:
Yarn 2.0 zero installs production vs development deployment?
So we are in the process of moving from yarn 1.x to yarn 2 (yarn 3.1.1) and I'm getting a little confused on how to configure yarn in my CI/CD config. As of right now our pipeline does the following to deploy to our kubernetes cluster:

On branch PR:

Obtain branch repo in gitlab runner

Lint

Run jest

Build with environment variables, dependencies, and devdependencies

Publish image to container registry with tag test

a. If success, allow merge to main

Kubernetes watches for updates to test and deploys a test pod to cluster

On merge to main:

Obtain main repo in gitlab runner

Lint

Run jest

Build with environment variables and dependencies

Publish image to container registry with tag latest

Kubernetes watches for updates to latest and deploys a staging pod to cluster

(NOTE: For full-blown production releases we will be using the release feature to manually deploy releases to the production server)

The issue is that we are using yarn 2 with zero installs and in the past we have been able prevent the production environment from using any dev dependencies by running yarn install --production. In yarn 2 this command is deprecated.

Is there any ideal solution to prevent dev dependencies from being installed on production? I've seen some posts mention using workspaces but that seems to be more tailored towards mono-repos where there are more than one application.

Thanks in advance for any help!

答:
I had the same question and came to the same conclusion as you. I could not find an easy way to perform a production build on yarn 2. Yarn Workspaces comes closest but I did find the paragraph below in the documentation:

Note that this command is only very moderately useful when using zero-installs, since the cache will contain all the packages anyway - meaning that the only difference between a full install and a focused install would just be a few extra lines in the .pnp.cjs file, at the cost of introducing an extra complexity.

From: https://yarnpkg.com/cli/workspaces/focus#options-production

Does that mean that there essentially is no production install? It would be nice if that was officially addressed somewhere but this was the closest I could find.

Personally, I am using NextJS and upgraded my project to Yarn 2. The features of Yarn 2 seem to work (no node_modules folder) but I can still use yarn build from NextJS to create a production build with output in the .next folder.


问:
How to change background color of the selected item in a list
How do I change the background color of the selected item in a list.
I'm not sure whether this is done in the CSS or my script.</p>
```<code><script id="INLINE_PEN_JS_ID">
$(document).ready(function () {

  $('.accordion-list > li > .answer').hide();

  $('.accordion-list > li').click(function () {
    if ($(this).hasClass("active")) {

       if (event.target.closest('a')) {
        // an <a> was clicked
        return;
        }
      $(this).removeClass("active").find(".answer").slideUp();

    } else {

      $(".accordion-list > li.active .answer").slideUp();
      $(".accordion-list > li.active").removeClass("active");
      $(this).addClass("active").find(".answer").slideDown();
      $(".accordion-list > li.style.backgroundColor = "red";
    }
    return false;
  });

});
</script>
</code>```

答:
Consider the following.

$(function() {
  $('.accordion-list > li > .answer').hide();
  $('.accordion-list > li').click(function(event) {
    if ($(this).hasClass("active")) {
      if ($("a", this).length && $(event.target).is("a")) {
        //
 contains  &&  was clicked
        return;
      }
      $(this).removeClass("active").find(".answer").slideUp();
    } else {
      $(".accordion-list > li.active .answer").slideUp();
      $(".accordion-list > li.active").removeClass("active");
      $(this).addClass("active").find(".answer").slideDown();
    }
    return false;
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.accordion-list>li {
  height: 60px;
  padding: 20px;
}

.accordion-list>li.active {
  background-color: red;
}</code>```

Item 1

Item 2

Item 3

Item 4

Item 5

```

As you did not provide an example, I had to make some guesses. You can see that this is using both CSS and jQuery to help highlight the targeted list item.

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.

See more: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

Body:
Consider the following.

$(function() {
  $('.accordion-list > li > .answer').hide();
  $('.accordion-list > li').click(function(event) {
    if ($(this).hasClass("active")) {
      if ($("a", this).length && $(event.target).is("a")) {
        // <LI> contains <A> && <A> was clicked
        return;
      }
      $(this).removeClass("active").find(".answer").slideUp();
    } else {
      $(".accordion-list > li.active .answer").slideUp();
      $(".accordion-list > li.active").removeClass("active");
      $(this).addClass("active").find(".answer").slideDown();
    }
    return false;
  });
});

.accordion-list>li {
  height: 60px;
  padding: 20px;
}

.accordion-list>li.active {
  background-color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="accordion-list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li class="active"><i class="answer"></i>Item 4</li>
  <li>Item 5</li>
</ul>

As you did not provide an example, I had to make some guesses. You can see that this is using both CSS and jQuery to help highlight the targeted list item.

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.

See more: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest


问:
Next-auth. Login User then what?
After I have logged in a user with next-auth, how I do fetch data using their information? Do I keep calling useSession or do something else? I want to fetch data on each page but this appears impossible become of the async nature of useSession() on each page</p>

答:
At a high level, you can use the access token provided to you by the OAuth provider to further authenticate against that provider and do other stuff, i.e. get the users Google Drive files, Google Contacts, etc. etc.

Check out this example where I do just that in a Next.js API route with Google Drive and NextAuth.js here: https://github.com/ndom91/newtelco-tab/blob/main/src/pages/api/gdrive.ts

Title: Next-auth. Login User then what?


问:
Kotlin :Execution failed for task ':app:checkDebugAarMetadata'
I am using kotlin ,and I get these error when I add the third library:
** implementation 'com.github.AsynctaskCoffee:tinderlikecardstack:1.0'**

from:  https://github.com/AsynctaskCoffee/TinderLikeCardStack

The Error:

```<code>Execution failed for task ':app:checkDebugAarMetadata'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Could not find com.github.AsynctaskCoffee:tinderlikecardstack:1.0.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/com/github/AsynctaskCoffee/tinderlikecardstack/1.0/tinderlikecardstack-1.0.pom
       - https://repo.maven.apache.org/maven2/com/github/AsynctaskCoffee/tinderlikecardstack/1.0/tinderlikecardstack-1.0.pom
       - https://jcenter.bintray.com/com/github/AsynctaskCoffee/tinderlikecardstack/1.0/tinderlikecardstack-1.0.pom
     Required by:
         project :app

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html
</code>```

And my guild.gradle(:app)

```<code> plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'

}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.gearsrun.stackviewapplication"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.6.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
    implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation("androidx.recyclerview:recyclerview:1.2.1")
    // For control over item selection of both touch and mouse driven selection
    implementation("androidx.recyclerview:recyclerview-selection:1.1.0")
    implementation 'com.airbnb.android:lottie:3.4.1'
    implementation 'de.hdodenhof:circleimageview:3.1.0'
    implementation 'com.makeramen:roundedimageview:2.3.0'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.facebook.fresco:fresco:2.1.0'

    implementation 'com.squareup.retrofit2:retrofit:2.6.1'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
    implementation 'com.github.AsynctaskCoffee:tinderlikecardstack:1.0'

}
</code>```

build.grandle:

```<code>   // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.5.0"
    repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' }

    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

my gradle.properties:

```<code># Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official

android.enableJetifier=true
</code>```

Could anyone take a look what was going on please ,thank you so much !

答:
```<code>allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
        implementation 'com.github.AsynctaskCoffee:TinderLikeCardStack:1.0'
}
</code>```

Normally, your declarations are true but you may declare them on wrong places. implementation part should be in Gradle app - maven declaration should be in main Gradle.

You can also define project with maven

<dependency>
    <groupId>com.github.AsynctaskCoffee</groupId>
    <artifactId>TinderLikeCardStack</artifactId>
    <version>1.0</version>
</dependency>

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>
```

Also please check you should disable offline Gradle build. You can also download project and import as module.

Body:
I am using kotlin ,and I get these error when I add the third library:
** implementation 'com.github.AsynctaskCoffee:tinderlikecardstack:1.0'**

from:  https://github.com/AsynctaskCoffee/TinderLikeCardStack

The Error:

Execution failed for task ':app:checkDebugAarMetadata'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Could not find com.github.AsynctaskCoffee:tinderlikecardstack:1.0.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/com/github/AsynctaskCoffee/tinderlikecardstack/1.0/tinderlikecardstack-1.0.pom
       - https://repo.maven.apache.org/maven2/com/github/AsynctaskCoffee/tinderlikecardstack/1.0/tinderlikecardstack-1.0.pom
       - https://jcenter.bintray.com/com/github/AsynctaskCoffee/tinderlikecardstack/1.0/tinderlikecardstack-1.0.pom
     Required by:
         project :app

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html

And my guild.gradle(:app)

 plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'

}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.gearsrun.stackviewapplication"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.6.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
    implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation("androidx.recyclerview:recyclerview:1.2.1")
    // For control over item selection of both touch and mouse driven selection
    implementation("androidx.recyclerview:recyclerview-selection:1.1.0")
    implementation 'com.airbnb.android:lottie:3.4.1'
    implementation 'de.hdodenhof:circleimageview:3.1.0'
    implementation 'com.makeramen:roundedimageview:2.3.0'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.facebook.fresco:fresco:2.1.0'

    implementation 'com.squareup.retrofit2:retrofit:2.6.1'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
    implementation 'com.github.AsynctaskCoffee:tinderlikecardstack:1.0'

}

build.grandle:

   // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.5.0"
    repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' }

    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

my gradle.properties:

# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official

android.enableJetifier=true

Could anyone take a look what was going on please ,thank you so much !

Body:
allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
        implementation 'com.github.AsynctaskCoffee:TinderLikeCardStack:1.0'
}

Normally, your declarations are true but you may declare them on wrong places. implementation part should be in Gradle app - maven declaration should be in main Gradle.

You can also define project with maven

<dependency>
    <groupId>com.github.AsynctaskCoffee</groupId>
    <artifactId>TinderLikeCardStack</artifactId>
    <version>1.0</version>
</dependency>

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

Also please check you should disable offline Gradle build. You can also download project and import as module.


问:
Google Sheet Formula to extract from | separated hiearchy
I have a hierarchy list separated by |.  The hierarchy is listed as L1|L2|L3|L4|L5 ect.

I'm trying to create a formula to extract the L2 and L3 of the hierarchy.  The best method I've found for now is using the Text to Columns feature in Google Sheets but a formula would be ideal.  Giving some examples below.

答:
Try</p>
```<code>=query(arrayformula(if(C2:C="",,split(C2:C,"|"))),"select Col2,Col3")
</code>```

Body:
Try

=query(arrayformula(if(C2:C="",,split(C2:C,"|"))),"select Col2,Col3")


问:
Convert nested dictionary to csv
I have a particular case where I want to create a csv using the inner values of a nested dictionary as the keys and the inner keys as the header. The 'healthy' key can contain more subkeys other than 'height' and 'weight', but the 'unhealthy' will either ever contain None or a string of values.
My current dictionary looks like this:

```<code>{0: {'healthy': {'height': 160,
                 'weight': 180},
    'unhealthy': None},
 1: {'healthy': {'height': 170,
                'weight': 250},
    'unhealthy': 'alcohol, smoking, overweight'}
}
</code>```

How would I convert this to this csv:

```<code>+------+--------+----------------------------+
|height|  weight|                   unhealthy|
+------+--------+----------------------------+
|160   |     180|                            |
+------+--------+----------------------------+
|170   |     250|alcohol, smoking, overweight|
+------+--------+----------------------------+
</code>```

Is there anyway of not hardcoding this and doing this without Pandas and saving it to a location?

答:
I used pandas to deal with the value and to save it as a csv file.

I loaded the json format data as a dataframe.

By transposing the data, I got 'unhealty' columne

By using json_normalize(), I parsed the nested dictionary data, 'healthy' and generated two columns into 'height' and 'weight'

concat the 'healthy' and 'height', 'weight' columns

saved the dataframe as a csv file.

```<code>import pandas as pd

val = {
    0: {'healthy': {'height': 160, 'weight': 180},
        'unhealthy': None},
    1: {'healthy': {'height': 170, 'weight': 250},
        'unhealthy': 'alcohol, smoking, overweight'}
}

df = pd.DataFrame.from_dict(val)
df = df.transpose()
df = pd.concat([pd.json_normalize(df['healthy'], max_level=1), df['unhealthy']], axis=1)
df.to_csv('filename.csv', index=False) # A csv file generated.
</code>```

This is the csv file I generated (I opend it using MS Excel).

Title: Convert nested dictionary to csv

Body:
I have a particular case where I want to create a csv using the inner values of a nested dictionary as the keys and the inner keys as the header. The 'healthy' key can contain more subkeys other than 'height' and 'weight', but the 'unhealthy' will either ever contain None or a string of values.
My current dictionary looks like this:

{0: {'healthy': {'height': 160,
                 'weight': 180},
    'unhealthy': None},
 1: {'healthy': {'height': 170,
                'weight': 250},
    'unhealthy': 'alcohol, smoking, overweight'}
}

How would I convert this to this csv:

+------+--------+----------------------------+
|height|  weight|                   unhealthy|
+------+--------+----------------------------+
|160   |     180|                            |
+------+--------+----------------------------+
|170   |     250|alcohol, smoking, overweight|
+------+--------+----------------------------+

Is there anyway of not hardcoding this and doing this without Pandas and saving it to a location?

Body:
I used pandas to deal with the value and to save it as a csv file.

I loaded the json format data as a dataframe.

By transposing the data, I got 'unhealty' columne

By using json_normalize(), I parsed the nested dictionary data, 'healthy' and generated two columns into 'height' and 'weight'

concat the 'healthy' and 'height', 'weight' columns

saved the dataframe as a csv file.

import pandas as pd

val = {
    0: {'healthy': {'height': 160, 'weight': 180},
        'unhealthy': None},
    1: {'healthy': {'height': 170, 'weight': 250},
        'unhealthy': 'alcohol, smoking, overweight'}
}

df = pd.DataFrame.from_dict(val)
df = df.transpose()
df = pd.concat([pd.json_normalize(df['healthy'], max_level=1), df['unhealthy']], axis=1)
df.to_csv('filename.csv', index=False) # A csv file generated.

This is the csv file I generated (I opend it using MS Excel).


问:
AWS EC2 Export Instance Task Status
I am exporting an EC2 Instance to a VM by following steps give here:
https://docs.aws.amazon.com/vm-import/latest/userguide/vmexport.html

Under Monitor an instance export task, the Status shows as "Active" since about 6 hours now. Data is around 160GB on instance.

```<code>{
    "ExportTasks": [
        {
            "ExportTaskId": "export-i-<ID>",
            "ExportToS3Task": {
                "ContainerFormat": "ova",
                "DiskImageFormat": "vmdk",
                "S3Bucket": "exportedvmec2",
                "S3Key": "export-i-<ID>.ova"
            },
            "InstanceExportDetails": {},
            "State": "active"
        }
    ]
}
</code>```

How long it takes for this to complete? Also, how do we make sure that this has not gone "Frozen"?

答: It seems that there is not much information about it.. In my case I had a 500GB vm, and it took almost 18 hours.</p>

Title: AWS EC2 Export Instance Task Status

Body:
I am exporting an EC2 Instance to a VM by following steps give here:
https://docs.aws.amazon.com/vm-import/latest/userguide/vmexport.html

Under Monitor an instance export task, the Status shows as "Active" since about 6 hours now. Data is around 160GB on instance.

{
    "ExportTasks": [
        {
            "ExportTaskId": "export-i-<ID>",
            "ExportToS3Task": {
                "ContainerFormat": "ova",
                "DiskImageFormat": "vmdk",
                "S3Bucket": "exportedvmec2",
                "S3Key": "export-i-<ID>.ova"
            },
            "InstanceExportDetails": {},
            "State": "active"
        }
    ]
}

How long it takes for this to complete? Also, how do we make sure that this has not gone "Frozen"?


问:
Why am I getting postcss warnings when I'm not using it?
I'm using NX to build a React demo and it has a dependency of postcss however I'm not using it and none of my webpack configs or anything else is using it either... Yet when I run yarn start I get the following warning in my CLI.

```<code>You did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js.
</code>```

答: Looks like the issue has been resolved as @hallvors pointed out in this PR https://github.com/nrwl/nx/pull/5420</p>

Body:
I'm using NX to build a React demo and it has a dependency of postcss however I'm not using it and none of my webpack configs or anything else is using it either... Yet when I run yarn start I get the following warning in my CLI.

You did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js.


问:
Change order of categorical bars in Plotly parallel categories
I am trying to visualize changes in gene expression as categorical variables (up, down, no change) over various timepoints.

I have a dataframe describing differential expression data that looks like this:

```<code>data = {'gene':['Svm3G0018840','Svm5G0011050','Svm9G0059770'],
        '01h': ['nc','up','down'], '04h': ['up', 'down', 'nc'],'08h':['nc','down','up']}
df=pd.DataFrame.from_dict(data)
df=df.set_index('gene')
</code>```

I can use this df to create the parallel plot using the following code:

```<code>fig = px.parallel_categories(herbdf, dimensions=['01h', '04h', '08h','24h','48h'],
                labels={'01h':'', '04h':'', '08h':'','24h':'','48h':''})

fig.show()
</code>```

However, the categories (up, down, nc) are not always in the same order for every time point which makes the figure very difficult to read. I can change this in the interactive figure in a notebook, but I only have the option to output the corrected figure as a low quality png. I need the image in an svg format, which means I need to use the line:

```<code>fig.write_image("/figs/herb_de_pp.svg")
</code>```

But when I add this line in the code block to save the figure I have no control of the order the categorical boxes end up in:

I have tried to add fig.update_ lines to solve this problem, such as:

```<code>fig.update_layout(xaxis={'categoryorder':'total descending'})
</code>```

but this doesn't seem to change the output at all.

I could be missing something simple- any help would be much appreciated!

答:
not great answer here, but something that I think will work in a pinch...

It looks like the order of the categories of each figure/column come from the order that they are in the original dataset. That is, in your first column, nc is the first unique item, then down is the second unique item, up is third.

So, if you can rearrange/sort your data so that the data shows up in the order you want it displayed, that should work.

Have your first row be nc | nc | nc | nc | nc, second row down | down | down | down | down, and third row up | up | up | up | up (assuming you actually have records like that). That should do it, but isn't very elegant...

Body:
I am trying to visualize changes in gene expression as categorical variables (up, down, no change) over various timepoints.

I have a dataframe describing differential expression data that looks like this:

data = {'gene':['Svm3G0018840','Svm5G0011050','Svm9G0059770'],
        '01h': ['nc','up','down'], '04h': ['up', 'down', 'nc'],'08h':['nc','down','up']}
df=pd.DataFrame.from_dict(data)
df=df.set_index('gene')

I can use this df to create the parallel plot using the following code:

fig = px.parallel_categories(herbdf, dimensions=['01h', '04h', '08h','24h','48h'],
                labels={'01h':'', '04h':'', '08h':'','24h':'','48h':''})

fig.show()

However, the categories (up, down, nc) are not always in the same order for every time point which makes the figure very difficult to read. I can change this in the interactive figure in a notebook, but I only have the option to output the corrected figure as a low quality png. I need the image in an svg format, which means I need to use the line:

fig.write_image("/figs/herb_de_pp.svg")

But when I add this line in the code block to save the figure I have no control of the order the categorical boxes end up in:

I have tried to add fig.update_ lines to solve this problem, such as:

fig.update_layout(xaxis={'categoryorder':'total descending'})

but this doesn't seem to change the output at all.

I could be missing something simple- any help would be much appreciated!


问:
use std::fill to populate vector with increasing numbers
I would like to fill a vector<int> using std::fill, but instead of one value, the vector should contain numbers in increasing order after.

I tried achieving this by iterating the third parameter of the function by one, but this would only give me either vectors filled with 1 or 2 (depending of the position of the ++ operator).

Example:

```<code>vector<int> ivec;
int i = 0;
std::fill(ivec.begin(), ivec.end(), i++); // elements are set to 1
std::fill(ivec.begin(), ivec.end(), ++i); // elements are set to 2
</code>```

答:
The best way I've found would be to use std::generate_n with std::back_insert_iterator. This example is actually given in the cppreference page for std::back_insert_iterator. One change I would make to this example, however, would be to reserve the number of inserts you are about to make to minimize reallocations like so:

```<code>std::vector<int> v;
v.reserve(10);
std::generate_n(std::back_insert_iterator<std::vector<int>>(v), 10, [n=0]() mutable { return ++n; });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to fill a vector<int> using std::fill, but instead of one value, the vector should contain numbers in increasing order after.

I tried achieving this by iterating the third parameter of the function by one, but this would only give me either vectors filled with 1 or 2 (depending of the position of the ++ operator).

Example:

vector<int> ivec;
int i = 0;
std::fill(ivec.begin(), ivec.end(), i++); // elements are set to 1
std::fill(ivec.begin(), ivec.end(), ++i); // elements are set to 2

Body:
The best way I've found would be to use std::generate_n with std::back_insert_iterator. This example is actually given in the cppreference page for std::back_insert_iterator. One change I would make to this example, however, would be to reserve the number of inserts you are about to make to minimize reallocations like so:

std::vector<int> v;
v.reserve(10);
std::generate_n(std::back_insert_iterator<std::vector<int>>(v), 10, [n=0]() mutable { return ++n; });


问:
How to run lammps with GPU package in windows10?
I installed LAMMPS on WIndows 10 to perform calculations on the GPU.
Calculations on a very small scale completed without any problems, but when calculating a structure of some scale, I got the following error.

OpenCL error in file '/home/akohlmey/compile/lammps-packages/mingw-cross/lammps/lib/gpu/geryon/ocl_kernel.h' in line 467 : -4.

What kind of operation can I do to solve this?
My English is poor, but thank you for your kindness.

答:
It is more easy to run Lammps on Linux, you can create a virtual machine and then run your programs. I use Ubuntu and i doesn't have that kind of errors.

I hope my comment help you.

https://docs.lammps.org/Install_linux.html


问:
Learning Liquid - Shopify (where is issue on this code section)
im learning liquid language, and using visual code editor, i'm folliwing rules about writting with, but at the moment it shows me some issue on this section code, its about "Liquid syntax error (line 18): 'for' tag was never closed"

anyone is able to tell me where can i fix that?

```<code><div class="page-width">
  <div class="custom-content section-block">
    {%- liquid
   for block in section.blocks
     case block.settings.width
      when '25%'
        assign block_width = 'small--one-whole one-quarter'
      when '33%'
        assign block_width = 'small--one-whole one-third'
      when '50%'
        assign block_width = 'small--one-whole one-half'
      when '66%'
        assign block_width = 'small--one-whole two-thirds'
      when '75%'
         assign block_width = 'small--one-whole three-quarters'
       when '100%'
         assign block_width = 'one-whole'
    endcase -%}
    <div id="section-block-returns" class="section-block--padding grid__item {{ block_width }} {% if block.settings.alignment %}align--{{ block.settings.alignment }}{% endif %}" {{ block.shopify_attributes }}>
      <div class="grid__item-inner grid__item-inner--{{ block.type }}">
        <div class="rte">
          {{ block.settings.code }}
        </div>
      </div>
    </div>
  {% endfor %}
  </div>
</div>
</code>```

答:
You forgot to close the 'for loop' with the closing tag 'endfor', place it right after the 'endcase' closing tag. Like this:

```<code>{%- liquid
 for block in section.blocks
   case block.settings.width
    when '25%'
      assign block_width = 'small--one-whole one-quarter'
    when '33%'
      assign block_width = 'small--one-whole one-third'
    when '50%'
      assign block_width = 'small--one-whole one-half'
    when '66%'
      assign block_width = 'small--one-whole two-thirds'
    when '75%'
       assign block_width = 'small--one-whole three-quarters'
     when '100%'
       assign block_width = 'one-whole'
    endcase
  endfor -%}
</code>```

Hopefully it will work now

Body:
im learning liquid language, and using visual code editor, i'm folliwing rules about writting with, but at the moment it shows me some issue on this section code, its about "Liquid syntax error (line 18): 'for' tag was never closed"

anyone is able to tell me where can i fix that?

    {%- liquid
   for block in section.blocks
     case block.settings.width
      when '25%'
        assign block_width = 'small--one-whole one-quarter'
      when '33%'
        assign block_width = 'small--one-whole one-third'
      when '50%'
        assign block_width = 'small--one-whole one-half'
      when '66%'
        assign block_width = 'small--one-whole two-thirds'
      when '75%'
         assign block_width = 'small--one-whole three-quarters'
       when '100%'
         assign block_width = 'one-whole'
    endcase -%}

          {{ block.settings.code }}

  {% endfor %}

Body:
You forgot to close the 'for loop' with the closing tag 'endfor', place it right after the 'endcase' closing tag. Like this:

{%- liquid
 for block in section.blocks
   case block.settings.width
    when '25%'
      assign block_width = 'small--one-whole one-quarter'
    when '33%'
      assign block_width = 'small--one-whole one-third'
    when '50%'
      assign block_width = 'small--one-whole one-half'
    when '66%'
      assign block_width = 'small--one-whole two-thirds'
    when '75%'
       assign block_width = 'small--one-whole three-quarters'
     when '100%'
       assign block_width = 'one-whole'
    endcase
  endfor -%}

Hopefully it will work now


问:
Is there a way I can programmatically attach a large file to an outlook message despite it exceeding the server size limit?
A quick note in case you come upon this question hoping for a solution.... there isn't one. Sadly sometimes one has to accept that the right answer to one's question is "You can't do that".

I am hoping there is something I can do here to ensure that attaching a large file to an Outlook.MailItem works exactly the same as doing so manually.

To be precise... when a user composes an email in Outlook and they attach a file that is too large to the email, Outlook will happily attach the file to the email. Instead of simply refusing to do so, it will attach the file and a message will appear in the Inspector:

However....

When coding a similar action you would get access to an Outlook.MailItem and you would invoke the .Add method on its .Attachments object

```<code>oMailObject.Attachments.Add("<path to a file that is way too big here>")
</code>```

The problem is that that action fails. An error is thrown
"The file you're attaching is bigger than the server allows. Try putting the file in a shared location and sending a link instead."

Yes, we can obviously catch the error and then show a message to the user. That's what we're currently doing. It would, however, be nicer if there were a way I can prevent it from raising the error so it would still attach the file to the MailItem, and then when I show the inspector to the user they would see the same thing they would see if they had attached the attachment manually.

Is there an option on the MailItem to prevent it raising an error? Something in the Attachments.Add method? Any suggestions?

答:
The Attachments.Add method doesn't provide anything for that.

You may consider adjusting the maximum size of the attachments in Outlook. Regular mail profiles can be configured using the windows registry keys.

```<code>HKEY_CURRENT_USER\Software\Microsoft\Office\<x.0>\Outlook\Preferences
HKEY_CURRENT_USER\Software\Policies\Microsoft\Office\ x.0 \Outlook\Preferences
</code>```

There you can add a value type: DWORD
Value name: MaximumAttachmentSize
Value data: An integer that specifies the total maximum allowable attachment size. For example, specify 30720 (Decimal) to configure a 30-MB limit. Specify a value of zero (0) if you want to configure no limit for attachments.

Exchange accounts require configuration on the Exchange side, read more about that in the Microsoft Exchange Server email account configuration section.

Body:
A quick note in case you come upon this question hoping for a solution.... there isn't one. Sadly sometimes one has to accept that the right answer to one's question is "You can't do that".

I am hoping there is something I can do here to ensure that attaching a large file to an Outlook.MailItem works exactly the same as doing so manually.

To be precise... when a user composes an email in Outlook and they attach a file that is too large to the email, Outlook will happily attach the file to the email. Instead of simply refusing to do so, it will attach the file and a message will appear in the Inspector:

However....

When coding a similar action you would get access to an Outlook.MailItem and you would invoke the .Add method on its .Attachments object

oMailObject.Attachments.Add("<path to a file that is way too big here>")

The problem is that that action fails. An error is thrown
"The file you're attaching is bigger than the server allows. Try putting the file in a shared location and sending a link instead."

Yes, we can obviously catch the error and then show a message to the user. That's what we're currently doing. It would, however, be nicer if there were a way I can prevent it from raising the error so it would still attach the file to the MailItem, and then when I show the inspector to the user they would see the same thing they would see if they had attached the attachment manually.

Is there an option on the MailItem to prevent it raising an error? Something in the Attachments.Add method? Any suggestions?

Body:
The Attachments.Add method doesn't provide anything for that.

You may consider adjusting the maximum size of the attachments in Outlook. Regular mail profiles can be configured using the windows registry keys.

HKEY_CURRENT_USER\Software\Microsoft\Office\<x.0>\Outlook\Preferences
HKEY_CURRENT_USER\Software\Policies\Microsoft\Office\ x.0 \Outlook\Preferences

There you can add a value type: DWORD
Value name: MaximumAttachmentSize
Value data: An integer that specifies the total maximum allowable attachment size. For example, specify 30720 (Decimal) to configure a 30-MB limit. Specify a value of zero (0) if you want to configure no limit for attachments.

Exchange accounts require configuration on the Exchange side, read more about that in the Microsoft Exchange Server email account configuration section.


问:
How do you store an UInt64 in CoreData?
My understanding is that a UInt64 can be any value from: 0 to 18446744073709551615

I need to save a UInt64 identifier to CoreData, however the values I see are:

I initially tried Integer 64 but now I am understanding that has a range of: -9223372036854775808 to 9223372036854775807

Do developers usually store an UInt64 as a String and do conversions between the two types?  Is this the best practice?

答:
The accepted answer by Martin R will work.

However it appears that this is part of the default implementation of @NSManaged properties by Apple.

I tested it like so:

I created a new Xcode project with Core Data and made a single Entity called Hello.

It has a single attribute called short which is saved as an Integer 16.

Marked Codegen as Manual/None

Created the manual class file for Hello as follows:

```<code>class Hello: NSManagedObject {
    @NSManaged var short : UInt16
}
</code>```

You'll notice that I've typed it as an unsigned UInt16.

In my AppDelegate:

```<code>func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Get Context
        let context = self.persistentContainer.viewContext

        // Create Test Objects
        let hello1 = Hello(entity: Hello.entity(), insertInto: context)
        hello1.short = 255
        let hello2 = Hello(entity: Hello.entity(), insertInto: context)
        hello2.short = 266 // Should overflow Int16
        let hello3 = Hello(entity: Hello.entity(), insertInto: context)
        hello3.short = 65535 // Should overflow Int16 by a lot

        // Save them to the database
        do {
            try context.save()
        } catch {
            print(error)
        }

        // Fetch the save objects
        let fetch = NSFetchRequest<Hello>(entityName: "Hello")
        if let results = try? context.fetch(fetch) {
            for result in results {
                print(result.short)
            }
        }
    }
</code>```

This prints out the following:

```<code>255
266
65535
</code>```

Which I imagine is what someone would want from saving unsigned ints in Core Data.

Title: How do you store an UInt64 in CoreData?

Body:
The accepted answer by Martin R will work.

However it appears that this is part of the default implementation of @NSManaged properties by Apple.

I tested it like so:

I created a new Xcode project with Core Data and made a single Entity called Hello.

It has a single attribute called short which is saved as an Integer 16.

Marked Codegen as Manual/None

Created the manual class file for Hello as follows:

class Hello: NSManagedObject {
    @NSManaged var short : UInt16
}

You'll notice that I've typed it as an unsigned UInt16.

In my AppDelegate:

func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Get Context
        let context = self.persistentContainer.viewContext

        // Create Test Objects
        let hello1 = Hello(entity: Hello.entity(), insertInto: context)
        hello1.short = 255
        let hello2 = Hello(entity: Hello.entity(), insertInto: context)
        hello2.short = 266 // Should overflow Int16
        let hello3 = Hello(entity: Hello.entity(), insertInto: context)
        hello3.short = 65535 // Should overflow Int16 by a lot

        // Save them to the database
        do {
            try context.save()
        } catch {
            print(error)
        }

        // Fetch the save objects
        let fetch = NSFetchRequest<Hello>(entityName: "Hello")
        if let results = try? context.fetch(fetch) {
            for result in results {
                print(result.short)
            }
        }
    }

This prints out the following:

255
266
65535

Which I imagine is what someone would want from saving unsigned ints in Core Data.


问:
Snap applications not showing in "show applications", Ubuntu 20.04
Yesterday, after Ubuntu (or maybe Dell) installed some updates and I restarted, my snap applications were not showing on my sidebar, nor are they present in "show applications" or a normal search.

They are still installed and snap list still shows them, and they will still run via snap run <application>.

I've tried uninstalling them all (although I did not use --purge when I ran snap remove <application>), followed by uninstalling snap itself, then re-installing everything. They are still present but not showing up.

More searching has brought me to sites referencing the XDG_DATA_DIRS environment variable (explained HERE). If I understand correctly this should link all the folders where applications are stored, and the paths within should be separated by colons, not spaces. Thus I ran echo $XDG_DATA_DIRS and was rewarded with:

/usr/local/share/:/usr/share/:/var/lib/snapd/desktop /var/lib/snapd/desktop /var/lib/snapd/desktop

So I suspect my issue is the facts that the snapd directory is listed three times, and it is separated by spaces.

Does anyone have any ideas how I could fix this? I suspect, but am not certain that this is the issue.

I'm on Ubuntu 20.04, using fish shell.

I've found THIS post showing a possible solution, and upon running sudo ag "XDG_DATA_DIRS=" / 2>/dev/null | grep -v snap (and waiting a while) I got the following output (minus a few auth.log references which I've removed) Apologies for the big, possibly irreverent, "data dump"

```<code>/etc/profile.d/xdg_dirs_desktop_session.sh:4:DEFAULT_XDG_DATA_DIRS='/usr/local/share/:/usr/share/'
/etc/profile.d/xdg_dirs_desktop_session.sh:18:       XDG_DATA_DIRS="$DEFAULT_XDG_DATA_DIRS"
/etc/profile.d/xdg_dirs_desktop_session.sh:21:       XDG_DATA_DIRS=/usr/share/"$DESKTOP_SESSION":"$XDG_DATA_DIRS"
/etc/profile.d/apps-bin-path.sh:12:    export XDG_DATA_DIRS="/usr/local/share:/usr/share"
/etc/X11/Xsession.d/55gnome-session_gnomerc:17:      XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/
/etc/X11/Xsession.d/55gnome-session_gnomerc:19:      XDG_DATA_DIRS=/usr/share/gnome:"$XDG_DATA_DIRS"
/etc/X11/Xsession.d/60x11-common_xdg_path:5:DEFAULT_XDG_DATA_DIRS='/usr/local/share/:/usr/share/'
/etc/X11/Xsession.d/60x11-common_xdg_path:17:       XDG_DATA_DIRS="$DEFAULT_XDG_DATA_DIRS"
/etc/X11/Xsession.d/60x11-common_xdg_path:20:       XDG_DATA_DIRS=/usr/share/"$DESKTOP_SESSION":"$XDG_DATA_DIRS"
/usr/share/doc/gnome-software/README.md:24:$ XDG_DATA_DIRS=install/share:$XDG_DATA_DIRS ./install/bin/gnome-software
</code>```

I'm not certain I have found the correct places to think about updating the environment variable, as none of these referenced /var/lib/snaped/desktop...And this might not be the issue causing the problem at all! Any help would be welcome!

答:
I am also having the same problem (suddenly Firefox disappeared in Gnome Shell) and I'm using Ubuntu 21.10 with fish shell. And just like you I could not figure out what caused this XDG_DATA_DIRS modification with the separation by spaces. Because you apparently also use fish I tried switching back to bash as login shell (chsh -s /bin/bash), rebooted and voila, the desktop files are loaded again. After that I set fish as the command to start with in gnome-terminal.

TLDR: My quickfix/workaround was chsh -s /bin/bash to switch to bash as login shell (instead of fish) and reboot.

Body:
Yesterday, after Ubuntu (or maybe Dell) installed some updates and I restarted, my snap applications were not showing on my sidebar, nor are they present in "show applications" or a normal search.

They are still installed and snap list still shows them, and they will still run via snap run <application>.

I've tried uninstalling them all (although I did not use --purge when I ran snap remove <application>), followed by uninstalling snap itself, then re-installing everything. They are still present but not showing up.

More searching has brought me to sites referencing the XDG_DATA_DIRS environment variable (explained HERE). If I understand correctly this should link all the folders where applications are stored, and the paths within should be separated by colons, not spaces. Thus I ran echo $XDG_DATA_DIRS and was rewarded with:

/usr/local/share/:/usr/share/:/var/lib/snapd/desktop /var/lib/snapd/desktop /var/lib/snapd/desktop

So I suspect my issue is the facts that the snapd directory is listed three times, and it is separated by spaces.

Does anyone have any ideas how I could fix this? I suspect, but am not certain that this is the issue.

I'm on Ubuntu 20.04, using fish shell.

I've found THIS post showing a possible solution, and upon running sudo ag "XDG_DATA_DIRS=" / 2>/dev/null | grep -v snap (and waiting a while) I got the following output (minus a few auth.log references which I've removed) Apologies for the big, possibly irreverent, "data dump"

/etc/profile.d/xdg_dirs_desktop_session.sh:4:DEFAULT_XDG_DATA_DIRS='/usr/local/share/:/usr/share/'
/etc/profile.d/xdg_dirs_desktop_session.sh:18:       XDG_DATA_DIRS="$DEFAULT_XDG_DATA_DIRS"
/etc/profile.d/xdg_dirs_desktop_session.sh:21:       XDG_DATA_DIRS=/usr/share/"$DESKTOP_SESSION":"$XDG_DATA_DIRS"
/etc/profile.d/apps-bin-path.sh:12:    export XDG_DATA_DIRS="/usr/local/share:/usr/share"
/etc/X11/Xsession.d/55gnome-session_gnomerc:17:      XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/
/etc/X11/Xsession.d/55gnome-session_gnomerc:19:      XDG_DATA_DIRS=/usr/share/gnome:"$XDG_DATA_DIRS"
/etc/X11/Xsession.d/60x11-common_xdg_path:5:DEFAULT_XDG_DATA_DIRS='/usr/local/share/:/usr/share/'
/etc/X11/Xsession.d/60x11-common_xdg_path:17:       XDG_DATA_DIRS="$DEFAULT_XDG_DATA_DIRS"
/etc/X11/Xsession.d/60x11-common_xdg_path:20:       XDG_DATA_DIRS=/usr/share/"$DESKTOP_SESSION":"$XDG_DATA_DIRS"
/usr/share/doc/gnome-software/README.md:24:$ XDG_DATA_DIRS=install/share:$XDG_DATA_DIRS ./install/bin/gnome-software

I'm not certain I have found the correct places to think about updating the environment variable, as none of these referenced /var/lib/snaped/desktop...And this might not be the issue causing the problem at all! Any help would be welcome!


问:
How can I split a String and keep the delimiters in Swift?
I am new to Swift, I come from Java background. I want to make a struct for parsing input for a calculator. Here is my code

```<code>struct Parse {
    var runningCalc: String

    init(runningCalc: String) {
        self.runningCalc = runningCalc
    }

    mutating func toArray(String: runningCalc){
        runningCalc = runningCalc.split()
    }
}
</code>```

I want to have input of a string, and have it return a string Array with delimiters of
{ +-/*()%}.

In java you could do a string tokenizer to keep the delimiters in the returned string array.

How can I use the split or components method to separate my string input to a string array?

答:
AFAIK there is no native Swift split method that allows you to keep the delimiters. You will need to implement your own split method extending Collection. Special thanks for @MartinR and @Rob for the code review:

```<code>extension Collection {
    func splitAndKeep(
        maxSplits: Int = .max,
        omittingEmptySubsequences: Bool = true,
        whereSeparator isSeparator: (Element) throws -> Bool
    ) rethrows -> [SubSequence] {
        precondition(maxSplits >= 0, "maxSplits can not be negative")
        if isEmpty { return [] }
        var subsequences: [SubSequence] = []
        var lowerBound = startIndex
        func appendAndAdvance(with upperBound: Index) {
            let range = lowerBound..<upperBound
            if !omittingEmptySubsequences || !range.isEmpty {
                subsequences.append(self[range])
                lowerBound = upperBound
            }
        }
        while
            var upperBound = try self[lowerBound...].firstIndex(where: isSeparator),
            subsequences.count < maxSplits {
            appendAndAdvance(with: upperBound)
            if subsequences.count == maxSplits {
                break
            }
            formIndex(after: &upperBound)
            appendAndAdvance(with: upperBound)
        }
        appendAndAdvance(with: endIndex)
        return subsequences
    }
}
</code>```

```<code>let string = "*(22+13)/"
let delimiters = Set<Character>("{+-/*()%}.")

let ss = string.splitAndKeep(whereSeparator: delimiters.contains)  // ["*", "(", "22", "+", "13", ")", "/"]
let ss1 = string.splitAndKeep(maxSplits: 0, whereSeparator: delimiters.contains)  // ["*(22+13)/"]
let ss2 = string.splitAndKeep(maxSplits: 1, whereSeparator: delimiters.contains)  // ["*", "(22+13)/"]
let ss3 = string.splitAndKeep(maxSplits: 2, whereSeparator: delimiters.contains)  // ["*", "(", "22+13)/"]

let ss4 = string.splitAndKeep(omittingEmptySubsequences: false, whereSeparator: delimiters.contains)  // ["", "*", "", "(", "22", "+", "13", ")", "", "/", ""]["", "*", "", "(", "22", "+", "13", ")", "", "/", ""]
let ss5 = string.splitAndKeep(maxSplits: 0, omittingEmptySubsequences: false, whereSeparator: delimiters.contains)  // ["*(22+13)/"]
let ss6 = string.splitAndKeep(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: delimiters.contains)  // ["", "*(22+13)/"]
let ss7 = string.splitAndKeep(maxSplits: 2, omittingEmptySubsequences: false, whereSeparator: delimiters.contains)  // ["", "*", "(22+13)/"]
</code>```

Body:
I am new to Swift, I come from Java background. I want to make a struct for parsing input for a calculator. Here is my code

struct Parse {
    var runningCalc: String

    init(runningCalc: String) {
        self.runningCalc = runningCalc
    }

    mutating func toArray(String: runningCalc){
        runningCalc = runningCalc.split()
    }
}

I want to have input of a string, and have it return a string Array with delimiters of
{ +-/*()%}.

In java you could do a string tokenizer to keep the delimiters in the returned string array.

How can I use the split or components method to separate my string input to a string array?

Body:
AFAIK there is no native Swift split method that allows you to keep the delimiters. You will need to implement your own split method extending Collection. Special thanks for @MartinR and @Rob for the code review:

extension Collection {
    func splitAndKeep(
        maxSplits: Int = .max,
        omittingEmptySubsequences: Bool = true,
        whereSeparator isSeparator: (Element) throws -> Bool
    ) rethrows -> [SubSequence] {
        precondition(maxSplits >= 0, "maxSplits can not be negative")
        if isEmpty { return [] }
        var subsequences: [SubSequence] = []
        var lowerBound = startIndex
        func appendAndAdvance(with upperBound: Index) {
            let range = lowerBound..<upperBound
            if !omittingEmptySubsequences || !range.isEmpty {
                subsequences.append(self[range])
                lowerBound = upperBound
            }
        }
        while
            var upperBound = try self[lowerBound...].firstIndex(where: isSeparator),
            subsequences.count < maxSplits {
            appendAndAdvance(with: upperBound)
            if subsequences.count == maxSplits {
                break
            }
            formIndex(after: &upperBound)
            appendAndAdvance(with: upperBound)
        }
        appendAndAdvance(with: endIndex)
        return subsequences
    }
}

let string = "*(22+13)/"
let delimiters = Set<Character>("{+-/*()%}.")

let ss = string.splitAndKeep(whereSeparator: delimiters.contains)  // ["*", "(", "22", "+", "13", ")", "/"]
let ss1 = string.splitAndKeep(maxSplits: 0, whereSeparator: delimiters.contains)  // ["*(22+13)/"]
let ss2 = string.splitAndKeep(maxSplits: 1, whereSeparator: delimiters.contains)  // ["*", "(22+13)/"]
let ss3 = string.splitAndKeep(maxSplits: 2, whereSeparator: delimiters.contains)  // ["*", "(", "22+13)/"]

let ss4 = string.splitAndKeep(omittingEmptySubsequences: false, whereSeparator: delimiters.contains)  // ["", "*", "", "(", "22", "+", "13", ")", "", "/", ""]["", "*", "", "(", "22", "+", "13", ")", "", "/", ""]
let ss5 = string.splitAndKeep(maxSplits: 0, omittingEmptySubsequences: false, whereSeparator: delimiters.contains)  // ["*(22+13)/"]
let ss6 = string.splitAndKeep(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: delimiters.contains)  // ["", "*(22+13)/"]
let ss7 = string.splitAndKeep(maxSplits: 2, omittingEmptySubsequences: false, whereSeparator: delimiters.contains)  // ["", "*", "(22+13)/"]


问:
BAT script to copy files from Windows to remote Linux systems
Is there anyway to copy files from Windows machine to a remote Linux machine with a DOS command/other command-line tool (by specifying username and password in the command). I normally do this using WinSCP and would like to write a script (BAT) to automate this.</p>

答:
If anyone is looking to do this in 2022, Windows 10 now comes with scp. You can do

scp path/localfile.txt remote-user@host:/home/path

or the recursive version for directories

scp -r localfolder remote-user@host:/home/path

Of course with scp you'll run into issues if you have a large number of files. It copies everything as opposed to only changed / new files only.

Then you'll need a tool like rsync, which is available through WSL (windows subsystem linux).

rsync -r localfolder remote-user@host:/home/path

(I personally hesitate to install new tools for a job, hence my desire to stick with what's already available)


问:
GCP - How to update api specification in API Gateway
I have created an API Gateway and created an API config as well associated with it which lists a set of APIs. Now I want to add/modify a set of APIs. How do I update the same API config of this gateway?</p>

答:
I did it using gcloud CLI.

First create a new config using your updated open api spec file:

```<code>gcloud api-gateway api-configs create NEW_CONFIG_ID --api=MY_API --openapi-spec=openapi2-functions.yaml
</code>```

Then update your api gateway with new config:

```<code>gcloud api-gateway gateways update MY-GATEWAY --api=MY-API --api-config=NEW_CONFIG_ID --location=YOUR_LOCATION
</code>```

Body:
I did it using gcloud CLI.

First create a new config using your updated open api spec file:

gcloud api-gateway api-configs create NEW_CONFIG_ID --api=MY_API --openapi-spec=openapi2-functions.yaml

Then update your api gateway with new config:

gcloud api-gateway gateways update MY-GATEWAY --api=MY-API --api-config=NEW_CONFIG_ID --location=YOUR_LOCATION


问:
How to retrieve a JWT access token from Azure B2C using `NextAuth.js`
my infrastructure is as follows:

I have a back-end Web API that uses Azure B2C authentication (respectively via JWT tokens)

I have a front-end app written on Next.js and it uses NextAuth.js to manage the authentication.

Everything seems ok - I can authenticate users in the front-end with the registered identity providers but... I need to call the back-end with an access token from Azure B2C so my requests are authenticated.

What is the correct way of managing this access token? I could not find any information about whether or not I should generate it by myself or there is some mechanism to simplify all this?

There is another question I would like to discuss - is NextAuth.js the correct library for my use case? I mean, there is more documentation and examples for @azure/msal-react, it is specialized into this matter, so is it the better option?

答:
NextAuth.js is a fine library to use for this.

You can put the accessToken that AzureB2C gives you for the signed-in user into their session JWT in the jwt callback in your NextAuth.js config.

See docs about exactly this use-case here: https://next-auth.js.org/configuration/callbacks#jwt-callback
See another example of it in action here: https://github.com/nextauthjs/next-auth-refresh-token-example/blob/57f84dbc50f30233d4ee389c7239212858ecae14/pages/api/auth/%5B...nextauth%5D.js#L67

Once you have it in the session JWT, you can use the getToken() method in Next.js API routes, for example, to retrieve the token and make calls with it, etc.


问:
Graphql is returning the promise and not my DynamoDB data
I am using a Graphql API to access my DynamoDB database. I am then trying to render the list of users in my app. According to the docs I should use:

```<code>import * as queries from './graphql/queries';

const users = await API.graphql({ query: queries.listUsers });
console.log(users);
</code>```

However, I get an error regarding the await. So I removed the await key word, but const users = API.graphql({ query: queries.listUsers }); returns the promise. This is the response:

```<code>Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}
</code>```

I put my code into an async function and used the await keyword and still only got the promise. Is there a way to simply call the query and without the await and get the correct data instead of the promise? I have also been trying to use the GraphQLResult to get the actual result, but that isn't working, I am either getting errors or I am still getting the promise.

答:
using try catch block to handle error of the await
await return the promise result but after remove the await, it just return the promise, you should use then catch to get the result

Body:
I am using a Graphql API to access my DynamoDB database. I am then trying to render the list of users in my app. According to the docs I should use:

import * as queries from './graphql/queries';

const users = await API.graphql({ query: queries.listUsers });
console.log(users);

However, I get an error regarding the await. So I removed the await key word, but const users = API.graphql({ query: queries.listUsers }); returns the promise. This is the response:

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}

I put my code into an async function and used the await keyword and still only got the promise. Is there a way to simply call the query and without the await and get the correct data instead of the promise? I have also been trying to use the GraphQLResult to get the actual result, but that isn't working, I am either getting errors or I am still getting the promise.


问:
How can I get server and stream key from AWS MediaLive
I need to configure live streaming using OBS studio software, live streaming has already been setup on AWS using ElementalMediaLive(auto wizard). but I am unable to figure out the way to find the server address and stream key which are required the configure the OBS studio.
can some one please guid me where can I find the above required information into AWS panel?
Thanks

答:
What OBS refers to as "stream key" is the App Instance.

Regards,


问:
How do I aggregate and avg the time between two dates?
Assuming the below is my element structure. How can I SHELL query the mongodb and get the avg difference (average length) each trip took for every trip in the db? I am guessing subtracting dates? But then how to subtract and then avg?

```<code>"_id": {
    "$oid": "5445ab058767000062"
},
"comment": null,
"scheduled_request": false,
"status": "blah",
"timestamp_started": {
    "$date": "2014-10-21T00:38:28.990Z"
},
"timestamp_transaction_complete": {
    "$date": "2014-10-21T00:49:12.990Z"
},
"user_id": "5445a9000057"
</code>```

UDPATE ========
Here is my query

```<code>db.ambulance_requests.aggregate([
  { "$group": {
    "_id": null,
    "avg_time": {
      "$avg": {
        "$subtract": [
          "$timestamp_transaction_complete",
          "$timestamp_started"
        ]
      }
    }
  }}
])
</code>```

AND MY RESULT (from a Mac Terminal Shell):

```<code>{ "_id" : null, "avg_time" : 0 }
</code>```

答:
https://mongoplayground.net/p/nFO54i5GIXU

if finishedAt dose not exist in a doc then skip that document from avg calculation

```<code>db.collection.aggregate([
  {
    "$match": {
      "finishedAt": {
        "$exists": true
      }
    }
  },
  {
    "$unwind": "$tags"
  },
  {
    "$match": {
      "$or": [
        {
          "tags.name": "Canada"
        },
        {
          "tags.name": "ABC"
        },
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "avg_time": {
        "$avg": {
          "$subtract": [
            "$finishedAt",
            "$createdAt"
          ]
        }
      }
    }
  }
])
</code>```

Body:
Assuming the below is my element structure. How can I SHELL query the mongodb and get the avg difference (average length) each trip took for every trip in the db? I am guessing subtracting dates? But then how to subtract and then avg?

"_id": {
    "$oid": "5445ab058767000062"
},
"comment": null,
"scheduled_request": false,
"status": "blah",
"timestamp_started": {
    "$date": "2014-10-21T00:38:28.990Z"
},
"timestamp_transaction_complete": {
    "$date": "2014-10-21T00:49:12.990Z"
},
"user_id": "5445a9000057"

UDPATE ========
Here is my query

db.ambulance_requests.aggregate([
  { "$group": {
    "_id": null,
    "avg_time": {
      "$avg": {
        "$subtract": [
          "$timestamp_transaction_complete",
          "$timestamp_started"
        ]
      }
    }
  }}
])

AND MY RESULT (from a Mac Terminal Shell):

{ "_id" : null, "avg_time" : 0 }

Body:
https://mongoplayground.net/p/nFO54i5GIXU

if finishedAt dose not exist in a doc then skip that document from avg calculation

db.collection.aggregate([
  {
    "$match": {
      "finishedAt": {
        "$exists": true
      }
    }
  },
  {
    "$unwind": "$tags"
  },
  {
    "$match": {
      "$or": [
        {
          "tags.name": "Canada"
        },
        {
          "tags.name": "ABC"
        },
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "avg_time": {
        "$avg": {
          "$subtract": [
            "$finishedAt",
            "$createdAt"
          ]
        }
      }
    }
  }
])


问:
JSON.stringify() array bizarreness with Prototype.js
I'm trying to figure out what's gone wrong with my json serializing, have the current version of my app with and old one and am finding some surprising differences in the way JSON.stringify() works (Using the JSON library from json.org).

In the old version of my app:

```<code> JSON.stringify({"a":[1,2]})
</code>```

gives me this;

```<code>"{\"a\":[1,2]}"
</code>```

in the new version,

```<code> JSON.stringify({"a":[1,2]})
</code>```

gives me this;

```<code>"{\"a\":\"[1, 2]\"}"
</code>```

any idea what could have changed to make the same library put quotes around the array brackets in the new version?

答:
I'm not that fluent with Prototype, but I saw this in its docs:

```<code>Object.toJSON({"a":[1,2]})
</code>```

I'm not sure if this would have the same problem the current encoding has, though.

There's also a longer tutorial about using JSON with Prototype.

OwnerDisplayName: morgancodes

Body:
I'm trying to figure out what's gone wrong with my json serializing, have the current version of my app with and old one and am finding some surprising differences in the way JSON.stringify() works (Using the JSON library from json.org).

In the old version of my app:

 JSON.stringify({"a":[1,2]})

gives me this;

"{\"a\":[1,2]}"

in the new version,

 JSON.stringify({"a":[1,2]})

gives me this;

"{\"a\":\"[1, 2]\"}"

any idea what could have changed to make the same library put quotes around the array brackets in the new version?

LastEditorDisplayName: Matthew Crumley

Body:
I'm not that fluent with Prototype, but I saw this in its docs:

Object.toJSON({"a":[1,2]})

I'm not sure if this would have the same problem the current encoding has, though.

There's also a longer tutorial about using JSON with Prototype.

OwnerDisplayName: R. Bemrose

ContentLicense: CC BY-SA 2.5


问:
How to disable actuator security without disabling it totally with Spring Boot 2
I'm using Spring Boot Security with OAuth2. I wan't to disable security for health endpoint.

I can totally disable security or write my own implementation of WebSecurityConfigurerAdapter and disable autoconfigured one.

But how to modify existing implementation of WebSecurityConfigurerAdapter (OAuth2SsoDefaultConfiguration)?

I tried to create my own configuration without disabling autoconfigured one, but it is impossible due to Order conflicts.

Here is the error message:

```<code>Caused by: java.lang.IllegalStateException: @Order on WebSecurityConfigurers must be unique.
Order of 100 was already used on SecurityConfiguration$$EnhancerBySpringCGLIB$$9505fc58@13f182b9,
 so it cannot be used on
org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2SsoDefaultConfiguration$$EnhancerBySpringCGLIB$$dc290e2b@5ee0cf64 too.
</code>```

Also, I tried to explicitly set higher order for my own security configuration, but looks like autoconfigured one overrides mine.

So how to override specific security rules without reimplementing whole configuration?

答:
management.security.enabled: false

does not work with spring boot 2.x versions

Body:
I'm using Spring Boot Security with OAuth2. I wan't to disable security for health endpoint.

I can totally disable security or write my own implementation of WebSecurityConfigurerAdapter and disable autoconfigured one.

But how to modify existing implementation of WebSecurityConfigurerAdapter (OAuth2SsoDefaultConfiguration)?

I tried to create my own configuration without disabling autoconfigured one, but it is impossible due to Order conflicts.

Here is the error message:

Caused by: java.lang.IllegalStateException: @Order on WebSecurityConfigurers must be unique.
Order of 100 was already used on SecurityConfiguration$$EnhancerBySpringCGLIB$$9505fc58@13f182b9,
 so it cannot be used on
org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2SsoDefaultConfiguration$$EnhancerBySpringCGLIB$$dc290e2b@5ee0cf64 too.

Also, I tried to explicitly set higher order for my own security configuration, but looks like autoconfigured one overrides mine.

So how to override specific security rules without reimplementing whole configuration?


问:
Object.defineProperty to override read-only property
In our NodeJS application, we define custom error classes by extending the default Error object:

```<code>"use strict";
const util = require("util");

function CustomError(message) {
    Error.call(this);
    Error.captureStackTrace(this, CustomError);
    this.message = message;
}

util.inherits(CustomError, Error);
</code>```

This allows us to throw CustomError("Something"); with the stack trace showing up correctly, and both instanceof Error and instanceof CustomError working correctly.

However, for returning errors in our API (over HTTP), we want to convert the error to JSON. Calling JSON.stringify() on an Error results in "{}", which is obviously not really descriptive for the consumer.

To fix this, I thought of overriding CustomError.prototype.toJSON(), to return an object literal with the error name and message. JSON.stringify() would then just stringify this object and all would work great:

```<code>// after util.inherits call

CustomError.prototype.toJSON = () => ({
    name    : "CustomError",
    message : this.message
});
</code>```

However, I quickly saw that this throws a TypeError: Cannot assign to read only property 'toJSON' of Error. Which might make sense as I'm trying to write to the prototype. So I changed the constructor instead:

```<code>function CustomError(message) {
    Error.call(this);
    Error.captureStackTrace(this, CustomError);
    this.message = message;
    this.toJSON = () => ({
        name    : "CustomError",
        message : this.message
    });
}
</code>```

This way (I expected), the CustomError.toJSON function would be used and the CustomError.prototype.toJSON (from Error) would be ignored.

Unfortunately, this just throws the error upon object construction: Cannot assign to read only property 'toJSON' of CustomError.

Next I tried removing "use strict"; from the file, which sort of solved the problem in that no error was being thrown anymore, although the toJSON() function was not used by JSON.stringify() at all.

At this point I'm just desperate and just try random things. Eventually I end up with using Object.defineProperty() instead of directly assigning to this.toJSON:

```<code>function CustomError(message) {
    Error.call(this);
    Error.captureStackTrace(this, CustomError);
    this.message = message;
    Object.defineProperty(this, "toJSON", {
        value: () => ({
            name    : "CustomError",
            message : this.message
        })
    });
</code>```

This works perfectly. In strict mode, no errors are being called, and JSON.stringify() returns {"name:" CustomError", "message": "Something"} like I want it to.

So although it works as I want it to now, I still want to know:

Why does this work exactly? I expect it to be the equivalent to this.toJSON = ... but apparently it is not.

Should it work like this? I.e. is it safe to depend on this behaviour?

If not, how should I override the toJSON method correctly? (if possible at all)

答:
If you truly need to use components or other React features inside your <template> element you can fix the React to render in content by monkey-patching a few of DOM methods of HTMLTemplateElement.

HTMLTemplateElement.prototype.appendChild = function (child) {
  return this.content.appendChild(child);
}

HTMLTemplateElement.prototype.removeChild = function (child) {
  return this.content.removeChild(child);
}

Object.defineProperty(HTMLTemplateElement.prototype, "firstChild", {
  get() {
    return this.content.firstChild;
  }
})
```

I was able to render anything inside a template element after this. The appendChild and removeChild is mandatory because it will be used for render but if you're not using hydration you may not need the firstChild patch.

Body:
In our NodeJS application, we define custom error classes by extending the default Error object:

"use strict";
const util = require("util");

function CustomError(message) {
    Error.call(this);
    Error.captureStackTrace(this, CustomError);
    this.message = message;
}

util.inherits(CustomError, Error);

This allows us to throw CustomError("Something"); with the stack trace showing up correctly, and both instanceof Error and instanceof CustomError working correctly.

However, for returning errors in our API (over HTTP), we want to convert the error to JSON. Calling JSON.stringify() on an Error results in "{}", which is obviously not really descriptive for the consumer.

To fix this, I thought of overriding CustomError.prototype.toJSON(), to return an object literal with the error name and message. JSON.stringify() would then just stringify this object and all would work great:

// after util.inherits call

CustomError.prototype.toJSON = () => ({
    name    : "CustomError",
    message : this.message
});

However, I quickly saw that this throws a TypeError: Cannot assign to read only property 'toJSON' of Error. Which might make sense as I'm trying to write to the prototype. So I changed the constructor instead:

function CustomError(message) {
    Error.call(this);
    Error.captureStackTrace(this, CustomError);
    this.message = message;
    this.toJSON = () => ({
        name    : "CustomError",
        message : this.message
    });
}

This way (I expected), the CustomError.toJSON function would be used and the CustomError.prototype.toJSON (from Error) would be ignored.

Unfortunately, this just throws the error upon object construction: Cannot assign to read only property 'toJSON' of CustomError.

Next I tried removing "use strict"; from the file, which sort of solved the problem in that no error was being thrown anymore, although the toJSON() function was not used by JSON.stringify() at all.

At this point I'm just desperate and just try random things. Eventually I end up with using Object.defineProperty() instead of directly assigning to this.toJSON:

function CustomError(message) {
    Error.call(this);
    Error.captureStackTrace(this, CustomError);
    this.message = message;
    Object.defineProperty(this, "toJSON", {
        value: () => ({
            name    : "CustomError",
            message : this.message
        })
    });

This works perfectly. In strict mode, no errors are being called, and JSON.stringify() returns {"name:" CustomError", "message": "Something"} like I want it to.

So although it works as I want it to now, I still want to know:

Why does this work exactly? I expect it to be the equivalent to this.toJSON = ... but apparently it is not.

Should it work like this? I.e. is it safe to depend on this behaviour?

If not, how should I override the toJSON method correctly? (if possible at all)

Body:
If you truly need to use components or other React features inside your <template> element you can fix the React to render in content by monkey-patching a few of DOM methods of HTMLTemplateElement.

HTMLTemplateElement.prototype.appendChild = function (child) {
  return this.content.appendChild(child);
}

HTMLTemplateElement.prototype.removeChild = function (child) {
  return this.content.removeChild(child);
}

Object.defineProperty(HTMLTemplateElement.prototype, "firstChild", {
  get() {
    return this.content.firstChild;
  }
})

I was able to render anything inside a template element after this. The appendChild and removeChild is mandatory because it will be used for render but if you're not using hydration you may not need the firstChild patch.


问:
How can I get polar-transformed click data for an Shiny interactive ggplot that uses `coord_polar`?
I'm working on an interactive, polar ggplot bar with polar coordinates. The end goal is for the bars in each segment to 'rise' to meet the position of a mouse click in that sector.

The trouble is that click data for polar ggplots is cartesian, rather than polar: The bottom-left of the plot is c(0,0), rather than the centre. How can I get around this problem? Is there a simple coordinate transform I could use, or an option I could set?

You can see a prototype of the app here, and my code is below:

library(shiny)
library(ggplot2)
library(tibble)

xNames <-  c("Authentic", "Visionary", "Sustainable",
             "Inspiring", "Collaborative", "Raising up\nnew leaders")
segments <- length(xNames)

ui <- fluidPage(
mainPanel(
  plotOutput("evaluation_wheel", click = "plot_click"),
  p("Coordinates: "), textOutput("coordinates")
)
)

server <- function(input, output) {

  ## Plot evaluation wheel
  wheel_plot <- function(wheel.data){
    ggplot2::ggplot(wheel.data, aes(x = name, y = value)) +
      geom_bar(stat = "identity") +
      scale_y_continuous(limits = c(0,10)) +
      coord_polar()
  }

  modify_plot_data <- function(click.value, old.plot.data){
    print(click.value)
    if(is.null(click.value))(click.value <- c(0,0))
    else{
      cat("x: ")
      print(click.value$x)
      cat("y: ")
      print(click.value$y)
      click.value <- c(click.value$x, click.value$y)
    }
    click.value <- floor(click.value)
    new.plot.data <- old.plot.data
    new.plot.data[click.value[1]] <- click.value[2]
    new.plot.data
  }

  plotData <- reactiveVal(integer(segments))

    output$evaluation_wheel <- renderPlot({
      # plotData <- modify_plot_data(input$plot_click, plotData)
      plotData(modify_plot_data(input$plot_click, plotData()))

      plotTibble <- tibble(
        name = xNames,
        value = plotData()
      )
      wheel_plot(plotTibble)

    })

    output$coordinates <- renderText({
      paste0("c(", input$plot_click$x, ",", input$plot_click$y, ")")
    })
}

# Run the application
shinyApp(ui = ui, server = server)
```

答:
You "just" need to convert back from polar projection.

```<code> modify_plot_data <- function(click.value, old.plot.data){
    print(click.value)
    if(is.null(click.value))(click.value <- c(0,0))
    else{
      # Number of categories
      N_CAT = length(xNames)
      # Max value
      Y_LIMIT = 10

      # Center and rescale X
      x=(click.value$x -( (N_CAT + 1) / 2 ) ) / N_CAT * Y_LIMIT / .4

      # Center and rescale Y
      y=(click.value$y - ( Y_LIMIT / 2 ) ) / Y_LIMIT * Y_LIMIT / .4

      # Compute angle from X and Y
      angle = atan2( y, x)

      # Compute item number from angle (might be simplified)
      i = (( 5 * pi / 2 - angle ) %% ( 2 * pi )) / pi * ( N_CAT / 2 ) + 1

      # Compute length from angle and X
      j = min( Y_LIMIT, x / cos(angle) ) # length

      click.value <- c(i, j)
    }
    new.plot.data <- old.plot.data
    new.plot.data[floor(click.value[1])] <- click.value[2]
    new.plot.data
  }
</code>```

Also for it to work as-is, you need to sort your values:

```<code>xNames <-  sort(c("Authentic", "Visionary", "Sustainable",
                  "Inspiring", "Collaborative", "Raising up\nnew leaders"))
</code>```

Body:
You "just" need to convert back from polar projection.

 modify_plot_data <- function(click.value, old.plot.data){
    print(click.value)
    if(is.null(click.value))(click.value <- c(0,0))
    else{
      # Number of categories
      N_CAT = length(xNames)
      # Max value
      Y_LIMIT = 10

      # Center and rescale X
      x=(click.value$x -( (N_CAT + 1) / 2 ) ) / N_CAT * Y_LIMIT / .4

      # Center and rescale Y
      y=(click.value$y - ( Y_LIMIT / 2 ) ) / Y_LIMIT * Y_LIMIT / .4

      # Compute angle from X and Y
      angle = atan2( y, x)

      # Compute item number from angle (might be simplified)
      i = (( 5 * pi / 2 - angle ) %% ( 2 * pi )) / pi * ( N_CAT / 2 ) + 1

      # Compute length from angle and X
      j = min( Y_LIMIT, x / cos(angle) ) # length

      click.value <- c(i, j)
    }
    new.plot.data <- old.plot.data
    new.plot.data[floor(click.value[1])] <- click.value[2]
    new.plot.data
  }

Also for it to work as-is, you need to sort your values:

xNames <-  sort(c("Authentic", "Visionary", "Sustainable",
                  "Inspiring", "Collaborative", "Raising up\nnew leaders"))