问:
Can't implement synchronization in class
In the course of training, as well as with the analysis of multithreading, I decided to try my hand at thread synchronization. In this regard, I made a small test, where the creation of threads occurs through the creation of objects. And I got into a problem situation, the streams cannot be synchronized, and I don't understand what the problem is.

```<code>public class MainClass {
    static int firstInt;
    static int secondInt;
    static int thirdInt;
    public static void main(String[] args) {
        SecondClass s1 = new SecondClass("Первый");
        SecondClass s2 = new SecondClass("Второй");
        SecondClass s3 = new SecondClass("Третий");
        SecondClass s4 = new SecondClass("Четвертый");
        SecondClass s5 = new SecondClass("Пятый");

        try {
            s1.t.join();
            s2.t.join();
            s3.t.join();
            s4.t.join();
            s5.t.join();
        } catch (InterruptedException exp) {
            System.out.println("Прервано!");
        }

        System.out.println(firstInt);
        System.out.println(secondInt);
        System.out.println(thirdInt);
    }
}

class SecondClass implements Runnable {
    String name;
    Thread t;

    SecondClass(String a) {
        name = a;
        t = new Thread(this);
        t.setName(name);
        t.start();
        System.out.println("Поток с именем "+t.getName()+" создан и запущен.");
    }

    private void plusFirstInt() {
        MainClass.firstInt++;
    }

    private void plusSecondInt() {
        MainClass.secondInt++;
    }

    private void plusThirdInt() {
        MainClass.thirdInt++;
    }

    private synchronized void fori() {
        try {
            for (int i = 0; i < 10000; i++) {
                plusFirstInt();
                plusSecondInt();
                plusThirdInt();
            }
            Thread.sleep(10);
        } catch (InterruptedException exp) {
            System.out.println("Прервано!");
        }
    }

    @Override
    public void run() {
        fori();
    }
}
</code>```

Tried to sync using object reference.

```<code>Object a = new Object();

private void plusFirstInt() {
    synchronized (a){
        MainClass.firstInt++;
    }
}
</code>```

Body:
In the course of training, as well as with the analysis of multithreading, I decided to try my hand at thread synchronization. In this regard, I made a small test, where the creation of threads occurs through the creation of objects. And I got into a problem situation, the streams cannot be synchronized, and I don't understand what the problem is.

public class MainClass {
    static int firstInt;
    static int secondInt;
    static int thirdInt;
    public static void main(String[] args) {
        SecondClass s1 = new SecondClass("Первый");
        SecondClass s2 = new SecondClass("Второй");
        SecondClass s3 = new SecondClass("Третий");
        SecondClass s4 = new SecondClass("Четвертый");
        SecondClass s5 = new SecondClass("Пятый");

        try {
            s1.t.join();
            s2.t.join();
            s3.t.join();
            s4.t.join();
            s5.t.join();
        } catch (InterruptedException exp) {
            System.out.println("Прервано!");
        }

        System.out.println(firstInt);
        System.out.println(secondInt);
        System.out.println(thirdInt);
    }
}

class SecondClass implements Runnable {
    String name;
    Thread t;

    SecondClass(String a) {
        name = a;
        t = new Thread(this);
        t.setName(name);
        t.start();
        System.out.println("Поток с именем "+t.getName()+" создан и запущен.");
    }

    private void plusFirstInt() {
        MainClass.firstInt++;
    }

    private void plusSecondInt() {
        MainClass.secondInt++;
    }

    private void plusThirdInt() {
        MainClass.thirdInt++;
    }

    private synchronized void fori() {
        try {
            for (int i = 0; i < 10000; i++) {
                plusFirstInt();
                plusSecondInt();
                plusThirdInt();
            }
            Thread.sleep(10);
        } catch (InterruptedException exp) {
            System.out.println("Прервано!");
        }
    }

    @Override
    public void run() {
        fori();
    }
}

Tried to sync using object reference.

Object a = new Object();

private void plusFirstInt() {
    synchronized (a){
        MainClass.firstInt++;
    }
}


来源: stackexchange

问:
Change the request body
In Insomnia test suite, is it possible to add or update the request body?

For example, I have get/post request in a collection which takes a json as request body, I like to test the request by changing this json. By default in test suite I can select a  request and the defined json (under collections) is used for testing, what if I want to change this json request?

An example code is

```<code>const response1 = await insomnia.send();
expect(response1.status).to.equal(200);
</code>```

Is it possible to change what is posted in insomnia.send() within the test suite? As of now I have to go to the collection change this json but what if I want to test the same api end point with different jsons?

I am aware, I can test it under collection (Debug tab) by changing the JSON and directly testing there but I am trying to leverage the test suite to write a bunch of test against an end point. Insomnia uses Mochajs for testing, is there any sample of that used long with insomnia?

I cannot find any pointers in Insomnia documentation.

ContentLicense: CC BY-SA 4.0

Title: Change the request body

Body:
In Insomnia test suite, is it possible to add or update the request body?

For example, I have get/post request in a collection which takes a json as request body, I like to test the request by changing this json. By default in test suite I can select a  request and the defined json (under collections) is used for testing, what if I want to change this json request?

An example code is

const response1 = await insomnia.send();
expect(response1.status).to.equal(200);

Is it possible to change what is posted in insomnia.send() within the test suite? As of now I have to go to the collection change this json but what if I want to test the same api end point with different jsons?

I am aware, I can test it under collection (Debug tab) by changing the JSON and directly testing there but I am trying to leverage the test suite to write a bunch of test against an end point. Insomnia uses Mochajs for testing, is there any sample of that used long with insomnia?

I cannot find any pointers in Insomnia documentation.


问:
Batch call to PlaylistItems: insert YouTube API v3 with Google API Python client library produces intermittent HttpError 500
I'm using the Google API Python client library to run a batch of PlaylistItems: insert calls per the batch method described in the docs. When it's all put together it looks like this:

```<code>youtube = get_authenticated_service()
batch = youtube.new_batch_http_request(callback=insert_callback)

playlistId = "[redacted]"
video_ids   = [
               "d7ypnPjz81I",
               "vZv9-TWdBJM",
               "7uG6E6bVKU0",
               "8EzfBYFU8Q0"
             ]
playlist_items = []

for video_id in video_ids:
    batch.add(youtube.playlistItems().insert(
        part="snippet",
        body={
          "snippet": {
            "playlistId": playlistId,
            "resourceId": {
              "kind": "youtube#video",
              "videoId": video_id
            }
          }
        }
      )
    )

response = batch.execute()

print(response)

def insert_callback(request_id, response, exception):
    if exception is not None:
        print(exception)
    else:
        print(response)
</code>```

The script loops through the videos and makes an API call to add each one to the playlist, printing the result of the API call to the screen. The outcome of each call is unpredictable. In some cases, the video is successfully added to the playlist and in others, I get the following error response:

<HttpError 500 when requesting
https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&alt=json
returned "Internal error encountered.". Details: "[{'message':
'Internal error encountered.', 'domain': 'global', 'reason':
'backendError'}]">

There is no discernable pattern of success or failure. A video can fail to be added on one run and then succeed on the next.

Is there something I can do to overcome this error? If not, is there any advantage running batches and then retrying the videos that error out until they succeed?

EDIT:

The Google API team suggested that I implement a delay between API calls. Can this be done using the Python client library?

Body:
I'm using the Google API Python client library to run a batch of PlaylistItems: insert calls per the batch method described in the docs. When it's all put together it looks like this:

youtube = get_authenticated_service()
batch = youtube.new_batch_http_request(callback=insert_callback)

playlistId = "[redacted]"
video_ids   = [
               "d7ypnPjz81I",
               "vZv9-TWdBJM",
               "7uG6E6bVKU0",
               "8EzfBYFU8Q0"
             ]
playlist_items = []

for video_id in video_ids:
    batch.add(youtube.playlistItems().insert(
        part="snippet",
        body={
          "snippet": {
            "playlistId": playlistId,
            "resourceId": {
              "kind": "youtube#video",
              "videoId": video_id
            }
          }
        }
      )
    )

response = batch.execute()

print(response)

def insert_callback(request_id, response, exception):
    if exception is not None:
        print(exception)
    else:
        print(response)

The script loops through the videos and makes an API call to add each one to the playlist, printing the result of the API call to the screen. The outcome of each call is unpredictable. In some cases, the video is successfully added to the playlist and in others, I get the following error response:

<HttpError 500 when requesting
https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&alt=json
returned "Internal error encountered.". Details: "[{'message':
'Internal error encountered.', 'domain': 'global', 'reason':
'backendError'}]">

There is no discernable pattern of success or failure. A video can fail to be added on one run and then succeed on the next.

Is there something I can do to overcome this error? If not, is there any advantage running batches and then retrying the videos that error out until they succeed?

EDIT:

The Google API team suggested that I implement a delay between API calls. Can this be done using the Python client library?


问:
Why does my Ingress.yaml file not expose my containerised frontend?
I'm using microk8s to run my containerised frontend in a k8s cluster. However when I try to access it, I get a 'site can't be reached' error. I first tested it out in minikube with minikube tunnel and that works. What am I doing wrong here?
Note: I've enabled the ingress addon in microk8s with microk8s enable ingress.

ingress.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: http-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: mf1
                port:
                  number: 80
```
<br/>
<p><code>service.yaml</code></p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
  name: mf1
spec:
  type: ClusterIP
  ports:
    - port: 80
  selector:
    app: mf1

</code>```

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mf1
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mf1
  template:
    metadata:
      labels:
        app: mf1
    spec:
      nodeSelector:
        "kubernetes.io/os": linux
      containers:
        - name: mf1
          image: nginx:latest
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 250m
              memory: 256Mi
          ports:
            - containerPort: 80
              name: redis
          imagePullPolicy: Always
