问:
boost filesystem version 3 issue?
the example code on the boost website is not working. http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/tutorial.html#Using-path-decomposition

```<code>int main(int argc, char* argv[])
{
  path p (argv[1]);   // p reads clearer than argv[1] in the following code

  try
  {
    if (exists(p))    // does p actually exist?
    {
      if (is_regular_file(p))        // is p a regular file?
        cout << p << " size is " << file_size(p) << '\n';

      else if (is_directory(p))      // is p a directory?
      {
        cout << p << " is a directory containing:\n";

        typedef vector<path> vec;             // store paths,
        vec v;                                // so we can sort them later

        copy(directory_iterator(p), directory_iterator(), back_inserter(v));

        sort(v.begin(), v.end());             // sort, since directory iteration
                                          // is not ordered on some file systems

        for (vec::const_iterator it (v.begin()); it != v.end(); ++it)
        {
          path fn = it->path().filename();   // extract the filename from the path
          v.push_back(fn);                   // push into vector for later sorting
        }
      }

      else
        cout << p << " exists, but is neither a regular file nor a directory\n";
    }
    else
      cout << p << " does not exist\n";
  }

  catch (const filesystem_error& ex)
  {
    cout << ex.what() << '\n';
  }

  return 0;
}
</code>```

two error messages when compiled in visual studio 2010 for the line path fn = it->path().filename();

The first error is: 'function-style cast' : illegal as right side of '->' operator and the second error is: left of '.filename' must have class/struct/union

Also, when I mouse over path() it says: class boost::filesystem3::path Error: typename not allowed

答:
After you posted the link it seems that the code posted is working fine. But problem is introduced in the modified code in for loop. 1st problem is that, path() is a constructor. 2nd problem, I am not sure about boost::path contains any method as filename(). You can try,

```<code>path fn = (*it);
</code>```

Title: boost filesystem version 3 issue?

Body:
the example code on the boost website is not working. http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/tutorial.html#Using-path-decomposition

int main(int argc, char* argv[])
{
  path p (argv[1]);   // p reads clearer than argv[1] in the following code

  try
  {
    if (exists(p))    // does p actually exist?
    {
      if (is_regular_file(p))        // is p a regular file?
        cout << p << " size is " << file_size(p) << '\n';

      else if (is_directory(p))      // is p a directory?
      {
        cout << p << " is a directory containing:\n";

        typedef vector<path> vec;             // store paths,
        vec v;                                // so we can sort them later

        copy(directory_iterator(p), directory_iterator(), back_inserter(v));

        sort(v.begin(), v.end());             // sort, since directory iteration
                                          // is not ordered on some file systems

        for (vec::const_iterator it (v.begin()); it != v.end(); ++it)
        {
          path fn = it->path().filename();   // extract the filename from the path
          v.push_back(fn);                   // push into vector for later sorting
        }
      }

      else
        cout << p << " exists, but is neither a regular file nor a directory\n";
    }
    else
      cout << p << " does not exist\n";
  }

  catch (const filesystem_error& ex)
  {
    cout << ex.what() << '\n';
  }

  return 0;
}

two error messages when compiled in visual studio 2010 for the line path fn = it->path().filename();

The first error is: 'function-style cast' : illegal as right side of '->' operator and the second error is: left of '.filename' must have class/struct/union

Also, when I mouse over path() it says: class boost::filesystem3::path Error: typename not allowed

Body:
After you posted the link it seems that the code posted is working fine. But problem is introduced in the modified code in for loop. 1st problem is that, path() is a constructor. 2nd problem, I am not sure about boost::path contains any method as filename(). You can try,

path fn = (*it);


来源: stackexchange

问:
How to push an array value in Firebase Firestore
I am trying to push an array element but am destroying all the content there and replacing with the pushed data:

```<code>db .collection('households')
  .doc(householdId)
  .set( { users: [uid], }, { merge: true }, )
  .then(() => { resolve(); })
  .catch(() => reject());
</code>```

I thought the merge true doesn't destroy the data that is already there? Struggling a little with the firestore api docs.

This is the structure of my data:

```<code>households
  2435djgnfk
    users [
      0: user1
      1: user2
    ]
</code>```

Thank you!

答:
I think now you can do it better with the update command on document by using FieldValue.arrayUnion without destroying data that was added meanwhile. Like this:

```<code>const admin = require('firebase-admin');
let db = admin.firestore();
const FieldValue = admin.firestore.FieldValue;
let collectionRef = db.collection(collection);
let ref = collectionRef.doc(id);

let setWithOptions = ref.update(arrayFieldName, FieldValue.arrayUnion(value));
</code>```

As described in https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html

ContentLicense: CC BY-SA 3.0

Body:
I am trying to push an array element but am destroying all the content there and replacing with the pushed data:

db .collection('households')
  .doc(householdId)
  .set( { users: [uid], }, { merge: true }, )
  .then(() => { resolve(); })
  .catch(() => reject());

I thought the merge true doesn't destroy the data that is already there? Struggling a little with the firestore api docs.

This is the structure of my data:

households
  2435djgnfk
    users [
      0: user1
      1: user2
    ]

Thank you!

Body:
I think now you can do it better with the update command on document by using FieldValue.arrayUnion without destroying data that was added meanwhile. Like this:

const admin = require('firebase-admin');
let db = admin.firestore();
const FieldValue = admin.firestore.FieldValue;
let collectionRef = db.collection(collection);
let ref = collectionRef.doc(id);

let setWithOptions = ref.update(arrayFieldName, FieldValue.arrayUnion(value));

As described in https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html

ContentLicense: CC BY-SA 4.0


问:
The best extension method overload requires a receiver of type List
the best extension method overload requires a receiver of type List
i am facing this problem:

list jvdem does not contain the defination for ToModelListJVDET and the best extension overload method modelhelper.ToModelListJVDET(List) requires a receiver of type list

so please check my code and guide me how can i solve this problem

This is my code:

// Controller

public IActionResult Index() {
    List<JVDM> jVDMs = new LocationHandler().GetjVDM().ToModelListJVDET();

    return View(jVDMs);
}

// ModelHelper class

public static List<JVDetModel> ToModelListJVDET(this List<JVDetModel> entityJVDetModels) {
    List<JVDetModel> jVDetModel = new List<JVDetModel>();

    foreach (var i in entityJVDetModels) {
        jVDetModel.Add(i);
    }

    jVDetModel.TrimExcess();
    return jVDetModel;
}

// Location Handler

public List<JVDM> GetjVDM() {
    using (myDBContext context = new myDBContext()) {
        return (from c in context.JVDetTable select c).ToList();
    }
}
```

答:
The method GetjVDM() returns a List<JDVM> and your extension method ToModelListJVDET is extend List<JVDetModel>.

So if you want to call ToModlListJVDET you need to extend List<JDVM>, or instead return a List<JVDetModel> from GetjVDM().


问:
Adding custom Node OUs with Hyperledger Fabric
I am trying to add custom Node OU in policy definition inside the configtx.yaml file. The policy definition is present in Application section of configtx.yaml file as follows:

```<code>Application: &ApplicationDefaults

# Organizations is the list of orgs which are defined as participants on
# the application side of the network
ACLs: &ACLsDefault
    peer/Propose: /Channel/Application/Checkous

Organizations:

# Policies defines the set of policies at this level of the config tree
# For Application policies, their canonical path is
#   /Channel/Application/<PolicyName>
Policies:
    Readers:
        Type: ImplicitMeta
        Rule: "ANY Readers"
    Writers:
        Type: ImplicitMeta
        Rule: "ANY Writers"
    Admins:
        Type: ImplicitMeta
        Rule: "MAJORITY Admins"
    Checkous:
        Type: Signature
        Rule: "OR('Org1MSP.admin', 'Org1MSP.client', 'Org1MSP.dept')"

Capabilities:
    <<: *ApplicationCapabilities
</code>```

I already generated the crypto-material using cryptogen tool. As you can see I am also using the custom policy inside one of the ACLs.

Next, I created the orderer genesis block.

```<code>##########################################################
#########  Generating Orderer Genesis block ##############
##########################################################
CONSENSUS_TYPE=solo
+ '[' solo == solo ']'
+ configtxgen -profile TwoOrgsOrdererGenesis -channelID byfn-sys-channel -outputBlock ./channel-artifacts/genesis.block
2020-02-17 05:17:01.991 UTC [common.tools.configtxgen] main -> INFO 001 Loading configuration
2020-02-17 05:17:02.150 UTC [common.tools.configtxgen.localconfig] completeInitialization -> INFO 002 orderer type: solo
2020-02-17 05:17:02.150 UTC [common.tools.configtxgen.localconfig] Load -> INFO 003 Loaded configuration: /home/chintanr11/fabric-samples/first-network/configtx.yaml
2020-02-17 05:17:02.309 UTC [common.tools.configtxgen.localconfig] completeInitialization -> INFO 004 orderer type: solo
2020-02-17 05:17:02.309 UTC [common.tools.configtxgen.localconfig] LoadTopLevel -> INFO 005 Loaded configuration: /home/chintanr11/fabric-samples/first-network/configtx.yaml
2020-02-17 05:17:02.311 UTC [common.tools.configtxgen] doOutputBlock -> INFO 006 Generating genesis block
2020-02-17 05:17:02.311 UTC [common.tools.configtxgen] doOutputBlock -> INFO 007 Writing genesis block
+ res=0
+ set +x
</code>```

Followed by which, when I try to create channel configuration block, I receive the following error:

```<code>#################################################################
### Generating channel configuration transaction 'channel.tx' ###
#################################################################
+ configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID mychannel
2020-02-17 05:17:02.346 UTC [common.tools.configtxgen] main -> INFO 001 Loading configuration
2020-02-17 05:17:02.518 UTC [common.tools.configtxgen.localconfig] Load -> INFO 002 Loaded configuration: /home/chintanr11/fabric-samples/first-network/configtx.yaml
2020-02-17 05:17:02.680 UTC [common.tools.configtxgen.localconfig] completeInitialization -> INFO 003 orderer type: solo
2020-02-17 05:17:02.680 UTC [common.tools.configtxgen.localconfig] LoadTopLevel -> INFO 004 Loaded configuration: /home/chintanr11/fabric-samples/first-network/configtx.yaml
2020-02-17 05:17:02.680 UTC [common.tools.configtxgen] doOutputChannelCreateTx -> INFO 005 Generating new channel configtx
2020-02-17 05:17:02.680 UTC [common.tools.configtxgen] main -> FATA 006 Error on outputChannelCreateTx: could not generate default config template: error parsing configuration: could not create application group: error adding policies to application group: invalid signature policy rule 'OR('Org1MSP.admin', 'Org1MSP.client', 'Org1MSP.dept')': Unable to parse numeric value '.' to float64
+ res=1
+ set +x
Failed to generate channel configuration transaction...
</code>```

NOTE: I have added the definition for this OU in my config.yaml file located at: ~/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/msp. The file looks as follows:

```<code>NodeOUs:
  Enable: true
  ClientOUIdentifier:
    Certificate: cacerts/ca.org1.example.com-cert.pem
    OrganizationalUnitIdentifier: client
  PeerOUIdentifier:
    Certificate: cacerts/ca.org1.example.com-cert.pem
    OrganizationalUnitIdentifier: peer
  AdminOUIdentifier:
    Certificate: cacerts/ca.org1.example.com-cert.pem
    OrganizationalUnitIdentifier: admin
  OrdererOUIdentifier:
    Certificate: cacerts/ca.org1.example.com-cert.pem
    OrganizationalUnitIdentifier: orderer
  DeptOUIdentifier:
    Certificate: cacerts/ca.org1.example.com-cert.pem
    OrganizationalUnitIdentifier: dept
