问:
How to use puppeteer with NordVPN?
Any existing sample on how to use puppeteer with nordVpn ?

I tried that:

```<code>page = await browser.newPage();
await useProxy(page, `socks5://login:password}@fr806.nordvpn.com:1080`);
</code>```

I also tried:

```<code>'--proxy-server=socks5://login:password@fr806.nordvpn.com:1080'
</code>```

答:
This script works, you need to change the user/pass to yours... these are not your Nord user/pass... you need to get the service/api ones from in your account settings. Change the server to whatever one you need to use.</p>
```<code>#!/usr/bin/env node

// Screengrab generator
// outputs a JSON object with a base64 encoded image of the screengrab
// eg;

const puppeteer = require('puppeteer');

let conf          = new Object();

conf.url      = "https://www.telegraph.co.uk";

// VPN
conf.vpnUser   = conf.vpnUSer   || 'USERNAME';
conf.vpnPass   = conf.vpnPass   || 'PASSWORD';
conf.vpnServer = conf.vpnServer || "https://uk1785.nordvpn.com:89";

(async() => {

    const browser = await puppeteer.launch({
            headless: true,
            args: [
                    '--disable-dev-shm-usage',
                    '--proxy-server='+conf.vpnServer
            ]
    });

    try {
      const page = await browser.newPage();

      await page.authenticate({
        username: conf.vpnUser,
        password: conf.vpnPass,
      });

      await page.goto(conf.url, { waitUntil: 'networkidle2' });

    } catch (error) {
        console.error(error);
    } finally {
        await browser.close();
    }

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

Title: How to use puppeteer with NordVPN?

Body:
Any existing sample on how to use puppeteer with nordVpn ?

I tried that:

page = await browser.newPage();
await useProxy(page, `socks5://login:password}@fr806.nordvpn.com:1080`);

I also tried:

'--proxy-server=socks5://login:password@fr806.nordvpn.com:1080'

Body:
This script works, you need to change the user/pass to yours... these are not your Nord user/pass... you need to get the service/api ones from in your account settings. Change the server to whatever one you need to use.

#!/usr/bin/env node

// Screengrab generator
// outputs a JSON object with a base64 encoded image of the screengrab
// eg;

const puppeteer = require('puppeteer');

let conf          = new Object();

conf.url      = "https://www.telegraph.co.uk";

// VPN
conf.vpnUser   = conf.vpnUSer   || 'USERNAME';
conf.vpnPass   = conf.vpnPass   || 'PASSWORD';
conf.vpnServer = conf.vpnServer || "https://uk1785.nordvpn.com:89";

(async() => {

    const browser = await puppeteer.launch({
            headless: true,
            args: [
                    '--disable-dev-shm-usage',
                    '--proxy-server='+conf.vpnServer
            ]
    });

    try {
      const page = await browser.newPage();

      await page.authenticate({
        username: conf.vpnUser,
        password: conf.vpnPass,
      });

      await page.goto(conf.url, { waitUntil: 'networkidle2' });

    } catch (error) {
        console.error(error);
    } finally {
        await browser.close();
    }

})();


来源: stackexchange

问:
When using Vuetify's v-menu, only the first click of the menu is displayed

　What I want to solve

I am using Vuetify to create my calendar. I use a combination of drag and drop and event clicking. I added the Vuetify v-menu so that I can change the color of the event in the popup that appears when clicked. When the button is clicked, the popup to change the color appears. However, the v-menu that I added only responds to the first event, and closes when the button is pressed on the second event. How can I solve this problem?
By the way, no error is shown.

Code

Calendar

<template>
  <v-row class="fill-height">
    <v-col>
      <v-sheet height="600">
        <v-calendar
          ref="calendar"
          v-model="value"
          color="primary"
          type="week"
          :events="events"
          :event-color="getEventColor"
          :event-ripple="false"
          locale="ja-jp"
          :day-format="(timestamp) => new Date(timestamp.date).getDate()"
          :month-format="(timestamp) => (new Date(timestamp.date).getMonth() + 1) + ' /'"
          @change="getEvents"
          @mousedown:event="startDrag"
          @click:event="showEvent"
          @mousedown:time="startTime"
          @mousemove:time="mouseMove"
          @mouseup:time="endDrag"
          @mouseleave.native="cancelDrag"
        >
          <template #event="{ event, timed, eventSummary }">

// A pop-up will appear when you click on it.
////////////////////////////////////////////////////////////////////

            <v-menu
              v-model="selectedOpen"
              :close-on-content-click="false"
              :activator="selectedElement"
              offset-x
            >
              <v-card
                color="grey lighten-2"
                min-width="350px"
                flat
              >
                <v-toolbar>
                  <v-btn icon>
                    <v-icon>mdi-pencil</v-icon>
                  </v-btn>
                  <v-toolbar-title v-html="selectedEvent.name" />
                  <v-spacer />

                    <v-menu offset-y>
                      <template #activator="{ on, attrs }">
                        <v-btn
                          icon
                          v-bind="attrs"
                          v-on="on"
                        >
                          <v-icon
                            :color="selectedEvent.color"
                          >
                            mdi-brightness-1
                          </v-icon>
                        </v-btn>
                      </template>
                      <v-list>
                        <v-list-item
                          v-for="(color, index) in colors"
                          :key="index"
                        >
                          <v-icon
                            :color="color"
                            @click="changeColor(color)"
                          >
                            mdi-brightness-1
                          </v-icon>
                        </v-list-item>
                      </v-list>
                    </v-menu>

////////////////////////////////////////////////////////////////////////////////////

                  <v-btn icon>
                    <v-icon>mdi-dots-vertical</v-icon>
                  </v-btn>
                </v-toolbar>
                <v-card-text>

                </v-card-text>
                <v-card-actions>
                  <v-btn
                    text
                    color="secondary"
                    @click="selectedOpen = false"
                  >
                    Cancel
                  </v-btn>
                </v-card-actions>
              </v-card>
            </v-menu>

          </template>
        </v-calendar>
      </v-sheet>
    </v-col>
  </v-row>
</template>

```

What I've tried.

・I thought it was caused by the v-slot:activator, so I checked it out. As a result, I found out that on has a function to display a popup, but I couldn't find the relevance of this.

答:
In the default configuration of Vuetify, the popup display was controlled by v-model, but I was able to solve this problem by binding with :value.

            <v-menu
             "selectedOpen"
              :value="selectedOpen"
              :close-on-content-click="false"
              :activator="selectedElement"
              offset-x
            >
```

ContentLicense: CC BY-SA 4.0

Body:
　What I want to solve

I am using Vuetify to create my calendar. I use a combination of drag and drop and event clicking. I added the Vuetify v-menu so that I can change the color of the event in the popup that appears when clicked. When the button is clicked, the popup to change the color appears. However, the v-menu that I added only responds to the first event, and closes when the button is pressed on the second event. How can I solve this problem?
By the way, no error is shown.

Code

Calendar

<template>
  <v-row class="fill-height">
    <v-col>
      <v-sheet height="600">
        <v-calendar
          ref="calendar"
          v-model="value"
          color="primary"
          type="week"
          :events="events"
          :event-color="getEventColor"
          :event-ripple="false"
          locale="ja-jp"
          :day-format="(timestamp) => new Date(timestamp.date).getDate()"
          :month-format="(timestamp) => (new Date(timestamp.date).getMonth() + 1) + ' /'"
          @change="getEvents"
          @mousedown:event="startDrag"
          @click:event="showEvent"
          @mousedown:time="startTime"
          @mousemove:time="mouseMove"
          @mouseup:time="endDrag"
          @mouseleave.native="cancelDrag"
        >
          <template #event="{ event, timed, eventSummary }">

// A pop-up will appear when you click on it.
////////////////////////////////////////////////////////////////////

            <v-menu
              v-model="selectedOpen"
              :close-on-content-click="false"
              :activator="selectedElement"
              offset-x
            >
              <v-card
                color="grey lighten-2"
                min-width="350px"
                flat
              >
                <v-toolbar>
                  <v-btn icon>
                    <v-icon>mdi-pencil</v-icon>
                  </v-btn>
                  <v-toolbar-title v-html="selectedEvent.name" />
                  <v-spacer />

                    <v-menu offset-y>
                      <template #activator="{ on, attrs }">
                        <v-btn
                          icon
                          v-bind="attrs"
                          v-on="on"
                        >
                          <v-icon
                            :color="selectedEvent.color"
                          >
                            mdi-brightness-1
                          </v-icon>
                        </v-btn>
                      </template>
                      <v-list>
                        <v-list-item
                          v-for="(color, index) in colors"
                          :key="index"
                        >
                          <v-icon
                            :color="color"
                            @click="changeColor(color)"
                          >
                            mdi-brightness-1
                          </v-icon>
                        </v-list-item>
                      </v-list>
                    </v-menu>

////////////////////////////////////////////////////////////////////////////////////

                  <v-btn icon>
                    <v-icon>mdi-dots-vertical</v-icon>
                  </v-btn>
                </v-toolbar>
                <v-card-text>

                </v-card-text>
                <v-card-actions>
                  <v-btn
                    text
                    color="secondary"
                    @click="selectedOpen = false"
                  >
                    Cancel
                  </v-btn>
                </v-card-actions>
              </v-card>
            </v-menu>

          </template>
        </v-calendar>
      </v-sheet>
    </v-col>
  </v-row>
</template>

What I've tried.

・I thought it was caused by the v-slot:activator, so I checked it out. As a result, I found out that on has a function to display a popup, but I couldn't find the relevance of this.

Body:
In the default configuration of Vuetify, the popup display was controlled by v-model, but I was able to solve this problem by binding with :value.

 <!-- Show popup when clicked -->
            <v-menu
             "selectedOpen"
              :value="selectedOpen"
              :close-on-content-click="false"
              :activator="selectedElement"
              offset-x
            >


问:
How to generate hd wallet keys & addresses given seed phrase with cosmos sdk?
I am trying to generate hd wallet private keys , public keys and addresess using cosmos sdk. Below is the equivalent implementation in python which generates the keys , address as expected but when trying to generated in golang using cosmos sdk it won't generate same keys. Any inputs for equivalent golang version of the python implementation is much appreciated. Thank you.

Python

```<code>seed = Mnemonic.to_seed("blast about old claw current first paste risk involve victory edit current", passphrase="")
print("Seed: ", seed.hex())
purpose = 44
coinType = 118
account = 0
change = 0

hdwallet = HDWallet()
hdwallet.from_seed(seed=seed.hex())

for addressIndex in range(1):
    hdwallet.clean_derivation()
    hdwallet.from_index(purpose, hardened=True)
    hdwallet.from_index(coinType, hardened=True)
    hdwallet.from_index(account, hardened=True)
    hdwallet.from_index(change)
    hdwallet.from_index(addressIndex, hardened=True)

    print("---")
    print("Derivation Path: ", hdwallet.path())
    print("Private Key: ", hdwallet.private_key())
    print("Public Key: ", hdwallet.public_key())

    readdr_bytes = b"\x04" + bytearray.fromhex(hdwallet.public_key())
    readdr_bytes5 = bech32.convertbits(readdr_bytes, 8, 5)
    wallet_addr = bech32.bech32_encode("atom", readdr_bytes5)
    print("Wallet Address: ", wallet_addr)
</code>```

OUTPUT

Derivation Path:  m/44'/118'/0'/0/0'
Private Key:  69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a
Public Key:  03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8
Wallet Address:  atom1qspau72rtj7g57v7lsjvmnna8vvqlvq56hcejj0m34sau0eph8mvr7qgl9avu

GoLang ( Gernerating differnt keys )

```<code>import (
    "github.com/tendermint/tendermint/crypto/secp256k1"
    "github.com/cosmos/cosmos-sdk/crypto/hd"
    "github.com/cosmos/go-bip39"
    "github.com/decred/dcrd/bech32"
 )

path := hd.BIP44Params{
    Purpose:      44,
    CoinType:     118,
    Account:      0,
    Change:       false,
    AddressIndex: 0,
}

seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current","")

master, ch := hd.ComputeMastersFromSeed(seed)
priv, err := hd.DerivePrivateKeyForPath(master, ch, path.String())
if err != nil {
    log.Fatal(err)
}
var privKey = secp256k1.GenPrivKeySecp256k1(priv)
pubKey := privKey.PubKey()
fmt.Println(hex.EncodeToString(pubKey.Bytes()))

decodeString, _ := hex.DecodeString(fmt.Sprintf("04%x", pubKey.Bytes()))

// Convert test data to base32:
conv, err := bech32.ConvertBits(decodeString, 8, 5, true)
if err != nil {
    fmt.Println("Error:", err)
}
encoded, err := bech32.Encode("atom", conv)
if err != nil {
    fmt.Println("Error:", err)
}

// Show the encoded data.
fmt.Println("Atom address:", encoded)
</code>```

OUTPUT

Derivation Path:  m/44'/1022'/0'/0/0'
Private Key:  84925813eac8c1dc39f170e93b3bebe0bf961ac9c46507e858ce178a1a715c26
Public Key:  0204a0bad86cafed2daf1b4080a3e908afcf524e2a9c24e20817920c478d537cc1
Wallet Address:  atom1qsp3yaurlt463pl6pekgae4yudlcwk2dhxt93cxz5d5ymw3j8xmngaqef5j7p

答:
The results of both codes differ because of two issues:

In the Go Code, the private key is derived incorrectly:

In the Python code, the path m/44'/118'/0'/0/0' is used, as the output of hdwallet.path() shows. In the Go code, in contrast, the path m/44'/118'/0'/0/0 is used, as shown by the output of path.String().

To use the path of the Python code in the Go code, the path can be e.g. specified directly. For this the line:

priv, err := hd.DerivePrivateKeyForPath(master, ch, path.String())
```
<p>has to be replaced by:</p>
<pre class="lang-golang prettyprint-override"><code>priv, err := hd.DerivePrivateKeyForPath(master, ch, "m/44'/118'/0'/0/0'")
</code>```

and the path variable can be removed.

With this change, the Go code provides the same private key as the Python code.

In the Go Code, the private key is imported incorrectly. Therefore, the public key is determined wrongly. To fix this, the line:

var privKey = secp256k1.GenPrivKeySecp256k1(priv)
```
<p>must be replaced by:</p>
<pre class="lang-golang prettyprint-override"><code>var privKey = secp256k1.PrivKey(priv)
</code>```

With this change, the Go code gives the same public key as the Python code.

The rest of the Go code is functionally equivalent to the Python code, so the Go code produces the same address as the Python code.

The complete Go code is:

package main

import (
    "encoding/hex"
    "fmt"
    "log"

    "github.com/cosmos/cosmos-sdk/crypto/hd"
    "github.com/cosmos/go-bip39"
    "github.com/decred/dcrd/bech32"
    "github.com/tendermint/tendermint/crypto/secp256k1"
)

func main() {

    seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
    fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed:  dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd

    master, ch := hd.ComputeMastersFromSeed(seed)
    path := "m/44'/118'/0'/0/0'"
    priv, err := hd.DerivePrivateKeyForPath(master, ch, path)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Derivation Path: ", path)                 // Derivation Path:  m/44'/118'/0'/0/0'
    fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key:  69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a

    var privKey = secp256k1.PrivKey(priv)
    pubKey := privKey.PubKey()
    fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key:  03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8

    decodeString, err := hex.DecodeString(fmt.Sprintf("04%x", pubKey.Bytes()))
    if err != nil {
        log.Fatal(err)
    }

    // Convert test data to base32:
    conv, err := bech32.ConvertBits(decodeString, 8, 5, true)
    if err != nil {
        fmt.Println("Error:", err)
    }
    encoded, err := bech32.Encode("atom", conv)
    if err != nil {
        fmt.Println("Error:", err)
    }

    // Show the encoded data.
    fmt.Println("Wallet Address:", encoded) // Wallet Address: atom1qspau72rtj7g57v7lsjvmnna8vvqlvq56hcejj0m34sau0eph8mvr7qgl9avu
}
```

Body:
I am trying to generate hd wallet private keys , public keys and addresess using cosmos sdk. Below is the equivalent implementation in python which generates the keys , address as expected but when trying to generated in golang using cosmos sdk it won't generate same keys. Any inputs for equivalent golang version of the python implementation is much appreciated. Thank you.

Python

seed = Mnemonic.to_seed("blast about old claw current first paste risk involve victory edit current", passphrase="")
print("Seed: ", seed.hex())
purpose = 44
coinType = 118
account = 0
change = 0

hdwallet = HDWallet()
hdwallet.from_seed(seed=seed.hex())

for addressIndex in range(1):
    hdwallet.clean_derivation()
    hdwallet.from_index(purpose, hardened=True)
    hdwallet.from_index(coinType, hardened=True)
    hdwallet.from_index(account, hardened=True)
    hdwallet.from_index(change)
    hdwallet.from_index(addressIndex, hardened=True)

    print("---")
    print("Derivation Path: ", hdwallet.path())
    print("Private Key: ", hdwallet.private_key())
    print("Public Key: ", hdwallet.public_key())

    readdr_bytes = b"\x04" + bytearray.fromhex(hdwallet.public_key())
    readdr_bytes5 = bech32.convertbits(readdr_bytes, 8, 5)
    wallet_addr = bech32.bech32_encode("atom", readdr_bytes5)
    print("Wallet Address: ", wallet_addr)

OUTPUT

Derivation Path:  m/44'/118'/0'/0/0'
Private Key:  69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a
Public Key:  03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8
Wallet Address:  atom1qspau72rtj7g57v7lsjvmnna8vvqlvq56hcejj0m34sau0eph8mvr7qgl9avu

GoLang ( Gernerating differnt keys )

import (
    "github.com/tendermint/tendermint/crypto/secp256k1"
    "github.com/cosmos/cosmos-sdk/crypto/hd"
    "github.com/cosmos/go-bip39"
    "github.com/decred/dcrd/bech32"
 )

path := hd.BIP44Params{
    Purpose:      44,
    CoinType:     118,
    Account:      0,
    Change:       false,
    AddressIndex: 0,
}

seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current","")

master, ch := hd.ComputeMastersFromSeed(seed)
priv, err := hd.DerivePrivateKeyForPath(master, ch, path.String())
if err != nil {
    log.Fatal(err)
}
var privKey = secp256k1.GenPrivKeySecp256k1(priv)
pubKey := privKey.PubKey()
fmt.Println(hex.EncodeToString(pubKey.Bytes()))

decodeString, _ := hex.DecodeString(fmt.Sprintf("04%x", pubKey.Bytes()))

// Convert test data to base32:
conv, err := bech32.ConvertBits(decodeString, 8, 5, true)
if err != nil {
    fmt.Println("Error:", err)
}
encoded, err := bech32.Encode("atom", conv)
if err != nil {
    fmt.Println("Error:", err)
}

// Show the encoded data.
fmt.Println("Atom address:", encoded)

OUTPUT

Derivation Path:  m/44'/1022'/0'/0/0'
Private Key:  84925813eac8c1dc39f170e93b3bebe0bf961ac9c46507e858ce178a1a715c26
Public Key:  0204a0bad86cafed2daf1b4080a3e908afcf524e2a9c24e20817920c478d537cc1
Wallet Address:  atom1qsp3yaurlt463pl6pekgae4yudlcwk2dhxt93cxz5d5ymw3j8xmngaqef5j7p

Body:
The results of both codes differ because of two issues:

In the Go Code, the private key is derived incorrectly:

In the Python code, the path m/44'/118'/0'/0/0' is used, as the output of hdwallet.path() shows. In the Go code, in contrast, the path m/44'/118'/0'/0/0 is used, as shown by the output of path.String().

To use the path of the Python code in the Go code, the path can be e.g. specified directly. For this the line:

priv, err := hd.DerivePrivateKeyForPath(master, ch, path.String())

has to be replaced by:

priv, err := hd.DerivePrivateKeyForPath(master, ch, "m/44'/118'/0'/0/0'")

and the path variable can be removed.

With this change, the Go code provides the same private key as the Python code.

In the Go Code, the private key is imported incorrectly. Therefore, the public key is determined wrongly. To fix this, the line:

var privKey = secp256k1.GenPrivKeySecp256k1(priv)

must be replaced by:

var privKey = secp256k1.PrivKey(priv)

With this change, the Go code gives the same public key as the Python code.

The rest of the Go code is functionally equivalent to the Python code, so the Go code produces the same address as the Python code.

The complete Go code is:

package main

import (
    "encoding/hex"
    "fmt"
    "log"

    "github.com/cosmos/cosmos-sdk/crypto/hd"
    "github.com/cosmos/go-bip39"
    "github.com/decred/dcrd/bech32"
    "github.com/tendermint/tendermint/crypto/secp256k1"
)

func main() {

    seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
    fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed:  dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd

    master, ch := hd.ComputeMastersFromSeed(seed)
    path := "m/44'/118'/0'/0/0'"
    priv, err := hd.DerivePrivateKeyForPath(master, ch, path)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Derivation Path: ", path)                 // Derivation Path:  m/44'/118'/0'/0/0'
    fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key:  69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a

    var privKey = secp256k1.PrivKey(priv)
    pubKey := privKey.PubKey()
    fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key:  03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8

    decodeString, err := hex.DecodeString(fmt.Sprintf("04%x", pubKey.Bytes()))
    if err != nil {
        log.Fatal(err)
    }

    // Convert test data to base32:
    conv, err := bech32.ConvertBits(decodeString, 8, 5, true)
    if err != nil {
        fmt.Println("Error:", err)
    }
    encoded, err := bech32.Encode("atom", conv)
    if err != nil {
        fmt.Println("Error:", err)
    }

    // Show the encoded data.
    fmt.Println("Wallet Address:", encoded) // Wallet Address: atom1qspau72rtj7g57v7lsjvmnna8vvqlvq56hcejj0m34sau0eph8mvr7qgl9avu
}


问:
Ruby Gem Ultraviolet, Rails, Leopard
I cannot get this crazy dependency to work and please don't tell me to go to Snow Leopard because I have a PPC.

I have oniguruma, textpow, ultraviolet all installed. I'm using rvm which is probably the problem. Not that rvm is bad it's just that I don't know how to get the paths correct.

When I startup a rails app the error I'm getting states that I'm missing the ultraviolet gem which is not really the case because it's listed under gem list with other gems which are working correctly.

Let me know if you need more information and what kinda specific info:

Here is my error log:

Macintosh:sam samgilman$ script/server
  => Booting WEBrick
  => Rails 2.3.5 application starting on http://0.0.0.0:3000
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/rails/gem_dependency.rb:119:Warning: Gem::Dependency#version_requirements is deprecated and will be removed on or after August 2010.  Use #requirement
  no such file to load -- ultraviolet
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require'
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in require'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:innew_constants_in'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in require'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/rails/gem_dependency.rb:208:inload'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:307:in load_gems'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:307:ineach'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:307:in load_gems'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:164:inprocess'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:113:in send'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:113:inrun'
  /Users/samgilman/Sites/sam/config/environment.rb:9
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require'
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in require'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:innew_constants_in'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in require'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/commands/server.rb:84
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:ingem_original_require'
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in require'
  script/server:3
  no such file to load -- ultraviolet
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:ingem_original_require'
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in require'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:inrequire'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in new_constants_in'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:inrequire'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/rails/gem_dependency.rb:208:in load'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:307:inload_gems'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:307:in each'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:307:inload_gems'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:169:in process'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:113:insend'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/initializer.rb:113:in run'
  /Users/samgilman/Sites/sam/config/environment.rb:9
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:ingem_original_require'
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in require'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:inrequire'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in new_constants_in'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:inrequire'
  /Users/samgilman/.rvm/gems/ruby-1.8.7-p302/gems/rails-2.3.5/lib/commands/server.rb:84
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require'
  /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
  script/server:3
  Missing these required gems:
    ultraviolet

  You're running:
    ruby 1.8.7.302 at /Users/samgilman/.rvm/rubies/ruby-1.8.7-p302/bin/ruby
    rubygems 1.3.7 at /Users/samgilman/.rvm/gems/ruby-1.8.7-p302, /Users/samgilman/.rvm/gems/ruby-1.8.7-p302@global
  Run rake gems:install to install the missing gems.
  Macintosh:sam samgilman$

答:
For Rails 3, Rails 4 and Rails 5, you should have Gemfile,

```<code>gem "ultraviolet", :require => "uv"
</code>```

ContentLicense: CC BY-SA 2.5

Title: Ruby Gem Ultraviolet, Rails, Leopard

Body:
For Rails 3, Rails 4 and Rails 5, you should have Gemfile,

gem "ultraviolet", :require => "uv"

ContentLicense: CC BY-SA 3.0


问:
Seems git turned a folder into a text file
I have code in a repo that I've been happily pushing up for many a month.
Today I checked and there is a local folder named 'pages' in my working dir, but in the origin, it is only a text file.

```<code>PS W:\dev> git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
</code>```

Looking at the local files

```<code>PS W:\dev> ls .\pages\

    Directory: W:\dev\pages

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        29/01/2022   7:09 pm                charts
d-----        21/12/2020   1:56 pm                tables
d-----        30/12/2020   3:58 pm                transactions
</code>```

This is what the pages files looks like in the repo, just a string

I don't have anything in my gitignore file.

Could someone let me know how I can add the 'pages' directory?
Bonus points if someone can tell me what I did wrong to accomplish this weirdness.

As suggested, I checked if it was a sub-repo, but does not seem to be the case:

答:
I worked around the problem in the end by deleting the pages directory in origin.

Then, denied the unlink on pull:

```<code>> git pull
Unlink of file 'pages' failed. Should I try again? (y/n) n
Removing pages
Merge made by the 'recursive' strategy.
pages | 1 -
1 file changed, 1 deletion(-)
delete mode 160000 pages
</code>```

Add them again:  git add .\pages\

Now they appear again and seem to track fine.

Body:
I have code in a repo that I've been happily pushing up for many a month.
Today I checked and there is a local folder named 'pages' in my working dir, but in the origin, it is only a text file.

PS W:\dev> git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

Looking at the local files

PS W:\dev> ls .\pages\

    Directory: W:\dev\pages

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        29/01/2022   7:09 pm                charts
d-----        21/12/2020   1:56 pm                tables
d-----        30/12/2020   3:58 pm                transactions

This is what the pages files looks like in the repo, just a string

I don't have anything in my gitignore file.

Could someone let me know how I can add the 'pages' directory?
Bonus points if someone can tell me what I did wrong to accomplish this weirdness.

As suggested, I checked if it was a sub-repo, but does not seem to be the case:

Body:
I worked around the problem in the end by deleting the pages directory in origin.

Then, denied the unlink on pull:

> git pull
Unlink of file 'pages' failed. Should I try again? (y/n) n
Removing pages
Merge made by the 'recursive' strategy.
pages | 1 -
1 file changed, 1 deletion(-)
delete mode 160000 pages

Add them again:  git add .\pages\

Now they appear again and seem to track fine.


问:
Error using text2image Font Exocet Light failed with 223518 hits = 99.94% when trying to build image file using Diablo 2 font
I am running tesseract on windows 11 using the command prompt.

The text file is my training data. Words that I want to turn into images.
The output is the next step in the Tesseract process for training my font.
I am saying find fonts but I only have one font in the folder.

text2image --text="C:\PythonProjects\DiabloTesseractTrainFont\text.txt" --outputbase="C:\PythonProjects\DiabloTesseractTrainFont\Output\Dia.font.exp0" --fontconfig_tmpdir="C:\PythonProjects\DiabloTesseractTrainFont" --find_fonts --fonts_dir="C:\PythonProjects\DiabloTesseractTrainFont\Diablo Fonts"

The result:
Total chars = 223645
Font Exocet Light failed with 223518 hits = 99.94%

Not sure why it fails. I have built something similar to this before. I have tried with a font file that I know has worked and it does the exact same thing.

Any help would be appreciated.

答: I solved it. In the text file, there were some characters that had been changed when I read them into python. I believe they used to be bullet points but when I read the file I had implemented in python ASCII encoding and ignore errors. I figured that those characters would be removed. I was wrong. Those bullet points were replaced with text that said PAD. I found it in notepad++ and highlighted one of them and then replaced them with a space. Note in Notepad++ when I did the replace it did not have anything in the find field but it still replaced all of them. Now it compiles just fine. I was stuck for many hours I hope this helps someone.</p>


问:
Smart XLS examples?
I want to use the Smart XLS library for dealing with excel files in C# (particularly because it can generate charts, and it's price is significantly lower than Aspose Cells), but I can't find any good examples for it.  I just want to know how to create and modify charts, any guidance?</p>

答:
Maybe you could be interested in EPPlus:

Open Source.

Charting capabilities.

Very good reputation.

Active maintenance, last release is just 3 months old.

It only work with xlsx files so if if you need to work with xls, its not an option.

Title: Smart XLS examples?


问:
Cannot read second page scanned via ADF
I have a Brother mutlifunction networked printer/scanner/fax (model MFC-9140CDN). I am trying to use the following code with WIA, to retrieve items scanned in with the document feeder:

```<code>const int FEEDER = 1;

var manager=new DeviceManager();
var deviceInfo=manager.DeviceInfos.Cast<DeviceInfo>().First();
var device=deviceInfo.Connect();
device.Properties["Pages"].set_Value(1);
device.Properties["Document Handling Select"].set_Value(1);

var morePages=true;
var counter=0;
while (morePages) {
    counter++;
    var item=device.Items[1];
    item.Properties["Bits Per Pixel"].set_Value(1);
    item.Properties["Horizontal Resolution"].set_Value(300);
    item.Properties["Vertical Resolution"].set_Value(300);

    var img=(WIA.ImageFile)item.Transfer();
    var path=String.Format(@"C:\Users\user1\Documents\test_{0}.tiff",counter);
    img.SaveFile(path);

    var status=(int)device.Properties["Document Handling Status"].get_Value();
    morePages = (status & FEEDER) > 0;
}
</code>```

When the Transfer method is reached for the first time, all the pages go through the document feeder. The first page gets saved with img.SaveFile to the passed-in path, but all the subsequent pages are not available - device.Items.Count is 1, and trying device.Items[2] raises an exception.

In the next iteration, calling Transfer raises an exception -- understandably, because there are now no pages in the feeder.

How can I get the subsequent images that have been scanned into the feeder?

(N.B. Iterating through all the device properties, there is an additional unnamed property with the id of 38922. I haven't been able to find any reference to this property.)

Update

I couldn't find a property on the device corresponding to WIA_IPS_SCAN_AHEAD or WIA_DPS_SCAN_AHEAD_PAGES, but that makes sense because this property is optional according to the documentation.

I tried using TWAIN (via the NTwain library, which I highly recommend) with the same problem.

答:
This bug did cost me hours...
So thanks a lot Zev.

I also had two scanners shown in the dialog for physically one machine. One driver scans only the first page and then empties the feeder without any chance to intercept. The other one works as expected.

BTW: It is not needed to initialize the scanner for each page. I call my routines for initialization prior to the Transfer() loop. Works just fine.

Another hickup I ran into was to first initialize page sizes, then the feeder. So if you do not get it to work, try switching the sequence how you change the properties for your WIA driver. As mentioned in the MSDN, some properties also influence others, potentially resetting your changes.

So praise to ZEV SPITZ for the answer on Aug. 09, 2015.

Title: Cannot read second page scanned via ADF

Body:
I have a Brother mutlifunction networked printer/scanner/fax (model MFC-9140CDN). I am trying to use the following code with WIA, to retrieve items scanned in with the document feeder:

const int FEEDER = 1;

var manager=new DeviceManager();
var deviceInfo=manager.DeviceInfos.Cast<DeviceInfo>().First();
var device=deviceInfo.Connect();
device.Properties["Pages"].set_Value(1);
device.Properties["Document Handling Select"].set_Value(1);

var morePages=true;
var counter=0;
while (morePages) {
    counter++;
    var item=device.Items[1];
    item.Properties["Bits Per Pixel"].set_Value(1);
    item.Properties["Horizontal Resolution"].set_Value(300);
    item.Properties["Vertical Resolution"].set_Value(300);

    var img=(WIA.ImageFile)item.Transfer();
    var path=String.Format(@"C:\Users\user1\Documents\test_{0}.tiff",counter);
    img.SaveFile(path);

    var status=(int)device.Properties["Document Handling Status"].get_Value();
    morePages = (status & FEEDER) > 0;
}

When the Transfer method is reached for the first time, all the pages go through the document feeder. The first page gets saved with img.SaveFile to the passed-in path, but all the subsequent pages are not available - device.Items.Count is 1, and trying device.Items[2] raises an exception.

In the next iteration, calling Transfer raises an exception -- understandably, because there are now no pages in the feeder.

How can I get the subsequent images that have been scanned into the feeder?

(N.B. Iterating through all the device properties, there is an additional unnamed property with the id of 38922. I haven't been able to find any reference to this property.)

Update

I couldn't find a property on the device corresponding to WIA_IPS_SCAN_AHEAD or WIA_DPS_SCAN_AHEAD_PAGES, but that makes sense because this property is optional according to the documentation.

I tried using TWAIN (via the NTwain library, which I highly recommend) with the same problem.


问:
Is it Possible to Connect to NordVPN Via Puppeteer on a Windows Server?
I have a Puppeteer app running on a Windows Server. That server's IP address is blocked by some of the sites it has been crawling, so it needs a new one. I have a NordVPN account but have been informed via Server Fault that if I were to run the NordVPN app that I would lose remote desktop access at its static IP (https://serverfault.com/questions/1060082/would-adding-nordvpn-to-a-windows-server-block-remote-access-at-its-ip/1060085) and I believe that websites whose DNS is pointing at that IP would not be accessible either, so I need a different solution.

I have found a few examples of using Puppeteer to connect to a VPN, but those solution appear to use or Linux servers (How to connect VPN using nodejs in ubuntu).

答:
Try this... it does not rely on any other modules... Change the user/pass to you service ones in your account and change the vpnServer to whatever one you want to use.

```<code>#!/usr/bin/env node

// Screengrab generator
// outputs a JSON object with a base64 encoded image of the screengrab
// eg;

const puppeteer = require('puppeteer');

let conf = new Object();

conf.url = "https://www.telegraph.co.uk";

// VPN
conf.vpnUser   = conf.vpnUSer   || 'USERNAME';
conf.vpnPass   = conf.vpnPass   || 'PASSWORD';
conf.vpnServer = conf.vpnServer || "https://uk1785.nordvpn.com:89";

(async() => {
    const browser = await puppeteer.launch({
        headless: true,
        args: [
            '--disable-dev-shm-usage',
            '--proxy-server='+conf.vpnServer
        ]
    });

    try {
        const page = await browser.newPage();

        await page.authenticate({
            username: conf.vpnUser,
            password: conf.vpnPass,
        });

        await page.goto(conf.url, { waitUntil: 'networkidle2' });
    } catch (error) {
        console.error(error);
    } finally {
        await browser.close();
    }
})();
</code>```

Body:
Try this... it does not rely on any other modules... Change the user/pass to you service ones in your account and change the vpnServer to whatever one you want to use.

#!/usr/bin/env node

// Screengrab generator
// outputs a JSON object with a base64 encoded image of the screengrab
// eg;

const puppeteer = require('puppeteer');

let conf = new Object();

conf.url = "https://www.telegraph.co.uk";

// VPN
conf.vpnUser   = conf.vpnUSer   || 'USERNAME';
conf.vpnPass   = conf.vpnPass   || 'PASSWORD';
conf.vpnServer = conf.vpnServer || "https://uk1785.nordvpn.com:89";

(async() => {
    const browser = await puppeteer.launch({
        headless: true,
        args: [
            '--disable-dev-shm-usage',
            '--proxy-server='+conf.vpnServer
        ]
    });

    try {
        const page = await browser.newPage();

        await page.authenticate({
            username: conf.vpnUser,
            password: conf.vpnPass,
        });

        await page.goto(conf.url, { waitUntil: 'networkidle2' });
    } catch (error) {
        console.error(error);
    } finally {
        await browser.close();
    }
})();


问:
How to solve my error in this shell script
I have been trying to run the following command but it gives me the following error but when I type command in terminal it runs, how to fix this

Command:

```<code>host=''
user=''
pass=''
path='path'
srcfile='file.txt'
lftp -u $user,$pass $host   << --EOF--
set ssl:verify-certificate no
put $srcfile
quit

</code>```

Error:

答:
If you told shell that you're using here document you have to tell it
where it ends:</p>
```<code>lftp -u $user,$pass $host   << --EOF--
set ssl:verify-certificate no
put $srcfile
quit
--EOF--
</code>```

Body:
I have been trying to run the following command but it gives me the following error but when I type command in terminal it runs, how to fix this

Command:

host=''
user=''
pass=''
path='path'
srcfile='file.txt'
lftp -u $user,$pass $host   << --EOF--
set ssl:verify-certificate no
put $srcfile
quit

Error:

Body:
If you told shell that you're using here document you have to tell it
where it ends:

lftp -u $user,$pass $host   << --EOF--
set ssl:verify-certificate no
put $srcfile
quit
--EOF--


问:
Twitter API and Retweets
I'm using the Twitter API method 'getRetweets' to pull retweets of a specific status ID.
The problem I have is that the API only pulls back the new style 'automatic' RTs made using the specific RT button. I need to also pull back old style 'manual' retweets made by placeing the letters 'RT' in front of a tweet.

Anyone have any idea how I can achieve this? At present the only thing I can think of is to use the search method, but that seems like overkill somehow.

答:
Retweets are always mentions. You could GET statuses/mentions of an authenticated user or just plain old GET search for '@his_username'
In both cases you must manually map originals with the retweeted ones.

Title: Twitter API and Retweets


问:
How to find the average total per order in R
I'm trying to find the average total of an order across the entire data set. Here is what a little bit of the data set looks like:

order_id
qty
price
discount

20752
1
58
5

20753
1
34
0

20753
1
64
0

20753
1
78
0

20754
2
34
0

20755
1
62
0

What I'm looking to do is find the average total of each order.

I'm able to find the average of each order by using this code but I'm not sure how to find the average of each order across the entire data set.

```<code>'''
project %>%

    group_by(order_id) %>%

    summarise(Avg_total = mean(price, na.rm=TRUE))
'''
</code>```

This gives me the following table:

order_id
Avg_total

20752
58

20753
58.7

20754
34

20755
62

However, what I want is this:

Avg_total

89.75

Here is how I calculated that number -

order 20752 has a total of 53

order 20753 has a total of 176

order 20754 has a total of 68

order 20755 has a total of 62

53 + 176 + 68 + 62 = 359 / 4 (# of orders) = 89.75 average total per order across the whole set.

If possible, I would also like to filter out any order totals above 500 to remove any outliers.

答:
So, you have the following code:

```<code>Book1 %>%
+ group_by(Book1$order_id)%>%
+ summarise(Avg_total=mean(price, na.rm=TRUE))
</code>```

which gives you the grouping summarizing it by average of price for each order_id (e.g. 20752 -> 58/1 = 58, 20753 -> (34+64+78)/3 = 58.66666 = 58.7)

For your case I would first create a new column with the values price-discount as follows:

```<code>Book1$final_price = Book1$price-Book1$discount
</code>```

The code simply subtracts the discount from price and adds it to a new column called final_price. R handles the operation row by row.

Which gives the following result:

This, by following the code that you shared gives a different table (meaning that the discount is removed from the price):

```<code>    Book1 %>%
+ group_by(Book1$order_id)%>%
+ summarise(Avg_total=mean(final_price, na.rm=TRUE))
</code>```

What you are having though is 58 + (34 + 64 + 78) + 34 + 62 = 330 (for not removing discount) or 53 + (34 + 64 + 78) + 34 + 62 = 325 (by removing discount).

Therefore you mean would be (53 + 176 + 34 + 62)/4 = 81.25

You could find the desired output:

```<code>        Book1%>%
+ group_by(Book1$order_id)%>%
+ summarise(Sum_total=sum(final_price, na.rm=TRUE))%>%
+ summarise(Avg = mean(Sum_total, na.rm=TRUE))
</code>```

What happens here is that we are first grouping by the order_id, then creating the sum (and not mean) for every order_id and then doing the mean.

Please be careful, this finds the mean of totals for order_ids and not the mean of totals for every order, which should be the following:

```<code>    Book1%>%
+ summarise(Avg = mean(price, na.rm=TRUE))
</code>```

In order to remove rows you could run the following before any arithmetic operations:

```<code>x <-subset(Book1, price<=500)
</code>```

Body:
I'm trying to find the average total of an order across the entire data set. Here is what a little bit of the data set looks like:

order_id
qty
price
discount

20752
1
58
5

20753
1
34
0

20753
1
64
0

20753
1
78
0

20754
2
34
0

20755
1
62
0

What I'm looking to do is find the average total of each order.

I'm able to find the average of each order by using this code but I'm not sure how to find the average of each order across the entire data set.

'''
project %>%

    group_by(order_id) %>%

    summarise(Avg_total = mean(price, na.rm=TRUE))
'''

This gives me the following table:

order_id
Avg_total

20752
58

20753
58.7

20754
34

20755
62

However, what I want is this:

Avg_total

89.75

Here is how I calculated that number -

order 20752 has a total of 53

order 20753 has a total of 176

order 20754 has a total of 68

order 20755 has a total of 62

53 + 176 + 68 + 62 = 359 / 4 (# of orders) = 89.75 average total per order across the whole set.

If possible, I would also like to filter out any order totals above 500 to remove any outliers.

Body:
So, you have the following code:

Book1 %>%
+ group_by(Book1$order_id)%>%
+ summarise(Avg_total=mean(price, na.rm=TRUE))

which gives you the grouping summarizing it by average of price for each order_id (e.g. 20752 -> 58/1 = 58, 20753 -> (34+64+78)/3 = 58.66666 = 58.7)

For your case I would first create a new column with the values price-discount as follows:

Book1$final_price = Book1$price-Book1$discount

The code simply subtracts the discount from price and adds it to a new column called final_price. R handles the operation row by row.

Which gives the following result:

This, by following the code that you shared gives a different table (meaning that the discount is removed from the price):

    Book1 %>%
+ group_by(Book1$order_id)%>%
+ summarise(Avg_total=mean(final_price, na.rm=TRUE))

What you are having though is 58 + (34 + 64 + 78) + 34 + 62 = 330 (for not removing discount) or 53 + (34 + 64 + 78) + 34 + 62 = 325 (by removing discount).

Therefore you mean would be (53 + 176 + 34 + 62)/4 = 81.25

You could find the desired output:

        Book1%>%
+ group_by(Book1$order_id)%>%
+ summarise(Sum_total=sum(final_price, na.rm=TRUE))%>%
+ summarise(Avg = mean(Sum_total, na.rm=TRUE))

What happens here is that we are first grouping by the order_id, then creating the sum (and not mean) for every order_id and then doing the mean.

Please be careful, this finds the mean of totals for order_ids and not the mean of totals for every order, which should be the following:

    Book1%>%
+ summarise(Avg = mean(price, na.rm=TRUE))

In order to remove rows you could run the following before any arithmetic operations:

x <-subset(Book1, price<=500)


问:
Logo not showing on Google Search results
I recently made a website using HTML/CSS/and JS. I have deployed it and given it a domain name and everything works fine. However, the logo image of my website isn't showing up in google search results. I've added the favicon link, and the logo does show when I hover over a tab. It's just not showing in google search results. Any way I can fix this? Thanks in advance.

Here is the favicon link I put in my header:

```<code><link rel="shortcut icon" type="image/x-icon" href="images/website.png" />
</code>```

答: Google needs time to read the information and update it in the search, now try to properly make sitemap.xml to facilitate the reading of information for search engines, as well as add the site in google search results through the Google Search Console</p>

Body:
I recently made a website using HTML/CSS/and JS. I have deployed it and given it a domain name and everything works fine. However, the logo image of my website isn't showing up in google search results. I've added the favicon link, and the logo does show when I hover over a tab. It's just not showing in google search results. Any way I can fix this? Thanks in advance.

Here is the favicon link I put in my header:

<link rel="shortcut icon" type="image/x-icon" href="images/website.png" />


问:
Conan with cmake-conan missing conanbuild.conf
I am want to package a CMake project with conan.
For that I use the following conanfile.py:

import os
from conans import ConanFile, tools
from conan.tools.cmake import CMake, CMakeToolchain
from conans.tools import Version

class BaseLibrary(ConanFile):
    name = "base-library"
    version = "1.0.0"
    description = """This is a test project with a library base::io
    and base::math and an executable cli."""
    license = "MIT"
    generators = "cmake_find_package_multi", "cmake_find_package",
    default_options = {"fmt:shared": True}
    build_policy = "missing"  # if this package is build by default if missing.
    settings = "os", "compiler", "build_type", "arch"
    exports_sources = "*"

    _cmake = None

    def requirements(self):
        if Version(self.version) >= "1.0.0":
            self.requires("fmt/8.0.1")

    def _configure_cmake(self):
        if self._cmake:
            return self._cmake
        self._cmake = CMake(self)
        self._cmake.configure(source_folder=".")
        return self._cmake

    def build(self):
        cmake = self._configure_cmake()
        cmake.build()
        cmake.install()

    def package(self):
        cmake = self._configure_cmake()
        cmake.install()
        tools.rmdir(os.path.join(self.package_folder, "lib", "cmake"))
        tools.rmdir(os.path.join(self.package_folder, "lib", "pkgconfig"))
        tools.rmdir(os.path.join(self.package_folder, "share"))

    def package_info(self):
        self.cpp_info.names["cmake_find_package"] = "base"
        self.cpp_info.names["cmake_find_package_multi"] = "base"
        self.cpp_info.names["pkg_config"] = "base"
```
<p>which is next to my main <code>CMakeLists.txt</code> file. The CMake project builds without problems and also has a proper <code>install</code> target which installs everything properly: <code>bin,lib,include,share</code>. In CMake I use the conan-cmake module with basically something like this.</p>
<p>When I run</p>
<pre class="lang-sh prettyprint-override"><code>conan create -s build_type=Release . demo/testing
</code>```

I get the following weird error:

...
Requirements
    base-library/1.0.0@demo/testing from local cache - Cache
    fmt/8.0.1 from 'conancenter' - Cache
Packages
    base-library/1.0.0@demo/testing:4f2b14d304ab8e4391d162a6eb44110cc27a3faa - Build
    fmt/8.0.1:d4e9c4f02b4f03edf5a640dcd22779727d782e79 - Cache

Installing (downloading, building) binaries...
fmt/8.0.1: Already installed!
base-library/1.0.0@demo/testing: WARN: Build folder is dirty, removing it: /home/developer/.conan/data/base-library/1.0.0/demo/testing/build/4f2b14d304ab8e4391d162a6eb44110cc27a3faa
base-library/1.0.0@demo/testing: Configuring sources in /home/developer/.conan/data/base-library/1.0.0/demo/testing/source
base-library/1.0.0@demo/testing: Copying sources to build folder
base-library/1.0.0@demo/testing: Building your package in /home/developer/.conan/data/base-library/1.0.0/demo/testing/build/4f2b14d304ab8e4391d162a6eb44110cc27a3faa
base-library/1.0.0@demo/testing: Generator cmake_find_package created Findfmt.cmake
base-library/1.0.0@demo/testing: Generator cmake_find_package_multi created fmt-config-version.cmake
base-library/1.0.0@demo/testing: Generator cmake_find_package_multi created fmt-config.cmake
base-library/1.0.0@demo/testing: Generator cmake_find_package_multi created fmtTargets.cmake
base-library/1.0.0@demo/testing: Generator cmake_find_package_multi created fmtTarget-release.cmake
base-library/1.0.0@demo/testing: Aggregating env generators
base-library/1.0.0@demo/testing: Calling build()
base-library/1.0.0@demo/testing:
base-library/1.0.0@demo/testing: ERROR: Package '4f2b14d304ab8e4391d162a6eb44110cc27a3faa' build failed
base-library/1.0.0@demo/testing: WARN: Build folder /home/developer/.conan/data/base-library/1.0.0/demo/testing/build/4f2b14d304ab8e4391d162a6eb44110cc27a3faa
ERROR: base-library/1.0.0@demo/testing: Error in build() method, line 74
        cmake = self._configure_cmake()
while calling '_configure_cmake', line 65
        self._cmake = CMake(self)
        ConanException: The file /home/developer/.conan/data/base-library/1.0.0/demo/testing/build/4f2b14d304ab8e4391d162a6eb44110cc27a3faa/conanbuild.conf does not exist. Please, make sure that it was not generated in another folder.
```

What is the problem here and how can I resolve this? I could not find anything related to this?

答:
I had the same problem and finally found the issue:

The CMake you are importing is the one working with the CMakeToolchain which are both part of the conan.tools.cmake module.
The one that is described in the usage of cmake_find_package[ref] is the one in conans module

So replacing:

```<code>from conans import ConanFile, tools
from conan.tools.cmake import CMake, CMakeToolchain
</code>```

by

```<code>from conans import ConanFile, tools, CMake
from conan.tools.cmake import CMakeToolchain
</code>```

should fix your problem

Body:
I am want to package a CMake project with conan.
For that I use the following conanfile.py:

import os
from conans import ConanFile, tools
from conan.tools.cmake import CMake, CMakeToolchain
from conans.tools import Version

class BaseLibrary(ConanFile):
    name = "base-library"
    version = "1.0.0"
    description = """This is a test project with a library base::io
    and base::math and an executable cli."""
    license = "MIT"
    generators = "cmake_find_package_multi", "cmake_find_package",
    default_options = {"fmt:shared": True}
    build_policy = "missing"  # if this package is build by default if missing.
    settings = "os", "compiler", "build_type", "arch"
    exports_sources = "*"

    _cmake = None

    def requirements(self):
        if Version(self.version) >= "1.0.0":
            self.requires("fmt/8.0.1")

    def _configure_cmake(self):
        if self._cmake:
            return self._cmake
        self._cmake = CMake(self)
        self._cmake.configure(source_folder=".")
        return self._cmake

    def build(self):
        cmake = self._configure_cmake()
        cmake.build()
        cmake.install()

    def package(self):
        cmake = self._configure_cmake()
        cmake.install()
        tools.rmdir(os.path.join(self.package_folder, "lib", "cmake"))
        tools.rmdir(os.path.join(self.package_folder, "lib", "pkgconfig"))
        tools.rmdir(os.path.join(self.package_folder, "share"))

    def package_info(self):
        self.cpp_info.names["cmake_find_package"] = "base"
        self.cpp_info.names["cmake_find_package_multi"] = "base"
        self.cpp_info.names["pkg_config"] = "base"

which is next to my main CMakeLists.txt file. The CMake project builds without problems and also has a proper install target which installs everything properly: bin,lib,include,share. In CMake I use the conan-cmake module with basically something like this.

When I run

conan create -s build_type=Release . demo/testing

I get the following weird error:

...
Requirements
    base-library/1.0.0@demo/testing from local cache - Cache
    fmt/8.0.1 from 'conancenter' - Cache
Packages
    base-library/1.0.0@demo/testing:4f2b14d304ab8e4391d162a6eb44110cc27a3faa - Build
    fmt/8.0.1:d4e9c4f02b4f03edf5a640dcd22779727d782e79 - Cache

Installing (downloading, building) binaries...
fmt/8.0.1: Already installed!
base-library/1.0.0@demo/testing: WARN: Build folder is dirty, removing it: /home/developer/.conan/data/base-library/1.0.0/demo/testing/build/4f2b14d304ab8e4391d162a6eb44110cc27a3faa
base-library/1.0.0@demo/testing: Configuring sources in /home/developer/.conan/data/base-library/1.0.0/demo/testing/source
base-library/1.0.0@demo/testing: Copying sources to build folder
base-library/1.0.0@demo/testing: Building your package in /home/developer/.conan/data/base-library/1.0.0/demo/testing/build/4f2b14d304ab8e4391d162a6eb44110cc27a3faa
base-library/1.0.0@demo/testing: Generator cmake_find_package created Findfmt.cmake
base-library/1.0.0@demo/testing: Generator cmake_find_package_multi created fmt-config-version.cmake
base-library/1.0.0@demo/testing: Generator cmake_find_package_multi created fmt-config.cmake
base-library/1.0.0@demo/testing: Generator cmake_find_package_multi created fmtTargets.cmake
base-library/1.0.0@demo/testing: Generator cmake_find_package_multi created fmtTarget-release.cmake
base-library/1.0.0@demo/testing: Aggregating env generators
base-library/1.0.0@demo/testing: Calling build()
base-library/1.0.0@demo/testing:
base-library/1.0.0@demo/testing: ERROR: Package '4f2b14d304ab8e4391d162a6eb44110cc27a3faa' build failed
base-library/1.0.0@demo/testing: WARN: Build folder /home/developer/.conan/data/base-library/1.0.0/demo/testing/build/4f2b14d304ab8e4391d162a6eb44110cc27a3faa
ERROR: base-library/1.0.0@demo/testing: Error in build() method, line 74
        cmake = self._configure_cmake()
while calling '_configure_cmake', line 65
        self._cmake = CMake(self)
        ConanException: The file /home/developer/.conan/data/base-library/1.0.0/demo/testing/build/4f2b14d304ab8e4391d162a6eb44110cc27a3faa/conanbuild.conf does not exist. Please, make sure that it was not generated in another folder.

What is the problem here and how can I resolve this? I could not find anything related to this?

Body:
I had the same problem and finally found the issue:

The CMake you are importing is the one working with the CMakeToolchain which are both part of the conan.tools.cmake module.
The one that is described in the usage of cmake_find_package[ref] is the one in conans module

So replacing:

from conans import ConanFile, tools
from conan.tools.cmake import CMake, CMakeToolchain

by

from conans import ConanFile, tools, CMake
from conan.tools.cmake import CMakeToolchain

should fix your problem


问:
when can we rebuild the Consumerwidget 【flutter+riverpod】
I'm beginner in flutter and riverpod and have a issue which troubles me.
could anyone solve the issue?

I'm developing app which has BottomNavigationBar on its bottom.
when tap any button of them, I wanna change the colors of buttons so that selected button seems to be active
I use StateProvider of riverpod to hold state of the BottomNavigationBarItems.
but when I tap the button, the ConsumerWidget isn't being rebuilt.
what is the reason??
version:flutter_riverpod: ^1.0.3

here is the code below

```<code>final _bottomNavigationBarItemsProvider = StateProvider.autoDispose((ref) {

  List<BottomNavigationBarItem>_bottomNavigationBarItems = <BottomNavigationBarItem>[];
  return _bottomNavigationBarItems;
});

class RootWidget extends ConsumerWidget  {
  Map<String,String>  argumentUserData;
  Map<String, String> argumentMasterData;
  Map<String,Map<String,String>>  argumentFriendData;
  Image? argumentMainPhotoData;
  int _selectedIndex=0;

～～～～～～～～～～～～～～～～～～～～～～～～～～～

//change button color to be active
  BottomNavigationBarItem _UpdateActiveState(int index) {
    return BottomNavigationBarItem(
        icon: Icon(
          _footerIcons[index],
          color: Colors.black87,
        ),
        title: Text(
          _footerItemNames[index],
          style: TextStyle(
            color: Colors.black87,
          ),
        ));
  }

//change button color to be nonactive
  BottomNavigationBarItem _UpdateDeactiveState(int index) {
    return BottomNavigationBarItem(
        icon: Icon(
          _footerIcons[index],
          color: Colors.black26,
        ),
        title: Text(
          _footerItemNames[index],
          style: TextStyle(
            color: Colors.black26,
          ),
        ));
  }

  void _onItemTapped(int index, WidgetRef ref) {

    ref.watch(_bottomNavigationBarItemsProvider.state).update((state){
      state[_selectedIndex] = _UpdateDeactiveState(_selectedIndex);
      state[index] = _UpdateActiveState(index);
      return state;}  );
    _selectedIndex = index;
  }

  RootWidget({required this.argumentUserData,required this.argumentMasterData,required this.argumentFriendData, required this.argumentMainPhotoData}) {

  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {

    ref.watch(_bottomNavigationBarItemsProvider.state).update((state){
      state.clear();
      state.add(_UpdateActiveState(0));
      for (var i = 1; i < _footerItemNames.length; i++) {
        state.add(_UpdateDeactiveState(i));
      }
      return state;}  );

    final _bottomNavigationBarItems=ref.watch(_bottomNavigationBarItemsProvider);

    return Scaffold(
      body:
      routeElement(_selectedIndex,argumentUserData["email"]!,argumentUserData["userDocId"]!),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: _bottomNavigationBarItems,
        currentIndex: _selectedIndex,
        onTap: (int index){ _onItemTapped(index,ref);
        }
      ),
    );
  }

～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～

}

</code>```

答:
To change the color you have a parameter for that "selectedItemColor" have a look : https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html. Look at my code below with the riverpod version:</p>
```<code>final indexProvider = StateProvider<int>((ref) {
  return 0;
});

class RootWidget extends ConsumerWidget {
  const RootWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      body: Container(),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
        currentIndex: ref.watch(indexProvider),
        selectedItemColor: Colors.amber[800],
        onTap: (index) {
          ref.read(indexProvider.state).update((_) => index);
        },
      ),
    );
  }
}
</code>```

Body:
I'm beginner in flutter and riverpod and have a issue which troubles me.
could anyone solve the issue?

I'm developing app which has BottomNavigationBar on its bottom.
when tap any button of them, I wanna change the colors of buttons so that selected button seems to be active
I use StateProvider of riverpod to hold state of the BottomNavigationBarItems.
but when I tap the button, the ConsumerWidget isn't being rebuilt.
what is the reason??
version:flutter_riverpod: ^1.0.3

here is the code below

final _bottomNavigationBarItemsProvider = StateProvider.autoDispose((ref) {

  List<BottomNavigationBarItem>_bottomNavigationBarItems = <BottomNavigationBarItem>[];
  return _bottomNavigationBarItems;
});

class RootWidget extends ConsumerWidget  {
  Map<String,String>  argumentUserData;
  Map<String, String> argumentMasterData;
  Map<String,Map<String,String>>  argumentFriendData;
  Image? argumentMainPhotoData;
  int _selectedIndex=0;

～～～～～～～～～～～～～～～～～～～～～～～～～～～

//change button color to be active
  BottomNavigationBarItem _UpdateActiveState(int index) {
    return BottomNavigationBarItem(
        icon: Icon(
          _footerIcons[index],
          color: Colors.black87,
        ),
        title: Text(
          _footerItemNames[index],
          style: TextStyle(
            color: Colors.black87,
          ),
        ));
  }

//change button color to be nonactive
  BottomNavigationBarItem _UpdateDeactiveState(int index) {
    return BottomNavigationBarItem(
        icon: Icon(
          _footerIcons[index],
          color: Colors.black26,
        ),
        title: Text(
          _footerItemNames[index],
          style: TextStyle(
            color: Colors.black26,
          ),
        ));
  }

  void _onItemTapped(int index, WidgetRef ref) {

    ref.watch(_bottomNavigationBarItemsProvider.state).update((state){
      state[_selectedIndex] = _UpdateDeactiveState(_selectedIndex);
      state[index] = _UpdateActiveState(index);
      return state;}  );
    _selectedIndex = index;
  }

  RootWidget({required this.argumentUserData,required this.argumentMasterData,required this.argumentFriendData, required this.argumentMainPhotoData}) {

  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {

    ref.watch(_bottomNavigationBarItemsProvider.state).update((state){
      state.clear();
      state.add(_UpdateActiveState(0));
      for (var i = 1; i < _footerItemNames.length; i++) {
        state.add(_UpdateDeactiveState(i));
      }
      return state;}  );

    final _bottomNavigationBarItems=ref.watch(_bottomNavigationBarItemsProvider);

    return Scaffold(
      body:
      routeElement(_selectedIndex,argumentUserData["email"]!,argumentUserData["userDocId"]!),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: _bottomNavigationBarItems,
        currentIndex: _selectedIndex,
        onTap: (int index){ _onItemTapped(index,ref);
        }
      ),
    );
  }

～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～

}

Body:
To change the color you have a parameter for that "selectedItemColor" have a look : https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html. Look at my code below with the riverpod version:

final indexProvider = StateProvider<int>((ref) {
  return 0;
});

class RootWidget extends ConsumerWidget {
  const RootWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      body: Container(),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
        currentIndex: ref.watch(indexProvider),
        selectedItemColor: Colors.amber[800],
        onTap: (index) {
          ref.read(indexProvider.state).update((_) => index);
        },
      ),
    );
  }
}


