问:
How can I keep the discord bot active without pycharm?
when you make a discord bot with javascript

```<code>"echo off"
color 0f
cls
:a
node bot.js
goto a"
</code>```

When I put this command in the folder and run it as .bat, it could run without the need for a client. Do you know how I can do this with python?

答:
```<code>"echo off"
color 0f
cls
:a
python bot.py
goto a"
</code>```

Do you mean something like this?

Notice that the command python doesn't work for all the operative systems, you may need to use some aliases like py, and in case you have more than one version installed you may need to specify py -3.

Anyway you can "keep the discord bot active" running it from the IDLE Shell or from the command prompt of your operative system.

Body:
when you make a discord bot with javascript

"echo off"
color 0f
cls
:a
node bot.js
goto a"

When I put this command in the folder and run it as .bat, it could run without the need for a client. Do you know how I can do this with python?

Body:
"echo off"
color 0f
cls
:a
python bot.py
goto a"

Do you mean something like this?

Notice that the command python doesn't work for all the operative systems, you may need to use some aliases like py, and in case you have more than one version installed you may need to specify py -3.

Anyway you can "keep the discord bot active" running it from the IDLE Shell or from the command prompt of your operative system.


来源: stackexchange

问:
styled component multiple override css no effect?
I have a React component styled using styled-components, but can it be apply style again? My button is a react component

```<code>import Button from "./Button";
</code>```

Then somewhere else I add margin-top, it don't apply the style.

```<code>//margin-top has no effect?
const ButtonStyled = styled(Button)`
  margin-top: 100px;
`;

export default function App() {
  return <ButtonStyled>My button</ButtonStyled>;
}
</code>```

Demo here
https://codesandbox.io/s/goofy-montalcini-l47kp?file=/src/App.js:144-150

答:
In order for the styled function to work, the component must accept a className prop. Now, when you define Button:

```<code>const Button = ({ children }, props) => {
  return <ButtonStyled {...props}>{children}</ButtonStyled>;
};
</code>```

You try to spread the props to ButtonStyled, which is good, you just mis typed the place of props. Try this:

```<code>const Button = ({ children, ...props }) => {
  return <ButtonStyled {...props}>{children}</ButtonStyled>;
};
</code>```

This way, the className prop (which is applied by styled()) will be passed onto StyledButton.

ContentLicense: CC BY-SA 4.0

Body:
I have a React component styled using styled-components, but can it be apply style again? My button is a react component

import Button from "./Button";

Then somewhere else I add margin-top, it don't apply the style.

//margin-top has no effect?
const ButtonStyled = styled(Button)`
  margin-top: 100px;
`;

export default function App() {
  return <ButtonStyled>My button</ButtonStyled>;
}

Demo here
https://codesandbox.io/s/goofy-montalcini-l47kp?file=/src/App.js:144-150

Body:
In order for the styled function to work, the component must accept a className prop. Now, when you define Button:

const Button = ({ children }, props) => {
  return <ButtonStyled {...props}>{children}</ButtonStyled>;
};

You try to spread the props to ButtonStyled, which is good, you just mis typed the place of props. Try this:

const Button = ({ children, ...props }) => {
  return <ButtonStyled {...props}>{children}</ButtonStyled>;
};

This way, the className prop (which is applied by styled()) will be passed onto StyledButton.


问:
Unix command for find updated and newly added files/folder
I need to find out the listed for files or folders that has been added/updated in the file system path (/home/user01/myapps/) between two different time (scripts starting and ending time).

I am running a Shell scripts to do the updating/adding new files to the resource path /home/user01/myapps/ from different source. So, at the end of scripts I want to know the list of files or folders that has been added or updated.

I have the below command

find /opt/app/tds/tdsbatch -mtime -1

But, I am not sure about the script running time.

Any help indeed!

答:
To record times at whatever desired moment:

```<code># record the current time in seconds on script startup
start_time=$(date +%s)
...
# do whatever you like
...
# to get the runtime in secods - if you like:
runtime=$(($(date +%s) - start_time))
# to get the runtime in minutes (minutes are useful for -mmin find param)
runtime=$((($(date +%s) - start_time) / 60))
...
# to record the finish time in seconds:
end_time=$(date +%s)
</code>```

and now find according to your needs. something like

```<code>find /path \( -mmin $((-($(date +%s) - start_time) / 60)) \
  -a $((($(date +%s) - end_time) / 60)) \)
</code>```

the first -mmin argument specifies modifed after (current time - script start time) minutes back from now

the second -mmin argument specifies modified before (current time - script end time) minutes back from now

both of them are in conjunction with -a parameter and enclosed in prefixed brackets

You could probably do with these. Otherwise I would need more clarification about your needs.

ContentLicense: CC BY-SA 3.0

Body:
To record times at whatever desired moment:

# record the current time in seconds on script startup
start_time=$(date +%s)
...
# do whatever you like
...
# to get the runtime in secods - if you like:
runtime=$(($(date +%s) - start_time))
# to get the runtime in minutes (minutes are useful for -mmin find param)
runtime=$((($(date +%s) - start_time) / 60))
...
# to record the finish time in seconds:
end_time=$(date +%s)

and now find according to your needs. something like

find /path \( -mmin $((-($(date +%s) - start_time) / 60)) \
  -a $((($(date +%s) - end_time) / 60)) \)

the first -mmin argument specifies modifed after (current time - script start time) minutes back from now

the second -mmin argument specifies modified before (current time - script end time) minutes back from now

both of them are in conjunction with -a parameter and enclosed in prefixed brackets

You could probably do with these. Otherwise I would need more clarification about your needs.


问:
An error occurred while installing mysql2 (0.4.8), and Bundler cannot continue
How can I fix this error in ruby on rail.

```<code>source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.2'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
gem 'mysql 2', '0.4.8'
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'spree', '~> 3.2.1'
gem 'spree_auth_devise', github: 'spree/spree_auth_devise'
gem 'spree_gateway', github: 'spree/spree_gateway'
gem 'spree_i18n', github: 'spree-contrib/spree_i18n', branch: 'master'
</code>```

I ran the 'bundle install' and this error occurred.
So to fix the bug of the project, I ran 'gem install mysql2 '0.4.8'' command in console but I can't fix it.

This ruby on rails uses Spree framework.

edit:

```<code>Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/admin/.rvm/gems/ruby-2.4.1/gems/mysql2-0.4.8/ext/mysql2
/Users/admin/.rvm/rubies/ruby-2.4.1/bin/ruby -r ./siteconf20170803-6579-foq4sg.rb extconf.rb
checking for rb_absint_size()... yes
</code>```

I ran 'bundle install' but I can't success this command because of this error.

答:
For people who use macOS Monterey (M1 Pro/Max), I found a simple and fast solution:

Copy and past it in your terminal

```<code>arch -x86_64 gem install mysql2 -v 0.5.3 -- --srcdir=/usr/local/mysql/include
</code>```

Now you can run bundle without any MySql errors

Body:
How can I fix this error in ruby on rail.

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.2'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
gem 'mysql 2', '0.4.8'
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'spree', '~> 3.2.1'
gem 'spree_auth_devise', github: 'spree/spree_auth_devise'
gem 'spree_gateway', github: 'spree/spree_gateway'
gem 'spree_i18n', github: 'spree-contrib/spree_i18n', branch: 'master'

I ran the 'bundle install' and this error occurred.
So to fix the bug of the project, I ran 'gem install mysql2 '0.4.8'' command in console but I can't fix it.

This ruby on rails uses Spree framework.

edit:

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/admin/.rvm/gems/ruby-2.4.1/gems/mysql2-0.4.8/ext/mysql2
/Users/admin/.rvm/rubies/ruby-2.4.1/bin/ruby -r ./siteconf20170803-6579-foq4sg.rb extconf.rb
checking for rb_absint_size()... yes

I ran 'bundle install' but I can't success this command because of this error.

Body:
For people who use macOS Monterey (M1 Pro/Max), I found a simple and fast solution:

Copy and past it in your terminal

arch -x86_64 gem install mysql2 -v 0.5.3 -- --srcdir=/usr/local/mysql/include

Now you can run bundle without any MySql errors


问:
Sorting CommandLineRunner execution
I've four CommandLineRunner to be executed in a specific order. Two of them are annotated as @Component and the other two are declared as Bean. I used the  @Order annotation to specify the execution order but I found an unexpected behavior running the code below:

...
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Bean
    @Order(2)
    public CommandLineRunner upRunner(){
        return args -> log.info("2 - Running upRunner");
    }

    @Bean
    @Order(1)
    public CommandLineRunner downRunner(){
        return args -> log.info("1 - Running downRunner");
    }
}
```
<pre class="lang-java prettyprint-override"><code>...
@Component
@Order(4)
public class RightRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        log.info("4 - Running RightRunner");
    }
}
</code>```

...
@Component
@Order(3)
public class LeftRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        log.info("3 - Running LeftRunner");
    }
}
```
<p>The execution does not follow the order specified by the @Order annotation, see the log below:</p>
```[INFO ] Started App in 2.988 seconds (JVM running for 3.949)
[INFO ] 3 - Running LeftRunner
[INFO ] 4 - Running RightRunner
[INFO ] 2 - Running upRunner
[INFO ] 1 - Running downRunner
```
<p>So, it seems that:</p>
<ul>
<li>the runners annotated as @Component are executed in the expected order and before the others.</li>
<li>the runners declared as @Bean are executed in the order they are defined in the App class with no regard of the @Order annotation.</li>
</ul>
<p>Is there something I miss to enforce the required order?
Could someone clarify this behavior, I'm using spring-boot version 2.4.0?</p>
<p>It is also quite strange that Spring is able to properly sort those beans when injected, just adding the Bean below:</p>
<pre class="lang-java prettyprint-override"><code>...

    @Bean
    public Object runners(List<CommandLineRunner> runners) throws Exception {

        for(int i=0; i<runners.size(); i++){
            runners.get(i).run(null);
        }
        return new Object();
    }

</code>```

the log shows that the injected CommandLineRunner list is sorted according to the @Order annotation:

```<code>[INFO ] 1 - Running downRunner
[INFO ] 2 - Running upRunner
[INFO ] 3 - Running LeftRunner
[INFO ] 4 - Running RightRunner
[INFO ] ...
[INFO ] Started App in 2.754 seconds (JVM running for 3.847)
[INFO ] 3 - Running LeftRunner
[INFO ] 4 - Running RightRunner
[INFO ] 2 - Running upRunner
[INFO ] 1 - Running downRunner
</code>```

Thanks in advance,

Andrea

答:
I also faced the same issue.

Since I could not resolve it with @Order interface, I implemented Ordered interface to fix the issue

Title: Sorting CommandLineRunner execution

