问:
Schema DB querying with Mongo Db. I don't understand why but the way I call to push or retrieve data from the db it seems to time out and throw err
I'm very new to MERN so I'm trying to figure out how to use schema correctly within my backend. I'm trying to just make a very simple case here where I just create a new user document in the database. I'm not trying to do anything with auth yet I just want to figure the syntax i guess behind why my code is not communicating correctly with the db.
When I run my backend code it says I successfully am running on port 4000 and that I've connected to my database.
When I check my routes with Postman it seems to time out and return bad request.

Here is my Schema code

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    name: {type:String, required:true},
    balance: {type:Number, required:true},
    currentLimit: {type:Number, required:true},
    maximumLimit: {type: Number, required:true, default:50}
});

module.exports = mongoose.model('user', userSchema);
</code>```

This is where I make the call to the database in my router function

```<code>const express = require('express');
const User = require('../Models/user');
const userInfo = express.Router();

userInfo.route('/userInfo').get(
    async function (req, res) {
        await User.find().then((err, results) => {
            if (err) throw err;
            res.json(result);

        })
    }
);

userInfo.route('/makeUser').post(
    async function (req, res) {
        const { name, balance, currentLimit, maximumLimit } = req.body;
        try {
            const user = await User.create({ name, balance, currentLimit, maximumLimit });
            res.status(200).json(user);
        } catch (error) {
            res.status(400).json(error);
            console.log('error');
        }
    }
);
module.exports = userInfo;
</code>```

This is my connection code

```<code>const { MongoClient } = require('mongodb');
const Db = process.env.URI;
const client = new MongoClient(Db, {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

module.exports = {
    connectToDatabase: async function (callback) {
        try {
            client.connect();
            console.log('Succesfully Connected to Database');
        } catch (e) {
            console.error(e);
        }
    }
}
</code>```

This is my index file

```<code>const express = require('express');
const cors = require('cors');
require('dotenv').config({path: "./config.env"});
const PORT = process.env.PORT || 4000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(require('./routing/userInfo'));
const dbo = require("./DB/connection");

app.listen(PORT, ()=>{
    console.log(`Server is running on port ${PORT}.`);
    dbo.connectToDatabase(function (err){
        if (err) console.error(err);
    })

})
</code>```

I feel like I've read so many mongodb schema docs and I do exactly as the docs say but still fail to read or write to/from the db.

Body:
I'm very new to MERN so I'm trying to figure out how to use schema correctly within my backend. I'm trying to just make a very simple case here where I just create a new user document in the database. I'm not trying to do anything with auth yet I just want to figure the syntax i guess behind why my code is not communicating correctly with the db.
When I run my backend code it says I successfully am running on port 4000 and that I've connected to my database.
When I check my routes with Postman it seems to time out and return bad request.

Here is my Schema code

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    name: {type:String, required:true},
    balance: {type:Number, required:true},
    currentLimit: {type:Number, required:true},
    maximumLimit: {type: Number, required:true, default:50}
});

module.exports = mongoose.model('user', userSchema);

This is where I make the call to the database in my router function

const express = require('express');
const User = require('../Models/user');
const userInfo = express.Router();

userInfo.route('/userInfo').get(
    async function (req, res) {
        await User.find().then((err, results) => {
            if (err) throw err;
            res.json(result);

        })
    }
);

userInfo.route('/makeUser').post(
    async function (req, res) {
        const { name, balance, currentLimit, maximumLimit } = req.body;
        try {
            const user = await User.create({ name, balance, currentLimit, maximumLimit });
            res.status(200).json(user);
        } catch (error) {
            res.status(400).json(error);
            console.log('error');
        }
    }
);
module.exports = userInfo;

This is my connection code

const { MongoClient } = require('mongodb');
const Db = process.env.URI;
const client = new MongoClient(Db, {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

module.exports = {
    connectToDatabase: async function (callback) {
        try {
            client.connect();
            console.log('Succesfully Connected to Database');
        } catch (e) {
            console.error(e);
        }
    }
}

This is my index file

const express = require('express');
const cors = require('cors');
require('dotenv').config({path: "./config.env"});
const PORT = process.env.PORT || 4000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(require('./routing/userInfo'));
const dbo = require("./DB/connection");

app.listen(PORT, ()=>{
    console.log(`Server is running on port ${PORT}.`);
    dbo.connectToDatabase(function (err){
        if (err) console.error(err);
    })

})

I feel like I've read so many mongodb schema docs and I do exactly as the docs say but still fail to read or write to/from the db.


来源: stackexchange

问:
Introspect related model to determine name of attribute for reverse descriptor?
Given schema:

```<code>class User(models.Model):
    name = models.CharField(max_length=50)

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

User objects will end up having a post_set attribute of type:

```<code>django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager
</code>```

Which returns a RelatedManager based on Post's default manager.  Cool.

Q: But if you're trying to introspect on a schema, how do you determine that the attribute name is "post_set"?

When I call User._meta.get_fields(), I see a field called "post", not "post_set".  (Of type: django.db.models.fields.reverse_related.ManyToOneRel)

I've explored nearly all of ManyToOneRel's API, and can't find any attribute or method that will return the value "post_set", only "post".

ContentLicense: CC BY-SA 4.0

Body:
Given schema:

class User(models.Model):
    name = models.CharField(max_length=50)

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)

User objects will end up having a post_set attribute of type:

django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager

Which returns a RelatedManager based on Post's default manager.  Cool.

Q: But if you're trying to introspect on a schema, how do you determine that the attribute name is "post_set"?

When I call User._meta.get_fields(), I see a field called "post", not "post_set".  (Of type: django.db.models.fields.reverse_related.ManyToOneRel)

I've explored nearly all of ManyToOneRel's API, and can't find any attribute or method that will return the value "post_set", only "post".


问:
Give access to Azure Logic App in a CICD pipeline to connect to a service bus topic with managed identity
I am trying to get a logic app to read messages from a service bus topic.  I am getting the error with the connection in logic app designer as :

Could not retrieve values. Error code: 'Unauthorized', Message: 'The remote server returned an error: (401) Unauthorized. Manage,EntityRead claims required for this operation. TrackingId:, SystemTracker:, Timestamp: clientRequestId: '. More diagnostic information: x-ms-client-request-id is ''.

currently I have tried the following in my cicd pipeline:

```<code>Grant permission to the logic app standard to access the connection api
resource servicebusConnectorAccessPolicy 'Microsoft.Web/connections/accessPolicies@2018-07-01-preview' = {
  name: '${servicebusConnector.name}/${logicAppName}'
  location: location
  properties: {
    principal: {
      type: 'ActiveDirectory'
      identity: {
        tenantId: subscription().tenantId
        objectId: logicApp.identity.principalId
      }
    }
  }
}
</code>```

Get this error:
ERROR: {"status":"Failed","error":{"code":"DeploymentFailed","message":"At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.","details":[{"code":"BadRequest","message":"{\r\n  "error": {\r\n    "code": "InvalidTemplate",\r\n    "message": "Unable to process template language expressions for resource '/subscriptions//resourceGroups//providers/Microsoft.Web/connections/servicebus/accessPolicies/' at line '124' and column '5'. 'The language expression property 'principalId' doesn't exist, available properties are 'type, userAssignedIdentities'.'",\r\n    "additionalInfo": [\r\n      {\r\n        "type": "TemplateViolation",\r\n        "info": {\r\n          "lineNumber": 124,\r\n          "linePosition": 5,\r\n          "path": ""\r\n        }\r\n      }\r\n    ]\r\n  }\r\n}"}]}}

also:

```<code>resource logicAppServiceBusRoleAssignment 'Microsoft.Authorization/roleAssignments@2020-10-01-preview' = {
  scope: serviceBusNamespace
  name: guid('${serviceBusNamespaceName}-${roleDefinitionId}')
  properties: {
    principalType: 'ServicePrincipal'
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', roleDefinitionId)
    principalId: logicApp.identity.principalId
  }
}
</code>```

which yields this error:

ERROR: {"code": "InvalidTemplateDeployment", "message": "The template deployment failed with error: 'Authorization failed for template resource '' of type 'Microsoft.Authorization/roleAssignments'. The client '' with object id '' does not have permission to perform action 'Microsoft.Authorization/roleAssignments/write' at scope '/subscriptions//resourceGroups//providers/Microsoft.ServiceBus/namespaces//providers/Microsoft.Authorization/roleAssignments/'.'."}

for the role, it lacks permissions to add the role.

my logic app bicep file is as follows:

```<code>param logicAppName string // The name of the logic app to create.
param location string //Location for all resources.
param workflowDefinition object // the workflow schema in json
param connectorName string
param serviceBusNamespaceName string

resource managedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2022-01-31-preview' = {
  name: <managedIDname>
  location: location
}

resource servicebusConnector 'Microsoft.Web/connections@2016-06-01' = {
  name: connectorName
  location: location
  kind: 'V2'
  properties: {
    api: {
      id: concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Web/locations/', resourceGroup().location, '/managedApis/servicebus')
    }

    displayName: connectorName
    parameterValueSet: {
      name: 'managedIdentityAuth'
      values: {
        namespaceEndpoint: {
          value: '<endpoint>'
        }
      }
    }
  }
}

resource logicApp 'Microsoft.Logic/workflows@2019-05-01' = {
  name: logicAppName
  location: location

  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${managedIdentity.id}': {}
    }
  }

  tags: {
    displayName: logicAppName
  }
  properties: {
    state: 'Enabled'
    definition: workflowDefinition.definition
    parameters: workflowDefinition.parameters
  }

}

</code>```

and for the service bus I have the following code:

```<code>param serviceBusNamespaceName string //Name of the Service Bus namespace
param serviceBusQueueName string // Name of the Queue
param location string // Location for all resources.
param topicApprovalName string // name of the topic for approval
param topicApprovalSubscriptionName string // name of the topic subscription
param connectorName string // name of the connector
param logicAppName string
param roleDefinitionId string = '8e3af657-a8ff-443c-a75c-2fe8c4bcb635'

resource logicApp 'Microsoft.Logic/workflows@2019-05-01' existing = {
  name: logicAppName
}

resource lamanagedidentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2022-01-31-preview' existing = {
  name: 'managedIdentity'
}

resource serviceBusNamespace 'Microsoft.ServiceBus/namespaces@2022-01-01-preview' = {
  name: serviceBusNamespaceName
  location: location
  sku: {
    name: 'Standard'
  }
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${lamanagedidentity.id}': {}
    }
  }
  properties: {}
}

resource serviceBusQueue 'Microsoft.ServiceBus/namespaces/queues@2022-01-01-preview' = {
  parent: serviceBusNamespace
  name: serviceBusQueueName
  properties: {
    lockDuration: 'PT5M'
    maxSizeInMegabytes: 1024
    requiresDuplicateDetection: false
    requiresSession: false
    defaultMessageTimeToLive: 'P10675199DT2H48M5.4775807S'
    deadLetteringOnMessageExpiration: false
    duplicateDetectionHistoryTimeWindow: 'PT10M'
    maxDeliveryCount: 10
    autoDeleteOnIdle: 'P10675199DT2H48M5.4775807S'
    enablePartitioning: false
    enableExpress: false
  }
}

resource topic 'Microsoft.ServiceBus/namespaces/topics@2021-11-01' = {
  name: topicApprovalName
  parent: serviceBusNamespace
}

resource topicsubscription 'Microsoft.ServiceBus/namespaces/topics/subscriptions@2022-01-01-preview' = {
  name: topicApprovalSubscriptionName
  parent: topic
}

resource sbNamespaceAuthRules 'Microsoft.ServiceBus/namespaces/AuthorizationRules@2022-01-01-preview' = {
  name: <auth name>
  parent: serviceBusNamespace
  properties: {
    rights: [
      'Listen'
      'Manage'
      'Send'
    ]
  }
}

resource servicebusConnector 'Microsoft.Web/connections@2018-07-01-preview' = {
  name: connectorName
  location: location
  kind: 'V2'
  properties: {
    api: {
      id: '/subscriptions/${subscription().subscriptionId}/providers/Microsoft.Web/locations/${location}/managedApis/servicebus'
    }
    displayName: connectorName
    parameterValueSet: {
      name: <name>
      values: {
        namespaceEndpoint: {
          value: '<endpoint>'
        }
      }
    }
  }
}

// Grant permission to the logic app standard to access the connection api
resource servicebusConnectorAccessPolicy 'Microsoft.Web/connections/accessPolicies@2018-07-01-preview' = {
  name: '${servicebusConnector.name}/${logicAppName}'
  location: location
  properties: {
    principal: {
      type: 'ActiveDirectory'
      identity: {
        tenantId: subscription().tenantId
        objectId: logicApp.identity.principalId
      }
    }
  }

}
//output connectionRuntimeUrl string = reference(servicebusConnector.id, servicebusConnector.apiVersion, 'full').properties.connectionRuntimeUrl

</code>```

Not sure why this isn't working... the issue that I'm landing on is the object id of this:

```<code>resource servicebusConnectorAccessPolicy 'Microsoft.Web/connections/accessPolicies@2018-07-01-preview' = {
  name: '${servicebusConnector.name}/${logicAppName}'
  location: location
  properties: {
    principal: {
      type: 'ActiveDirectory'
      identity: {
        tenantId: subscription().tenantId
        objectId: logicApp.identity.principalId
      }
    }
  }

}
</code>```

any help or advice would be welcome, I've been bashing my head against this for three days, and it just won't work.

thank you very much

I tried using a keyvault and connecting with a primary connection string, this did not work.
I have tried managed identity and roles, but both are not working for me.
it can find the connection, but gives an access error as cited above.

I was expecting for the connection to be authorized and for there to not be an error with the access policy.

Body:
I am trying to get a logic app to read messages from a service bus topic.  I am getting the error with the connection in logic app designer as :

Could not retrieve values. Error code: 'Unauthorized', Message: 'The remote server returned an error: (401) Unauthorized. Manage,EntityRead claims required for this operation. TrackingId:, SystemTracker:, Timestamp: clientRequestId: '. More diagnostic information: x-ms-client-request-id is ''.

currently I have tried the following in my cicd pipeline:

Grant permission to the logic app standard to access the connection api
resource servicebusConnectorAccessPolicy 'Microsoft.Web/connections/accessPolicies@2018-07-01-preview' = {
  name: '${servicebusConnector.name}/${logicAppName}'
  location: location
  properties: {
    principal: {
      type: 'ActiveDirectory'
      identity: {
        tenantId: subscription().tenantId
        objectId: logicApp.identity.principalId
      }
    }
  }
}

Get this error:
ERROR: {"status":"Failed","error":{"code":"DeploymentFailed","message":"At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.","details":[{"code":"BadRequest","message":"{\r\n  "error": {\r\n    "code": "InvalidTemplate",\r\n    "message": "Unable to process template language expressions for resource '/subscriptions//resourceGroups//providers/Microsoft.Web/connections/servicebus/accessPolicies/' at line '124' and column '5'. 'The language expression property 'principalId' doesn't exist, available properties are 'type, userAssignedIdentities'.'",\r\n    "additionalInfo": [\r\n      {\r\n        "type": "TemplateViolation",\r\n        "info": {\r\n          "lineNumber": 124,\r\n          "linePosition": 5,\r\n          "path": ""\r\n        }\r\n      }\r\n    ]\r\n  }\r\n}"}]}}

also:

resource logicAppServiceBusRoleAssignment 'Microsoft.Authorization/roleAssignments@2020-10-01-preview' = {
  scope: serviceBusNamespace
  name: guid('${serviceBusNamespaceName}-${roleDefinitionId}')
  properties: {
    principalType: 'ServicePrincipal'
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', roleDefinitionId)
    principalId: logicApp.identity.principalId
  }
}

which yields this error:

ERROR: {"code": "InvalidTemplateDeployment", "message": "The template deployment failed with error: 'Authorization failed for template resource '' of type 'Microsoft.Authorization/roleAssignments'. The client '' with object id '' does not have permission to perform action 'Microsoft.Authorization/roleAssignments/write' at scope '/subscriptions//resourceGroups//providers/Microsoft.ServiceBus/namespaces//providers/Microsoft.Authorization/roleAssignments/'.'."}

for the role, it lacks permissions to add the role.

my logic app bicep file is as follows:

param logicAppName string // The name of the logic app to create.
param location string //Location for all resources.
param workflowDefinition object // the workflow schema in json
param connectorName string
param serviceBusNamespaceName string

resource managedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2022-01-31-preview' = {
  name: <managedIDname>
  location: location
}

resource servicebusConnector 'Microsoft.Web/connections@2016-06-01' = {
  name: connectorName
  location: location
  kind: 'V2'
  properties: {
    api: {
      id: concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Web/locations/', resourceGroup().location, '/managedApis/servicebus')
    }

    displayName: connectorName
    parameterValueSet: {
      name: 'managedIdentityAuth'
      values: {
        namespaceEndpoint: {
          value: '<endpoint>'
        }
      }
    }
  }
}

resource logicApp 'Microsoft.Logic/workflows@2019-05-01' = {
  name: logicAppName
  location: location

  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${managedIdentity.id}': {}
    }
  }

  tags: {
    displayName: logicAppName
  }
  properties: {
    state: 'Enabled'
    definition: workflowDefinition.definition
    parameters: workflowDefinition.parameters
  }

}

and for the service bus I have the following code:

param serviceBusNamespaceName string //Name of the Service Bus namespace
param serviceBusQueueName string // Name of the Queue
param location string // Location for all resources.
param topicApprovalName string // name of the topic for approval
param topicApprovalSubscriptionName string // name of the topic subscription
param connectorName string // name of the connector
param logicAppName string
param roleDefinitionId string = '8e3af657-a8ff-443c-a75c-2fe8c4bcb635'

resource logicApp 'Microsoft.Logic/workflows@2019-05-01' existing = {
  name: logicAppName
}

resource lamanagedidentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2022-01-31-preview' existing = {
  name: 'managedIdentity'
}

resource serviceBusNamespace 'Microsoft.ServiceBus/namespaces@2022-01-01-preview' = {
  name: serviceBusNamespaceName
  location: location
  sku: {
    name: 'Standard'
  }
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${lamanagedidentity.id}': {}
    }
  }
  properties: {}
}

resource serviceBusQueue 'Microsoft.ServiceBus/namespaces/queues@2022-01-01-preview' = {
  parent: serviceBusNamespace
  name: serviceBusQueueName
  properties: {
    lockDuration: 'PT5M'
    maxSizeInMegabytes: 1024
    requiresDuplicateDetection: false
    requiresSession: false
    defaultMessageTimeToLive: 'P10675199DT2H48M5.4775807S'
    deadLetteringOnMessageExpiration: false
    duplicateDetectionHistoryTimeWindow: 'PT10M'
    maxDeliveryCount: 10
    autoDeleteOnIdle: 'P10675199DT2H48M5.4775807S'
    enablePartitioning: false
    enableExpress: false
  }
}

resource topic 'Microsoft.ServiceBus/namespaces/topics@2021-11-01' = {
  name: topicApprovalName
  parent: serviceBusNamespace
}

resource topicsubscription 'Microsoft.ServiceBus/namespaces/topics/subscriptions@2022-01-01-preview' = {
  name: topicApprovalSubscriptionName
  parent: topic
}

resource sbNamespaceAuthRules 'Microsoft.ServiceBus/namespaces/AuthorizationRules@2022-01-01-preview' = {
  name: <auth name>
  parent: serviceBusNamespace
  properties: {
    rights: [
      'Listen'
      'Manage'
      'Send'
    ]
  }
}

resource servicebusConnector 'Microsoft.Web/connections@2018-07-01-preview' = {
  name: connectorName
  location: location
  kind: 'V2'
  properties: {
    api: {
      id: '/subscriptions/${subscription().subscriptionId}/providers/Microsoft.Web/locations/${location}/managedApis/servicebus'
    }
    displayName: connectorName
    parameterValueSet: {
      name: <name>
      values: {
        namespaceEndpoint: {
          value: '<endpoint>'
        }
      }
    }
  }
}

// Grant permission to the logic app standard to access the connection api
resource servicebusConnectorAccessPolicy 'Microsoft.Web/connections/accessPolicies@2018-07-01-preview' = {
  name: '${servicebusConnector.name}/${logicAppName}'
  location: location
  properties: {
    principal: {
      type: 'ActiveDirectory'
      identity: {
        tenantId: subscription().tenantId
        objectId: logicApp.identity.principalId
      }
    }
  }

}
//output connectionRuntimeUrl string = reference(servicebusConnector.id, servicebusConnector.apiVersion, 'full').properties.connectionRuntimeUrl

Not sure why this isn't working... the issue that I'm landing on is the object id of this:

resource servicebusConnectorAccessPolicy 'Microsoft.Web/connections/accessPolicies@2018-07-01-preview' = {
  name: '${servicebusConnector.name}/${logicAppName}'
  location: location
  properties: {
    principal: {
      type: 'ActiveDirectory'
      identity: {
        tenantId: subscription().tenantId
        objectId: logicApp.identity.principalId
      }
    }
  }

}

any help or advice would be welcome, I've been bashing my head against this for three days, and it just won't work.

thank you very much

I tried using a keyvault and connecting with a primary connection string, this did not work.
I have tried managed identity and roles, but both are not working for me.
it can find the connection, but gives an access error as cited above.

I was expecting for the connection to be authorized and for there to not be an error with the access policy.


问:
Python imageio: What is the best way to transfer video over TCP?
I have a python program running on an embedded Linux board (like a raspberry pi), and another python program running on my PC.

I am trying to use the imageio library as a way of capturing frames from the webcam (e.g., pi camera) of the linux board, send these to my PC via a TCP connection, and then read the frames as numpy arrays on my PC, all with the lowest latency.

(Note: my previous approach was using opencv to compress frames into low-quality jpeg before sending them through TCP on the board and had a latency of ~0.25-0.5s on my local network, but I think it is suboptimal, and I do not want to use opencv).

Thus far I have been doing something like the following, but I think my approach is dumb (and it has a latency > 1s):

# Linux board:

for idx, frame in enumerate(iio.imiter("<video0>", size=(resolution[0], resolution[1]), fps=fps)):
    data = pkl.dumps(frame, 0)
    framelen = len(data)
    connection.write(struct.pack('<L', framelen))
    connection.flush()
    connection.write(data)
```
<pre class="lang-py prettyprint-override"><code># PC:

 while True:
    framelen = struct.unpack('<L', connection.read(struct.calcsize('<L')))[0]
    if not framelen:
        break

    data = connection.read(framelen)  # raw undecoded pickle bytestring
    frame = pkl.loads(data, fix_imports=True, encoding="bytes")
</code>```

Is there a way of doing something more clever/efficient, like using imageio for sending the encoded/compressed video at the desired resolution and framerate from the board through my python socket and decompressing them on my PC, please?

Thanks.

Body:
I have a python program running on an embedded Linux board (like a raspberry pi), and another python program running on my PC.

I am trying to use the imageio library as a way of capturing frames from the webcam (e.g., pi camera) of the linux board, send these to my PC via a TCP connection, and then read the frames as numpy arrays on my PC, all with the lowest latency.

(Note: my previous approach was using opencv to compress frames into low-quality jpeg before sending them through TCP on the board and had a latency of ~0.25-0.5s on my local network, but I think it is suboptimal, and I do not want to use opencv).

Thus far I have been doing something like the following, but I think my approach is dumb (and it has a latency > 1s):

# Linux board:

for idx, frame in enumerate(iio.imiter("<video0>", size=(resolution[0], resolution[1]), fps=fps)):
    data = pkl.dumps(frame, 0)
    framelen = len(data)
    connection.write(struct.pack('<L', framelen))
    connection.flush()
    connection.write(data)

# PC:

 while True:
    framelen = struct.unpack('<L', connection.read(struct.calcsize('<L')))[0]
    if not framelen:
        break

    data = connection.read(framelen)  # raw undecoded pickle bytestring
    frame = pkl.loads(data, fix_imports=True, encoding="bytes")

Is there a way of doing something more clever/efficient, like using imageio for sending the encoded/compressed video at the desired resolution and framerate from the board through my python socket and decompressing them on my PC, please?

Thanks.


问:
JSF page jumps to a new page after using the ajax filter method and fails to bind the current object
When I don't use filter from the search area.

After I clicked zoom icon. It runs as normal.

But when I use filter from the search area.

Search area of customer details always returns first data of datatable

This is part of my codes related to search area of customer list
licenseholder.xhtml

```<code><p:commandButton process="@this"
                                                         title="Details"
                                                         icon="fa button-icon-color icon-search"
                                                         action="#{licenseHolderAdmin.doShowDetails()}">
                                            <f:setPropertyActionListener value="#{serviceCustomer}" target="#{licenseHolderAdmin.holderCurrent}" />
                                            <f:setPropertyActionListener value="0" target="#{licenseHolderAdmin.activeTab}" />
                                        </p:commandButton>
</code>```

LicenseholderAdmin.java

```<code>    public String doShowDetails() {
        if (updateCurrentHolder) {
            this.getHolderCurrent();
        }

        setSelectedLicenses(new ArrayList<License>());
        return "licenseholderdetails";
    }

    public LicenseHolder getHolderCurrent() {
        if (updateCurrentHolder) {
            if (holderCurrent != null
                    && holderCurrent.getCustomerId() != null) {
                holderCurrent = customerDao.update(holderCurrent);
            }
            updateCurrentHolder = false;
        }
        return holderCurrent;
    }

</code>```

CustomerDao.java

```<code>    @Override
    public LicenseHolder findById(long id) {
        try {
            Query query = em.createQuery("select distinct lh from LicenseHolder lh where customerId = :id");
            Integer intId = (int) id;
            query.setParameter("id", intId);
            return (LicenseHolder) query.getSingleResult();
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Datensatz konnte nicht gefunden werden.", "ID=" + id));
            LOGGER.error("Error while retrieving single customer.");
            return null;
        }
    }

    public LicenseHolder update(LicenseHolder customer) {
        return findById(customer.getCustomerId());
    }
</code>```

This is part of my codes related to Search area of customer details
licenseholder-details.xhtml

```<code><p:selectOneMenu class="dropdown"  value="#{licenseHolderAdmin.holderCurrent}"  converter="licenseHolderConverter" >

<f:selectItems value="#{licenseHolderAdmin.getServiceCustomers()}" var="customer"
itemLabel="#{customer.company} (#{customer.customberNumber})" itemValue="#{customer}" />

<p:ajax event="change" oncomplete="switchToCustomer()" process="@form" />
</p:selectOneMenu>
</code>```

LicenseHolderAdmin.java

```<code>    public List<LicenseHolder> getServiceCustomers() {
        return getHolders();
    }

    public List<LicenseHolder> getHolders() {
        if (holders == null || updateHolderList) {
            holders = customerDao.getAllCustomers();
            updateHolderList = false;
        }
        return holders;
    }

</code>```

CustomerDao.java

```<code>    public List<LicenseHolder> getAllCustomers() {
        List<LicenseHolder> holders = null;

        try {
            Query query = em.createQuery("select distinct lh from LicenseHolder lh order by COMPANY");
            holders = query.getResultList();
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Datensätze konnte nicht geladen werden.", ""));
            LOGGER.error("Error while retrieving all customers.");
        }

        return holders;
    }
</code>```

I have tried f:selectItems to set itemValue="#{customer.customberNumber}". Result doesn't change.
I have also tried f:selectItems to set value="#{licenseHolderAdmin.getHolder(Long id). But I will lost function of query of dropdown. For example.

I am unfamiliar with JSF. Any advice will be grateful!

Body:
When I don't use filter from the search area.

After I clicked zoom icon. It runs as normal.

But when I use filter from the search area.

Search area of customer details always returns first data of datatable

This is part of my codes related to search area of customer list
licenseholder.xhtml

                                            <f:setPropertyActionListener value="#{serviceCustomer}" target="#{licenseHolderAdmin.holderCurrent}" />
                                            <f:setPropertyActionListener value="0" target="#{licenseHolderAdmin.activeTab}" />

LicenseholderAdmin.java

    public String doShowDetails() {
        if (updateCurrentHolder) {
            this.getHolderCurrent();
        }

        setSelectedLicenses(new ArrayList<License>());
        return "licenseholderdetails";
    }

    public LicenseHolder getHolderCurrent() {
        if (updateCurrentHolder) {
            if (holderCurrent != null
                    && holderCurrent.getCustomerId() != null) {
                holderCurrent = customerDao.update(holderCurrent);
            }
            updateCurrentHolder = false;
        }
        return holderCurrent;
    }

CustomerDao.java

    @Override
    public LicenseHolder findById(long id) {
        try {
            Query query = em.createQuery("select distinct lh from LicenseHolder lh where customerId = :id");
            Integer intId = (int) id;
            query.setParameter("id", intId);
            return (LicenseHolder) query.getSingleResult();
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Datensatz konnte nicht gefunden werden.", "ID=" + id));
            LOGGER.error("Error while retrieving single customer.");
            return null;
        }
    }

    public LicenseHolder update(LicenseHolder customer) {
        return findById(customer.getCustomerId());
    }

This is part of my codes related to Search area of customer details
licenseholder-details.xhtml

<f:selectItems value="#{licenseHolderAdmin.getServiceCustomers()}" var="customer"
itemLabel="#{customer.company} (#{customer.customberNumber})" itemValue="#{customer}" />

LicenseHolderAdmin.java

    public List<LicenseHolder> getServiceCustomers() {
        return getHolders();
    }

    public List<LicenseHolder> getHolders() {
        if (holders == null || updateHolderList) {
            holders = customerDao.getAllCustomers();
            updateHolderList = false;
        }
        return holders;
    }

CustomerDao.java

    public List<LicenseHolder> getAllCustomers() {
        List<LicenseHolder> holders = null;

        try {
            Query query = em.createQuery("select distinct lh from LicenseHolder lh order by COMPANY");
            holders = query.getResultList();
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Datensätze konnte nicht geladen werden.", ""));
            LOGGER.error("Error while retrieving all customers.");
        }

        return holders;
    }

I have tried f:selectItems to set itemValue="#{customer.customberNumber}". Result doesn't change.
I have also tried f:selectItems to set value="#{licenseHolderAdmin.getHolder(Long id). But I will lost function of query of dropdown. For example.

I am unfamiliar with JSF. Any advice will be grateful!


问:
For loop question, Why do I end up with an extra row R STUDIO
I ran a for loop to look for letters in my txt files and I calculated the probability of each letter I want and combined them into a new dataframe, but some how it create an extra row of 0s, I don't get where it came from

Please help!

Also If I want to add a new column for my file name, what is the best way to do it?

Here's what i have so far :

```<code>virus = data.frame()
for (i in virus_data){
b = read.table(i, header = FALSE)
str_split(b,"")
old_data = data.frame(A = str_count(b,"A")/str_length(b),
B = str_count(b,"B")/str_length(b),
D = str_count(b,"D")/str_length(b),
C = str_count(b,"C")/str_length(b))
virus = rbind(virus,old_data)}
</code>```

it turns out like this

Body:
I ran a for loop to look for letters in my txt files and I calculated the probability of each letter I want and combined them into a new dataframe, but some how it create an extra row of 0s, I don't get where it came from

Please help!

Also If I want to add a new column for my file name, what is the best way to do it?

Here's what i have so far :

virus = data.frame()
for (i in virus_data){
b = read.table(i, header = FALSE)
str_split(b,"")
old_data = data.frame(A = str_count(b,"A")/str_length(b),
B = str_count(b,"B")/str_length(b),
D = str_count(b,"D")/str_length(b),
C = str_count(b,"C")/str_length(b))
virus = rbind(virus,old_data)}

it turns out like this


问:
How to add an array of Keys to Nested Arrays of Values
I want to assign the keys in (arr1) to the strings in each nested array in (arr2).
I am only a month into learning javascript, and have been stuck on this problem for 3 days trying to find a working method.

I did consult this answer - Create an object from an array of keys and an array of values

I could not figure out how to do this with Nested Arrays which is why i am reposting.  Any help is greatly appreciated!!

Given the following arrays:

```<code>arr1 = ["Date","Start","High","Low","End","AdjEnd","Amount"] //KEYS I WANT TO ASSIGN TO EACH STRING
arr2 = [["1997-06-01","75","80","65","78","79","3000"],
         ["1997-06-02","70","75","60","73","74","3300"],
         ["1997-06-03","80","85","70","83","84","3800"],...] // THERE ARE 10,000+ OF THESE STRINGS
</code>```

I want the output to create objects that look like this:

```<code>var newArray = [
{
  Date: "1997-06-01",
  Start: "75",
  High: "80",
  Low: "65",
  End: "78",
  AdjEnd: "79",
  Amount: "3000"
}

{
  Date: "1997-06-02",
  Start: "70",
  High: "75",
  Low: "60",
  End: "73",
  AdjEnd: "74",
  Amount: "3300"
}

{
  Date: "1997-06-03",
  Start: "80",
  High: "85",
  Low: "70",
  End: "83",
  AdjEnd: "84",
  Amount: "3800"
}

//continuing through all nested arrays
</code>```

I tried this, it gives the correct format but only outputs 1 set instead of 10,000+

```<code>const obj3 = {};
arr1.forEach((element, index) => {
   obj3[element] = arr2[0][index];
 });
console.log(obj3);
</code>```

I also tried this but it only outputs the "Date" to the first string and doesn't convert the nested arrays into objects.

```<code>function setID(item, index) {
  var fullnames =
  "Date: " + item[0]
  "Start: " + item[1]
  "High: " + item[2]
  "Low: " + item[3]
  "End: " + item[4]
  "AdjEnd: " + item[5]
  "Amount: " + item[6];
  return fullnames;
}

var output = arr2.map(setID);
console.log(output);
</code>```

Any help is appreciated!

Body:
I want to assign the keys in (arr1) to the strings in each nested array in (arr2).
I am only a month into learning javascript, and have been stuck on this problem for 3 days trying to find a working method.

I did consult this answer - Create an object from an array of keys and an array of values

I could not figure out how to do this with Nested Arrays which is why i am reposting.  Any help is greatly appreciated!!

Given the following arrays:

arr1 = ["Date","Start","High","Low","End","AdjEnd","Amount"] //KEYS I WANT TO ASSIGN TO EACH STRING
arr2 = [["1997-06-01","75","80","65","78","79","3000"],
         ["1997-06-02","70","75","60","73","74","3300"],
         ["1997-06-03","80","85","70","83","84","3800"],...] // THERE ARE 10,000+ OF THESE STRINGS

I want the output to create objects that look like this:

var newArray = [
{
  Date: "1997-06-01",
  Start: "75",
  High: "80",
  Low: "65",
  End: "78",
  AdjEnd: "79",
  Amount: "3000"
}

{
  Date: "1997-06-02",
  Start: "70",
  High: "75",
  Low: "60",
  End: "73",
  AdjEnd: "74",
  Amount: "3300"
}

{
  Date: "1997-06-03",
  Start: "80",
  High: "85",
  Low: "70",
  End: "83",
  AdjEnd: "84",
  Amount: "3800"
}

//continuing through all nested arrays

I tried this, it gives the correct format but only outputs 1 set instead of 10,000+

const obj3 = {};
arr1.forEach((element, index) => {
   obj3[element] = arr2[0][index];
 });
console.log(obj3);

I also tried this but it only outputs the "Date" to the first string and doesn't convert the nested arrays into objects.

function setID(item, index) {
  var fullnames =
  "Date: " + item[0]
  "Start: " + item[1]
  "High: " + item[2]
  "Low: " + item[3]
  "End: " + item[4]
  "AdjEnd: " + item[5]
  "Amount: " + item[6];
  return fullnames;
}

var output = arr2.map(setID);
console.log(output);

Any help is appreciated!


问:
Change the timestamp of an .exe, via python code
I developed a code that changes me all the datetime, but I can't get the last string to change for example:
!2022/11/04:11:23:02!5f6dd6! I can change everything except the final part !5f6dd6!

you know what it refers to and how to integrate it into python code

```<code>from binascii import hexlify
import random
import pefile

file = input("Drag file here: ")

pe = pefile.PE(file)

def writetimestamp(filename, newtimestamp):
    try:
        filehandle = open(filename, 'r+b')

        if hexlify(filehandle.read(2)) != hexlify(bytes('MZ',
                                                        encoding="utf8")):
            filehandle.close()
            print("not  pe format")
            return
    except Exception as e:
        print(e)
        return

    try:
        filehandle.seek(60, 0)
        offset = filehandle.read(4)
        offset = hexlify(offset[::-1])

        if offset == '':
            print("no offset")
            filehandle.close()
            return

        offset = int(offset, 16)

        filehandle.seek(offset + 8, 0)
        filehandle.write(newtimestamp)
        filehandle.close()
    except Exception as e:
        print(e)
        return

writetimestamp(file, bytes.fromhex(str(random.randint(10000000, 99999999))))
</code>```

Body:
I developed a code that changes me all the datetime, but I can't get the last string to change for example:
!2022/11/04:11:23:02!5f6dd6! I can change everything except the final part !5f6dd6!

you know what it refers to and how to integrate it into python code

from binascii import hexlify
import random
import pefile

file = input("Drag file here: ")

pe = pefile.PE(file)

def writetimestamp(filename, newtimestamp):
    try:
        filehandle = open(filename, 'r+b')

        if hexlify(filehandle.read(2)) != hexlify(bytes('MZ',
                                                        encoding="utf8")):
            filehandle.close()
            print("not  pe format")
            return
    except Exception as e:
        print(e)
        return

    try:
        filehandle.seek(60, 0)
        offset = filehandle.read(4)
        offset = hexlify(offset[::-1])

        if offset == '':
            print("no offset")
            filehandle.close()
            return

        offset = int(offset, 16)

        filehandle.seek(offset + 8, 0)
        filehandle.write(newtimestamp)
        filehandle.close()
    except Exception as e:
        print(e)
        return

writetimestamp(file, bytes.fromhex(str(random.randint(10000000, 99999999))))


问:
Do I have to enable billing for my project to use google analytics data API?
As the image, they said Enable billing for your account is a pre-requisite for using google analytics data API. Since I have no enabled billing for my account, do I not able to use it?


问:
SQS Consumers Setting, are there any disadvantages for setting consumers less than or greater than the existing worker node/executors in the cluster?
Are there any disadvantages for setting SQS Consumers less than or greater than the existing worker nodes in a Spark streaming cluster?

For example, I have 10 worker nodes, each represents 1 executor in a Spark app.

Is the optimal SQS Consumer setting 10? What if I set it to 5 or 15? Are there any disadvantages? I don't see any documentation on this unfortunately.

Thanks!


问:
How to make the datatable react to filters?
I have applied a filter on a column of the datatable and everything(selecting filters, clear filters) works just fine, but when i click apply, the data in the table does not change based on the filter

I have honestly tried everything but nothing works


问:
How can I wrap NSView in SwiftUI macOS?
I am trying to build a NSView wrapper, I made this code so far:

struct NSViewWrapper: View {
    let nsView: NSView
    var body: some View {
        NSHostingView(rootView: nsView)
    }
}
```
<p>I tried this code but Xcode say:</p>
<p>Return type of property 'body' requires that 'NSHostingView' conform to 'View'</p>
<p>Generic class 'NSHostingView' requires that 'NSView' conform to 'View'</p>
<p>Static method 'buildBlock' requires that 'NSHostingView' conform to 'View'</p>
<p>How can make this wrapper works and solving the issues?</p>
<p>I updated my code to:</p>
<pre class="lang-swift prettyprint-override"><code>struct nsViewRepresentable: NSViewRepresentable {
    typealias NSViewType = NSView

    func makeNSView(context: Context) -> NSView {

    }

    func updateNSView(_ nsView: NSView, context: Context) {

    }
}
</code>```

Error: Missing return in instance method expected to return 'NSView'

Title: How can I wrap NSView in SwiftUI macOS?

Body:
I am trying to build a NSView wrapper, I made this code so far:

struct NSViewWrapper: View {
    let nsView: NSView
    var body: some View {
        NSHostingView(rootView: nsView)
    }
}

I tried this code but Xcode say:

Return type of property 'body' requires that 'NSHostingView' conform to 'View'

Generic class 'NSHostingView' requires that 'NSView' conform to 'View'

Static method 'buildBlock' requires that 'NSHostingView' conform to 'View'

How can make this wrapper works and solving the issues?

I updated my code to:

struct nsViewRepresentable: NSViewRepresentable {
    typealias NSViewType = NSView

    func makeNSView(context: Context) -> NSView {

    }

    func updateNSView(_ nsView: NSView, context: Context) {

    }
}

Error: Missing return in instance method expected to return 'NSView'


问:
BluetoothSocket `read failed, socket might closed or timeout` when first connected with connectGatt
In summary, does a device with a RN4678 module accept connections over UART and SPP at the same time?

The goal is to use both Bluetooth Smart UART and Bluetooth Classic SPP to send data to a device. From what I understand, Android can connect to multiple devices, but it is unclear if the device can accept connections over both Smart and Classic at the same time.

The app is connecting to a RN4678 Bluetooth® 4.2 Dual-Mode Module. I could not find any definition for "dual-mode" in any of the documentation.

It is already connected to through a GattCallback (Bluetooth Smart). In another thread, I call createRfcommSocketToServiceRecord with 00001101-0000-1000-8000-00805F9B34FB and call connect to create the socket (Bluetooth Classic). When calling connect, an exception is produced:

```<code>E/Receiver: Failed to start Bluetooth Classic socket
    java.io.IOException: read failed, socket might closed or timeout, read ret: -1
        at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:920)
        at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:934)
        at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:494)
        at com.agragps.agragps.services.receiver.ReceiverGatt.lambda$finishConnect$12$com-agragps-agragps-services-receiver-ReceiverGatt(ReceiverGatt.java:485)
        at com.agragps.agragps.services.receiver.ReceiverGatt$$ExternalSyntheticLambda10.call(Unknown Source:2)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
</code>```

For GattCallback:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    gatt = device.connectGatt(
        this,
        false,
        mGattCallback,
        BluetoothDevice.TRANSPORT_LE,
        BluetoothDevice.PHY_OPTION_NO_PREFERRED,
        mReceiverHandler);
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        gatt = device.connectGatt(
            this,
            false,
            mGattCallback,
            BluetoothDevice.TRANSPORT_LE);
    else
        gatt = device.connectGatt(
            this,
            false,
            mGattCallback);
```
<p>For BluetoothSocket</p>
<pre class="lang-java prettyprint-override"><code>mRFCOMMSocket = mRFCOMMExecutor.submit((Callable<BluetoothSocket>) () -> {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ActivityCompat.checkSelfPermission(mService, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
        mLogger.log(Level.WARNING, "Bluetooth classic thread does not have Bluetooth_Connect permission");
        return null;
    }
    try {
        BluetoothSocket socket = mDevice.createRfcommSocketToServiceRecord(SPPCommonUUID);
                    ((BluetoothManager)mService.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter().cancelDiscovery();
        socket.connect();
        mLogger.log(Level.INFO, "Connected through Bluetooth classic after Bluetooth LE");
        return socket;
    } catch (IOException e) {
        mLogger.log(Level.SEVERE, "Failed to start Bluetooth Classic socket", e);
    }
    return null;
});
</code>```

Body:
In summary, does a device with a RN4678 module accept connections over UART and SPP at the same time?

The goal is to use both Bluetooth Smart UART and Bluetooth Classic SPP to send data to a device. From what I understand, Android can connect to multiple devices, but it is unclear if the device can accept connections over both Smart and Classic at the same time.

The app is connecting to a RN4678 Bluetooth® 4.2 Dual-Mode Module. I could not find any definition for "dual-mode" in any of the documentation.

It is already connected to through a GattCallback (Bluetooth Smart). In another thread, I call createRfcommSocketToServiceRecord with 00001101-0000-1000-8000-00805F9B34FB and call connect to create the socket (Bluetooth Classic). When calling connect, an exception is produced:

E/Receiver: Failed to start Bluetooth Classic socket
    java.io.IOException: read failed, socket might closed or timeout, read ret: -1
        at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:920)
        at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:934)
        at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:494)
        at com.agragps.agragps.services.receiver.ReceiverGatt.lambda$finishConnect$12$com-agragps-agragps-services-receiver-ReceiverGatt(ReceiverGatt.java:485)
        at com.agragps.agragps.services.receiver.ReceiverGatt$$ExternalSyntheticLambda10.call(Unknown Source:2)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)