```

Body:
I'm using microk8s to run my containerised frontend in a k8s cluster. However when I try to access it, I get a 'site can't be reached' error. I first tested it out in minikube with minikube tunnel and that works. What am I doing wrong here?
Note: I've enabled the ingress addon in microk8s with microk8s enable ingress.

ingress.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: http-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: mf1
                port:
                  number: 80

service.yaml

apiVersion: v1
kind: Service
metadata:
  name: mf1
spec:
  type: ClusterIP
  ports:
    - port: 80
  selector:
    app: mf1

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mf1
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mf1
  template:
    metadata:
      labels:
        app: mf1
    spec:
      nodeSelector:
        "kubernetes.io/os": linux
      containers:
        - name: mf1
          image: nginx:latest
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 250m
              memory: 256Mi
          ports:
            - containerPort: 80
              name: redis
          imagePullPolicy: Always


问:
Hyperledger Fabric Service Endpoint Error While Trying to Connect Organization3 From Client
I am using Hyperledger Fabric's test network.

When I try to login Admin user with Org1 or Org2 from client side of my project, I don't have any problem. But when I try to login with Org 3 it gives these errors:

```<code>"2022-12-20T12:33:07.185Z - info: [NetworkConfig] : buildPeer - Unable to connect to the endorser peer0.org3 .example.com due to Error : Failed to connect before the deadline on Endorser- name: peer0.org3 .example.com, url:grpcs ://localhost:11051, connected:false, connectAttempted: true"
at checkState (/Users/ecem/hyperledger fab/fa bric-samples/Hyperledger -Fabric_Supplychain/a pi/node_modules/@grpc/grpc-js/build/src/client. js:77:26) at Timeout._ onTimeout (/Users/ecem/hyperledger fab/fa bric-samples/Hyperledger -Fabric_Supplychain/a pi/node_modules/@grpc/grpc-js/build/src/channel. js
:525:17)
at listOnTimeout (node:internal/timers :559:17) at processTimers (node:internal/timers :502:7) {
connectFailed: true
}
"2022-12-20T12:33:10.197Z - error : [ServiceEnd point]: Error : Failed to connect before the deadline on Discoverer- name: peer0.org3 .example.com, url:grpc s://localhost:11051, connected:false, connectAttempted: true"
2022-12-20T12:33:10.198Z - error : [ServiceEnd point]: waitForReady - Failed to connect to remote gRPC server peer0.org3 .example.com url:grpcs ://localhos t:11051 timeout:3000
"2022-12-20T12:33:10.198Z - error : [ServiceEnd point]: ServiceEnd point grpcs ://localhost:11051 reset connection failed :: Error : Failed to connect before the deadline on Discoverer- name: peer0.org3 .example.com, url:grpcs ://localhost:11051, connected:false, connectAttempted: true"
2022-12-20T12:33:10.198Z - error : [DiscoveryServiceJ : send [mychannel] - no discovery results GET /users/login?username=admin &password=adminpw &organization=org3 304 6108.941 ms - -
</code>```

I created organization 3 in the test network by using following commands respectively:

```<code>cd hyperledgerfab/fabric-samples/test-network
./network.sh down
./network.sh up createChannel -ca -s couchdb
cd addOrg3
./addOrg3.sh up -c mychannel -ca -s couchdb
export FABRIC_CFG_PATH=$PWD
../../bin/configtxgen -printOrg Org3MSP > ../organizations/peerOrganizations/org3.example.com/org3.json
export DOCKER_DEFAULT_PLATFORM=linux/amd64
docker-compose -f compose/docker/docker-compose-org3.yaml up -d
cd ..
./network.sh deployCC -ccn SupplychainContract -ccp ../HyperLedger-Fabric_Supplychain/chaincode/ -ccl javascript -ccep "OR('Org1MSP.peer','Org2MSP.peer','Org3MSP.peer')"
export PATH=${PWD}/../bin:$PATH
export FABRIC_CFG_PATH=$PWD/../config/
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"
export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051
</code>```

When I run ./addOrg3.sh up -c mychannel -ca -s couchdb, there is no problem :

```<code>2022-12-20 20:20:56.173 UTC 0001 INFO [channelCmd] InitCmdFactory -> Endorser and orderer connections initialized
2022-12-20 20:20:56.263 UTC 0002 INFO [channelCmd] update -> Successfully submitted channel update
Anchor peer set for org 'Org3MSP' on channel 'mychannel'
Channel 'mychannel' joined
Org3 peer successfully added to network
</code>```

When I run the docker-compose -f compose/docker/docker-compose-org3.yaml up -d command it seems like there is no problem:

```<code>ecem@Ecems-MacBook-Air addOrg3 % docker-compose -f compose/docker/docker-compose-org3.yaml up -d

[+] Running 1/0
⠿ Container peer0.org3.example.com  Running
</code>```

I don't have any errors while adding admins to all three organizations :

```<code>ecem@Ecems-MacBook-Air api % node enrollAdmin.js org1 admin adminpw

0: /Users/ecem/.nvm/versions/node/v16.18.1/bin/node
1: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/enrollAdmin.js
2: org1
3: admin
4: adminpw
Wallet path: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/wallet/org1
Test1
Test2
Test3
Successfully enrolled admin user "admin" and imported it into the wallet
ecem@Ecems-MacBook-Air api % node enrollAdmin.js org2 admin adminpw

0: /Users/ecem/.nvm/versions/node/v16.18.1/bin/node
1: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/enrollAdmin.js
2: org2
3: admin
4: adminpw
Wallet path: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/wallet/org2
Test1
Test2
Test3
Successfully enrolled admin user "admin" and imported it into the wallet
ecem@Ecems-MacBook-Air api % node enrollAdmin.js org3 admin adminpw

0: /Users/ecem/.nvm/versions/node/v16.18.1/bin/node
1: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/enrollAdmin.js
2: org3
3: admin
4: adminpw
Wallet path: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/wallet/org3
Test1
Test2
Test3
Successfully enrolled admin user "admin" and imported it into the wallet
</code>```

This is my docker-compose-org3.yaml file :

```<code># Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#

version: '2'

volumes:
  peer0.org3.example.com:

networks:
  test:
    name: fabric_test

services:

  peer0.org3.example.com:
    container_name: peer0.org3.example.com
    image: hyperledger/fabric-peer:latest
    environment:
      - DOCKER_DEFAULT_PLATFORM=linux/amd64
      #Generic peer variables
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=fabric_test
      - FABRIC_LOGGING_SPEC=INFO
      #- FABRIC_LOGGING_SPEC=DEBUG
      - CORE_PEER_TLS_ENABLED=true
      - CORE_PEER_PROFILE_ENABLED=true
      - CORE_PEER_TLS_CERT_FILE=/etc/hyperledger/fabric/tls/server.crt
      - CORE_PEER_TLS_KEY_FILE=/etc/hyperledger/fabric/tls/server.key
      - CORE_PEER_TLS_ROOTCERT_FILE=/etc/hyperledger/fabric/tls/ca.crt
      # Peer specific variabes
      - CORE_PEER_ID=peer0.org3.example.com
      - CORE_PEER_ADDRESS=peer0.org3.example.com:11051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:11051
      - CORE_PEER_CHAINCODEADDRESS=peer0.org3.example.com:11052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:11052
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org3.example.com:11051
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org3.example.com:11051
      - CORE_PEER_LOCALMSPID=Org3MSP
    volumes:
        - /var/run/docker.sock:/host/var/run/docker.sock
        - ../../organizations/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/msp:/etc/hyperledger/fabric/msp
        - ../../organizations/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/tls:/etc/hyperledger/fabric/tls
        - peer0.org3.example.com:/var/hyperledger/production
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
    command: peer node start
    ports:
      - 11051:11051
    networks:
      - test

</code>```

Body:
I am using Hyperledger Fabric's test network.

When I try to login Admin user with Org1 or Org2 from client side of my project, I don't have any problem. But when I try to login with Org 3 it gives these errors:

"2022-12-20T12:33:07.185Z - info: [NetworkConfig] : buildPeer - Unable to connect to the endorser peer0.org3 .example.com due to Error : Failed to connect before the deadline on Endorser- name: peer0.org3 .example.com, url:grpcs ://localhost:11051, connected:false, connectAttempted: true"
at checkState (/Users/ecem/hyperledger fab/fa bric-samples/Hyperledger -Fabric_Supplychain/a pi/node_modules/@grpc/grpc-js/build/src/client. js:77:26) at Timeout._ onTimeout (/Users/ecem/hyperledger fab/fa bric-samples/Hyperledger -Fabric_Supplychain/a pi/node_modules/@grpc/grpc-js/build/src/channel. js
:525:17)
at listOnTimeout (node:internal/timers :559:17) at processTimers (node:internal/timers :502:7) {
connectFailed: true
}
"2022-12-20T12:33:10.197Z - error : [ServiceEnd point]: Error : Failed to connect before the deadline on Discoverer- name: peer0.org3 .example.com, url:grpc s://localhost:11051, connected:false, connectAttempted: true"
2022-12-20T12:33:10.198Z - error : [ServiceEnd point]: waitForReady - Failed to connect to remote gRPC server peer0.org3 .example.com url:grpcs ://localhos t:11051 timeout:3000
"2022-12-20T12:33:10.198Z - error : [ServiceEnd point]: ServiceEnd point grpcs ://localhost:11051 reset connection failed :: Error : Failed to connect before the deadline on Discoverer- name: peer0.org3 .example.com, url:grpcs ://localhost:11051, connected:false, connectAttempted: true"
2022-12-20T12:33:10.198Z - error : [DiscoveryServiceJ : send [mychannel] - no discovery results GET /users/login?username=admin &password=adminpw &organization=org3 304 6108.941 ms - -

I created organization 3 in the test network by using following commands respectively:

cd hyperledgerfab/fabric-samples/test-network
./network.sh down
./network.sh up createChannel -ca -s couchdb
cd addOrg3
./addOrg3.sh up -c mychannel -ca -s couchdb
export FABRIC_CFG_PATH=$PWD
../../bin/configtxgen -printOrg Org3MSP > ../organizations/peerOrganizations/org3.example.com/org3.json
export DOCKER_DEFAULT_PLATFORM=linux/amd64
docker-compose -f compose/docker/docker-compose-org3.yaml up -d
cd ..
./network.sh deployCC -ccn SupplychainContract -ccp ../HyperLedger-Fabric_Supplychain/chaincode/ -ccl javascript -ccep "OR('Org1MSP.peer','Org2MSP.peer','Org3MSP.peer')"
export PATH=${PWD}/../bin:$PATH
export FABRIC_CFG_PATH=$PWD/../config/
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"
export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051

When I run ./addOrg3.sh up -c mychannel -ca -s couchdb, there is no problem :

2022-12-20 20:20:56.173 UTC 0001 INFO [channelCmd] InitCmdFactory -> Endorser and orderer connections initialized
2022-12-20 20:20:56.263 UTC 0002 INFO [channelCmd] update -> Successfully submitted channel update
Anchor peer set for org 'Org3MSP' on channel 'mychannel'
Channel 'mychannel' joined
Org3 peer successfully added to network

When I run the docker-compose -f compose/docker/docker-compose-org3.yaml up -d command it seems like there is no problem:

ecem@Ecems-MacBook-Air addOrg3 % docker-compose -f compose/docker/docker-compose-org3.yaml up -d

[+] Running 1/0
⠿ Container peer0.org3.example.com  Running

I don't have any errors while adding admins to all three organizations :

ecem@Ecems-MacBook-Air api % node enrollAdmin.js org1 admin adminpw

0: /Users/ecem/.nvm/versions/node/v16.18.1/bin/node
1: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/enrollAdmin.js
2: org1
3: admin
4: adminpw
Wallet path: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/wallet/org1
Test1
Test2
Test3
Successfully enrolled admin user "admin" and imported it into the wallet
ecem@Ecems-MacBook-Air api % node enrollAdmin.js org2 admin adminpw

0: /Users/ecem/.nvm/versions/node/v16.18.1/bin/node
1: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/enrollAdmin.js
2: org2
3: admin
4: adminpw
Wallet path: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/wallet/org2
Test1
Test2
Test3
Successfully enrolled admin user "admin" and imported it into the wallet
ecem@Ecems-MacBook-Air api % node enrollAdmin.js org3 admin adminpw

0: /Users/ecem/.nvm/versions/node/v16.18.1/bin/node
1: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/enrollAdmin.js
2: org3
3: admin
4: adminpw
Wallet path: /Users/ecem/hyperledgerfab/fabric-samples/HyperLedger-Fabric_Supplychain/api/wallet/org3
Test1
Test2
Test3
Successfully enrolled admin user "admin" and imported it into the wallet

This is my docker-compose-org3.yaml file :

# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#

version: '2'

volumes:
  peer0.org3.example.com:

networks:
  test:
    name: fabric_test

services:

  peer0.org3.example.com:
    container_name: peer0.org3.example.com
    image: hyperledger/fabric-peer:latest
    environment:
      - DOCKER_DEFAULT_PLATFORM=linux/amd64
      #Generic peer variables
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=fabric_test
      - FABRIC_LOGGING_SPEC=INFO
      #- FABRIC_LOGGING_SPEC=DEBUG
      - CORE_PEER_TLS_ENABLED=true
      - CORE_PEER_PROFILE_ENABLED=true
      - CORE_PEER_TLS_CERT_FILE=/etc/hyperledger/fabric/tls/server.crt
      - CORE_PEER_TLS_KEY_FILE=/etc/hyperledger/fabric/tls/server.key
      - CORE_PEER_TLS_ROOTCERT_FILE=/etc/hyperledger/fabric/tls/ca.crt
      # Peer specific variabes
      - CORE_PEER_ID=peer0.org3.example.com
      - CORE_PEER_ADDRESS=peer0.org3.example.com:11051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:11051
      - CORE_PEER_CHAINCODEADDRESS=peer0.org3.example.com:11052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:11052
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org3.example.com:11051
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org3.example.com:11051
      - CORE_PEER_LOCALMSPID=Org3MSP
    volumes:
        - /var/run/docker.sock:/host/var/run/docker.sock
        - ../../organizations/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/msp:/etc/hyperledger/fabric/msp
        - ../../organizations/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/tls:/etc/hyperledger/fabric/tls
        - peer0.org3.example.com:/var/hyperledger/production
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
    command: peer node start
    ports:
      - 11051:11051
    networks:
      - test


问:
When checking the assumptions for an ANOVA my tables appear very close together so they are unreadable, how do I change this?
When checking the assumptions for an ANOVA my tables appear very close together so they are unreadable, how do I change this? Below is the code I have currently

```<code>library(performance)
install.packages("patchwork")
library(patchwork)
plot(check_normality(full_model))
check_model(full_model)
</code>```

I do not remember the code to expand my tables, and google isn't being very helpful

enter image description here

Body:
When checking the assumptions for an ANOVA my tables appear very close together so they are unreadable, how do I change this? Below is the code I have currently

library(performance)
install.packages("patchwork")
library(patchwork)
plot(check_normality(full_model))
check_model(full_model)

I do not remember the code to expand my tables, and google isn't being very helpful

enter image description here


问:
Looking for Dx and Px in headers vs. service lines guidance for PLAID customers?
Question from client: "In the MEDICAL_HEADERS table, I just wanted to confirm that the ICD_TYPE refers to both the 'D' codes and the 'P' codes?"

Need to develop guidance around where to look for dx vs. px in headers vs service lines and how to identify for PLAID customers not receiving reference tables outside of Sentinel and anomalies.

Hoping to aggregate info to fit PLAID customers.


问:
Implement an emedder for rnnDataset which takes an input tensor, transforms it to words->tokens->embeddings, then stores the embeddings
I need to write a function to embed an RNN dataset that takes the inputs as tensors and transforms them to words. I know the function has the structure below but don't know how to declare the arguments.</p>
```<code>def rnn_embedder(tensor, embedding_length):
'''
# Takes a tensor and a vocabulary and returns the BoW embedding of that tensor
# Args:
    tensor (torch.Tensor): A tensor of words represented by their index in the vocabulary
    vocab_lenght (int): The number of entries in the vocabulary
Returns (torch.Tensor): An tensor containing the BoW embedding of the input tensor
'''

tensor = tensor.long()
embedding = ...
words = ...

for ...

return numpy.asarray(embedding)
</code>```

Body:
I need to write a function to embed an RNN dataset that takes the inputs as tensors and transforms them to words. I know the function has the structure below but don't know how to declare the arguments.

def rnn_embedder(tensor, embedding_length):
'''
# Takes a tensor and a vocabulary and returns the BoW embedding of that tensor
# Args:
    tensor (torch.Tensor): A tensor of words represented by their index in the vocabulary
    vocab_lenght (int): The number of entries in the vocabulary
Returns (torch.Tensor): An tensor containing the BoW embedding of the input tensor
'''

tensor = tensor.long()
embedding = ...
words = ...

for ...

return numpy.asarray(embedding)


问:
SonarQube Access denied in Jenkins Pipeline
I'm trying to set up my Jenkins Pipeline to work along with SonarQube, However at the building stage Im getting the following error message:

/var/jenkins_home/workspace/practica3/node_modules/sonar-scanner/bin/sonar-scanner: exec: line 59: : Permission denied

I have the next Jenkins pipeline file:

```<code>pipeline {
    agent {
        docker {
            image 'node:17-alpine3.14'
            args '-p 3001:3000'
        }
    }
    stages {
        stage('Build') {
            steps {
                sh 'npm install'
             withSonarQubeEnv('SonarQube'){
                sh "npm install sonar-scanner"
                sh "npm run sonar"
                }
            }
        }
        stage('Test') {
            steps {
                sh 'npm run test'
            }
        }
    }
}
</code>```

My sonar-project.properties looks like this:

```<code>sonar.projectKey=nodejs-app
sonar.projectName=nodejs-app
sonar.projectVersion=1.0
sonar.sourceEncoding=UTF-8
sonar.host.url=http://localhost:9000
sonar.login=MyToken
sonar.javascript.lcov.reportPaths=coverage/lcov.info
</code>```

Any Ideas? I will appreciate it.

Body:
I'm trying to set up my Jenkins Pipeline to work along with SonarQube, However at the building stage Im getting the following error message:

/var/jenkins_home/workspace/practica3/node_modules/sonar-scanner/bin/sonar-scanner: exec: line 59: : Permission denied

I have the next Jenkins pipeline file:

pipeline {
    agent {
        docker {
            image 'node:17-alpine3.14'
            args '-p 3001:3000'
        }
    }
    stages {
        stage('Build') {
            steps {
                sh 'npm install'
             withSonarQubeEnv('SonarQube'){
                sh "npm install sonar-scanner"
                sh "npm run sonar"
                }
            }
        }
        stage('Test') {
            steps {
                sh 'npm run test'
            }
        }
    }
}

My sonar-project.properties looks like this:

sonar.projectKey=nodejs-app
sonar.projectName=nodejs-app
sonar.projectVersion=1.0
sonar.sourceEncoding=UTF-8
sonar.host.url=http://localhost:9000
sonar.login=MyToken
sonar.javascript.lcov.reportPaths=coverage/lcov.info

Any Ideas? I will appreciate it.


问:
Maintain expected json to validate against response payload
Usecase:
Rest API returns response payload having 10 fields. We have store expected json in DB. When we run test - we compare expected json with actual json returned by api to assert each field.

Let's say - we have 500 such test.

Now - when we change response of Rest API to start returning 15 fields as part of response (additional 5 fields) - for existing 500 tests - should we update expected json to validate additional 5 fields? If yes - what would be most effective way to do it?

Existing approach is - we have to manually update expected json for all 500 tests which is time consuming and can be erroneous.

For Example:

Here is sample response of an API:

{
"field1" : "val1",
"field2" : "val2",
"field3" : {
"field3.a" : "val3",
"field3.b" : "val4",
},
"field4" : "val5"
}

For all 500 tests - we have expected json - with same schema as above to assert all 4 fields.

Now - REST API evolved and started returning 7 fields.

{
"field1" : "val1",
"field2" : "val2",
"field3" : {
"field3.a" : "val3",
"field3.b" : "val4",
},
"field4" : "val5",
"field5" : "val6",
"field6" : "val7",
"field7" : "val8"
}

In such case - existing 500 tests with expected json only assert 5 fields.

To assert all 7 fields - we have to manually update expected json for each 500 tests which is lots of maintenance when rest api response keeps changing.

How to effectively handle it?

Thanks,


问:
Biocircos Link track automation
I would like to automate BioCircos plot in R and here is my code. However, I am not able to link the tracks when I am using the full file.

Thank you in advance
KL

```<code>Input file

All_C1.txt

query   pos1    sub     pos2
AUSP_1  15147   AUSA_1  93903
AUSP_1  15147   AUSA_2  93903
AUSP_1  15182   AUSA_1  93938
AUSP_9  15204   AUSA_4  93960
AUSP_1  15228   AUSA_1  93984
AUSP_2  15242   AUSA_3  93998
AUSP_1  15263   AUSA_1  94019
AUSP_3  15264   AUSA_5  94021
AUSP_1  15285   AUSA_1  94042
AUSP_4  15287   AUSA_6  94044
AUSP_1  15301   AUSA_1  94058
AUSP_5  15309   AUSA_7  94066
AUSP_6  15313   AUSA_8  94070
AUSP_7  15319   AUSA_9  94076
AUSP_8  15320   AUSA_1  94077

library(BioCircos)
setwd("/PATH/TO/FILE")
data <- read.table("All_C1.txt")
head(data)

myGenomeAus0 = list("AUSP_1" = 31248581,
                    "AUSP_2" = 31645086,
                    "AUSP_3" = 47108296,
                    "AUSP_4" = 29969644,
                    "AUSP_5" = 36443716,
                    "AUSP_6" = 26560673,
                    "AUSP_7" = 28486927,
                    "AUSP_8" = 29326496,
                    "AUSP_9" = 29774650,
                    "AUSA_1" = 31122193,
                    "AUSA_2" = 32101233,
                    "AUSA_3" = 46783639,
                    "AUSA_4" = 29229108,
                    "AUSA_5" = 36358360,
                    "AUSA_6" = 26077416,
                    "AUSA_7" = 27897604,
                    "AUSA_8" = 29233132,
                    "AUSA_9" = 30348868)

links_chromosomes_1 <- read.table("All_C1.txt")
V1 <- links_chromosomes_1[1]
#V1

links_pos_1 <- read.table("All_C1.txt")
V2 <- links_pos_1[2]
#V2

links_chromosomes_2 <- read.table("All_C1.txt")
V3 <- links_chromosomes_2[3]
#V3

links_pos_2 <- read.table("All_C1.txt")
V4 <- links_pos_2[4]

for (i in V1[1]){
#print (i)
  for (j in V2[1]){
#print (j)
    for (k in V3[1]){
#print (k)
      for (l in V4[1]){
#print (l)
    tracklist = BioCircosLinkTrack('myLinkTrack', i, j, j,
                                   k, l, l, genome = myGenomeAus0,
                                   maxRadius = 1, color = "black", width = "1.0em",
                                   displayAxis = TRUE, axisColor = "black", axisWidth = 0.5,
                                   axisPadding = 0, displayLabel = TRUE, labelColor = "black",
                                   labelSize = "1em")
      }
  }
  }
}

BioCircos(tracklist, genome = myGenomeAus0, genomeFillColor = c("Spectral"),
          chrPad = 0.05, displayGenomeBorder = FALSE,
          genomeTicksDisplay = FALSE,  genomeLabelTextSize = "20pt", genomeLabelDy = 0)
</code>```

Title: Biocircos Link track automation

Body:
I would like to automate BioCircos plot in R and here is my code. However, I am not able to link the tracks when I am using the full file.

Thank you in advance
KL

Input file

All_C1.txt

query   pos1    sub     pos2
AUSP_1  15147   AUSA_1  93903
AUSP_1  15147   AUSA_2  93903
AUSP_1  15182   AUSA_1  93938
AUSP_9  15204   AUSA_4  93960
AUSP_1  15228   AUSA_1  93984
AUSP_2  15242   AUSA_3  93998
AUSP_1  15263   AUSA_1  94019
AUSP_3  15264   AUSA_5  94021
AUSP_1  15285   AUSA_1  94042
AUSP_4  15287   AUSA_6  94044
AUSP_1  15301   AUSA_1  94058
AUSP_5  15309   AUSA_7  94066
AUSP_6  15313   AUSA_8  94070
AUSP_7  15319   AUSA_9  94076
AUSP_8  15320   AUSA_1  94077

library(BioCircos)
setwd("/PATH/TO/FILE")
data <- read.table("All_C1.txt")
head(data)

myGenomeAus0 = list("AUSP_1" = 31248581,
                    "AUSP_2" = 31645086,
                    "AUSP_3" = 47108296,
                    "AUSP_4" = 29969644,
                    "AUSP_5" = 36443716,
                    "AUSP_6" = 26560673,
                    "AUSP_7" = 28486927,
                    "AUSP_8" = 29326496,
                    "AUSP_9" = 29774650,
                    "AUSA_1" = 31122193,
                    "AUSA_2" = 32101233,
                    "AUSA_3" = 46783639,
                    "AUSA_4" = 29229108,
                    "AUSA_5" = 36358360,
                    "AUSA_6" = 26077416,
                    "AUSA_7" = 27897604,
                    "AUSA_8" = 29233132,
                    "AUSA_9" = 30348868)

links_chromosomes_1 <- read.table("All_C1.txt")
V1 <- links_chromosomes_1[1]
#V1

links_pos_1 <- read.table("All_C1.txt")
V2 <- links_pos_1[2]
#V2

links_chromosomes_2 <- read.table("All_C1.txt")
V3 <- links_chromosomes_2[3]
#V3

links_pos_2 <- read.table("All_C1.txt")
V4 <- links_pos_2[4]

for (i in V1[1]){
#print (i)
  for (j in V2[1]){
#print (j)
    for (k in V3[1]){
#print (k)
      for (l in V4[1]){
#print (l)
    tracklist = BioCircosLinkTrack('myLinkTrack', i, j, j,
                                   k, l, l, genome = myGenomeAus0,
                                   maxRadius = 1, color = "black", width = "1.0em",
                                   displayAxis = TRUE, axisColor = "black", axisWidth = 0.5,
                                   axisPadding = 0, displayLabel = TRUE, labelColor = "black",
                                   labelSize = "1em")
      }
  }
  }
}

BioCircos(tracklist, genome = myGenomeAus0, genomeFillColor = c("Spectral"),
          chrPad = 0.05, displayGenomeBorder = FALSE,
          genomeTicksDisplay = FALSE,  genomeLabelTextSize = "20pt", genomeLabelDy = 0)


问:
What is the fastest notification possible? Does it depend on the provider (telegram/slack/email etc)?
For example, I want information about a new tweet from my code. How can I get the information as quickly as possible after the trigger?

For example, I can use telegram but I have a 3 second delay. How about discord, slack, or maybe the easiest way is via email? Do you have any thoughts on what to use to make it the fastest of all possible options?

I tried using telegram, but it's too slow, maybe I don't know how to do it right?


问:
Why did my pypi choose a tarball hash yesterday vs now its using a wheel hash?
After the new version for python-crontab (2.7.0) got uploaded yesterday, my pipeline builds started to fail because there was a new hash for the same old pinned version (2.6.0). Local builds fail too with no code changes on my end. Simply updating the lockfile does resolve this but I thought the purpose of the hashes was to certify authenticity of the packages you are getting matches a previous version aka prevent binary distrubition/supply-chain hijacking using signatures.

```<code>#0 18.96 [pipenv.exceptions.InstallError]:   Using cached python_crontab-2.6.0-py3-none-any.whl (25 kB)
#0 18.96 [pipenv.exceptions.InstallError]: ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.
#0 18.96 [pipenv.exceptions.InstallError]:     python-crontab==2.6.0 from https://files.pythonhosted.org/packages/8a/65/ee4f4db956d14b42aa6cf0dbd0b77217a206484b99f1d4aa11326cd3952a/python_crontab-2.6.0-py3-none-any.whl (from -r /tmp/pipenv-om9jbtdi-requirements/pipenv-0ytg305b-hashed-reqs.txt (line 80)):
#0 18.96 [pipenv.exceptions.InstallError]:         Expected sha256 1e35ed7a3cdc3100545b43e196d34754e6551e7f95e4caebbe0e1c0ca41c2f1b
#0 18.96 [pipenv.exceptions.InstallError]:              Got        f308a64b8b1d072da4a235e9320398a242e92d080c1d8143bd0c600b24e160f8
#0 18.96 ERROR: Couldn't install package: [omitted for length]
</code>```

Looking at wheel hash:

https://pypi.org/project/python-crontab/2.6.0/#copy-hash-modal-556e5941-9a7b-49bb-8d72-bd7d824f8614 f308a64b8b1d072da4a235e9320398a242e92d080c1d8143bd0c600b24e160f8

vs tar.gz hash:

https://pypi.org/project/python-crontab/2.6.0/#copy-hash-modal-811f8508-00b8-4437-9256-13cdb7f532df 1e35ed7a3cdc3100545b43e196d34754e6551e7f95e4caebbe0e1c0ca41c2f1b

What am I missing?

Error msg with my pipeline command -- this has worked for years.

```<code>------
failed to solve: executor failed running [/bin/sh -c pipenv install --dev --system --deploy]: exit code: 1

Exited with code exit status 17

</code>```

My lockfile:

```<code>        "python-crontab": {
            "hashes": [
                "sha256:1e35ed7a3cdc3100545b43e196d34754e6551e7f95e4caebbe0e1c0ca41c2f1b"
            ],
            "index": "pypi",
            "version": "==2.6.0"
        },

</code>```

Body:
After the new version for python-crontab (2.7.0) got uploaded yesterday, my pipeline builds started to fail because there was a new hash for the same old pinned version (2.6.0). Local builds fail too with no code changes on my end. Simply updating the lockfile does resolve this but I thought the purpose of the hashes was to certify authenticity of the packages you are getting matches a previous version aka prevent binary distrubition/supply-chain hijacking using signatures.

#0 18.96 [pipenv.exceptions.InstallError]:   Using cached python_crontab-2.6.0-py3-none-any.whl (25 kB)
#0 18.96 [pipenv.exceptions.InstallError]: ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.
#0 18.96 [pipenv.exceptions.InstallError]:     python-crontab==2.6.0 from https://files.pythonhosted.org/packages/8a/65/ee4f4db956d14b42aa6cf0dbd0b77217a206484b99f1d4aa11326cd3952a/python_crontab-2.6.0-py3-none-any.whl (from -r /tmp/pipenv-om9jbtdi-requirements/pipenv-0ytg305b-hashed-reqs.txt (line 80)):
#0 18.96 [pipenv.exceptions.InstallError]:         Expected sha256 1e35ed7a3cdc3100545b43e196d34754e6551e7f95e4caebbe0e1c0ca41c2f1b
#0 18.96 [pipenv.exceptions.InstallError]:              Got        f308a64b8b1d072da4a235e9320398a242e92d080c1d8143bd0c600b24e160f8
#0 18.96 ERROR: Couldn't install package: [omitted for length]

Looking at wheel hash:

https://pypi.org/project/python-crontab/2.6.0/#copy-hash-modal-556e5941-9a7b-49bb-8d72-bd7d824f8614 f308a64b8b1d072da4a235e9320398a242e92d080c1d8143bd0c600b24e160f8

vs tar.gz hash:

https://pypi.org/project/python-crontab/2.6.0/#copy-hash-modal-811f8508-00b8-4437-9256-13cdb7f532df 1e35ed7a3cdc3100545b43e196d34754e6551e7f95e4caebbe0e1c0ca41c2f1b

What am I missing?

Error msg with my pipeline command -- this has worked for years.

------
failed to solve: executor failed running [/bin/sh -c pipenv install --dev --system --deploy]: exit code: 1

Exited with code exit status 17

My lockfile:

        "python-crontab": {
            "hashes": [
                "sha256:1e35ed7a3cdc3100545b43e196d34754e6551e7f95e4caebbe0e1c0ca41c2f1b"
            ],
            "index": "pypi",
            "version": "==2.6.0"
        },


问:
How to know all the dimens.xml(hYYYdp) files I have to create to support all the screen sizes?
I am a little bit desperate because I'm trying to know how can I know the exact list of different dimens.xml(hYYYdp) I have to create in order to support all the screen sizes. I think I have already seen all the related questions to mine but none of them has helped me to solve this doubt. This is the most related question that hasn't solved my doubt: How to define dimens.xml for every different screen size in android? .

To give you some context. The reason of having different values according to the screen size is because I have a ConstraintLayout with some items that have Top and Bottom margin and in some devices that margin is not looking good. In this post I made, someone suggested me to use different margin values according to the screen size: How to solve TextView being cropped in small devices because of layout margin?

I have thought that as the margin is dependent of the height of the device (as I am using only Top and Bottom margin) I would have to create a list of different dimens.xml files according to the height of the device (hYYYdp).

The real concern I have is that I don't know how many dimens.xml files I have to create to support all the screen sizes. What I have been doing is creating some specific dimens.xml files that are working for specific devices, but I think there has to be a general list of all the dimens.xml files that have to be created to support all the screen sizes.

For example, what I have been doing is to look the test devices of Android Studio one by one and create specific dimens.xml files for them. This is the process I have followed to create a specific dimens file:

Example:

1- First I have seen the list of the test devices of Android Studio, for example let's take this one:

2- After this, I have calculated the dp of the height of this specific test device:

240x400px (ldpi) device. So the height's dp is = 400/(120(ldpi)/160)== 533.33dp

3- Finally, I have added the dimens.xml(hYYYdp) correspondent to this specific device with the specific margin value that is looking good:

I have repeated this process for most of the test devices of Android Studio but as a result, I have a list of specific devices but I think there will remain many devices without being supported  as not all the Android devices are in the Android Studio test devices list. I hope you have understand what I am trying to explain.


问:
Accidently pulled code from repository and now the code I was working on is gone. Can I revert it back?
I was writing code and then I tried to commit the code but I got a message saying I have not pulled beforehand. Instinctively I pulled but later I saw that all the code I wrote was gone and was changed with the current one in Gitlab. Is there possibility to revert back to the code I had saved on my local machine ?

I do not know if it will be of any help but I can see the commit I tried to send when using git reflog.

I get 222a4f0 (HEAD -> main) HEAD@{0}: commit: mymessage.


问:
How to send and receive data with socket in parallel?(python)
I've been recently doing a sort of a netcat clone, because i want ot improve my skills at this little project and also use it in ctfs, since it's much more convinient to use a tcp client u hve written yourself.Everythin kinda works, but for whatever reason if the person i'm communicating with sends me a message, i can't send an answer after this(the message sent by him appears fine). May you please point out my mistake and possibly help me with an idea on how to solve this?
Below is the source code for my project:

```<code>import tkinter as tk
from scrolledtext import *    #it`s mostly the gui part, all the socket stuff is in connect(),
import socket, threading      #send() and recv()

def connect():
    global s, reader
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    addrlbl.configure(state='disabled')
    addr = addrntr.get()
    addrntr.configure(state='disabled')
    portlbl.configure(state='disabled')
    port = portntr.get()
    portntr.configure(state='disabled')
    connbtn.configure(text='CONNECTED',state='disabled')
    msginput.configure(state='normal')
    s.connect((addr, int(port)))
    reader = threading.Thread(target=recv, daemon=False)
    reader.start()

def send(event):
    global s, reader
    msg = msginput.get()
    msginput.delete(0, tk.END)
    writero(chat, msg)
    s.sendall(msg.encode())
    reader = threading.Thread(target=recv, daemon=False)
    reader.start()

def recv():
    global s
    while True:
         data = s.recv(4096).decode()
         if not data:
            writero(chat, '\n')
            break
         writero(chat, data)
                                      #IDEA:
def writero(chat, msg):               #our msg is sent normally
    chat.configure(state='normal')    #bot msg is sent like: --><msg>
    chat.insert('end', msg)
    chat.configure(state='disabled')

def srcopen():
    from tkinter.filedialog import askopenfilename
    filepath = askopenfilename(filetypes=[("Python scripts", "*.py"), ("All Files", "*.*")])
    srclabel['text'] = filepath
    if not filepath:
        return

window = tk.Tk()
chat = ScrolledText()
chat.insert('end', "Here is your conversation:")
chat.config(state='disabled')
msginput = tk.Entry(width=110)
connframe = tk.Frame(master=window, relief=tk.GROOVE)
addrlbl = tk.Label(text='Address:', master=connframe)
addrntr = tk.Entry(master=connframe)
portlbl = tk.Label(text='Port:', master=connframe)
portntr = tk.Entry(master=connframe)
connbtn = tk.Button(text='CONNECT', master=connframe, command=connect)
srcbtn = tk.Button(text='Open script', command=srcopen)
srclabel = tk.Label(text='Script not attached...')

chat.grid(sticky = "nw", column=0, row=0)
msginput.grid(sticky="nw", column=0, row=1)
chat.configure(state='disabled')
msginput.configure(state='disabled')
connframe.grid(sticky="nw", column=1, row=0, padx=10)
addrlbl.grid(column=0, row=0)
addrntr.grid(column=0, row=1)
portlbl.grid(column=0, row=2)
portntr.grid(column=0, row=3)
connbtn.grid(column=0, row=4)
srclabel.grid(column=1, row=1)
srcbtn.grid(column = 1, row = 2)

msginput.bind('<Return>', send)

window.mainloop()
</code>```

I tried following multiple guides(for example in the above code you can see a two-threads idea implementation) and use different methods overall, but nthing worked

Body:
I've been recently doing a sort of a netcat clone, because i want ot improve my skills at this little project and also use it in ctfs, since it's much more convinient to use a tcp client u hve written yourself.Everythin kinda works, but for whatever reason if the person i'm communicating with sends me a message, i can't send an answer after this(the message sent by him appears fine). May you please point out my mistake and possibly help me with an idea on how to solve this?
Below is the source code for my project:

import tkinter as tk
from scrolledtext import *    #it`s mostly the gui part, all the socket stuff is in connect(),
import socket, threading      #send() and recv()

def connect():
    global s, reader
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    addrlbl.configure(state='disabled')
    addr = addrntr.get()
    addrntr.configure(state='disabled')
    portlbl.configure(state='disabled')
    port = portntr.get()
    portntr.configure(state='disabled')
    connbtn.configure(text='CONNECTED',state='disabled')
    msginput.configure(state='normal')
    s.connect((addr, int(port)))
    reader = threading.Thread(target=recv, daemon=False)
    reader.start()

def send(event):
    global s, reader
    msg = msginput.get()
    msginput.delete(0, tk.END)
    writero(chat, msg)
    s.sendall(msg.encode())
    reader = threading.Thread(target=recv, daemon=False)
    reader.start()

def recv():
    global s
    while True:
         data = s.recv(4096).decode()
         if not data:
            writero(chat, '\n')
            break
         writero(chat, data)
                                      #IDEA:
def writero(chat, msg):               #our msg is sent normally
    chat.configure(state='normal')    #bot msg is sent like: --><msg>
    chat.insert('end', msg)
    chat.configure(state='disabled')

def srcopen():
    from tkinter.filedialog import askopenfilename
    filepath = askopenfilename(filetypes=[("Python scripts", "*.py"), ("All Files", "*.*")])
    srclabel['text'] = filepath
    if not filepath:
        return

window = tk.Tk()
chat = ScrolledText()
chat.insert('end', "Here is your conversation:")
chat.config(state='disabled')
msginput = tk.Entry(width=110)
connframe = tk.Frame(master=window, relief=tk.GROOVE)
addrlbl = tk.Label(text='Address:', master=connframe)
addrntr = tk.Entry(master=connframe)
portlbl = tk.Label(text='Port:', master=connframe)
portntr = tk.Entry(master=connframe)
connbtn = tk.Button(text='CONNECT', master=connframe, command=connect)
srcbtn = tk.Button(text='Open script', command=srcopen)
srclabel = tk.Label(text='Script not attached...')

chat.grid(sticky = "nw", column=0, row=0)
msginput.grid(sticky="nw", column=0, row=1)
chat.configure(state='disabled')
msginput.configure(state='disabled')
connframe.grid(sticky="nw", column=1, row=0, padx=10)
addrlbl.grid(column=0, row=0)
addrntr.grid(column=0, row=1)
portlbl.grid(column=0, row=2)
portntr.grid(column=0, row=3)
connbtn.grid(column=0, row=4)
srclabel.grid(column=1, row=1)
srcbtn.grid(column = 1, row = 2)

msginput.bind('<Return>', send)

window.mainloop()

I tried following multiple guides(for example in the above code you can see a two-threads idea implementation) and use different methods overall, but nthing worked


问:
How to send SSIS failure notification when executing from SQL Agent Job
I have a SQL Agent Job with steps that resemble the following:

Exec SSIS package A

Exec SSIS package B

Exec SSIS package C

Exec stored proc

I have it set up so that if any of the SSIS packages fail, the job moves on to next step. The package failure notification comes from SSIS. I have 2 script tasks. One in event handler to capture/append error codes/messages to a variable:

The second script task is in control flow and grabs the appended error message variables and  other email forming variables and sends them to an outlook email account:

This works when running the package with my credentials + just the individual package. When I try to run the package through the SQL Agent Job with default credentials (or even my own) I get the following errors:

The desired result is SQL Agent Job runs completely regardless of any of steps 1-3 failing. When any step 1-3 fail, within SSIS the failure email message is sent.

EDIT: SQL Agent Job

We are using the legacy Package Deployment Model. The Package lives on the file system.


问:
How should I integrate a go library in a flutter app ? platform channels ? Pigeon ? FFI?
I have a go library with around 100 functions and around 40 struct types.
It's mostly interacting with structs and byte arrays.
I would like to build a multi platform app (android/ios/windows/linux) using flutter.
My first port would be the Android app.

-- edit --

I don't really need callbacks from native code to Dart.

My structs do contain nested structs and arrays of structs

-- edit --

I created bindings with gomobile and have my lib.aar for Android.
From the flutter documentation, it seems to me that there are 3 different methods for doing that :

platform channels, lots of code to write ?

pigeon, automatic code generation, but a lot of code to write anyway ?

FFI ?

What is the best/fastest/painless method ?

I would have expected that generating interface code from java classes or go code, would be more or less automatic but it seems not possible.

Do you know where can I could find complete examples, not just basic a+b ?

Thank you


问:
Applying class scoped CSS custom properties to web component
Is there a specific rule around how class scoped CSS custom properties cascade/are inherited with the shadow root? Let's say I have a default theme with custom properties scoped to :root and a dark theme scoped to a .dark-mode class, I can apply that class to the app-container component and my simple-button text color is set to blue. However, if I apply the dark-mode class directly to the simple-button as demonstrated, it inherits black from :root. It doesn't even pick up .dark-mode. I'm looking for some official docs that might explain this as well.</p>
```<code><!DOCTYPE html>
<head>
  <script type="module" src="./app-container.js"></script>
  <style>
    :root {
      --text-color: black;
    }
  </style>
  <style>
    .dark-mode {
      --text-color: blue;
    }
  </style>
</head>
<body>
  <app-container name="World"></app-container>
</body>
</code>```
```<code>// app-container.js
import {html, css, LitElement} from 'lit';
import './simple-button.js';

export class AppContainer extends LitElement {
  static styles = css`p { color: var(--text-color)}`;

  static properties = {
  };

  constructor() {
    super();
  }

  render() {
    return html`
      <p>App Container</p>
      <simple-button class="dark-mode"></simple-button>
    `;
  }
}
customElements.define('app-container', AppContainer);
</code>```
```<code>// simple-button.js
import {html, css, LitElement} from 'lit';

export class SimpleButton extends LitElement {
  static styles = css`button { color: var(--text-color)}`;

  static properties = {
  };

  constructor() {
    super();
  }

  render() {
    return html`<button>Button</button>`;
  }
}
customElements.define('simple-button', SimpleButton);
</code>```

Body:
Is there a specific rule around how class scoped CSS custom properties cascade/are inherited with the shadow root? Let's say I have a default theme with custom properties scoped to :root and a dark theme scoped to a .dark-mode class, I can apply that class to the app-container component and my simple-button text color is set to blue. However, if I apply the dark-mode class directly to the simple-button as demonstrated, it inherits black from :root. It doesn't even pick up .dark-mode. I'm looking for some official docs that might explain this as well.

<!DOCTYPE html>

  <app-container name="World"></app-container>

// app-container.js
import {html, css, LitElement} from 'lit';
import './simple-button.js';

export class AppContainer extends LitElement {
  static styles = css`p { color: var(--text-color)}`;

  static properties = {
  };

  constructor() {
    super();
  }

  render() {
    return html`

App Container

      <simple-button class="dark-mode"></simple-button>
    `;
  }
}
customElements.define('app-container', AppContainer);

// simple-button.js
import {html, css, LitElement} from 'lit';

export class SimpleButton extends LitElement {
  static styles = css`button { color: var(--text-color)}`;

  static properties = {
  };

  constructor() {
    super();
  }

  render() {
    return html`<button>Button</button>`;
  }
}
customElements.define('simple-button', SimpleButton);


问:
Disable Insert Column between Columns
I'm trying to stop users from adding a column to an Excel spreadsheet between columns A and AC.

I know I can stop them from adding a column to the whole sheet using Protect Sheet, but I don't care what they do outside of A to AC, so they can add columns out there, but just trying to protect A to AC.

I also found the below code through a search (from ExtendOffice), but this stops both rows and columns, and again for the entire sheet. I'm fine if they add rows, just, again, no adding columns between A and AC:

```<code>Sub NoInsert()
'Updateby Extendoffice
    Dim I As Integer
    Dim cbStr As String
    Dim cbCtrl As CommandBarControl
    Application.ScreenUpdating = False
    For I = 1 To 2
        If I = 1 Then
            cbStr = "row"
        Else
            cbStr = "column"
        End If
        For Each cbCtrl In Application.CommandBars(cbStr).Controls
            If cbCtrl.ID = 3183 Then
                cbCtrl.Enabled = False
            End If
        Next
    Next
    Application.ScreenUpdating = True
End Sub
</code>```

Any help would be greatly appreciated!

Title: Disable Insert Column between Columns

Body:
I'm trying to stop users from adding a column to an Excel spreadsheet between columns A and AC.

I know I can stop them from adding a column to the whole sheet using Protect Sheet, but I don't care what they do outside of A to AC, so they can add columns out there, but just trying to protect A to AC.

I also found the below code through a search (from ExtendOffice), but this stops both rows and columns, and again for the entire sheet. I'm fine if they add rows, just, again, no adding columns between A and AC:

Sub NoInsert()
'Updateby Extendoffice
    Dim I As Integer
    Dim cbStr As String
    Dim cbCtrl As CommandBarControl
    Application.ScreenUpdating = False
    For I = 1 To 2
        If I = 1 Then
            cbStr = "row"
        Else
            cbStr = "column"
        End If
        For Each cbCtrl In Application.CommandBars(cbStr).Controls
            If cbCtrl.ID = 3183 Then
                cbCtrl.Enabled = False
            End If
        Next
    Next
    Application.ScreenUpdating = True
End Sub

Any help would be greatly appreciated!


问:
mysql statement in python but one variable has a space
I have a statement in python that is a SQL query but the problem is one of the variables has a space in it so it throws a syntax error. this is my statement where the second %s is a full name and idk how to make it work

```<code>sql_query = ('INSERT INTO tempSales(Account_Num,Customer_Name) VALUES (%s,%s);', row)
</code>```

I've tried every which way I can think of to write this statement and it does not work

Body:
I have a statement in python that is a SQL query but the problem is one of the variables has a space in it so it throws a syntax error. this is my statement where the second %s is a full name and idk how to make it work

sql_query = ('INSERT INTO tempSales(Account_Num,Customer_Name) VALUES (%s,%s);', row)

I've tried every which way I can think of to write this statement and it does not work


问:
intellisense is not working with the components imported from the storybook
I am working on a project that consumes components from a storybook (built with react and ts) where a component named Button is built as following:

```<code>// Button.tsx

import React, { FC } from 'react';
import { ButtonProps } from './types';

const Button: FC<ButtonProps> = ({ children, type = 'button', className = '', ...props }:
ButtonProps) => {
  return (
    <button className={className} type={type} {...props}>
      {children}
    </button>
  );
};

export default Button;
</code>```

And here us the type definitions file of the Button component

```<code>// types.d.ts
import React from 'react';

export interface ButtonProps
extends React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement> {
   className?: string;
}
</code>```

Now, intellisense works just fine in the storybook and it displays all HTML button props as following:

But the issue here is, when I try to import this button in another react project and extends the ButtonProps that I export from the storybook, it doesn't show up any of the HTML props and intellisense stops working:

And here is how the type definitions file of the consuming react project:

```<code>import { ButtonProps } from "my-storybook"

export interface ISampleProps extends ButtonProps {
  children: JSX.Element | string;
}
</code>```

Any idea on how to get this to work and display all HTML props in the consuming react project.

Thanks in advance.

Body:
I am working on a project that consumes components from a storybook (built with react and ts) where a component named Button is built as following:

// Button.tsx

import React, { FC } from 'react';
import { ButtonProps } from './types';

const Button: FC<ButtonProps> = ({ children, type = 'button', className = '', ...props }:
ButtonProps) => {
  return (
    <button className={className} type={type} {...props}>
      {children}
    </button>
  );
};

export default Button;

And here us the type definitions file of the Button component

// types.d.ts
import React from 'react';

export interface ButtonProps
extends React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement> {
   className?: string;
}

Now, intellisense works just fine in the storybook and it displays all HTML button props as following:

But the issue here is, when I try to import this button in another react project and extends the ButtonProps that I export from the storybook, it doesn't show up any of the HTML props and intellisense stops working:

And here is how the type definitions file of the consuming react project:

import { ButtonProps } from "my-storybook"

export interface ISampleProps extends ButtonProps {
  children: JSX.Element | string;
}

Any idea on how to get this to work and display all HTML props in the consuming react project.

Thanks in advance.


问:
Checkbox to update Boolean value in Firestore db, Kotlin
I'm hoping to update a Boolean value of data that I have in the list. If checkbox is checked I would like the value to be true, but if the checkbox is unchecked, I would like it to change the value to false, and vice versa.

On clicking the checkbox, I would like it to change the value of 'favourite' in my db to either true or false, depending on whether the checkbox is checked or not. I am unsure how to update this value with a checkbox. Please help! My code is as follows:

Adapter:

```<code>package org.wit.hikingtrails.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import org.wit.hikingtrails.databinding.CardHikeBinding
import org.wit.hikingtrails.main.MainApp
import org.wit.hikingtrails.models.HikeModel
import timber.log.Timber.i

interface HikeListener {
    fun onHikeClick(hike: HikeModel)
}

class HikeAdapter constructor(private var hikes: List<HikeModel>,
                              private val listener: HikeListener) :
    RecyclerView.Adapter<HikeAdapter.MainHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainHolder {
        val binding = CardHikeBinding
            .inflate(LayoutInflater.from(parent.context), parent, false)
        return MainHolder(binding)
    }

    override fun onBindViewHolder(holder: MainHolder, position: Int) {
        val hike = hikes[holder.adapterPosition]
        holder.bind(hike, listener)
    }

    override fun getItemCount(): Int = hikes.size

    class MainHolder(private val binding : CardHikeBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(hike: HikeModel, listener: HikeListener) {
            binding.hikeName.text = hike.name
            binding.description.text = hike.description

            binding.favourite.isChecked = hike.favourite
            binding.favourite.setOnClickListener {
                hike.favourite = binding.favourite.isChecked
                listener.onHikeClick(hike)
            }

            if (hike.image != ""){
                Picasso.get()
                    .load(hike.image)
                    .resize(200, 200)
                    .into(binding.imageIcon)
            }
            binding.root.setOnClickListener { listener.onHikeClick(hike) }

        }
    }
}
</code>```

Presenter:

```<code>package org.wit.hikingtrails.views.hikeList

import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.google.firebase.auth.FirebaseAuth
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.wit.hikingtrails.main.MainApp
import org.wit.hikingtrails.models.HikeModel

import org.wit.hikingtrails.views.BasePresenter
import org.wit.hikingtrails.views.BaseView
import org.wit.hikingtrails.views.VIEW
import org.wit.hikingtrails.views.hike.HikeView
import org.wit.hikingtrails.views.map.HikeMapView
import org.wit.hikingtrails.views.signIn.SignInView

class HikeListPresenter(view: BaseView) : BasePresenter(view) {

    var hike = HikeModel()

    private lateinit var refreshIntentLauncher : ActivityResultLauncher<Intent>
    private lateinit var editIntentLauncher : ActivityResultLauncher<Intent>

    init {
        registerEditCallback()
        registerRefreshCallback()
    }

    suspend fun getHikes() = app.hikes.findAll()

    fun doAddHike() {
        val launcherIntent = Intent(view, HikeView::class.java)
        editIntentLauncher.launch(launcherIntent)
    }

    fun doEditHike(hike: HikeModel) {
        val launcherIntent = Intent(view, HikeView::class.java)
        launcherIntent.putExtra("hike_edit", hike)
        editIntentLauncher.launch(launcherIntent)
    }

    fun doShowHikesMap() {
        val launcherIntent = Intent(view, HikeMapView::class.java)
        editIntentLauncher.launch(launcherIntent)
    }

    fun doLogout() {
        FirebaseAuth.getInstance().signOut()
        val launcherIntent = Intent(view, SignInView::class.java)
        editIntentLauncher.launch(launcherIntent)
    }

    private fun registerRefreshCallback() {
        refreshIntentLauncher =
            view!!.registerForActivityResult(ActivityResultContracts.StartActivityForResult())
            {
                GlobalScope.launch(Dispatchers.Main){
                    getHikes()
                }
            }
    }
    private fun registerEditCallback() {
        editIntentLauncher =
            view!!.registerForActivityResult(ActivityResultContracts.StartActivityForResult())
            {  }

    }

}
</code>```

View:

```<code>package org.wit.hikingtrails.views.hikeList

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import org.wit.hikingtrails.R
import org.wit.hikingtrails.adapters.HikeAdapter
import org.wit.hikingtrails.adapters.HikeListener
//import org.wit.hikingtrails.databinding.ActivityHikeListBinding
import org.wit.hikingtrails.main.MainApp
import org.wit.hikingtrails.models.HikeModel
import android.content.Intent
import android.view.*
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.wit.hikingtrails.databinding.ActivityHikeListBinding
import org.wit.hikingtrails.views.BaseView
import timber.log.Timber

class HikeListView :  BaseView(), HikeListener {

    lateinit var app: MainApp
    lateinit var binding: ActivityHikeListBinding
    lateinit var presenter: HikeListPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHikeListBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.toolbar.title = title
        setSupportActionBar(binding.toolbar)

        presenter = HikeListPresenter(this)
        val layoutManager = LinearLayoutManager(this)
        binding.recyclerView.layoutManager = layoutManager

        updateRecyclerView()
    }

//    override fun showHikes(hikes: List<HikeModel>) {
//        recyclerView.adapter = HikeAdapter(hikes, this)
//        recyclerView.adapter?.notifyDataSetChanged()
//    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onResume() {
        //update the view
        super.onResume()
        updateRecyclerView()
        binding.recyclerView.adapter?.notifyDataSetChanged()
        Timber.i("recyclerView onResume")

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item?.itemId) {
            R.id.item_add -> presenter.doAddHike()
            R.id.item_map -> presenter.doShowHikesMap()
            R.id.logout -> presenter.doLogout()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onHikeClick(hike: HikeModel) {
        presenter.doEditHike(hike)
    }

    private fun updateRecyclerView(){
        GlobalScope.launch(Dispatchers.Main){
            binding.recyclerView.adapter =
                HikeAdapter(presenter.getHikes(), this@HikeListView)
        }
    }
}
</code>```

Body:
I'm hoping to update a Boolean value of data that I have in the list. If checkbox is checked I would like the value to be true, but if the checkbox is unchecked, I would like it to change the value to false, and vice versa.

On clicking the checkbox, I would like it to change the value of 'favourite' in my db to either true or false, depending on whether the checkbox is checked or not. I am unsure how to update this value with a checkbox. Please help! My code is as follows:

Adapter:

package org.wit.hikingtrails.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import org.wit.hikingtrails.databinding.CardHikeBinding
import org.wit.hikingtrails.main.MainApp
import org.wit.hikingtrails.models.HikeModel
import timber.log.Timber.i

interface HikeListener {
    fun onHikeClick(hike: HikeModel)
}

class HikeAdapter constructor(private var hikes: List<HikeModel>,
                              private val listener: HikeListener) :
    RecyclerView.Adapter<HikeAdapter.MainHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainHolder {
        val binding = CardHikeBinding
            .inflate(LayoutInflater.from(parent.context), parent, false)
        return MainHolder(binding)
    }

    override fun onBindViewHolder(holder: MainHolder, position: Int) {
        val hike = hikes[holder.adapterPosition]
        holder.bind(hike, listener)
    }

    override fun getItemCount(): Int = hikes.size

    class MainHolder(private val binding : CardHikeBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(hike: HikeModel, listener: HikeListener) {
            binding.hikeName.text = hike.name
            binding.description.text = hike.description

            binding.favourite.isChecked = hike.favourite
            binding.favourite.setOnClickListener {
                hike.favourite = binding.favourite.isChecked
                listener.onHikeClick(hike)
            }

            if (hike.image != ""){
                Picasso.get()
                    .load(hike.image)
                    .resize(200, 200)
                    .into(binding.imageIcon)
            }
            binding.root.setOnClickListener { listener.onHikeClick(hike) }

        }
    }
}

