问:
Access 'scrollLeft' property in react
I'm facing a problem with div property attributes when I convert my code from basic HTML and JS to react

the old code and the Desired result would be like this    :

https://codepen.io/fadeomar/project/editor/DVWGjd

now when starting to convert this project to react it cant change the value of scrollLeft property

my question is how I can change the value of scrollLeft for a certain element in react, all I got when I searched this issue that setting event listener to the whole window object, not for a specific element in DOM

I thought to use reusable component for Drag and Scroll and here is the code

```<code>import React from 'react';
import PropTypes from 'prop-types';

export class ScrollDrag extends React.Component {
  constructor(props) {
    super(props);
    this.ref = React.createRef();
    this.state = {
      isScrolling: false,
      clientX: 0,
      scrollX: 0,
    };
  }

  onMouseDown = e => {
    this.setState({ ...this.state, isScrolling: true,
     clientX: e.clientX });
  };

  onMouseUp = () => {
    this.setState({ ...this.state, isScrolling: false });
  };

  onMouseMove = e => {
    const { clientX, scrollX } = this.state;
    if (this.state.isScrolling) {
      this.ref.current.scrollLeft = scrollX + e.clientX - clientX;
      this.setState({scrollX: scrollX + e.clientX - clientX, clientX: e.clientX})
    }
  };

  render() {
    const { rootClass } = this.props;
    return (
      <div
        ref={this.ref}
        onMouseDown={this.onMouseDown}
        onMouseUp={this.onMouseUp}
        onMouseMove={this.onMouseMove}
        className={rootClass}
      >
        {React.Children.map(this.props.children, child =>
            React.Children.only(child))}
      </div>
    );
  }
}

ScrollDrag.defaultProps = {
  ref: { current: {} },
  rootClass: '',
};

ScrollDrag.propTypes = {
  ref: PropTypes.object,
  rootClass: PropTypes.string,
  children: PropTypes.string,
};

export default ScrollDrag;
</code>```

then I use it as an heir order component in the app

this is my try :
https://codesandbox.io/s/peaceful-butterfly-ndp6z?file

Any help to make this works be appreciated

答:
Updated answer

You were scrolling the wrong element. I removed the wrappers from the items and tweaked the css. I also had to reverse the polarity of the scrolling. Now it works.

https://codesandbox.io/s/awesome-tree-s8miv?file=/src/DragScroll.js

Original answer to original (now edited) question

The error is caused by the fact that you're not using ref you've created in this component:

```<code>render() {
    const { ref, rootClass } = this.props; // <-- this is wrong
    return (
      <div
        ref={ref}
        onMouseDown={this.onMouseDown}
        onMouseUp={this.onMouseUp}
        onMouseMove={this.onMouseMove}
        className={rootClass}
      >
        {React.Children.map(this.props.children, child =>
            React.Children.only(child))}
      </div>
    );
</code>```

It should just be like this:

```<code>render() {
    const { rootClass } = this.props;
    return (
      <div
        ref={this.ref}
        onMouseDown={this.onMouseDown}
        onMouseUp={this.onMouseUp}
        onMouseMove={this.onMouseMove}
        className={rootClass}
      >
        {React.Children.map(this.props.children, child =>
            React.Children.only(child))}
      </div>
    );
</code>```

Title: Access 'scrollLeft' property in react

Body:
I'm facing a problem with div property attributes when I convert my code from basic HTML and JS to react

the old code and the Desired result would be like this    :

https://codepen.io/fadeomar/project/editor/DVWGjd

now when starting to convert this project to react it cant change the value of scrollLeft property

my question is how I can change the value of scrollLeft for a certain element in react, all I got when I searched this issue that setting event listener to the whole window object, not for a specific element in DOM

I thought to use reusable component for Drag and Scroll and here is the code

import React from 'react';
import PropTypes from 'prop-types';

export class ScrollDrag extends React.Component {
  constructor(props) {
    super(props);
    this.ref = React.createRef();
    this.state = {
      isScrolling: false,
      clientX: 0,
      scrollX: 0,
    };
  }

  onMouseDown = e => {
    this.setState({ ...this.state, isScrolling: true,
     clientX: e.clientX });
  };

  onMouseUp = () => {
    this.setState({ ...this.state, isScrolling: false });
  };

  onMouseMove = e => {
    const { clientX, scrollX } = this.state;
    if (this.state.isScrolling) {
      this.ref.current.scrollLeft = scrollX + e.clientX - clientX;
      this.setState({scrollX: scrollX + e.clientX - clientX, clientX: e.clientX})
    }
  };

  render() {
    const { rootClass } = this.props;
    return (

        {React.Children.map(this.props.children, child =>
            React.Children.only(child))}

    );
  }
}

ScrollDrag.defaultProps = {
  ref: { current: {} },
  rootClass: '',
};

ScrollDrag.propTypes = {
  ref: PropTypes.object,
  rootClass: PropTypes.string,
  children: PropTypes.string,
};

export default ScrollDrag;

then I use it as an heir order component in the app

this is my try :
https://codesandbox.io/s/peaceful-butterfly-ndp6z?file

Any help to make this works be appreciated

Body:
Updated answer

You were scrolling the wrong element. I removed the wrappers from the items and tweaked the css. I also had to reverse the polarity of the scrolling. Now it works.

https://codesandbox.io/s/awesome-tree-s8miv?file=/src/DragScroll.js

Original answer to original (now edited) question

The error is caused by the fact that you're not using ref you've created in this component:

render() {
    const { ref, rootClass } = this.props; // <-- this is wrong
    return (
      <div
        ref={ref}
        onMouseDown={this.onMouseDown}
        onMouseUp={this.onMouseUp}
        onMouseMove={this.onMouseMove}
        className={rootClass}
      >
        {React.Children.map(this.props.children, child =>
            React.Children.only(child))}
      </div>
    );

It should just be like this:

render() {
    const { rootClass } = this.props;
    return (
      <div
        ref={this.ref}
        onMouseDown={this.onMouseDown}
        onMouseUp={this.onMouseUp}
        onMouseMove={this.onMouseMove}
        className={rootClass}
      >
        {React.Children.map(this.props.children, child =>
            React.Children.only(child))}
      </div>
    );


来源: stackexchange

问:
Creating a FactoryBot Hash model with complicated structure, including multiple nested attributes
I'm implementing a set of Cucumber driven API tests and stumbled into one specific model that has a few nested elements, like this:

```<code>factory :human_being, class: Hash do
  human {
    name {
      first_name { Faker::Name.first_name }
      last_name  { Faker::Name.last_name }
    }
    age { rand(1..100) }
  }
  initialize_with { attributes }
end
</code>```

The result I wanted to achieve should look like this:

```<code>{
  :human => {
    :name => {
      :first_name => "mike",
      :last_name => "blob"
      },
    :age => 16
  }
}
</code>```

I am invoking creation using FactoryBot.build(:human_being) and I get undefined method 'name' for #<FactoryBot::SyntaxRunner:0x00007fd640a39a80>

My env.rb has the World(FactoryBot::Syntax::Methods) / FactoryBot.find_definitions lines.

I've lurked through a few answers regarding the nested attributes / associations / traits but I didn't find a proper way to get what I want. Sorry if the post is duplicated and thanks in advance for help.

答:
Okay, seems that I've found the solution right after posting the question. Currently the following model creates the Hash I described in the question:

```<code>factory :human_being, class: Hash do
  human { {
    name: {
      first_name: Faker::Name.first_name,
      last_name:  Faker::Name.last_name,
    },
    age: rand(1..100),
    sex: %w(male female other).sample
  } }
  initialize_with { attributes }
end
</code>```

Although I'm not sure it is a completely correct answer from guidelines perspective, but at least it works for my exact case.

source (See 'Defining factories'): Because of the block syntax in Ruby, defining attributes as Hashes (for serialized/JSON columns, for example) requires two sets of curly brackets:

```<code>factory :program do
  configuration { { auto_resolve: false, auto_define: true } }
end
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm implementing a set of Cucumber driven API tests and stumbled into one specific model that has a few nested elements, like this:

factory :human_being, class: Hash do
  human {
    name {
      first_name { Faker::Name.first_name }
      last_name  { Faker::Name.last_name }
    }
    age { rand(1..100) }
  }
  initialize_with { attributes }
end

The result I wanted to achieve should look like this:

{
  :human => {
    :name => {
      :first_name => "mike",
      :last_name => "blob"
      },
    :age => 16
  }
}

I am invoking creation using FactoryBot.build(:human_being) and I get undefined method 'name' for #<FactoryBot::SyntaxRunner:0x00007fd640a39a80>

My env.rb has the World(FactoryBot::Syntax::Methods) / FactoryBot.find_definitions lines.

I've lurked through a few answers regarding the nested attributes / associations / traits but I didn't find a proper way to get what I want. Sorry if the post is duplicated and thanks in advance for help.

Body:
Okay, seems that I've found the solution right after posting the question. Currently the following model creates the Hash I described in the question:

factory :human_being, class: Hash do
  human { {
    name: {
      first_name: Faker::Name.first_name,
      last_name:  Faker::Name.last_name,
    },
    age: rand(1..100),
    sex: %w(male female other).sample
  } }
  initialize_with { attributes }
end

Although I'm not sure it is a completely correct answer from guidelines perspective, but at least it works for my exact case.

source (See 'Defining factories'): Because of the block syntax in Ruby, defining attributes as Hashes (for serialized/JSON columns, for example) requires two sets of curly brackets:

factory :program do
  configuration { { auto_resolve: false, auto_define: true } }
end


问:
Value of -faligned-new in GCC
I had an issue similar to this one
gcc over-aligned new support (alignas )
so I added -faligned-new compiler flag.

This fixed a compiler warning. However, when the compiler is run with --verbose flag, I get this output https://pastebin.com/X2QZAtSb, in which the most important line is

```<code>COLLECT_GCC_OPTIONS='-o' 'main' '-faligned-new=1' '-v' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
</code>```

GCC manual (https://gcc.gnu.org/onlinedocs/gcc-9.3.0/gcc/C_002b_002b-Dialect-Options.html#C_002b_002b-Dialect-Options) states that:

-faligned-new

```<code>Enable support for C++17 new of types that require more
alignment than void* ::operator new(std::size_t) provides.
A numeric argument such as -faligned-new=32 can be used to specify how much alignment
(in bytes) is provided by that function, but few users will need to override
the default of alignof(std::max_align_t).
</code>```

What does -faligned-new=1 mean? If I understand correctly, it should be equal to 8 or 16 or something (default of alignof(std::max_align_t), https://en.cppreference.com/w/cpp/types/max_align_t), not 1.

To reproduce compile simple main.cpp:

```<code>#include <iostream>

int main() {
    std::cout << "hello world\n";

    return 0;
}
</code>```

using g++ main.cpp -o main -faligned-new --verbose

I am compiling the program on GCC 9.3.0, on a Debian system,  sizeof(max_align_t) is 32 on my system.

答:
What does -faligned-new=1 mean?

Apparently, it means that -faligned-new was used without explicit threshold.

As per documentation, the threshold defaults to alignment of std::max_align_t in this case.

Title: Value of -faligned-new in GCC

Body:
I had an issue similar to this one
gcc over-aligned new support (alignas )
so I added -faligned-new compiler flag.

This fixed a compiler warning. However, when the compiler is run with --verbose flag, I get this output https://pastebin.com/X2QZAtSb, in which the most important line is

COLLECT_GCC_OPTIONS='-o' 'main' '-faligned-new=1' '-v' '-shared-libgcc' '-mtune=generic' '-march=x86-64'

GCC manual (https://gcc.gnu.org/onlinedocs/gcc-9.3.0/gcc/C_002b_002b-Dialect-Options.html#C_002b_002b-Dialect-Options) states that:

-faligned-new

Enable support for C++17 new of types that require more
alignment than void* ::operator new(std::size_t) provides.
A numeric argument such as -faligned-new=32 can be used to specify how much alignment
(in bytes) is provided by that function, but few users will need to override
the default of alignof(std::max_align_t).

What does -faligned-new=1 mean? If I understand correctly, it should be equal to 8 or 16 or something (default of alignof(std::max_align_t), https://en.cppreference.com/w/cpp/types/max_align_t), not 1.

To reproduce compile simple main.cpp:

#include <iostream>

int main() {
    std::cout << "hello world\n";

    return 0;
}

using g++ main.cpp -o main -faligned-new --verbose

I am compiling the program on GCC 9.3.0, on a Debian system,  sizeof(max_align_t) is 32 on my system.


问:
How to access client socket id from the http request?
Recently I've stumbled upon an interesting problem.

The goal was to create a communication between a browser client and my expressJs server via web sockets to quickly show changes made on the another client. Also I'm using a standard http connection to communicate with my database.

The problem is that I need to generate an individual link for every user (based on their cookie I've created) but on the server only the last one is valid.
So every person displaying invalid link should see something like Please refresh the page.
To achieve that I've emitted event linkExpired globally which marked sender's link as expired as well.

I can't access a client socket (which would solve my problem) because I don't want to store them after establishing connection (as was proposed here for example). In my opinion it isn't an elegant solution.

Any help would be appreciated.

答:
After some time I've come up with a different approach.
Maybe creating a cookie storing id of the client socket after establishing connection would be sufficient. So I did that... And I've realised that socket.io already have a cookie containing a socket id.

The only thing to do was to use cookie-parser with express:

const cookieParser = require('cookie-parser');
require('express')().use(cookieParser());
```

<p>After that I had an access to all the cookies passed to all http requests which allowed me to filter sockets based on the id and avoid sending an event to the sender.</p>

<pre class="lang-js prettyprint-override"><code>const io = require("socket.io").io;
Object.keys(io.sockets.sockets).forEach((_socketId) => {
  if (req.cookies.io !== _socketId) {
    io.to(_socketId).emit('linkExpired');
  }
});
</code>```

Please pay attention to the fragment where I used a req.cookies.io as an id of the socket. I've noticed that socket.io is using cookie named io to store current id of the client socket.

And on the client side I could achieve showing banner about expiration as follows:

import socketIOClient from "socket.io-client";
const io = socketIOClient(process.env.REACT_APP_URL);
io.on('linkExpired', () => {
  setLink('Refresh the page');
});
```

<p>Also I had to remember to pass options to the <code>fetch</code> method to send cookies:</p>

<pre class="lang-js prettyprint-override"><code>fetch(`${process.env.REACT_APP_URL}/api/main`, {
  credentials: 'include'
});
</code>```

I've spend too much time with this so I hope somebody would benefit from this explanation.

Body:
After some time I've come up with a different approach.
Maybe creating a cookie storing id of the client socket after establishing connection would be sufficient. So I did that... And I've realised that socket.io already have a cookie containing a socket id.

The only thing to do was to use cookie-parser with express:

const cookieParser = require('cookie-parser');
require('express')().use(cookieParser());

After that I had an access to all the cookies passed to all http requests which allowed me to filter sockets based on the id and avoid sending an event to the sender.

const io = require("socket.io").io;
Object.keys(io.sockets.sockets).forEach((_socketId) => {
  if (req.cookies.io !== _socketId) {
    io.to(_socketId).emit('linkExpired');
  }
});

Please pay attention to the fragment where I used a req.cookies.io as an id of the socket. I've noticed that socket.io is using cookie named io to store current id of the client socket.

And on the client side I could achieve showing banner about expiration as follows:

import socketIOClient from "socket.io-client";
const io = socketIOClient(process.env.REACT_APP_URL);
io.on('linkExpired', () => {
  setLink('Refresh the page');
});

Also I had to remember to pass options to the fetch method to send cookies:

fetch(`${process.env.REACT_APP_URL}/api/main`, {
  credentials: 'include'
});

I've spend too much time with this so I hope somebody would benefit from this explanation.


问:
How to loop over an Array with JavaScript?
I have a string that has data separated by a pipe character (|).

Example

```<code>var somestring = "data1|data2|data3";
var separated = somestring.split("|");
</code>```

I know how to use the split() to separate each data.

However, I don't know how many pipes there will be in the resulting Array.

In jQuery or JavaScript, how do I loop over the array returned?

答:
Loop through with a FOR...NEXT construct like in most other languages:</p>

```<code>var somestring = "data1|data2|data3";
var separated = somestring.split("|");

for (i=0 ; i<separated.length; i++) {
 document.write(separated[i]);
 document.write("<br/>");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a string that has data separated by a pipe character (|).

Example

var somestring = "data1|data2|data3";
var separated = somestring.split("|");

I know how to use the split() to separate each data.

However, I don't know how many pipes there will be in the resulting Array.

In jQuery or JavaScript, how do I loop over the array returned?

Body:
Loop through with a FOR...NEXT construct like in most other languages:

var somestring = "data1|data2|data3";
var separated = somestring.split("|");

for (i=0 ; i<separated.length; i++) {
 document.write(separated[i]);
 document.write("<br/>");
}


问:
finding the unpaired integer with O(logN)
I stumbled upon this quiz:

A non-empty array A consisting of N integers is given.

  The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

  E.G

    A = [9,3,9,3,5,7,5 ] // 3, 5 and 9 can be paired while 7 is left alone

  Write a efficient function that given an array A of N integers returns the value of the unpaired element.

  Note:

  1) N is an odd integer within the range [1..1,000,000];

  2) each element of array A is an integer within the range [1..1,000,000,000];

  3) all but one of the values in A occur an even number of times.

here's my solution, which is not considered efficient because it's complexity is O(N**2).

```<code>function solution(A) {
    let res;
    A.sort();
    //3,3,7,9,9,9,9
    while(A.length>1) {
        if(A[0] === A[1]) {
            A.shift();
            A.shift();
        } else {
            res = A[0];
            break;
        }
    }
    res = A.length === 1 ? A[0] : res;
    return res;
}
</code>```

How do i improve this from here?

Here the failing tests:

答:
I already saw this problem, you can XOR all numbers in an array and the final result will be the only number not paired.
This solution is quite fast and should satisfy your speed requirement,

Small basic example:

console.log(12 ^ 3 ^ 3 ^ 12 ^ 4 ^ 5 ^ 4)

The above code will return 5 (which is the only number with no pair on my example).

Body:
I stumbled upon this quiz:

A non-empty array A consisting of N integers is given.

  The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

  E.G

    A = [9,3,9,3,5,7,5 ] // 3, 5 and 9 can be paired while 7 is left alone

  Write a efficient function that given an array A of N integers returns the value of the unpaired element.

  Note:

  1) N is an odd integer within the range [1..1,000,000];

  2) each element of array A is an integer within the range [1..1,000,000,000];

  3) all but one of the values in A occur an even number of times.

here's my solution, which is not considered efficient because it's complexity is O(N**2).

function solution(A) {
    let res;
    A.sort();
    //3,3,7,9,9,9,9
    while(A.length>1) {
        if(A[0] === A[1]) {
            A.shift();
            A.shift();
        } else {
            res = A[0];
            break;
        }
    }
    res = A.length === 1 ? A[0] : res;
    return res;
}

How do i improve this from here?

Here the failing tests:


问:
Difficulties setting up maven project using AWS encryption SDK
I have the following pom file in my maven project on IntelliJ-

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>aws-encryption</groupId>
    <artifactId>aws-encryption</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencyManagement>
     <dependencies>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-encryption-sdk-java</artifactId>
            <version>1.6.1</version>
        </dependency>
         <dependency>
             <groupId>com.amazonaws</groupId>
             <artifactId>aws-java-sdk</artifactId>
             <version>1.11.327</version>
         </dependency>

         <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-ext-jdk15on -->
         <dependency>
             <groupId>org.bouncycastle</groupId>
             <artifactId>bcprov-ext-jdk15on</artifactId>
             <version>1.65</version>
         </dependency>

         <dependency>
             <groupId>com.amazonaws</groupId>
             <artifactId>aws-java-sdk-kms</artifactId>
             <version>1.11.765</version>
         </dependency>

     </dependencies>
    </dependencyManagement>
</project>
</code>```

And the following class file -

```<code>package com.aws.encrypt;

import java.util.Collections;
import java.util.Map;

public class Main {

    private static String keyArn;
    private static String data;