</code>```

What does the above error in channel block creation mean and any solution to resolve it?

How to possibly use custom Node OUs in the network using Fabric CA (and not cryptogen)?

答:
You cannot use "custom" NodeOU identifiers.  Fabric policies only support the following roles:

$MSPID.admin

$MSPID.member

$MSPID.peer

$MSPID.client

$MSPID.orderer

This means you can only use the built-in Node OU identifiers:

ClientOUIdentifier

PeerOUIdentifier

AdminOUIdentifier

OrdererOUIdentifier

Body:
I am trying to add custom Node OU in policy definition inside the configtx.yaml file. The policy definition is present in Application section of configtx.yaml file as follows:

Application: &ApplicationDefaults

# Organizations is the list of orgs which are defined as participants on
# the application side of the network
ACLs: &ACLsDefault
    peer/Propose: /Channel/Application/Checkous

Organizations:

# Policies defines the set of policies at this level of the config tree
# For Application policies, their canonical path is
#   /Channel/Application/<PolicyName>
Policies:
    Readers:
        Type: ImplicitMeta
        Rule: "ANY Readers"
    Writers:
        Type: ImplicitMeta
        Rule: "ANY Writers"
    Admins:
        Type: ImplicitMeta
        Rule: "MAJORITY Admins"
    Checkous:
        Type: Signature
        Rule: "OR('Org1MSP.admin', 'Org1MSP.client', 'Org1MSP.dept')"

Capabilities:
    <<: *ApplicationCapabilities

I already generated the crypto-material using cryptogen tool. As you can see I am also using the custom policy inside one of the ACLs.

Next, I created the orderer genesis block.

##########################################################
#########  Generating Orderer Genesis block ##############
##########################################################
CONSENSUS_TYPE=solo
+ '[' solo == solo ']'
+ configtxgen -profile TwoOrgsOrdererGenesis -channelID byfn-sys-channel -outputBlock ./channel-artifacts/genesis.block
2020-02-17 05:17:01.991 UTC [common.tools.configtxgen] main -> INFO 001 Loading configuration
2020-02-17 05:17:02.150 UTC [common.tools.configtxgen.localconfig] completeInitialization -> INFO 002 orderer type: solo
2020-02-17 05:17:02.150 UTC [common.tools.configtxgen.localconfig] Load -> INFO 003 Loaded configuration: /home/chintanr11/fabric-samples/first-network/configtx.yaml
2020-02-17 05:17:02.309 UTC [common.tools.configtxgen.localconfig] completeInitialization -> INFO 004 orderer type: solo
2020-02-17 05:17:02.309 UTC [common.tools.configtxgen.localconfig] LoadTopLevel -> INFO 005 Loaded configuration: /home/chintanr11/fabric-samples/first-network/configtx.yaml
2020-02-17 05:17:02.311 UTC [common.tools.configtxgen] doOutputBlock -> INFO 006 Generating genesis block
2020-02-17 05:17:02.311 UTC [common.tools.configtxgen] doOutputBlock -> INFO 007 Writing genesis block
+ res=0
+ set +x

Followed by which, when I try to create channel configuration block, I receive the following error:

#################################################################
### Generating channel configuration transaction 'channel.tx' ###
#################################################################
+ configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID mychannel
2020-02-17 05:17:02.346 UTC [common.tools.configtxgen] main -> INFO 001 Loading configuration
2020-02-17 05:17:02.518 UTC [common.tools.configtxgen.localconfig] Load -> INFO 002 Loaded configuration: /home/chintanr11/fabric-samples/first-network/configtx.yaml
2020-02-17 05:17:02.680 UTC [common.tools.configtxgen.localconfig] completeInitialization -> INFO 003 orderer type: solo
2020-02-17 05:17:02.680 UTC [common.tools.configtxgen.localconfig] LoadTopLevel -> INFO 004 Loaded configuration: /home/chintanr11/fabric-samples/first-network/configtx.yaml
2020-02-17 05:17:02.680 UTC [common.tools.configtxgen] doOutputChannelCreateTx -> INFO 005 Generating new channel configtx
2020-02-17 05:17:02.680 UTC [common.tools.configtxgen] main -> FATA 006 Error on outputChannelCreateTx: could not generate default config template: error parsing configuration: could not create application group: error adding policies to application group: invalid signature policy rule 'OR('Org1MSP.admin', 'Org1MSP.client', 'Org1MSP.dept')': Unable to parse numeric value '.' to float64
+ res=1
+ set +x
Failed to generate channel configuration transaction...

NOTE: I have added the definition for this OU in my config.yaml file located at: ~/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/msp. The file looks as follows:

NodeOUs:
  Enable: true
  ClientOUIdentifier:
    Certificate: cacerts/ca.org1.example.com-cert.pem
    OrganizationalUnitIdentifier: client
  PeerOUIdentifier:
    Certificate: cacerts/ca.org1.example.com-cert.pem
    OrganizationalUnitIdentifier: peer
  AdminOUIdentifier:
    Certificate: cacerts/ca.org1.example.com-cert.pem
    OrganizationalUnitIdentifier: admin
  OrdererOUIdentifier:
    Certificate: cacerts/ca.org1.example.com-cert.pem
    OrganizationalUnitIdentifier: orderer
  DeptOUIdentifier:
    Certificate: cacerts/ca.org1.example.com-cert.pem
    OrganizationalUnitIdentifier: dept

What does the above error in channel block creation mean and any solution to resolve it?

How to possibly use custom Node OUs in the network using Fabric CA (and not cryptogen)?


问:
Flutter bottom sheet modal effect
I want to achieve a similar design to the bottom sheet used on the Samsung Notes app:

I'm able to add the rounded corners, but I'm unable to make the system navigation bar at the bottom transparent. I think there is also a slight margin between the bottom sheet and the system navigation bar which I'm unable to achieve.

This is what I currently have:

I've been made aware of the SystemChrome class which I think is supposed to help with this, but I haven't had any luck yet:

```<code>SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    systemNavigationBarIconBrightness: Brightness.dark,
    systemNavigationBarColor: Colors.transparent,
  ));
</code>```

答:
I'm not sure where you are running that last piece of code, But it works for me. I put the following code being called in a button and I didn't even need to use a setState:

```<code>class SystemColorChangeIssue extends StatefulWidget {
  static const routeNamed = '/news-screen-detail';

  @override
  _SystemColorChangeIssueState createState() => _SystemColorChangeIssueState();
}

class _SystemColorChangeIssueState extends State<SystemColorChangeIssue> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          RaisedButton(
            color: Colors.red,
            onPressed: () => changeSystemColor(Colors.red),
            child: Text('Red'),
          ),
          RaisedButton(
            color: Colors.blue,
            onPressed: () => changeSystemColor(Colors.blue),
            child: Text('Blue'),
          ),
          RaisedButton(
            color: Colors.black,
            onPressed: () => changeSystemColor(Colors.transparent),
            child: Text('Transparent'),
          ),
          RaisedButton(
            color: Colors.pink,
            onPressed: () => showModal(context),
            child: Text('Show modal and show pink'),
          ),
        ],
      ),
    );
  }

  void changeSystemColor(Color color){
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      systemNavigationBarColor: color,
      systemNavigationBarIconBrightness: Brightness.dark,
    ));
  }

  void showModal(context){
    changeSystemColor(Colors.pink);
    showModalBottomSheet(
      context: context,
      builder: (context){
        return Container(
          padding: EdgeInsets.all(8),
          height: 200,
          alignment: Alignment.center,
          child: Text('Modal'),
        );
      }
    );
  }
}
</code>```

You should be able to run the same code on trigger to show your modal.

Title: Flutter bottom sheet modal effect

Body:
I want to achieve a similar design to the bottom sheet used on the Samsung Notes app:

I'm able to add the rounded corners, but I'm unable to make the system navigation bar at the bottom transparent. I think there is also a slight margin between the bottom sheet and the system navigation bar which I'm unable to achieve.

This is what I currently have:

I've been made aware of the SystemChrome class which I think is supposed to help with this, but I haven't had any luck yet:

SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    systemNavigationBarIconBrightness: Brightness.dark,
    systemNavigationBarColor: Colors.transparent,
  ));

Body:
I'm not sure where you are running that last piece of code, But it works for me. I put the following code being called in a button and I didn't even need to use a setState:

class SystemColorChangeIssue extends StatefulWidget {
  static const routeNamed = '/news-screen-detail';

  @override
  _SystemColorChangeIssueState createState() => _SystemColorChangeIssueState();
}

class _SystemColorChangeIssueState extends State<SystemColorChangeIssue> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          RaisedButton(
            color: Colors.red,
            onPressed: () => changeSystemColor(Colors.red),
            child: Text('Red'),
          ),
          RaisedButton(
            color: Colors.blue,
            onPressed: () => changeSystemColor(Colors.blue),
            child: Text('Blue'),
          ),
          RaisedButton(
            color: Colors.black,
            onPressed: () => changeSystemColor(Colors.transparent),
            child: Text('Transparent'),
          ),
          RaisedButton(
            color: Colors.pink,
            onPressed: () => showModal(context),
            child: Text('Show modal and show pink'),
          ),
        ],
      ),
    );
  }

  void changeSystemColor(Color color){
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      systemNavigationBarColor: color,
      systemNavigationBarIconBrightness: Brightness.dark,
    ));
  }

  void showModal(context){
    changeSystemColor(Colors.pink);
    showModalBottomSheet(
      context: context,
      builder: (context){
        return Container(
          padding: EdgeInsets.all(8),
          height: 200,
          alignment: Alignment.center,
          child: Text('Modal'),
        );
      }
    );
  }
}

You should be able to run the same code on trigger to show your modal.


问:
Remove the numbers < 4 digits in list in a data frame in R
I have a data frame like this this, i need to remove the values less than 4 digits in the item column,

```<code>department  item
xyz009   c("1","676547","2","434567","3","567369","4","987654","6","54546676732")
</code>```

Output

```<code>department  item

