问:
How can you convert apostrophe type in PHP? Wrong one being echoed
Basically I've got an array in PHP I'm looping through and outputting to an HTML text area. The data going in contains a list of strings, some of which use apostrophe's. EG: "Item One's Data", "Item Two Data", "Item Three's Data"....etc. The apostrophe being used are correct going in. But when they get outputted into the text area they change from the correct ' type to the incorrect ’ type. (they look VERY similar here but they are different characters).

I've tried using a variety of different things to swap these out such as str_replace, preg_replace, htmlspecialchars and mb_convert_encoding. None of which work. Either they are unable to find the ’ or even after it's replaced with a ' it still comes out as ’

My closest guess is an encoding issue. Because even after using mb_convert_encoding, when I check the result with mb_detect_encoding it still shows as ASCII type.

The html page does have this at the top:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Any insight for how I can force the use of the correct apostrophe format/encoding would be appreciated.

答:
SOLUTION Turns out this appears to be a problem with Wordpress Smart or Curly Quotes changing the characters.

Was able to solve the issue by adding this to the theme functions file and/or in the plugin file.

add_filter( 'run_wptexturize', '__return_false' );


来源: stackexchange

问:
Regex to match a word only when the line starts with a certain string
I want to make a Regex to match something only when the line starts with a given string. Given the following two lines, I want to match width and height only in the 1st string:

frame at x1 y1 width 50 height 200
 rectangle at x1 y1 width 50 height 200

The closest I got was this:

(?<=frame\s).*(width|height)

But this expression is matching everything between frame and 200

I'm using https://rubular.com/ to test it.

答:
You can try this
\Aframe.*width\s(?<width>\d+)\sheight\s(?<height>\d+)\z

In ruby, the result would like

ContentLicense: CC BY-SA 4.0


问:
Is using output buffering considered a bad practice?
Are ob_start / ob_get_clean() considered bad practice by php programmers in general?

Are there any disadvantages of output buffering?

答:
Surely output buffering means that content which could have been sent to the browser immediately is now sticking around on the server, which is taking up extra memory (a very important issue if you're dealing with high scalability) so if your program is then taking a while to execute, this memory overhead would impair performance.

I don't know PHP well enough to say if this is true or if it even frees the memory when you don't use buffering, but that is usually the theory.

ContentLicense: CC BY-SA 3.0


答:
```<code>r = /\Aframe\b.*\swidth\s+(\d+)\s+height\s+(\d+)/
</code>```

```<code>"frame at x1 y1 width 50 height 200".scan(r).flatten
  #=> ["50", "200"]
"rectangle at x1 y1 width 50 height 200".scan(r).flatten
  #=> []
"framer at x1 y1 width 50 height 200".scan(r).flatten
  #=> []
"frame at x1 y1 bandwidth 50 height 200".scan(r).flatten
  #=> []
"frame at x1 y1 width 50 midheight 200".scan(r).flatten
  #=> []
</code>```

Title: Regex to match a word only when the line starts with a certain string

Body:
I want to make a Regex to match something only when the line starts with a given string. Given the following two lines, I want to match width and height only in the 1st string:

frame at x1 y1 width 50 height 200
 rectangle at x1 y1 width 50 height 200

The closest I got was this:

(?<=frame\s).*(width|height)

But this expression is matching everything between frame and 200

I'm using https://rubular.com/ to test it.

Body:
r = /\Aframe\b.*\swidth\s+(\d+)\s+height\s+(\d+)/

"frame at x1 y1 width 50 height 200".scan(r).flatten
  #=> ["50", "200"]
"rectangle at x1 y1 width 50 height 200".scan(r).flatten
  #=> []
"framer at x1 y1 width 50 height 200".scan(r).flatten
  #=> []
"frame at x1 y1 bandwidth 50 height 200".scan(r).flatten
  #=> []
"frame at x1 y1 width 50 midheight 200".scan(r).flatten
  #=> []


问:
What would be consider as my local scope in this function?
just wondering what would be considered as my local scope in this function? Just a tad confused.</p>

```<code>function hello(name, age) {
    var message = name + ", who is " + age + " years old, says hi!";

    return function sayHello() {
        console.log(message);
    };
}

var sayHelloToJohn = hello("John", 33);

sayHelloToJohn();

</code>```

答:
If I understand you mean correctly, in your case, message and sayHello are local variable/function. That means they cannot be assigned from the outside hello function.

But notice that, if you remove var keyword from

```<code>var message = name + ", who is " + age + " years old, says hi!";
</code>```

it can be assigned from the outside of hello function. Same to sayHello function:

function hello(name, age) {
    message = name + ", who is " + age + " years old, says hi!";

    sayHello = function () {
        console.log(message);
    };

    return sayHello;
}

var sayHelloToJohn = hello("John", 33);

sayHelloToJohn();
console.log(message);
sayHello();```

Body:
just wondering what would be considered as my local scope in this function? Just a tad confused.

function hello(name, age) {
    var message = name + ", who is " + age + " years old, says hi!";

    return function sayHello() {
        console.log(message);
    };
}

var sayHelloToJohn = hello("John", 33);

sayHelloToJohn();

Body:
If I understand you mean correctly, in your case, message and sayHello are local variable/function. That means they cannot be assigned from the outside hello function.

But notice that, if you remove var keyword from

var message = name + ", who is " + age + " years old, says hi!";

it can be assigned from the outside of hello function. Same to sayHello function:

function hello(name, age) {
    message = name + ", who is " + age + " years old, says hi!";

    sayHello = function () {
        console.log(message);
    };

    return sayHello;
}

var sayHelloToJohn = hello("John", 33);

sayHelloToJohn();
console.log(message);
sayHello();


问:
How to get the IP address of a client request in an Aqueduct Dart server
I'm making an Aqueduct server. I'd like to know the IP address of the client request for monitoring logs and for providing general location based content.

In Aqueduct I don't see how to get the IP address.

I was going to say that I tried X, Y, and Z and that didn't work, but I just found the answer so I will add it below.

答:
In your controller you can get the IP address from the Request.

```<code>String ipAddress = request.connectionInfo.remoteAddress.address;
</code>```

Note that if your server is running behind an nginx proxy then you will have to configure nxinx to forward the real IP to Aqueduct. To do that you can add the X-Real-IP header with the remote address to your proxied API location in the server block.

```<code>location /api {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://127.0.0.1:8888;
    proxy_http_version 1.1;
}
</code>```

Then in Aqueduct you can get the IP address from the raw headers:

```<code>String ipAddress = request.raw.headers['x-real-ip'].first;
</code>```

More info here:

Documentation: Passing Request Headers

Setting up an Nginx Reverse Proxy

Get user real ip in nginx behind nginx reverse proxy

Forwarding Visitor’s Real-IP + Nginx Proxy/Fastcgi backend correctly

Body:
In your controller you can get the IP address from the Request.

String ipAddress = request.connectionInfo.remoteAddress.address;

Note that if your server is running behind an nginx proxy then you will have to configure nxinx to forward the real IP to Aqueduct. To do that you can add the X-Real-IP header with the remote address to your proxied API location in the server block.

location /api {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://127.0.0.1:8888;
    proxy_http_version 1.1;
}

Then in Aqueduct you can get the IP address from the raw headers:

String ipAddress = request.raw.headers['x-real-ip'].first;

More info here:

Documentation: Passing Request Headers

Setting up an Nginx Reverse Proxy

Get user real ip in nginx behind nginx reverse proxy

Forwarding Visitor’s Real-IP + Nginx Proxy/Fastcgi backend correctly


答:
Is using match groups an option? In your example, the full match is at x1 y1 width 50 height, but the match group is just width. What do you want to capture, the values for width and height?

If you know the format of the strings (as in, width is always before height), then you can have a regex like this:

/\Aframe.*width (?<width>\d+).*height (?<height>\d+)/
```


问:
Should you check before setting a Django model's field?
I have a background service that imports django, and uses my django project's ORM directly.

It monitors something, in a loop, very often - every few seconds.
It goes through every user in my database, checks a condition, and based on that, sets a flag to either be True or False. I might have thousands of users in the database, so the efficiency here can add up.

```<code>while True:
    time.sleep(5)
    for user in User.objects.all():
        if user.check():
            user.flag = True
        else:
            user.flag = False
        user.save()
</code>```

I'm using MySQL as my database.

What I'm curious about is this: if a particular user has .flag set to True, am I doing a disk write every time I run user.flag = True; user.save(), even though nothing changed? Or is Django or MySQL smart enough not to do a disk write if nothing changed?

I assume a MySQL read operation is less expensive than a write operation. Would it make more sense to check the value of user.flag, and only try to set user.flag if the value actually changed? This would essentially be exchanging a database read for a database write, from what I understand (except in cases where something actually changed, in which case, first a read is performed, and then a write).

Note: This is just a basic example. I'm not actually dealing with users.

答:
If you can move the logic of check into a .filter() clause, that would be best. That way you could do:

```<code>User.objects.filter(match_check, flag=False).update(flag=True)
User.objects.filter(~Q(match_check), flag=True).update(flag=False)
</code>```

Or if you could annotate the value:

```<code>User.objects.annotate(
    new_flag=some_check,
).exclude(flag=F('new_flag')).update(flag= ('new_flag'))
</code>```

Otherwise if you can't then maybe do it like this:

```<code>new_flag = user.check()
if new_flag != user.flag:
    user.flag = new_flag
    user.save(update_fields=['flag']) # This will only update that single column.
</code>```

Body:
I have a background service that imports django, and uses my django project's ORM directly.

It monitors something, in a loop, very often - every few seconds.
It goes through every user in my database, checks a condition, and based on that, sets a flag to either be True or False. I might have thousands of users in the database, so the efficiency here can add up.

while True:
    time.sleep(5)
    for user in User.objects.all():
        if user.check():
            user.flag = True
        else:
            user.flag = False
        user.save()

I'm using MySQL as my database.

What I'm curious about is this: if a particular user has .flag set to True, am I doing a disk write every time I run user.flag = True; user.save(), even though nothing changed? Or is Django or MySQL smart enough not to do a disk write if nothing changed?

I assume a MySQL read operation is less expensive than a write operation. Would it make more sense to check the value of user.flag, and only try to set user.flag if the value actually changed? This would essentially be exchanging a database read for a database write, from what I understand (except in cases where something actually changed, in which case, first a read is performed, and then a write).

Note: This is just a basic example. I'm not actually dealing with users.

Body:
If you can move the logic of check into a .filter() clause, that would be best. That way you could do:

User.objects.filter(match_check, flag=False).update(flag=True)
User.objects.filter(~Q(match_check), flag=True).update(flag=False)

Or if you could annotate the value:

User.objects.annotate(
    new_flag=some_check,
).exclude(flag=F('new_flag')).update(flag= ('new_flag'))

Otherwise if you can't then maybe do it like this:

new_flag = user.check()
if new_flag != user.flag:
    user.flag = new_flag
    user.save(update_fields=['flag']) # This will only update that single column.


问:
How to return number-loops in String? [Java]
I am practicing some exercises of java and I got some problems in returning this in String as asked in the question.

"Write nested for-loops to produce the following output from the given
  input n."

Can someone help me to return this same logic in String? [Java]

```<code>public String numberLoops(int n) {
    int n = 8;
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < n; j++) {
            if (j < n - i) {
                System.out.print(".");
            } else if (j == j) {
                System.out.print(i);
            }

        }
        if (i < n) {
            System.out.print("");
        }
        System.out.println();
    }
    return null;
}
</code>```

答:
Won't just give you the finished code because, well, what fun would that be?  But here are some hints.

Basically what you want to do is collect your results in a StringBuilder instance instead of printing them, and then obtain the final String result from the StringBuilder.  If sb is your StringBuilder instance, you can map your I/O operations to StringBuilder operations roughly as follows:

System.out.print(x) => sb.append(x)

System.out.println(x) => sb.append(x).append('\n')

System.out.println() => sb.append('\n')

When you're done, sb.toString() will give you the String version of the result you've constructed in sb.

Body:
I am practicing some exercises of java and I got some problems in returning this in String as asked in the question.

"Write nested for-loops to produce the following output from the given
  input n."

Can someone help me to return this same logic in String? [Java]

public String numberLoops(int n) {
    int n = 8;
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < n; j++) {
            if (j < n - i) {
                System.out.print(".");
            } else if (j == j) {
                System.out.print(i);
            }

        }
        if (i < n) {
            System.out.print("");
        }
        System.out.println();
    }
    return null;
}