    public static void main(String[] args) {
        keyArn = args[0];
        data = args[1];

        // Instantiate the SDK
        final AwsCrypto crypto = new AwsCrypto();

        // Set up the KmsMasterKeyProvider backed by the default credentials
        final KmsMasterKeyProvider prov = KmsMasterKeyProvider.builder().withKeysForEncryption(keyArn).build();

        // Encrypt the data
        //
        // Most encrypted data should have an associated encryption context
        // to protect integrity. This sample uses placeholder values.
        //
        // For more information see:
        // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management
        final Map<String, String> context = Collections.singletonMap("Example", "String");

        final String ciphertext = crypto.encryptString(prov, data, context).getResult();
        System.out.println("Ciphertext: " + ciphertext);

        // Decrypt the data
        final CryptoResult<String, KmsMasterKey> decryptResult = crypto.decryptString(prov, ciphertext);

        // Before returning the plaintext, verify that the customer master key that
        // was used in the encryption operation was the one supplied to the master key provider.
        if (!decryptResult.getMasterKeyIds().get(0).equals(keyArn)) {
            throw new IllegalStateException("Wrong key ID!");
        }

        // Also, verify that the encryption context in the result contains the
        // encryption context supplied to the encryptString method. Because the
        // SDK can add values to the encryption context, don't require that
        // the entire context matches.
        for (final Map.Entry<String, String> e : context.entrySet()) {
            if (!e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey()))) {
                throw new IllegalStateException("Wrong Encryption Context!");
            }
        }

        // Now we can return the plaintext data
        System.out.println("Decrypted: " + decryptResult.getResult());
    }

}
</code>```

It seems all the dependency jars were not downloaded.
I can only find aws-encryption-1.0-SNAPSHOT.jar in my local repository.
Not sure why the others did not get downloaded. I tried mvn clean install as well.

I don't see any issues with my repository settings -

```<code><settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                        http://maven.apache.org/xsd/settings-1.0.0.xsd">

<localRepository>/Users/sandeepan.nath/.m2/repository</localRepository>

</settings>
</code>```

What could be wrong.

答:
Have you tried the maven debug flag?
eg

```<code>mvn clean install -X
</code>```

it may give you some clue about what actually happens under the hood
hth
update:
dependency management is for grouping dependencies for child projects, in a parent pom. If this is not the case one can just use dependencies alone.

Body:
I have the following pom file in my maven project on IntelliJ-

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>aws-encryption</groupId>
    <artifactId>aws-encryption</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencyManagement>
     <dependencies>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-encryption-sdk-java</artifactId>
            <version>1.6.1</version>
        </dependency>
         <dependency>
             <groupId>com.amazonaws</groupId>
             <artifactId>aws-java-sdk</artifactId>
             <version>1.11.327</version>
         </dependency>

         <dependency>
             <groupId>org.bouncycastle</groupId>
             <artifactId>bcprov-ext-jdk15on</artifactId>
             <version>1.65</version>
         </dependency>

         <dependency>
             <groupId>com.amazonaws</groupId>
             <artifactId>aws-java-sdk-kms</artifactId>
             <version>1.11.765</version>
         </dependency>

     </dependencies>
    </dependencyManagement>
</project>

And the following class file -

package com.aws.encrypt;

import java.util.Collections;
import java.util.Map;

public class Main {

    private static String keyArn;
    private static String data;

    public static void main(String[] args) {
        keyArn = args[0];
        data = args[1];

        // Instantiate the SDK
        final AwsCrypto crypto = new AwsCrypto();

        // Set up the KmsMasterKeyProvider backed by the default credentials
        final KmsMasterKeyProvider prov = KmsMasterKeyProvider.builder().withKeysForEncryption(keyArn).build();

        // Encrypt the data
        //
        // Most encrypted data should have an associated encryption context
        // to protect integrity. This sample uses placeholder values.
        //
        // For more information see:
        // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management
        final Map<String, String> context = Collections.singletonMap("Example", "String");

        final String ciphertext = crypto.encryptString(prov, data, context).getResult();
        System.out.println("Ciphertext: " + ciphertext);

        // Decrypt the data
        final CryptoResult<String, KmsMasterKey> decryptResult = crypto.decryptString(prov, ciphertext);

        // Before returning the plaintext, verify that the customer master key that
        // was used in the encryption operation was the one supplied to the master key provider.
        if (!decryptResult.getMasterKeyIds().get(0).equals(keyArn)) {
            throw new IllegalStateException("Wrong key ID!");
        }

        // Also, verify that the encryption context in the result contains the
        // encryption context supplied to the encryptString method. Because the
        // SDK can add values to the encryption context, don't require that
        // the entire context matches.
        for (final Map.Entry<String, String> e : context.entrySet()) {
            if (!e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey()))) {
                throw new IllegalStateException("Wrong Encryption Context!");
            }
        }

        // Now we can return the plaintext data
        System.out.println("Decrypted: " + decryptResult.getResult());
    }

}

It seems all the dependency jars were not downloaded.
I can only find aws-encryption-1.0-SNAPSHOT.jar in my local repository.
Not sure why the others did not get downloaded. I tried mvn clean install as well.

I don't see any issues with my repository settings -

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                        http://maven.apache.org/xsd/settings-1.0.0.xsd">

<localRepository>/Users/sandeepan.nath/.m2/repository</localRepository>

</settings>

What could be wrong.

Body:
Have you tried the maven debug flag?
eg

mvn clean install -X

it may give you some clue about what actually happens under the hood
hth
update:
dependency management is for grouping dependencies for child projects, in a parent pom. If this is not the case one can just use dependencies alone.


问:
Getting tidy output from post hoc tests
Consider this data frame dat1:

dat1 <- data.frame(Region = rep(c("r1","r2"), each = 100),
                   State = rep(c("NY","MA","FL","GA"), each = 10),
                   Loc = rep(c("a","b","c","d","e","f","g","h"),each = 5),
                   ID = rep(c(1:10), each=2),
                   var1 = rnorm(200),
                   var2 = rnorm(200),
                   var3 = rnorm(200),
                   var4 = rnorm(200),
                   var5 = rnorm(200))
```

<p>I have data frames that are similar to <code>dat1</code> created above. <code>Region</code>,<code>State</code>,and <code>Loc</code> are grouping variables for each observation <code>ID</code>, and 5 measurements are taken upon each observation <code>var1:var5</code>. For each grouping variable, I am conducting univariate anovas on each <code>var</code>. When significant differences are found, I am using the <code>TukeyHSD()</code> function and the <code>multcompLetters()</code> function from the <code>multcompView</code> package to generate CLD's on the groups. Since I want to do this for each grouping variable I am trying to write a function to keep myself from being repetitive and making typos. Below shows where I am with this:</p>

<pre class="lang-r prettyprint-override"><code>library(tidyverse)
library(multcomp)
library(multcompView)

Tuk <- function(dat,groupvar,var){
  TUK <- TukeyHSD(aov(lm(get(var) ~ get(groupvar), data=dat)))
  names(TUK)[[1]] <- paste0(groupvar)
  lets<-multcompLetters(extract_p(TUK$groupvar))
  lets
}
#assuming all 5 vars were significant in the anovas, I would then run this for each grouping variable as follows:
vars <- paste0(names(dat1[,5:9]))
#by Region
lapply(vars, FUN=Tuk, dat=dat1, groupvar="Region")
#by State
lapply(vars, FUN=Tuk, dat=dat1, groupvar="State")
#by Loc
lapply(vars, FUN=Tuk, dat=dat1, groupvar="Loc")
</code>```

The code works outside of the function. The function will create the model, but I cant figure out how to format it so that it recognizes what groupvar is for the multcompLetters(extract_p()) part? How can I fix this, and how can I get it the function to output a tidy table that shows each group and the letters for each variable I give it at once. For example it would look something like this for State using all 5 variables

     NY   MA   FL   GA
var1  a    ab   c    a
var2  a    ab   b    c
var3  a    c    ab   bc
var4  ab   c    ab   ab
var5  a    b    c     b
```

Also, is there a reasonable way to make this function produce boxplots (for each variable) of the groups that show the CLD letters?

答:
You accepted the answer but just documenting you can get what you originally asked with a little work...

# https://stackoverflow.com/questions/62050403/getting-tidy-output-from-post-hoc-tests/62052651#62052651

library(multcompView)
library(dplyr)
library(purrr)
library(tidyselect)

set.seed(1111)
dat1 <- data.frame(Region = rep(c("r1","r2"), each = 100),
                   State = rep(c("NY","MA","FL","GA"), each = 10),
                   Loc = rep(c("a","b","c","d","e","f","g","h"),each = 5),
                   ID = rep(c(1:10), each = 2),
                   var1 = rnorm(200),
                   var2 = rnorm(200),
                   var3 = rnorm(200),
                   var4 = rnorm(200),
                   var5 = rnorm(200))

# You want just the letters which you can get by ...
multcompLetters(TukeyHSD(aov(var1  ~ State, data = dat1))$State[,4])$Letters
#>  GA  MA  NY  FL
#> "a" "a" "a" "a"

# Your function redone...
Tuk3 <- function(data,
                 groupvar,
                 var) {
  lst <- as.list(match.call())
  if (is.symbol(lst$groupvar) || is.symbol(lst$var)) {
    stop("Please quote all variables")
  }
  if (!is.call(groupvar)) {
    grouplabel <- rlang::as_name(rlang::enquo(groupvar))
  }

  data <-
    dplyr::select(
      .data = data,
      var = {{ var }},
      groupvar = {{ groupvar }}
    )

  aov_object <- aov(var ~ groupvar, data = data)
  aov_results <- broom::tidy(aov_object) %>%
    mutate(term = if_else(term != "Residuals", grouplabel, term))
  tukey_results <- broom::tidy(TukeyHSD(aov_object)) %>%
    mutate(term = grouplabel)

  # multcompLetters is annoying and wants named vectors
  p_values <- tukey_results %>% pull(adj.p.value)
  names(p_values) <- tukey_results %>% pull(comparison)
  letters_results <-  data.frame(as.list(multcompLetters(p_values)$Letters))
  return(letters_results)
}

# works for one
Tuk3(data = dat1, groupvar = "State", var = "var1")
#>   GA MA NY FL
#> 1  a  a  a  a

# you could do this manually but I do it a lot so I have a function
variables_list <- CGPfunctions::cross2_var_vectors(dat1, 1:3, 5:9)

# Make the names nice
outcomes2 <- variables_list$lista
groupings2 <- variables_list$listb
names(groupings2) <- unlist(groupings2)
names(outcomes2) <- paste(unlist(outcomes2), "~", unlist(groupings2))

# get all 15 results and a final map_dfr to make one tibble
map2(.x = outcomes2,
     .y = groupings2,
     .f = ~ Tuk3(dat = dat1,
                 var = tidyselect::all_of(.x),
                 groupvar = tidyselect::all_of(.y))) %>%
       map_dfr(~ rbind(.), .id = "Which_ANOVA")