xyz009      676547,434567,567369,987654,54546676732
</code>```

Thank you for your help

Body:
I have a data frame like this this, i need to remove the values less than 4 digits in the item column,

department  item
xyz009   c("1","676547","2","434567","3","567369","4","987654","6","54546676732")

Output

department  item

xyz009      676547,434567,567369,987654,54546676732

Thank you for your help

Body:
Using base R you can use unlist, and lapply:

xyz009<-c("1","676547","2","434567","3","567369","4","987654","6","54546676732")
unlist(lapply(xyz009,function(x) x[nchar(x)>3]))

The result is:

[1] "676547"      "434567"      "567369"      "987654"      "54546676732"


问:
Powershell- How to identify via variable, the matched string index on a array
```<code>$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow')

$array | ForEach-Object {
    if ($array2 -contains $_) {
        Write-Host "`$array2 contains the `$array1 string [$_]"
    }
}
</code>```

how to get the index of the match string?

答:
You could also do a for loop using an index counter:

```<code>$array  = 'blue','red','purple','pink', 'black'
$array2 = 'brown','red','black','yellow', 'red'

for ($i = 0; $i -lt $array2.Count; $i++) {
    if ($array -contains $array2[$i]) {
        Write-Host "`$array2 contains the the string '$($array2[$i])' at index: $i"
    }
}
</code>```

Result:

```<code>$array2 contains the the string 'red' at index: 1
$array2 contains the the string 'black' at index: 2
$array2 contains the the string 'red' at index: 4
</code>```

Body:
$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow')

$array | ForEach-Object {
    if ($array2 -contains $_) {
        Write-Host "`$array2 contains the `$array1 string [$_]"
    }
}

how to get the index of the match string?

Body:
You could also do a for loop using an index counter:

$array  = 'blue','red','purple','pink', 'black'
$array2 = 'brown','red','black','yellow', 'red'

for ($i = 0; $i -lt $array2.Count; $i++) {
    if ($array -contains $array2[$i]) {
        Write-Host "`$array2 contains the the string '$($array2[$i])' at index: $i"
    }
}

Result:

$array2 contains the the string 'red' at index: 1
$array2 contains the the string 'black' at index: 2
$array2 contains the the string 'red' at index: 4


问:
Get the username with django profileserializer
I developed api with django. I created a code structure like below.
How do I get the user's first_name and last_name in class ProfileSerializer?

that is, with ProfileSerializer, I want to get information such as the user's name, surname, id number

``

```<code>from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from rest_framework.serializers import ModelSerializer, Serializer
from rest_framework import serializers
from account.models import Profile

class ProfileSerializer(ModelSerializer):

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email', 'address', 'userState')

class UserSerializer(ModelSerializer):
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'profile')

    def update(self, instance, validated_data):
        profile = validated_data.pop('profile')
        profile_serializer = ProfileSerializer(instance=instance.profile, data=profile)
        profile_serializer.is_valid(raise_exception=True)
        profile_serializer.save()
        return super(UserSerializer, self).update(instance, validated_data)
</code>```

``

答:
Simply define serializers.CharField() as,

```<code>class ProfileSerializer(ModelSerializer):
    <b>first_name = serializers.CharField(source='user.first_name', read_only=True)
    last_name = serializers.CharField(source='user.last_name' read_only=True)</b>

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email',
                  'address', 'userState', <b>'first_name', 'last_name'</b>)</code>```

Body:
I developed api with django. I created a code structure like below.
How do I get the user's first_name and last_name in class ProfileSerializer?

that is, with ProfileSerializer, I want to get information such as the user's name, surname, id number

``

from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from rest_framework.serializers import ModelSerializer, Serializer
from rest_framework import serializers
from account.models import Profile

class ProfileSerializer(ModelSerializer):

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email', 'address', 'userState')

class UserSerializer(ModelSerializer):
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'profile')

    def update(self, instance, validated_data):
        profile = validated_data.pop('profile')
        profile_serializer = ProfileSerializer(instance=instance.profile, data=profile)
        profile_serializer.is_valid(raise_exception=True)
        profile_serializer.save()
        return super(UserSerializer, self).update(instance, validated_data)

``

Body:
Simply define serializers.CharField() as,

class ProfileSerializer(ModelSerializer):
    first_name = serializers.CharField(source='user.first_name', read_only=True)
    last_name = serializers.CharField(source='user.last_name' read_only=True)

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email',
                  'address', 'userState', 'first_name', 'last_name')


问:
Programmatically scrolling to and coloring a UITableViewCell at runtime
I have UITableViewController which contains a list of items. Now, I want the list to be automatically scrolled to a item (index = bestOne ) once the view appears. Meanwhile I want the item to be colored into red and be labeled as Marked.

My code roughly achieves what I want. But, I actually see more than one red items iterating: every 10 items, there is a red item.

I am quite new to iphone development, I figure it might have something to do with reusable cells. But I am not exactly sure why. Can anybody suggest one way to solve this issue? Thanks in advance.

```<code>(void)viewDidAppear:(BOOL)animated
{
    if (self.bestOne != -1)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.bestOne inSection:0];
        [self.tableView scrollToRowAtIndexPath: atScrollPosition: animated:YES];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
    if (indexPath.row == self.bestOne)
    {
        cell.detailTextLabel.text = @"Marked";
        cell.textLabel.textColor = [UIColor redColor];
    }
    return cell;
}
</code>```

答: you look like you are on the right track with the color issue, you may accumulate red colored text cells, if you aren't calling [tableView reloadData] or reloading the old  red cells specifically, which you would want to do if you have a large table. your scrolling looks good, don't know why that wouldn't work.

Body:
I have UITableViewController which contains a list of items. Now, I want the list to be automatically scrolled to a item (index = bestOne ) once the view appears. Meanwhile I want the item to be colored into red and be labeled as Marked.

My code roughly achieves what I want. But, I actually see more than one red items iterating: every 10 items, there is a red item.

I am quite new to iphone development, I figure it might have something to do with reusable cells. But I am not exactly sure why. Can anybody suggest one way to solve this issue? Thanks in advance.

(void)viewDidAppear:(BOOL)animated
{
    if (self.bestOne != -1)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.bestOne inSection:0];
        [self.tableView scrollToRowAtIndexPath: atScrollPosition: animated:YES];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
    if (indexPath.row == self.bestOne)
    {
        cell.detailTextLabel.text = @"Marked";
        cell.textLabel.textColor = [UIColor redColor];
    }
    return cell;
}


问:
Find the last file name in python
I have same file name eg: filename1, filename2 , filename3, filename4 ..... filename10

I want to find last file of that specific name
over here last file name is filename10

```<code>import os
import datetime
import re

files = []
for file in os.listdir("C:\\Users\\Mayur Pawar\\Desktop\\FTP work"):
    if file.endswith(".csv"):
        files.append(file)
#s = sorted(files)

#print(files)

sorted(files)
</code>```

答:
You can use a Regex to do this. Not the most beautiful code ever, but it works. However, if filename has other number, you may need a more complex regex:

import re

files = ["filename10", "filename2", "fileename3"]

highest = 0
filename = ""
for f in files:
    dd = re.search(r'\d+', f)
    filenumber = int(dd.group())
    if filenumber > highest:
        highest = filenumber
        filename = f

```

Title: Find the last file name in python

Body:
I have same file name eg: filename1, filename2 , filename3, filename4 ..... filename10

I want to find last file of that specific name
over here last file name is filename10

import os
import datetime
import re

files = []
for file in os.listdir("C:\\Users\\Mayur Pawar\\Desktop\\FTP work"):
    if file.endswith(".csv"):
        files.append(file)
#s = sorted(files)

#print(files)

sorted(files)


问:
Sort grouped ranges of rows - Google Sheets
Example Sheet: Link

I have a fairly small data set that I sort frequently and to avoid sorting manually every time, I have created a basic sort in apps-script that works but is far from ideal. I was hoping there is a more straight forward sort method without needing any input from google formulas.

The data is set out like as (left) and once sorted as (right):

The apps-script I have so far looks like:

```<code>function sortSheet() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Sheet1');
  var data = ss.getSheetByName('Data');

  var lA = data.getRange('B2').getValue(); //Retuns the row for the first occurance of this value. Via.(=MATCH($A2,'Sheet1'!$A:$A,0)) Where Match(Value,Range to check) on the 'data' sheet.
  var nA = data.getRange('C2').getValue(); //Returns the total number of these values. Via. (=COUNTIF('Sheet1'!$A:$A,$A2)) Where CountIF(Range to check,Value) on the 'data' sheet.
  var sortA = sheet.getRange('A'+lA+':Y'+(lA+nA)); //Selects the range that contains the values to be sorted. Via. A through Y within the specified rows.
  sortA.sort({column: 2, ascending: true}) //Sorts range by column 2.

  var lB = data.getRange('B3').getValue();
  var nB = data.getRange('C3').getValue();
  var sortB = sheet.getRange('A'+lB+':Y'+(lB+nB));
  sortB.sort({column: 2, ascending: true})

  var lC = data.getRange('B4').getValue();
  var nC = data.getRange('C4').getValue();
  var sortC = sheet.getRange('A'+lC+':Y'+(lC+nC));
  sortC.sort({column: 2, ascending: true})

}
</code>```

This script is reliant on the information given from the sheet "Data".
Within this sheet it takes the first row that the given key is found in column B and the count of that key in column C.

The script then gets the required range to sort and runs through them one at a time.
Anyone be able to assist with simplifying this operation or going about it in an easier way?

答:
You can do this with regular formulas, without the need to use Apps Script:

=QUERY(A:B, "SELECT A,B where A is not null and B is not null order by A, B",1)

This is the result:

You can see it working here.

Note: This will not keep your empty spaces between each ID "section".

Body:
Example Sheet: Link

I have a fairly small data set that I sort frequently and to avoid sorting manually every time, I have created a basic sort in apps-script that works but is far from ideal. I was hoping there is a more straight forward sort method without needing any input from google formulas.

The data is set out like as (left) and once sorted as (right):

The apps-script I have so far looks like:

function sortSheet() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Sheet1');
  var data = ss.getSheetByName('Data');

  var lA = data.getRange('B2').getValue(); //Retuns the row for the first occurance of this value. Via.(=MATCH($A2,'Sheet1'!$A:$A,0)) Where Match(Value,Range to check) on the 'data' sheet.
  var nA = data.getRange('C2').getValue(); //Returns the total number of these values. Via. (=COUNTIF('Sheet1'!$A:$A,$A2)) Where CountIF(Range to check,Value) on the 'data' sheet.
  var sortA = sheet.getRange('A'+lA+':Y'+(lA+nA)); //Selects the range that contains the values to be sorted. Via. A through Y within the specified rows.
  sortA.sort({column: 2, ascending: true}) //Sorts range by column 2.

  var lB = data.getRange('B3').getValue();
  var nB = data.getRange('C3').getValue();
  var sortB = sheet.getRange('A'+lB+':Y'+(lB+nB));
  sortB.sort({column: 2, ascending: true})

  var lC = data.getRange('B4').getValue();
  var nC = data.getRange('C4').getValue();
  var sortC = sheet.getRange('A'+lC+':Y'+(lC+nC));
  sortC.sort({column: 2, ascending: true})

}

This script is reliant on the information given from the sheet "Data".
Within this sheet it takes the first row that the given key is found in column B and the count of that key in column C.

The script then gets the required range to sort and runs through them one at a time.
Anyone be able to assist with simplifying this operation or going about it in an easier way?


问:
How to implement Spring boot + Hibernate
I am getting this error:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field sessionFactory in com.demo.dao.EmployeeDAO required a bean of type 'org.hibernate.SessionFactory' that could not be found.

Action: Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.
</code>```