Presenter:

package org.wit.hikingtrails.views.hikeList

import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.google.firebase.auth.FirebaseAuth
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.wit.hikingtrails.main.MainApp
import org.wit.hikingtrails.models.HikeModel

import org.wit.hikingtrails.views.BasePresenter
import org.wit.hikingtrails.views.BaseView
import org.wit.hikingtrails.views.VIEW
import org.wit.hikingtrails.views.hike.HikeView
import org.wit.hikingtrails.views.map.HikeMapView
import org.wit.hikingtrails.views.signIn.SignInView

class HikeListPresenter(view: BaseView) : BasePresenter(view) {

    var hike = HikeModel()

    private lateinit var refreshIntentLauncher : ActivityResultLauncher<Intent>
    private lateinit var editIntentLauncher : ActivityResultLauncher<Intent>

    init {
        registerEditCallback()
        registerRefreshCallback()
    }

    suspend fun getHikes() = app.hikes.findAll()

    fun doAddHike() {
        val launcherIntent = Intent(view, HikeView::class.java)
        editIntentLauncher.launch(launcherIntent)
    }

    fun doEditHike(hike: HikeModel) {
        val launcherIntent = Intent(view, HikeView::class.java)
        launcherIntent.putExtra("hike_edit", hike)
        editIntentLauncher.launch(launcherIntent)
    }