#>      Which_ANOVA   r2   r1   GA   MA   NY   FL    b    c    d    e    f    g
#> 1  var1 ~ Region    a    a <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 2  var2 ~ Region    a    a <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 3  var3 ~ Region    a    a <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 4  var4 ~ Region    a    a <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 5  var5 ~ Region    a    a <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 6   var1 ~ State <NA> <NA>    a    a    a    a <NA> <NA> <NA> <NA> <NA> <NA>
#> 7   var2 ~ State <NA> <NA>    a    a    a    a <NA> <NA> <NA> <NA> <NA> <NA>
#> 8   var3 ~ State <NA> <NA>    a    a    a    a <NA> <NA> <NA> <NA> <NA> <NA>
#> 9   var4 ~ State <NA> <NA>    a    a    a    a <NA> <NA> <NA> <NA> <NA> <NA>
#> 10  var5 ~ State <NA> <NA>    a    b   ab   ab <NA> <NA> <NA> <NA> <NA> <NA>
#> 11    var1 ~ Loc <NA> <NA> <NA> <NA> <NA> <NA>    a    a    a    a    a    a
#> 12    var2 ~ Loc <NA> <NA> <NA> <NA> <NA> <NA>    a    a    a    a    a    a
#> 13    var3 ~ Loc <NA> <NA> <NA> <NA> <NA> <NA>    a    a    a    a    a    a
#> 14    var4 ~ Loc <NA> <NA> <NA> <NA> <NA> <NA>    a    a    a    a    a    a
#> 15    var5 ~ Loc <NA> <NA> <NA> <NA> <NA> <NA>   ab   ab   ab    a   ab    b