My HibernateUtil class is:

```<code>@Configuration
public class HibernateUtil {

    @Autowired
    private EntityManagerFactory factory;

    @Bean
    public SessionFactory getSessionFactory() {
        if(factory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("Factory is not a hibernate factory.");
        }
        return factory.unwrap(SessionFactory.class);
    }
}
</code>```

my EmployeeDao class is:

```<code>@Repository
public class EmployeeDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }

    public void save(Employee emp) {

        Session session = null;

        try {
            session = sessionFactory.openSession();
            System.out.println("Session got.");
            Transaction tx = session.beginTransaction();
            session.save(emp);
            tx.commit();
        }catch(HibernateException he) {
            he.printStackTrace();
        }
    }
}
</code>```

application.properties file,

```<code>spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://localhost:3306/manissh
spring.datasource.username=root
spring.datasource.password=admin
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
</code>```

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

答:
You need not create session. Just add the dependency spring-boot-starter-jpa in pom.xml  to use hibernate.
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

If you do so , then you can directly give the query in repository.

Body:
I am getting this error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field sessionFactory in com.demo.dao.EmployeeDAO required a bean of type 'org.hibernate.SessionFactory' that could not be found.

Action: Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.

My HibernateUtil class is:

@Configuration
public class HibernateUtil {

    @Autowired
    private EntityManagerFactory factory;

    @Bean
    public SessionFactory getSessionFactory() {
        if(factory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("Factory is not a hibernate factory.");
        }
        return factory.unwrap(SessionFactory.class);
    }
}

my EmployeeDao class is:

@Repository
public class EmployeeDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }

    public void save(Employee emp) {

        Session session = null;

        try {
            session = sessionFactory.openSession();
            System.out.println("Session got.");
            Transaction tx = session.beginTransaction();
            session.save(emp);
            tx.commit();
        }catch(HibernateException he) {
            he.printStackTrace();
        }
    }
}

application.properties file,

spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://localhost:3306/manissh
spring.datasource.username=root
spring.datasource.password=admin
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext


问:
How can I receive an event from Electron in a Non-Electron Web Page
I get how to communicate between an electron process and a web page within electron and I have seen examples of that on the web using IPCrenderer

If I have a web page that is completely outside of electron ( in this case a vue.js web application )  - but then I wrap it inside an electron app - how can I receive events from within the web application?

To understand the bigger picture, I have a web application that I want to use mainly on the web, but for one of the pages, I need to be able to send and receive between the web page and barcode scanners / serial scales. I can manage USB events within Electron, I am just unsure what to put in the web page to receive events sent from Electron when it is wrapping the web page.

Thanks for your time.

答: Have you considered using websockets, with e.g. https://www.npmjs.com/package/ws ? It's the same principle as IPC, but allows two-way communication outside Electron.</p>


问:
Something like margin or padding except where background doesn't draw
Is there something that will do what margin does but without the background drawing in that area? For instance, when you give an element margin: 1em you get a 1em border of blank space around the element, but the background draws in that area. Is there something similar to that except where the background doesn't draw?

My problem is I'm trying to put something below three float: lefted divs and right now I can't get any spacing between that and the floated divs above it. They just abut directly against each other.

The div that is going below the float: lefted divs has the property clear: both. If there was something that made that div have space between it and that floated div above it then that would work too.

答: With floated elements the margin around elements next to them is ignored.  I think you will have to create an additional element between the floated element and the item you want.</p>