    fun doShowHikesMap() {
        val launcherIntent = Intent(view, HikeMapView::class.java)
        editIntentLauncher.launch(launcherIntent)
    }

    fun doLogout() {
        FirebaseAuth.getInstance().signOut()
        val launcherIntent = Intent(view, SignInView::class.java)
        editIntentLauncher.launch(launcherIntent)
    }

    private fun registerRefreshCallback() {
        refreshIntentLauncher =
            view!!.registerForActivityResult(ActivityResultContracts.StartActivityForResult())
            {
                GlobalScope.launch(Dispatchers.Main){
                    getHikes()
                }
            }
    }
    private fun registerEditCallback() {
        editIntentLauncher =
            view!!.registerForActivityResult(ActivityResultContracts.StartActivityForResult())
            {  }

    }

}

View:

package org.wit.hikingtrails.views.hikeList

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import org.wit.hikingtrails.R
import org.wit.hikingtrails.adapters.HikeAdapter
import org.wit.hikingtrails.adapters.HikeListener
//import org.wit.hikingtrails.databinding.ActivityHikeListBinding
import org.wit.hikingtrails.main.MainApp
import org.wit.hikingtrails.models.HikeModel
import android.content.Intent
import android.view.*
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.wit.hikingtrails.databinding.ActivityHikeListBinding
import org.wit.hikingtrails.views.BaseView
import timber.log.Timber