```

I cut off the results

Title: Getting tidy output from post hoc tests

Body:
Consider this data frame dat1:

dat1 <- data.frame(Region = rep(c("r1","r2"), each = 100),
                   State = rep(c("NY","MA","FL","GA"), each = 10),
                   Loc = rep(c("a","b","c","d","e","f","g","h"),each = 5),
                   ID = rep(c(1:10), each=2),
                   var1 = rnorm(200),
                   var2 = rnorm(200),
                   var3 = rnorm(200),
                   var4 = rnorm(200),
                   var5 = rnorm(200))

I have data frames that are similar to dat1 created above. Region,State,and Loc are grouping variables for each observation ID, and 5 measurements are taken upon each observation var1:var5. For each grouping variable, I am conducting univariate anovas on each var. When significant differences are found, I am using the TukeyHSD() function and the multcompLetters() function from the multcompView package to generate CLD's on the groups. Since I want to do this for each grouping variable I am trying to write a function to keep myself from being repetitive and making typos. Below shows where I am with this:

library(tidyverse)
library(multcomp)
library(multcompView)

Tuk <- function(dat,groupvar,var){
  TUK <- TukeyHSD(aov(lm(get(var) ~ get(groupvar), data=dat)))
  names(TUK)[[1]] <- paste0(groupvar)
  lets<-multcompLetters(extract_p(TUK$groupvar))
  lets
}
#assuming all 5 vars were significant in the anovas, I would then run this for each grouping variable as follows:
vars <- paste0(names(dat1[,5:9]))
#by Region
lapply(vars, FUN=Tuk, dat=dat1, groupvar="Region")
#by State
lapply(vars, FUN=Tuk, dat=dat1, groupvar="State")
#by Loc
lapply(vars, FUN=Tuk, dat=dat1, groupvar="Loc")

The code works outside of the function. The function will create the model, but I cant figure out how to format it so that it recognizes what groupvar is for the multcompLetters(extract_p()) part? How can I fix this, and how can I get it the function to output a tidy table that shows each group and the letters for each variable I give it at once. For example it would look something like this for State using all 5 variables

     NY   MA   FL   GA
var1  a    ab   c    a
var2  a    ab   b    c
var3  a    c    ab   bc
var4  ab   c    ab   ab
var5  a    b    c     b

Also, is there a reasonable way to make this function produce boxplots (for each variable) of the groups that show the CLD letters?

Body:
You accepted the answer but just documenting you can get what you originally asked with a little work...

# https://stackoverflow.com/questions/62050403/getting-tidy-output-from-post-hoc-tests/62052651#62052651

library(multcompView)
library(dplyr)
library(purrr)
library(tidyselect)

set.seed(1111)
dat1 <- data.frame(Region = rep(c("r1","r2"), each = 100),
                   State = rep(c("NY","MA","FL","GA"), each = 10),
                   Loc = rep(c("a","b","c","d","e","f","g","h"),each = 5),
                   ID = rep(c(1:10), each = 2),
                   var1 = rnorm(200),
                   var2 = rnorm(200),
                   var3 = rnorm(200),
                   var4 = rnorm(200),
                   var5 = rnorm(200))

# You want just the letters which you can get by ...
multcompLetters(TukeyHSD(aov(var1  ~ State, data = dat1))$State[,4])$Letters
#>  GA  MA  NY  FL
#> "a" "a" "a" "a"

# Your function redone...
Tuk3 <- function(data,
                 groupvar,
                 var) {
  lst <- as.list(match.call())
  if (is.symbol(lst$groupvar) || is.symbol(lst$var)) {
    stop("Please quote all variables")
  }
  if (!is.call(groupvar)) {
    grouplabel <- rlang::as_name(rlang::enquo(groupvar))
  }

  data <-
    dplyr::select(
      .data = data,
      var = {{ var }},
      groupvar = {{ groupvar }}
    )

  aov_object <- aov(var ~ groupvar, data = data)
  aov_results <- broom::tidy(aov_object) %>%
    mutate(term = if_else(term != "Residuals", grouplabel, term))
  tukey_results <- broom::tidy(TukeyHSD(aov_object)) %>%
    mutate(term = grouplabel)

  # multcompLetters is annoying and wants named vectors
  p_values <- tukey_results %>% pull(adj.p.value)
  names(p_values) <- tukey_results %>% pull(comparison)
  letters_results <-  data.frame(as.list(multcompLetters(p_values)$Letters))
  return(letters_results)
}

# works for one
Tuk3(data = dat1, groupvar = "State", var = "var1")
#>   GA MA NY FL
#> 1  a  a  a  a

# you could do this manually but I do it a lot so I have a function
variables_list <- CGPfunctions::cross2_var_vectors(dat1, 1:3, 5:9)

# Make the names nice
outcomes2 <- variables_list$lista
groupings2 <- variables_list$listb
names(groupings2) <- unlist(groupings2)
names(outcomes2) <- paste(unlist(outcomes2), "~", unlist(groupings2))

# get all 15 results and a final map_dfr to make one tibble
map2(.x = outcomes2,
     .y = groupings2,
     .f = ~ Tuk3(dat = dat1,
                 var = tidyselect::all_of(.x),
                 groupvar = tidyselect::all_of(.y))) %>%
       map_dfr(~ rbind(.), .id = "Which_ANOVA")
#>      Which_ANOVA   r2   r1   GA   MA   NY   FL    b    c    d    e    f    g
#> 1  var1 ~ Region    a    a <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 2  var2 ~ Region    a    a <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 3  var3 ~ Region    a    a <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 4  var4 ~ Region    a    a <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 5  var5 ~ Region    a    a <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#> 6   var1 ~ State <NA> <NA>    a    a    a    a <NA> <NA> <NA> <NA> <NA> <NA>
#> 7   var2 ~ State <NA> <NA>    a    a    a    a <NA> <NA> <NA> <NA> <NA> <NA>
#> 8   var3 ~ State <NA> <NA>    a    a    a    a <NA> <NA> <NA> <NA> <NA> <NA>
#> 9   var4 ~ State <NA> <NA>    a    a    a    a <NA> <NA> <NA> <NA> <NA> <NA>
#> 10  var5 ~ State <NA> <NA>    a    b   ab   ab <NA> <NA> <NA> <NA> <NA> <NA>
#> 11    var1 ~ Loc <NA> <NA> <NA> <NA> <NA> <NA>    a    a    a    a    a    a
#> 12    var2 ~ Loc <NA> <NA> <NA> <NA> <NA> <NA>    a    a    a    a    a    a
#> 13    var3 ~ Loc <NA> <NA> <NA> <NA> <NA> <NA>    a    a    a    a    a    a
#> 14    var4 ~ Loc <NA> <NA> <NA> <NA> <NA> <NA>    a    a    a    a    a    a
#> 15    var5 ~ Loc <NA> <NA> <NA> <NA> <NA> <NA>   ab   ab   ab    a   ab    b

I cut off the results


问:
change folder name in url using htaccess
I want change the folder name on fly, using htaccess

this is actual url : http://dailycode.local:8384/home/View/dashboard/

I want to see this url like this : http://dailycode.local:8384/en/v/dashboard/

change the :
"home" -> en
"view" -> v

答:
To 301 redirect all files in the direct to the new directory in .htaccess, try this:

```<code>RewriteEngine On
RewriteRule ^old\ foldr/(.*) /newfolder/$1 [R=301,NC,L]
</code>```

This should redirect all HTML pages, images, you name it.  It should also account for the space too.

You'll want to move all your files to the new folder location so when the redirect happens your end user doesn't receive a 404 error.

Also, you might possibly have to detail the white-space explicitly with '\s'

```<code>RewriteEngine On
RewriteRule ^old\sfoldr/(.*) /newfolder/$1 [R=301,NC,L]
</code>```

Body:
To 301 redirect all files in the direct to the new directory in .htaccess, try this:

RewriteEngine On
RewriteRule ^old\ foldr/(.*) /newfolder/$1 [R=301,NC,L]

This should redirect all HTML pages, images, you name it.  It should also account for the space too.

You'll want to move all your files to the new folder location so when the redirect happens your end user doesn't receive a 404 error.

Also, you might possibly have to detail the white-space explicitly with '\s'

RewriteEngine On
RewriteRule ^old\sfoldr/(.*) /newfolder/$1 [R=301,NC,L]


问:
How to get JSON data from custom end point of WP Rest Api and apply it to Gutenberg custom block component
I want to get JSON object from custom end point that I made and apply it as options for
React Select component.

Registration of my custom end point

```<code>register_rest_route('namespace/v1', 'products', array(
    'methods'  => WP_REST_Server::READABLE,
    'callback' => 'namespace_result_products',
));
</code>```

JSON object that web browser showing is below.
I think it's fine.

```<code>[
  {
    "value": 15,
    "label": "Apple"
  },
  {
    "value": 21,
    "label": "Banana"
  },
  {
    "value": 18,
    "label": "Apple"
  },...
</code>```

Edit function of my gutenberg custom block.

```<code>edit: props => {
const { attributes: { selectedOption }, setAttributes } = props;
const handleSelectChange = ( selectedOption ) => setAttributes( { selectedOption: JSON.stringify( selectedOption ) } );
return (
    <InspectorControls>
        <PanelBody
            title={ 'Products'}
        >
            <PanelRow>
                <Select
                    name='select'
                    value={ JSON.parse( selectedOption ) }
                    onChange={ handleSelectChange }
                    options={[
                        // !!!!!!!!  I want to apply my JSON data here  !!!!!!!!
                    ]}
                    isMulti='true'
                    />
            </PanelRow>
        </PanelBody>
    </InspectorControls>
    )
},
</code>```

By hard coding, this works fine.

```<code><PanelRow>
    <Select
        name='select'
        value={ JSON.parse( selectedOption ) }
        onChange={ handleSelectChange }
        options={[
            { value: '15', label: 'Apple' },
            { value: '21', label: 'Banana' },
            { value: '18', label: 'Apple' },
        ]}
        isMulti='true'
        />
</PanelRow>
</code>```

Thank you in advance.

答:
In your component make an Ajax call in the componentDidMount lifecycle method and set the state. Like this.

```<code>fetch('http://url.com/namespace/v1/products')
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      this.setState({
          options: data
    });

</code>```

This will set the state of your component to have your json from your endpoint inside a property called options.

Then in you return where you hardcoded your data call the state.

```<code><PanelRow>
    <Select
        name='select'
        value={ JSON.parse( selectedOption ) }
        onChange={ handleSelectChange }
        options={this.state.options}
        isMulti='true'
    />
</PanelRow>
</code>```

This will throw an error if it tries to mount the component before the state is set so make sure to wrap you return statement in a check.

```<code>if(this.state.options) {
    return(...) //your components return
} else {
    return <p>Loading</p>
}
</code>```

Body:
I want to get JSON object from custom end point that I made and apply it as options for
React Select component.

Registration of my custom end point

register_rest_route('namespace/v1', 'products', array(
    'methods'  => WP_REST_Server::READABLE,
    'callback' => 'namespace_result_products',
));

JSON object that web browser showing is below.
I think it's fine.

[
  {
    "value": 15,
    "label": "Apple"
  },
  {
    "value": 21,
    "label": "Banana"
  },
  {
    "value": 18,
    "label": "Apple"
  },...

Edit function of my gutenberg custom block.

edit: props => {
const { attributes: { selectedOption }, setAttributes } = props;
const handleSelectChange = ( selectedOption ) => setAttributes( { selectedOption: JSON.stringify( selectedOption ) } );
return (
    <InspectorControls>
        <PanelBody
            title={ 'Products'}
        >
            <PanelRow>
                <Select
                    name='select'
                    value={ JSON.parse( selectedOption ) }
                    onChange={ handleSelectChange }
                    options={[
                        // !!!!!!!!  I want to apply my JSON data here  !!!!!!!!
                    ]}
                    isMulti='true'
                    />
            </PanelRow>
        </PanelBody>
    </InspectorControls>
    )
},

By hard coding, this works fine.

<PanelRow>
    <Select
        name='select'
        value={ JSON.parse( selectedOption ) }
        onChange={ handleSelectChange }
        options={[
            { value: '15', label: 'Apple' },
            { value: '21', label: 'Banana' },
            { value: '18', label: 'Apple' },
        ]}
        isMulti='true'
        />
</PanelRow>

Thank you in advance.

Body:
In your component make an Ajax call in the componentDidMount lifecycle method and set the state. Like this.

fetch('http://url.com/namespace/v1/products')
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      this.setState({
          options: data
    });

This will set the state of your component to have your json from your endpoint inside a property called options.

Then in you return where you hardcoded your data call the state.

<PanelRow>
    <Select
        name='select'
        value={ JSON.parse( selectedOption ) }
        onChange={ handleSelectChange }
        options={this.state.options}
        isMulti='true'
    />
</PanelRow>

This will throw an error if it tries to mount the component before the state is set so make sure to wrap you return statement in a check.

if(this.state.options) {
    return(...) //your components return
} else {
    return <p>Loading</p>
}


问:
Creating a login form in Microsoft Access using macros, without VBA.
I've looked around for ages and I haven't found an answer to my problem so I was hoping someone here could help me.

I am creating a system using Microsoft Access where I have a members table containing a username and password and various other fields such as date of birth, etc.

I want to create a form where users can enter a username and password. By clicking a button on this form, these details will then be checked against the usernames and passwords in the members table. If the details match, a message will be displayed saying they have logged in. If the details are not found in the table, a message saying the details are incorrect will show.

How can I do this without using VBA?

I have started by creating a form called loginform with two text boxes loginusername and loginpassword.

Where should I go from here?

答:
The VBA solution shouldn't be that complicated. A quick and dirty solution:</p>

```<code>Dim Result as Variant

Result=Dlookup("Password","tblMembers","UserName='" & nz(loginusername.value,"") & "'")
If nz(Result,"")<>nz([login password].value,"") Then
  MsgBox "Invalid password"
Else
  MsgBox "Password correct"
End If
</code>```

Body:
The VBA solution shouldn't be that complicated. A quick and dirty solution:

Dim Result as Variant

Result=Dlookup("Password","tblMembers","UserName='" & nz(loginusername.value,"") & "'")
If nz(Result,"")<>nz([login password].value,"") Then
  MsgBox "Invalid password"
Else
  MsgBox "Password correct"
End If


问:
Shopify: Display discount codes in new order email template
I want to display discount codes in new order email notification template, using this code:

```<code>{% for discount in discounts %}
  {{ discount.code }} : {{ discount.savings | money_with_currency }}
{% endfor %}
</code>```

It's displaying the discount amount but not the discount code name/title. It's returning blank even if the discount is manually entered in the back-end when creating an order.

How can I display discount codes no matter where it's entered i.e in admin or checkout?

答:
In notifications you may access to discount_application object as explained here:
https://shopify.dev/docs/themes/liquid/reference/objects/discount-application

So (not tested), something like that might work:

```<code>{% for discount_application in discount_applications %}
  {{ discount_application.title }} : {{ discount_application.value }}
{% endfor %}
</code>```

HTH

Body:
I want to display discount codes in new order email notification template, using this code:

{% for discount in discounts %}
  {{ discount.code }} : {{ discount.savings | money_with_currency }}
{% endfor %}

It's displaying the discount amount but not the discount code name/title. It's returning blank even if the discount is manually entered in the back-end when creating an order.

How can I display discount codes no matter where it's entered i.e in admin or checkout?

Body:
In notifications you may access to discount_application object as explained here:
https://shopify.dev/docs/themes/liquid/reference/objects/discount-application

So (not tested), something like that might work:

{% for discount_application in discount_applications %}
  {{ discount_application.title }} : {{ discount_application.value }}
{% endfor %}

HTH


问:
getting rxjs value in sync, is this an anti pattern?
I often find myself having to just get a value from the store and do something like this which seems like an anti pattern (side effect of remembering r) and wonder if there is a better way.

```<code>    getAssetName(i_page: IPager): string {
        let r = '';
        if (i_page.Player[0].$.src) {
            this.storeSelector.getScene(i_page.Player[0].$.src)
                .take(1)
                .subscribe((v) => {
                    r = v.Player.$.label;
                });
        } else {
            this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .take(1)
                .subscribe((v) => {
                    r = v.resource_name;
                });
        }
        return r;
    }
</code>```

in other words, a better way of getting value 'r' without having to closure it?

now, I am using Angular and am aware I can use 'async' as in

```<code>{{ getAssetName$(element.pager) | async | truncate:[maxStringSize]}}

this.getAssetName$ = this.getAssetName;

 getAssetName(i_page: IPager): Observable<string> {
        if (i_page.Player[0].$.src) {
            return this.storeSelector.getScene(i_page.Player[0].$.src)
                .map((v) => {
                    return v.Player.$.label;
                });
        } else {
            return this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .map((v) => {
                    return v.resource_name;
                });
        }
    }

</code>```

but trying to see if there is a way to do without async template method.
If I use the async without onPush template performance degradation is visible

Thanks,

Sean

答:
I suggest you to use BehaviourSubject, it is a variant of Subject, so you can use it as observable using the method asObservable and get the value in sync with the method getValue.

Example:

public scene$: BehaviourSubject<any> = new BehaviourSubject(null); // needs a first value
public resource$: BehaviourSubject<any> = new BehaviourSubject(null);;

...
scene$.next(newValue); // update current value of scene

...
scene$.asObservable().subscribe(console.log) // async
scene$.getValue() // sync
```

Body:
I often find myself having to just get a value from the store and do something like this which seems like an anti pattern (side effect of remembering r) and wonder if there is a better way.

    getAssetName(i_page: IPager): string {
        let r = '';
        if (i_page.Player[0].$.src) {
            this.storeSelector.getScene(i_page.Player[0].$.src)
                .take(1)
                .subscribe((v) => {
                    r = v.Player.$.label;
                });
        } else {
            this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .take(1)
                .subscribe((v) => {
                    r = v.resource_name;
                });
        }
        return r;
    }

in other words, a better way of getting value 'r' without having to closure it?

now, I am using Angular and am aware I can use 'async' as in

{{ getAssetName$(element.pager) | async | truncate:[maxStringSize]}}

this.getAssetName$ = this.getAssetName;

 getAssetName(i_page: IPager): Observable<string> {
        if (i_page.Player[0].$.src) {
            return this.storeSelector.getScene(i_page.Player[0].$.src)
                .map((v) => {
                    return v.Player.$.label;
                });
        } else {
            return this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .map((v) => {
                    return v.resource_name;
                });
        }
    }

but trying to see if there is a way to do without async template method.
If I use the async without onPush template performance degradation is visible

Thanks,

Sean


问:
Drop rows in pandas based on the same key
How can I drop rows where column A is the key, and any rows for that key contain both "foo" and "moo" in column C

df_before:

```<code>"cat"   |"waverly way"|"foo"|10.0
"cat"   |"smokey st"  |"moo"|9.7
"rabbit"|"rapid ave"  |"foo"|6.6
"rabbit"|"far blvd"   |"too"|3.2
</code>```

df_after:

```<code>"rabbit"|"rapid ave"  |"foo"|6.6
"rabbit"|"far blvd"   |"too"|3.2
</code>```

答:
You can do it this way:

```<code>df.columns = ['A', 'B', 'C', 'D']
</code>```

df:

```<code>        A            B    C     D
0     cat  waverly way  foo  10.0
1     cat    smokey st  moo   9.7
2  rabbit    rapid ave  foo   6.6
3  rabbit     far blvd  too   3.2
</code>```

.

```<code>filter = ['foo,moo']
# used transform to concat all the values in column 'C' for a given 'A'
df['C'] = df[['A', 'B', 'C', 'D']].groupby(by=['A'])['C'].transform(lambda x: ','.join(x))
</code>```

Modified df:

```<code>        A            B        C     D
0     cat  waverly way  foo,moo  10.0
1     cat    smokey st  foo,moo   9.7
2  rabbit    rapid ave  foo,too   6.6
3  rabbit     far blvd  foo,too   3.2
</code>```

.

```<code># applied negative mask to filter values with foo,moo in 'C'
df1 = df.loc[~df['C'].isin(filter)].reset_index(drop=True)

print(df1)
</code>```

Output:

```<code>        A          B        C    D
0  rabbit  rapid ave  foo,too  6.6
1  rabbit   far blvd  foo,too  3.2
</code>```

Body:
How can I drop rows where column A is the key, and any rows for that key contain both "foo" and "moo" in column C

df_before:

"cat"   |"waverly way"|"foo"|10.0
"cat"   |"smokey st"  |"moo"|9.7
"rabbit"|"rapid ave"  |"foo"|6.6
"rabbit"|"far blvd"   |"too"|3.2

df_after:

"rabbit"|"rapid ave"  |"foo"|6.6
"rabbit"|"far blvd"   |"too"|3.2

Body:
You can do it this way:

df.columns = ['A', 'B', 'C', 'D']

df:

        A            B    C     D
0     cat  waverly way  foo  10.0
1     cat    smokey st  moo   9.7
2  rabbit    rapid ave  foo   6.6
3  rabbit     far blvd  too   3.2

.

filter = ['foo,moo']
# used transform to concat all the values in column 'C' for a given 'A'
df['C'] = df[['A', 'B', 'C', 'D']].groupby(by=['A'])['C'].transform(lambda x: ','.join(x))

Modified df:

        A            B        C     D
0     cat  waverly way  foo,moo  10.0
1     cat    smokey st  foo,moo   9.7
2  rabbit    rapid ave  foo,too   6.6
3  rabbit     far blvd  foo,too   3.2

.

# applied negative mask to filter values with foo,moo in 'C'
df1 = df.loc[~df['C'].isin(filter)].reset_index(drop=True)

print(df1)

Output:

        A          B        C    D
0  rabbit  rapid ave  foo,too  6.6
1  rabbit   far blvd  foo,too  3.2


问:
Angular - How to get data from subscribed service few times and not overwrite previous results
I have a service which has following method:

room-service.ts

@Injectable()
export class RoomService {
  private readonly _equipment: BehaviorSubject<EquipmentDto[]> = new BehaviorSubject([]);
  public equipment$ = this._equipment.asObservable();

  getEquipmentForRoom(roomId: number) {
    this.restService.getEquipmentForRoom(roomId).subscribe(res => {
      this._equipment.next(res);
    });
  }
```

<p>room-component.ts:</p>

<pre class="lang-js prettyprint-override"><code>@Component()
export class RoomsComponent implements OnInit {
  @Input() room: RoomEntity;
  equipment$: Observable < EquipmentDto[] > ;
  equipmentList: Array < EquipmentDto > ;

  constructor(private equipmentService: EquipmentService) {}

  ngOnInit() {
      this.equipment$ = this.equipmentService.equipment$;
      this.equipmentService.getEquipmentForRoom(this.room.id);

      this.equipment$.subscribe(items => {
        this.equipmentList = items;
      });
</code>```

room-component.html

```

Now I have a parent component which contains multiple Room Components (those are added programmatically based on the amount of rooms). Anyway, list of equipment is the same for each of the rooms. It looks like once subscribed, the data in first components is overwritten by the component created as the last one.

My question is, how can I get a proper data for each of the rooms using the observable from my service?

答:
You can use this approach with single BehaviorSubject only when your data is the only source of this data.

Instead, you can change your getEquipmentForRoom(roomId: number) like this:

```<code>getEquipmentForRoom(roomId: number) {
    return this.restService.getEquipmentForRoom(roomId);
}
</code>```

And then subscribe to it in the compoment:

```<code>this.equipmentService.getEquipmentForRoom(this.room.id).subscribe(items => {
  this.equipmentList = items;
});
</code>```

And I agree with Alexander, this component should be dumb as possible.

Body:
I have a service which has following method:

room-service.ts

@Injectable()
export class RoomService {
  private readonly _equipment: BehaviorSubject<EquipmentDto[]> = new BehaviorSubject([]);
  public equipment$ = this._equipment.asObservable();

  getEquipmentForRoom(roomId: number) {
    this.restService.getEquipmentForRoom(roomId).subscribe(res => {
      this._equipment.next(res);
    });
  }

room-component.ts:

@Component()
export class RoomsComponent implements OnInit {
  @Input() room: RoomEntity;
  equipment$: Observable < EquipmentDto[] > ;
  equipmentList: Array < EquipmentDto > ;

  constructor(private equipmentService: EquipmentService) {}

  ngOnInit() {
      this.equipment$ = this.equipmentService.equipment$;
      this.equipmentService.getEquipmentForRoom(this.room.id);

      this.equipment$.subscribe(items => {
        this.equipmentList = items;
      });

room-component.html

Now I have a parent component which contains multiple Room Components (those are added programmatically based on the amount of rooms). Anyway, list of equipment is the same for each of the rooms. It looks like once subscribed, the data in first components is overwritten by the component created as the last one.

My question is, how can I get a proper data for each of the rooms using the observable from my service?

Body:
You can use this approach with single BehaviorSubject only when your data is the only source of this data.

Instead, you can change your getEquipmentForRoom(roomId: number) like this:

getEquipmentForRoom(roomId: number) {
    return this.restService.getEquipmentForRoom(roomId);
}

And then subscribe to it in the compoment:

this.equipmentService.getEquipmentForRoom(this.room.id).subscribe(items => {
  this.equipmentList = items;
});

And I agree with Alexander, this component should be dumb as possible.


问:
How to add properties at runtime to JSON (C#)
Note: Im working with  System.Text.Json package
Below is JSON I am getting from a database. I have to go through each of the keys in the JSON and check if there is a period (.) in the key name; if so, I need to add a property required with the value of true in the JSON in order to provide runtime validation:

```<code>validate:{"required", true}
</code>```

Here is my JSON:

```<code>{
    "display": "wizard",
    "settings": {},
    "components": [{
        "title": "Event Information",
        "label": "Event Information",
        "type": "panel",
        "key": "EventInformation",
        "components": [{
            "label": "Row1Columns",
            "columns": [{
                "components": [{
                    "label": "Event Date",
                    "format": "dd/MM/yyyy hh:mm a",
                    "tableView": false,
                    "datePicker": {
                        "disableWeekends": false,
                        "disableWeekdays": false
                    },
                    "validate": {
                        "unique": true
                    },
                    "key": "Event.EventDate",
                    "type": "datetime",
                    "input": true,
                    "suffix": "<i ref=\"icon\" class=\"fa fa-calendar\" style=\"\"></i>",
                    "widget": {
                        "type": "calendar",
                        "displayInTimezone": "viewer",
                        "language": "en",
                        "useLocaleSettings": false,
                        "allowInput": true,
                        "mode": "single",
                        "enableTime": true,
                        "noCalendar": false,
                        "format": "dd/MM/yyyy hh:mm a",
                        "hourIncrement": 1,
                        "minuteIncrement": 1,
                        "time_24hr": false,
                        "minDate": null,
                        "disableWeekends": false,
                        "disableWeekdays": false,
                        "maxDate": null
                    }
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }, {
                "components": [{
                    "label": "Duration (minutes)",
                    "mask": false,
                    "spellcheck": true,
                    "tableView": false,
                    "delimiter": false,
                    "requireDecimal": false,
                    "inputFormat": "plain",
                    "key": "Event.Duration",
                    "type": "number",
                    "input": true
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }],
            "tableView": false,
            "key": "row1Columns",
            "type": "columns",
            "input": false
        }, {
            "label": "Row2Columns",
            "columns": [{
                "components": [{
                    "label": "Event Category",
                    "widget": "choicesjs",
                    "tableView": true,
                    "dataSrc": "custom",
                    "data": {
                        "custom": "values = getEventCategoryValues()"
                    },
                    "valueProperty": "AgencyEventCategoryId",
                    "template": "<span>{{ item.text }}</span>",
                    "selectThreshold": 0.3,
                    "validate": {
                        "required": true
                    },
                    "key": "Event.AgencyEventCategoryId",
                    "type": "select",
                    "indexeddb": {
                        "filter": {}
                    },
                    "input": true
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }, {
                "components": [{
                    "label": "Attendance",
                    "widget": "choicesjs",
                    "tableView": true,
                    "multiple": false,
                    "dataSrc": "custom",
                    "data": {
                        "custom": "values = getAttendanceValues()"
                    },
                    "valueProperty": "AgencyEventAttendanceId",
                    "template": "<span>{{ item.text }}</span>",
                    "selectThreshold": 0.3,
                    "validate": {
                        "required": true,
                    },
                    "key": "Event.AgencyEventAttendanceId",
                    "type": "select",
                    "indexeddb": {
                        "filter": {}
                    },
                    "input": true
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }],
            "tableView": false,
            "key": "row2Columns",
            "type": "columns",
            "input": false
        }, {
            "label": "Event Options",
            "widget": "choicesjs",
            "tableView": true,
            "multiple": true,
            "dataSrc": "custom",
            "data": {
                "custom": "values = getEventManagerValues(data.Event.AgencyEventCategoryId)"
            },
            "template": "<span>{{ item.text }}</span>",
            "refreshOn": "Event.AgencyEventCategoryId",
            "clearOnRefresh": true,
            "selectThreshold": 0.3,
            "calculateServer": false,
            "validate": {
                "required": true,
                "multiple": true
            },
            "key": "Event.EventDetail",
            "type": "select",
            "indexeddb": {
                "filter": {}
            },
            "input": true
        }, {
            "label": "Casenote",
            "wysiwyg": true,
            "autoExpand": true,
            "spellcheck": true,
            "tableView": true,
            "calculateServer": false,
            "key": "Event.EventCasenote[0].Casenote",
            "type": "textarea",
            "input": true
        }],
        "input": false,
        "tableView": false,
        "breadcrumbClickable": true,
        "buttonSettings": {
            "previous": true,
            "cancel": true,
            "next": true
        },
        "collapsible": false
    }]
}
</code>```

答:
It was interesting task for me, so this is what i have written

```<code>class Program
{
    static void Main(string[] args)
    {
        string jsonFilePath = @"test.json"; //path to your json
        string json = File.ReadAllText(jsonFilePath);
        var data = JObject.Parse(json);
        CheckJson(data);
        Console.ReadLine();
    }

    static void CheckJson(JToken value)
    {
        if (value.Values().Count() != 0) //if more than 0 - so value is object or array and we have to call this method for each property
        {
            foreach (var item in value.Values().ToList())
            {
                CheckJson(item);
            }
        }
        else if (true) //else - we have exactly value of key, which we can check, for example if . exists or additional checks
        {
            if (value.Parent.Parent is JObject jObject && jObject["validate"] == null) //check if above "required" property exists
            {
                jObject.Add("validate", JObject.FromObject(new { required = true })); //add required property
            }
        }

    }
}
</code>```

This code will add in each object property "required" if it is not exists.
All you need - just add Validation method and call it in if block.
And better to add additional validation that won't continue checking all properties if "required" property exists

Body:
Note: Im working with  System.Text.Json package
Below is JSON I am getting from a database. I have to go through each of the keys in the JSON and check if there is a period (.) in the key name; if so, I need to add a property required with the value of true in the JSON in order to provide runtime validation:

validate:{"required", true}

Here is my JSON:

{
    "display": "wizard",
    "settings": {},
    "components": [{
        "title": "Event Information",
        "label": "Event Information",
        "type": "panel",
        "key": "EventInformation",
        "components": [{
            "label": "Row1Columns",
            "columns": [{
                "components": [{
                    "label": "Event Date",
                    "format": "dd/MM/yyyy hh:mm a",
                    "tableView": false,
                    "datePicker": {
                        "disableWeekends": false,
                        "disableWeekdays": false
                    },
                    "validate": {
                        "unique": true
                    },
                    "key": "Event.EventDate",
                    "type": "datetime",
                    "input": true,
                    "suffix": "",
                    "widget": {
                        "type": "calendar",
                        "displayInTimezone": "viewer",
                        "language": "en",
                        "useLocaleSettings": false,
                        "allowInput": true,
                        "mode": "single",
                        "enableTime": true,
                        "noCalendar": false,
                        "format": "dd/MM/yyyy hh:mm a",
                        "hourIncrement": 1,
                        "minuteIncrement": 1,
                        "time_24hr": false,
                        "minDate": null,
                        "disableWeekends": false,
                        "disableWeekdays": false,
                        "maxDate": null
                    }
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }, {
                "components": [{
                    "label": "Duration (minutes)",
                    "mask": false,
                    "spellcheck": true,
                    "tableView": false,
                    "delimiter": false,
                    "requireDecimal": false,
                    "inputFormat": "plain",
                    "key": "Event.Duration",
                    "type": "number",
                    "input": true
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }],
            "tableView": false,
            "key": "row1Columns",
            "type": "columns",
            "input": false
        }, {
            "label": "Row2Columns",
            "columns": [{
                "components": [{
                    "label": "Event Category",
                    "widget": "choicesjs",
                    "tableView": true,
                    "dataSrc": "custom",
                    "data": {
                        "custom": "values = getEventCategoryValues()"
                    },
                    "valueProperty": "AgencyEventCategoryId",
                    "template": "{{ item.text }}",
                    "selectThreshold": 0.3,
                    "validate": {
                        "required": true
                    },
                    "key": "Event.AgencyEventCategoryId",
                    "type": "select",
                    "indexeddb": {
                        "filter": {}
                    },
                    "input": true
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }, {
                "components": [{
                    "label": "Attendance",
                    "widget": "choicesjs",
                    "tableView": true,
                    "multiple": false,
                    "dataSrc": "custom",
                    "data": {
                        "custom": "values = getAttendanceValues()"
                    },
                    "valueProperty": "AgencyEventAttendanceId",
                    "template": "{{ item.text }}",
                    "selectThreshold": 0.3,
                    "validate": {
                        "required": true,
                    },
                    "key": "Event.AgencyEventAttendanceId",
                    "type": "select",
                    "indexeddb": {
                        "filter": {}
                    },
                    "input": true
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }],
            "tableView": false,
            "key": "row2Columns",
            "type": "columns",
            "input": false
        }, {
            "label": "Event Options",
            "widget": "choicesjs",
            "tableView": true,
            "multiple": true,
            "dataSrc": "custom",
            "data": {
                "custom": "values = getEventManagerValues(data.Event.AgencyEventCategoryId)"
            },
            "template": "{{ item.text }}",
            "refreshOn": "Event.AgencyEventCategoryId",
            "clearOnRefresh": true,
            "selectThreshold": 0.3,
            "calculateServer": false,
            "validate": {
                "required": true,
                "multiple": true
            },
            "key": "Event.EventDetail",
            "type": "select",
            "indexeddb": {
                "filter": {}
            },
            "input": true
        }, {
            "label": "Casenote",
            "wysiwyg": true,
            "autoExpand": true,
            "spellcheck": true,
            "tableView": true,
            "calculateServer": false,
            "key": "Event.EventCasenote[0].Casenote",
            "type": "textarea",
            "input": true
        }],
        "input": false,
        "tableView": false,
        "breadcrumbClickable": true,
        "buttonSettings": {
            "previous": true,
            "cancel": true,
            "next": true
        },
        "collapsible": false
    }]
}

Body:
It was interesting task for me, so this is what i have written

class Program
{
    static void Main(string[] args)
    {
        string jsonFilePath = @"test.json"; //path to your json
        string json = File.ReadAllText(jsonFilePath);
        var data = JObject.Parse(json);
        CheckJson(data);
        Console.ReadLine();
    }

    static void CheckJson(JToken value)
    {
        if (value.Values().Count() != 0) //if more than 0 - so value is object or array and we have to call this method for each property
        {
            foreach (var item in value.Values().ToList())
            {
                CheckJson(item);
            }
        }
        else if (true) //else - we have exactly value of key, which we can check, for example if . exists or additional checks
        {
            if (value.Parent.Parent is JObject jObject && jObject["validate"] == null) //check if above "required" property exists
            {
                jObject.Add("validate", JObject.FromObject(new { required = true })); //add required property
            }
        }

    }
}

This code will add in each object property "required" if it is not exists.
All you need - just add Validation method and call it in if block.
And better to add additional validation that won't continue checking all properties if "required" property exists


问:
Why can't Bundler locate this gem?
Why can't bundler locate the Mechanize gem?

The following is in my Rails project's Gemfile:

```<code>gem 'mechanize', :git => 'git://github.com/tenderlove/mechanize.git'
</code>```

Running bundle install throws the following error:

```<code>Updating git://github.com/tenderlove/mechanize.git
Fetching source index for http://rubygems.org/
Could not find gem 'mechanize (>= 0)' in git://github.com/tenderlove/mechanize.git (at master).
Source does not contain any versions of 'mechanize (>= 0)'
</code>```

I arrived at this problem after forking the project to make some small changes, but was not able to get bundler to use the github location nor a local path. Why is it that it cannot locate the gem?

If I remove all instructions and simply do gem 'mechanize' then it works flawlessly.

Versions: Bundler 1.0.14 + Rails 3.1 Release Canditate + Ruby 1.8.7 (via RVM) + Debian 5

答:
I have seen older version of bundler having issues with git:// like urls.

Have you tried updating bundler; or replacing git:// with http:// ?

Title: Why can't Bundler locate this gem?

Body:
Why can't bundler locate the Mechanize gem?

The following is in my Rails project's Gemfile:

gem 'mechanize', :git => 'git://github.com/tenderlove/mechanize.git'

Running bundle install throws the following error:

Updating git://github.com/tenderlove/mechanize.git
Fetching source index for http://rubygems.org/
Could not find gem 'mechanize (>= 0)' in git://github.com/tenderlove/mechanize.git (at master).
Source does not contain any versions of 'mechanize (>= 0)'

I arrived at this problem after forking the project to make some small changes, but was not able to get bundler to use the github location nor a local path. Why is it that it cannot locate the gem?

If I remove all instructions and simply do gem 'mechanize' then it works flawlessly.

Versions: Bundler 1.0.14 + Rails 3.1 Release Canditate + Ruby 1.8.7 (via RVM) + Debian 5


问:
Removing numbers from a given string
I am trying to get rid of any numbers in a string.

However, when I run my program the number is removed, but other parts of the string are removed as well.

```<code>string = 'My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?'

def num_remover(words):
    t = words.split()
    d = [e for e in t if e.isalpha()]
    a = " ".join(d)
    return a

print(bluh_remover(string))
</code>```

output:

My name is I am 22 years The wall is and the floor is The weather is but it is

答:
NEVERMIND: I figured it out.

Apart from calling out the wrong function haha. I was able to think simply and just replace the number with nothing.

Title: Removing numbers from a given string

Body:
I am trying to get rid of any numbers in a string.

However, when I run my program the number is removed, but other parts of the string are removed as well.

string = 'My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?'

def num_remover(words):
    t = words.split()
    d = [e for e in t if e.isalpha()]
    a = " ".join(d)
    return a

print(bluh_remover(string))

output:

My name is I am 22 years The wall is and the floor is The weather is but it is


问:
Python using array twice results in wrong return value
Okay, so I am working on a project where there is a website, that can calculate how much profit you can make from each item from a video game!

I ran into a few issues down the road but managed to solve a few of them, both myself and got help here on StackOverflow. Now the issue I am at right now, I cant seem to figure out.

I am trying to get a "total cost" of products, which I do by doing this (code: 1):

```<code>total = []
for x in range(len(buy)):
    total.append(amount[x] * sell[x])
</code>```

I get 'amount' from this code right here(code: 2):

```<code>amount = []
for x in range(len(buy)):
   amount.append(userInput / sell[x])
</code>```

Now the issue is that whenever I try to get the total cost, it pretty much just straight up copies whatever the user have put in, and I am guessing it does so because of the -

```<code>amount.append(userInput / sell[x])
</code>```

When I am trying to reach that "amount" from an different for loop, it causes issues? I might be completely wrong here, and that's why I need your help! :)

Here is the full code of the page:

```<code>@app.route('/bflipper', methods=['POST', 'GET'])
def bFlipper():
    product_name = []
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2').json()
    for x in productNames:
        product_name.append(f["products"][x]["product_id"])
    if request.method == 'POST':
        userInput = request.form['coins']
        userInput = int(userInput)
        sell = [product['sell_summary'][0]['pricePerUnit']
                for product in f['products'].values() if product['sell_summary']]

        buy = [product['buy_summary'][0]['pricePerUnit']
               for product in f['products'].values() if product['buy_summary']]

        amount = []
        for x in range(len(buy)):
            totAmount = userInput / sell[x]
            amount.append(totAmount)

        total = []
        for x in range(len(buy)):
            total.append(amount[x] * sell[x])

        return render_template("flipper.html", userInput=userInput, product_name=product_name, amount=amount, total=total, sell=sell, buy=buy)
    else:
        return render_template("flipper.html", product_name=product_name)
</code>```

Here is how it looks on the page:

I wrote in '123321' as an 'userInput', and you can see on 'total cost' that it pretty much copied what I put in, so somewhere in 'code:1 & code:2' it is causing issues!

Thanks!
- Simon

答:
total ends up as copies of userInput because that's exactly what you programmed it to do. Walking through this: at each index, what is amount[x]? Well, you set it equal to userInput / sell[x]. So, what will each of total[x] be? total[x] == amount[x] * sell[x] == (userInput / sell[x]) * sell[x] == userInput (roughly, with some floating point imprecision visible in your screenshot). So, all of the entries in total end up as copies of userInput like you observed.

In conclusion, I'm not sure that "using the array twice" is necessarily the issue here. I don't know what your code is supposed to do, but this is why it's doing what it is.

Body:
Okay, so I am working on a project where there is a website, that can calculate how much profit you can make from each item from a video game!

I ran into a few issues down the road but managed to solve a few of them, both myself and got help here on StackOverflow. Now the issue I am at right now, I cant seem to figure out.

I am trying to get a "total cost" of products, which I do by doing this (code: 1):

total = []
for x in range(len(buy)):
    total.append(amount[x] * sell[x])

I get 'amount' from this code right here(code: 2):

amount = []
for x in range(len(buy)):
   amount.append(userInput / sell[x])

Now the issue is that whenever I try to get the total cost, it pretty much just straight up copies whatever the user have put in, and I am guessing it does so because of the -

amount.append(userInput / sell[x])

When I am trying to reach that "amount" from an different for loop, it causes issues? I might be completely wrong here, and that's why I need your help! :)

Here is the full code of the page:

@app.route('/bflipper', methods=['POST', 'GET'])
def bFlipper():
    product_name = []
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2').json()
    for x in productNames:
        product_name.append(f["products"][x]["product_id"])
    if request.method == 'POST':
        userInput = request.form['coins']
        userInput = int(userInput)
        sell = [product['sell_summary'][0]['pricePerUnit']
                for product in f['products'].values() if product['sell_summary']]

        buy = [product['buy_summary'][0]['pricePerUnit']
               for product in f['products'].values() if product['buy_summary']]

        amount = []
        for x in range(len(buy)):
            totAmount = userInput / sell[x]
            amount.append(totAmount)

        total = []
        for x in range(len(buy)):
            total.append(amount[x] * sell[x])

        return render_template("flipper.html", userInput=userInput, product_name=product_name, amount=amount, total=total, sell=sell, buy=buy)
    else:
        return render_template("flipper.html", product_name=product_name)

Here is how it looks on the page:

I wrote in '123321' as an 'userInput', and you can see on 'total cost' that it pretty much copied what I put in, so somewhere in 'code:1 & code:2' it is causing issues!

Thanks!
- Simon


问:
Android 3.0, Widget Preview
In Honeycomb some of the System apps have a "preview" of the widget when you click the "add" options on the home screen.

How do I go about adding a thumbnail/preview of my widget to my application so the user can get a feel for what it looks like when adding it in Honeycomb?

答:
If you run the android emulator against the Honeycomb sdk, you should see an app called Widget Preview, which will allow you to pick the widget to take a preview of (you will have to install your widget on the emulated device).  I think you can also build it yourself if you have the source checked out (it's under development/apps/WidgetPreview).

http://developer.android.com/guide/topics/appwidgets/index.html#preview

Title: Android 3.0, Widget Preview


问:
php file_put_contents not creating file from url
I'm working with two different APIs trying to transfer documents from one services to another. So far, the API has been kind of clunky to work with, but I was getting it to work, until now with the documents problem. Here is what I have to do:

1. I need to get the url of the document from the one service (which I have done).

2. Download it to my own servers to a folder called filesToUpload (which I have created).

3. Transfer it to the other services (which I have done with a document already on my servers.)

So as you can see, the problem isn't transferring it to the other service, the real problem is downloading it to my own servers. Here is what I have tried:(the $doc['url'] is the response from the one server, and I have confirmed that the url supplied is an existent document)

```<code>$fileToPost = str_replace(" ", "+", $doc["url"]);
$fileName = strchr($fileToPost, "-");
$fileName = substr($fileName, 1);
file_put_contents("/api/ricochet-clean/filesToUpload/$fileName", fopen($fileToPost, 'r'));
</code>```

Here is my error message:

```<code>file_put_contents(/api/ricochet-clean/filesToUpload/uploaded-leads.s3.amazonaws.com/219-2018-06-10-10-19-04-Assign6.docx): failed to open stream: No such file or directory in <b>/Applications/XAMPP/xamppfiles/htdocs/SoftwareAPIs/api/ricochet-clean/index.php</b> on line <b>191</b><br />
</code>```

In the file_put_contents() function call, I have tried the /api/ricochet-clean/filesToUpload/$fileName absolute path and I have also tried a relative path of filesToUpload/$fileName.

I saw this question: file_put_contents: Failed to open stream, no such file or directory

The answer to this was the developer hadn't created the directory he was trying to download the file to, that isn't my problem because I've confirmed I created the directory AND it is spelled the same both places.

What am I missing here?

答:
The file you wish to write is

/api/ricochet-clean/filesToUpload/$fileName

but the file being written is

/api/ricochet-clean/filesToUpload/uploaded-leads.s3.amazonaws.com/219-2018-06-10-10-19-04-Assign6.docx

Assuming the directory uploaded-leads.s3.amazonaws.com does not exist, you will need to create it, or write code to create it.

The quotation marks you're using here are absolutely fine.

Body:
I'm working with two different APIs trying to transfer documents from one services to another. So far, the API has been kind of clunky to work with, but I was getting it to work, until now with the documents problem. Here is what I have to do:

1. I need to get the url of the document from the one service (which I have done).

2. Download it to my own servers to a folder called filesToUpload (which I have created).

3. Transfer it to the other services (which I have done with a document already on my servers.)

So as you can see, the problem isn't transferring it to the other service, the real problem is downloading it to my own servers. Here is what I have tried:(the $doc['url'] is the response from the one server, and I have confirmed that the url supplied is an existent document)

$fileToPost = str_replace(" ", "+", $doc["url"]);
$fileName = strchr($fileToPost, "-");
$fileName = substr($fileName, 1);
file_put_contents("/api/ricochet-clean/filesToUpload/$fileName", fopen($fileToPost, 'r'));

Here is my error message:

file_put_contents(/api/ricochet-clean/filesToUpload/uploaded-leads.s3.amazonaws.com/219-2018-06-10-10-19-04-Assign6.docx): failed to open stream: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/SoftwareAPIs/api/ricochet-clean/index.php on line 191

In the file_put_contents() function call, I have tried the /api/ricochet-clean/filesToUpload/$fileName absolute path and I have also tried a relative path of filesToUpload/$fileName.

I saw this question: file_put_contents: Failed to open stream, no such file or directory

The answer to this was the developer hadn't created the directory he was trying to download the file to, that isn't my problem because I've confirmed I created the directory AND it is spelled the same both places.

What am I missing here?


问:
What is happening when require("http").Server() is evaluated with an Express app as its argument?
I was reading the Socket.io Chat Demo here: http://socket.io/get-started/chat/
and I got confused when looking at their require statements.

```<code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendfile('index.html');
});

io.on('connection', function(socket){
console.log('a user connected');
});

http.listen(3000, function(){
console.log('listening on *:3000');
});
</code>```

Am I correct in thinking that require("express") produces an executable Express function (with all of the necessary functions and fields that go with that), and that require("http").Server(app) creates a http.Server object with all of its fields and functions.

If so, I am confused because Express creates a server when we call the .listen function so it seems redundant and backwards to pass an Express app to an http module server.

So, my question is, what is really happening here?

答:
```<code>const app = express();
let server = require('http').Server(app);
server.listen(3000);
</code>```

This makes the server listening to the port we provide.

```<code>const app = express();
let server = require('http').createServer(app);
server.listen(3000);
</code>```

So Server and createServer are the same according to the node.js HTTP library source code.

Ref : nodejs/lib/http.js

```<code>exports.Server = Server;

exports.createServer = function(requestListener) {
  return new Server(requestListener);
</code>```

};

Body:
I was reading the Socket.io Chat Demo here: http://socket.io/get-started/chat/
and I got confused when looking at their require statements.

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendfile('index.html');
});

io.on('connection', function(socket){
console.log('a user connected');
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

Am I correct in thinking that require("express") produces an executable Express function (with all of the necessary functions and fields that go with that), and that require("http").Server(app) creates a http.Server object with all of its fields and functions.

If so, I am confused because Express creates a server when we call the .listen function so it seems redundant and backwards to pass an Express app to an http module server.

So, my question is, what is really happening here?

Body:
const app = express();
let server = require('http').Server(app);
server.listen(3000);

This makes the server listening to the port we provide.

const app = express();
let server = require('http').createServer(app);
server.listen(3000);

So Server and createServer are the same according to the node.js HTTP library source code.

Ref : nodejs/lib/http.js

exports.Server = Server;

exports.createServer = function(requestListener) {
  return new Server(requestListener);

};