问:
Concatenate numeric value to the right side of an Arabic String in JS
var data = "عينات";

var num = "123";

var res = data + num; // returns عينات123

I am trying to concatenate numbers to the right side of the arabic text, but its jumping to the left side, also tried reversing the string, but didn't help.

Please suggest a solution in Javascript.

Thanks in Advance!

答:
Another answer suggested adding control characters into the text, but as someone commented this approach has it's downsides.

The reason you get the digits to the left no matter the order of the string is because you are using an LTR element (or the browser's console which is always LTR). Then if the digits come first they start at the left, and if the arabic letters come first they start at the right because arabic letters have "hard" RTL directionning even inside an LTR element.

However, if you are using an RTL element and put the digits first, it will show up as intended:

123عينات
```
</div>
</div>
</p>
<p>Or dynamically with JavaScript:
<div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = "عينات";
var num = "123";
var res = num + data;

var el = document.createElement('div');
el.dir = "rtl";
el.textContent = res;
document.body.append(el);</code>```

Body:
Another answer suggested adding control characters into the text, but as someone commented this approach has it's downsides.

The reason you get the digits to the left no matter the order of the string is because you are using an LTR element (or the browser's console which is always LTR). Then if the digits come first they start at the left, and if the arabic letters come first they start at the right because arabic letters have "hard" RTL directionning even inside an LTR element.

However, if you are using an RTL element and put the digits first, it will show up as intended:

<div dir="rtl">123عينات</div>

Or dynamically with JavaScript:

var data = "عينات";
var num = "123";
var res = num + data;

var el = document.createElement('div');
el.dir = "rtl";
el.textContent = res;
document.body.append(el);


问:
Webscraping: How to skip getelement when element/webpage doesn't exist?
I am scraping data from a website (thousands of different pages from the website), however, some of the webpages I try to navigate to don't exist or don't have the element/tag I need, these cases result in a bug prompt appearing and my code stops running. Because I am running through so many pages, I would prefer for my code just to return a blank/ignore them and move on.

I tried to use an iferror then null type statement for both the Price and WatchlistCount variables below, but this hasn't worked. Can you please help?

The code below is what I'm using to navigate to and scrape the webpages. The code before this creates the URLs that I need.

```<code>  Sub CM_Watchlist2000()

'Declaration
Dim Watchlist As Workbook
Dim Inp As Worksheet
Dim Inp2 As Worksheet
Dim ie As InternetExplorer
Dim doc As HTMLDocument
Dim i As Long
Dim iStart As Long

'Initialisation of Coinmarketcap and spreadsheet
Set Watchlist = Workbooks("Watchlist.xlsm")
Set Inp = Watchlist.Worksheets("Top 2000")
Set Inp2 = Watchlist.Worksheets("Lookup")
Set ie = New InternetExplorer

iStart = 0

For i = iStart To 100

Inp.Activate

    Range("A2").Offset(i, 0).Select
    Selection.Copy

Inp2.Activate

    Range("B1").Select
     Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=True

ie.Visible = True
ie.Navigate Inp2.Range("D1")

'Waits until webpage is open before running macro
Do Until ie.ReadyState = READYSTATE_COMPLETE
   DoEvents
Loop

Set doc = ie.Document
Price = doc.getElementsByClassName("priceValue ")(0).innerText
WatchlistCount = doc.getElementsByClassName("namePill")(2).innerText

Inp.Activate

    Range("B2").Offset(i, 0) = Price
    Range("C2").Offset(i, 0) = WatchlistCount

Next i

End Sub
</code>```

答:
First, try assigning the element to an object variable.  Then, if it returns the element, assign the price to your variable.</p>
```<code>Dim priceElement As Object
Set priceElement = doc.getElementsByClassName("priceValue")(0)

If Not priceElement Is Nothing Then
    Dim price As String
    price = priceElement.innerText
End If
</code>```

Body:
I am scraping data from a website (thousands of different pages from the website), however, some of the webpages I try to navigate to don't exist or don't have the element/tag I need, these cases result in a bug prompt appearing and my code stops running. Because I am running through so many pages, I would prefer for my code just to return a blank/ignore them and move on.

I tried to use an iferror then null type statement for both the Price and WatchlistCount variables below, but this hasn't worked. Can you please help?

The code below is what I'm using to navigate to and scrape the webpages. The code before this creates the URLs that I need.

  Sub CM_Watchlist2000()

'Declaration
Dim Watchlist As Workbook
Dim Inp As Worksheet
Dim Inp2 As Worksheet
Dim ie As InternetExplorer
Dim doc As HTMLDocument
Dim i As Long
Dim iStart As Long

'Initialisation of Coinmarketcap and spreadsheet
Set Watchlist = Workbooks("Watchlist.xlsm")
Set Inp = Watchlist.Worksheets("Top 2000")
Set Inp2 = Watchlist.Worksheets("Lookup")
Set ie = New InternetExplorer

iStart = 0

For i = iStart To 100

Inp.Activate

    Range("A2").Offset(i, 0).Select
    Selection.Copy

Inp2.Activate

    Range("B1").Select
     Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=True

ie.Visible = True
ie.Navigate Inp2.Range("D1")

'Waits until webpage is open before running macro
Do Until ie.ReadyState = READYSTATE_COMPLETE
   DoEvents
Loop

Set doc = ie.Document
Price = doc.getElementsByClassName("priceValue ")(0).innerText
WatchlistCount = doc.getElementsByClassName("namePill")(2).innerText

Inp.Activate

    Range("B2").Offset(i, 0) = Price
    Range("C2").Offset(i, 0) = WatchlistCount

Next i

End Sub

Body:
First, try assigning the element to an object variable.  Then, if it returns the element, assign the price to your variable.

Dim priceElement As Object
Set priceElement = doc.getElementsByClassName("priceValue")(0)

If Not priceElement Is Nothing Then
    Dim price As String
    price = priceElement.innerText
End If


问:
ASP.NET Core 3.1 service.AddControllerWithViews not working as expected
I am trying to create a controller and my startup.cs is defined like this:

```<code>using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp1
{
    public class Startup
    {
        public void ConfigurationServices(IServiceCollection service)
        {
            service.AddControllersWithViews();
            // service.AddControllers(); tried adding this line did not work
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }
}
</code>```

However on running the application, I am getting an error:

System.InvalidOperationException: 'Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddControllers' inside the call to 'ConfigureServices(...)' in the application startup code.'

Please help.

HomeController:

```<code>using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ConsoleApp1.Controllers
{
    public class HomeController : Controller
    {
        public string Index() // called action methods
        {
            return "Some string";
        }
    }
}
</code>```

Please let me know if any additional details are required

答:
since you are need controller with views, not api one, try this</p>
```<code>app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

            });
</code>```

Body:
I am trying to create a controller and my startup.cs is defined like this:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp1
{
    public class Startup
    {
        public void ConfigurationServices(IServiceCollection service)
        {
            service.AddControllersWithViews();
            // service.AddControllers(); tried adding this line did not work
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }
}

However on running the application, I am getting an error:

System.InvalidOperationException: 'Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddControllers' inside the call to 'ConfigureServices(...)' in the application startup code.'

Please help.

HomeController:

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ConsoleApp1.Controllers
{
    public class HomeController : Controller
    {
        public string Index() // called action methods
        {
            return "Some string";
        }
    }
}

Please let me know if any additional details are required

Body:
since you are need controller with views, not api one, try this

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

            });


问:
LINQ - Remove Parts of Expression Tree
I have the following LINQ query:

```<code>var query = session.Query<Event>()
    .Fetch(e => e.Venue); // Fetch is an IQueryable extension which does a join

// Code needed here to remove the fetch part

var num = query.Count(); // This then hits the database
</code>```

Unfortunately this throws an error as fetch is not supported for a count method. At this stage i'm sure you're thinking why don't i remove the fetch part. However i have simplified my example and this is not possible. What i'd ideally like to be able to do is navigate the expression tree for the LINQ query and remove any calls to Fetch before i call Count.

I'd appreciate it if someone could show how this is possible. Thanks

答:
Would it help to convert the query to an Enumerable and call Count() on this like this:

```<code>var num = query.AsEnumerable().Count();
</code>```

This would execute the query and afterwards makes a simple Count() on the result instead of letting the Count() flow into the ExpressionTree.

Title: LINQ - Remove Parts of Expression Tree

Body:
I have the following LINQ query:

var query = session.Query<Event>()
    .Fetch(e => e.Venue); // Fetch is an IQueryable extension which does a join

// Code needed here to remove the fetch part

var num = query.Count(); // This then hits the database

Unfortunately this throws an error as fetch is not supported for a count method. At this stage i'm sure you're thinking why don't i remove the fetch part. However i have simplified my example and this is not possible. What i'd ideally like to be able to do is navigate the expression tree for the LINQ query and remove any calls to Fetch before i call Count.

I'd appreciate it if someone could show how this is possible. Thanks

Body:
Would it help to convert the query to an Enumerable and call Count() on this like this:

var num = query.AsEnumerable().Count();

This would execute the query and afterwards makes a simple Count() on the result instead of letting the Count() flow into the ExpressionTree.


问:
Laravel Invoke or render a component directly from a route or controller
I have a component

```<code>class Projects extends Component
{

    public $projects;

    public function __construct()
    {
        $this->projects = Project::get();
    }

    public function render()
    {
        return view('components.projects');
    }
}
</code>```

and the corresponding components/projects.blade.php file containing

```<code>@dump($projects)
</code>```

I saw somewhere it is possible to return the component view directly from a route. However, none of these works

```<code>Route::get('projects1', Projects::class); // error

Route::get('projects2', [Projects::class]); // error

Route::get('projects3', [Projects::class, 'render']); // view does not have access to public $projects

Route::get('projects4', [Projects::class, '__construct']); // renders blank

Route::view('projects5', 'components.projects'); // view does not have access to public $projects

Route::get('projects6', fn() => view('components.projects'));  // view does not have access to public $projects

Route::get('projects7', fn() => <<<'blade'
    <x-projects></x-projects>
blade); // component not accessed
</code>```

Any clue?

When components/projects.blade.php contains

```<code> @dump(get_defined_vars())
</code>```

I see

```<code>array:5 [▼
  "__path" => "...\storage\framework\views/80c6e39e032dd35edb0d114508f22feaa7951180.php"
  "__data" => array:3 [▶]
  "__env" => Illuminate\View\Factory {#1791 ▶}
  "app" => Illuminate\Foundation\Application {#4 ▶}
  "errors" => Illuminate\Support\ViewErrorBag {#1811 ▶}
]
</code>```

projects is missing when using

```<code>Route::view('projects5', 'components.projects');
</code>```

The component class is not active, only the blade file.

When using either

```<code>return view('components.projects');

return (new Projects)->render();

return app(Projects::class)->render();
</code>```

from a controller, I get the same results.

The only way I can make it act as a component is going via a blade file containing

```<code><x-projects></x-projects>
</code>```

In that case, I see, as expected for a component:

```<code>array:10 [▼
  "__path" => "...\storage\framework\views/80c6e39e032dd35edb0d114508f22feaa7951180.php"
  "__data" => array:8 [▶]
  "__env" => Illuminate\View\Factory {#1793 ▶}
  "app" => Illuminate\Foundation\Application {#4 ▶}
  "errors" => Illuminate\Support\ViewErrorBag {#1813 ▶}
  "projects" => Illuminate\Database\Eloquent\Collection {#1831 ▶}
  "componentName" => "projects"
  "attributes" => Illuminate\View\ComponentAttributeBag {#1820 ▶}
  "slot" => Illuminate\Support\HtmlString {#1823 ▶}
  "__laravel_slots" => array:1 [▶]
]
</code>```

I wish to avoid to use an intermediate file only referencing the component.

答:
Taylor just showed this new feature at Laracon. It is part of Laravel  release 8.83

```<code>Route::get('projects', fn() => Blade::renderComponent(new Projects()));
</code>```

https://youtu.be/0Rq-yHAwYjQ?t=20525

It is this pull request: https://github.com/laravel/framework/pull/40745

Body:
I have a component

class Projects extends Component
{

    public $projects;

    public function __construct()
    {
        $this->projects = Project::get();
    }

    public function render()
    {
        return view('components.projects');
    }
}

and the corresponding components/projects.blade.php file containing

@dump($projects)

I saw somewhere it is possible to return the component view directly from a route. However, none of these works

Route::get('projects1', Projects::class); // error

Route::get('projects2', [Projects::class]); // error

Route::get('projects3', [Projects::class, 'render']); // view does not have access to public $projects

Route::get('projects4', [Projects::class, '__construct']); // renders blank

Route::view('projects5', 'components.projects'); // view does not have access to public $projects

Route::get('projects6', fn() => view('components.projects'));  // view does not have access to public $projects

Route::get('projects7', fn() => <<<'blade'
    <x-projects></x-projects>
blade); // component not accessed

Any clue?

When components/projects.blade.php contains

 @dump(get_defined_vars())

I see

array:5 [▼
  "__path" => "...\storage\framework\views/80c6e39e032dd35edb0d114508f22feaa7951180.php"
  "__data" => array:3 [▶]
  "__env" => Illuminate\View\Factory {#1791 ▶}
  "app" => Illuminate\Foundation\Application {#4 ▶}
  "errors" => Illuminate\Support\ViewErrorBag {#1811 ▶}
]

projects is missing when using

Route::view('projects5', 'components.projects');

The component class is not active, only the blade file.

When using either

return view('components.projects');

return (new Projects)->render();

return app(Projects::class)->render();

from a controller, I get the same results.

The only way I can make it act as a component is going via a blade file containing

<x-projects></x-projects>

In that case, I see, as expected for a component:

array:10 [▼
  "__path" => "...\storage\framework\views/80c6e39e032dd35edb0d114508f22feaa7951180.php"
  "__data" => array:8 [▶]
  "__env" => Illuminate\View\Factory {#1793 ▶}
  "app" => Illuminate\Foundation\Application {#4 ▶}
  "errors" => Illuminate\Support\ViewErrorBag {#1813 ▶}
  "projects" => Illuminate\Database\Eloquent\Collection {#1831 ▶}
  "componentName" => "projects"
  "attributes" => Illuminate\View\ComponentAttributeBag {#1820 ▶}
  "slot" => Illuminate\Support\HtmlString {#1823 ▶}
  "__laravel_slots" => array:1 [▶]
]

I wish to avoid to use an intermediate file only referencing the component.

Body:
Taylor just showed this new feature at Laracon. It is part of Laravel  release 8.83

Route::get('projects', fn() => Blade::renderComponent(new Projects()));

https://youtu.be/0Rq-yHAwYjQ?t=20525

It is this pull request: https://github.com/laravel/framework/pull/40745


问:
How to convert an array of numbers to bitmap image in python?
How do I convert a list of 1D numbers to a bitmap image?

I tried the following but it seems it doesn't quite work.

from PIL import Image

def get_img():
  img = Image.new('RGB', (255,255), "black") # Create a new black image
  pixels = img.load() # Create the pixel map
  width, height = img.size
  for i in range(width):    # For every pixel:
    for j in range(height):
      pixels[i,j] = (i, j, 100) # Set the colour accordingly
  return pixels

display(get_img()) # <PixelAccess at 0x7fca63ded7d0>
```

答:
```<code>from PIL import Image
from IPython.display import display

img = Image.new('RGB', (255,255), "black") # Create a new black image
list_of_pixels = list(img.getdata())
print(list_of_pixels)
im2 = Image.new(img.mode, img.size)
im2.putdata(list_of_pixels)

display(im2)
</code>```


问:
NumPy setup / import issue in lambda function
Runtime python 3.7 w/ compatible runtime 3.7

I keep getting Import error when trying to test API in lambda function

```<code>PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!\n\nImporting the numpy C-extensions failed. This error can happen for\nmany reasons, often due to issues with your setup or how NumPy was\ninstalled.\n\nWe have compiled some common reasons and troubleshooting tips at:\n\n    https://numpy.org/devdocs/user/troubleshooting-importerror.html\n\nPlease note and check the following:\n\n  * The Python version is: Python3.7 from \"/var/lang/bin/python3.7\"\n  * The NumPy version is: \"1.21.5\"\n\nand make sure that they are the versions you expect.\nPlease carefully study the documentation linked above for further help.\n\nOriginal error was: No module named 'numpy.core._multiarray_umath'\n",
  "errorType": "Runtime.ImportModuleError",
  "stackTrace": []
</code>```

I have tried adding numpy pip install inside docker, yet the issue still persists...

The dockfile engine used is amazonlinux:2

Any way of solving this weird issue?

答:
Based on the comments.

The solution was to use Numpy layer provided by AWS.

Body:
Runtime python 3.7 w/ compatible runtime 3.7

I keep getting Import error when trying to test API in lambda function

PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!\n\nImporting the numpy C-extensions failed. This error can happen for\nmany reasons, often due to issues with your setup or how NumPy was\ninstalled.\n\nWe have compiled some common reasons and troubleshooting tips at:\n\n    https://numpy.org/devdocs/user/troubleshooting-importerror.html\n\nPlease note and check the following:\n\n  * The Python version is: Python3.7 from \"/var/lang/bin/python3.7\"\n  * The NumPy version is: \"1.21.5\"\n\nand make sure that they are the versions you expect.\nPlease carefully study the documentation linked above for further help.\n\nOriginal error was: No module named 'numpy.core._multiarray_umath'\n",
  "errorType": "Runtime.ImportModuleError",
  "stackTrace": []

I have tried adding numpy pip install inside docker, yet the issue still persists...

The dockfile engine used is amazonlinux:2

Any way of solving this weird issue?


问:
Honeysql - Clojure - How to pass a vector as arguments into Values in insert-into statement
I'm working with Clojure using honeySql for formatting SQL statements.
The statement will run on a MySQL DB.

I'm looking for a way to pass an argument in the params and use it as the values in the inset-inro statement.

This is the statement I'm looking for :

```<code>INSERT INTO some_table
(a, b, c)
VALUES (1, 2, 3),
       (4, 5, 6);
</code>```

insert attempt:

```<code>(def insert-demo
  (-> (insert-into :some_table)
      (columns :a :b :c)
      (values [:param :vals)))
</code>```

This is the way I'm calling to the format function:

```<code>(sql/format dbcst/insert-demo {:inline true
                               :pretty true
                               :params {:vals [[1 2 3] [4 5 6]]}})
</code>```

Unforentualy this won't work.

I tried a few options in the values section no success so far.

```<code>(values [:?vals])

(values :?vals)
</code>```

Is there a way to pass a vector and use it as a param?

To be clear: I'm looking for a way to pass values dynamically.

Thanks

答:
Try this :</p>
```<code>(def insert-demo
  (-> (insert-into :some_table)
      (columns :a :b :c)
      (values [[1 2 3]
               [4 5 6]])))
</code>```

Body:
I'm working with Clojure using honeySql for formatting SQL statements.
The statement will run on a MySQL DB.

I'm looking for a way to pass an argument in the params and use it as the values in the inset-inro statement.

This is the statement I'm looking for :

INSERT INTO some_table
(a, b, c)
VALUES (1, 2, 3),
       (4, 5, 6);

insert attempt:

(def insert-demo
  (-> (insert-into :some_table)
      (columns :a :b :c)
      (values [:param :vals)))

This is the way I'm calling to the format function:

(sql/format dbcst/insert-demo {:inline true
                               :pretty true
                               :params {:vals [[1 2 3] [4 5 6]]}})

Unforentualy this won't work.

I tried a few options in the values section no success so far.

(values [:?vals])

(values :?vals)

Is there a way to pass a vector and use it as a param?

To be clear: I'm looking for a way to pass values dynamically.

Thanks

Body:
Try this :

(def insert-demo
  (-> (insert-into :some_table)
      (columns :a :b :c)
      (values [[1 2 3]
               [4 5 6]])))