class HikeListView :  BaseView(), HikeListener {

    lateinit var app: MainApp
    lateinit var binding: ActivityHikeListBinding
    lateinit var presenter: HikeListPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHikeListBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.toolbar.title = title
        setSupportActionBar(binding.toolbar)

        presenter = HikeListPresenter(this)
        val layoutManager = LinearLayoutManager(this)
        binding.recyclerView.layoutManager = layoutManager

        updateRecyclerView()
    }

//    override fun showHikes(hikes: List<HikeModel>) {
//        recyclerView.adapter = HikeAdapter(hikes, this)
//        recyclerView.adapter?.notifyDataSetChanged()
//    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onResume() {
        //update the view
        super.onResume()
        updateRecyclerView()
        binding.recyclerView.adapter?.notifyDataSetChanged()
        Timber.i("recyclerView onResume")

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item?.itemId) {
            R.id.item_add -> presenter.doAddHike()
            R.id.item_map -> presenter.doShowHikesMap()
            R.id.logout -> presenter.doLogout()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onHikeClick(hike: HikeModel) {
        presenter.doEditHike(hike)
    }

    private fun updateRecyclerView(){
        GlobalScope.launch(Dispatchers.Main){
            binding.recyclerView.adapter =
                HikeAdapter(presenter.getHikes(), this@HikeListView)
        }
    }
}