问:
Making Materialize slider responsive
I'm trying to make Materialize slider responsive using a CSS, but it's doesn't work properly. when I test my code with the adaptive view of Firefox, I get slider images responsive with a grey background much bigger than the height of the slider images(as you can see below).

   .slider .slides li img {

background-size: 100% auto;;
background-repeat: no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
<div class="slider " >
  <ul class="slides ">
                <li>
      <img class="responsive-img" id="img" src="{{ asset('font/images/IMG_61.jpg') }}">
    </li>
      <li>
      <img class="responsive-img" id="img" src="{{ asset('font/images/IMG_53.jpg') }}">
    </li>
    <li>
      <img class="responsive-img" id="img" src="{{ asset('font/images/IMG_2.jpg') }}">
    </li>
  </ul>
</div>
</div></code>```

screen shot  size 360×640

答:
You literally have add:

```<code>.fullscreen
</code>```

to the slider and this works, as shown in the documentation. Patience to read people, that's all it takes :)

https://materializecss.com/fullscreen-slider-demo.html

Codepen showing markup and initialisation:

https://codepen.io/doughballs/pen/YzXqdPO

```<code><div class="slider fullscreen">
  <ul class="slides">
    <li class="active" style="opacity: 1; transform: translateX(0px) translateY(0px);">
      <img src="data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" style="background-image: url("https://images.unsplash.com/photo-1464817739973-0128fe77aaa1?dpr=1&auto=compress,format&fit=crop&w=1199&h=799&q=80&cs=tinysrgb&crop=");"> <!-- random image -->
      <div class="caption center-align" style="opacity: 1; transform: translateX(0px) translateY(0px);">
        <h3>This is our big Tagline!</h3>
        <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5>
      </div>
    </li>
    <li class="" style="opacity: 0; transform: translateX(0px) translateY(0px);">
      <img src="data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" style="background-image: url("https://ununsplash.imgix.net/photo-1414849424631-8b18529a81ca?q=75&fm=jpg&s=0e993004a2f3704e8f2ad5469315ccb7");"> <!-- random image -->
      <div class="caption left-align" style="opacity: 0; transform: translateX(-100px);">
        <h3>Left Aligned Caption</h3>
        <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5>
      </div>
    </li>
    <li class="" style="opacity: 0; transform: translateX(0px) translateY(0px);">
      <img src="data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" style="background-image: url("https://ununsplash.imgix.net/uploads/1413259835094dcdeb9d3/6e609595?q=75&fm=jpg&s=6a4fc66161293fc4a43a6ca6f073d1c5");"> <!-- random image -->
      <div class="caption right-align" style="opacity: 0; transform: translateX(100px);">
        <h3>Right Aligned Caption</h3>
        <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5>
      </div>
    </li>
  </ul>
<ul class="indicators"><li class="indicator-item active"></li><li class="indicator-item"></li><li class="indicator-item"></li></ul></div>
</code>```

Title: Making Materialize slider responsive

Body:
I'm trying to make Materialize slider responsive using a CSS, but it's doesn't work properly. when I test my code with the adaptive view of Firefox, I get slider images responsive with a grey background much bigger than the height of the slider images(as you can see below).

   .slider .slides li img {

background-size: 100% auto;;
background-repeat: no-repeat;
}

screen shot  size 360×640

Body:
You literally have add:

.fullscreen

to the slider and this works, as shown in the documentation. Patience to read people, that's all it takes :)

https://materializecss.com/fullscreen-slider-demo.html

Codepen showing markup and initialisation:

https://codepen.io/doughballs/pen/YzXqdPO

<div class="slider fullscreen">
  <ul class="slides">
    <li class="active" style="opacity: 1; transform: translateX(0px) translateY(0px);">
      <img src="data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" style="background-image: url(&quot;https://images.unsplash.com/photo-1464817739973-0128fe77aaa1?dpr=1&amp;auto=compress,format&amp;fit=crop&amp;w=1199&amp;h=799&amp;q=80&amp;cs=tinysrgb&amp;crop=&quot;);"> <!-- random image -->
      <div class="caption center-align" style="opacity: 1; transform: translateX(0px) translateY(0px);">
        <h3>This is our big Tagline!</h3>
        <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5>
      </div>
    </li>
    <li class="" style="opacity: 0; transform: translateX(0px) translateY(0px);">
      <img src="data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" style="background-image: url(&quot;https://ununsplash.imgix.net/photo-1414849424631-8b18529a81ca?q=75&amp;fm=jpg&amp;s=0e993004a2f3704e8f2ad5469315ccb7&quot;);"> <!-- random image -->
      <div class="caption left-align" style="opacity: 0; transform: translateX(-100px);">
        <h3>Left Aligned Caption</h3>
        <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5>
      </div>
    </li>
    <li class="" style="opacity: 0; transform: translateX(0px) translateY(0px);">
      <img src="data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" style="background-image: url(&quot;https://ununsplash.imgix.net/uploads/1413259835094dcdeb9d3/6e609595?q=75&amp;fm=jpg&amp;s=6a4fc66161293fc4a43a6ca6f073d1c5&quot;);"> <!-- random image -->
      <div class="caption right-align" style="opacity: 0; transform: translateX(100px);">
        <h3>Right Aligned Caption</h3>
        <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5>
      </div>
    </li>
  </ul>
<ul class="indicators"><li class="indicator-item active"></li><li class="indicator-item"></li><li class="indicator-item"></li></ul></div>


问:
elif <= invalid syntax?
i am currently working on a calculator using pandas, and to determine a variable I have used a nested if statement. But unfortunately, I get an invalid syntax error from the below code.

```<code>    if net_option == 'Y':
        if age <= 30:
            desired_net = 0.15
        elif age >= 31 and <= 60:
            desired_net = 0.12
        elif age >= 61 and <= 90:
            desired_net = 0.11
        elif age >= 91 and <= 140:
            desired_net = 0.10
        elif age >= 141 and <= 180:
            desired_net = 0.09
        elif age >= 181 and <= 245:
            desired_net = 0.08
        elif age >= 246 and <= 270:
            desired_net = 0.07
        elif age >= 271 and <= 365:
            desired_net = 0.6
        elif age >= 366 and <= 500:
            desired_net = 0.3
        elif: age >= 501 and <= 700:
            desired_net = 0.0
        elif age > 700:
            desired_net = -0.1
        else:
            desired_net = 0.1
    else:
        desired_net = desired_net
</code>```

Error message:

```<code>elif age >= 31 and <= 60:
                    ^
SyntaxError: invalid syntax
</code>```

I think I am missing something here as I am pretty sure that <= is a valid syntax.

Has anyone got an idea what may be wrong? Let me know if you would like to see more lines.

答:
elif age >= 31 and age <= 60:

When using the and operator, you are required to write the variable to compare against again, because each expression before and after and stands on its own.

Title: elif <= invalid syntax?

Body:
i am currently working on a calculator using pandas, and to determine a variable I have used a nested if statement. But unfortunately, I get an invalid syntax error from the below code.

    if net_option == 'Y':
        if age <= 30:
            desired_net = 0.15
        elif age >= 31 and <= 60:
            desired_net = 0.12
        elif age >= 61 and <= 90:
            desired_net = 0.11
        elif age >= 91 and <= 140:
            desired_net = 0.10
        elif age >= 141 and <= 180:
            desired_net = 0.09
        elif age >= 181 and <= 245:
            desired_net = 0.08
        elif age >= 246 and <= 270:
            desired_net = 0.07
        elif age >= 271 and <= 365:
            desired_net = 0.6
        elif age >= 366 and <= 500:
            desired_net = 0.3
        elif: age >= 501 and <= 700:
            desired_net = 0.0
        elif age > 700:
            desired_net = -0.1
        else:
            desired_net = 0.1
    else:
        desired_net = desired_net

Error message:

elif age >= 31 and <= 60:
                    ^
SyntaxError: invalid syntax

I think I am missing something here as I am pretty sure that <= is a valid syntax.

Has anyone got an idea what may be wrong? Let me know if you would like to see more lines.


问:
Seeking within MP3 file
I am working on the development of driving software for the hardware implementation by these people. The decoder works properly in overall, but I am struggling making it starting playing the sound at the middle. I suspect that it is common feature of the MP3 decoders as they must have some history of data in order to properly construct current sound (I am not that skilled in MPEG, however have an idea of some basics).
The problem is that this decoder is a black box, and any deepening in its code is an enormous time and effort.
I empirically found out that the sound garbage, when starting somewhere in the middle, happens in no more that 1 (one) seconds after start with file @ 320 kbps and 44100 sampling rate. I am actually ok to mute decoder for a second (while it gathers/decodes proper required data for further playback), and then unmute it to continue playback.

I did search on the internet for the matter, did not find anything useful. Tried to invalidate first frames by corrupting frame headers (the easiest that could be done without going into the MP3 headers/data), made things even worse.

Questions:

is there any body of knowledge of how players perform seek in MP3 files and keep non-corrupt sound?

Is my action plan seem valid - mute for 1 second while decoder plays garbage? Is there any way to (easily) calculate the time I must mute output for?

Update: just tried on another file @ 128 kbps/48k and maximal garbage time to be about 2 seconds... I can not believe that decoder with so limited resources - input buffer used is 2 kB with some intermediate working buffers, in total must be not more than 36 kB - can keep the history for 2 seconds, or decoder is having problems finding the sync word in the stream... and thus my driver needs to figure out the frame start (by finding out sync word, reading frame header, calculating frame size, and looking after the frame to contain another sync word).

答:
I've found workarounds. The difficulty was that there are actually two problems overlaying each other, but was easy to cope with having structured approach.

The decoder is having issues getting the first sync word of the stream, and works very well when the first bytes supplied to it are FF FB or FF FA. All other bytes - in the middle of the frame - with very high probability, cause major sound corruption, until decoder catches correct sync. Thus I designed the code seeking to the next frame start after the seek point, checking that this is actual start of the frame by calculating frame size and looking at the next frame to contain FFFB/FA.

Having fixed the problem 1 I have had minor corruption left from the decoder starting decoding the frame without historical data. I have solved it by muting the decoder for the first 4 buffering transactions.

Major corruption still happens, but is rare, and it seems that nature of corruption depends on what was in the decoder buffers (not only Huffman input buffer, but other intermediate buffers) before the decoder is instructed to start. My hardware performs clear of the input buffers to 0 when decoder is in reset state, but it seems to be not enough (or just incorrect)...

The decoder itself is a kind of PoC (proof of concept) work, a student term with the aim to prove that they were able to make it; the package is having test bench code, but lacks low level documentation/comments in the code, and is not ready for field implementation and production. In general the fact that it worked for me at all (almost) out of the box makes the honor to the developers and is a mark of high quality of their work. I have reviewed and tried several published projects for MP3 decoders for silicon implementation (FPGA) and concluded that this one is the best available. In addition, the license they provide their work on is generous one.

Update: my research have shown that the most problem lies not in the input buffer (however it is possible to improve the situation by uploading 528 bytes of historical data to the decoder's buffer so that it would be able to grab main data from previous frame), but in the internal state of the decoder. Its documentation says:

To reduce resource usage, part of the RAM for buffering the intermediate data is also shared with Huffman decoding as bit reservoir ...

thus it is a contents of the reservoir and intermediate computed data affecting the decoding. I have confirmed it by starting various set of frames in different sequence, and if set of frames are played in different sequence, nature of garbage changes, or garbage may simply not appear.

Thus, unfortunately, my conclusion: it is not possible to properly seek using this decoder as is. I even do not think it is possible to "fake" playback (to quickly "play" the file till the needed point in buffers) as all three clocks are tied to each other.

I will keep my "best tested" implementation, with the notes on the quality.

Update 2: I was wrong, it is possible to seek softly, but to mitigate the sound corruption (yes, I am still unsure if I fixed it completely) I had to find another deficiency in the decoder: it is related to timing, decoder assumes that further data is always available in the buffer, while it may not be there yet. (It is actually clear from the test bench code supplied within the IP - the way data was replenished during QA and testing). In the cases I caught the corruption, first frames in the first part of the input buffer RAM were not decoded properly, skipped, and decoder quickly skips to second part of the RAM, assuming new data is there, however driving hardware is not ready yet fetching required data and putting this data into the second part of decoder's buffer RAM, thus corruption persisted for quite a long time with decoder looping skipping "invalid" frames until it catches correct image of the frame and normalizes its pace through the buffer.

Now the solution:

play (almost) 5 frames of silence through decoder before unmuting it. This will ensure all decoder's internal buffers are purged. It will not take much time, however requires some coding;

introduce a possibility to set huffman's decoder starting pointer readptr (in huffctl.v) after reset into the value other than 0. It will give the flexibility to have some history data uploaded into the decoder's buffer and start huffman decoder from the middle of the buffer rather than from its very start;

calculate the position to seek to, it calculates relatively easily for MPEG-1 Layer-3: duration=(filesize-ID3size)/(bitrate/8*1000), newPosition=ID3size+seekTime*(bitrate/8*1000). Duration is needed to check that position to seek to fits into the play time, alternatively newPosition can be used to check against file size. These forumlas do not take into account older tag versions appearing at the end of the file, but they are usually not more than 128 bytes, thus a kind of negligible for timing calculation relative to average MP3 sound file size; it also assumes CBR (VBR will require completely different way, requiring more power and data I/O for accurate seeking). Funny enough I found web pages with incorrect duration calculation formula, thus beware posts by ignorant people with cool job titles;

Seek to the calculated position, find next frame from this position on, calculate frame size, and ensure that there's next valid frame at that distance. New pointer will point to this next frame found at the distance;

find out the main_data_begin lookback pointer of the frame now being pointed to at step 4. Decrease the new pointer by this value so that pointer points within previous frame to the start of the main data for the current frame - it will be a pointer for the decoder data start. Note that it will fail if main data begins in more than one frame back (removal of headers of previous frame(s) will be required for proper operation);

fill decoder's buffer starting pointer identified in step 5, and set decoder's decoding start pointer to the one identified in step 4. While the implementation assumes you fill buffer in halves, do it different from the start: fill the whole buffer instead of just a first half. For this, after reset, set idle bit, check for data request, reset idle bit, perform two 1024 byte transfers to the decoder's buffer (effectively filling it completely), and then set idle bit, then reset it, and then set it again;

after performing step 7 continue normally replenishing 1024 bytes per decoder's request.

Employing this plan I had zero sound corruption cases. As you see it requires some changes to Verilog, but it must be easy if you know basics or hardware, know Verilog amd can perform reverse engineering.

Title: Seeking within MP3 file


问:
Dynamically operate on application properties - vault settings (or any other values)
I would like to be able to flexibly choose between 3rd party components my application is using. ATM I have hardcoded values

```<code>spring.cloud.vault.token=ffffffff-ffff-ffff-ffff-ffffffffffff
spring.cloud.vault.scheme=http
spring.cloud.vault.application-name=test
spring.cloud.vault.host=127.0.0.1
spring.cloud.vault.port=8200
</code>```

The goal is to :

If spring.cloud.vault.host is set try to use it. If spring.cloud.vault.host is empty use
local DB instead (with proper configuration)

My first thought was to use environment variables like:

```<code>spring.cloud.vault.token=${VAULT_TOKEN}
spring.cloud.vault.scheme=${VAULT_SCHEME}
spring.cloud.vault.application-name=${VAULT_APP_NAME}
spring.cloud.vault.host=${VAULT_HOST}
spring.cloud.vault.port=${VAULT_PORT}
</code>```

and later use the component class like:

```<code>@Component
public class VaultHelper {
    private final VaultOperations vaultOperations;
    @Value("${spring.cloud.vault.host}")
    String vaultHostname;

    @Autowired
    public VaultHelper(VaultOperations vaultOperations){
        this.vaultOperations = vaultOperations;
    }

    public void saveToVault(String password){
        if (!vaultHostname.equals("")) {
            // Use vaultOperations to store password
        } else {
            // Use plaintext db storage
        }
    }

    public byte[] readFromVault(String passwordLoc){
        if (!vaultHostname.equals("")) {
            // Use vaultOperations to access password
        } else {
            // return plaintext password
        }
        return new byte[0];
    }

}
</code>```

This way I could set ${VAULT_HOST} both from the environment variable (running application from docker-compose) or just set --spring.cloud.vault.host=URL on the local machine as java parameter.

Unfortunately, I get an exception while unparsing ${VAULT_PORT} field

```<code>Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [int] for value '${VAULT_PORT}'; nested exception is java.lang.NumberFormatException: For input string: "${VAULT_PORT}"
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:47) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:191) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.BindConverter$CompositeConversionService.convert(BindConverter.java:170) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.BindConverter.convert(BindConverter.java:96) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.BindConverter.convert(BindConverter.java:88) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.Binder.bindProperty(Binder.java:435) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.Binder.bindObject(Binder.java:380) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.Binder.bind(Binder.java:320) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    ... 83 common frames omitted
Caused by: java.lang.NumberFormatException: For input string: "${VAULT_PORT}"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_231]
    at java.lang.Integer.parseInt(Integer.java:569) ~[na:1.8.0_231]
    at java.lang.Integer.valueOf(Integer.java:766) ~[na:1.8.0_231]
    at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:211) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.core.convert.support.StringToNumberConverterFactory$StringToNumber.convert(StringToNumberConverterFactory.java:62) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.core.convert.support.StringToNumberConverterFactory$StringToNumber.convert(StringToNumberConverterFactory.java:49) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService$ConverterFactoryAdapter.convert(GenericConversionService.java:436) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    ... 90 common frames omitted

Process finished with exit code 1
</code>```

could anyone give me a hint how to make it work?

答:
I guess its the matter of fact, that you do not provide a default / fallback. In this case, when it cannot find the corresponding environment variable it just declares the field PORT as the given string. try something with default using (:).

You can also provide another variable as default, which you know will be set.

```<code>spring.cloud.vault.port=${VAULT_PORT}:9000

