Why do I have only one processor id when using Async.Parallel?
Code:
open System
open System.Threading
[for i in 1..10 -> async {return i}] |> Async.Parallel
|> Async.RunSynchronously
|> Seq.iter (fun i -> printfn "Processor Id: %d Value: %d" Thread.CurrentThread.ManagedThreadId i)
Output:
Processor Id: 1 Value: 1
Processor Id: 1 Value: 2
Processor Id: 1 Value: 3
Processor Id: 1 Value: 4
Processor Id: 1 Value: 5
Processor Id: 1 Value: 6
Processor Id: 1 Value: 7
Processor Id: 1 Value: 8
Processor Id: 1 Value: 9
Processor Id: 1 Value: 10
val it : unit = ()
>
You're doing printfn from your main thread, outside your async workflow. Try this:
[for i in 1..10 ->
async {return sprintf "Processor Id: %d Value: %d" Thread.CurrentThread.ManagedThreadId i}]
|> Async.Parallel
|> Async.RunSynchronously
Related
Working with InfluxDB is new for me. My problem is I have two measurements (StopCause and MachineState). Both have some objects inside. I wanna join from MachineState to StopCause with join.left. I check the timestamp (Flux's standard _timeobject). But the result gives me not the "relation object" (so to say) what I hope to see.
First the sturctures of the objects:
StopCause
{
_start: '2023-02-09T10:00:00Z',
_stop: '2023-02-09T13:00:00Z',
_time: '2023-02-09T11:00:00Z',
_value: 100002,
_field: 'stopCauseId',
_measurement: 'StopCause',
eventId: '"267e2cab-fd2d-4684-a5fc-7792368115b3"',
machine: '5000002_dev'
},
MachineState
{
_start: '2023-02-09T10:00:00Z',
_stop: '2023-02-09T13:00:00Z',
_time: '2023-02-09T11:00:00Z',
_value: 1,
_field: 'state',
_measurement: 'MachineState',
machine: '5000002_dev'
},
You see the _time object is absolutely the same. I insert data with manually set the timestamp.
Here is the query:
*Note: I working with NodeJS and the official #influxdata/influxdb-client package. The ${VALUE} things are Javascript variables.
${dateFrom.toISOString()} = 2023-02-09T10:00:00Z
${dateTo.toISOString()} = 2023-02-09T13:00:00Z
${externalAssetId} = 5000002_dev
import "join"
import "contrib/tomhollingworth/events"
t1 = from(bucket: "Downtime_OEE")
|> range(start: ${dateFrom.toISOString()}, stop: ${dateTo.toISOString()})
|> filter(fn: (r) => r["_measurement"] == "MachineState")
|> filter(fn: (r) => r["machine"] == "${externalAssetId}")
|> group(columns: ["_time"])
t2 = from(bucket: "Downtime_OEE")
|> range(start: ${dateFrom.toISOString()}, stop: ${dateTo.toISOString()})
|> filter(fn: (r) => r["_measurement"] == "StopCause")
|> filter(fn: (r) => r["machine"] == "${externalAssetId}")
|> pivot(rowKey:["_time","eventId","machine"], columnKey: ["_field"], valueColumn: "_value")
join.left(
left: t1,
right: t2,
on: (l, r) => l._time == r._time,
as: (l, r) => {
id = if exists r.eventId then r.eventId else "Nothing"
return {_time: l._time, otime: r._time, start: l._start, eventId: id}},
)
What I expect to have:
{
result: '_result',
table: 1,
_time: '2023-02-09T11:00:00Z',
eventId: 'xyz-123456',
otime: '2023-02-09T11:00:00Z',
start: '2023-02-09T10:00:00Z'
}
What I get:
{
result: '_result',
table: 1,
_time: '2023-02-09T11:00:00Z',
eventId: 'Nothing',
otime: '2023-02-09T11:00:00Z',
start: '2023-02-09T10:00:00Z'
}
So... how do I join correctly to get the eventId?
SO i was watching this tutorial (https://www.youtube.com/watch?v=KYNbHGs-qG4)minute:14.50 to 15.14 by "tech with Tim" about the api and he put the username and ranks of the players but at me just give me the error "TypeError: string indices must be integers"
but for him works
from chessdotcom import get_leaderboards
import pprint
printer = pprint.PrettyPrinter()
def print_leaderboards():
data = get_leaderboards().json
categories = data.keys()
for category in categories:
print('Category:', category)
# idx = index
for idx, entry in enumerate(data[category]):
print(f'Rank: {idx + 1} | Username: {entry["username"]} | Rating: {entry["score"]}')
print_leaderboards()
Because there are no such keys inside "data[category]".
You need to add a subcategory from keys:
['daily', 'daily960', 'live_rapid', 'live_blitz', 'live_bullet', 'live_bughouse', 'live_blitz960', 'live_threecheck', 'live_crazyhouse', 'live_kingofthehill', 'tactics', 'rush', ' battle']
And line with FOR loop will be like:
for idx, entry in enumerate(data[category]['daily']):
And you will see:
Rank: 1 | Username: igorkovalenko | Rating: 2715
Rank: 2 | Username: RWHaines | Rating: 2604
Rank: 3 | Username: Zgorl | Rating: 2601
Rank: 4 | Username: francisbegbie | Rating: 2513
Rank: 5 | Username: Ryzeaf | Rating: 2509
Rank: 6 | Username: if_name_main_a | Rating: 2508
Rank: 7 | Username: JolinTsai | Rating: 2506
I'm trying to check if a response from the body matches partially an object of data "partialLaunchData" . I'm surprised to get this error:
● Test POST /launches › It should respond with 201 success created
expect(received).toMatchObject(expected)
- Expected - 3
+ Received + 13
Object {
- "mission": "Kepler_155",
- "rocket": "Explorer IS1",
- "target": "Kepler-186 f",
+ "launch": Object {
+ "customer": Array [
+ "SAFTA",
+ "NASA",
+ ],
+ "flightNumber": 101,
+ "launchDate": "2022-10-13T21:24:59.189Z",
+ "mission": "Kepler Exploration x",
+ "rocket": " Explorer IS1",
+ "success": true,
+ "target": "Kepler-442",
+ "upcoming": true,
+ },
}
42 | const responseDate= Date(response.body.launchDate).valueOf();
43 | expect(responseDate).toBe(requestDate);
> 44 | expect(response.body).toMatchObject(partialLaunchData);
| ^
45 | })
46 | //tests on the propreties sent
47 | test('It should catch missing required propreties', ()=>{});
at Object.toMatchObject (src/routes/launches/launches.test.js:44:31)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 3 passed, 4 total
Snapshots: 0 total
Time: 3.452 s
Ran all test suites.
This is my Code in the launches.test.js file describing a post Test on launches path "/launches" .
describe( 'Test POST /launches ', ()=> {
// test the response
const completeLaunchData={
// flightNumber: 100,
mission: 'Kepler Exploration x',
rocket: ' Explorer IS1',
launchDate: new Date(),
target: 'Kepler-442',
// customer: ['SpaceX, NASA'],
// upcoming: true,
}
const partialLaunchData={
// flightNumber: 100,
mission: 'Kepler_155',
rocket: 'Explorer IS1',
target: 'Kepler-186 f',
// upcoming: true,
}
test('It should respond with 201 success created', async()=>{
const response = await request(app).post('/launches')
// comparing two dates and joining them in one format : we will compare the value of the two dates
.send(
completeLaunchData
)
.expect('Content-Type',/json/)
.expect(201);
const requestDate = Date(completeLaunchData.launchDate).valueOf();
const responseDate= Date(response.body.launchDate).valueOf();
expect(responseDate).toBe(requestDate);
expect(response.body).toMatchObject(partialLaunchData);
})
Who has an idea about the issue ? I need help please.
Given the following struct definition:
#[derive(Builder)]
pub struct Command {
executable: String,
#[builder(each = "arg")]
args: Vec<String>,
#[builder(each = "env")]
env: Vec<String>,
current_dir: Option<String>,
}
(where the #[builder(...)] attributes are inert attributes defined by my Builder derive macro implementation),
the Builder macro cannot "see" the #[builder(...)] field attributes. The following code
let name = &f.ident;
let attrs = &f.attrs;
println!("Attributes: {:?}: {}", name, attrs.len());
(where f is a syn::Field) gives
Attributes: Some(Ident { ident: "executable", span: #0 bytes(2830..2840) }): 0
Attributes: Some(Ident { ident: "args", span: #0 bytes(2854..2858) }): 0
Attributes: Some(Ident { ident: "env", span: #0 bytes(2877..2880) }): 0
Attributes: Some(Ident { ident: "current_dir", span: #0 bytes(2899..2910) }): 0
(Full code: https://github.com/pdkovacs/forked-proc-macro-workshop/blob/a471007968f974ea3c1c684cc47a77fbd20b91dc/builder/src/lib.rs)
Can anybody help me find out what I am missing here, please?
I think you might just be interpreting the terminal output incorrectly since when I cloned your fork and removed the test code that failed to compile this is the output I got for the test with the attributes:
test tests/07-repeated-field.rs ... ok
WARNINGS:
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
warning: unused import: `builder_trait:: Builder`
--> tests/07-repeated-field.rs:32:5
|
32 | use builder_trait:: Builder;
| ^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: 1 warning emitted
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
STDOUT:
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
Attributes: Some(Ident { ident: "executable", span: #0 bytes(1471..1481) }): 0
Attributes: Some(Ident { ident: "args", span: #0 bytes(1524..1528) }): 1
Attributes: Some(Ident { ident: "env", span: #0 bytes(1576..1579) }): 1
Attributes: Some(Ident { ident: "current_dir", span: #0 bytes(1598..1609) }): 0
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
STDERR:
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
warning: unused import: `builder_trait:: Builder`
--> /home/cassy/projects/forked-proc-macro-workshop/builder/tests/07-repeated-field.rs:32:5
|
32 | use builder_trait:: Builder;
| ^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
To be clear I completely commented out the body of main in 07-repeated-field.rs since it was failing to compile, and doing so allowed me to see this output.
I haven't used trybuild before but it seems like if a test fails to build then it doesn't give you the output from the proc macro invocation. Moreover it displays the STDOUT/STDERR of the test compilation process after it displays the test name, which likely was the source of the confusion.
I am receiving the below error when trying to compile the device_handler code for the Sylvania Smart+ Plug. The code comes from https://images-na.ssl-images-amazon.com/images/I/71PrgM-PamL.pdf
The error:
Org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: script_dth_metadata_0631e407_ffd8_4ceb_b49a_877fd47635df: 94: expecting ''', found '\r' # line 94, column 55. nalResult.value == "on" ? '{{ ^ 1 error
Line 94:
def descriptionText = finalResult.value == "on" ? '{{
metadata {
definition (name: "SYLVANIA Smart Plug", namespace: "ledvanceDH", author:
"Ledvance") {
capability "Actuator"
capability "Switch"
capability "Power Meter"
capability "Configuration"
capability "Refresh"
capability "Sensor"
capability "Health Check"
fingerprint profileId: "C05E", inClusters:
"1000,0000,0003,0004,0005,0006,0B04,FC0F", outClusters: "0019", manufacturer: "OSRAM",
model: "Plug 01", deviceJoinName: "SYLVANIA Smart Plug"
fingerprint profileId: "0104", inClusters:
"0000,0003,0004,0005,0006,0B05,FC01,FC08", outClusters: "0003,0019", manufacturer:
"LEDVACE", model: "PLUG", deviceJoinName: "SYLVANIA Smart Plug"
}
// simulator metadata
simulator {
// status messages
status "on": "on/off: 1"
status "off": "on/off: 0"
// reply messages
reply "zcl on-off on": "on/off: 1"
reply "zcl on-off off": "on/off: 0"
}
preferences {
section {
image(name: 'educationalcontent', multiple: true, images: [
"http://cdn.devicegse.smartthings.com/Outlet/US/OutletUS1.jpg",
"http://cdn.devicegse.smartthings.com/Outlet/US/OutletUS2.jpg"
])
}
}
// UI tile definitions
tiles(scale: 2) {
multiAttributeTile(name:"switch", type: "lighting", width: 6, height: 4,
canChangeIcon: true){
tileAttribute ("device.switch", key: "PRIMARY_CONTROL") {
attributeState "on", label: 'On', action: "switch.off",
icon: "st.Appliances.appliances17", backgroundColor: "#79b821", nextState: "turningOff"
attributeState "off", label: 'Off', action: "switch.on",
icon: "st.Appliances.appliances17", backgroundColor: "#565C51", nextState: "turningOn"
attributeState "turningOn", label: 'Turning On', action:
"switch.off", icon: "st.Appliances.appliances17", backgroundColor: "#60903A", nextState:
"turningOff"
attributeState "turningOff", label: 'Turning Off', action:
"switch.on", icon: "st.Appliances.appliances17", backgroundColor: "#CACACA", nextState:
"turningOn"
}
tileAttribute ("power", key: "SECONDARY_CONTROL") {
attributeState "power", label:'${currentValue} W'
}
}
standardTile("refresh", "device.power", inactiveLabel: false, decoration:
"flat", width: 2, height: 2) {
state "default", label:'', action:"refresh.refresh",
icon:"st.secondary.refresh"
}
main "switch"
details(["switch","refresh"])
}
}
// Parse incoming device messages to generate events
def parse(String description) {
log.debug "description is $description"
def finalResult = zigbee.getKnownDescription(description)
def event = [:]
//TODO: Remove this after getKnownDescription can parse it automatically
if (!finalResult && description!="updated")
finalResult =
getPowerDescription(zigbee.parseDescriptionAsMap(description))
if (finalResult) {
log.info "final result = $finalResult"
if (finalResult.type == "update") {
log.info "$device updates: ${finalResult.value}"
event = null
}
else if (finalResult.type == "power") {
def powerValue = (finalResult.value as Integer)/10
event = createEvent(name: "power", value: powerValue,
descriptionText: '{{ device.displayName }} power is {{ value }} Watts', translatable:
true)
/*
Dividing by 10 as the Divisor is 10000 and unit is kW for
the device. AttrId: 0302 and 0300. Simplifying to 10
power level is an integer. The exact power level with
correct units needs to be handled in the device type
to account for the different Divisor value (AttrId: 0302)
and POWER Unit (AttrId: 0300). CLUSTER for simple metering is 0702
*/
}
else {
def descriptionText = finalResult.value == "on" ? '{{
device.displayName }} is On' : '{{ device.displayName }} is Off'
event = createEvent(name: finalResult.type, value:
finalResult.value, descriptionText: descriptionText, translatable: true)
}
}
else {
def cluster = zigbee.parse(description)
if (cluster && cluster.clusterId == 0x0006 && cluster.command == 0x07){
if (cluster.data[0] == 0x00) {
log.debug "ON/OFF REPORTING CONFIG RESPONSE: " + cluster
event = createEvent(name: "checkInterval", value: 60 * 12,
displayed: false, data: [protocol: "zigbee", hubHardwareId: device.hub.hardwareID])
}
else {
log.warn "ON/OFF REPORTING CONFIG FAILED- error
code:${cluster.data[0]}"
event = null
}
}
else {
log.warn "DID NOT PARSE MESSAGE for description : $description"
log.debug "${cluster}"
}
}
return event
}
def off() {
zigbee.off()
}
def on() {
zigbee.on()
}
/**
* PING is used by Device-Watch in attempt to reach the Device
* */
def ping() {
return zigbee.onOffRefresh()
}
def refresh() {
zigbee.onOffRefresh() + zigbee.electricMeasurementPowerRefresh()
}
def configure() {
// Device-Watch allows 2 check-in misses from device + ping (plus 1 min lag time)
// enrolls with default periodic reporting until newer 5 min interval is confirmed
sendEvent(name: "checkInterval", value: 2 * 10 * 60 + 1 * 60, displayed: false,
data: [protocol: "zigbee", hubHardwareId: device.hub.hardwareID])
// OnOff minReportTime 0 seconds, maxReportTime 5 min. Reporting interval if no
activity
refresh() + zigbee.onOffConfig(0, 300) + powerConfig()
}
//power config for devices with min reporting interval as 1 seconds and reporting
interval if no activity as 10min (600s)
//min change in value is 01
def powerConfig() {
[
"zdo bind 0x${device.deviceNetworkId} 1 ${endpointId} 0x0B04
{${device.zigbeeId}} {}", "delay 2000",
"zcl global send-me-a-report 0x0B04 0x050B 0x29 1 600 {05 00}",
//The send-me-a-report is custom to the attribute type for CentraLite
"delay 200",
"send 0x${device.deviceNetworkId} 1 ${endpointId}", "delay 2000"
]
}
private getEndpointId() {
new BigInteger(device.endpointId, 16).toString()
}
//TODO: Remove this after getKnownDescription can parse it automatically
def getPowerDescription(descMap) {
def powerValue = "undefined"
if (descMap.cluster == "0B04") {
if (descMap.attrId == "050b") {
if(descMap.value!="ffff")
powerValue = zigbee.convertHexToInt(descMap.value)
}
}
else if (descMap.clusterId == "0B04") {
if(descMap.command=="07"){
return [type: "update", value : "power (0B04) capability configured
successfully"]
}
}
if (powerValue != "undefined"){
return [type: "power", value : powerValue]
}
else {
return [:]
}
}
I should have thought of it sooner... The problem is with the copy/paste. The long lines were broken by a "return". I removed the returns and the script compiled.