Body:
I've four CommandLineRunner to be executed in a specific order. Two of them are annotated as @Component and the other two are declared as Bean. I used the  @Order annotation to specify the execution order but I found an unexpected behavior running the code below:

...
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Bean
    @Order(2)
    public CommandLineRunner upRunner(){
        return args -> log.info("2 - Running upRunner");
    }

    @Bean
    @Order(1)
    public CommandLineRunner downRunner(){
        return args -> log.info("1 - Running downRunner");
    }
}

...
@Component
@Order(4)
public class RightRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        log.info("4 - Running RightRunner");
    }
}

...
@Component
@Order(3)
public class LeftRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        log.info("3 - Running LeftRunner");
    }
}

The execution does not follow the order specified by the @Order annotation, see the log below:

[INFO ] Started App in 2.988 seconds (JVM running for 3.949)
[INFO ] 3 - Running LeftRunner
[INFO ] 4 - Running RightRunner
[INFO ] 2 - Running upRunner
[INFO ] 1 - Running downRunner

So, it seems that:

the runners annotated as @Component are executed in the expected order and before the others.

the runners declared as @Bean are executed in the order they are defined in the App class with no regard of the @Order annotation.

Is there something I miss to enforce the required order?
Could someone clarify this behavior, I'm using spring-boot version 2.4.0?

It is also quite strange that Spring is able to properly sort those beans when injected, just adding the Bean below:

...

    @Bean
    public Object runners(List<CommandLineRunner> runners) throws Exception {

        for(int i=0; i<runners.size(); i++){
            runners.get(i).run(null);
        }
        return new Object();
    }

the log shows that the injected CommandLineRunner list is sorted according to the @Order annotation:

[INFO ] 1 - Running downRunner
[INFO ] 2 - Running upRunner
[INFO ] 3 - Running LeftRunner
[INFO ] 4 - Running RightRunner
[INFO ] ...
[INFO ] Started App in 2.754 seconds (JVM running for 3.847)
[INFO ] 3 - Running LeftRunner
[INFO ] 4 - Running RightRunner
[INFO ] 2 - Running upRunner
[INFO ] 1 - Running downRunner

Thanks in advance,

Andrea


问:
How To Scale The Contents Of A UIView To Fit A Destination Rectangle Whilst Maintaining The Aspect Ratio?
I am trying to solve a problem without success and am hoping someone could help.

I have looked for similar posts but haven't been able to find anything which solves my problem.

My Scenario is as follows:
I have a UIView on which a number of other UIViews can be placed. These can be moved, scaled and rotated using gesture recognisers (There is no issue here).
The User is able to change the Aspect Ratio of the Main View (the Canvas) and my problem is trying to scale the content of the Canvas to fit into the new destination size.

There are a number of posts with a similar theme e.g:

calculate new size and location on a CGRect

How to create an image of specific size from UIView

But these don't address the changing of ratios multiple times.

My Approach:

When I change the aspect ratio of the canvas, I make use of AVFoundation to calculate an aspect fitted rectangle which the subviews of the canvas should fit:

```<code>let sourceRectangleSize = canvas.frame.size

canvas.setAspect(aspect, screenSize: editorLayoutGuide.layoutFrame.size)
view.layoutIfNeeded()

let destinationRectangleSize = canvas.frame.size

let aspectFittedFrame = AVMakeRect(aspectRatio:sourceRectangleSize, insideRect: CGRect(origin: .zero, size: destinationRectangleSize))
ratioVisualizer.frame = aspectFittedFrame
</code>```

The Red frame is simply to visualise the Aspect Fitted Rectangle. As you can see whilst the aspect fitted rectangle is correct, the scaling of objects isn't working. This is especially true when I apply scale and rotation to the subviews (CanvasElement).

The logic where I am scaling the objects is clearly wrong:

```<code>@objc
private func setRatio(_ control: UISegmentedControl) {
  guard let aspect = Aspect(rawValue: control.selectedSegmentIndex) else { return }

  let sourceRectangleSize = canvas.frame.size

  canvas.setAspect(aspect, screenSize: editorLayoutGuide.layoutFrame.size)
  view.layoutIfNeeded()

  let destinationRectangleSize = canvas.frame.size

  let aspectFittedFrame = AVMakeRect(aspectRatio:sourceRectangleSize, insideRect: CGRect(origin: .zero, size: destinationRectangleSize))
  ratioVisualizer.frame = aspectFittedFrame

  let scale = min(aspectFittedFrame.size.width/canvas.frame.width, aspectFittedFrame.size.height/canvas.frame.height)

  for case let canvasElement as CanvasElement in canvas.subviews {

    canvasElement.frame.size = CGSize(
      width: canvasElement.baseFrame.width * scale,
      height: canvasElement.baseFrame.height * scale
    )
    canvasElement.frame.origin = CGPoint(
      x: aspectFittedFrame.origin.x + canvasElement.baseFrame.origin.x * scale,
      y:  aspectFittedFrame.origin.y + canvasElement.baseFrame.origin.y * scale
    )
  }
}
</code>```

I am enclosing the CanvasElement Class as well if this helps:

```<code>final class CanvasElement: UIView {

  var rotation: CGFloat = 0
  var baseFrame: CGRect = .zero

  var id: String = UUID().uuidString

  // MARK: - Initialization

  override init(frame: CGRect) {
    super.init(frame: frame)
    storeState()
    setupGesture()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }

  // MARK: - Gesture Setup

  private func setupGesture() {
    let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGesture(_:)))
    let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchGesture(_:)))
    let rotateGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(rotateGesture(_:)))
    addGestureRecognizer(panGestureRecognizer)
    addGestureRecognizer(pinchGestureRecognizer)
    addGestureRecognizer(rotateGestureRecognizer)
  }

  // MARK: - Touches

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    moveToFront()
  }

  //MARK: - Gestures

  @objc
  private func panGesture(_ sender: UIPanGestureRecognizer) {
    let move = sender.translation(in: self)
    transform = transform.concatenating(.init(translationX: move.x, y: move.y))
    sender.setTranslation(CGPoint.zero, in: self)
    storeState()
  }

  @objc
  private func pinchGesture(_ sender: UIPinchGestureRecognizer) {
    transform = transform.scaledBy(x: sender.scale, y: sender.scale)
    sender.scale = 1
    storeState()
  }

  @objc
  private func rotateGesture(_ sender: UIRotationGestureRecognizer) {
    rotation += sender.rotation
    transform = transform.rotated(by: sender.rotation)
    sender.rotation = 0
    storeState()
  }

  // MARK: - Miscelaneous

  func moveToFront() {
    superview?.bringSubviewToFront(self)
  }

  public func rotated(by degrees: CGFloat) {
    transform = transform.rotated(by: degrees)
    rotation += degrees
  }

  func storeState() {
    print("""
    Element Frame = \(frame)
    Element Bounds = \(bounds)
    Element Center = \(center)
    """)
    baseFrame = frame
  }
}
</code>```

Any help or advise, approaches, with some actual examples would be great. Im not expecting anyone to provide full source code, but something which I could use as a basis.

Thank you for taking the time to read my question.

答:
Here are a few thoughts and findings while playing around with this

1. Is the right scale factor being used?

The scaling you use is a bit custom and cannot be compared directly to the examples which has just 1 scale factor like 2 or 3. However, your scale factor has 2 dimensions but I see you compensate for this to get the minimum of the width and height scaling:

```<code>let scale = min(aspectFittedFrame.size.width / canvas.frame.width,
                aspectFittedFrame.size.height / canvas.frame.height)
</code>```

In my opinion, I don't think this is the right scale factor. To me this compares new aspectFittedFrame with the new canvas frame

when actually I believe the right scaling factor is to compare the new aspectFittedFrame with the previous canvas frame

```<code>let scale
    = min(aspectFittedFrame.size.width / sourceRectangleSize.width,
          aspectFittedFrame.size.height / sourceRectangleSize.height)
</code>```

2. Is the scale being applied on the right values?

If you notice, the first order from 1:1 to 16:9 works quite well. However after that it does not seem to work and I believe the issue is here:

```<code>for case let canvasElement as CanvasElement in strongSelf.canvas.subviews
{
    canvasElement.frame.size = CGSize(
        width: canvasElement.baseFrame.width * scale,
        height: canvasElement.baseFrame.height * scale
    )

    canvasElement.frame.origin = CGPoint(
        x: aspectFittedFrame.origin.x
            + canvasElement.baseFrame.origin.x * scale,

        y:  aspectFittedFrame.origin.y
            + canvasElement.baseFrame.origin.y * scale
    )
}
</code>```

The first time, the scale works well because canvas and the canvas elements are being scaled in sync or mapped properly:

However, if you go beyond that, because you are always scaling based on the base values your aspect ratio frame and your canvas elements are out of sync

So in the example of 1:1 -> 16:9 -> 3:2

Your viewport has been scaled twice 1:1 -> 16:9 and from 16:9 -> 3:2

Whereas your elements are scaled once each time, 1:1 -> 16:9 and 1:1 -> 3:2 because you always scale from the base values

So I feel to see the values within the red viewport, you need to apply the same continuous scaling based on the previous view rather than the base view.

Just for an immediate quick fix, I update the base values of the canvas element after each change in canvas size by calling canvasElement.storeState():

```<code>for case let canvasElement as CanvasElement in strongSelf.canvas.subviews
{
    canvasElement.frame.size = CGSize(
        width: canvasElement.baseFrame.width * scale,
        height: canvasElement.baseFrame.height * scale
    )

    canvasElement.frame.origin = CGPoint(
        x: aspectFittedFrame.origin.x
            + canvasElement.baseFrame.origin.x * scale,

        y:  aspectFittedFrame.origin.y
            + canvasElement.baseFrame.origin.y * scale
    )

    // I added this
    canvasElement.storeState()
}
</code>```

The result is perhaps closer to what you want ?

Final thoughts

While this might fix your issue, you will notice that it is not possible to come back to the original state as at each step a transformation is applied.

A solution could be to store the current values mapped to a specific viewport aspect ratio and calculate the right sizes for the others so that if you needed to get back to the original, you could do that.

Body:
I am trying to solve a problem without success and am hoping someone could help.

I have looked for similar posts but haven't been able to find anything which solves my problem.

My Scenario is as follows:
I have a UIView on which a number of other UIViews can be placed. These can be moved, scaled and rotated using gesture recognisers (There is no issue here).
The User is able to change the Aspect Ratio of the Main View (the Canvas) and my problem is trying to scale the content of the Canvas to fit into the new destination size.

There are a number of posts with a similar theme e.g:

calculate new size and location on a CGRect

How to create an image of specific size from UIView

But these don't address the changing of ratios multiple times.

My Approach:

When I change the aspect ratio of the canvas, I make use of AVFoundation to calculate an aspect fitted rectangle which the subviews of the canvas should fit:

let sourceRectangleSize = canvas.frame.size

canvas.setAspect(aspect, screenSize: editorLayoutGuide.layoutFrame.size)
view.layoutIfNeeded()

let destinationRectangleSize = canvas.frame.size

let aspectFittedFrame = AVMakeRect(aspectRatio:sourceRectangleSize, insideRect: CGRect(origin: .zero, size: destinationRectangleSize))
ratioVisualizer.frame = aspectFittedFrame

The Red frame is simply to visualise the Aspect Fitted Rectangle. As you can see whilst the aspect fitted rectangle is correct, the scaling of objects isn't working. This is especially true when I apply scale and rotation to the subviews (CanvasElement).

The logic where I am scaling the objects is clearly wrong:

@objc
private func setRatio(_ control: UISegmentedControl) {
  guard let aspect = Aspect(rawValue: control.selectedSegmentIndex) else { return }

  let sourceRectangleSize = canvas.frame.size

  canvas.setAspect(aspect, screenSize: editorLayoutGuide.layoutFrame.size)
  view.layoutIfNeeded()

  let destinationRectangleSize = canvas.frame.size

  let aspectFittedFrame = AVMakeRect(aspectRatio:sourceRectangleSize, insideRect: CGRect(origin: .zero, size: destinationRectangleSize))
  ratioVisualizer.frame = aspectFittedFrame

  let scale = min(aspectFittedFrame.size.width/canvas.frame.width, aspectFittedFrame.size.height/canvas.frame.height)

  for case let canvasElement as CanvasElement in canvas.subviews {

    canvasElement.frame.size = CGSize(
      width: canvasElement.baseFrame.width * scale,
      height: canvasElement.baseFrame.height * scale
    )
    canvasElement.frame.origin = CGPoint(
      x: aspectFittedFrame.origin.x + canvasElement.baseFrame.origin.x * scale,
      y:  aspectFittedFrame.origin.y + canvasElement.baseFrame.origin.y * scale
    )
  }
}

I am enclosing the CanvasElement Class as well if this helps:

final class CanvasElement: UIView {

  var rotation: CGFloat = 0
  var baseFrame: CGRect = .zero

  var id: String = UUID().uuidString

  // MARK: - Initialization

  override init(frame: CGRect) {
    super.init(frame: frame)
    storeState()
    setupGesture()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }

  // MARK: - Gesture Setup

  private func setupGesture() {
    let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGesture(_:)))
    let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchGesture(_:)))
    let rotateGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(rotateGesture(_:)))
    addGestureRecognizer(panGestureRecognizer)
    addGestureRecognizer(pinchGestureRecognizer)
    addGestureRecognizer(rotateGestureRecognizer)
  }

  // MARK: - Touches

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    moveToFront()
  }

  //MARK: - Gestures

  @objc
  private func panGesture(_ sender: UIPanGestureRecognizer) {
    let move = sender.translation(in: self)
    transform = transform.concatenating(.init(translationX: move.x, y: move.y))
    sender.setTranslation(CGPoint.zero, in: self)
    storeState()
  }

  @objc
  private func pinchGesture(_ sender: UIPinchGestureRecognizer) {
    transform = transform.scaledBy(x: sender.scale, y: sender.scale)
    sender.scale = 1
    storeState()
  }

  @objc
  private func rotateGesture(_ sender: UIRotationGestureRecognizer) {
    rotation += sender.rotation
    transform = transform.rotated(by: sender.rotation)
    sender.rotation = 0
    storeState()
  }

  // MARK: - Miscelaneous

  func moveToFront() {
    superview?.bringSubviewToFront(self)
  }

  public func rotated(by degrees: CGFloat) {
    transform = transform.rotated(by: degrees)
    rotation += degrees
  }

  func storeState() {
    print("""
    Element Frame = \(frame)
    Element Bounds = \(bounds)
    Element Center = \(center)
    """)
    baseFrame = frame
  }
}

Any help or advise, approaches, with some actual examples would be great. Im not expecting anyone to provide full source code, but something which I could use as a basis.

Thank you for taking the time to read my question.

Body:
Here are a few thoughts and findings while playing around with this

1. Is the right scale factor being used?

The scaling you use is a bit custom and cannot be compared directly to the examples which has just 1 scale factor like 2 or 3. However, your scale factor has 2 dimensions but I see you compensate for this to get the minimum of the width and height scaling:

let scale = min(aspectFittedFrame.size.width / canvas.frame.width,
                aspectFittedFrame.size.height / canvas.frame.height)

In my opinion, I don't think this is the right scale factor. To me this compares new aspectFittedFrame with the new canvas frame

when actually I believe the right scaling factor is to compare the new aspectFittedFrame with the previous canvas frame

let scale
    = min(aspectFittedFrame.size.width / sourceRectangleSize.width,
          aspectFittedFrame.size.height / sourceRectangleSize.height)

2. Is the scale being applied on the right values?

If you notice, the first order from 1:1 to 16:9 works quite well. However after that it does not seem to work and I believe the issue is here:

for case let canvasElement as CanvasElement in strongSelf.canvas.subviews
{
    canvasElement.frame.size = CGSize(
        width: canvasElement.baseFrame.width * scale,
        height: canvasElement.baseFrame.height * scale
    )

    canvasElement.frame.origin = CGPoint(
        x: aspectFittedFrame.origin.x
            + canvasElement.baseFrame.origin.x * scale,

        y:  aspectFittedFrame.origin.y
            + canvasElement.baseFrame.origin.y * scale
    )
}

The first time, the scale works well because canvas and the canvas elements are being scaled in sync or mapped properly:

However, if you go beyond that, because you are always scaling based on the base values your aspect ratio frame and your canvas elements are out of sync

So in the example of 1:1 -> 16:9 -> 3:2

Your viewport has been scaled twice 1:1 -> 16:9 and from 16:9 -> 3:2

Whereas your elements are scaled once each time, 1:1 -> 16:9 and 1:1 -> 3:2 because you always scale from the base values

So I feel to see the values within the red viewport, you need to apply the same continuous scaling based on the previous view rather than the base view.

Just for an immediate quick fix, I update the base values of the canvas element after each change in canvas size by calling canvasElement.storeState():

for case let canvasElement as CanvasElement in strongSelf.canvas.subviews
{
    canvasElement.frame.size = CGSize(
        width: canvasElement.baseFrame.width * scale,
        height: canvasElement.baseFrame.height * scale
    )

    canvasElement.frame.origin = CGPoint(
        x: aspectFittedFrame.origin.x
            + canvasElement.baseFrame.origin.x * scale,

        y:  aspectFittedFrame.origin.y
            + canvasElement.baseFrame.origin.y * scale
    )

    // I added this
    canvasElement.storeState()
}

The result is perhaps closer to what you want ?

Final thoughts

While this might fix your issue, you will notice that it is not possible to come back to the original state as at each step a transformation is applied.

A solution could be to store the current values mapped to a specific viewport aspect ratio and calculate the right sizes for the others so that if you needed to get back to the original, you could do that.


问:
Python/Pandas: Repeat row value for each row in column when multiple conditions are met
I have used pd.wide_to_long() to create a longer df.
I want to create a new column called "Bodyweight" that takes the value from the "Load" column when the exercise == "bodyweight" and displays it for each row entry for an athlete on that date.
the current layout is:

ie

Input

```<code>        Date    Player_Name Exercise    Set Reps    Load
0   Day 1   Player 1    Bench Press 1   5   120
1   Day 1   Player 1    Bench Press 2   5   120
2   Day 1   Player 1    Bench Press 3   5   120
3   Day 1   Player 1    Bodyweight  1   1   100
4   Day 2   Player 1    Squat   1   5   180
5   Day 2   Player 1    Squat   2   5   180
6   Day 2   Player 1    Squat   3   5   180
7   Day 2   Player 1    Bodyweight  1   1   101.5
8   Day 1   Player 2    Chin up 1   3   125
9   Day 1   Player 2    Bodyweight  1   1   92
</code>```

Output

```<code>Date    Player_Name Bodyweight  Exercise    Set Reps    Load
0   Day 1   Player 1    100 Bench Press 1   5   120
1   Day 1   Player 1    100 Bench Press 2   5   120
2   Day 1   Player 1    100 Bench Press 3   5   120
3   Day 2   Player 1    101.5   Squat   1   5   180
4   Day 2   Player 1    101.5   Squat   2   5   180
5   Day 2   Player 1    101.5   Squat   3   5   180
6   Day 1   Player 2    92  Chin up 1   3   125
</code>```

I have tried:

```<code>df["Body_Weight"] = df[df["Exercise"] == "Body Weight"]["Load"]
</code>```

to create a new column but this does not repeat the value for each entry of that player on that date.

Any help would be great!
Thanks,
Liam

答:
Create a boolean mask and transform to broadcast the Load value of Bodyweight to each row of the group:

```<code>m = df['Exercise'] == 'Bodyweight'
bw = df.groupby(['Date', 'Player_Name'])['Load'].transform(lambda x: x[m].max())[~m]
out = df.assign(Body_Weight=bw)[~m]
print(out)

# Output
    Date Player_Name     Exercise  Set  Reps   Load  Body_Weight
0  Day 1    Player 1  Bench Press    1     5  120.0        100.0
1  Day 1    Player 1  Bench Press    2     5  120.0        100.0
2  Day 1    Player 1  Bench Press    3     5  120.0        100.0
4  Day 2    Player 1        Squat    1     5  180.0        101.5
5  Day 2    Player 1        Squat    2     5  180.0        101.5
6  Day 2    Player 1        Squat    3     5  180.0        101.5
8  Day 1    Player 2      Chin up    1     3  125.0         92.0
</code>```

Body:
I have used pd.wide_to_long() to create a longer df.
I want to create a new column called "Bodyweight" that takes the value from the "Load" column when the exercise == "bodyweight" and displays it for each row entry for an athlete on that date.
the current layout is:

ie

Input

        Date    Player_Name Exercise    Set Reps    Load
0   Day 1   Player 1    Bench Press 1   5   120
1   Day 1   Player 1    Bench Press 2   5   120
2   Day 1   Player 1    Bench Press 3   5   120
3   Day 1   Player 1    Bodyweight  1   1   100
4   Day 2   Player 1    Squat   1   5   180
5   Day 2   Player 1    Squat   2   5   180
6   Day 2   Player 1    Squat   3   5   180
7   Day 2   Player 1    Bodyweight  1   1   101.5
8   Day 1   Player 2    Chin up 1   3   125
9   Day 1   Player 2    Bodyweight  1   1   92

Output