spring.cloud.vault.port=${VAULT_PORT:8200}
</code>```

Body:
I would like to be able to flexibly choose between 3rd party components my application is using. ATM I have hardcoded values

spring.cloud.vault.token=ffffffff-ffff-ffff-ffff-ffffffffffff
spring.cloud.vault.scheme=http
spring.cloud.vault.application-name=test
spring.cloud.vault.host=127.0.0.1
spring.cloud.vault.port=8200

The goal is to :

If spring.cloud.vault.host is set try to use it. If spring.cloud.vault.host is empty use
local DB instead (with proper configuration)

My first thought was to use environment variables like:

spring.cloud.vault.token=${VAULT_TOKEN}
spring.cloud.vault.scheme=${VAULT_SCHEME}
spring.cloud.vault.application-name=${VAULT_APP_NAME}
spring.cloud.vault.host=${VAULT_HOST}
spring.cloud.vault.port=${VAULT_PORT}

and later use the component class like:

@Component
public class VaultHelper {
    private final VaultOperations vaultOperations;
    @Value("${spring.cloud.vault.host}")
    String vaultHostname;

    @Autowired
    public VaultHelper(VaultOperations vaultOperations){
        this.vaultOperations = vaultOperations;
    }

    public void saveToVault(String password){
        if (!vaultHostname.equals("")) {
            // Use vaultOperations to store password
        } else {
            // Use plaintext db storage
        }
    }

    public byte[] readFromVault(String passwordLoc){
        if (!vaultHostname.equals("")) {
            // Use vaultOperations to access password
        } else {
            // return plaintext password
        }
        return new byte[0];
    }

}

This way I could set ${VAULT_HOST} both from the environment variable (running application from docker-compose) or just set --spring.cloud.vault.host=URL on the local machine as java parameter.

Unfortunately, I get an exception while unparsing ${VAULT_PORT} field

Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [int] for value '${VAULT_PORT}'; nested exception is java.lang.NumberFormatException: For input string: "${VAULT_PORT}"
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:47) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:191) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.BindConverter$CompositeConversionService.convert(BindConverter.java:170) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.BindConverter.convert(BindConverter.java:96) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.BindConverter.convert(BindConverter.java:88) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.Binder.bindProperty(Binder.java:435) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.Binder.bindObject(Binder.java:380) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.context.properties.bind.Binder.bind(Binder.java:320) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    ... 83 common frames omitted
Caused by: java.lang.NumberFormatException: For input string: "${VAULT_PORT}"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_231]
    at java.lang.Integer.parseInt(Integer.java:569) ~[na:1.8.0_231]
    at java.lang.Integer.valueOf(Integer.java:766) ~[na:1.8.0_231]
    at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:211) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.core.convert.support.StringToNumberConverterFactory$StringToNumber.convert(StringToNumberConverterFactory.java:62) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.core.convert.support.StringToNumberConverterFactory$StringToNumber.convert(StringToNumberConverterFactory.java:49) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService$ConverterFactoryAdapter.convert(GenericConversionService.java:436) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    ... 90 common frames omitted

Process finished with exit code 1

could anyone give me a hint how to make it work?

Body:
I guess its the matter of fact, that you do not provide a default / fallback. In this case, when it cannot find the corresponding environment variable it just declares the field PORT as the given string. try something with default using (:).

You can also provide another variable as default, which you know will be set.

spring.cloud.vault.port=${VAULT_PORT}:9000

spring.cloud.vault.port=${VAULT_PORT:8200}


问:
copy all xml attributes from 1 node to another
hi I have 2 xml nodes and I need to copy only all the attributes from the first into the other
`

```<code> XmlDocument doc = new XmlDocument();
XmlDocument doc1 = new XmlDocument();
doc.Load(somepath);
XmlNode node=doc.CreateNode(System.Xml.XmlNodeType.Element, "something", null);
System.Xml.XmlNodeList list = doc.GetElementsByTagName("tananana");
XmlNode node1= list[0];
Foreach (XmlAttribute att in node1.Attributes)
{
     System.Xml.XmlAttribute rAtt= doc.CreateAttribute(att.name ); //att.name is problem
     rAtt.Value=att.Value;  //att.value is problem
     node1.Attributes.Add(rAtt);
 }
</code>```

Input test.xml:

```<code><data>
  <tananana a1="1" a2="2"/>
  <tananana a3="3" a4="5"/>
  <tananana a1="5" a2="7"/>
</data>
</code>```

Output:

```<code><data>
  <something a1="1" a2="2" />
  <something a3="3" a4="5" />
  <something a1="5" a2="7" />
</data>
</code>```

答:
Beside copying name and value, you should also consider what happens if an attribute is prefixed with a namespace, which the other answers so far would miss. Therefor just use the CloneNode method, instead copying 'manually'.</p>

```<code>XmlAttribute newAttribute = (XmlAttribute)sourceAttribute.CloneNode(true);
</code>```

Body:
hi I have 2 xml nodes and I need to copy only all the attributes from the first into the other
`

 XmlDocument doc = new XmlDocument();
XmlDocument doc1 = new XmlDocument();
doc.Load(somepath);
XmlNode node=doc.CreateNode(System.Xml.XmlNodeType.Element, "something", null);
System.Xml.XmlNodeList list = doc.GetElementsByTagName("tananana");
XmlNode node1= list[0];
Foreach (XmlAttribute att in node1.Attributes)
{
     System.Xml.XmlAttribute rAtt= doc.CreateAttribute(att.name ); //att.name is problem
     rAtt.Value=att.Value;  //att.value is problem
     node1.Attributes.Add(rAtt);
 }

Input test.xml:

<data>
  <tananana a1="1" a2="2"/>
  <tananana a3="3" a4="5"/>
  <tananana a1="5" a2="7"/>
</data>

Output:

<data>
  <something a1="1" a2="2" />
  <something a3="3" a4="5" />
  <something a1="5" a2="7" />
</data>

Body:
Beside copying name and value, you should also consider what happens if an attribute is prefixed with a namespace, which the other answers so far would miss. Therefor just use the CloneNode method, instead copying 'manually'.

XmlAttribute newAttribute = (XmlAttribute)sourceAttribute.CloneNode(true);


问:
Thread freezing the application
I'm designing an application which reads DICOM data sets and visualizes them with volume rendering techniques by using VTK library. Anyway, the problem I'm dealing is volume rendering is really CPU-bounded process. If I handle the volume rendering in a single threaded process, application (GUI) freezes and passes to "not responding" state. I have written another thread for volume rendering process. However GUI still freezes, here are the codes.

```<code>private: System::Void volumeRenderButton_Click(System::Object^  sender, System::EventArgs^  e) {

             volumeRenderThread = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this, &Form1::volumeRender));
             volumeRenderThread->Priority = System::Threading::ThreadPriority::Lowest;
             volumeRenderThread->Start();
         }

private: void volumeRender()
         {
             threeDPictureBox->Invoke(gcnew volumeDelegate(this, &Form1::volumeDelegateMethod));

             /*
             if ( threeDPictureBox->InvokeRequired )
             {
                threeDPictureBox->Invoke(gcnew System::Action(this, &Form1::volumeRender));
             }
             else
             {
                 dicom->VolumeRender(threeDPictureBox, vrSettings);
             }
             */
         }
private: delegate void volumeDelegate();

private: void volumeDelegateMethod()
         {
             dicom->VolumeRender(threeDPictureBox, vrSettings);
         }

void Dicom::VolumeRender( Windows::Forms::PictureBox ^pictureBox, VRsettings *settings )
{
    renderer = vtkSmartPointer < vtkRenderer > :: New();
    renderWindow = vtkSmartPointer < vtkWin32OpenGLRenderWindow > :: New();
    renderWindow->AddRenderer(renderer);
    renderWindow->SetParentId((HWND)((pictureBox->Handle).ToPointer()));
    renderWindow->SetSize(pictureBox->Width, pictureBox->Height);
    renderWindow->Initialize();
    /* A lot of stuff here */
    ...
    ...
    renderWindow->Render();
    iren->Initialize();     // vtkWin32RenderWindowInteractor

}
</code>```

threeDPictureBox is a PictureBox component that I'm sending it to volumeRender method of dicom object. vrSettings is a struct for volume Rendering parameters.

When the volume Render button is clicked and click event handler fired, volumeRenderThread starts and freezes the application even I have set its priority Lowest! I have also tried the lines which is commented. None of them works. What's the point I'm missing?? Thanks for answers from now!!

答:
You are just passing a delegate that does the actual work back to your UI thread to execute with that call to Invoke so setting the priority of volumeRenderThread doesn't help any.

You need to move as much of the actual work out of the UI thread as possible. Your snip only says /* A lot of stuff here */ so it's hard to suggest exactly how you should go about separating most of the work from the stuff that must be run on the UI thread, but that's what you'll need to do.

Title: Thread freezing the application

Body:
I'm designing an application which reads DICOM data sets and visualizes them with volume rendering techniques by using VTK library. Anyway, the problem I'm dealing is volume rendering is really CPU-bounded process. If I handle the volume rendering in a single threaded process, application (GUI) freezes and passes to "not responding" state. I have written another thread for volume rendering process. However GUI still freezes, here are the codes.

private: System::Void volumeRenderButton_Click(System::Object^  sender, System::EventArgs^  e) {

             volumeRenderThread = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this, &Form1::volumeRender));
             volumeRenderThread->Priority = System::Threading::ThreadPriority::Lowest;
             volumeRenderThread->Start();
         }

private: void volumeRender()
         {
             threeDPictureBox->Invoke(gcnew volumeDelegate(this, &Form1::volumeDelegateMethod));

             /*
             if ( threeDPictureBox->InvokeRequired )
             {
                threeDPictureBox->Invoke(gcnew System::Action(this, &Form1::volumeRender));
             }
             else
             {
                 dicom->VolumeRender(threeDPictureBox, vrSettings);
             }
             */
         }
private: delegate void volumeDelegate();

private: void volumeDelegateMethod()
         {
             dicom->VolumeRender(threeDPictureBox, vrSettings);
         }

void Dicom::VolumeRender( Windows::Forms::PictureBox ^pictureBox, VRsettings *settings )
{
    renderer = vtkSmartPointer < vtkRenderer > :: New();
    renderWindow = vtkSmartPointer < vtkWin32OpenGLRenderWindow > :: New();
    renderWindow->AddRenderer(renderer);
    renderWindow->SetParentId((HWND)((pictureBox->Handle).ToPointer()));
    renderWindow->SetSize(pictureBox->Width, pictureBox->Height);
    renderWindow->Initialize();
    /* A lot of stuff here */
    ...
    ...
    renderWindow->Render();
    iren->Initialize();     // vtkWin32RenderWindowInteractor

}

threeDPictureBox is a PictureBox component that I'm sending it to volumeRender method of dicom object. vrSettings is a struct for volume Rendering parameters.

When the volume Render button is clicked and click event handler fired, volumeRenderThread starts and freezes the application even I have set its priority Lowest! I have also tried the lines which is commented. None of them works. What's the point I'm missing?? Thanks for answers from now!!


问:
how to run ejabberd tests and write new unit tests in erlang?
How do I run ejabberd tests in the test folder?
I installed rebar and made sure to have a running ejabberd server and followed the steps here to:
https://docs.ejabberd.im/developer/extending-ejabberd/testing/
to run the test suite.

But I get the following error:

```<code>[ec2-user@ip-173-33-33-236 ejabberd]$CT_BACKENDS=mnesia rebar ct suites=ejabberd groups=mnesia
WARN:  Missing plugins: [rebar3_hex]
==> ejabberd (ct)
ERROR: ct_run -noshell -pa "/home/ec2-user/ejabberd/ebin"
"/home/ec2-user/ejabberd/deps/jose/ebin" "/home/ec2-user/ejabberd/deps/idna/ebin"
"/home/ec2-user/ejabberd/deps/yconf/ebin" "/home/ec2-user/ejabberd/deps/jiffy/ebin"
"/home/ec2-user/ejabberd/deps/p1_utils/ebin" "/home/ec2-user/ejabberd/deps/base64url/ebin"
"/home/ec2-user/ejabberd/deps/fast_yaml/ebin" "/home/ec2-user/ejabberd/deps/stringprep/ebin"
"/home/ec2-user/ejabberd/deps/ezlib/ebin" "/home/ec2-user/ejabberd/deps/fast_tls/ebin"
"/home/ec2-user/ejabberd/deps/fast_xml/ebin" "/home/ec2-user/ejabberd/deps/unicode_util_compat/ebin"
"/home/ec2-user/ejabberd/deps/proper/ebin" "/home/ec2-user/ejabberd/deps/base16/ebin"
"/home/ec2-user/ejabberd/deps/lhttpc/ebin"
"/home/ec2-user/ejabberd/deps/eini/ebin" "/home/ec2-user/ejabberd/deps/jsx/ebin"
"/home/ec2-user/ejabberd/deps/meck/ebin" "/home/ec2-user/ejabberd/deps/goldrush/ebin"
"/home/ec2-user/ejabberd/deps/p1_mysql/ebin" "/home/ec2-user/ejabberd/deps/p1_acme/ebin"
"/home/ec2-user/ejabberd/deps/mqtree/ebin" "/home/ec2-user/ejabberd/deps/eimp/ebin"
"/home/ec2-user/ejabberd/deps/pkix/ebin" "/home/ec2-user/ejabberd/deps/p1_oauth2/ebin"
"/home/ec2-user/ejabberd/deps/xmpp/ebin" "/home/ec2-user/ejabberd/deps/cache_tab/ebin"
 "/home/ec2-user/ejabberd/deps/uuid/ebin" "/home/ec2-user/ejabberd/deps/erlcloud/ebin"