问:
Tensorflow: save the model with smallest validation error
I ran a training job with tensorflow and got the following curve for loss on validation set. The net starts to overfit after 6000-th iteration. So I'd like to get the model before overfitting.

My training code is something like below:

```<code>train_step = ......
summary = tf.scalar_summary(l1_loss.op.name, l1_loss)
summary_writer = tf.train.SummaryWriter("checkpoint", sess.graph)
saver = tf.train.Saver()
for i in xrange(20000):
    batch = get_next_batch(batch_size)
    sess.run(train_step, feed_dict = {x: batch.x, y:batch.y})
    if (i+1) % 100 == 0:
        saver.save(sess, "checkpoint/net", global_step = i+1)
        summary_str = sess.run(summary, feed_dict=validation_feed_dict)
        summary_writer.add_summary(summary_str, i+1)
        summary_writer.flush()
</code>```

After training finishes, there is only five checkpoints saved (19600, 19700, 19800, 19900, 20000). Is there any way to let tensorflow save checkpoint according to the validation error?

P.S. I know that tf.train.Saver has a max_to_keep argument, which in principal could save all the checkpoints. But that's not I wanted (unless it's the only option). I want the saver keep the checkpoint with the smallest validation loss so far. Is that possible?

答:
This can be done with checkpoints.  In tensorflow 1:

```<code># you should import other functions/libs as needed to build the model

from keras.callbacks.callbacks import ModelCheckpoint

# add checkpoint to save model with lowest val loss
filepath = 'tf1_mnist_cnn.hdf5'
save_checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, \
                             save_best_only=True, save_weights_only=False, \
                             mode='auto', period=1)

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test),
          callbacks=[save_checkpoint])
</code>```

Tensorflow 2:

```<code># import other libs as needed for building model
from tensorflow.keras.callbacks import ModelCheckpoint

# add a checkpoint to save the lowest validation loss
filepath = 'tf2_mnist_model.hdf5'

checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, \
                             save_best_only=True, save_weights_only=False, \
                             mode='auto', save_frequency=1)

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test),
          callbacks=[checkpoint])
</code>```

Complete demo files are here: https://github.com/nateGeorge/slurm_gpu_ubuntu/tree/master/demo_files.

Body:
I ran a training job with tensorflow and got the following curve for loss on validation set. The net starts to overfit after 6000-th iteration. So I'd like to get the model before overfitting.

My training code is something like below:

train_step = ......
summary = tf.scalar_summary(l1_loss.op.name, l1_loss)
summary_writer = tf.train.SummaryWriter("checkpoint", sess.graph)
saver = tf.train.Saver()
for i in xrange(20000):
    batch = get_next_batch(batch_size)
    sess.run(train_step, feed_dict = {x: batch.x, y:batch.y})
    if (i+1) % 100 == 0:
        saver.save(sess, "checkpoint/net", global_step = i+1)
        summary_str = sess.run(summary, feed_dict=validation_feed_dict)
        summary_writer.add_summary(summary_str, i+1)
        summary_writer.flush()

After training finishes, there is only five checkpoints saved (19600, 19700, 19800, 19900, 20000). Is there any way to let tensorflow save checkpoint according to the validation error?

P.S. I know that tf.train.Saver has a max_to_keep argument, which in principal could save all the checkpoints. But that's not I wanted (unless it's the only option). I want the saver keep the checkpoint with the smallest validation loss so far. Is that possible?

Body:
This can be done with checkpoints.  In tensorflow 1:

# you should import other functions/libs as needed to build the model

from keras.callbacks.callbacks import ModelCheckpoint

# add checkpoint to save model with lowest val loss
filepath = 'tf1_mnist_cnn.hdf5'
save_checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, \
                             save_best_only=True, save_weights_only=False, \
                             mode='auto', period=1)

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test),
          callbacks=[save_checkpoint])

Tensorflow 2:

# import other libs as needed for building model
from tensorflow.keras.callbacks import ModelCheckpoint

# add a checkpoint to save the lowest validation loss
filepath = 'tf2_mnist_model.hdf5'

checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, \
                             save_best_only=True, save_weights_only=False, \
                             mode='auto', save_frequency=1)

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test),
          callbacks=[checkpoint])

Complete demo files are here: https://github.com/nateGeorge/slurm_gpu_ubuntu/tree/master/demo_files.


问:
How to apply App.vue extension in IntelliJ
I use IntelliJ.
I want to App.vue file to apply to Vue template.
Why don't be applied only App.vue? Help me please.

答:
I solved problem.

enter image description here


问:
Do different/older processors run c++ code differently?
I was coding a function that loops through a 2d array, if the current element in the array is less than the element next to it, then I would add 1 to my int counter variable. The issue is, when I run the code on my windows based machine with a AMD ryzen 7 processor, it works correctly and the counter gets to 20 (on a 5x5 array). But when I run it on my 2014 Macbook with a intel core i5 processor, on both MacOS and Windows 10 (bootcamp) the counter only gets to 19 using the same exact block of code. Here is my loop

```<code>int counter = 0;
for(int i=0; i < ROWS; i++){
    for(int j=0; j < COLUMNS; j++){
        if(board[i][j] < board[i][j + 1]){
            counter += 1;
        }
    }
}
</code>```

I would think this would work in any situation.

答:
Well it would be nice to have a minimal reproducible example like others said, I think I can see it from here.

using j+1 will let the index go out of bounds causing undefined behaviour.

Try :

for(int i=0; i < ROWS; i++){
  for(int j=0; j < COLUMNS - 1; j++){
    if(board[i][j] < board[i][j + 1]){
      counter += 1;
    }
  }
}
```

This should avoid that problem by simply stopping one sooner

Body:
I was coding a function that loops through a 2d array, if the current element in the array is less than the element next to it, then I would add 1 to my int counter variable. The issue is, when I run the code on my windows based machine with a AMD ryzen 7 processor, it works correctly and the counter gets to 20 (on a 5x5 array). But when I run it on my 2014 Macbook with a intel core i5 processor, on both MacOS and Windows 10 (bootcamp) the counter only gets to 19 using the same exact block of code. Here is my loop

int counter = 0;
for(int i=0; i < ROWS; i++){
    for(int j=0; j < COLUMNS; j++){
        if(board[i][j] < board[i][j + 1]){
            counter += 1;
        }
    }
}

I would think this would work in any situation.

Body:
Well it would be nice to have a minimal reproducible example like others said, I think I can see it from here.

using j+1 will let the index go out of bounds causing undefined behaviour.

Try :

for(int i=0; i < ROWS; i++){
  for(int j=0; j < COLUMNS - 1; j++){
    if(board[i][j] < board[i][j + 1]){
      counter += 1;
    }
  }
}

This should avoid that problem by simply stopping one sooner


问:
Flutter - Stream error not persisting (using bloc pattern)
So I am trying to make a signup form in flutter using streams and the bloc pattern.

The problem is that the error added to the sink for one my streams does not seem to persist?

The submitValid getter does not seem to consider the error added to the passwordretype stream, this causes the login button to be clickable when it shouldn't

Steps to reproduce:

Fill out a valid email

Fill out a valid password (password field)

Fill out a valid password (password retype field)

Delete everything from the retype field

Delete everything from the password field.

Type a valid password in the password field and the login button appears clickable even though the retype field is empty.

Here's my code along with a screenshot.

Bloc.dart

```<code>import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';

import 'validators.dart';
import 'dart:io';
import 'package:rxdart/rxdart.dart';

class Bloc extends Object with Validators {

  final _email = BehaviorSubject<String>();
  final _password = BehaviorSubject<String>();
  final _passwordretype = BehaviorSubject<String>();
  final _isSignedIn = BehaviorSubject<bool>();

  //Add data to stream
  Stream<String> get email => _email.stream.transform(validateEmail);
  Stream<String> get password => _password.stream.transform(validatePassword);

  Stream<String> get passwordretype=> _passwordretype.stream.transform(validatePasswordRetype)
  .doOnData((String c){
    if(0 != _password.value.compareTo(c)){
      _passwordretype.addError("Passwords do not match");
    }
  });

  Stream<bool> get signInStatus => _isSignedIn.stream;

  Stream<bool> get submitValid =>
    Rx.combineLatest3(email, password, passwordretype, (e, p, r) => true);

  //Change data
  Function(String) get changeEmail => _email.sink.add;
  Function(String) get changePassword => _password.sink.add;
  Function(String) get changePasswordRetype => _passwordretype.sink.add;
  Function(bool) get showProgressBar => _isSignedIn.add;