问:
Ability to minimize modal window with materializecss
How can we minimize a modal window created using materializecss.

Here is a working fiddle.

HTML

```<code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/js/materialize.min.js"></script>
<!-- Modal Trigger -->
<a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal</a>

<!-- Modal Structure -->
<div id="modal1" class="modal">
  <div class="modal-content">
    <h4>Modal Header</h4>
    <p>A bunch of text</p>
  </div>
  <div class="modal-footer">
    <a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat">Close !!</a>
  </div>
</div>
</code>```

Jquery

```<code>$(document).ready(function(){
    $('.modal-trigger').leanModal({
        dismissible: false
    });
});
</code>```

Body:
How can we minimize a modal window created using materializecss.

Here is a working fiddle.

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.min.css" />

Modal

Modal Header

A bunch of text

    Close !!

Jquery

$(document).ready(function(){
    $('.modal-trigger').leanModal({
        dismissible: false
    });
});


问:
How can I fix 403 Forbidden Error When Using MusicKit?
I am trying to make a library GET request using MusicKit but I keep getting a 403 Forbidden Error.

Here is the code I'm running in Python:

```<code>import datetime
import jwt

secret = """
-----BEGIN PRIVATE KEY-----
{Insert Private Key Here}
-----END PRIVATE KEY-----
"""

keyId  = "{Insert KeyID Here}"    # https://developer.apple.com/account/ios/authkey/
teamId = "{Insert TeamID Here}"   # https://developer.apple.com/account/#/membership/
alg    = "ES256"

time_now = datetime.datetime.now()
time_expired = datetime.datetime.now() + datetime.timedelta(hours = 4320)   #180d

headers = {
    "kid": keyId,
    "alg": alg
}

payload = {
    "iss": teamId,
    "iat": int(time_now.strftime("%s")),
    "exp": int(time_expired.strftime("%s"))
}

if __name__ == "__main__":
    token = jwt.encode(payload, secret, algorithm = alg, headers = headers)

    MUT = {Insert Music User Token Here}

    print("\n----CURL----")
    print("curl -v -H 'Authorization: Bearer %s' \"https://api.music.apple.com/v1/catalog/us/artists/36954\" \n" % (token))
    print(f"curl -v -H 'Music-User-Token: Bearer {MUT}' -H 'Authorization: Bearer {token}' \"https://api.music.apple.com/v1/me/library/albums\" \n")

</code>```