"/home/ec2-user/ejabberd/deps/lager/ebin" "/usr/local/bin/rebar/rebar/ebin"
"/usr/local/bin/rebar" "/home/ec2-user/ejabberd/."  -include "/home/ec2-user/ejabberd/include"
-name test2876@ip-172-31-32-236.us-east-2.compute.internal -logdir
"/home/ec2-user/ejabberd/logs" -env TEST_DIR "/home/ec2-user/ejabberd/test"
-cover /home/ec2-user/ejabberd/cover.spec  -suite test/ejabberd_SUITE.erl
-group mnesia -ct_hooks cth_surefire  -include /home/ec2-user/ejabberd/tools
-include /home/ec2-user/ejabberd/include -include /home/ec2-user/ejabberd/deps/p1_utils/include
-include /home/ec2-user/ejabberd/deps/fast_xml/include
-include /home/ec2-user/ejabberd/deps/xmpp/include  >>
 /home/ec2-user/ejabberd/logs/raw.log 2>&1 failed with error: 1 and output:

ERROR: ct failed while processing /home/ec2-user/ejabberd: rebar_abort
</code>```

How do I run these unit tests?
Also, is there a recommended framework to write ejabberd/erlang unit tests?
I basically want to run some specific functions in the module for various inputs and make sure the output is correct and I do need the server part running for this?

Any suggestions/pointers would be really appreciated. Thanks!

答:
You don't mention what ejabberd and erlang version, so I assume they are the latest available.

How do I run these unit tests?

Notice that ejabberd already includes the rebar program. So better use that one instead of whatever you have installed. I simply run this, and works correctly:

```<code>CT_BACKENDS=mnesia ./rebar ct suites=ejabberd groups=mnesia
</code>```

I do need the server part running for this?

No need for ejabberd to be started when running that command. At least I stop it before running the tests...

Also, is there a recommended framework to write ejabberd/erlang unit tests? I basically want to run some specific functions in the module for various inputs and make sure the output is correct and

Sorry, no idea.

Body:
How do I run ejabberd tests in the test folder?
I installed rebar and made sure to have a running ejabberd server and followed the steps here to:
https://docs.ejabberd.im/developer/extending-ejabberd/testing/
to run the test suite.

But I get the following error:

[ec2-user@ip-173-33-33-236 ejabberd]$CT_BACKENDS=mnesia rebar ct suites=ejabberd groups=mnesia
WARN:  Missing plugins: [rebar3_hex]
==> ejabberd (ct)
ERROR: ct_run -noshell -pa "/home/ec2-user/ejabberd/ebin"
"/home/ec2-user/ejabberd/deps/jose/ebin" "/home/ec2-user/ejabberd/deps/idna/ebin"
"/home/ec2-user/ejabberd/deps/yconf/ebin" "/home/ec2-user/ejabberd/deps/jiffy/ebin"
"/home/ec2-user/ejabberd/deps/p1_utils/ebin" "/home/ec2-user/ejabberd/deps/base64url/ebin"
"/home/ec2-user/ejabberd/deps/fast_yaml/ebin" "/home/ec2-user/ejabberd/deps/stringprep/ebin"
"/home/ec2-user/ejabberd/deps/ezlib/ebin" "/home/ec2-user/ejabberd/deps/fast_tls/ebin"
"/home/ec2-user/ejabberd/deps/fast_xml/ebin" "/home/ec2-user/ejabberd/deps/unicode_util_compat/ebin"
"/home/ec2-user/ejabberd/deps/proper/ebin" "/home/ec2-user/ejabberd/deps/base16/ebin"
"/home/ec2-user/ejabberd/deps/lhttpc/ebin"
"/home/ec2-user/ejabberd/deps/eini/ebin" "/home/ec2-user/ejabberd/deps/jsx/ebin"
"/home/ec2-user/ejabberd/deps/meck/ebin" "/home/ec2-user/ejabberd/deps/goldrush/ebin"
"/home/ec2-user/ejabberd/deps/p1_mysql/ebin" "/home/ec2-user/ejabberd/deps/p1_acme/ebin"
"/home/ec2-user/ejabberd/deps/mqtree/ebin" "/home/ec2-user/ejabberd/deps/eimp/ebin"
"/home/ec2-user/ejabberd/deps/pkix/ebin" "/home/ec2-user/ejabberd/deps/p1_oauth2/ebin"
"/home/ec2-user/ejabberd/deps/xmpp/ebin" "/home/ec2-user/ejabberd/deps/cache_tab/ebin"
 "/home/ec2-user/ejabberd/deps/uuid/ebin" "/home/ec2-user/ejabberd/deps/erlcloud/ebin"
"/home/ec2-user/ejabberd/deps/lager/ebin" "/usr/local/bin/rebar/rebar/ebin"
"/usr/local/bin/rebar" "/home/ec2-user/ejabberd/."  -include "/home/ec2-user/ejabberd/include"
-name test2876@ip-172-31-32-236.us-east-2.compute.internal -logdir
"/home/ec2-user/ejabberd/logs" -env TEST_DIR "/home/ec2-user/ejabberd/test"
-cover /home/ec2-user/ejabberd/cover.spec  -suite test/ejabberd_SUITE.erl
-group mnesia -ct_hooks cth_surefire  -include /home/ec2-user/ejabberd/tools
-include /home/ec2-user/ejabberd/include -include /home/ec2-user/ejabberd/deps/p1_utils/include
-include /home/ec2-user/ejabberd/deps/fast_xml/include
-include /home/ec2-user/ejabberd/deps/xmpp/include  >>
 /home/ec2-user/ejabberd/logs/raw.log 2>&1 failed with error: 1 and output:

ERROR: ct failed while processing /home/ec2-user/ejabberd: rebar_abort

How do I run these unit tests?
Also, is there a recommended framework to write ejabberd/erlang unit tests?
I basically want to run some specific functions in the module for various inputs and make sure the output is correct and I do need the server part running for this?

Any suggestions/pointers would be really appreciated. Thanks!

Body:
You don't mention what ejabberd and erlang version, so I assume they are the latest available.

How do I run these unit tests?

Notice that ejabberd already includes the rebar program. So better use that one instead of whatever you have installed. I simply run this, and works correctly:

CT_BACKENDS=mnesia ./rebar ct suites=ejabberd groups=mnesia

I do need the server part running for this?

No need for ejabberd to be started when running that command. At least I stop it before running the tests...

Also, is there a recommended framework to write ejabberd/erlang unit tests? I basically want to run some specific functions in the module for various inputs and make sure the output is correct and

Sorry, no idea.


问:
MySQL - get users in location between dates
I have a logs table that contains logs of entrances and exits of users in a location.

I need to create a query that returns me the following data:

All users that have been visiting the site between two dates (FromDate & ToDate)

for this query a user visited the site between the two dates if:

the user has an entrance log before the ToDate but has no exit log at all

the user has an exit log after the FromDate but has no entrance log at all

en entrance and exit logs exist and the there is an entrance before the ToDate and there is en exit log after the FromDate

these are some of my tries:

```<code>SELECT UserId,
       MAX(EventDate) as lastAction,
       MAX(CASE WHEN InOrOut = 1 THEN EventDate END) as lastEntrance,
       MAX(CASE WHEN InOrOut = 0 THEN EventDate END) as lastExit
    FROM site_entrances
    WHERE siteId = 35
    GROUP BY UserId
    HAVING (lastExit IS NULL AND lastEntrance <= '2020-02-17 00:00:00') OR (lastEntrance IS NULL AND  lastExit >= '2020-01-17 00:00:00') OR (lastEntrance <= '2020-02-17 00:00:00' AND lastExit >= '2020-01-17 00:00:00');
</code>```

the problem with this one is: if there latest entrance is after the ToDate but an older entrance that is valid in this query exists, it is ignored...

```<code>SELECT t.*
FROM site_entrances as t, (SELECT site_entrances.UserId, MAX(EventDate) as 'latest'
                                     FROM site_entrances
                                     WHERE siteid = 35
                                     AND site_entrances.EventDate <= '2020-02-17 09:26:10'
                                     GROUP BY UserId) as maxDate