Date    Player_Name Bodyweight  Exercise    Set Reps    Load
0   Day 1   Player 1    100 Bench Press 1   5   120
1   Day 1   Player 1    100 Bench Press 2   5   120
2   Day 1   Player 1    100 Bench Press 3   5   120
3   Day 2   Player 1    101.5   Squat   1   5   180
4   Day 2   Player 1    101.5   Squat   2   5   180
5   Day 2   Player 1    101.5   Squat   3   5   180
6   Day 1   Player 2    92  Chin up 1   3   125

I have tried:

df["Body_Weight"] = df[df["Exercise"] == "Body Weight"]["Load"]

to create a new column but this does not repeat the value for each entry of that player on that date.

Any help would be great!
Thanks,
Liam

Body:
Create a boolean mask and transform to broadcast the Load value of Bodyweight to each row of the group:

m = df['Exercise'] == 'Bodyweight'
bw = df.groupby(['Date', 'Player_Name'])['Load'].transform(lambda x: x[m].max())[~m]
out = df.assign(Body_Weight=bw)[~m]
print(out)

# Output
    Date Player_Name     Exercise  Set  Reps   Load  Body_Weight
0  Day 1    Player 1  Bench Press    1     5  120.0        100.0
1  Day 1    Player 1  Bench Press    2     5  120.0        100.0
2  Day 1    Player 1  Bench Press    3     5  120.0        100.0
4  Day 2    Player 1        Squat    1     5  180.0        101.5
5  Day 2    Player 1        Squat    2     5  180.0        101.5
6  Day 2    Player 1        Squat    3     5  180.0        101.5
8  Day 1    Player 2      Chin up    1     3  125.0         92.0


问:
How to update loop?
I have string like this

```<code>txt = 'hi how are you user alex12 ?'
</code>```

and I need to make some changes like this

```<code> col1          |  col2
 --------------|------------
'hi'           |  'H1'
'are you'      |  'B1'
'user alex12'  |  'A1 B2 C1'
</code>```

I want this result

```<code>txt = 'H1 how B1 A1 B2 C1 ?'
</code>```

and this is the hard part, the col1 is a list of 1,000 item's, I made this code but it's not work well

```<code>check_list = ['hi', 'are you', ...]
temp = txt.split()
for i in range(len(temp)):
    if temp in check_list:
        temp[i] = check_list[check_list.index(temp[i])
</code>```

答:
So what i got from your question according to that

this solution should be enough

```<code>txt = 'hi how are you user alex12 ?'
col1 = ["hi","are you","user alex12"]
col2 = ['H1','B1','A1 B1 C1']
for i in range(0,len(col1)):
    txt = txt.replace(col1[i],col2[i])

print(txt)
</code>```

Title: How to update loop?

Body:
I have string like this

txt = 'hi how are you user alex12 ?'

and I need to make some changes like this

 col1          |  col2
 --------------|------------
'hi'           |  'H1'
'are you'      |  'B1'
'user alex12'  |  'A1 B2 C1'

I want this result

txt = 'H1 how B1 A1 B2 C1 ?'

and this is the hard part, the col1 is a list of 1,000 item's, I made this code but it's not work well

check_list = ['hi', 'are you', ...]
temp = txt.split()
for i in range(len(temp)):
    if temp in check_list:
        temp[i] = check_list[check_list.index(temp[i])

Body:
So what i got from your question according to that

this solution should be enough

txt = 'hi how are you user alex12 ?'
col1 = ["hi","are you","user alex12"]
col2 = ['H1','B1','A1 B1 C1']
for i in range(0,len(col1)):
    txt = txt.replace(col1[i],col2[i])

print(txt)


问:
node js http createServer socket
The doubt with with code is two things:

When i send request through a browser, i dont get a console log message as "connected" but if i use http.get() or http.request() , it works fine
2)The "connect" event receives a callback with req,clientSocke,head ! now where can i see the server socket ?

```<code>const http=require("http")

const server=http.createServer()
server.on("connect",(req,c_socket,head)=>{

 console.log("connected")

})
server.listen(5000,()=>{console.log("server up)})
</code>```

答:
when you access the server via browser, the method is using GET not CONNECT. That's why console.log does not show.
if you want console.log to show when accessing from the browser, you can use request event.

this is an explanation from node.js docs.

'connect' event is emitted each time a server responds to a request
with a CONNECT method. If this event is not being listened for,
clients receiving a CONNECT method will have their connections closed.
node.js docs

you can make a socket server with a net package with createSever method.
this is an example of how to make a simple request to the socket server.

```<code>const http = require('http');
const net = require('net');
const { URL } = require('url');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('hello world');
});

server.on('connect', (req, clientSocket, head) => {
  console.log('connected');
  // Connect to an origin server
  const { port, hostname } = new URL(`http://${req.url}`);
  const serverSocket = net.connect(port || 80, hostname, () => {
    clientSocket.write(
      'HTTP/1.1 200 Connection Established\r\n' +
        'Proxy-agent: Node.js-Proxy\r\n' +
        '\r\n'
    );
    serverSocket.write(head);
    serverSocket.pipe(clientSocket);
    clientSocket.pipe(serverSocket);
  });
});

server.listen(5000, () => {
  console.log('server up');
});

// Make a request to a tunneling server
const req = http
  .request({
    port: 5000,
    host: 'localhost',
    method: 'CONNECT',
    path: 'www.google.com:80',
  })
  .end();

req.on('connect', (res, socket, head) => {
  console.log('got connected!');

  // Make a request over an HTTP tunnel
  socket.write(
    'GET / HTTP/1.1\r\n' +
      'Host: www.google.com:80\r\n' +
      'Connection: close\r\n' +
      '\r\n'
  );
  socket.on('data', (chunk) => {
    console.log(chunk.toString());
  });
  socket.on('end', () => {
    console.log('end');
  });
});
</code>```

Title: node js http createServer socket

Body:
The doubt with with code is two things:

When i send request through a browser, i dont get a console log message as "connected" but if i use http.get() or http.request() , it works fine
2)The "connect" event receives a callback with req,clientSocke,head ! now where can i see the server socket ?

const http=require("http")

const server=http.createServer()
server.on("connect",(req,c_socket,head)=>{

 console.log("connected")

})
server.listen(5000,()=>{console.log("server up)})

Body:
when you access the server via browser, the method is using GET not CONNECT. That's why console.log does not show.
if you want console.log to show when accessing from the browser, you can use request event.

this is an explanation from node.js docs.

'connect' event is emitted each time a server responds to a request
with a CONNECT method. If this event is not being listened for,
clients receiving a CONNECT method will have their connections closed.
node.js docs

you can make a socket server with a net package with createSever method.
this is an example of how to make a simple request to the socket server.

const http = require('http');
const net = require('net');
const { URL } = require('url');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('hello world');
});

server.on('connect', (req, clientSocket, head) => {
  console.log('connected');
  // Connect to an origin server
  const { port, hostname } = new URL(`http://${req.url}`);
  const serverSocket = net.connect(port || 80, hostname, () => {
    clientSocket.write(
      'HTTP/1.1 200 Connection Established\r\n' +
        'Proxy-agent: Node.js-Proxy\r\n' +
        '\r\n'
    );
    serverSocket.write(head);
    serverSocket.pipe(clientSocket);
    clientSocket.pipe(serverSocket);
  });
});

server.listen(5000, () => {
  console.log('server up');
});

// Make a request to a tunneling server
const req = http
  .request({
    port: 5000,
    host: 'localhost',
    method: 'CONNECT',
    path: 'www.google.com:80',
  })
  .end();

req.on('connect', (res, socket, head) => {
  console.log('got connected!');

  // Make a request over an HTTP tunnel
  socket.write(
    'GET / HTTP/1.1\r\n' +
      'Host: www.google.com:80\r\n' +
      'Connection: close\r\n' +
      '\r\n'
  );
  socket.on('data', (chunk) => {
    console.log(chunk.toString());
  });
  socket.on('end', () => {
    console.log('end');
  });
});


问:
How to find the background-position / background-image etc for multiple backgrounds using jQuery in Safari
Maybe I'm missing something here.

I'm trying to get the current background info for an element (div) with multiple backgrounds, set using the longhand background-repeat, background-position and background-image.

Using jQuery, I simply do var bPos = $('#element').css('background-position') to get the set of current positions, which will give me something like '0 0, 100px 100px, left bottom' in Firefox and Chromium (currently versions 5 and 12 respectively), but in Safari (version 5 on OS-X) it just returns the first value pair ('0 0'). These CSS values are set in an external stylesheet.