When I put the curl in for the first one (the catalog request) it works fine, but when I make the request using the second one (the library request) I get {"errors":[{"id":"4KHPECFWDNNRKXBJGYVIBO2PY4","title":"Forbidden","detail":"Invalid authentication","status":"403","code":"40300"}]}%

Is there a way to do the authentication in Python? Am I using the wrong Music-User-Token? I am using the one from the P8 File downloaded when I made the key. Ideally, I wouldn't be using that because I assume it's unique to me, and I want to eventually put this on the App Store for other people to use. Would I need to authenticate externally to authorize the app to use my Apple Music Library? The App is currently not being hosted anywhere, so not sure if that would be a problem. Right now, I am in the beginning stages of building it, so I mainly want to test and see if I can get things working.

Body:
I am trying to make a library GET request using MusicKit but I keep getting a 403 Forbidden Error.

Here is the code I'm running in Python:

import datetime
import jwt

secret = """
-----BEGIN PRIVATE KEY-----
{Insert Private Key Here}
-----END PRIVATE KEY-----
"""

keyId  = "{Insert KeyID Here}"    # https://developer.apple.com/account/ios/authkey/
teamId = "{Insert TeamID Here}"   # https://developer.apple.com/account/#/membership/
alg    = "ES256"

time_now = datetime.datetime.now()
time_expired = datetime.datetime.now() + datetime.timedelta(hours = 4320)   #180d