  register() async {

    final FirebaseAuth _auth = FirebaseAuth.instance;

    try {
      showProgressBar(true);
      final FirebaseUser user = (await _auth.createUserWithEmailAndPassword(
        email: _email.value,
        password: _password.value,
      ))
          .user;
      if (user != null) {
//        setState(() {
//          _success = true;
//          _userEmail = user.email;
//          Navigator.of(context).pushNamedAndRemoveUntil(
//              '/home', (Route<dynamic> route) => false);
//
////        Navigator.of(context).pushReplacementNamed('/home');
//
//        });
      } else {
//        Scaffold.of(context).showSnackBar(SnackBar(
//          content: Text("Error occured, please try again later"),
//        ));
//        _success = false;
      }
    } catch (err) {
      _isSignedIn.addError(err);
      print(err);
//      setState(() {
//        _showLoading = false;
//        _error = true;
//      });
    }

  }

  dispose() {
    _email.drain();
    _email.close();
    _password.drain();
    _password.close();
    _passwordretype.drain();
    _passwordretype.close();
  }

}
</code>```

SignupScreen.dart

```<code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:lendy/src/blocs/bloc.dart';
import 'package:lendy/src/blocs/provider.dart';

class SignupScreen extends StatelessWidget {
//  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
//  final TextEditingController _emailController = TextEditingController();
//  final TextEditingController _passwordController = TextEditingController();
//  final TextEditingController _passwordController2 = TextEditingController();
  final FirebaseAuth _auth = FirebaseAuth.instance;
//  final GoogleSignIn _googleSignIn = GoogleSignIn();
  String _userID = "";

  bool _success;
  String _userEmail;

  @override
  Widget build(BuildContext context) {
    final bloc = Provider.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text("Signup"),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            emailField(bloc),
            passwordField(bloc),
            passwordFieldRe(bloc),
            SizedBox(
              height: 10.0,
            ),
            button(bloc)
          ],
        ),
      ),
    );
  }

  Widget emailField(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.email,
      builder: (context, snapshot) {
        return TextField(
          onChanged: bloc.changeEmail,
          keyboardType: TextInputType.emailAddress,
          decoration: InputDecoration(
              hintText: 'Enter email address',
              labelText: 'Email-address',
              errorText: snapshot.error),
        );
      },
    );
  }

  Widget passwordField(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.password,
        builder: (context, snapshot) {
          return TextField(
            onChanged: bloc.changePassword,
            decoration: InputDecoration(
                hintText: 'Enter password',
                labelText: 'Password',
                errorText: snapshot.error),
          );
        });
  }

  Widget passwordFieldRe(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.passwordretype,
        builder: (context, snapshot) {
          return TextField(
            onChanged: bloc.changePasswordRetype,
            decoration: InputDecoration(
                hintText: 'Retype password',
                labelText: 'Password',
                errorText: snapshot.error),
          );
        });
  }

  Widget button(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot) {
        return RaisedButton(
            child: Text('Register'),
            color: Colors.blue,
            //if true
            onPressed: snapshot.hasData
                ? () {
//            bloc.showProgressBar(true);
                    bloc.register();
                  }
                : null);
      },
    );
  }

  Widget buttons(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot1) {
        return StreamBuilder(
          stream: bloc.signInStatus,
          builder: (context, snapshot2) {
            if (!snapshot2.hasData || snapshot2.hasError) {
              return Column(
                children: <Widget>[
                  RaisedButton(
                    child: Text('Register'),
                    color: Colors.blue,
                    onPressed: snapshot1.hasData
                        ? () {
                      bloc.register();
                    }
                        : null,
                  ),
                  snapshot2.hasError ? Text("ee") : Container()
                ],
              );
            } else {
              return CircularProgressIndicator();
            }
          },
        );
      },
    );
  }

  Widget submitButton(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.signInStatus,
        builder: (context, snapshot) {
          if (snapshot.hasError || !snapshot.hasData) {
            return buttons(bloc);
          } else {
            return CircularProgressIndicator();
          }
        });

  }

/
</code>```

Validators.dart

```<code>import 'dart:async';

class Validators {