WHERE t.UserId= maxDate.UserId
AND t.EventDate = maxDate.latest
AND (t.InOrOut = 1 OR (t.InOrOut = 0 AND t.EventDate >= '2020-01-17 00:00:00'))
</code>```

this is the one I used and it works for me. the problem is that it is slow...

I think the first one needs a little guidance in the right direction and it would be perfect for me but.
a point in the right direction would be appreciated.

EDIT

Create table:

```<code>create table site_entrances (
    Id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    EventDate DateTime NOT NULL,
    InOrOut TINYINT NOT NULL,
    SiteId INT NOT NULL,
    UserId VARCHAR(13) NOT NULL,
    INDEX (SiteId, EventDate, UserId)
);
</code>```

insert:

```<code>insert into rtls.site_entrances (EventDate, InOrOut, SiteId, UserId)
values
# entrance before ToDate and exit after FromDate -> valid
('2020-01-02 00:01:00', 1, 35, 'a'),
('2020-04-01 00:01:00', 0, 35, 'a'),

# entrance and exit in range -> valid
('2020-01-18 00:01:00', 1, 35, 'b'),
('2020-01-19 00:01:00', 0, 35, 'b'),
('2020-03-18 00:01:00', 1, 35, 'b'), # not relevant to the query

# entrances without exits but they are befor FromDate -> valid
('2020-01-01 00:01:00', 1, 35, 'c1'),
('2020-01-20 00:01:00', 1, 35, 'c2'),

# entrance before ToDate and exit after FromDate -> valid
('2020-01-01 00:01:00', 1, 35, 'd'),
('2020-02-01 00:01:00', 0, 35, 'd'),

# exits without entrances but they are after FromDate -> valid
('2020-03-01 00:01:00', 0, 35, 'e1'),
('2020-02-01 00:01:00', 0, 35, 'e2'),

# entrance before ToDate and exit after FromDate -> valid
('2020-01-20 00:01:00', 1, 35, 'f'),
('2020-04-20 00:01:00', 0, 35, 'f'),

# entrance before ToDate but exit not after FromDate -> not valid
('2020-01-01 00:01:00', 1, 35, 'x'),
('2020-01-03 00:01:00', 0, 35, 'x'),

# exit after FromDate but entrance  not before ToDate -> not valid
('2020-04-01 00:01:00', 1, 35, 'y'),
('2020-04-02 00:01:00', 0, 35, 'y');
</code>```

the search I'm doing is between the dates: '2020-01-17 00:00:00' AND '2020-02-17 00:00:00'

the expected result:

```<code>UserId | Entrance              | Exit
d      | '2020-01-01 00:01:00' | '2020-02-01 00:01:00'
a      | '2020-01-02 00:01:00' | '2020-04-01 00:01:00'
b      | '2020-01-18 00:01:00' | '2020-01-19 00:01:00'
c1     | '2020-01-01 00:01:00' | NULL
c2     | '2020-01-20 00:01:00' | NULL
f      | '2020-01-20 00:01:00' | '2020-04-20 00:01:00'
e2     | NULL                  | '2020-02-01 00:01:00'
e1     | NULL                  | '2020-03-01 00:01:00'
</code>```

答:
With a simulated FULL JOIN (because MySql does not support it) to get entrances and respective exits in 1 row:

```<code>select t.*
from (
  select e1.userid, e1.eventdate entrance, min(e2.eventdate) `exit`
  from site_entrances e1 left join site_entrances e2
  on e2.userid = e1.userid and e2.inorout = 0
  and e1.eventdate < e2.eventdate
  where e1.inorout = 1
  group by e1.userid, e1.eventdate
  union
  select e2.userid, max(e1.eventdate) entrance, e2.eventdate `exit`
  from site_entrances e1 right join site_entrances e2
  on e2.userid = e1.userid and e1.inorout = 1
  and e1.eventdate < e2.eventdate
  where e2.inorout = 0
  group by e2.userid, e2.eventdate
) t
where
  coalesce(t.entrance, '2020-02-17 00:00:00') <= '2020-02-17 00:00:00'
  and
  coalesce(t.`exit`, '2020-01-17 00:00:00') >= '2020-01-17 00:00:00'
</code>```

See the demo.

Results:

```<code>| userid | entrance            | exit                |
| ------ | ------------------- | ------------------- |
| a      | 2020-01-02 00:01:00 | 2020-04-01 00:01:00 |
| b      | 2020-01-18 00:01:00 | 2020-01-19 00:01:00 |
| c1     | 2020-01-01 00:01:00 |                     |
| c2     | 2020-01-20 00:01:00 |                     |
| d      | 2020-01-01 00:01:00 | 2020-02-01 00:01:00 |
| f      | 2020-01-20 00:01:00 | 2020-04-20 00:01:00 |
| e1     |                     | 2020-03-01 00:01:00 |
| e2     |                     | 2020-02-01 00:01:00 |
</code>```

Body:
I have a logs table that contains logs of entrances and exits of users in a location.

I need to create a query that returns me the following data:

All users that have been visiting the site between two dates (FromDate & ToDate)

for this query a user visited the site between the two dates if:

the user has an entrance log before the ToDate but has no exit log at all

the user has an exit log after the FromDate but has no entrance log at all

en entrance and exit logs exist and the there is an entrance before the ToDate and there is en exit log after the FromDate

these are some of my tries:

SELECT UserId,
       MAX(EventDate) as lastAction,
       MAX(CASE WHEN InOrOut = 1 THEN EventDate END) as lastEntrance,
       MAX(CASE WHEN InOrOut = 0 THEN EventDate END) as lastExit
    FROM site_entrances
    WHERE siteId = 35
    GROUP BY UserId
    HAVING (lastExit IS NULL AND lastEntrance <= '2020-02-17 00:00:00') OR (lastEntrance IS NULL AND  lastExit >= '2020-01-17 00:00:00') OR (lastEntrance <= '2020-02-17 00:00:00' AND lastExit >= '2020-01-17 00:00:00');

the problem with this one is: if there latest entrance is after the ToDate but an older entrance that is valid in this query exists, it is ignored...

SELECT t.*
FROM site_entrances as t, (SELECT site_entrances.UserId, MAX(EventDate) as 'latest'
                                     FROM site_entrances
                                     WHERE siteid = 35
                                     AND site_entrances.EventDate <= '2020-02-17 09:26:10'
                                     GROUP BY UserId) as maxDate
WHERE t.UserId= maxDate.UserId
AND t.EventDate = maxDate.latest
AND (t.InOrOut = 1 OR (t.InOrOut = 0 AND t.EventDate >= '2020-01-17 00:00:00'))

this is the one I used and it works for me. the problem is that it is slow...

I think the first one needs a little guidance in the right direction and it would be perfect for me but.
a point in the right direction would be appreciated.

EDIT

Create table:

create table site_entrances (
    Id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    EventDate DateTime NOT NULL,
    InOrOut TINYINT NOT NULL,
    SiteId INT NOT NULL,
    UserId VARCHAR(13) NOT NULL,
    INDEX (SiteId, EventDate, UserId)
);

insert:

insert into rtls.site_entrances (EventDate, InOrOut, SiteId, UserId)
values
# entrance before ToDate and exit after FromDate -> valid
('2020-01-02 00:01:00', 1, 35, 'a'),
('2020-04-01 00:01:00', 0, 35, 'a'),

# entrance and exit in range -> valid
('2020-01-18 00:01:00', 1, 35, 'b'),
('2020-01-19 00:01:00', 0, 35, 'b'),
('2020-03-18 00:01:00', 1, 35, 'b'), # not relevant to the query

# entrances without exits but they are befor FromDate -> valid
('2020-01-01 00:01:00', 1, 35, 'c1'),
('2020-01-20 00:01:00', 1, 35, 'c2'),

# entrance before ToDate and exit after FromDate -> valid
('2020-01-01 00:01:00', 1, 35, 'd'),
('2020-02-01 00:01:00', 0, 35, 'd'),

# exits without entrances but they are after FromDate -> valid
('2020-03-01 00:01:00', 0, 35, 'e1'),
('2020-02-01 00:01:00', 0, 35, 'e2'),

# entrance before ToDate and exit after FromDate -> valid
('2020-01-20 00:01:00', 1, 35, 'f'),
('2020-04-20 00:01:00', 0, 35, 'f'),

# entrance before ToDate but exit not after FromDate -> not valid
('2020-01-01 00:01:00', 1, 35, 'x'),
('2020-01-03 00:01:00', 0, 35, 'x'),

# exit after FromDate but entrance  not before ToDate -> not valid
('2020-04-01 00:01:00', 1, 35, 'y'),
('2020-04-02 00:01:00', 0, 35, 'y');

the search I'm doing is between the dates: '2020-01-17 00:00:00' AND '2020-02-17 00:00:00'

the expected result:

UserId | Entrance              | Exit
d      | '2020-01-01 00:01:00' | '2020-02-01 00:01:00'
a      | '2020-01-02 00:01:00' | '2020-04-01 00:01:00'
b      | '2020-01-18 00:01:00' | '2020-01-19 00:01:00'
c1     | '2020-01-01 00:01:00' | NULL
c2     | '2020-01-20 00:01:00' | NULL
f      | '2020-01-20 00:01:00' | '2020-04-20 00:01:00'
e2     | NULL                  | '2020-02-01 00:01:00'
e1     | NULL                  | '2020-03-01 00:01:00'

Body:
With a simulated FULL JOIN (because MySql does not support it) to get entrances and respective exits in 1 row:

select t.*
from (
  select e1.userid, e1.eventdate entrance, min(e2.eventdate) `exit`
  from site_entrances e1 left join site_entrances e2
  on e2.userid = e1.userid and e2.inorout = 0
  and e1.eventdate < e2.eventdate
  where e1.inorout = 1
  group by e1.userid, e1.eventdate
  union
  select e2.userid, max(e1.eventdate) entrance, e2.eventdate `exit`
  from site_entrances e1 right join site_entrances e2
  on e2.userid = e1.userid and e1.inorout = 1
  and e1.eventdate < e2.eventdate
  where e2.inorout = 0
  group by e2.userid, e2.eventdate
) t
where
  coalesce(t.entrance, '2020-02-17 00:00:00') <= '2020-02-17 00:00:00'
  and
  coalesce(t.`exit`, '2020-01-17 00:00:00') >= '2020-01-17 00:00:00'

See the demo.

Results:

| userid | entrance            | exit                |
| ------ | ------------------- | ------------------- |
| a      | 2020-01-02 00:01:00 | 2020-04-01 00:01:00 |
| b      | 2020-01-18 00:01:00 | 2020-01-19 00:01:00 |
| c1     | 2020-01-01 00:01:00 |                     |
| c2     | 2020-01-20 00:01:00 |                     |
| d      | 2020-01-01 00:01:00 | 2020-02-01 00:01:00 |
| f      | 2020-01-20 00:01:00 | 2020-04-20 00:01:00 |
| e1     |                     | 2020-03-01 00:01:00 |
| e2     |                     | 2020-02-01 00:01:00 |