headers = {
    "kid": keyId,
    "alg": alg
}

payload = {
    "iss": teamId,
    "iat": int(time_now.strftime("%s")),
    "exp": int(time_expired.strftime("%s"))
}

if __name__ == "__main__":
    token = jwt.encode(payload, secret, algorithm = alg, headers = headers)

    MUT = {Insert Music User Token Here}

    print("\n----CURL----")
    print("curl -v -H 'Authorization: Bearer %s' \"https://api.music.apple.com/v1/catalog/us/artists/36954\" \n" % (token))
    print(f"curl -v -H 'Music-User-Token: Bearer {MUT}' -H 'Authorization: Bearer {token}' \"https://api.music.apple.com/v1/me/library/albums\" \n")

When I put the curl in for the first one (the catalog request) it works fine, but when I make the request using the second one (the library request) I get {"errors":[{"id":"4KHPECFWDNNRKXBJGYVIBO2PY4","title":"Forbidden","detail":"Invalid authentication","status":"403","code":"40300"}]}%

Is there a way to do the authentication in Python? Am I using the wrong Music-User-Token? I am using the one from the P8 File downloaded when I made the key. Ideally, I wouldn't be using that because I assume it's unique to me, and I want to eventually put this on the App Store for other people to use. Would I need to authenticate externally to authorize the app to use my Apple Music Library? The App is currently not being hosted anywhere, so not sure if that would be a problem. Right now, I am in the beginning stages of building it, so I mainly want to test and see if I can get things working.


问:
chrome.idle is active in Selenium headless execution
Currently using Selenium to test a chrome extension.
One of the features relies on the chrome.idle API to trigger an event when the idle state is not active (meaning no user interaction for a certain duration). This API is supposed to detect when the machine's idle state changes as per the docs.

Weird thing is, the test is run in headless mode via Github Actions, and regardless of that, the idle state is active. You would think a webdriver.sleep() in headless mode would be enough to emulate an idle machine, but apparently not.

Any ideas what could explain this behaviour? And could there be a way to force the browser/machine to be idle during a headless test execution?


问:
the playerMotor script for my fps game isnt working
[enter image description here]
(https://i.stack.imgur.com/Qhv31.png)

i tried following the tutorial and copied everything to perfection


问:
security.keyFile error when creating mongdb container with docker-compose file
My old docker-compose file config was

```<code>image: mongo:4.2-bionic
container_name: mongodb1
restart: on-failure
env_file: .env
environment:
  - MONGO_INITDB_ROOT_USERNAME=$MONGO_USERNAME
  - MONGO_INITDB_ROOT_PASSWORD=$MONGO_PASSWORD
ports:
  - "$MONGO_PORT:27017"
volumes:
  - data1:/data/db
networks:
  - app_network
command: ["--replSet", "rs0", "--bind_ip_all"]
</code>```

This was working fine. It would create the docker-container and then I would create replica inside docker-container. But then I upgraded the docker image to mongo:6.0.3 and now every time I try to start the container it throws error:

BadValue: security.keyFile is required when authorization is enabled
with replica sets

Body:
My old docker-compose file config was

image: mongo:4.2-bionic
container_name: mongodb1
restart: on-failure
env_file: .env
environment:
  - MONGO_INITDB_ROOT_USERNAME=$MONGO_USERNAME
  - MONGO_INITDB_ROOT_PASSWORD=$MONGO_PASSWORD
ports:
  - "$MONGO_PORT:27017"
volumes:
  - data1:/data/db
networks:
  - app_network
command: ["--replSet", "rs0", "--bind_ip_all"]

This was working fine. It would create the docker-container and then I would create replica inside docker-container. But then I upgraded the docker image to mongo:6.0.3 and now every time I try to start the container it throws error:

BadValue: security.keyFile is required when authorization is enabled
with replica sets