  final validateEmail = StreamTransformer<String, String>.fromHandlers(
      handleData: (email, sink){
        if (RegExp(
        r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
        .hasMatch(email)){
          sink.add(email);
        } else {
          sink.addError('Please enter a valid email address.');
        }
      }
  );

  final validatePassword = StreamTransformer<String, String>.fromHandlers(
      handleData: (password, sink){
        if (password.length > 3){
          sink.add(password);
        } else {
          sink.addError('Password is too short.');
        }
      }
  );

  final validatePasswordRetype = StreamTransformer<String, String>.fromHandlers(
      handleData: (password, sink){
        print("HANDLE DATA");
        if (password.length > 3){
          sink.add(password);
        } else {
          sink.addError('Password is too short.');
        }
      }
  );

}
</code>```

screenshot

答:
For the submitValid Stream you are using the BehaviorSubjects instead of use the stream.transforms, so for that reason, your submitValid doesn't receive the errors. Replace your submitValid with the next code:

Stream<bool> get submitValid => Rx.combineLatest3(email, password, passwordretype, (e, p, r) => true);

Body:
So I am trying to make a signup form in flutter using streams and the bloc pattern.

The problem is that the error added to the sink for one my streams does not seem to persist?

The submitValid getter does not seem to consider the error added to the passwordretype stream, this causes the login button to be clickable when it shouldn't

Steps to reproduce:

Fill out a valid email

Fill out a valid password (password field)

Fill out a valid password (password retype field)

Delete everything from the retype field

Delete everything from the password field.

Type a valid password in the password field and the login button appears clickable even though the retype field is empty.

Here's my code along with a screenshot.

Bloc.dart

import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';

import 'validators.dart';
import 'dart:io';
import 'package:rxdart/rxdart.dart';

class Bloc extends Object with Validators {

  final _email = BehaviorSubject<String>();
  final _password = BehaviorSubject<String>();
  final _passwordretype = BehaviorSubject<String>();
  final _isSignedIn = BehaviorSubject<bool>();

  //Add data to stream
  Stream<String> get email => _email.stream.transform(validateEmail);
  Stream<String> get password => _password.stream.transform(validatePassword);

  Stream<String> get passwordretype=> _passwordretype.stream.transform(validatePasswordRetype)
  .doOnData((String c){
    if(0 != _password.value.compareTo(c)){
      _passwordretype.addError("Passwords do not match");
    }
  });

  Stream<bool> get signInStatus => _isSignedIn.stream;

  Stream<bool> get submitValid =>
    Rx.combineLatest3(email, password, passwordretype, (e, p, r) => true);

  //Change data
  Function(String) get changeEmail => _email.sink.add;
  Function(String) get changePassword => _password.sink.add;
  Function(String) get changePasswordRetype => _passwordretype.sink.add;
  Function(bool) get showProgressBar => _isSignedIn.add;

  register() async {

    final FirebaseAuth _auth = FirebaseAuth.instance;

    try {
      showProgressBar(true);
      final FirebaseUser user = (await _auth.createUserWithEmailAndPassword(
        email: _email.value,
        password: _password.value,
      ))
          .user;
      if (user != null) {
//        setState(() {
//          _success = true;
//          _userEmail = user.email;
//          Navigator.of(context).pushNamedAndRemoveUntil(
//              '/home', (Route<dynamic> route) => false);
//
////        Navigator.of(context).pushReplacementNamed('/home');
//
//        });
      } else {
//        Scaffold.of(context).showSnackBar(SnackBar(
//          content: Text("Error occured, please try again later"),
//        ));
//        _success = false;
      }
    } catch (err) {
      _isSignedIn.addError(err);
      print(err);
//      setState(() {
//        _showLoading = false;
//        _error = true;
//      });
    }

  }

  dispose() {
    _email.drain();
    _email.close();
    _password.drain();
    _password.close();
    _passwordretype.drain();
    _passwordretype.close();
  }

}

SignupScreen.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:lendy/src/blocs/bloc.dart';
import 'package:lendy/src/blocs/provider.dart';

class SignupScreen extends StatelessWidget {
//  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
//  final TextEditingController _emailController = TextEditingController();
//  final TextEditingController _passwordController = TextEditingController();
//  final TextEditingController _passwordController2 = TextEditingController();
  final FirebaseAuth _auth = FirebaseAuth.instance;
//  final GoogleSignIn _googleSignIn = GoogleSignIn();
  String _userID = "";

  bool _success;
  String _userEmail;

  @override
  Widget build(BuildContext context) {
    final bloc = Provider.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text("Signup"),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            emailField(bloc),
            passwordField(bloc),
            passwordFieldRe(bloc),
            SizedBox(
              height: 10.0,
            ),
            button(bloc)
          ],
        ),
      ),
    );
  }

  Widget emailField(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.email,
      builder: (context, snapshot) {
        return TextField(
          onChanged: bloc.changeEmail,
          keyboardType: TextInputType.emailAddress,
          decoration: InputDecoration(
              hintText: 'Enter email address',
              labelText: 'Email-address',
              errorText: snapshot.error),
        );
      },
    );
  }

  Widget passwordField(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.password,
        builder: (context, snapshot) {
          return TextField(
            onChanged: bloc.changePassword,
            decoration: InputDecoration(
                hintText: 'Enter password',
                labelText: 'Password',
                errorText: snapshot.error),
          );
        });
  }

  Widget passwordFieldRe(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.passwordretype,
        builder: (context, snapshot) {
          return TextField(
            onChanged: bloc.changePasswordRetype,
            decoration: InputDecoration(
                hintText: 'Retype password',
                labelText: 'Password',
                errorText: snapshot.error),
          );
        });
  }

  Widget button(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot) {
        return RaisedButton(
            child: Text('Register'),
            color: Colors.blue,
            //if true
            onPressed: snapshot.hasData
                ? () {
//            bloc.showProgressBar(true);
                    bloc.register();
                  }
                : null);
      },
    );
  }

  Widget buttons(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot1) {
        return StreamBuilder(
          stream: bloc.signInStatus,
          builder: (context, snapshot2) {
            if (!snapshot2.hasData || snapshot2.hasError) {
              return Column(
                children: <Widget>[
                  RaisedButton(
                    child: Text('Register'),
                    color: Colors.blue,
                    onPressed: snapshot1.hasData
                        ? () {
                      bloc.register();
                    }
                        : null,
                  ),
                  snapshot2.hasError ? Text("ee") : Container()
                ],
              );
            } else {
              return CircularProgressIndicator();
            }
          },
        );
      },
    );
  }

  Widget submitButton(Bloc bloc) {
    return StreamBuilder(
        stream: bloc.signInStatus,
        builder: (context, snapshot) {
          if (snapshot.hasError || !snapshot.hasData) {
            return buttons(bloc);
          } else {
            return CircularProgressIndicator();
          }
        });

  }

/

Validators.dart

import 'dart:async';

class Validators {

  final validateEmail = StreamTransformer<String, String>.fromHandlers(
      handleData: (email, sink){
        if (RegExp(
        r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
        .hasMatch(email)){
          sink.add(email);
        } else {
          sink.addError('Please enter a valid email address.');
        }
      }
  );

  final validatePassword = StreamTransformer<String, String>.fromHandlers(
      handleData: (password, sink){
        if (password.length > 3){
          sink.add(password);
        } else {
          sink.addError('Password is too short.');
        }
      }
  );

  final validatePasswordRetype = StreamTransformer<String, String>.fromHandlers(
      handleData: (password, sink){
        print("HANDLE DATA");
        if (password.length > 3){
          sink.add(password);
        } else {
          sink.addError('Password is too short.');
        }
      }
  );

}

screenshot


问:
Play Framework returning 404 with play.http.context and trailing slash
I have a Play Framework application that serves an SPA. The routes file contains the following routes:

```<code>GET      /            controllers.Home.index
GET      /index.html  controllers.Home.index

# /api/* routes

GET      /*file       controllers.Assets.at(file)
</code>```

controllers.Home.index serves the SPA's index after performing SSO routines.

When I run the application without any additional configuration, upon visiting localhost:3000 and localhost:3000/, the index action in Home controller is invoked as expected.

The problems start when I configure play.http.context:

When set to /my-app, requests to localhost:3000/my-app succeed; to localhost:3000/my-app/ return 404.

When set to /my-app/, requests to localhost:3000/my-app return 404; to localhost:3000/my-app/ succeed.

Is there a way to configure Play such that requests to both URLs succeed with controllers.Home.index?

答: Use both urls. With and without the trailing slash.</p>

Body:
I have a Play Framework application that serves an SPA. The routes file contains the following routes:

GET      /            controllers.Home.index
GET      /index.html  controllers.Home.index

# /api/* routes

GET      /*file       controllers.Assets.at(file)

controllers.Home.index serves the SPA's index after performing SSO routines.

When I run the application without any additional configuration, upon visiting localhost:3000 and localhost:3000/, the index action in Home controller is invoked as expected.

The problems start when I configure play.http.context:

When set to /my-app, requests to localhost:3000/my-app succeed; to localhost:3000/my-app/ return 404.

When set to /my-app/, requests to localhost:3000/my-app return 404; to localhost:3000/my-app/ succeed.

Is there a way to configure Play such that requests to both URLs succeed with controllers.Home.index?


问:
Using d3.nest to create a pie chart
I have an assortment of data, and I have used it to create a donut chart. I want to make a pie chart using a breakdown of the data, which I've acquired using d3.nest to subdivide the data I had (it was currently in 3 categories: nest breaks it down into 129). Basically, I have Olympic data based on medals awarded, and I want to subdivide the data on interaction into which sports they were earned in.

I'm just not sure how to use nested data to create a pie chart, particularly if the keys are variable. I'll include my implementation for the donut chart.

```<code>  var pie = d3.pie();

  // color based on medal awarded
  // order: gold, silver, bronze
  var color = d3.scaleOrdinal()
    .range(['#e5ce0c', '#e5e4e0', '#a4610a']);

  var arcs = d3.select(svg).selectAll("g.arc")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "arc")
    .attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");

  arcs.append("path")
  .attr("fill", function(d, i) {
    return color(i);
  })
  .attr("d", arc)
  .attr("stroke", "white")
  .style("stroke-width", "0.5px")
  .on('mouseover', function(d) {
    d3.select(this).attr('opacity', .7);

  })
  .on('mouseleave', function(d) {
    d3.select(this).attr('opacity', 1);
  });

  // title
  d3.select(svg).append('text')
    .attr('x', function(d) {
      return ((w/2) - 85);
    })
    .attr('y', '20')
    .text(function(d) {
      return ('Medal breakdown for ' + country);
    })
    .attr('font-size', '16px');

  arcs.append("text")
    .attr("transform", function(d) {
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle")
    .text(function(d) {
      return d.value;
    });
</code>```

答:
Can you please confirm is this the format of data you have ?

Please find the code below and let me know if you have any doubt.

var w = 400;
var h = 400;
var r = h/2;
var color = d3.scale.category20c();

var data = [
{name:"football", medal:1},
{name:"hockey", medal:2},
{name:"cricket", medal:3},
{name:"tennis", medal:4},
{name:"table tennis", medal:5},
];

var vis = d3.select('#chart').append("svg:svg").data([data]).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + r + "," + r + ")");
var pie = d3.layout.pie().value(function(d){return d.medal;});

// declare an arc generator function
var arc = d3.svg.arc().outerRadius(r);

// select paths, use arc generator to draw
var arcs = vis.selectAll("g.slice").data(pie).enter().append("svg:g").attr("class", "slice");
arcs.append("svg:path")
    .attr("fill", function(d, i){
        return color(i);
    })
    .attr("d", function (d) {
        // log the result of the arc generator to show how cool it is :)
        return arc(d);
    });

// add the text
arcs.append("svg:text").attr("transform", function(d){
   d.innerRadius = 0;
   d.outerRadius = r;
    return "translate(" + arc.centroid(d) + ")";}).attr("text-anchor", "middle").text( function(d, i) {
    return data[i].name;}
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.15/d3.min.js"></script>
<div id="chart"></div></code>```

Title: Using d3.nest to create a pie chart

Body:
I have an assortment of data, and I have used it to create a donut chart. I want to make a pie chart using a breakdown of the data, which I've acquired using d3.nest to subdivide the data I had (it was currently in 3 categories: nest breaks it down into 129). Basically, I have Olympic data based on medals awarded, and I want to subdivide the data on interaction into which sports they were earned in.

I'm just not sure how to use nested data to create a pie chart, particularly if the keys are variable. I'll include my implementation for the donut chart.

  var pie = d3.pie();

  // color based on medal awarded
  // order: gold, silver, bronze
  var color = d3.scaleOrdinal()
    .range(['#e5ce0c', '#e5e4e0', '#a4610a']);

  var arcs = d3.select(svg).selectAll("g.arc")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "arc")
    .attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");

  arcs.append("path")
  .attr("fill", function(d, i) {
    return color(i);
  })
  .attr("d", arc)
  .attr("stroke", "white")
  .style("stroke-width", "0.5px")
  .on('mouseover', function(d) {
    d3.select(this).attr('opacity', .7);

  })
  .on('mouseleave', function(d) {
    d3.select(this).attr('opacity', 1);
  });

  // title
  d3.select(svg).append('text')
    .attr('x', function(d) {
      return ((w/2) - 85);
    })
    .attr('y', '20')
    .text(function(d) {
      return ('Medal breakdown for ' + country);
    })
    .attr('font-size', '16px');

  arcs.append("text")
    .attr("transform", function(d) {
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle")
    .text(function(d) {
      return d.value;
    });

Body:
Can you please confirm is this the format of data you have ?

Please find the code below and let me know if you have any doubt.

var w = 400;
var h = 400;
var r = h/2;
var color = d3.scale.category20c();

var data = [
{name:"football", medal:1},
{name:"hockey", medal:2},
{name:"cricket", medal:3},
{name:"tennis", medal:4},
{name:"table tennis", medal:5},
];

var vis = d3.select('#chart').append("svg:svg").data([data]).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + r + "," + r + ")");
var pie = d3.layout.pie().value(function(d){return d.medal;});

// declare an arc generator function
var arc = d3.svg.arc().outerRadius(r);

// select paths, use arc generator to draw
var arcs = vis.selectAll("g.slice").data(pie).enter().append("svg:g").attr("class", "slice");
arcs.append("svg:path")
    .attr("fill", function(d, i){
        return color(i);
    })
    .attr("d", function (d) {
        // log the result of the arc generator to show how cool it is :)
        return arc(d);
    });

// add the text
arcs.append("svg:text").attr("transform", function(d){
   d.innerRadius = 0;
   d.outerRadius = r;
    return "translate(" + arc.centroid(d) + ")";}).attr("text-anchor", "middle").text( function(d, i) {
    return data[i].name;}
  );

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.15/d3.min.js"></script>
<div id="chart"></div>


问:
Fit content mode for a custom view in SwiftUI
How can I set content mode as fit for a custom UIImageView wrapped in SwiftU?

```<code>struct CustomView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIImageView {
        CustomUIImage()
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {
    }
}

struct ContentView: View {
    var body: some View {
        CustomView()
    }
}
</code>```

In the code above, CustomUIImage is a subclass of UIImageView from UIKit. It's wrapped in UIViewRepresentable to integrate it with the SwiftUI framework. Calling CustomView().aspectRatio(contentMode: .fit) didn't work in this case

答:
Here is possible approach</p>

```<code>struct CustomView: UIViewRepresentable {

    private let imageView = CustomUIImage()

    init(contentMode: UIView.ContentMode = .center) {
        imageView.contentMode = contentMode
    }

    func makeUIView(context: Context) -> UIImageView {
        imageView
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {
    }
}

struct ContentView: View {
    var body: some View {
        CustomView(contentMode: .scaleAspectFit)
    }
}
</code>```

Body:
How can I set content mode as fit for a custom UIImageView wrapped in SwiftU?

struct CustomView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIImageView {
        CustomUIImage()
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {
    }
}

struct ContentView: View {
    var body: some View {
        CustomView()
    }
}

In the code above, CustomUIImage is a subclass of UIImageView from UIKit. It's wrapped in UIViewRepresentable to integrate it with the SwiftUI framework. Calling CustomView().aspectRatio(contentMode: .fit) didn't work in this case

Body:
Here is possible approach

struct CustomView: UIViewRepresentable {

    private let imageView = CustomUIImage()

    init(contentMode: UIView.ContentMode = .center) {
        imageView.contentMode = contentMode
    }

    func makeUIView(context: Context) -> UIImageView {
        imageView
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {
    }
}

struct ContentView: View {
    var body: some View {
        CustomView(contentMode: .scaleAspectFit)
    }
}


问:
Google maps set heading not working and map remains on heading to north
I am trying to do: map.setHeading(180) but this doesn't work and map remains heading to north. Everything else is working - I am using the very basic template of Gmaps from their docs, zoomings, pannings, markers and other things work as excepted, but the heading not. What am I missing in here?

For example, I got the position and heading from the GPS and I move the marker using marker.setPosition(position) which also works as excepted.

答:
The reason for this is that you can use setHeading if your map is displaying 45 degrees imagery as stated on the documentation.

It looks like your use case is the same as this existing Feature Request which is requesting for a feature to change the orientation of the map. You can star the issue to receive updates regarding the issue. You can also leave a comment on the issue regarding your use case.


问:
How do I truncate floats to two decimal places in cheetah templates?
I'm currently using Cheetah Templates with my python code and I'm passing in a number of floating point numbers. I'd like to truncate these floats to only two decimal places within the template, e.g. 0.2153406 would become 0.21

Is it possible to do this within the Cheetah template of do I have to pass in already truncated strings?

答:
#echo works, but you can instead define your own filter class to take control of formatting details, letting you write simpler templates.  Here's a filter that rounds floats to a certain precision.

```<code>import Cheetah.Filters

class MyFilter(Cheetah.Filters.Filter):
    """
    Overrides filtering to control the number of digits output for
    floats.
    """
    def filter(self,val,numDigits=2,**kw):
        """
        Called each time a top level placeholder is to be
        formatted for output.
        """
        if isinstance(val,float):
            return f"{val:.{numDigits}f}"

        return super().filter(val,**kw)
</code>```

To use this custom filter, specify it when you create your template.  Here's one way.

```<code>cls=Cheetah.Template.Template.compile(tmpl)
print(cls(filter=MyFilter))
</code>```

You can also add custom arguments to your filter function, like numDigits in the above example.  To specify that value, you have to use the long form in placeholders.

```<code>#import math

π to two digits is $math.pi
π to ten digits is ${math.pi,numDigits=10}
</code>```

This is an old question, but earlier answers don't mention filters, even though formatting placeholders is their primary purpose.

Jim

Body:
#echo works, but you can instead define your own filter class to take control of formatting details, letting you write simpler templates.  Here's a filter that rounds floats to a certain precision.

import Cheetah.Filters

class MyFilter(Cheetah.Filters.Filter):
    """
    Overrides filtering to control the number of digits output for
    floats.
    """
    def filter(self,val,numDigits=2,**kw):
        """
        Called each time a top level placeholder is to be
        formatted for output.
        """
        if isinstance(val,float):
            return f"{val:.{numDigits}f}"

        return super().filter(val,**kw)

To use this custom filter, specify it when you create your template.  Here's one way.

cls=Cheetah.Template.Template.compile(tmpl)
print(cls(filter=MyFilter))

You can also add custom arguments to your filter function, like numDigits in the above example.  To specify that value, you have to use the long form in placeholders.

#import math

π to two digits is $math.pi
π to ten digits is ${math.pi,numDigits=10}

This is an old question, but earlier answers don't mention filters, even though formatting placeholders is their primary purpose.

Jim


问:
Failed to add saved page to menu bar - wrapper application using electron
I recently follow a project electron on geeksforgeeks: https://www.geeksforgeeks.org/create-a-geeksforgeeks-wrapper-application-using-electron/

Here is its code on Github https://github.com/sayantanm19/geeksforgeeks-desktop/blob/master/index.js

The function appenItemToMenu doesn't work, which means I could save pages offline but the savedpagelist on menu bar is always empty ...

Could you try it on your machine and point out the bug?

```<code>function appendItemToMenu(filename) {
curr_menu = Menu.getApplicationMenu()
        .getMenuItemById("saved").submenu

curr_menu.append(
    new MenuItem({
    label: path.basename(filename, '.html'),
    click() {
        console.log('Saved page opened')
        win.loadFile(savedFolder + path.basename(filename))
    }
    }))
}
</code>```

答:
```<code>function appendItemToMenu(filename) {
  const newMenu = Menu.getApplicationMenu()
  curr_menu = newMenu.getMenuItemById('saved').submenu
  curr_menu.append(
    new MenuItem({
      label: path.basename(filename, '.html'),
      click() {
        console.log('Saved page opened')
        win.loadFile(savedFolder + path.basename(filename))
      }
    }))
  Menu.setApplicationMenu(newMenu)
}
</code>```

Update the application menu after change. Any dynamic change or append Item not allowed.

Body:
I recently follow a project electron on geeksforgeeks: https://www.geeksforgeeks.org/create-a-geeksforgeeks-wrapper-application-using-electron/

Here is its code on Github https://github.com/sayantanm19/geeksforgeeks-desktop/blob/master/index.js

The function appenItemToMenu doesn't work, which means I could save pages offline but the savedpagelist on menu bar is always empty ...

Could you try it on your machine and point out the bug?

function appendItemToMenu(filename) {
curr_menu = Menu.getApplicationMenu()
        .getMenuItemById("saved").submenu

curr_menu.append(
    new MenuItem({
    label: path.basename(filename, '.html'),
    click() {
        console.log('Saved page opened')
        win.loadFile(savedFolder + path.basename(filename))
    }
    }))
}

Body:
function appendItemToMenu(filename) {
  const newMenu = Menu.getApplicationMenu()
  curr_menu = newMenu.getMenuItemById('saved').submenu
  curr_menu.append(
    new MenuItem({
      label: path.basename(filename, '.html'),
      click() {
        console.log('Saved page opened')
        win.loadFile(savedFolder + path.basename(filename))
      }
    }))
  Menu.setApplicationMenu(newMenu)
}

Update the application menu after change. Any dynamic change or append Item not allowed.


问:
Are there any resources that explain what each of the Flutter TextTheme values affect?
Flutter has a class named TextTheme which can be used to set the styling of text across your entire app. It has several different fields which decide which style will be used on which Text widgets. The names hint at what they are for but some are also quite vague. I have not been able to find any documentation that explains exactly which widgets these styles will end up automatically getting applied to.

For example title will change the title text in an AppBar, which seems obvious enough... but how about body2 or display3?

Are there any resources that explain each of these and which widgets they will apply to (ideally visually)?

```<code>class TextTheme extends Diagnosticable {
  const TextTheme({
    this.display4,
    this.display3,
    this.display2,
    this.display1,
    this.headline,
    this.title,
    this.subhead,
    this.body2,
    this.body1,
    this.caption,
    this.button,
    this.subtitle,
    this.overline,
  });
</code>```

答:
I think the document about TextTheme is here.

I don't think these styles will automatically apply to, it's just an option for you apply to text.

Body:
Flutter has a class named TextTheme which can be used to set the styling of text across your entire app. It has several different fields which decide which style will be used on which Text widgets. The names hint at what they are for but some are also quite vague. I have not been able to find any documentation that explains exactly which widgets these styles will end up automatically getting applied to.

For example title will change the title text in an AppBar, which seems obvious enough... but how about body2 or display3?

Are there any resources that explain each of these and which widgets they will apply to (ideally visually)?

class TextTheme extends Diagnosticable {
  const TextTheme({
    this.display4,
    this.display3,
    this.display2,
    this.display1,
    this.headline,
    this.title,
    this.subhead,
    this.body2,
    this.body1,
    this.caption,
    this.button,
    this.subtitle,
    this.overline,
  });


问:
PhpUnit how to run --filter with multiple conditions
I have seen How to run single test method with phpunit?

And I have no trouble applying a filter eg --filter=SomeTest but I want to be able to check a number of test files in one command line eg, --filter=SomeTest, SomeOtherTest but this does not work.

Is there a way I can do this from the command line?

答:
This works --filter="SomeTest|SomeOtherTest"

According to documentation found here:
https://phpunit.readthedocs.io/en/8.5/textui.html#command-line-options

Any regex pattern will also work.
"If the pattern is not enclosed in delimiters, PHPUnit will enclose the pattern in / delimiters."

Also helped me to read about regular expressions:
https://sitespect.force.com/onlinehelp/s/article/About-Regular-Expressions-1459718276


问:
get variables substituted when I cat a file
Is it possible, in a clean way to get the variable values when I cat a file, instead of the variable names, as written in the file. It's hard to explain, but here goes a simple example:

```<code>$ cat <<EOF
$HOME
EOF
/home/myself
</code>```

cat returns /home/myself because it is already expanded by the shell.

```<code>$ echo \$HOME >/tmp/home
$ cat /tmp/home
$HOME
</code>```

cat simply reads the file, I want $HOME to be expanded here somehow by cat, because the file will contain variable names (not like HOME=/home/myself)

My question is if this is possible somehow, otherwise I will have to write some dirty code.

EDIT: they are big xml files containing

```<code><checkbox active="$value">
</code>```

true or false

答:
The obvious way to do this has a lot of problems:

```
# This will fail with certain inputs.  HTML will certainly be a problem
# as the '<' and '>' characters will be interpreted as file redirects
$ while read r; do eval echo $r; done < input
```

The following perl should handle the problem fairly well for simple inputs.

```
$ perl -pwe 'while(($k,$v) = each %ENV ) { s/\${?$k}?/$v/ }' input
```

But it doesn't do anything with constructs like ${FOO-bar}.  If you need to handle such constructs, it might be sufficient to escape all of the shell meta-characters and do the while/read loop:

```
$ sed -e 's/\([<>&|();]\)/\\\1/g' input | while read -r l; do eval echo "$l"; done
```

Note that this is neither robust nor secure.  Consider what happens on input like:

```
\; rm -rf /
```

I said "consider".  Do not test that.  The sed will insert a backslash before the semicolon, the eval will then get the string "\\;" which will be interpreted as a single backslash followed by a semi-colon which termintates the echo, and the rm -rf will be executed.  Given the insecurity of evaling unknown input, it would probably be safer to stick with something like perl and explicitly replace the desired sh constructs.  Something like:

```
$ perl -pwe 'while(($k,$v) = each %ENV ) { s/\${?$k}?/$v/ };
    s/\${[^-]*-([^}]*)}/$1/g' input
```

This one has problems with input like ${FOO=some-text}.  In order to reliably get all of the sh constructs (${word:rhs} where the ':' can be any of '-', '?', '=', '+', '%', '#' or any of the same with a colon prepended (or a lot of other symbols if you allow non-posix sh syntax!)) you would have to construct a fairly elaborate set of comparisons.

Body:
Is it possible, in a clean way to get the variable values when I cat a file, instead of the variable names, as written in the file. It's hard to explain, but here goes a simple example:

$ cat <<EOF
$HOME
EOF
/home/myself

cat returns /home/myself because it is already expanded by the shell.

$ echo \$HOME >/tmp/home
$ cat /tmp/home
$HOME

cat simply reads the file, I want $HOME to be expanded here somehow by cat, because the file will contain variable names (not like HOME=/home/myself)

My question is if this is possible somehow, otherwise I will have to write some dirty code.

EDIT: they are big xml files containing

<checkbox active="$value">

true or false

Body:
The obvious way to do this has a lot of problems:

# This will fail with certain inputs.  HTML will certainly be a problem
# as the '<' and '>' characters will be interpreted as file redirects
$ while read r; do eval echo $r; done < input

The following perl should handle the problem fairly well for simple inputs.

$ perl -pwe 'while(($k,$v) = each %ENV ) { s/\${?$k}?/$v/ }' input

But it doesn't do anything with constructs like ${FOO-bar}.  If you need to handle such constructs, it might be sufficient to escape all of the shell meta-characters and do the while/read loop:

$ sed -e 's/\([<>&|();]\)/\\\1/g' input | while read -r l; do eval echo "$l"; done

Note that this is neither robust nor secure.  Consider what happens on input like:

\; rm -rf /

I said "consider".  Do not test that.  The sed will insert a backslash before the semicolon, the eval will then get the string "\\;" which will be interpreted as a single backslash followed by a semi-colon which termintates the echo, and the rm -rf will be executed.  Given the insecurity of evaling unknown input, it would probably be safer to stick with something like perl and explicitly replace the desired sh constructs.  Something like:

$ perl -pwe 'while(($k,$v) = each %ENV ) { s/\${?$k}?/$v/ };
    s/\${[^-]*-([^}]*)}/$1/g' input

This one has problems with input like ${FOO=some-text}.  In order to reliably get all of the sh constructs (${word:rhs} where the ':' can be any of '-', '?', '=', '+', '%', '#' or any of the same with a colon prepended (or a lot of other symbols if you allow non-posix sh syntax!)) you would have to construct a fairly elaborate set of comparisons.


问:
How NOT to change file extension when uploading it?
In my Laravel project I need to upload mp3 files, However Laravel using mpga as a mime type to validate mp3 files type I found that in this answer.

$results = Validator::make($request->all(), [
            "song" => "required|file|mimes:mpga|max:8192",
        ]);
```

<p>I am okay with that but my problem is the file is stored with <code>mpga</code> extension, I know the reason behind this weird action from this answer.</p>

<p><strong>How I store the file</strong></p>

<pre class="lang-php prettyprint-override"><code>// Upload the song
$filePath = $request->song->store("public/songs");
</code>```

But I want to store the file with mp3 extension.

答:
Without seeing your code, the best I can suggest is to use the putFileAs() method from the Storage class.

This method allows you to specify a file name when storing your file:

use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;

// Manually specify a file name:
Storage::putFileAs(
    'folder',
    new File('/path/to/uploaded-music.mp3'),
    'stored-song-name.mp3'
);
```

<p>See Laravel doc: https://laravel.com/docs/5.8/filesystem#storing-files</p>

<hr>

<p>Edit: If you want to keep Laravel random file naming just like the <code>putFile()</code> method does, you can generate a random string and append your extension:</p>

<pre class="lang-php prettyprint-override"><code>use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

// Manually specify a file name:
Storage::putFileAs(
    'folder',
    new File('/path/to/uploaded-music.mp3'),
    Str::random(40) . '.mp3'
);
</code>```

If you look at Laravel source code, this is how putFile() does it to generate a random file name.

Body:
In my Laravel project I need to upload mp3 files, However Laravel using mpga as a mime type to validate mp3 files type I found that in this answer.

$results = Validator::make($request->all(), [
            "song" => "required|file|mimes:mpga|max:8192",
        ]);

I am okay with that but my problem is the file is stored with mpga extension, I know the reason behind this weird action from this answer.

How I store the file

// Upload the song
$filePath = $request->song->store("public/songs");

But I want to store the file with mp3 extension.

Body:
Without seeing your code, the best I can suggest is to use the putFileAs() method from the Storage class.

This method allows you to specify a file name when storing your file:

use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;

// Manually specify a file name:
Storage::putFileAs(
    'folder',
    new File('/path/to/uploaded-music.mp3'),
    'stored-song-name.mp3'
);

See Laravel doc: https://laravel.com/docs/5.8/filesystem#storing-files

Edit: If you want to keep Laravel random file naming just like the putFile() method does, you can generate a random string and append your extension:

use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

// Manually specify a file name:
Storage::putFileAs(
    'folder',
    new File('/path/to/uploaded-music.mp3'),
    Str::random(40) . '.mp3'
);

If you look at Laravel source code, this is how putFile() does it to generate a random file name.


问:
Generate Nested JSON Using R
I am trying to generate a nested JSON file using R, and am having difficulties in setting it up. I am admittedly very new to JSON, so conceptually I'm behind. I would appreciate any help- including advice on places (other than R) that would make this task easier.

I have 3 datasets I'm working with- all connected via keys. Essentially, my objective is to create a JSON file that contains patient objects, with nested encounters & within those encounters, nested claim lines.

Here's the set up in R:

```<code>patients <- data.frame (
                      PatientID = c('PID01','PID02'),
                      PatientName = c('John Doe','Jane Doe'),
                      PatientGroup = c('Group A','Group B')
                    )

encounters <- data.frame (
                          EncounterID = c('Enc01','Enc02','Enc03','Enc04','Enc05'),
                          PatientID = c('PID01','PID01','PID02','PID02','PID02'),
                          EncounterType = c('Outpatient','Outpatient','Inpatient','Outpatient','SNF')
                         )

encounterLines <- data.frame (
                              EncounterID = c(rep('Enc01',5),rep('Enc04',2)),
                              RevCodes = c('001','100','200','300','400','001','100'),
                              ClaimLine = c(seq(1:5),seq(1:2))
                              )

 ----------------------------------------
 PatientID   PatientName   PatientGroup
----------- ------------- --------------
   PID01      John Doe       Group A

   PID02      Jane Doe       Group B
----------------------------------------

-----------------------------------------
 EncounterID   PatientID   EncounterType
------------- ----------- ---------------
    Enc01        PID01      Outpatient

    Enc02        PID01      Outpatient

    Enc03        PID02       Inpatient

    Enc04        PID02      Outpatient

    Enc05        PID02          SNF
-----------------------------------------

------------------------------------
 EncounterID   RevCodes   ClaimLine
------------- ---------- -----------
    Enc01        001          1

    Enc01        100          2

    Enc01        200          3

    Enc01        300          4

    Enc01        400          5

    Enc04        001          1

    Enc04        100          2
------------------------------------
</code>```

The JSON output I'm looking for is as follows. I've tried using jsonlite but I can't seem to get any real traction:

```<code>[
    {
        "PatientID": "PID01",
        "PatientName": "John Doe",
        "PatientGroup": "Group A",
        "Encounters": [
            {
                "EncounterID": "Enc01",
                "EncounterType": "Outpatient",
                "ClaimLines": [
                    {
                        "ClaimLine": 1,
                        "RevenueCode": "001"
                    },
                    {
                        "ClaimLine": 2,
                        "RevenueCode": "100"
                    },
                    {
                        "ClaimLine": 3,
                        "RevenueCode": "200"
                    },
                    {
                        "ClaimLine": 4,
                        "RevenueCode": "300"
                    },
                    {
                        "ClaimLine": 5,
                        "RevenueCode": "400"
                    }
                ]
            },
            {
                "EncounterID": "Enc02",
                "EncounterType": "Outpatient"
            }
        ]
    },
    {
        "PatientID": "PID02",
        "PatientName": "Jane Doe",
        "PatientGroup": "Group B",
        "Encounters": [
            {
                "EncounterID": "Enc03",
                "EncounterType": "Inpatient"
            },
            {
                "EncounterID": "Enc04",
                "EncounterType": "Outpatient",
                "ClaimLines": [
                    {
                        "ClaimLine": 1,
                        "RevenueCode": "001"
                    },
                    {
                        "ClaimLine": 2,
                        "RevenueCode": "100"
                    }
                ]
            },
            {
                "EncounterID": "Enc05",
                "EncounterType": "SNF"
            }
        ]
    }
]
</code>```

Any/all help would be GREATLY appreciated. As I mentioned before, I'm not opposed to using tools outside R.

Thanks!

答:
This seems to get very close

library(tidyverse)
library(jsonlite)

json <- reduce(list(
    patients %>% mutate_if(is.factor, as.character),
    encounters %>% mutate_if(is.factor, as.character),
    encounterLines %>%
        mutate_if(is.factor, as.character) %>%
        group_by(EncounterID) %>%
        nest() %>%
        rename(ClaimLines = data) %>%
        mutate(ClaimLines = map(ClaimLines, transpose))),
    left_join) %>%
    nest(Encounters = c(EncounterID, EncounterType, ClaimLines)) %>%
    transpose() %>%
    toJSON(pretty = TRUE)
#[
#  {
#    "PatientID": ["PID01"],
#    "PatientName": ["John Doe"],
#    "PatientGroup": ["Group A"],
#    "Encounters": [
#      {
#        "EncounterID": "Enc01",
#        "EncounterType": "Outpatient",
#        "ClaimLines": [
#          {
#            "RevCodes": ["001"],
#            "ClaimLine": [1]
#          },
#          {
#            "RevCodes": ["100"],
#            "ClaimLine": [2]
#          },
#          {
#            "RevCodes": ["200"],
#            "ClaimLine": [3]
#          },
#          {
#            "RevCodes": ["300"],
#            "ClaimLine": [4]
#          },
#          {
#            "RevCodes": ["400"],
#            "ClaimLine": [5]
#          }
#        ]
#      },
#      {
#        "EncounterID": "Enc02",
#        "EncounterType": "Outpatient",
#        "ClaimLines": {}
#      }
#    ]
#  },
#  {
#    "PatientID": ["PID02"],
#    "PatientName": ["Jane Doe"],
#    "PatientGroup": ["Group B"],
#    "Encounters": [
#      {
#        "EncounterID": "Enc03",
#        "EncounterType": "Inpatient",
#        "ClaimLines": {}
#      },
#      {
#        "EncounterID": "Enc04",
#        "EncounterType": "Outpatient",
#        "ClaimLines": [
#          {
#            "RevCodes": ["001"],
#            "ClaimLine": [1]
#          },
#          {
#            "RevCodes": ["100"],
#            "ClaimLine": [2]
#          }
#        ]
#      },
#      {
#        "EncounterID": "Enc05",
#        "EncounterType": "SNF",
#        "ClaimLines": {}
#      }
#    ]
#  }
#]
#
```

The key is to create a suitable nested list first (using multiple purrr::transposes) which is then properly translated into a nested JSON using jsonlite::toJSON.

Title: Generate Nested JSON Using R

Body:
I am trying to generate a nested JSON file using R, and am having difficulties in setting it up. I am admittedly very new to JSON, so conceptually I'm behind. I would appreciate any help- including advice on places (other than R) that would make this task easier.

I have 3 datasets I'm working with- all connected via keys. Essentially, my objective is to create a JSON file that contains patient objects, with nested encounters & within those encounters, nested claim lines.

Here's the set up in R:

patients <- data.frame (
                      PatientID = c('PID01','PID02'),
                      PatientName = c('John Doe','Jane Doe'),
                      PatientGroup = c('Group A','Group B')
                    )

encounters <- data.frame (
                          EncounterID = c('Enc01','Enc02','Enc03','Enc04','Enc05'),
                          PatientID = c('PID01','PID01','PID02','PID02','PID02'),
                          EncounterType = c('Outpatient','Outpatient','Inpatient','Outpatient','SNF')
                         )

encounterLines <- data.frame (
                              EncounterID = c(rep('Enc01',5),rep('Enc04',2)),
                              RevCodes = c('001','100','200','300','400','001','100'),
                              ClaimLine = c(seq(1:5),seq(1:2))
                              )

 ----------------------------------------
 PatientID   PatientName   PatientGroup
----------- ------------- --------------
   PID01      John Doe       Group A

   PID02      Jane Doe       Group B
----------------------------------------

-----------------------------------------
 EncounterID   PatientID   EncounterType
------------- ----------- ---------------
    Enc01        PID01      Outpatient

    Enc02        PID01      Outpatient

    Enc03        PID02       Inpatient

    Enc04        PID02      Outpatient

    Enc05        PID02          SNF
-----------------------------------------

------------------------------------
 EncounterID   RevCodes   ClaimLine
------------- ---------- -----------
    Enc01        001          1

    Enc01        100          2

    Enc01        200          3

    Enc01        300          4

    Enc01        400          5

    Enc04        001          1

    Enc04        100          2
------------------------------------

The JSON output I'm looking for is as follows. I've tried using jsonlite but I can't seem to get any real traction:

[
    {
        "PatientID": "PID01",
        "PatientName": "John Doe",
        "PatientGroup": "Group A",
        "Encounters": [
            {
                "EncounterID": "Enc01",
                "EncounterType": "Outpatient",
                "ClaimLines": [
                    {
                        "ClaimLine": 1,
                        "RevenueCode": "001"
                    },
                    {
                        "ClaimLine": 2,
                        "RevenueCode": "100"
                    },
                    {
                        "ClaimLine": 3,
                        "RevenueCode": "200"
                    },
                    {
                        "ClaimLine": 4,
                        "RevenueCode": "300"
                    },
                    {
                        "ClaimLine": 5,
                        "RevenueCode": "400"
                    }
                ]
            },
            {
                "EncounterID": "Enc02",
                "EncounterType": "Outpatient"
            }
        ]
    },
    {
        "PatientID": "PID02",
        "PatientName": "Jane Doe",
        "PatientGroup": "Group B",
        "Encounters": [
            {
                "EncounterID": "Enc03",
                "EncounterType": "Inpatient"
            },
            {
                "EncounterID": "Enc04",
                "EncounterType": "Outpatient",
                "ClaimLines": [
                    {
                        "ClaimLine": 1,
                        "RevenueCode": "001"
                    },
                    {
                        "ClaimLine": 2,
                        "RevenueCode": "100"
                    }
                ]
            },
            {
                "EncounterID": "Enc05",
                "EncounterType": "SNF"
            }
        ]
    }
]

Any/all help would be GREATLY appreciated. As I mentioned before, I'm not opposed to using tools outside R.

Thanks!

Body:
This seems to get very close

library(tidyverse)
library(jsonlite)

json <- reduce(list(
    patients %>% mutate_if(is.factor, as.character),
    encounters %>% mutate_if(is.factor, as.character),
    encounterLines %>%
        mutate_if(is.factor, as.character) %>%
        group_by(EncounterID) %>%
        nest() %>%
        rename(ClaimLines = data) %>%
        mutate(ClaimLines = map(ClaimLines, transpose))),
    left_join) %>%
    nest(Encounters = c(EncounterID, EncounterType, ClaimLines)) %>%
    transpose() %>%
    toJSON(pretty = TRUE)
#[
#  {
#    "PatientID": ["PID01"],
#    "PatientName": ["John Doe"],
#    "PatientGroup": ["Group A"],
#    "Encounters": [
#      {
#        "EncounterID": "Enc01",
#        "EncounterType": "Outpatient",
#        "ClaimLines": [
#          {
#            "RevCodes": ["001"],
#            "ClaimLine": [1]
#          },
#          {
#            "RevCodes": ["100"],
#            "ClaimLine": [2]
#          },
#          {
#            "RevCodes": ["200"],
#            "ClaimLine": [3]
#          },
#          {
#            "RevCodes": ["300"],
#            "ClaimLine": [4]
#          },
#          {
#            "RevCodes": ["400"],
#            "ClaimLine": [5]
#          }
#        ]
#      },
#      {
#        "EncounterID": "Enc02",
#        "EncounterType": "Outpatient",
#        "ClaimLines": {}
#      }
#    ]
#  },
#  {
#    "PatientID": ["PID02"],
#    "PatientName": ["Jane Doe"],
#    "PatientGroup": ["Group B"],
#    "Encounters": [
#      {
#        "EncounterID": "Enc03",
#        "EncounterType": "Inpatient",
#        "ClaimLines": {}
#      },
#      {
#        "EncounterID": "Enc04",
#        "EncounterType": "Outpatient",
#        "ClaimLines": [
#          {
#            "RevCodes": ["001"],
#            "ClaimLine": [1]
#          },
#          {
#            "RevCodes": ["100"],
#            "ClaimLine": [2]
#          }
#        ]
#      },
#      {
#        "EncounterID": "Enc05",
#        "EncounterType": "SNF",
#        "ClaimLines": {}
#      }
#    ]
#  }
#]
#

The key is to create a suitable nested list first (using multiple purrr::transposes) which is then properly translated into a nested JSON using jsonlite::toJSON.


答:
you can use OUTER APPLY() to get the last low with price difference

```<code>SELECT *,
       unit_price_diff = T.[unit_price] - L.[last_unit_price_before]
FROM   T
       OUTER APPLY
       (
           SELECT TOP 1
                  last_unit_price_before = x.[unit_price],
                  last_unit_price_change_date = x.[order_date]
           FROM   T x
           WHERE  x.[prdt_no] = T.[prdt_no]
           AND    x.[order_date] < T.[order_date]
           AND    x.[unit_price] <> T.[unit_price]
           ORDER BY x.[order_date] DESC
       ) L
WHERE  T.[order_date] >= '2020-02-01'
AND    T.[order_date] <= '2020-02-10'
</code>```

db<>fiddle

Title: Query last unt price before with detail record

Body:
sample

+---------+------------+----------+------------+
| prdt_no | order_date | quantity | unit_price |
+---------+------------+----------+------------+
| A001    | 2020-01-01 |      100 |         10 |
| A001    | 2020-01-10 |      200 |         10 |
| A001    | 2020-02-01 |      100 |         20 |
| A001    | 2020-02-05 |      100 |         20 |
| A001    | 2020-02-07 |      100 |         20 |
| A001    | 2020-02-10 |      100 |         15 |
| A002    | 2020-01-01 |      100 |         10 |
| A002    | 2020-01-10 |      200 |         10 |
| A002    | 2020-02-01 |      100 |         20 |
| A002    | 2020-02-05 |      100 |         20 |
| A002    | 2020-02-07 |      100 |         20 |
| A002    | 2020-02-10 |      100 |         15 |
+---------+------------+----------+------------+

expected

if query condition is order_date between 2020-02-02 and 2020-02-10 then the data will be expected to get below result

+---------+------------+----------+------------+------------------------+-----------------+-------------+-----------------------------+
| prdt_no | order_date | quantity | unit_price | last_unit_price_before | unit_price_diff | cost_reduce | last_unit_price_change_date |
+---------+------------+----------+------------+------------------------+-----------------+-------------+-----------------------------+
| A001    | 2020-02-05 |      100 |         20 |                     10 |              10 |        1000 | 2020-02-01                  |
| A001    | 2020-02-07 |      100 |         20 |                     10 |              10 |        1000 | 2020-02-01                  |
| A001    | 2020-02-10 |      100 |         15 |                     20 |              -5 |        -500 | 2020-02-10                  |
| A002    | 2020-02-05 |      100 |         20 |                     10 |              10 |        1000 | 2020-02-01                  |
| A002    | 2020-02-07 |      100 |         20 |                     10 |              10 |        1000 | 2020-02-01                  |
| A002    | 2020-02-10 |      100 |         15 |                     20 |              -5 |        -500 | 2020-02-10                  |
+---------+------------+----------+------------+------------------------+-----------------+-------------+-----------------------------+

logic

I hope to get same product last unit price before then use it to calculate the price difference

the data record count actually over 200K

like photo

test demo link

SQL Server 2012 | db<>fiddle

Body:
you can use OUTER APPLY() to get the last low with price difference

SELECT *,
       unit_price_diff = T.[unit_price] - L.[last_unit_price_before]
FROM   T
       OUTER APPLY
       (
           SELECT TOP 1
                  last_unit_price_before = x.[unit_price],
                  last_unit_price_change_date = x.[order_date]
           FROM   T x
           WHERE  x.[prdt_no] = T.[prdt_no]
           AND    x.[order_date] < T.[order_date]
           AND    x.[unit_price] <> T.[unit_price]
           ORDER BY x.[order_date] DESC
       ) L
WHERE  T.[order_date] >= '2020-02-01'
AND    T.[order_date] <= '2020-02-10'

db<>fiddle


问:
Sorting dates using SQL
How can I sort by date here, while keeping all the parameters?
I'm sorry, I'm really stupid in SQL.

```<code>SELECT
  chat_identifier,
  datetime(date/1000000000 + 978307200,'unixepoch','localtime'),
  case when [error]=0 then 'ok' when [error]=1 then 'Not ok' end
FROM
  chat
  INNER JOIN message
    ON chat.ROWID = message.ROWID"
</code>```

This query returns this:

```<code>[('Alex',), ('2020-02-16 05:22:49',), ('ok',)]
[('Grace',), ('2020-02-20 04:17:27',), ('ok',)]
[('Bob',), ('2020-02-16 05:22:25',), ('Not ok',)]
[('Brad',), ('2020-02-20 04:17:32',), ('ok',)]
[('Haruhi',), ('2020-02-16 05:22:10',), ('ok',)]
</code>```

答:
In general, to sort data, you use the ORDER BY clause followed by the colunns you wish to order by. By default, order by defaults to ascending order, but you can specifiy DESC after a column to indicate descending order.

For instance, given the following query:

```<code>SELECT chat_identifier,
  datetime(date/1000000000 + 978307200,'unixepoch','localtime'),
  case when [error]=0 then 'ok' when [error]=1 then 'Not ok' end
FROM chat INNER JOIN message
ON chat.ROWID = message.ROWID"
ORDER BY chat_identifier
</code>```

Should give something like this:

```<code>[('Alex',), ('2020-02-16 05:22:49',), ('ok',)]
[('Bob',), ('2020-02-16 05:22:25',), ('Not ok',)]
[('Brad',), ('2020-02-20 04:17:32',), ('ok',)]
[('Grace',), ('2020-02-20 04:17:27',), ('ok',)]
[('Haruhi',), ('2020-02-16 05:22:10',), ('ok',)]
</code>```

Since you are calculating the date field manually, you will also want to use a column alias. Thus, your query would look something like this:

```<code>SELECT chat_identifier,
  datetime(date/1000000000 + 978307200,'unixepoch','localtime') AS my_date,
  case when [error]=0 then 'ok' when [error]=1 then 'Not ok' end
FROM chat INNER JOIN message
ON chat.ROWID = message.ROWID"
ORDER BY my_date
</code>```

Title: Sorting dates using SQL

Body:
How can I sort by date here, while keeping all the parameters?
I'm sorry, I'm really stupid in SQL.

SELECT
  chat_identifier,
  datetime(date/1000000000 + 978307200,'unixepoch','localtime'),
  case when [error]=0 then 'ok' when [error]=1 then 'Not ok' end
FROM
  chat
  INNER JOIN message
    ON chat.ROWID = message.ROWID"

This query returns this:

[('Alex',), ('2020-02-16 05:22:49',), ('ok',)]
[('Grace',), ('2020-02-20 04:17:27',), ('ok',)]
[('Bob',), ('2020-02-16 05:22:25',), ('Not ok',)]
[('Brad',), ('2020-02-20 04:17:32',), ('ok',)]
[('Haruhi',), ('2020-02-16 05:22:10',), ('ok',)]

Body:
In general, to sort data, you use the ORDER BY clause followed by the colunns you wish to order by. By default, order by defaults to ascending order, but you can specifiy DESC after a column to indicate descending order.

For instance, given the following query:

SELECT chat_identifier,
  datetime(date/1000000000 + 978307200,'unixepoch','localtime'),
  case when [error]=0 then 'ok' when [error]=1 then 'Not ok' end
FROM chat INNER JOIN message
ON chat.ROWID = message.ROWID"
ORDER BY chat_identifier

Should give something like this:

[('Alex',), ('2020-02-16 05:22:49',), ('ok',)]
[('Bob',), ('2020-02-16 05:22:25',), ('Not ok',)]
[('Brad',), ('2020-02-20 04:17:32',), ('ok',)]
[('Grace',), ('2020-02-20 04:17:27',), ('ok',)]
[('Haruhi',), ('2020-02-16 05:22:10',), ('ok',)]

Since you are calculating the date field manually, you will also want to use a column alias. Thus, your query would look something like this:

SELECT chat_identifier,
  datetime(date/1000000000 + 978307200,'unixepoch','localtime') AS my_date,
  case when [error]=0 then 'ok' when [error]=1 then 'Not ok' end
FROM chat INNER JOIN message
ON chat.ROWID = message.ROWID"
ORDER BY my_date


问:
Store last created model's row in memory
I am working on ajax-game. The abstract: 2+ gamers(browsers) change a variable which is saved to DB through json. All gamers are synchronized by javascript-timer+json - periodically reading that variable from DB.

In general, all changes are stored in DB as history, but I want the recent change duplicated in memory.

So the problem is: i want one variable to be stored in memory instead of DB.

答:
You can use the cache system:

http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache

OwnerDisplayName: slatvick

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Tiago


问:
I have an array contains string values, in that same name i have image in drawable.so i want to add in integer array how to do that?
I have an array contains string values, in that same name i have image in drawable.so i want to add in integer array how to do that? ex string newarray[]={"jj","kk","ll"};
i want to access R.drawable.jj ,R.drwable.kk,R.drawable.ll</p>

答:
You could try to get the identifier by name:

```<code>Resources res = getResources();
res.getDrawable(res.getIdentifier(myStringArray[0], "drawable", myPackage));
</code>```

A similar question was already answered: get resource id by passing name as a parameter in android

Body:
You could try to get the identifier by name:

Resources res = getResources();
res.getDrawable(res.getIdentifier(myStringArray[0], "drawable", myPackage));

A similar question was already answered: get resource id by passing name as a parameter in android


问:
Error when trying to insert datagridview row collection to database using parameters
I have a form with a datagridview that displays columns from a db table after being scanned using barcode scanner, the displayed datas then is supposed to be inserted to another table with additional information from the form like combobox text and label text but I kept getting an error. This is the code I use, this works on other forms but not with this one and I can't find out what's wrong.

Sub SewingReport()
    Try

        Dim sdate As String = Now.ToString("yyyy-MM-dd")

        If MsgBox("Are you sure you want to save this record to Sewing Report?", vbYesNo + vbQuestion) = vbYes Then
            cn.Open()
            cm = Nothing
            cm = New MySqlCommand("insert into tblsewingreport (tsnumber, bundle#, itemcode, operation, color, size, quantity, price, amount, sdate, employee) values(@tsnumber, @bundle#, @itemcode, @operation, @color, @size, @quantity, @price, @amount, @sdate, @employee)", cn)

            For i = 0 To dgvRecord.Rows.Count - 1
                cm.Parameters.Clear()
                cn.Close()
                cn.Open()
                cm.Parameters.AddWithValue("@tsnumber", lblInvoice.Text)
                cm.Parameters.AddWithValue("@bundle#", dgvRecord.Rows(i).Cells("Column6").Value.ToString)
                cm.Parameters.AddWithValue("@itemcode", dgvRecord.Rows(i).Cells("Column4").Value.ToString)
                cm.Parameters.AddWithValue("@operation", dgvRecord.Rows(i).Cells("Column5").Value.ToString)
                cm.Parameters.AddWithValue("@color", dgvRecord.Rows(i).Cells("Column7").Value.ToString)
                cm.Parameters.AddWithValue("@size", dgvRecord.Rows(i).Cells("Column8").Value.ToString)
                cm.Parameters.AddWithValue("@quantity", CDec(dgvRecord.Rows(i).Cells("Column9").Value.ToString))
                cm.Parameters.AddWithValue("@price", CDec(dgvRecord.Rows(i).Cells("Column10").Value.ToString))
                cm.Parameters.AddWithValue("@amount", CDec(dgvRecord.Rows(i).Cells("Column11").Value.ToString))
                cm.Parameters.AddWithValue("@sdate", sdate)
                cm.Parameters.AddWithValue("@employee", ComboBox1.Text)
                cm.ExecuteNonQuery()

                cn.Close()
            Next
            MinusStockQty()

            MsgBox("Record has been successfully saved to Sewing Report.", vbInformation)
            lblInvoice.Text = GetInvoiceNo()
            txtSearch.Clear()
            txtSearch.Focus()

        End If

    Catch ex As Exception
        cn.Close()
        MsgBox(ex.ToString)
    End Try
End Sub
```

This is the exception message, the error throws on the ExecuteNonQuery line and all my datagrid column names are correct. This is the datagridview and this is my database table im trying to insert to.

答:
The specific issue in this case is almost certainly the bundle# column name. Any identifiers that contain spaces or other special characters need to be escaped. The MySQL standard for that is to use graves while the Microsoft standard is to use brackets. I believe that the MySQL ADO.NET provider (Connector/Net) supports both:

cm = New MySqlCommand("insert into tblsewingreport (tsnumber, `bundle#`, itemcode, ...
```

<p>or:</p>

<pre class="lang-vb prettyprint-override"><code>cm = New MySqlCommand("insert into tblsewingreport (tsnumber, [bundle#], itemcode, ...
</code>```

Body:
I have a form with a datagridview that displays columns from a db table after being scanned using barcode scanner, the displayed datas then is supposed to be inserted to another table with additional information from the form like combobox text and label text but I kept getting an error. This is the code I use, this works on other forms but not with this one and I can't find out what's wrong.

Sub SewingReport()
    Try

        Dim sdate As String = Now.ToString("yyyy-MM-dd")

        If MsgBox("Are you sure you want to save this record to Sewing Report?", vbYesNo + vbQuestion) = vbYes Then
            cn.Open()
            cm = Nothing
            cm = New MySqlCommand("insert into tblsewingreport (tsnumber, bundle#, itemcode, operation, color, size, quantity, price, amount, sdate, employee) values(@tsnumber, @bundle#, @itemcode, @operation, @color, @size, @quantity, @price, @amount, @sdate, @employee)", cn)

            For i = 0 To dgvRecord.Rows.Count - 1
                cm.Parameters.Clear()
                cn.Close()
                cn.Open()
                cm.Parameters.AddWithValue("@tsnumber", lblInvoice.Text)
                cm.Parameters.AddWithValue("@bundle#", dgvRecord.Rows(i).Cells("Column6").Value.ToString)
                cm.Parameters.AddWithValue("@itemcode", dgvRecord.Rows(i).Cells("Column4").Value.ToString)
                cm.Parameters.AddWithValue("@operation", dgvRecord.Rows(i).Cells("Column5").Value.ToString)
                cm.Parameters.AddWithValue("@color", dgvRecord.Rows(i).Cells("Column7").Value.ToString)
                cm.Parameters.AddWithValue("@size", dgvRecord.Rows(i).Cells("Column8").Value.ToString)
                cm.Parameters.AddWithValue("@quantity", CDec(dgvRecord.Rows(i).Cells("Column9").Value.ToString))
                cm.Parameters.AddWithValue("@price", CDec(dgvRecord.Rows(i).Cells("Column10").Value.ToString))
                cm.Parameters.AddWithValue("@amount", CDec(dgvRecord.Rows(i).Cells("Column11").Value.ToString))
                cm.Parameters.AddWithValue("@sdate", sdate)
                cm.Parameters.AddWithValue("@employee", ComboBox1.Text)
                cm.ExecuteNonQuery()

                cn.Close()
            Next
            MinusStockQty()

            MsgBox("Record has been successfully saved to Sewing Report.", vbInformation)
            lblInvoice.Text = GetInvoiceNo()
            txtSearch.Clear()
            txtSearch.Focus()

        End If

    Catch ex As Exception
        cn.Close()
        MsgBox(ex.ToString)
    End Try
End Sub

This is the exception message, the error throws on the ExecuteNonQuery line and all my datagrid column names are correct. This is the datagridview and this is my database table im trying to insert to.

Body:
The specific issue in this case is almost certainly the bundle# column name. Any identifiers that contain spaces or other special characters need to be escaped. The MySQL standard for that is to use graves while the Microsoft standard is to use brackets. I believe that the MySQL ADO.NET provider (Connector/Net) supports both:

cm = New MySqlCommand("insert into tblsewingreport (tsnumber, `bundle#`, itemcode, ...

or:

cm = New MySqlCommand("insert into tblsewingreport (tsnumber, [bundle#], itemcode, ...


问:
Can I post all Messages in rabbitmq to a REST API?
I have a rabbitmq producer sending data to a queue in rabbitmq in a docker container, I have another micro-service with only an /POST entry.

Can I POST all messages in queue to this API?

答: In order to access the messages in the queue and POST them to your API, you need to have consumer(s) that listens to the queue.