Does anyone have any idea as to why this is, and how to go about it to get the full set of value pairs in Safari (using the shorthand background property doesn't do it either)?

Edit:

Here is the CSS that is used in an external style sheet:

```<code>#page{
    background-repeat: repeat-x, repeat-x, repeat-x, repeat-x, repeat-x;
    background-image: url('../images/line.png'), url('../images/line.png'), url('../images/line.png'), url('../images/line.png'), url('../images/line.png');
    background-position: 0 798px, 0 653px, 0 125px, 0 88px, 0 78px;
}
</code>```

Edit:

Ok, I made a test case for this on jsFiddle and have reported it as a jQuery bug since it seems to be reproducible behaviour (although I accept that it might be a browser implementation problem rather than actually a jQuery bug).

Still, if anyone has any ideas...

Edit:

The jQuery ticket has been closed - I take this to mean that it is a Safari bug - I'm not quite sure how to go further from here, but I've posted a bug report with Apple.

Edit:

As pointed out by Sindre Sorhus, this appears to have been corrected in Safari 5.1.

答:
Use Jquery Background Position plugin.
http://www.webinventif.fr/jquery-background-position-mettez-du-mouvement-dans-votre-background/</p>

Body:
Maybe I'm missing something here.

I'm trying to get the current background info for an element (div) with multiple backgrounds, set using the longhand background-repeat, background-position and background-image.

Using jQuery, I simply do var bPos = $('#element').css('background-position') to get the set of current positions, which will give me something like '0 0, 100px 100px, left bottom' in Firefox and Chromium (currently versions 5 and 12 respectively), but in Safari (version 5 on OS-X) it just returns the first value pair ('0 0'). These CSS values are set in an external stylesheet.

Does anyone have any idea as to why this is, and how to go about it to get the full set of value pairs in Safari (using the shorthand background property doesn't do it either)?

Edit:

Here is the CSS that is used in an external style sheet:

#page{
    background-repeat: repeat-x, repeat-x, repeat-x, repeat-x, repeat-x;
    background-image: url('../images/line.png'), url('../images/line.png'), url('../images/line.png'), url('../images/line.png'), url('../images/line.png');
    background-position: 0 798px, 0 653px, 0 125px, 0 88px, 0 78px;
}

Edit:

Ok, I made a test case for this on jsFiddle and have reported it as a jQuery bug since it seems to be reproducible behaviour (although I accept that it might be a browser implementation problem rather than actually a jQuery bug).

Still, if anyone has any ideas...

Edit:

The jQuery ticket has been closed - I take this to mean that it is a Safari bug - I'm not quite sure how to go further from here, but I've posted a bug report with Apple.

Edit:

As pointed out by Sindre Sorhus, this appears to have been corrected in Safari 5.1.


问:
Reliable alternative to Java Watch Service
I am using Java nio's WatchService but I find it quite unreliable for the following use cases:

When a very big file (>500 megs) is written to the directory being watched, if I rely on ENTRY_CREATE event, the file is often times not yet ready to read - it's still being written by the other thread. So I normally resort to listening for ENTRY_MODIFY instead.

But when thousands of small sized (~2Kb) files are copied to the watched directory, the ENTRY_CREATE or ENTRY_MODIFY doesn't get invoked for 80% of them!

Has anyone else faced this? And is there a better more reliable lib or should I simply switch to a blocking queue imlementation where the file copier adds the file name into the queue and the consumer thread handles processing of the files?

Code around WatchService implementation:

```<code>
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Path path = Paths.get( coreProperties.getStagingLocation() );
            path.register( watchService,
                    new WatchEvent.Kind[] { ENTRY_MODIFY, ENTRY_CREATE },
                    SensitivityWatchEventModifier.MEDIUM
            );

            WatchKey key;
            while ( ( key = watchService.take() ) != null ) {
                for ( WatchEvent<?> event : key.pollEvents() ) {
                    log.info( "Event kind: {} . File affected: {}.", event.kind(), event.context() );
            // Processing the file..
                }
                key.reset();
            }

</code>```

答:
Based on the helpful comments by DuncG and Jim Garrison, I realised that Watch Service is sensitive to the processing times of each notification. I was copying 6,416 files to the folder it was watching and if I was doing anything more than logging the ENTRY_XX event, it was missing on many of the updates.

Here is what worked for me:

While handling ENTRY_XX events, I am writing it to a LMAX Disruptor which has ring buffer size higher than max files expected in a batch (I set it to  2^19 i.e. 524,288 slots, and it's good enough to handle 50k or more file updates without blocking, assuming file will have 10 watch service notications).

[PS: writing to a simple ExecutorService queue didn't help due to latency around thread synchronisation. I only got 1273 file names out of the 6,416!].

I also had to warm up the ring buffer or else I was still missing some Watch Service updates. I am filling all its slots with test messages and then sending an async event to the function which copies 6,416 files to the watched folder.

Sample code:

```<code>// publishing file names from watch service event to Disrupto ring buffer

    private void watchStagingFolder() {
        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Path path = Paths.get( coreProperties.getStagingLocation() );
            path.register( watchService,
                    new WatchEvent.Kind[] { ENTRY_MODIFY, ENTRY_CREATE },
                    SensitivityWatchEventModifier.HIGH
            );

            WatchKey key;
            while ( ( key = watchService.take() ) != null ) {
                log.info( "key found: {}", key );
                for ( WatchEvent<?> event : key.pollEvents() ) {
                    String eventKindStr = event.kind().name();
                    log.info( "Event kind: {} . File affected: {}", eventKindStr, event.context() );
                    if ( event.kind().equals( ENTRY_CREATE ) || event.kind().equals( ENTRY_MODIFY ) ) {
                        String fileName = event.context().toString();
                        log.info( "File to be processed: {}", fileName );
                        fileProcessorDisruptorEventProducer.send( fileName );
                    } else {
                        log.info( "Ignoring event kind {}", event.kind() );
                    }
                }
                key.reset();
            }
        } catch ( Exception e ) {
            log.error( "Found error while watching the staging directory.", e );
        }
    }

// ensuring Disruptor ring buffer is warmed up
@Component
@RequiredArgsConstructor
@Slf4j
public class DisruptorWarmer {
    public static final String TEST_FILE_NAME = "TEST_FILE_NAME";
    private final CoreProperties coreProperties;
    private final FileProcessorDisruptorEventProducer fileProcessorDisruptorEventProducer;

    @PostConstruct
    public void init() {
        int bufferSize = coreProperties.getDisruptor().getBufferSize();
        for ( int i = 0; i < bufferSize; i++ ) {
            fileProcessorDisruptorEventProducer.send( TEST_FILE_NAME );
        }
        log.info( "Warmed up disruptor with {} test messages.", bufferSize );
    }
}

// processing files in the Disruptor consumer/handler
    @Override
    public void onEvent( Msg msg, long l, boolean b ) {
        try {
            if ( count < bufferSize ) {
                log.debug( "Disruptor warming up. Count: {}. Ignoring msg: {}", count, msg.getPayload() );
                count++;
            } else if ( count == bufferSize ) {
                log.info( "Disruptor warmed up now with {} test messages.", count + 1 );
                newSingleThreadExecutor.submit( () ->
                        applicationEventPublisher.publishEvent( new FileProcessorDisruptorReadyEvent( this, "Disruptor warmed up." ) )
                );
                count++;
            } else {
                log.debug( "File: {}", msg.getPayload() );
############
// no longer worried about slow processing impacting watch service
                processFile( ( String ) msg.getPayload() );
############
            }
        } catch ( RuntimeException rte ) {
            log.error( "Found error while processing msg: [{}]. Skipping to next message.", msg, rte );
        }
    }
</code>```

Body:
I am using Java nio's WatchService but I find it quite unreliable for the following use cases:

When a very big file (>500 megs) is written to the directory being watched, if I rely on ENTRY_CREATE event, the file is often times not yet ready to read - it's still being written by the other thread. So I normally resort to listening for ENTRY_MODIFY instead.

But when thousands of small sized (~2Kb) files are copied to the watched directory, the ENTRY_CREATE or ENTRY_MODIFY doesn't get invoked for 80% of them!

Has anyone else faced this? And is there a better more reliable lib or should I simply switch to a blocking queue imlementation where the file copier adds the file name into the queue and the consumer thread handles processing of the files?

Code around WatchService implementation:

            WatchService watchService = FileSystems.getDefault().newWatchService();
            Path path = Paths.get( coreProperties.getStagingLocation() );
            path.register( watchService,
                    new WatchEvent.Kind[] { ENTRY_MODIFY, ENTRY_CREATE },
                    SensitivityWatchEventModifier.MEDIUM
            );

            WatchKey key;
            while ( ( key = watchService.take() ) != null ) {
                for ( WatchEvent<?> event : key.pollEvents() ) {
                    log.info( "Event kind: {} . File affected: {}.", event.kind(), event.context() );
            // Processing the file..
                }
                key.reset();
            }

Body:
Based on the helpful comments by DuncG and Jim Garrison, I realised that Watch Service is sensitive to the processing times of each notification. I was copying 6,416 files to the folder it was watching and if I was doing anything more than logging the ENTRY_XX event, it was missing on many of the updates.

Here is what worked for me:

While handling ENTRY_XX events, I am writing it to a LMAX Disruptor which has ring buffer size higher than max files expected in a batch (I set it to  2^19 i.e. 524,288 slots, and it's good enough to handle 50k or more file updates without blocking, assuming file will have 10 watch service notications).

[PS: writing to a simple ExecutorService queue didn't help due to latency around thread synchronisation. I only got 1273 file names out of the 6,416!].

I also had to warm up the ring buffer or else I was still missing some Watch Service updates. I am filling all its slots with test messages and then sending an async event to the function which copies 6,416 files to the watched folder.

Sample code:

// publishing file names from watch service event to Disrupto ring buffer

    private void watchStagingFolder() {
        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Path path = Paths.get( coreProperties.getStagingLocation() );
            path.register( watchService,
                    new WatchEvent.Kind[] { ENTRY_MODIFY, ENTRY_CREATE },
                    SensitivityWatchEventModifier.HIGH
            );

            WatchKey key;
            while ( ( key = watchService.take() ) != null ) {
                log.info( "key found: {}", key );
                for ( WatchEvent<?> event : key.pollEvents() ) {
                    String eventKindStr = event.kind().name();
                    log.info( "Event kind: {} . File affected: {}", eventKindStr, event.context() );
                    if ( event.kind().equals( ENTRY_CREATE ) || event.kind().equals( ENTRY_MODIFY ) ) {
                        String fileName = event.context().toString();
                        log.info( "File to be processed: {}", fileName );
                        fileProcessorDisruptorEventProducer.send( fileName );
                    } else {
                        log.info( "Ignoring event kind {}", event.kind() );
                    }
                }
                key.reset();
            }
        } catch ( Exception e ) {
            log.error( "Found error while watching the staging directory.", e );
        }
    }

// ensuring Disruptor ring buffer is warmed up
@Component
@RequiredArgsConstructor
@Slf4j
public class DisruptorWarmer {
    public static final String TEST_FILE_NAME = "TEST_FILE_NAME";
    private final CoreProperties coreProperties;
    private final FileProcessorDisruptorEventProducer fileProcessorDisruptorEventProducer;

    @PostConstruct
    public void init() {
        int bufferSize = coreProperties.getDisruptor().getBufferSize();
        for ( int i = 0; i < bufferSize; i++ ) {
            fileProcessorDisruptorEventProducer.send( TEST_FILE_NAME );
        }
        log.info( "Warmed up disruptor with {} test messages.", bufferSize );
    }
}

// processing files in the Disruptor consumer/handler
    @Override
    public void onEvent( Msg msg, long l, boolean b ) {
        try {
            if ( count < bufferSize ) {
                log.debug( "Disruptor warming up. Count: {}. Ignoring msg: {}", count, msg.getPayload() );
                count++;
            } else if ( count == bufferSize ) {
                log.info( "Disruptor warmed up now with {} test messages.", count + 1 );
                newSingleThreadExecutor.submit( () ->
                        applicationEventPublisher.publishEvent( new FileProcessorDisruptorReadyEvent( this, "Disruptor warmed up." ) )
                );
                count++;
            } else {
                log.debug( "File: {}", msg.getPayload() );
############
// no longer worried about slow processing impacting watch service
                processFile( ( String ) msg.getPayload() );
############
            }
        } catch ( RuntimeException rte ) {
            log.error( "Found error while processing msg: [{}]. Skipping to next message.", msg, rte );
        }
    }


问:
difference between interface and abstract contract in solidity
I am learning solidity and got to know that interface and abstract are both classes that may contain unused functions.
My doubt is: What is the difference between interface and abstract contract in a solidity smart contract?

答:
It's the same as in most other object-oriented programming languages:

Interface only declares functions. Cannot implement them.

Abstract class can declare functions (same as interface) as well as implement them.

Both cannot be instantiated and need to be implemented/inherited from.

Example:

```<code>interface IMyContract {
    // can declare, cannot implement
    function foo() external returns (bool);
}
</code>```
```<code>abstract contract MyContract {
    // can declare
    function foo() virtual external returns (bool);

    // can implement
    function hello() external pure returns (uint8) {
        return 1;
    }
}
</code>```

Body:
It's the same as in most other object-oriented programming languages:

Interface only declares functions. Cannot implement them.

Abstract class can declare functions (same as interface) as well as implement them.

Both cannot be instantiated and need to be implemented/inherited from.

Example:

interface IMyContract {
    // can declare, cannot implement
    function foo() external returns (bool);
}

abstract contract MyContract {
    // can declare
    function foo() virtual external returns (bool);

    // can implement
    function hello() external pure returns (uint8) {
        return 1;
    }
}


问:
How to Iterate a list of list data to fill html table in JQuery
I have a table like this

```<code><table>
        <tr>
            <td class="text-center">
                <input class="form-control clsEmployeeId" id="txtEmployeeId" type="text" id="employeeId"  value="' + mainList.EmployeeId + '"/>
               </td>
               <td class="text-center">
                <input class="form-control clsEmployeeName" id="txtEmployeeName" type="text" id="employeeName"  value="' + mainList.EmployeeName + '"/>
               </td>
               <td class="text-center">
                <input type="button" value="Details" style="color: Red;" id="btnDetails" class="clsbtnDet"/>
              </td>
        </tr>
     </table>
</code>```

What I want is to iterate a list and fill those fields and there is a secondary list of each row (Contains Employee Details) inside the main one and that secondary list data need to fill a modal which initiate by clicking the "Details "button.

Any help will be much appreciated.

答:
You can use .each() loop function which allows you to loop item(row) one by one at a time. It will passes the index (an integer) and the actual element that you can
use like the following.

```<code>function primaryTable(list){

    $.each(list, function (i, mainList){
      <tr>
           <td class="text-center">
           <input class="form-control clsEmployeeId" id="txtEmployeeId" type="text" id="employeeId"  value="' + mainList.EmployeeId + '"/>
           </td>
           <td class="text-center">
           <input class="form-control clsEmployeeName" id="txtEmployeeName" type="text" id="employeeName"  value="' + mainList.EmployeeName + '"/>
           </td>
           <td class="text-center">
           <input type="button" value="Detail" style="color: Red;" id="btnDetails" class="clsbtnDet" data-detail="'+ JSON.stringify(mainList.DetailList) + '"/>
           </td>
      </tr>
     });
}
</code>```

At the Button field you can pass a list through the data-* attribute which is used to store custom data.

After storing your secondary list details data, you could get that list in the button click event by the following code..

```<code>var detail_data = $(this).attr('data-detail'));

var json_detail=new Array();

json_detail = json_detail = JSON.parse(detail_data);   // Parse list data as JSON
</code>```

Then pass this "json_detail" list to a your modal function and use .each() loop onece again to fill up your modal.

Body:
I have a table like this

                <input class="form-control clsEmployeeId" id="txtEmployeeId" type="text" id="employeeId"  value="' + mainList.EmployeeId + '"/>

                <input class="form-control clsEmployeeName" id="txtEmployeeName" type="text" id="employeeName"  value="' + mainList.EmployeeName + '"/>

                <input type="button" value="Details" style="color: Red;" id="btnDetails" class="clsbtnDet"/>

What I want is to iterate a list and fill those fields and there is a secondary list of each row (Contains Employee Details) inside the main one and that secondary list data need to fill a modal which initiate by clicking the "Details "button.

Any help will be much appreciated.

Body:
You can use .each() loop function which allows you to loop item(row) one by one at a time. It will passes the index (an integer) and the actual element that you can
use like the following.

function primaryTable(list){

    $.each(list, function (i, mainList){
      <tr>
           <td class="text-center">
           <input class="form-control clsEmployeeId" id="txtEmployeeId" type="text" id="employeeId"  value="' + mainList.EmployeeId + '"/>
           </td>
           <td class="text-center">
           <input class="form-control clsEmployeeName" id="txtEmployeeName" type="text" id="employeeName"  value="' + mainList.EmployeeName + '"/>
           </td>
           <td class="text-center">
           <input type="button" value="Detail" style="color: Red;" id="btnDetails" class="clsbtnDet" data-detail="'+ JSON.stringify(mainList.DetailList) + '"/>
           </td>
      </tr>
     });
}

At the Button field you can pass a list through the data-* attribute which is used to store custom data.

After storing your secondary list details data, you could get that list in the button click event by the following code..

var detail_data = $(this).attr('data-detail'));

var json_detail=new Array();

json_detail = json_detail = JSON.parse(detail_data);   // Parse list data as JSON

Then pass this "json_detail" list to a your modal function and use .each() loop onece again to fill up your modal.


问:
npm start not refreshing new content on save on one computer, but is on another with almost exact same setup
I have my work computer which is a Windows 10 Pro and my laptop is a Windows 10 Home. Working on the same project on both: push and pull to Git. Learning React through Udemy. Both computers using Chrome. Both using Bash on Ubuntu on Windows with latest updates. Both using ConEmu for the console. Both npm -v = 3.10.10. Both node -v = 6.11.2. Hardware is different obviously, but not sure that is relevant and worth listing.

Anyway, this starter project I am playing around with, when I make changes to it and npm start is running, you can see activity in the console, hit refresh in the browser, and any changes made will be reflected.

On the laptop, this process does not work. Make change, save, no activity in console, refresh in browser does not reflect the changes. Have to restart npm start for changes to be reflected. A little irritating to say the least.

Anyway idea what might cause this? Really haven't come across anything in my Googling efforts.

答: For me, working in Windows, WSL2 caused this not to work. Running npm start in Command Prompt, not WSL solved this issue for me.


问:
How to wait for user action in separate Modal before continuing function execution?
I'm developing a drink counter app. User can add drinks but also has a drinkLimit state that is used to remind the user if the limit is reached when adding drinks. This reminder pops up in a modal with cancel and continue buttons when drink count has reached it's limit. The user can then either cancel the new drink addition or continue with it.

The problem is that I need to somehow wait or check for the user's action (clicking either "cancel" or "continue" in the modal), and based on that either return out of the addDrink function or continue the addition. I'm not sure how to implement that.

Using async/await seems intuitive but how can I await for a function when that function runs only after user clicks a button?

Using callbacks might be another solution but there as well I would need to halt the execution until user makes his action.

This seems like a common use case but I still can't seem to find any questions or tuts about this specific case.

App.tsx

```<code>const App = () => {
  const [drinklist, setDrinkList] = useState<DrinkType[]>();
  const [favorites, setFavorites] = useState<FavDrinkType[] | null>(null);
  const [drinkLimit, setDrinkLimit] = useState<number>();
  const [actionCalled, setActionCalled] = useState<string | null>();

const addDrink = (alcPercent: number, amount: number, name?: string) => {

    // if drink limit has been reached open reminder modal
    if (drinkLimit && drinklist) {
      if (drinklist?.length >= drinkLimit) {

        // how do I pause the execution here?
        const action = await openReminder();

        //cancel add
        if (action === 'cancel') {
          setShowReminder(false);
          return
        }
      }
    }

    // continue add

    setShowReminder(false);

    // *addition logic* (irrelevant)
  };

// Opens the modal (and waits for the user's action?)
const openReminder = async () => {
    setShowReminder(true);

  // should I wait for function handleActionCalled()?
}

// Modal calls this and sets state
const handleActionCalled = async (action: string) => {
    setActionCalled(action);
}

return (
      <View>
        <ReminderModal
          showModal={showReminder}
          handleActionCalled={handleActionCalled}
        />
      </View>
</code>```

ReminderModal.tsx:

```<code>const ReminderModal = ({
  showModal,
  handleActionCalled,
}: ReminderModalProps) => {

  const handleAction = (action: string) => {
    switch (action) {
      case 'cancel':
        return handleActionCalled('cancel');
      case 'continue':
        return handleActionCalled('continue');
    }
  };
  return (
    <Modal visible={showModal} animationType="slide" transparent={true}>
            <TouchableOpacity onPress={() => handleAction('cancel')}>
              <View>
                <Text>Cancel</Text>
              </View>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => handleAction('continue')}>
              <View>
                <Text>Continue</Text>
              </View>
            </TouchableOpacity>
    </Modal>
</code>```

答:
Seems you are overcomplicating the issue, you should break down your flow in multiple steps:

On first action => open modal if the addDrinks estimate that it reaches the limit. Should be the end of this function

a/ if hit cancel => trigger a
function that closes the modal

b/if hit continue trigger the
addDrinks function

I don't think you should include the opening of the modal as part of your addDrink function, or it should trigger a new flow but not await for an answer here.

Body:
I'm developing a drink counter app. User can add drinks but also has a drinkLimit state that is used to remind the user if the limit is reached when adding drinks. This reminder pops up in a modal with cancel and continue buttons when drink count has reached it's limit. The user can then either cancel the new drink addition or continue with it.

The problem is that I need to somehow wait or check for the user's action (clicking either "cancel" or "continue" in the modal), and based on that either return out of the addDrink function or continue the addition. I'm not sure how to implement that.

Using async/await seems intuitive but how can I await for a function when that function runs only after user clicks a button?

Using callbacks might be another solution but there as well I would need to halt the execution until user makes his action.

This seems like a common use case but I still can't seem to find any questions or tuts about this specific case.

App.tsx

const App = () => {
  const [drinklist, setDrinkList] = useState<DrinkType[]>();
  const [favorites, setFavorites] = useState<FavDrinkType[] | null>(null);
  const [drinkLimit, setDrinkLimit] = useState<number>();
  const [actionCalled, setActionCalled] = useState<string | null>();

const addDrink = (alcPercent: number, amount: number, name?: string) => {

    // if drink limit has been reached open reminder modal
    if (drinkLimit && drinklist) {
      if (drinklist?.length >= drinkLimit) {

        // how do I pause the execution here?
        const action = await openReminder();

        //cancel add
        if (action === 'cancel') {
          setShowReminder(false);
          return
        }
      }
    }

    // continue add

    setShowReminder(false);

    // *addition logic* (irrelevant)
  };

// Opens the modal (and waits for the user's action?)
const openReminder = async () => {
    setShowReminder(true);

  // should I wait for function handleActionCalled()?
}

// Modal calls this and sets state
const handleActionCalled = async (action: string) => {
    setActionCalled(action);
}

return (
      <View>
        <ReminderModal
          showModal={showReminder}
          handleActionCalled={handleActionCalled}
        />
      </View>

ReminderModal.tsx:

const ReminderModal = ({
  showModal,
  handleActionCalled,
}: ReminderModalProps) => {

  const handleAction = (action: string) => {
    switch (action) {
      case 'cancel':
        return handleActionCalled('cancel');
      case 'continue':
        return handleActionCalled('continue');
    }
  };
  return (
    <Modal visible={showModal} animationType="slide" transparent={true}>
            <TouchableOpacity onPress={() => handleAction('cancel')}>
              <View>
                <Text>Cancel</Text>
              </View>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => handleAction('continue')}>
              <View>
                <Text>Continue</Text>
              </View>
            </TouchableOpacity>
    </Modal>


问:
Preparing Android API for distribution
I'm developing an API for Android and it works great but I'm not sure how to package/distribute it. I've gotten the "meat" of the API into a jarfile - that's all the classes and an XML file in res/values/attrs.xml (I'm not sure if there's a way users can reference to that without having to copy my attrs.xml into their /values folder, but that's another question).

While trying my API in a test case, I've added my .jar to the build path and I can import a class successfully if I want to, but I don't want to :P My API allows users to implement a custom View into their own XML files, so nothing is instantiated in code.

The question: How can users reference to a custom View in my API? For example, if my View is called FooView and is in package com.myfoo, the following XML fails to load:

```<code><com.myfoo.FooView
android:layout_width="fill_parent"
android:layout_height="100dp"
/>
</code>```

答: Does this have to packaged into a jar , As i see facebook android sdk they give out the source code . I set it up as a new android project and from my android project reference this as library.In that case i am able to access all the apis exposed</p>

Title: Preparing Android API for distribution

Body:
I'm developing an API for Android and it works great but I'm not sure how to package/distribute it. I've gotten the "meat" of the API into a jarfile - that's all the classes and an XML file in res/values/attrs.xml (I'm not sure if there's a way users can reference to that without having to copy my attrs.xml into their /values folder, but that's another question).

While trying my API in a test case, I've added my .jar to the build path and I can import a class successfully if I want to, but I don't want to :P My API allows users to implement a custom View into their own XML files, so nothing is instantiated in code.

The question: How can users reference to a custom View in my API? For example, if my View is called FooView and is in package com.myfoo, the following XML fails to load:

<com.myfoo.FooView
android:layout_width="fill_parent"
android:layout_height="100dp"
/>


问:
Ruby 6 model validation for numericality: false
I'd like to make sure certain fields are populated only when the record has another flag set (and vice-versa). However my test is allowing the model to save even at points when I think it should fail.

```<code>class Measurement < ApplicationRecord

    validates :start_date, presence: true
    validates :end_date, presence: true
    validates :actual, numericality: true,    if: :is_baseline?      # baseline must have actual value
    validates :forecast, numericality: false, if: :is_baseline?      # baseline must not have forecast value
    validates :target, numericality: false,   unless: :is_target?    # only target can have target value
    validates :target, numericality: true,    if: :is_target?        # only target can have target value

    belongs_to :measure
    belongs_to :organisation

end
</code>```

First test that fails:

```<code>  test "can't create an invalid baseline measure" do

    measurement = @measure.measurements.new
    measurement.organisation = @organisation
    measurement.start_date   =  "2022-01-1"
    measurement.end_date     = "2022-01-31"
    measurement.is_baseline  = true
    measurement.actual       = 1000
    measurement.forecast     = 1000 # baseline should not have a forecast

    assert_not measurement.save, "Invalid Baseline Measurement saved"
  end
</code>```

Second test that fails

```<code>  test "can't create an invalid interval measure" do

    measurement = @measure.measurements.new
    measurement.organisation = @organisation
    measurement.start_date   =  "2022-01-1"
    measurement.end_date     = "2022-01-31"
    measurement.forecast     = 1000
    measurement.target       = 1000 # interval should not have a target

    assert_not measurement.save, "Invalid Interval Measurement saved"
  end
</code>```

Any idea why these tests are failing?

答:
This is not how these validations work. numericality: false doesn't validate the opposite but turns the validation off.

But instead, you can use the absence validator that checks that a value is not set:

```<code>validates :actual,   numericality: true, if: :is_baseline?      # baseline must have actual value
validates :forecast, absence: true,      if: :is_baseline?      # baseline must not have forecast value
validates :target,   absence: true,      unless: :is_target?    # only target can have target value
validates :target,   numericality: true, if: :is_target?        # only target can have target value
</code>```

Body:
I'd like to make sure certain fields are populated only when the record has another flag set (and vice-versa). However my test is allowing the model to save even at points when I think it should fail.

class Measurement < ApplicationRecord

    validates :start_date, presence: true
    validates :end_date, presence: true
    validates :actual, numericality: true,    if: :is_baseline?      # baseline must have actual value
    validates :forecast, numericality: false, if: :is_baseline?      # baseline must not have forecast value
    validates :target, numericality: false,   unless: :is_target?    # only target can have target value
    validates :target, numericality: true,    if: :is_target?        # only target can have target value

    belongs_to :measure
    belongs_to :organisation

end

First test that fails:

  test "can't create an invalid baseline measure" do

    measurement = @measure.measurements.new
    measurement.organisation = @organisation
    measurement.start_date   =  "2022-01-1"
    measurement.end_date     = "2022-01-31"
    measurement.is_baseline  = true
    measurement.actual       = 1000
    measurement.forecast     = 1000 # baseline should not have a forecast

    assert_not measurement.save, "Invalid Baseline Measurement saved"
  end

Second test that fails

  test "can't create an invalid interval measure" do

    measurement = @measure.measurements.new
    measurement.organisation = @organisation
    measurement.start_date   =  "2022-01-1"
    measurement.end_date     = "2022-01-31"
    measurement.forecast     = 1000
    measurement.target       = 1000 # interval should not have a target

    assert_not measurement.save, "Invalid Interval Measurement saved"
  end

Any idea why these tests are failing?

Body:
This is not how these validations work. numericality: false doesn't validate the opposite but turns the validation off.

But instead, you can use the absence validator that checks that a value is not set:

validates :actual,   numericality: true, if: :is_baseline?      # baseline must have actual value
validates :forecast, absence: true,      if: :is_baseline?      # baseline must not have forecast value
validates :target,   absence: true,      unless: :is_target?    # only target can have target value
validates :target,   numericality: true, if: :is_target?        # only target can have target value


问:
GADT with Type level Bool - making (&&) type operator imply constraints for its arguments
In summary I am trying to understand how I can tell ghc that a && b ~ True should imply that a ~ True and b ~ True within the context of a GADT.

Given a data constructor:

```<code>data Foo :: Bool -> * where
    ...
    Bar :: Foo j -> Foo k -> Foo (j && k)
    ...
</code>```

and, as an example, an instance for Eq (Foo True):

```<code>instance Eq (Foo True) where
   (Bar foo11 foo12) == (Bar foo21 foo22) = foo11 == ff21 && foo12 == foo22
   ....
</code>```

the compiler gives the following error:

```<code>Could not deduce: k1 ~ k
      from the context: 'True ~ (j && k)
        bound by a pattern with constructor:
                   Bar :: forall (j :: Bool) (k :: Bool).
                          Foo j -> Foo k -> Foo (j && k),
                 in an equation for `=='
        at Main.hs:12:4-14
      or from: 'True ~ (j1 && k1)
        bound by a pattern with constructor:
                   Bar :: forall (j :: Bool) (k :: Bool).
                          Foo j -> Foo k -> Foo (j && k),
                 in an equation for `=='
        at Main.hs:12:21-31
      `k1' is a rigid type variable bound by
        a pattern with constructor:
          Bar :: forall (j :: Bool) (k :: Bool).
                 Foo j -> Foo k -> Foo (j && k),
        in an equation for `=='
        at Main.hs:12:21-31
      `k' is a rigid type variable bound by
        a pattern with constructor:
          Bar :: forall (j :: Bool) (k :: Bool).
                 Foo j -> Foo k -> Foo (j && k),
        in an equation for `=='
        at Main.hs:12:4-14
      Expected type: Foo k
        Actual type: Foo k1
    * In the second argument of `(==)', namely `f22'
      In the second argument of `(&&)', namely `f12 == f22'
      In the expression: f11 == f21 && f12 == f22
    * Relevant bindings include
        f22 :: Foo k1 (bound at Main.hs:12:29)
        f12 :: Foo k (bound at Main.hs:12:12)
</code>```

(and an equivalent error for j and j1)

This is obviously complaining that it doesn't know that f12 :: Foo k and f22 :: Foo k1 have the same type.

Recently I have been using typelit-nat-normalise to solve what felt like a similar issue (with typenat addition), and I have searched for a similar library that may resolve these issues for bools - but to no avail.

I have found typelevel-rewrite-rules, which I think might enable me to write some kind of rewrite rule for this but I can't work out the syntax for telling the compiler that:

(a && b ~ True) implies (a ~ True) AND (b ~ True). Which I believe would solve this issue.

答:
I believe that such kind of "inversion" of a type family is impossible in current GHC, at least without unsafe functions.

Even with unsafe functions, I don't know if it is safe to add it. Kinds are weird beasts, and often contain more terms than one would expect. E.g. type family X :: Bool compiles, still we can not prove X ~ 'True nor X ~ 'False.

The code below does not fully answer the question, but I wanted to remark that, if we can add a few constraints to Foo so to carry a few singletons around, then we can write the wanted Eq instance.

The code below can probably be simplified further. Still, here it is. Below, I defined "conversion" functions fooT1, fooT2 to convince GHC that in Foo k and Foo j we do have k ~ j ~ 'True.

```<code>{-# LANGUAGE GADTs, ScopedTypeVariables, TypeApplications,
    DataKinds, TypeOperators, KindSignatures,
    FlexibleInstances, AllowAmbiguousTypes #-}
{-# OPTIONS -Wall #-}

import Data.Singletons
import Data.Singletons.Prelude.Bool

data Foo :: Bool -> * where
    Bar :: (SingI j, SingI k) =>
           Foo j -> Foo k -> Foo (j && k)

fooT1 :: forall a b. (SingI a, SingI b, (a && b) ~ 'True)
      => Foo a -> Foo b -> Foo 'True
fooT1 f _ = case (sing @a, sing @b) of
   (STrue, STrue) -> f

fooT2 :: forall a b. (SingI a, SingI b, (a && b) ~ 'True)
      => Foo a -> Foo b -> Foo 'True
fooT2 _ f = case (sing @a, sing @b) of
   (STrue, STrue) -> f

instance Eq (Foo 'True) where
   (Bar foo11 foo12) == (Bar foo21 foo22) =
      fooT1 foo11 foo12 == fooT1 foo21 foo22 &&
      fooT2 foo11 foo12 == fooT2 foo21 foo22
</code>```

Note that the pattern match (STrue, STrue) is exhaustive, and no warnings are raised by GHC.

Body:
In summary I am trying to understand how I can tell ghc that a && b ~ True should imply that a ~ True and b ~ True within the context of a GADT.

Given a data constructor:

data Foo :: Bool -> * where
    ...
    Bar :: Foo j -> Foo k -> Foo (j && k)
    ...

and, as an example, an instance for Eq (Foo True):

instance Eq (Foo True) where
   (Bar foo11 foo12) == (Bar foo21 foo22) = foo11 == ff21 && foo12 == foo22
   ....

the compiler gives the following error:

Could not deduce: k1 ~ k
      from the context: 'True ~ (j && k)
        bound by a pattern with constructor:
                   Bar :: forall (j :: Bool) (k :: Bool).
                          Foo j -> Foo k -> Foo (j && k),
                 in an equation for `=='
        at Main.hs:12:4-14
      or from: 'True ~ (j1 && k1)
        bound by a pattern with constructor:
                   Bar :: forall (j :: Bool) (k :: Bool).
                          Foo j -> Foo k -> Foo (j && k),
                 in an equation for `=='
        at Main.hs:12:21-31
      `k1' is a rigid type variable bound by
        a pattern with constructor:
          Bar :: forall (j :: Bool) (k :: Bool).
                 Foo j -> Foo k -> Foo (j && k),
        in an equation for `=='
        at Main.hs:12:21-31
      `k' is a rigid type variable bound by
        a pattern with constructor:
          Bar :: forall (j :: Bool) (k :: Bool).
                 Foo j -> Foo k -> Foo (j && k),
        in an equation for `=='
        at Main.hs:12:4-14
      Expected type: Foo k
        Actual type: Foo k1
    * In the second argument of `(==)', namely `f22'
      In the second argument of `(&&)', namely `f12 == f22'
      In the expression: f11 == f21 && f12 == f22
    * Relevant bindings include
        f22 :: Foo k1 (bound at Main.hs:12:29)
        f12 :: Foo k (bound at Main.hs:12:12)

(and an equivalent error for j and j1)

This is obviously complaining that it doesn't know that f12 :: Foo k and f22 :: Foo k1 have the same type.

Recently I have been using typelit-nat-normalise to solve what felt like a similar issue (with typenat addition), and I have searched for a similar library that may resolve these issues for bools - but to no avail.

I have found typelevel-rewrite-rules, which I think might enable me to write some kind of rewrite rule for this but I can't work out the syntax for telling the compiler that:

(a && b ~ True) implies (a ~ True) AND (b ~ True). Which I believe would solve this issue.

Body:
I believe that such kind of "inversion" of a type family is impossible in current GHC, at least without unsafe functions.

Even with unsafe functions, I don't know if it is safe to add it. Kinds are weird beasts, and often contain more terms than one would expect. E.g. type family X :: Bool compiles, still we can not prove X ~ 'True nor X ~ 'False.

The code below does not fully answer the question, but I wanted to remark that, if we can add a few constraints to Foo so to carry a few singletons around, then we can write the wanted Eq instance.

The code below can probably be simplified further. Still, here it is. Below, I defined "conversion" functions fooT1, fooT2 to convince GHC that in Foo k and Foo j we do have k ~ j ~ 'True.

{-# LANGUAGE GADTs, ScopedTypeVariables, TypeApplications,
    DataKinds, TypeOperators, KindSignatures,
    FlexibleInstances, AllowAmbiguousTypes #-}
{-# OPTIONS -Wall #-}

import Data.Singletons
import Data.Singletons.Prelude.Bool

data Foo :: Bool -> * where
    Bar :: (SingI j, SingI k) =>
           Foo j -> Foo k -> Foo (j && k)

fooT1 :: forall a b. (SingI a, SingI b, (a && b) ~ 'True)
      => Foo a -> Foo b -> Foo 'True
fooT1 f _ = case (sing @a, sing @b) of
   (STrue, STrue) -> f

fooT2 :: forall a b. (SingI a, SingI b, (a && b) ~ 'True)
      => Foo a -> Foo b -> Foo 'True
fooT2 _ f = case (sing @a, sing @b) of
   (STrue, STrue) -> f

instance Eq (Foo 'True) where
   (Bar foo11 foo12) == (Bar foo21 foo22) =
      fooT1 foo11 foo12 == fooT1 foo21 foo22 &&
      fooT2 foo11 foo12 == fooT2 foo21 foo22

Note that the pattern match (STrue, STrue) is exhaustive, and no warnings are raised by GHC.


问:
Avoid & Count non-numerical values computing basic statistics in Mathematica
Please consider:

```<code>dalist={{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
       {2.88`, 2.04`, 4.64`,0.56`, 4.92`, 2.06`, 3.46`, 2.68`, 2.72`,0.820},
       {"Laura1", "Laura1", "Laura1", "Laura1", "Laura1",
       "Laura1", "Laura1", "Laura1", "Laura1","Laura1"},
       {"RIGHT", 0, 1, 15.1`, 0.36`, 505, 20.059375`,15.178125`, ".", "."}}
</code>```

The actual dataset is about 6 000 rows and 147 columns. However the above reflects its content. I would like to compute some basic statistics, such as the mean. My attempt:

```<code>Table[Mean@dalist[[colNO]], {colNO, 1, 4}]
</code>```

How could I create a function such as to:

Avoid non-numerical values and

Count the number of non numerical values found in each lists.

I have not succeeded in finding the right pattern mechanism yet.

答:
First observation: you could use Mean /@ dalist if you wanted to average across rows. You don't need a Table function here.

Try using Cases (documentation), eg. Mean /@ (Cases[#,_?NumericQ] & /@ dalist)

If you want to be tricky and eliminate rows from your data that have no numeric elements (eg your third column), try the following. It first picks only the rows that have some numeric elements, and then takes only the numeric elements from those rows.

```<code>Mean /@ (Cases[#,_?NumericQ] & /@ (Cases[dalist, {___,_?NumericQ,___}]))
</code>```

To count the non-numeric elements, you would use a similar approach:

```<code>Length /@ (Cases[#,Except[_?NumericQ]] & /@ dalist)
</code>```

This answer has the caveat that I typed it out without the benefit of a Mathematica installation to actually check my syntax. Some typos could remeain.

Body:
Please consider:

dalist={{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
       {2.88`, 2.04`, 4.64`,0.56`, 4.92`, 2.06`, 3.46`, 2.68`, 2.72`,0.820},
       {"Laura1", "Laura1", "Laura1", "Laura1", "Laura1",
       "Laura1", "Laura1", "Laura1", "Laura1","Laura1"},
       {"RIGHT", 0, 1, 15.1`, 0.36`, 505, 20.059375`,15.178125`, ".", "."}}

The actual dataset is about 6 000 rows and 147 columns. However the above reflects its content. I would like to compute some basic statistics, such as the mean. My attempt:

Table[Mean@dalist[[colNO]], {colNO, 1, 4}]

How could I create a function such as to:

Avoid non-numerical values and

Count the number of non numerical values found in each lists.

I have not succeeded in finding the right pattern mechanism yet.

Body:
First observation: you could use Mean /@ dalist if you wanted to average across rows. You don't need a Table function here.

Try using Cases (documentation), eg. Mean /@ (Cases[#,_?NumericQ] & /@ dalist)

If you want to be tricky and eliminate rows from your data that have no numeric elements (eg your third column), try the following. It first picks only the rows that have some numeric elements, and then takes only the numeric elements from those rows.

Mean /@ (Cases[#,_?NumericQ] & /@ (Cases[dalist, {___,_?NumericQ,___}]))

To count the non-numeric elements, you would use a similar approach:

Length /@ (Cases[#,Except[_?NumericQ]] & /@ dalist)

This answer has the caveat that I typed it out without the benefit of a Mathematica installation to actually check my syntax. Some typos could remeain.


问:
Prevent updated_at and created_at from being hacked in postgresql
Let's say I have:

posts

id
created_at
updated_at
...

The default value for created_at is now(), and I have a trigger for updated_at like so:

create trigger posts_updated_at before update on posts
for each row execute procedure moddatetime (updated_at);
```
<p>How do I prevent everyone from updating the dates manually?</p>
<ul>
<li>created_at</li>
<li>updated_at</li>
</ul>
<p>I imagine there is a standard way to protect these field (column level security maybe)?</p>
<p>Something like this...</p>
<pre class="lang-sql prettyprint-override"><code>CREATE POLICY no_date_change ON posts
    FOR UPDATE
    USING (created_at === created_at);
</code>```

Either created_at does not change or created_at before = created_at after?

What is the standard way to protect these fields?

J

答:
I have a trigger for updated_at

So you have a trigger that sets updated_at. So there's already no way for anybody to update this field, as the trigger will overwrite it.

Then you just need additional check in the trigger - something like if OLD.created_at<>NEW.created_at then raise ERROR.

I'd also run similar trigger on CREATE, to force created_at and updated_at also while creating rows.

Body:
Let's say I have:

posts

id
created_at
updated_at
...

The default value for created_at is now(), and I have a trigger for updated_at like so:

create trigger posts_updated_at before update on posts
for each row execute procedure moddatetime (updated_at);

How do I prevent everyone from updating the dates manually?

created_at

updated_at

I imagine there is a standard way to protect these field (column level security maybe)?

Something like this...

CREATE POLICY no_date_change ON posts
    FOR UPDATE
    USING (created_at === created_at);

Either created_at does not change or created_at before = created_at after?

What is the standard way to protect these fields?

J


问:
Discord.js V13 -- Store persisting hidden data on the message object
I have coded a bot to send a message response to a given command, !a. I want to store additional data on the message object, so that if the user reacts to that message the bot can read the hidden data property and know the original message resulted from !a.

Ideas I had:

Create a custom property on the message object: Message.Custom_Prop

Hijack an unused property: Maybe Message.webhookId?

Store hidden text in the form of an embed or message content.

I haven't been able to get any of these to work though.

答:
The best way that I can think of is to store an array of message IDs that were triggered by !a. Something like this:

```<code>// At the start of your script
const commandResponses = [];

// Logic for sending the command response
message.channel.send("response here").then(msg => commandResponses.push(msg.id));

// Checking whether the message was a response
if (commandResponses.includes(reaction.message.id)) {
  // It's a response so do stuff here
}
</code>```

(Not tested so it's possible that this won't work)

Body:
The best way that I can think of is to store an array of message IDs that were triggered by !a. Something like this:

// At the start of your script
const commandResponses = [];

// Logic for sending the command response
message.channel.send("response here").then(msg => commandResponses.push(msg.id));

// Checking whether the message was a response
if (commandResponses.includes(reaction.message.id)) {
  // It's a response so do stuff here
}

(Not tested so it's possible that this won't work)