For GattCallback:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    gatt = device.connectGatt(
        this,
        false,
        mGattCallback,
        BluetoothDevice.TRANSPORT_LE,
        BluetoothDevice.PHY_OPTION_NO_PREFERRED,
        mReceiverHandler);
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        gatt = device.connectGatt(
            this,
            false,
            mGattCallback,
            BluetoothDevice.TRANSPORT_LE);
    else
        gatt = device.connectGatt(
            this,
            false,
            mGattCallback);

For BluetoothSocket

mRFCOMMSocket = mRFCOMMExecutor.submit((Callable<BluetoothSocket>) () -> {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ActivityCompat.checkSelfPermission(mService, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
        mLogger.log(Level.WARNING, "Bluetooth classic thread does not have Bluetooth_Connect permission");
        return null;
    }
    try {
        BluetoothSocket socket = mDevice.createRfcommSocketToServiceRecord(SPPCommonUUID);
                    ((BluetoothManager)mService.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter().cancelDiscovery();
        socket.connect();
        mLogger.log(Level.INFO, "Connected through Bluetooth classic after Bluetooth LE");
        return socket;
    } catch (IOException e) {
        mLogger.log(Level.SEVERE, "Failed to start Bluetooth Classic socket", e);
    }
    return null;
});


问:
new-object System.IO.FileStream passing the file name Vs passing the file path
I have this code as part of a script which get  SharePoint on-premises file and save it to local folder:-

```<code>$file = $spSourceWeb.GetFile($ItemAttachmentURLPrefix + $attachment)
$bytes = $file.OpenBinary()
$AttachmentFileName = $FilePrefix + "_AP_" + $InvoiceIDFormatted + "_" + $attachment
$Attachmentpath = $AttachmentFolder + $AttachmentFileName
$fs = new-object System.IO.FileStream($Attachmentpath, "OpenOrCreate")
$fs.Write($bytes, 0 , $bytes.Length)
$fs.Close()
</code>```

now at first i thought the $Attachmentpath inside the $fs = new-object System.IO.FileStream($Attachmentpath, "OpenOrCreate") will define the path where the file will be saved locally, but seems this variable $Attachmentpath will define the file name.. so what define the file local path?

Thanks

Body:
I have this code as part of a script which get  SharePoint on-premises file and save it to local folder:-

$file = $spSourceWeb.GetFile($ItemAttachmentURLPrefix + $attachment)
$bytes = $file.OpenBinary()
$AttachmentFileName = $FilePrefix + "_AP_" + $InvoiceIDFormatted + "_" + $attachment
$Attachmentpath = $AttachmentFolder + $AttachmentFileName
$fs = new-object System.IO.FileStream($Attachmentpath, "OpenOrCreate")
$fs.Write($bytes, 0 , $bytes.Length)
$fs.Close()

now at first i thought the $Attachmentpath inside the $fs = new-object System.IO.FileStream($Attachmentpath, "OpenOrCreate") will define the path where the file will be saved locally, but seems this variable $Attachmentpath will define the file name.. so what define the file local path?

Thanks


问:
Form fields not showing when including form template
The form fields don't show when including form in another template. This is the form:

```<code>class ClinicSearchForm(forms.Form):
    q = forms.CharField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['q'].label = 'Search for'
        self.fields['q'].widget.attrs.update(
            {'class': 'form-control'})
</code>```

This is the template:

```<code><form method="get">
    {{ form.as_p }}
    <input type="submit" class="btn btn-primary my-1" value="Search">
</form>
</code>```

And the view:

```<code>def clinic_search(request):
    form = ClinicSearchForm
    results = []
    if 'q' in request.GET:
        form = ClinicSearchForm(request.GET)
        if form.is_valid():
            q = form.cleaned_data['q']
            results = Clinic.objects.filter(name__icontains=q)

    context = {
        'form' : form,
        'results' : results,
    }

    return render(request, 'guide/clinic/clinic_search.html', context)
</code>```

I'm including the form with the include tag but I only get rendered the button, not the field.
The form shows when in its own url, but not when included in another template (this other template has no other forms).
What am I missing?

Body:
The form fields don't show when including form in another template. This is the form:

class ClinicSearchForm(forms.Form):
    q = forms.CharField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['q'].label = 'Search for'
        self.fields['q'].widget.attrs.update(
            {'class': 'form-control'})

This is the template:

<form method="get">
    {{ form.as_p }}
    <input type="submit" class="btn btn-primary my-1" value="Search">
</form>

And the view:

def clinic_search(request):
    form = ClinicSearchForm
    results = []
    if 'q' in request.GET:
        form = ClinicSearchForm(request.GET)
        if form.is_valid():
            q = form.cleaned_data['q']
            results = Clinic.objects.filter(name__icontains=q)

    context = {
        'form' : form,
        'results' : results,
    }

    return render(request, 'guide/clinic/clinic_search.html', context)

I'm including the form with the include tag but I only get rendered the button, not the field.
The form shows when in its own url, but not when included in another template (this other template has no other forms).
What am I missing?


问:
How to take another attribute value from another table, with known value from existing table
I'm trying to make a website where the system can generate patient bills based on clinic category and the action they've got in the clinic.

I have 3 tables :

Table to input the list of clinic category ("poli")

Table to input the list of clinic possible action for the patient ("tindakan")

Final table to input all of the above, where the patient choose one of the "poli" and the "tindakan" ("pasien").

This is some of my "poli" table entries :

```<code>    poli::create([
        'inisial' => 'GIGI',
        'namapoli' => 'Poli Gigi',
        'harga' => '12000',
    ]);

    poli::create([
        'inisial' => 'IMUN',
        'namapoli' => 'Poli Imun',
        'harga' => '10000',
    ]);
</code>```

This is some of my "tindakan" table entries :

```<code>    tindakan::create([
        'namatindak' => 'Tindakan Medis Sederhana',
        'harga' => '10000',
    ]);

    tindakan::create([
        'namatindak' => 'Tindakan Medis Ringan',
        'harga' => '15000',
    ]);

    tindakan::create([
        'namatindak' => 'Tindakan Medis Sedang',
        'harga' => '30000',
    ]);
</code>```

This is my current input form for "pasien" :

```<code><div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title">Tambahkan Pasien</h4>
                <h6 class="card-subtitle">Form untuk menambahkan pasien baru.</h6><br>
                <form method="post" action="/pasien" enctype="multipart/form-data">
                    @csrf
                    <div class="form-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="masuk">Tanggal</label>
                                    <input type="date" id="masuk" name="masuk" class="form-control @error('masuk') is-invalid @enderror" placeholder="Tanggal Perawatan">
                                    @error ('masuk')
                                    <div class="invalid-feedback">
                                                        {{ $message }}
                                                    </div>
                                                @enderror
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="nama">Nama</label>
                                                <input type="text" id="nama" name="nama" class="form-control @error('nama') is-invalid @enderror" placeholder="Nama Lengkap">
                                                @error ('nama')
                                                    <div class="invalid-feedback">
                                                        {{ $message }}
                                                    </div>
                                                @enderror
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="poli">Poli</label>
                                                <select class="form-control" name="poli" id="role">
                                                    @foreach ($poli as $info_poli)
                                                        <option value="{{ $info_poli->inisial }}">{{ $info_poli->inisial }}</option>
                                                    @endforeach
                                                </select>

                                                @error ('poli')
                                                    <div class="invalid-feedback">
                                                        {{ $message }}
                                                    </div>
                                                @enderror
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="tindakan">Tindakan</label>
                                                <select class="form-control" name="tindakan" id="tindakan">
                                                    <option value="-">...</option>
                                                    @foreach ($tindakan as $info_tindakan)
                                                        <option value="{{ $info_tindakan->namatindak }}">{{ $info_tindakan->namatindak }}</option>
                                                    @endforeach
                                                </select>

                                                @error ('tindakan')
                                                    <div class="invalid-feedback">
                                                        {{ $message }}
                                                    </div>
                                                @enderror
                                            </div>
                                        </div>
                                    </div>

                                </div>
                                <div class="form-actions">
                                    <div class="text-right">
                                        <button type="submit" class="btn btn-info">Submit</button>
                                        <button type="reset" class="btn btn-dark">Reset</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
</code>```

This is my current table for "pasien" :

```<code><div class="table-responsive">
                                <a href="/pasien/create" class="btn btn-block btn-success">Tambah Data</a><br>
                                <table id="zero_config" class="table table-striped table-bordered no-wrap">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>No. Karcis</th>
                                            <th>Tanggal Masuk</th>
                                            <th>Nama</th>
                                            <th>Poli</th>
                                            <th>Harga Karcis</th>
                                            <th>Tindakan</th>
                                            <th>Harga Tindakan</th>
                                            <th>Total</th>

                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach ($pasien as $info_pasien)
                                        <tr>
                                            <th>{{ $loop->iteration }}</th>

                                            <td>{{ $info_pasien->id }}</td>
                                            <td>{{ $info_pasien->masuk }}</td>
                                            <td>{{ $info_pasien->nama }}</td>
                                            <td>{{ $info_pasien->poli }}</td>
                                            <td>{{ $info_pasien->poli }}</td>
                                            <td>{{ $info_pasien->tindakan }}</td>
                                            <td>{{ $info_pasien->tindakan }}</td>
                                            <td>total</td>

                                            <td>
                                                <a href="/pasien/{{ $info_pasien->id }}/edit" class="badge bg-primary"><i data-feather="edit" style="color:white"></i></a>
                                                <form action="/pasien/{{ $info_pasien->id }}" method="post" class="d-inline">
                                                    @method('delete')
                                                    @csrf
                                                    <button class="badge bg-danger border-0" onclick="return confirm('Yakin hapus?')"><i data-feather="trash" style="color:white"></i></a>
                                                </form>
                                            </td>
                                        </tr>
                                        @endforeach
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th>#</th>
                                            <th>No. Karcis</th>
                                            <th>Tanggal Masuk</th>
                                            <th>Nama</th>
                                            <th>Poli</th>
                                            <th>Harga Karcis</th>
                                            <th>Tindakan</th>
                                            <th>Harga Tindakan</th>
                                            <th>Total</th>

                                            <th>Action</th>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
</code>```

This is my current "pasien" controller, I've tried calling the tables with "pasien" "id" but i don't know how to call them :

```<code><?php

namespace App\Http\Controllers;

use App\Models\pasien;

use App\Models\poli;
use App\Models\tindakan;
use Illuminate\Http\Request;
use Carbon\Carbon;

class dashpasienController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view ('dashboard.pasien.index', [
            'pasien' => pasien::orderBy('id', 'desc')->latest()->get(),
            'sekarang' => Carbon::now(),

            'poli' => poli::orderBy('id', 'desc')->latest()->get(),
            'tindakan' => tindakan::orderBy('id', 'desc')->latest()->get(),
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view ('dashboard.pasien.create', [

            'poli' => poli::orderBy('id', 'desc')->first()->get(),
            'tindakan' => tindakan::orderBy('id', 'desc')->first()->get(),
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validateData = $request->validate([

            'masuk' => 'required',
            'nama' => 'required',
            'poli' => 'required',
            'tindakan' => 'required',
        ]);

        pasien::create($validateData);

        return redirect('/pasien')->with('success','Data pasien berhasil ditambahkan');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\pasien  $pasien
     * @return \Illuminate\Http\Response
     */
    public function show(pasien $pasien)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\pasien  $pasien
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return view('dashboard.pasien.edit',[

            'poli' => poli::orderBy('id', 'desc')->first()->get(),
            'tindakan' => tindakan::orderBy('id', 'desc')->first()->get(),
        ])->with(['pasien' => pasien::findOrFail($id)]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\pasien  $pasien
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        $validateData = $request->validate([

            'masuk' => 'required',
            'nama' => 'required',
            'poli' => 'required',
            'tindakan' => 'required',
        ]);

        pasien::where('id', $id)->update($validateData);

        return redirect('/pasien')->with('success','Data pasien berhasil diperbarui');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\pasien  $pasien
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        pasien::destroy($id);

        return redirect('/pasien')->with('success','Data pasien berhasil dihapus');
    }
}
</code>```

Is it possible to get "poli->harga" from "poli" table and "tindakan->harga" from "tindakan" table to the current "harga poli" and "harga tindakan" column in "pasien" database. I also uploaded some picture to illustrate what I'm trying to do (see screenshot).

Body:
I'm trying to make a website where the system can generate patient bills based on clinic category and the action they've got in the clinic.

I have 3 tables :

Table to input the list of clinic category ("poli")

Table to input the list of clinic possible action for the patient ("tindakan")

Final table to input all of the above, where the patient choose one of the "poli" and the "tindakan" ("pasien").

This is some of my "poli" table entries :

    poli::create([
        'inisial' => 'GIGI',
        'namapoli' => 'Poli Gigi',
        'harga' => '12000',
    ]);

    poli::create([
        'inisial' => 'IMUN',
        'namapoli' => 'Poli Imun',
        'harga' => '10000',
    ]);

This is some of my "tindakan" table entries :

    tindakan::create([
        'namatindak' => 'Tindakan Medis Sederhana',
        'harga' => '10000',
    ]);

    tindakan::create([
        'namatindak' => 'Tindakan Medis Ringan',
        'harga' => '15000',
    ]);

    tindakan::create([
        'namatindak' => 'Tindakan Medis Sedang',
        'harga' => '30000',
    ]);

This is my current input form for "pasien" :

Tambahkan Pasien

Form untuk menambahkan pasien baru.

                <form method="post" action="/pasien" enctype="multipart/form-data">
                    @csrf

                                    Tanggal
                                    <input type="date" id="masuk" name="masuk" class="form-control @error('masuk') is-invalid @enderror" placeholder="Tanggal Perawatan">
                                    @error ('masuk')

                                                        {{ $message }}

                                                @enderror

                                                Nama
                                                <input type="text" id="nama" name="nama" class="form-control @error('nama') is-invalid @enderror" placeholder="Nama Lengkap">
                                                @error ('nama')

                                                        {{ $message }}

                                                @enderror

                                                Poli
                                                <select class="form-control" name="poli" id="role">
                                                    @foreach ($poli as $info_poli)
                                                        <option value="{{ $info_poli->inisial }}">{{ $info_poli->inisial }}</option>
                                                    @endforeach
                                                </select>

                                                @error ('poli')

                                                        {{ $message }}

                                                @enderror

                                                Tindakan
                                                <select class="form-control" name="tindakan" id="tindakan">
                                                    <option value="-">...</option>
                                                    @foreach ($tindakan as $info_tindakan)
                                                        <option value="{{ $info_tindakan->namatindak }}">{{ $info_tindakan->namatindak }}</option>
                                                    @endforeach
                                                </select>

                                                @error ('tindakan')

                                                        {{ $message }}

                                                @enderror

                                        <button type="submit" class="btn btn-info">Submit</button>
                                        <button type="reset" class="btn btn-dark">Reset</button>

                            </form>

This is my current table for "pasien" :

                                Tambah Data

                                            #
                                            No. Karcis
                                            Tanggal Masuk
                                            Nama
                                            Poli
                                            Harga Karcis
                                            Tindakan
                                            Harga Tindakan
                                            Total

                                            Action

                                        @foreach ($pasien as $info_pasien)

                                            {{ $loop->iteration }}

                                            {{ $info_pasien->id }}
                                            {{ $info_pasien->masuk }}
                                            {{ $info_pasien->nama }}
                                            {{ $info_pasien->poli }}
                                            {{ $info_pasien->poli }}
                                            {{ $info_pasien->tindakan }}
                                            {{ $info_pasien->tindakan }}
                                            total

                                                id }}/edit" class="badge bg-primary">
                                                <form action="/pasien/{{ $info_pasien->id }}" method="post" class="d-inline">
                                                    @method('delete')
                                                    @csrf
                                                    <button class="badge bg-danger border-0" onclick="return confirm('Yakin hapus?')">
                                                </form>

                                        @endforeach

                                            #
                                            No. Karcis
                                            Tanggal Masuk
                                            Nama
                                            Poli
                                            Harga Karcis
                                            Tindakan
                                            Harga Tindakan
                                            Total

                                            Action

This is my current "pasien" controller, I've tried calling the tables with "pasien" "id" but i don't know how to call them :

<?php

namespace App\Http\Controllers;

use App\Models\pasien;

use App\Models\poli;
use App\Models\tindakan;
use Illuminate\Http\Request;
use Carbon\Carbon;

class dashpasienController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view ('dashboard.pasien.index', [
            'pasien' => pasien::orderBy('id', 'desc')->latest()->get(),
            'sekarang' => Carbon::now(),

            'poli' => poli::orderBy('id', 'desc')->latest()->get(),
            'tindakan' => tindakan::orderBy('id', 'desc')->latest()->get(),
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view ('dashboard.pasien.create', [

            'poli' => poli::orderBy('id', 'desc')->first()->get(),
            'tindakan' => tindakan::orderBy('id', 'desc')->first()->get(),
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validateData = $request->validate([

            'masuk' => 'required',
            'nama' => 'required',
            'poli' => 'required',
            'tindakan' => 'required',
        ]);

        pasien::create($validateData);

        return redirect('/pasien')->with('success','Data pasien berhasil ditambahkan');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\pasien  $pasien
     * @return \Illuminate\Http\Response
     */
    public function show(pasien $pasien)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\pasien  $pasien
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return view('dashboard.pasien.edit',[

            'poli' => poli::orderBy('id', 'desc')->first()->get(),
            'tindakan' => tindakan::orderBy('id', 'desc')->first()->get(),
        ])->with(['pasien' => pasien::findOrFail($id)]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\pasien  $pasien
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        $validateData = $request->validate([

            'masuk' => 'required',
            'nama' => 'required',
            'poli' => 'required',
            'tindakan' => 'required',
        ]);

        pasien::where('id', $id)->update($validateData);

        return redirect('/pasien')->with('success','Data pasien berhasil diperbarui');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\pasien  $pasien
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        pasien::destroy($id);

        return redirect('/pasien')->with('success','Data pasien berhasil dihapus');
    }
}

Is it possible to get "poli->harga" from "poli" table and "tindakan->harga" from "tindakan" table to the current "harga poli" and "harga tindakan" column in "pasien" database. I also uploaded some picture to illustrate what I'm trying to do (see screenshot).


问:
Hibernate @preRemove doesn't work properly if on separate transaction
It seems like I can not get @preRemove to work while in a separate session for some reason (if using the object from the previous session).

Below example works. As you can see, there is one session. It gets server object and than removes it. @preRemove works and sets null to all allocations.

```<code>Session session = sessionFactory.getCurrentSession();

session.beginTransaction();

Server server = session.createQuery("from Server where id = :id", Server.class)
    .setParameter("id", "OpenSourcee")
    .getSingleResult();

session.getTransaction().commit();

session.beginTransaction();
session.remove(server);
session.getTransaction().commit();
</code>```

Below is another example. I have two sessions. In session1, I use server object that i got from session. While doing session.remove(server), it fires @preRemove properly, but it does not save server_id = null for all allocations.

```<code>Session session = sessionFactory.getCurrentSession();

session.beginTransaction();

Server server = session.createQuery("from Server where id = :id", Server.class)
    .setParameter("id", "OpenSourcee")
    .getSingleResult();

session.getTransaction().commit();

Session session1 = sessionFactory.getCurrentSession();
session.beginTransaction();
session.remove(server);
session.getTransaction().commit();
</code>```

There is a clear way to fix it. In the session I need to remove server, I can just create a new instance, based on ID from the one I got from previous session, but I'm looking for a way to avoid that... Any ideas? :)

Server model:

```<code>@Entity
@Table(name = "servers")
@Getter
@Setter
public class Server {

  @Id
  @Column(name = "id")
  private String id;

  @Column(name = "external_id")
  private Long externalId = null;

  @Column(name = "external_uuid")
  private UUID externalUuid = null;

  @Column(name = "owner", nullable = false)
  private UUID owner;

  @ManyToOne
  @JoinColumn(name = "node")
  private Node node;

  @OneToMany(mappedBy = "server", fetch = FetchType.EAGER)
  private List<Allocation> allocations;

  @JoinColumn(name = "default_allocation", referencedColumnName = "id")
  @OneToOne()
  private Allocation defaultAllocation;

  @PreRemove
  private void preRemove() {
    for (Allocation allocation : allocations) {
      allocation.setServer(null);
    }
    setAllocations(null);
  }
}
</code>```

Allocation object:

```<code>@Entity
@Table(name = "allocations")
@Getter
@Setter
public class Allocation {

  @Id
  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @Column(name = "ip", nullable = false)
  private String ip;

  @Column(name = "port", nullable = false)
  private Integer port;

  @ManyToOne
  @JoinColumn(name = "node")
  private Node node;

  @ManyToOne()
  @JoinColumn(name = "server_id")
  private Server server;
}
</code>```

Body:
It seems like I can not get @preRemove to work while in a separate session for some reason (if using the object from the previous session).

Below example works. As you can see, there is one session. It gets server object and than removes it. @preRemove works and sets null to all allocations.

Session session = sessionFactory.getCurrentSession();

session.beginTransaction();

Server server = session.createQuery("from Server where id = :id", Server.class)
    .setParameter("id", "OpenSourcee")
    .getSingleResult();

session.getTransaction().commit();

session.beginTransaction();
session.remove(server);
session.getTransaction().commit();

Below is another example. I have two sessions. In session1, I use server object that i got from session. While doing session.remove(server), it fires @preRemove properly, but it does not save server_id = null for all allocations.

Session session = sessionFactory.getCurrentSession();

session.beginTransaction();

Server server = session.createQuery("from Server where id = :id", Server.class)
    .setParameter("id", "OpenSourcee")
    .getSingleResult();

session.getTransaction().commit();

Session session1 = sessionFactory.getCurrentSession();
session.beginTransaction();
session.remove(server);
session.getTransaction().commit();

There is a clear way to fix it. In the session I need to remove server, I can just create a new instance, based on ID from the one I got from previous session, but I'm looking for a way to avoid that... Any ideas? :)

Server model:

@Entity
@Table(name = "servers")
@Getter
@Setter
public class Server {

  @Id
  @Column(name = "id")
  private String id;

  @Column(name = "external_id")
  private Long externalId = null;

  @Column(name = "external_uuid")
  private UUID externalUuid = null;

  @Column(name = "owner", nullable = false)
  private UUID owner;

  @ManyToOne
  @JoinColumn(name = "node")
  private Node node;

  @OneToMany(mappedBy = "server", fetch = FetchType.EAGER)
  private List<Allocation> allocations;

  @JoinColumn(name = "default_allocation", referencedColumnName = "id")
  @OneToOne()
  private Allocation defaultAllocation;

  @PreRemove
  private void preRemove() {
    for (Allocation allocation : allocations) {
      allocation.setServer(null);
    }
    setAllocations(null);
  }
}

Allocation object:

@Entity
@Table(name = "allocations")
@Getter
@Setter
public class Allocation {

  @Id
  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @Column(name = "ip", nullable = false)
  private String ip;

  @Column(name = "port", nullable = false)
  private Integer port;

  @ManyToOne
  @JoinColumn(name = "node")
  private Node node;

  @ManyToOne()
  @JoinColumn(name = "server_id")
  private Server server;
}


问:
Django Ajax Dropdown Select2 not return data
There is a dropdown form that I created with ajax. The form works without using the Select2 tag and returns data. But when I enter the select2 tag, it does not show the detail that should be displayed according to the selection.

I use select2 for all select fields in the system. That's why I defined the select2 tag on my layout template like this.

```<code><script>

   $('.select').select2({
        allowClear: true
    });

</script>
</code>```

Here is my ajax code :

```<code><script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_worksite_id").change(function () {
    const url = $("#subunitForm").attr("data-subunit-url");
    const worksiteId = $(this).val();

    $.ajax({
        url: url,
        data: {
            'worksite_id': worksiteId
        },
        success: function (data) {
            $("#id_upper_subunit_id").html(data);
        }
    });

});
</code>```

Thank you for your help, best regards

Body:
There is a dropdown form that I created with ajax. The form works without using the Select2 tag and returns data. But when I enter the select2 tag, it does not show the detail that should be displayed according to the selection.

I use select2 for all select fields in the system. That's why I defined the select2 tag on my layout template like this.

Here is my ajax code :


问:
Move Borderless Window Via PowerShell, VBScript, or Command Line Tool
I have a three monitor setup (total resolution 5760x1200) and I run certain applications sized to span two of those monitors (3840x1200).  These applications use borderless windows so I can't move them by simply dragging them.  By default these applications open and span across the left two monitors.  What I would like to do is script some way to move them so they can span across half a monitor, a full monitor, and half a monitor (ie: centered horizontally across the three monitors).  Is this possible, either via PowerShell, VBScript, or ideally an existing command line tool?</p>


问:
Primitive array validation with vuelidate
I'm using vuelidate 2.0 to validate a form.

I'm trying to validate a primitive array, and I can't find a way to do it.

When using helpers.forEach({ required }) it works perfectly with array of objects, but it doesn't seem to be working with array of primitives.

For example form values can be:

```<code>  const values = reactive({
     name: "",
     labels: []
  })
</code>```

Is there a way we can define labels validation?

I have tried to use:

```<code>  const validations = {
      name: { required },
      labels: {
         minLength: minLength(2),
         $each: helpers.forEach({
          required,
        }),
      }
  }
</code>```

But it seems to be working only on labels and not for each.
So what happens is that if I have less than 2 items in the array, I get the correct error, but each item is not getting the required error as should.

Body:
I'm using vuelidate 2.0 to validate a form.

I'm trying to validate a primitive array, and I can't find a way to do it.

When using helpers.forEach({ required }) it works perfectly with array of objects, but it doesn't seem to be working with array of primitives.

For example form values can be:

  const values = reactive({
     name: "",
     labels: []
  })

Is there a way we can define labels validation?

I have tried to use:

  const validations = {
      name: { required },
      labels: {
         minLength: minLength(2),
         $each: helpers.forEach({
          required,
        }),
      }
  }

But it seems to be working only on labels and not for each.
So what happens is that if I have less than 2 items in the array, I get the correct error, but each item is not getting the required error as should.


问:
`wd:Q887 wdt:P31 ?x` does not list that Yekaterinburg is a "big city". Why?
On the entity page it's listed that it's a "city or town" as well as "big city".

And if I query "What is Yekaterinburg?" via statement and specification I see that among other things it's "big city".

Query:

```<code> select ?x ?n where {
   wd:Q887 p:P31 [ps:P31 ?x].
   optional {?x rdfs:label ?n. filter(lang(?n)='en').}
 } limit 1000
</code>```

However if I query it via wdt I only see that it's "city or town" and not "big city".
Query:

```<code> select ?x ?n where {
   wd:Q887 wdt:P31 ?x.
   optional {?x rdfs:label ?n. filter(lang(?n)='en').}
 } limit 1000
</code>```

Why is that?

I could not find the explicit definition, but I thought that wdt is equivalent to sequence of p/ps turns out it's not.

Should Q887 be edited to make wdt:P31 refer to Yekatrinburg as a big city? If so, then how?

Thank you!

Body:
On the entity page it's listed that it's a "city or town" as well as "big city".

And if I query "What is Yekaterinburg?" via statement and specification I see that among other things it's "big city".

Query:

 select ?x ?n where {
   wd:Q887 p:P31 [ps:P31 ?x].
   optional {?x rdfs:label ?n. filter(lang(?n)='en').}
 } limit 1000

However if I query it via wdt I only see that it's "city or town" and not "big city".
Query:

 select ?x ?n where {
   wd:Q887 wdt:P31 ?x.
   optional {?x rdfs:label ?n. filter(lang(?n)='en').}
 } limit 1000

Why is that?

I could not find the explicit definition, but I thought that wdt is equivalent to sequence of p/ps turns out it's not.

Should Q887 be edited to make wdt:P31 refer to Yekatrinburg as a big city? If so, then how?

Thank you!


问:
queryintentactivities returns empty list android 11 in maps intent
Task - open map by deeplink. I create intent like

```<code>val uri = Uri.parse("google.navigation:q=37.419857,-122.078827");
val intent = Intent(Intent.ACTION_VIEW, uri)
</code>```

but i have not only one google maps, user can pick one more map app
question: i use queryIntentActivities to check if app is installed

```<code>val activities = packageManager?.queryIntentActivities(intent, 0)

</code>```

activities is always = 0, how can i fix this?

i know that i need to do intent in manifest , but what action?
thx

```<code>val activities = packageManager?.queryIntentActivities(intent, 0)

</code>```

activities is always = 0, how can i fix this?

i know that i need to do intent in manifest , but what action?
thx

Body:
Task - open map by deeplink. I create intent like

val uri = Uri.parse("google.navigation:q=37.419857,-122.078827");
val intent = Intent(Intent.ACTION_VIEW, uri)

but i have not only one google maps, user can pick one more map app
question: i use queryIntentActivities to check if app is installed

val activities = packageManager?.queryIntentActivities(intent, 0)

activities is always = 0, how can i fix this?

i know that i need to do intent in manifest , but what action?
thx

val activities = packageManager?.queryIntentActivities(intent, 0)

activities is always = 0, how can i fix this?

i know that i need to do intent in manifest , but what action?
thx


问:
Can't use :: Integral
I don't understand why I can't do this

fromIntegral (4 :: Integral) :: Double

fromIntegral function has such prototype:

```<code>fromIntegral :: (Integral a, Num b) => a -> b
</code>```

I think that it should be 4.0 (Double) as result.
But when I try this - an error happends:

```<code><interactive>:72:20: error:
    * Expecting one more argument to `Integral'
      Expected a type, but `Integral' has kind `* -> Constraint'
    * In an expression type signature: Integral
      In the first argument of `fromIntegral', namely `(4 :: Integral)'
      In the expression: fromIntegral (4 :: Integral) :: Double
</code>```

Title: Can't use :: Integral

Body:
I don't understand why I can't do this

fromIntegral (4 :: Integral) :: Double

fromIntegral function has such prototype:

fromIntegral :: (Integral a, Num b) => a -> b

I think that it should be 4.0 (Double) as result.
But when I try this - an error happends:

<interactive>:72:20: error:
    * Expecting one more argument to `Integral'
      Expected a type, but `Integral' has kind `* -> Constraint'
    * In an expression type signature: Integral
      In the first argument of `fromIntegral', namely `(4 :: Integral)'
      In the expression: fromIntegral (4 :: Integral) :: Double


问:
Get return value of a class method in jupyter notebook?
I have a folder called MyModule that contains an __init__.py file with the following contents:

```<code>class MyClass(object):
    def __init__(self):
        self.x = 5

    def MyOutput(self):
        return self.x
</code>```

Next to the MyModule folder I put a jupyter notebook MyNotebook.ipynb which contains the following code in a single cell:

```<code>from MyModule import MyClass
myClass = MyClass()
myClass.MyOutput()
</code>```

Now, I would have expected to see the output 5 below the cell after evaluating it. Instead there just is no output at all. I suspect that I am doing something wrong with the syntax. How should I fix it to have it display the output 5 after evaluating the cell in jupyter notebook?

Body:
I have a folder called MyModule that contains an __init__.py file with the following contents:

class MyClass(object):
    def __init__(self):
        self.x = 5

    def MyOutput(self):
        return self.x

Next to the MyModule folder I put a jupyter notebook MyNotebook.ipynb which contains the following code in a single cell:

from MyModule import MyClass
myClass = MyClass()
myClass.MyOutput()

Now, I would have expected to see the output 5 below the cell after evaluating it. Instead there just is no output at all. I suspect that I am doing something wrong with the syntax. How should I fix it to have it display the output 5 after evaluating the cell in jupyter notebook?


问:
Aligning items bottom in a scrollable container
I have a section for messages to be displayed in. I have the most recent one showing up at the bottom and they're in a fixed height container that has a scrollbar for overflow.

When there's not enough messages for the container to need to scroll, I want the messages to be aligned to the bottom of the container. I figured I could do that with flex-direction: column and justify-content: flex-end, but then it makes the container not scrollable.

Here's a jsfiddle example of what I'm looking at. As you can see, when the first three lines of the CSS are commented out the message box is functional but messages first appear at the top before the box fills up. When you uncomment the lines, the messages start appearing at the bottom but you can no longer scroll when it fills up.

let messageScrollArea = document.getElementById('message-area');
let messageScrollArea2 = document.getElementById('message-area-2');

messageScrollArea.scroll(0, 100000);
messageScrollArea2.scroll(0, 100000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#message-area,
#message-area-2 {
  /* display: flex;
    flex-direction: column;
    justify-content: flex-end; */
  height: 200px;
  width: 200px;
  padding-right: 8px;
  margin: 10px;
  overflow-y: scroll;
  overflow-x: hidden;
}

.message-card {
  width: 90%;
  margin: 3px;
  padding: 8px;
  border: 1px solid;
  border-radius: 5px;
}

#wrapper {
  display: flex;
}</code>```

      Test message

      Test message 2

      Test message 3

      Test message 4

      Test message 5

      Test message 6

      Test message

```

Body:
I have a section for messages to be displayed in. I have the most recent one showing up at the bottom and they're in a fixed height container that has a scrollbar for overflow.

When there's not enough messages for the container to need to scroll, I want the messages to be aligned to the bottom of the container. I figured I could do that with flex-direction: column and justify-content: flex-end, but then it makes the container not scrollable.

Here's a jsfiddle example of what I'm looking at. As you can see, when the first three lines of the CSS are commented out the message box is functional but messages first appear at the top before the box fills up. When you uncomment the lines, the messages start appearing at the bottom but you can no longer scroll when it fills up.

let messageScrollArea = document.getElementById('message-area');
let messageScrollArea2 = document.getElementById('message-area-2');

messageScrollArea.scroll(0, 100000);
messageScrollArea2.scroll(0, 100000);

#message-area,
#message-area-2 {
  /* display: flex;
    flex-direction: column;
    justify-content: flex-end; */
  height: 200px;
  width: 200px;
  padding-right: 8px;
  margin: 10px;
  overflow-y: scroll;
  overflow-x: hidden;
}

.message-card {
  width: 90%;
  margin: 3px;
  padding: 8px;
  border: 1px solid;
  border-radius: 5px;
}

#wrapper {
  display: flex;
}

      Test message

      Test message 2

      Test message 3

      Test message 4

      Test message 5

      Test message 6

      Test message


问:
Operations over transformers models weights
I want to blend some BERT pretrained models.
To do so I'm thinking about to do it by mix their weights.

Is it possible to make a BERT model from the weights of others?

I tried to read some documentation and forums but I didn't find any implementations of this.

I expect to find something like:
new_model.encoder.weights = 0.5 * old_model1.encoder.weights + 0.5 * old_model.encoder.weights