Explore all Chef open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Chef

gitextensions

v3.5.4

goss

k3os

v0.21.1-k3s1r0

FreeRTOS

FreeRTOSv202111.00

docker

10.1.8

Popular Libraries in Chef

chef

by chef doticonrubydoticon

star image 6865 doticonApache-2.0

Chef Infra, a powerful automation platform that transforms infrastructure into code automating how infrastructure is configured, deployed and managed across any environment, at any scale

gitextensions

by gitextensions doticoncsharpdoticon

star image 6198 doticonGPL-3.0

Git Extensions is a standalone UI tool for managing git repositories. It also integrates with Windows Explorer and Microsoft Visual Studio (2015/2017/2019).

ansible-for-devops

by geerlingguy doticonpythondoticon

star image 5640 doticonMIT

Ansible for DevOps examples.

goss

by aelsabbahy doticongodoticon

star image 4659 doticonApache-2.0

Quick and Easy server testing/validation

k3os

by rancher doticongodoticon

star image 2656 doticonApache-2.0

Purpose-built OS for Kubernetes, fully managed by Kubernetes.

brew

by Linuxbrew doticonrubydoticon

star image 2595 doticonBSD-2-Clause

:beer::penguin: The Homebrew package manager for Linux

oneget

by OneGet doticoncsharpdoticon

star image 2284 doticonMIT

PackageManagement (aka OneGet) is a package manager for Windows

FreeRTOS

by FreeRTOS doticoncdoticon

star image 2256 doticonMIT

'Classic' FreeRTOS distribution. Started as Git clone of FreeRTOS SourceForge SVN repo. Submodules the kernel.

pre-commit

by observing doticonjavascriptdoticon

star image 1820 doticonMIT

Automatically installs a git pre-commit script in your git repository which runs your `npm test` on pre-commit

Trending New libraries in Chef

webi-installers

by webinstall doticonshelldoticon

star image 283 doticonMPL-2.0

Primary and community-submitted packages for webinstall.dev

kotary

by ca-gip doticongodoticon

star image 73 doticonMIT

Managing Kubernetes Quota with confidence

cargo-quickinstall

by alsuren doticonrustdoticon

star image 65 doticonNOASSERTION

pre-compiled binary packages for `cargo install`

AnkhSVN

by AmpScm doticoncsharpdoticon

star image 54 doticonApache-2.0

AnkhSVN provides first class Subversion support for all recent Visual Studio versions.

instl

by installer doticongodoticon

star image 45 doticonMIT

đź’» A crossplatform installer for GitHub projects that just works!

homebrew-aws

by aws doticonrubydoticon

star image 40 doticonApache-2.0

Homebrew is a package manager for macOS which provides easy installation and update management of additional software. This Tap (repository) contains the Formulae that are used in the macOS AMI that AWS offers.

OpenGD77_UserGuide

by LibreDMR doticonhtmldoticon

star image 40 doticonGPL-2.0

yc-architect-solution-library

by yandex-cloud doticoncsharpdoticon

star image 39 doticonApache-2.0

piholemanual

by jpgpi250 doticonshelldoticon

star image 36 doticon

files referred to in my pihole installation manual

Top Authors in Chef

1

sous-chefs

136 Libraries

star icon10854

2

chef-boneyard

124 Libraries

star icon4636

3

cookbooks

96 Libraries

star icon362

4

chef-cookbooks

48 Libraries

star icon2770

5

chef

41 Libraries

star icon10421

6

froschi

29 Libraries

star icon304

7

poise

27 Libraries

star icon1460

8

zuazo

22 Libraries

star icon323

9

jtimberman

19 Libraries

star icon181

10

fnichol

18 Libraries

star icon524

1

136 Libraries

star icon10854

2

124 Libraries

star icon4636

3

96 Libraries

star icon362

4

48 Libraries

star icon2770

5

41 Libraries

star icon10421

6

29 Libraries

star icon304

7

27 Libraries

star icon1460

8

22 Libraries

star icon323

9

19 Libraries

star icon181

10

18 Libraries

star icon524

Trending Kits in Chef

No Trending Kits are available at this moment for Chef

Trending Discussions on Chef

how to shorten this JS function

Regex match strings divided by 'and'

How to make a joined well-known full node into an authority node in Substrate, automatically became an validator node?

Pandas filtering based on 2 different columns conditions

Can we automate updating the chef node attributes?

Inconsistent inheritance of interfaces with generic classes

C++ Producer Consumer Problem with condition variable + mutex + pthreads

Create elements by looping a javascript object

Same class but only trigger function for the one selected

symbolic link not working with chef recipe

QUESTION

how to shorten this JS function

Asked 2022-Jan-25 at 17:31

I have this Js function with hard coded filter parameters. It filter all the buckets sub objects when key start with a string from a given list. For now i havent found a way to put this list as an array...

1     function filter(buckets) {
2      return buckets.filter(({key}) => {
3        const _key = key.toLowerCase();
4        return (
5          !_key.startsWith("anciennes") && !_key.startsWith("anciens") && !_key.startsWith("arrondissements") && !_key.startsWith("autorites") && !_key.startsWith("cantons") && !_key.startsWith("capitales") &&
6          !_key.startsWith("chaines") && !_key.startsWith("chefs lieux") && !_key.startsWith("circonscriptions") && !_key.startsWith("communautes d") && !_key.startsWith("comtes d") && !_key.startsWith("constellations") && !_key.startsWith("continents") &&
7          !_key.startsWith("cours d") && !_key.startsWith("départements") && !_key.startsWith("districts d") && !_key.startsWith("établissements") && !_key.startsWith("états") && !_key.startsWith("ethnonymes") && !_key.startsWith("étoiles") &&
8          !_key.startsWith("europe") && !_key.startsWith("îles") && !_key.startsWith("lander-allemands") && !_key.startsWith("lieux-mythologiques") && !_key.startsWith("Localités d") && !_key.startsWith("mers") &&
9          !_key.startsWith("montagnes") && !_key.startsWith("municipalité") && !_key.startsWith("fromage") && !_key.startsWith("localités") && !_key.startsWith("noms de") && !_key.startsWith("numéros de") &&
10          !_key.startsWith("odonymes") && !_key.startsWith("organisations internationales") && !_key.startsWith("pays ") && !_key.startsWith("péninsules") && !_key.startsWith("préfectures") && !_key.startsWith("provinces") && !_key.startsWith("quartiers") &&
11          !_key.startsWith("régions") && !_key.startsWith("réserves indiennes") && !_key.startsWith("sous ") && !_key.startsWith("territoires") && !_key.startsWith("toponymes ") && !_key.startsWith("unions supranationales") && !_key.startsWith("villes du quebec") && !_key.startsWith("voivodies de pologne")
12        )
13      })
14    }
15
16
17    const buckets = [
18      {"key": "Aliments", "doc_count": 10}, {"key": "Adjectifs", "doc_count": 7}, {"key": "Vêtements", "doc_count": 6}, {"key": "Armures", "doc_count": 5}, {"key": "Anciennes divisions géographiques", "doc_count": 4}, {"key": "Super-règnes", "doc_count": 4},
19      {"key": "Eucaryotes", "doc_count": 3}, {"key": "Pays", "doc_count": 3}, {"key": "Antonomases", "doc_count": 2}, {"key": "Continents", "doc_count": 2}, {"key": "Europe", "doc_count": 2}, {"key": "France", "doc_count": 2},
20      {"key": "Localités", "doc_count": 2}, {"key": "Localités de France", "doc_count": 2}, {"key": "Plantes", "doc_count": 2}, {"key": "États", "doc_count": 2}, {"key": "Acaryotes", "doc_count": 1},
21      {"key": "Animaux", "doc_count": 1}, {"key": "Armes", "doc_count": 1}, {"key": "Aromates", "doc_count": 1}, {"key": "Chordés", "doc_count": 1}, {"key": "Couleurs", "doc_count": 1}, {"key": "Créatures mythologiques", "doc_count": 1},
22      {"key": "Fromages", "doc_count": 1}, {"key": "Fromages forts", "doc_count": 1}, {"key": "Fromages à pâte filée", "doc_count": 1}, {"key": "Fruits", "doc_count": 1}, {"key": "Langages informatiques", "doc_count": 1},
23      {"key": "Localités du département de la Corrèze", "doc_count": 1}, {"key": "Localités du département de la Dordogne", "doc_count": 1}, {"key": "Machines", "doc_count": 1}, {"key": "Oiseaux", "doc_count": 1}, {"key": "Tétrapodes", "doc_count": 1},
24      {"key": "Vertébrés", "doc_count": 1}, {"key": "Vie domestique", "doc_count": 1}, {"key": "Virus", "doc_count": 1}, {"key": "Volcans", "doc_count": 1}
25    ];
26

jsbin here :

https://jsbin.com/xicejozafe/edit?js,console

how to transform this function to generate the !_key.startsWith( ... ) && from and array of string insted of this crazy hard coded long &&

1     function filter(buckets) {
2      return buckets.filter(({key}) => {
3        const _key = key.toLowerCase();
4        return (
5          !_key.startsWith("anciennes") && !_key.startsWith("anciens") && !_key.startsWith("arrondissements") && !_key.startsWith("autorites") && !_key.startsWith("cantons") && !_key.startsWith("capitales") &&
6          !_key.startsWith("chaines") && !_key.startsWith("chefs lieux") && !_key.startsWith("circonscriptions") && !_key.startsWith("communautes d") && !_key.startsWith("comtes d") && !_key.startsWith("constellations") && !_key.startsWith("continents") &&
7          !_key.startsWith("cours d") && !_key.startsWith("départements") && !_key.startsWith("districts d") && !_key.startsWith("établissements") && !_key.startsWith("états") && !_key.startsWith("ethnonymes") && !_key.startsWith("étoiles") &&
8          !_key.startsWith("europe") && !_key.startsWith("îles") && !_key.startsWith("lander-allemands") && !_key.startsWith("lieux-mythologiques") && !_key.startsWith("Localités d") && !_key.startsWith("mers") &&
9          !_key.startsWith("montagnes") && !_key.startsWith("municipalité") && !_key.startsWith("fromage") && !_key.startsWith("localités") && !_key.startsWith("noms de") && !_key.startsWith("numéros de") &&
10          !_key.startsWith("odonymes") && !_key.startsWith("organisations internationales") && !_key.startsWith("pays ") && !_key.startsWith("péninsules") && !_key.startsWith("préfectures") && !_key.startsWith("provinces") && !_key.startsWith("quartiers") &&
11          !_key.startsWith("régions") && !_key.startsWith("réserves indiennes") && !_key.startsWith("sous ") && !_key.startsWith("territoires") && !_key.startsWith("toponymes ") && !_key.startsWith("unions supranationales") && !_key.startsWith("villes du quebec") && !_key.startsWith("voivodies de pologne")
12        )
13      })
14    }
15
16
17    const buckets = [
18      {"key": "Aliments", "doc_count": 10}, {"key": "Adjectifs", "doc_count": 7}, {"key": "Vêtements", "doc_count": 6}, {"key": "Armures", "doc_count": 5}, {"key": "Anciennes divisions géographiques", "doc_count": 4}, {"key": "Super-règnes", "doc_count": 4},
19      {"key": "Eucaryotes", "doc_count": 3}, {"key": "Pays", "doc_count": 3}, {"key": "Antonomases", "doc_count": 2}, {"key": "Continents", "doc_count": 2}, {"key": "Europe", "doc_count": 2}, {"key": "France", "doc_count": 2},
20      {"key": "Localités", "doc_count": 2}, {"key": "Localités de France", "doc_count": 2}, {"key": "Plantes", "doc_count": 2}, {"key": "États", "doc_count": 2}, {"key": "Acaryotes", "doc_count": 1},
21      {"key": "Animaux", "doc_count": 1}, {"key": "Armes", "doc_count": 1}, {"key": "Aromates", "doc_count": 1}, {"key": "Chordés", "doc_count": 1}, {"key": "Couleurs", "doc_count": 1}, {"key": "Créatures mythologiques", "doc_count": 1},
22      {"key": "Fromages", "doc_count": 1}, {"key": "Fromages forts", "doc_count": 1}, {"key": "Fromages à pâte filée", "doc_count": 1}, {"key": "Fruits", "doc_count": 1}, {"key": "Langages informatiques", "doc_count": 1},
23      {"key": "Localités du département de la Corrèze", "doc_count": 1}, {"key": "Localités du département de la Dordogne", "doc_count": 1}, {"key": "Machines", "doc_count": 1}, {"key": "Oiseaux", "doc_count": 1}, {"key": "Tétrapodes", "doc_count": 1},
24      {"key": "Vertébrés", "doc_count": 1}, {"key": "Vie domestique", "doc_count": 1}, {"key": "Virus", "doc_count": 1}, {"key": "Volcans", "doc_count": 1}
25    ];
26      const listOfTermToIgnore =  ["anciennes", "anciens", "arrondissements", "autorites", "cantons", "capitales",
27          "chaines", "chefs lieux", "circonscriptions", "communautes d", "comtes d", "constellations", "continents",
28          "cours d", "départements", "districts d", "établissements", "états", "ethnonymes", "étoiles",
29          "europe", "îles", "lander-allemands", "lieux-mythologiques", "Localités d", "mers",
30          "montagnes", "municipalité", "fromage", "localités", "noms de", "numéros de",
31          "odonymes", "organisations internationales", "pays ", "péninsules", "préfectures", "provinces", "quartiers",
32          "régions", "réserves indiennes", "sous ", "territoires", "toponymes ", "unions supranationales", "villes du quebec", "voivodies de pologne" ]
33

thanks for reading

ANSWER

Answered 2022-Jan-25 at 16:55

Use array.every() to check all the elements of the array.

1     function filter(buckets) {
2      return buckets.filter(({key}) => {
3        const _key = key.toLowerCase();
4        return (
5          !_key.startsWith("anciennes") && !_key.startsWith("anciens") && !_key.startsWith("arrondissements") && !_key.startsWith("autorites") && !_key.startsWith("cantons") && !_key.startsWith("capitales") &&
6          !_key.startsWith("chaines") && !_key.startsWith("chefs lieux") && !_key.startsWith("circonscriptions") && !_key.startsWith("communautes d") && !_key.startsWith("comtes d") && !_key.startsWith("constellations") && !_key.startsWith("continents") &&
7          !_key.startsWith("cours d") && !_key.startsWith("départements") && !_key.startsWith("districts d") && !_key.startsWith("établissements") && !_key.startsWith("états") && !_key.startsWith("ethnonymes") && !_key.startsWith("étoiles") &&
8          !_key.startsWith("europe") && !_key.startsWith("îles") && !_key.startsWith("lander-allemands") && !_key.startsWith("lieux-mythologiques") && !_key.startsWith("Localités d") && !_key.startsWith("mers") &&
9          !_key.startsWith("montagnes") && !_key.startsWith("municipalité") && !_key.startsWith("fromage") && !_key.startsWith("localités") && !_key.startsWith("noms de") && !_key.startsWith("numéros de") &&
10          !_key.startsWith("odonymes") && !_key.startsWith("organisations internationales") && !_key.startsWith("pays ") && !_key.startsWith("péninsules") && !_key.startsWith("préfectures") && !_key.startsWith("provinces") && !_key.startsWith("quartiers") &&
11          !_key.startsWith("régions") && !_key.startsWith("réserves indiennes") && !_key.startsWith("sous ") && !_key.startsWith("territoires") && !_key.startsWith("toponymes ") && !_key.startsWith("unions supranationales") && !_key.startsWith("villes du quebec") && !_key.startsWith("voivodies de pologne")
12        )
13      })
14    }
15
16
17    const buckets = [
18      {"key": "Aliments", "doc_count": 10}, {"key": "Adjectifs", "doc_count": 7}, {"key": "Vêtements", "doc_count": 6}, {"key": "Armures", "doc_count": 5}, {"key": "Anciennes divisions géographiques", "doc_count": 4}, {"key": "Super-règnes", "doc_count": 4},
19      {"key": "Eucaryotes", "doc_count": 3}, {"key": "Pays", "doc_count": 3}, {"key": "Antonomases", "doc_count": 2}, {"key": "Continents", "doc_count": 2}, {"key": "Europe", "doc_count": 2}, {"key": "France", "doc_count": 2},
20      {"key": "Localités", "doc_count": 2}, {"key": "Localités de France", "doc_count": 2}, {"key": "Plantes", "doc_count": 2}, {"key": "États", "doc_count": 2}, {"key": "Acaryotes", "doc_count": 1},
21      {"key": "Animaux", "doc_count": 1}, {"key": "Armes", "doc_count": 1}, {"key": "Aromates", "doc_count": 1}, {"key": "Chordés", "doc_count": 1}, {"key": "Couleurs", "doc_count": 1}, {"key": "Créatures mythologiques", "doc_count": 1},
22      {"key": "Fromages", "doc_count": 1}, {"key": "Fromages forts", "doc_count": 1}, {"key": "Fromages à pâte filée", "doc_count": 1}, {"key": "Fruits", "doc_count": 1}, {"key": "Langages informatiques", "doc_count": 1},
23      {"key": "Localités du département de la Corrèze", "doc_count": 1}, {"key": "Localités du département de la Dordogne", "doc_count": 1}, {"key": "Machines", "doc_count": 1}, {"key": "Oiseaux", "doc_count": 1}, {"key": "Tétrapodes", "doc_count": 1},
24      {"key": "Vertébrés", "doc_count": 1}, {"key": "Vie domestique", "doc_count": 1}, {"key": "Virus", "doc_count": 1}, {"key": "Volcans", "doc_count": 1}
25    ];
26      const listOfTermToIgnore =  ["anciennes", "anciens", "arrondissements", "autorites", "cantons", "capitales",
27          "chaines", "chefs lieux", "circonscriptions", "communautes d", "comtes d", "constellations", "continents",
28          "cours d", "départements", "districts d", "établissements", "états", "ethnonymes", "étoiles",
29          "europe", "îles", "lander-allemands", "lieux-mythologiques", "Localités d", "mers",
30          "montagnes", "municipalité", "fromage", "localités", "noms de", "numéros de",
31          "odonymes", "organisations internationales", "pays ", "péninsules", "préfectures", "provinces", "quartiers",
32          "régions", "réserves indiennes", "sous ", "territoires", "toponymes ", "unions supranationales", "villes du quebec", "voivodies de pologne" ]
33function filter(buckets) {
34    return buckets.filter(({key}) => {
35        const _key = key.toLowerCase();
36        return listOfTtermToIgnore.every(term => !_key.startsWith(term))
37    }
38});
39

Source https://stackoverflow.com/questions/70852570

QUESTION

Regex match strings divided by 'and'

Asked 2022-Jan-18 at 08:09

I need to parse a string to get desired number and position form a string, for example:

12 Better Developers and 3 Testers
25 Mechanics and chef
3medic and 3 nurses
4

Currently I am using code like this which returns list of tuples, like [('2', 'Better Developers'), ('3', 'Testers')]:

12 Better Developers and 3 Testers
25 Mechanics and chef
3medic and 3 nurses
4def parse_workers_list_from_str(string_value: str) -> [(str, str)]:
5    result: [(str, str)] = []
6    if string_value:
7        for part in string_value.split('and'):
8            result.append(re.findall(r'(?: *)(\d+|)(?: |)([\w ]+)', part.strip())[0])
9    return result
10

Can I do it without .split() using only regex?

ANSWER

Answered 2022-Jan-17 at 15:05

Together with re.MULTILINE you can do everything in one regex, that will also split everything correctly:

12 Better Developers and 3 Testers
25 Mechanics and chef
3medic and 3 nurses
4def parse_workers_list_from_str(string_value: str) -> [(str, str)]:
5    result: [(str, str)] = []
6    if string_value:
7        for part in string_value.split('and'):
8            result.append(re.findall(r'(?: *)(\d+|)(?: |)([\w ]+)', part.strip())[0])
9    return result
10>>> s = """2 Better Developers and 3 Testers
115 Mechanics and chef
12medic and 3 nurses"""
13>>> re.findall(r"\s*(\d*)\s*(.+?)(?:\s+and\s+|$)", s, re.MULTILINE)
14[('2', 'Better Developers'), ('3', 'Testers'), ('5', 'Mechanics'), ('', 'chef'), ('', 'medic'), ('3', 'nurses')]
15

With explanation and conversion of empty '' to 1:

12 Better Developers and 3 Testers
25 Mechanics and chef
3medic and 3 nurses
4def parse_workers_list_from_str(string_value: str) -> [(str, str)]:
5    result: [(str, str)] = []
6    if string_value:
7        for part in string_value.split('and'):
8            result.append(re.findall(r'(?: *)(\d+|)(?: |)([\w ]+)', part.strip())[0])
9    return result
10>>> s = """2 Better Developers and 3 Testers
115 Mechanics and chef
12medic and 3 nurses"""
13>>> re.findall(r"\s*(\d*)\s*(.+?)(?:\s+and\s+|$)", s, re.MULTILINE)
14[('2', 'Better Developers'), ('3', 'Testers'), ('5', 'Mechanics'), ('', 'chef'), ('', 'medic'), ('3', 'nurses')]
15import re
16
17s = """2 Better Developers and 3 Testers
185 Mechanics and chef
19medic and 3 nurses"""
20
21results = re.findall(r"""
22    # Capture the number if one exists
23    (\d*)
24    # Remove spacing between number and text
25    \s*
26    # Caputre the text
27    (.+?)
28    # Attempt to match the word 'and' or the end of the line
29    (?:\s+and\s+|$\n?)
30    """, s, re.MULTILINE|re.VERBOSE)
31
32results = [(int(n or 1), t.title()) for n, t in results]
33results == [(2, 'Better Developers'), (3, 'Testers'), (5, 'Mechanics'), (1, 'Chef'), (1, 'Medic'), (3, 'Nurses')]
34

Source https://stackoverflow.com/questions/70743028

QUESTION

How to make a joined well-known full node into an authority node in Substrate, automatically became an validator node?

Asked 2022-Jan-03 at 15:26

I use node-template to practise the tutorials.

I have finished the start a private network and Permissioned Network. At the end, I can see Charlie joined the network as a full node. I want to go further, I try to make Charlie to be an authority node, I want to make Charlie's role the same as Alice's and Bob's.

I want to let a node automatically joined and became an validator to generate blocks and finalize blocks.

Previously, Charlie runs as :

1./node-template \
2--chain=local \
3--base-path /tmp/validator3 \
4--name charlie  \
5--node-key=3a9d5b35b9fb4c42aafadeca046f6bf56107bd2579687f069b42646684b94d9e \
6--port 30335 \
7--ws-port=9946 \
8--offchain-worker always
9

Now Charlie can act as a full node.

I try to modify and make Charlie run as an authority role.

What I do :

  1. clear the db of Charlie.

    ./node-template purge-chain --chain=local --base-path /tmp/validator3 -y

  2. run Charlie as an validator,

remove --offchain-worker always , add --validator --pruning archive

1./node-template \
2--chain=local \
3--base-path /tmp/validator3 \
4--name charlie  \
5--node-key=3a9d5b35b9fb4c42aafadeca046f6bf56107bd2579687f069b42646684b94d9e \
6--port 30335 \
7--ws-port=9946 \
8--offchain-worker always
9./node-template \
10    --chain=local \
11    --base-path /tmp/validator3 \
12    --name charlie \
13    --node-key=3a9d5b35b9fb4c42aafadeca046f6bf56107bd2579687f069b42646684b94d9e \
14    --port 30335 \
15    --ws-port 9946 \
16    --rpc-port 9935 \
17    --validator \
18    --pruning archive \
19    --rpc-methods=unsafe \
20    --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/12D3KooWFzXtYJhUkMsWTXQodYaXhs6ah52xVExicuFPvmUQoZrE    # connecto to Alice, if not specified, could not find peer.
21
  1. submit auro grandpa keys:

input the auro key:

1./node-template \
2--chain=local \
3--base-path /tmp/validator3 \
4--name charlie  \
5--node-key=3a9d5b35b9fb4c42aafadeca046f6bf56107bd2579687f069b42646684b94d9e \
6--port 30335 \
7--ws-port=9946 \
8--offchain-worker always
9./node-template \
10    --chain=local \
11    --base-path /tmp/validator3 \
12    --name charlie \
13    --node-key=3a9d5b35b9fb4c42aafadeca046f6bf56107bd2579687f069b42646684b94d9e \
14    --port 30335 \
15    --ws-port 9946 \
16    --rpc-port 9935 \
17    --validator \
18    --pruning archive \
19    --rpc-methods=unsafe \
20    --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/12D3KooWFzXtYJhUkMsWTXQodYaXhs6ah52xVExicuFPvmUQoZrE    # connecto to Alice, if not specified, could not find peer.
21curl http://127.0.0.1:9935 -H "Content-Type:application/json;charset=utf-8" -d \
22       '{
23                     "jsonrpc":"2.0",
24                     "id":1,
25                     "method":"author_insertKey",
26                     "params": [
27                       "aura",
28          "scheme sure language chef bacon second club wild suggest advice awful room",
29          "0x7a96031a623cb0057299dfe51e9421fde3cc80cf7e534bd7c1fbd84b0d520547"
30        ]
31    }'
32

then input the grandpa key:

1./node-template \
2--chain=local \
3--base-path /tmp/validator3 \
4--name charlie  \
5--node-key=3a9d5b35b9fb4c42aafadeca046f6bf56107bd2579687f069b42646684b94d9e \
6--port 30335 \
7--ws-port=9946 \
8--offchain-worker always
9./node-template \
10    --chain=local \
11    --base-path /tmp/validator3 \
12    --name charlie \
13    --node-key=3a9d5b35b9fb4c42aafadeca046f6bf56107bd2579687f069b42646684b94d9e \
14    --port 30335 \
15    --ws-port 9946 \
16    --rpc-port 9935 \
17    --validator \
18    --pruning archive \
19    --rpc-methods=unsafe \
20    --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/12D3KooWFzXtYJhUkMsWTXQodYaXhs6ah52xVExicuFPvmUQoZrE    # connecto to Alice, if not specified, could not find peer.
21curl http://127.0.0.1:9935 -H "Content-Type:application/json;charset=utf-8" -d \
22       '{
23                     "jsonrpc":"2.0",
24                     "id":1,
25                     "method":"author_insertKey",
26                     "params": [
27                       "aura",
28          "scheme sure language chef bacon second club wild suggest advice awful room",
29          "0x7a96031a623cb0057299dfe51e9421fde3cc80cf7e534bd7c1fbd84b0d520547"
30        ]
31    }'
32curl http://127.0.0.1:9935 -H "Content-Type:application/json;charset=utf-8" -d \
33               '{
34                 "jsonrpc":"2.0",
35                 "id":1,
36                 "method":"author_insertKey",
37                 "params": [
38                   "gran",
39      "scheme sure language chef bacon second club wild suggest advice awful room",
40      "0x85935cef010757764ec07fd2ea8665a123283b7d81d2a063211b3d52d8cc215e"
41    ]
42}'
43

Doing this is to insert the SessionKeys for Charlie.

  1. restart Charlie.

5). I stop Alice(or Bob, kill either Alice or Bob), leave Bob and Charlie running. The Best block# is continuing, the finalized# is hanged there, not growing.

I have tried many times and search for a day. Does it need a session pallet to support this? Where am I wrong? what I didn't do?

ANSWER

Answered 2022-Jan-03 at 15:22

I got an answer substrate-validator-set. If you want to dynamically add validator on a PoA network, you need to add a session pallet, and let session to manage the auro key and grandpa key.

Source https://stackoverflow.com/questions/70541104

QUESTION

Pandas filtering based on 2 different columns conditions

Asked 2021-Dec-29 at 23:29

So lets say, I have the following dataframe.

1data = pd.DataFrame({'Name': ['RACHEL', 'MONICA', 'PHOEBE', 'ROSS', 'CHANDLER', 'JOEY', 'RACHEL', 'RACHEL'],
2                        
3                      'Age': [30, 35, 37, 33, 34, 30, 30, 15],
4                        
5                      'Salary': [100000, 93000, 88000, 120000, 94000, 95000, 100000, 10],
6                        
7                      'Job': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY',
8                              'IT', 'ARTIST', 'DESIGNER', 'CHEF']})
9

which gives:

1data = pd.DataFrame({'Name': ['RACHEL', 'MONICA', 'PHOEBE', 'ROSS', 'CHANDLER', 'JOEY', 'RACHEL', 'RACHEL'],
2                        
3                      'Age': [30, 35, 37, 33, 34, 30, 30, 15],
4                        
5                      'Salary': [100000, 93000, 88000, 120000, 94000, 95000, 100000, 10],
6                        
7                      'Job': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY',
8                              'IT', 'ARTIST', 'DESIGNER', 'CHEF']})
9Name    Age Salary  Job
10RACHEL  30  100000  DESIGNER
11MONICA  35  93000   CHEF
12PHOEBE  37  88000   MASUS
13ROSS    33  120000  PALENTOLOGY
14CHANDLER    34  94000   IT
15JOEY    30  95000   ARTIST
16RACHEL  30  100000  DESIGNER
17RACHEL  15  10  CHEF
18

What I want to do it pretty simple, I want to filter(get rows) and get rows where Name != 'RACHEL' and Job != 'CHEF';

Expected result set:

1data = pd.DataFrame({'Name': ['RACHEL', 'MONICA', 'PHOEBE', 'ROSS', 'CHANDLER', 'JOEY', 'RACHEL', 'RACHEL'],
2                        
3                      'Age': [30, 35, 37, 33, 34, 30, 30, 15],
4                        
5                      'Salary': [100000, 93000, 88000, 120000, 94000, 95000, 100000, 10],
6                        
7                      'Job': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY',
8                              'IT', 'ARTIST', 'DESIGNER', 'CHEF']})
9Name    Age Salary  Job
10RACHEL  30  100000  DESIGNER
11MONICA  35  93000   CHEF
12PHOEBE  37  88000   MASUS
13ROSS    33  120000  PALENTOLOGY
14CHANDLER    34  94000   IT
15JOEY    30  95000   ARTIST
16RACHEL  30  100000  DESIGNER
17RACHEL  15  10  CHEF
18Name    Age Salary  Job
19RACHEL  30  100000  DESIGNER
20MONICA  35  93000   CHEF
21PHOEBE  37  88000   MASUS
22ROSS    33  120000  PALENTOLOGY
23CHANDLER    34  94000   IT
24JOEY    30  95000   ARTIST
25RACHEL  30  100000  DESIGNER
26

Note that the last entry is removed.

What i have tried so far is:

1data = pd.DataFrame({'Name': ['RACHEL', 'MONICA', 'PHOEBE', 'ROSS', 'CHANDLER', 'JOEY', 'RACHEL', 'RACHEL'],
2                        
3                      'Age': [30, 35, 37, 33, 34, 30, 30, 15],
4                        
5                      'Salary': [100000, 93000, 88000, 120000, 94000, 95000, 100000, 10],
6                        
7                      'Job': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY',
8                              'IT', 'ARTIST', 'DESIGNER', 'CHEF']})
9Name    Age Salary  Job
10RACHEL  30  100000  DESIGNER
11MONICA  35  93000   CHEF
12PHOEBE  37  88000   MASUS
13ROSS    33  120000  PALENTOLOGY
14CHANDLER    34  94000   IT
15JOEY    30  95000   ARTIST
16RACHEL  30  100000  DESIGNER
17RACHEL  15  10  CHEF
18Name    Age Salary  Job
19RACHEL  30  100000  DESIGNER
20MONICA  35  93000   CHEF
21PHOEBE  37  88000   MASUS
22ROSS    33  120000  PALENTOLOGY
23CHANDLER    34  94000   IT
24JOEY    30  95000   ARTIST
25RACHEL  30  100000  DESIGNER
26data = data.loc[ (data.Name != 'RACHEL') & (data.Job != 'CHEF') ]
27

This filters other rows Where Name = "RACHEL" OR Job = "CHEF". I only want to filter the last row where Name = 'RACHEL' and in the same row the Job = "CHEF".

Any help is appreciated. Thanks.

ANSWER

Answered 2021-Dec-29 at 23:29
1data = pd.DataFrame({'Name': ['RACHEL', 'MONICA', 'PHOEBE', 'ROSS', 'CHANDLER', 'JOEY', 'RACHEL', 'RACHEL'],
2                        
3                      'Age': [30, 35, 37, 33, 34, 30, 30, 15],
4                        
5                      'Salary': [100000, 93000, 88000, 120000, 94000, 95000, 100000, 10],
6                        
7                      'Job': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY',
8                              'IT', 'ARTIST', 'DESIGNER', 'CHEF']})
9Name    Age Salary  Job
10RACHEL  30  100000  DESIGNER
11MONICA  35  93000   CHEF
12PHOEBE  37  88000   MASUS
13ROSS    33  120000  PALENTOLOGY
14CHANDLER    34  94000   IT
15JOEY    30  95000   ARTIST
16RACHEL  30  100000  DESIGNER
17RACHEL  15  10  CHEF
18Name    Age Salary  Job
19RACHEL  30  100000  DESIGNER
20MONICA  35  93000   CHEF
21PHOEBE  37  88000   MASUS
22ROSS    33  120000  PALENTOLOGY
23CHANDLER    34  94000   IT
24JOEY    30  95000   ARTIST
25RACHEL  30  100000  DESIGNER
26data = data.loc[ (data.Name != 'RACHEL') & (data.Job != 'CHEF') ]
27rachefs = df[~(df["Name"] == "RACHEL") | ~(df["Job"] == "CHEF")]
28

The | usually meaning OR turns into an AND because the negatives we use.

https://en.wikipedia.org/wiki/De_Morgan%27s_laws#

Source https://stackoverflow.com/questions/70525820

QUESTION

Can we automate updating the chef node attributes?

Asked 2021-Dec-04 at 03:01

I have a node with the following json in chef nodes:

1 {
2  "name": "app-node-01",
3  "chef_environment": "dev",
4  "run_list": [
5  "recipe[hello-world]"
6],
7  "normal": {
8    "app_version": "1.0.0",
9    "tags": [
10
11    ]
12  }
13}
14

I am trying to look for a way to manage this json config in github and when there is a change in the version of app_version, I update the json file in github and update the version to 1.0.1 and run a command like knife node edit -c <json file from github> app-node-01 the command will go over the json file and update the node in chef? is this possible?

I tried the command in my local but it opened the VI editor for me to edit.

I dont want to do manual edits as I am trying to look for a way to manage this also in github just like any other chef artifact (data bags, environment files, cookbooks etc)

ANSWER

Answered 2021-Dec-04 at 03:01

Like with other Chef artifacts, nodes can also be updated from file using the from file argument.

Instead of knife node edit, you need to run:

1 {
2  &quot;name&quot;: &quot;app-node-01&quot;,
3  &quot;chef_environment&quot;: &quot;dev&quot;,
4  &quot;run_list&quot;: [
5  &quot;recipe[hello-world]&quot;
6],
7  &quot;normal&quot;: {
8    &quot;app_version&quot;: &quot;1.0.0&quot;,
9    &quot;tags&quot;: [
10
11    ]
12  }
13}
14knife node from file PATH_TO_JSON_FILE
15

Source https://stackoverflow.com/questions/70220865

QUESTION

Inconsistent inheritance of interfaces with generic classes

Asked 2021-Dec-02 at 16:32

Take a class hierarchy Chef extends Person extends GraphNode, where each parent class is generic in an interface T that extends the interface of its parent class. The uppermost (abstract) class defines a method accepting as its argument a subset of the keys of T.

I'm seeing an error (highlighted below) when keys are a subset derived from T. When the derived keys are exactly keyof T, the code works as expected. As far as I can tell both should work – and it's notable that it does work in the final class Chef, which is not generic.

Inheritance extensions are not behaving as I'd expect, have I missed something there?

1type Literal = boolean | number | string;
2type LiteralKeys&lt;T&gt; = { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
3
4interface IPerson { name: string; friend: Person; }
5interface IChef extends IPerson { specialty: string; }
6
7export abstract class GraphNode&lt;T extends {} = {}&gt; {
8    // set&lt;K extends keyof T&gt;(_key: K, _value: T[K]) { /* ... */ }     // âś…
9    set&lt;K extends LiteralKeys&lt;T&gt;&gt;(_key: K, _value: T[K]) { /* ... */ } // ❌
10}
11
12export abstract class Person&lt;T extends IPerson = IPerson&gt; extends GraphNode&lt;T&gt; {
13    setName(name: string) {
14        this.set('name', name); // ❌ Argument of type 'string' is 
15        // ... not assignable to parameter of type 'LiteralKeys&lt;T&gt;'.
16    }
17}
18
19export class Chef extends Person&lt;IChef&gt; {
20    setSpecialty(specialty: string) {
21        this.set('specialty', specialty); // âś…
22    }
23}
24
25const sam = new Chef();
26sam.setName('Sam');
27sam.setSpecialty('BBQ');
28
29

ANSWER

Answered 2021-Dec-02 at 16:32

The generic type LiteralKeys<T> defined like

1type Literal = boolean | number | string;
2type LiteralKeys&lt;T&gt; = { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
3
4interface IPerson { name: string; friend: Person; }
5interface IChef extends IPerson { specialty: string; }
6
7export abstract class GraphNode&lt;T extends {} = {}&gt; {
8    // set&lt;K extends keyof T&gt;(_key: K, _value: T[K]) { /* ... */ }     // âś…
9    set&lt;K extends LiteralKeys&lt;T&gt;&gt;(_key: K, _value: T[K]) { /* ... */ } // ❌
10}
11
12export abstract class Person&lt;T extends IPerson = IPerson&gt; extends GraphNode&lt;T&gt; {
13    setName(name: string) {
14        this.set('name', name); // ❌ Argument of type 'string' is 
15        // ... not assignable to parameter of type 'LiteralKeys&lt;T&gt;'.
16    }
17}
18
19export class Chef extends Person&lt;IChef&gt; {
20    setSpecialty(specialty: string) {
21        this.set('specialty', specialty); // âś…
22    }
23}
24
25const sam = new Chef();
26sam.setName('Sam');
27sam.setSpecialty('BBQ');
28
29type LiteralKeys&lt;T&gt; = 
30  { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
31

is a combination of mapped types, indexed access types and conditional types. When you pass in a T that's some specific type like IPerson, the compiler can evaluate it right away:

1type Literal = boolean | number | string;
2type LiteralKeys&lt;T&gt; = { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
3
4interface IPerson { name: string; friend: Person; }
5interface IChef extends IPerson { specialty: string; }
6
7export abstract class GraphNode&lt;T extends {} = {}&gt; {
8    // set&lt;K extends keyof T&gt;(_key: K, _value: T[K]) { /* ... */ }     // âś…
9    set&lt;K extends LiteralKeys&lt;T&gt;&gt;(_key: K, _value: T[K]) { /* ... */ } // ❌
10}
11
12export abstract class Person&lt;T extends IPerson = IPerson&gt; extends GraphNode&lt;T&gt; {
13    setName(name: string) {
14        this.set('name', name); // ❌ Argument of type 'string' is 
15        // ... not assignable to parameter of type 'LiteralKeys&lt;T&gt;'.
16    }
17}
18
19export class Chef extends Person&lt;IChef&gt; {
20    setSpecialty(specialty: string) {
21        this.set('specialty', specialty); // âś…
22    }
23}
24
25const sam = new Chef();
26sam.setName('Sam');
27sam.setSpecialty('BBQ');
28
29type LiteralKeys&lt;T&gt; = 
30  { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
31type EagerlyEvaluated = LiteralKeys&lt;IPerson&gt; // &quot;name&quot;
32

But when T is or depends upon an unspecified type parameter, such as inside the body of setName(), it has to defer evaluation, and as such it stays mostly unevaluated:

1type Literal = boolean | number | string;
2type LiteralKeys&lt;T&gt; = { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
3
4interface IPerson { name: string; friend: Person; }
5interface IChef extends IPerson { specialty: string; }
6
7export abstract class GraphNode&lt;T extends {} = {}&gt; {
8    // set&lt;K extends keyof T&gt;(_key: K, _value: T[K]) { /* ... */ }     // âś…
9    set&lt;K extends LiteralKeys&lt;T&gt;&gt;(_key: K, _value: T[K]) { /* ... */ } // ❌
10}
11
12export abstract class Person&lt;T extends IPerson = IPerson&gt; extends GraphNode&lt;T&gt; {
13    setName(name: string) {
14        this.set('name', name); // ❌ Argument of type 'string' is 
15        // ... not assignable to parameter of type 'LiteralKeys&lt;T&gt;'.
16    }
17}
18
19export class Chef extends Person&lt;IChef&gt; {
20    setSpecialty(specialty: string) {
21        this.set('specialty', specialty); // âś…
22    }
23}
24
25const sam = new Chef();
26sam.setName('Sam');
27sam.setSpecialty('BBQ');
28
29type LiteralKeys&lt;T&gt; = 
30  { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
31type EagerlyEvaluated = LiteralKeys&lt;IPerson&gt; // &quot;name&quot;
32function deferred&lt;T extends IPerson&gt;() {
33    type Deferred = LiteralKeys&lt;T&gt;;
34    // type Deferred = { [K in keyof T]-?: T[K] extends Literal ? K : never; }[keyof T]
35}
36

And the compiler isn't able to do the sort of higher order reasoning that would let it decide if some specific value like "name" is compatible with such an unevaluated type for all T extends IPerson. It treats that type as mostly opaque. Since it can't verify that any value is assignable to it, it will generate an error if you do assign any value to it:

1type Literal = boolean | number | string;
2type LiteralKeys&lt;T&gt; = { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
3
4interface IPerson { name: string; friend: Person; }
5interface IChef extends IPerson { specialty: string; }
6
7export abstract class GraphNode&lt;T extends {} = {}&gt; {
8    // set&lt;K extends keyof T&gt;(_key: K, _value: T[K]) { /* ... */ }     // âś…
9    set&lt;K extends LiteralKeys&lt;T&gt;&gt;(_key: K, _value: T[K]) { /* ... */ } // ❌
10}
11
12export abstract class Person&lt;T extends IPerson = IPerson&gt; extends GraphNode&lt;T&gt; {
13    setName(name: string) {
14        this.set('name', name); // ❌ Argument of type 'string' is 
15        // ... not assignable to parameter of type 'LiteralKeys&lt;T&gt;'.
16    }
17}
18
19export class Chef extends Person&lt;IChef&gt; {
20    setSpecialty(specialty: string) {
21        this.set('specialty', specialty); // âś…
22    }
23}
24
25const sam = new Chef();
26sam.setName('Sam');
27sam.setSpecialty('BBQ');
28
29type LiteralKeys&lt;T&gt; = 
30  { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
31type EagerlyEvaluated = LiteralKeys&lt;IPerson&gt; // &quot;name&quot;
32function deferred&lt;T extends IPerson&gt;() {
33    type Deferred = LiteralKeys&lt;T&gt;;
34    // type Deferred = { [K in keyof T]-?: T[K] extends Literal ? K : never; }[keyof T]
35}
36const name: Deferred = &quot;name&quot; // error!
37

There are some GitHub issues around the compiler not using generic constraints like T extends IPerson to help partially evaluate conditional types instead of completely deferring them. See microsoft/TypeScript#39787 and microsoft/TypeScript#42077 for example. Even if this were improved it might not be possible for the compiler to understand that "name" should always be assignable to LiteralKeys<T> when T extends IPerson.


In the absence of getting the compiler to understand what you already know, you can use a type assertion to just tell the compiler that you are sure that "name" is assignable and that it shouldn't worry:

1type Literal = boolean | number | string;
2type LiteralKeys&lt;T&gt; = { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
3
4interface IPerson { name: string; friend: Person; }
5interface IChef extends IPerson { specialty: string; }
6
7export abstract class GraphNode&lt;T extends {} = {}&gt; {
8    // set&lt;K extends keyof T&gt;(_key: K, _value: T[K]) { /* ... */ }     // âś…
9    set&lt;K extends LiteralKeys&lt;T&gt;&gt;(_key: K, _value: T[K]) { /* ... */ } // ❌
10}
11
12export abstract class Person&lt;T extends IPerson = IPerson&gt; extends GraphNode&lt;T&gt; {
13    setName(name: string) {
14        this.set('name', name); // ❌ Argument of type 'string' is 
15        // ... not assignable to parameter of type 'LiteralKeys&lt;T&gt;'.
16    }
17}
18
19export class Chef extends Person&lt;IChef&gt; {
20    setSpecialty(specialty: string) {
21        this.set('specialty', specialty); // âś…
22    }
23}
24
25const sam = new Chef();
26sam.setName('Sam');
27sam.setSpecialty('BBQ');
28
29type LiteralKeys&lt;T&gt; = 
30  { [K in keyof T]-?: T[K] extends Literal ? K : never }[keyof T];
31type EagerlyEvaluated = LiteralKeys&lt;IPerson&gt; // &quot;name&quot;
32function deferred&lt;T extends IPerson&gt;() {
33    type Deferred = LiteralKeys&lt;T&gt;;
34    // type Deferred = { [K in keyof T]-?: T[K] extends Literal ? K : never; }[keyof T]
35}
36const name: Deferred = &quot;name&quot; // error!
37export abstract class Person&lt;T extends IPerson = IPerson&gt; extends GraphNode&lt;T&gt; {
38    setName(name: string) {
39        (this as Person).set('name', name); // okay now
40    }
41}
42

Here I'm asserting that it can treat this as a Person<IPerson> instead of a Person<T>, at which point the relevant type for the _key parameter is LiteralKeys<IPerson> (which is just "name") and not LiteralKeys<T> (which is âť“). Of course when we type-assert things we should take extra care to make sure we are not accidentally lying to the compiler, since the burden of verifying type safety has shifted from the compiler (which can't handle it in this instance) to the human developer (who potentially can handle it but are known to be somewhat unreliable especially immediately before or after meals or bedtime). In this case I think this as Person is probably harmless, especially because all IPerson subtypes will have to have a name property whose value is assignable to string and thus to Literal, but it's good to pause and triple check.

Playground link to code

Source https://stackoverflow.com/questions/70192877

QUESTION

C++ Producer Consumer Problem with condition variable + mutex + pthreads

Asked 2021-Nov-15 at 15:44

I'm need to do the producer consumer problem in c++, solve for 1 consumer and 6 producer, and for 1 producer and 6 consumer, below is the statement of the question.

Question 1: Imagine that you are waiting for some friends in a very busy restaurant and you are watching the staff, who wait on tables, bring food from the kitchen to their tables. This is an example of the classic "Producer-Consumer'' problem. There is a limit on servers and meals are constantly produced by the kitchen. Consider then that there is a limit on servers (consumers) and an "unlimited" supply of meals being produced by chefs (producers).

One approach to facilitate identification and thus reduce to a "producer-consumer" problem is to limit the number of consumers and thus limit the infinite number of meals. produced in the kitchen. Thus, the existence of a traffic light is suggested to control the production order of the meals that will be taken by the attendants.

The procedure would be something like:

  1. Create a semaphore;
  2. Create the server and chef threads;
  3. Produce as many meals as you can and keep a record of how many meals are in the queue;
  4. The server thread will run until it manages to deliver all the meals produced in the tables; and
  5. Threads must be "joined" with the main thread.

Also consider that there are 6 chefs and 1 attendant. If you want, you can consider that a chef takes 50 microseconds to produce a meal and the server takes 10 microseconds to deliver the meal on the table. Set a maximum number of customers to serve. Print on the screen, at the end of the execution, which chef is most and least idle and how many meals each chef has produced.

Question 2: Considering the restaurant described above. Now consider that there are 1 chef and 6 attendants. Assume that a chef takes 50 microseconds to produce a meal and the server takes 15 microseconds to deliver the meal to the table. Set a maximum number of customers to serve. Print which server is the most and least idle and how many meals each server has delivered.

I managed to solve for 6 producers and 1 consumer, but for 6 consumers and 1 producer it's not working, it seems that the program gets stuck in some DeadLock. I'm grateful if anyone knows how to help.

1#include &lt;iostream&gt;
2#include &lt;random&gt;
3#include &lt;chrono&gt;
4#include &lt;thread&gt;
5#include &lt;mutex&gt;
6#include &lt;deque&gt;
7
8//The mutex class is a synchronization primitive that can be used to protect shared data
9//from being simultaneously accessed by multiple threads.
10std::mutex semaforo;                       //semafoto para fazer o controle de acesso do buffer
11std::condition_variable notifica;          //variavel condicional para fazer a notificação de prato consumido/consumido
12std::deque&lt;int&gt; buffer;                    //buffer de inteiros
13const unsigned int capacidade_buffer = 10; //tamanho do buffer
14const unsigned int numero_pratos = 25;     //numeros de pratos a serem produzidos
15
16void produtor()
17{
18    unsigned static int contador_pratos_produzidos = 0;
19    while (contador_pratos_produzidos &lt; numero_pratos)
20    {
21        std::unique_lock&lt;std::mutex&gt; locker(semaforo);
22        notifica.wait(locker, []
23                      { return buffer.size() &lt; capacidade_buffer; });
24        std::this_thread::sleep_for(std::chrono::microseconds(50));
25        buffer.push_back(contador_pratos_produzidos);
26        if (contador_pratos_produzidos &lt; numero_pratos)
27        {
28            contador_pratos_produzidos++;
29        }
30        locker.unlock();
31        notifica.notify_all();
32    }
33}
34
35void consumidor(int ID, std::vector&lt;int&gt; &amp;consumido)
36{
37    unsigned static int contador_pratos_consumidos = 0;
38    while (contador_pratos_consumidos &lt; numero_pratos)
39    {
40        std::unique_lock&lt;std::mutex&gt; locker(semaforo);
41        notifica.wait(locker, []
42                      { return buffer.size() &gt; 0; });
43        std::this_thread::sleep_for(std::chrono::microseconds(15));
44        buffer.pop_front();
45        if (contador_pratos_consumidos &lt; numero_pratos)
46        {
47            contador_pratos_consumidos++;
48            consumido[ID]++;
49        }
50        locker.unlock();
51        notifica.notify_one();
52    }
53}
54
55int main()
56{
57    //vetor para contagem do consumo de cada garcon
58    std::vector&lt;int&gt; consumido(6, 0);
59
60    //vetor de threads garcon(consumidores)
61    std::vector&lt;std::thread&gt; consumidores;
62    for (int k = 0; k &lt; 6; k++)
63    {
64        consumidores.push_back(std::thread(consumidor, k, std::ref(consumido)));
65    }
66
67    //produtor/chef
68    std::thread p1(produtor);
69
70    for (auto &amp;k : consumidores)
71    {
72        k.join();
73    }
74    p1.join();
75
76    int mais_ocioso = 200, menos_ocioso = 0, mais, menos;
77    for (int k = 0; k &lt; 6; k++)
78    {
79        std::cout &lt;&lt; &quot;Garcon &quot; &lt;&lt; k + 1 &lt;&lt; &quot; entregou &quot; &lt;&lt; consumido[k] &lt;&lt; &quot; pratos\n&quot;;
80        if (consumido[k] &gt; menos_ocioso)
81        {
82            menos = k + 1;
83            menos_ocioso = consumido[k];
84        }
85        if (consumido[k] &lt; mais_ocioso)
86        {
87            mais = k + 1;
88            mais_ocioso = consumido[k];
89        }
90    }
91    std::cout &lt;&lt; &quot;\nO mais ocioso foi o garcon &quot; &lt;&lt; mais &lt;&lt; &quot; e o menos ocioso foi o garcon &quot; &lt;&lt; menos &lt;&lt; &quot;\n&quot;;
92}
93

ANSWER

Answered 2021-Nov-15 at 15:44

The same exact bug exists in both the consumer and the producer function. I'll explain one of them, and the same bug must also be fixed in the other one.

1#include &lt;iostream&gt;
2#include &lt;random&gt;
3#include &lt;chrono&gt;
4#include &lt;thread&gt;
5#include &lt;mutex&gt;
6#include &lt;deque&gt;
7
8//The mutex class is a synchronization primitive that can be used to protect shared data
9//from being simultaneously accessed by multiple threads.
10std::mutex semaforo;                       //semafoto para fazer o controle de acesso do buffer
11std::condition_variable notifica;          //variavel condicional para fazer a notificação de prato consumido/consumido
12std::deque&lt;int&gt; buffer;                    //buffer de inteiros
13const unsigned int capacidade_buffer = 10; //tamanho do buffer
14const unsigned int numero_pratos = 25;     //numeros de pratos a serem produzidos
15
16void produtor()
17{
18    unsigned static int contador_pratos_produzidos = 0;
19    while (contador_pratos_produzidos &lt; numero_pratos)
20    {
21        std::unique_lock&lt;std::mutex&gt; locker(semaforo);
22        notifica.wait(locker, []
23                      { return buffer.size() &lt; capacidade_buffer; });
24        std::this_thread::sleep_for(std::chrono::microseconds(50));
25        buffer.push_back(contador_pratos_produzidos);
26        if (contador_pratos_produzidos &lt; numero_pratos)
27        {
28            contador_pratos_produzidos++;
29        }
30        locker.unlock();
31        notifica.notify_all();
32    }
33}
34
35void consumidor(int ID, std::vector&lt;int&gt; &amp;consumido)
36{
37    unsigned static int contador_pratos_consumidos = 0;
38    while (contador_pratos_consumidos &lt; numero_pratos)
39    {
40        std::unique_lock&lt;std::mutex&gt; locker(semaforo);
41        notifica.wait(locker, []
42                      { return buffer.size() &gt; 0; });
43        std::this_thread::sleep_for(std::chrono::microseconds(15));
44        buffer.pop_front();
45        if (contador_pratos_consumidos &lt; numero_pratos)
46        {
47            contador_pratos_consumidos++;
48            consumido[ID]++;
49        }
50        locker.unlock();
51        notifica.notify_one();
52    }
53}
54
55int main()
56{
57    //vetor para contagem do consumo de cada garcon
58    std::vector&lt;int&gt; consumido(6, 0);
59
60    //vetor de threads garcon(consumidores)
61    std::vector&lt;std::thread&gt; consumidores;
62    for (int k = 0; k &lt; 6; k++)
63    {
64        consumidores.push_back(std::thread(consumidor, k, std::ref(consumido)));
65    }
66
67    //produtor/chef
68    std::thread p1(produtor);
69
70    for (auto &amp;k : consumidores)
71    {
72        k.join();
73    }
74    p1.join();
75
76    int mais_ocioso = 200, menos_ocioso = 0, mais, menos;
77    for (int k = 0; k &lt; 6; k++)
78    {
79        std::cout &lt;&lt; &quot;Garcon &quot; &lt;&lt; k + 1 &lt;&lt; &quot; entregou &quot; &lt;&lt; consumido[k] &lt;&lt; &quot; pratos\n&quot;;
80        if (consumido[k] &gt; menos_ocioso)
81        {
82            menos = k + 1;
83            menos_ocioso = consumido[k];
84        }
85        if (consumido[k] &lt; mais_ocioso)
86        {
87            mais = k + 1;
88            mais_ocioso = consumido[k];
89        }
90    }
91    std::cout &lt;&lt; &quot;\nO mais ocioso foi o garcon &quot; &lt;&lt; mais &lt;&lt; &quot; e o menos ocioso foi o garcon &quot; &lt;&lt; menos &lt;&lt; &quot;\n&quot;;
92}
93unsigned static int contador_pratos_consumidos = 0;
94while (contador_pratos_consumidos &lt; numero_pratos)
95{
96

This static counter gets accessed and modified by multiple execution threads.

Any non-atomic object that's used by multiple execution threads must be properly sequenced (accessed only when holding an appropriate mutex).

If you focus your attention on the above two lines it should be obvious that this counter is accessed without the protection of any mutex. Once you realize that, the bug is obvious: at some point contador_pratos_consumidos will be exactly one less than numero_pratos. When that happens you can have multiple execution threads evaluating the while condition, at the same time, and all of them will happily conclude that it's true.

Multiple execution threads then enter the while loop. One will succeed in acquiring the mutex and consuming the "product", and finish. The remaining execution threads will wait forever, for another "product" that will never arrive. No more products will ever be produced. No soup for them.

The same bug also exists in the producer, except that the effects of the bug will be rather subtle: more products will end up being produced than there should be.

Of course, pedantically all of this is undefined behavior, so anything can really happen, but these are the typical, usual consequences this kind of undefined behavior. Both bugs must be fixed in order for this algorithm to work correctly.

Source https://stackoverflow.com/questions/69975143

QUESTION

Create elements by looping a javascript object

Asked 2021-Oct-05 at 08:54

Lets say we have an array of objects and we loop through it and create a div in every iteration.

How could we take the property ol (which is also an array of objects) in every iteration and create an <ol> inside the div for every object in it, with as many <li>'s as the number in the property li. Also, text inside the li should be the text of the property title so it should look like this:

enter image description here

I'm hitting my head to solve it but my noobness doesn't let me. I tried another loop of the ol object inside the outer loop, but I cant get it right.

1var array_of_objects = [{
2  "name": "john",
3  "job": "pilot",
4  "email": "johnpilot@gmail.com",
5  "ol": [{
6    "li": 6,
7    "title": "6 li's"
8  }, {
9    "li": 2,
10    "title": "2 li's"
11  }, {
12    "li": 5,
13    "title": "5 li's"
14  }]
15}, {
16  "name": "mark",
17  "job": "engineer",
18  "email": "markengineer@gmail.com",
19  "ol": [{
20    "li": 2,
21    "title": "2 li's"
22  }, {
23    "li": 7,
24    "title": "7 li's"
25  }, {
26    "li": 2,
27    "title": "2 li's"
28  }, {
29    "li": 1,
30    "title": "1 li's"
31  }]
32}, {
33  "name": "george",
34  "job": "chef",
35  "email": "georgechef@gmail.com",
36  "ol": [{
37    "li": 1,
38    "title": "1 li's"
39  }, {
40    "li": 3,
41    "title": "3 li's"
42  }, {
43    "li": 4,
44    "title": "4 li's"
45  }, {
46    "li": 3,
47    "title": "3 li's"
48  }, {
49    "li": 3,
50    "title": "3 li's"
51  }]
52}]
53
54function iterate(arr) {
55  arr.forEach(i =&gt; {
56    var name = i.name;
57    var job = i.job;
58    var email = i.email;
59    var ol_li = i.ol_li;
60    var str = `&lt;div&gt;
61    &lt;span&gt;${name}&lt;/span&gt;
62    &lt;span&gt;${job}&lt;/span&gt;
63    &lt;span&gt;${email}&lt;/span&gt;
64    &lt;span&gt;ol's should be placed here&lt;/span&gt;
65    &lt;/div&gt;`
66    $("body").append(str);
67  })
68}
69
70iterate(array_of_objects)
1var array_of_objects = [{
2  "name": "john",
3  "job": "pilot",
4  "email": "johnpilot@gmail.com",
5  "ol": [{
6    "li": 6,
7    "title": "6 li's"
8  }, {
9    "li": 2,
10    "title": "2 li's"
11  }, {
12    "li": 5,
13    "title": "5 li's"
14  }]
15}, {
16  "name": "mark",
17  "job": "engineer",
18  "email": "markengineer@gmail.com",
19  "ol": [{
20    "li": 2,
21    "title": "2 li's"
22  }, {
23    "li": 7,
24    "title": "7 li's"
25  }, {
26    "li": 2,
27    "title": "2 li's"
28  }, {
29    "li": 1,
30    "title": "1 li's"
31  }]
32}, {
33  "name": "george",
34  "job": "chef",
35  "email": "georgechef@gmail.com",
36  "ol": [{
37    "li": 1,
38    "title": "1 li's"
39  }, {
40    "li": 3,
41    "title": "3 li's"
42  }, {
43    "li": 4,
44    "title": "4 li's"
45  }, {
46    "li": 3,
47    "title": "3 li's"
48  }, {
49    "li": 3,
50    "title": "3 li's"
51  }]
52}]
53
54function iterate(arr) {
55  arr.forEach(i =&gt; {
56    var name = i.name;
57    var job = i.job;
58    var email = i.email;
59    var ol_li = i.ol_li;
60    var str = `&lt;div&gt;
61    &lt;span&gt;${name}&lt;/span&gt;
62    &lt;span&gt;${job}&lt;/span&gt;
63    &lt;span&gt;${email}&lt;/span&gt;
64    &lt;span&gt;ol's should be placed here&lt;/span&gt;
65    &lt;/div&gt;`
66    $("body").append(str);
67  })
68}
69
70iterate(array_of_objects)div {
71  display: flex;
72  flex-direction: column;
73  border: thin solid black;
74  margin: 0.4em;
75  padding: 0.2em;
76}
77
78span:not(:nth-child(4)) {
79  display: flex;
80  flex-direction: column;
81  border: thin solid red;
82  margin: 0.2em;
83  padding: 0.2em;
84}
85
86span:nth-child(4) {
87  display: flex;
88  flex-direction: row;
89  margin: 0.4em;
90  padding: 0.2em;
91}
92
93ol {
94  border: thin solid blue;
95  margin: 0.2em;
96}
97
98li {
99  margin: 0.2em;
100}
1var array_of_objects = [{
2  "name": "john",
3  "job": "pilot",
4  "email": "johnpilot@gmail.com",
5  "ol": [{
6    "li": 6,
7    "title": "6 li's"
8  }, {
9    "li": 2,
10    "title": "2 li's"
11  }, {
12    "li": 5,
13    "title": "5 li's"
14  }]
15}, {
16  "name": "mark",
17  "job": "engineer",
18  "email": "markengineer@gmail.com",
19  "ol": [{
20    "li": 2,
21    "title": "2 li's"
22  }, {
23    "li": 7,
24    "title": "7 li's"
25  }, {
26    "li": 2,
27    "title": "2 li's"
28  }, {
29    "li": 1,
30    "title": "1 li's"
31  }]
32}, {
33  "name": "george",
34  "job": "chef",
35  "email": "georgechef@gmail.com",
36  "ol": [{
37    "li": 1,
38    "title": "1 li's"
39  }, {
40    "li": 3,
41    "title": "3 li's"
42  }, {
43    "li": 4,
44    "title": "4 li's"
45  }, {
46    "li": 3,
47    "title": "3 li's"
48  }, {
49    "li": 3,
50    "title": "3 li's"
51  }]
52}]
53
54function iterate(arr) {
55  arr.forEach(i =&gt; {
56    var name = i.name;
57    var job = i.job;
58    var email = i.email;
59    var ol_li = i.ol_li;
60    var str = `&lt;div&gt;
61    &lt;span&gt;${name}&lt;/span&gt;
62    &lt;span&gt;${job}&lt;/span&gt;
63    &lt;span&gt;${email}&lt;/span&gt;
64    &lt;span&gt;ol's should be placed here&lt;/span&gt;
65    &lt;/div&gt;`
66    $("body").append(str);
67  })
68}
69
70iterate(array_of_objects)div {
71  display: flex;
72  flex-direction: column;
73  border: thin solid black;
74  margin: 0.4em;
75  padding: 0.2em;
76}
77
78span:not(:nth-child(4)) {
79  display: flex;
80  flex-direction: column;
81  border: thin solid red;
82  margin: 0.2em;
83  padding: 0.2em;
84}
85
86span:nth-child(4) {
87  display: flex;
88  flex-direction: row;
89  margin: 0.4em;
90  padding: 0.2em;
91}
92
93ol {
94  border: thin solid blue;
95  margin: 0.2em;
96}
97
98li {
99  margin: 0.2em;
100}&lt;script src="https://code.jquery.com/jquery-3.6.0.js"&gt;&lt;/script&gt;

ANSWER

Answered 2021-Oct-05 at 08:54

To do what you require you can use map() to loop through the ol array of each object and create a HTML string which can be appended to the div you create.

Note the use of fill() in the example below to create the required number of li elements with the same content.

Also note that the same approach can be used to both tidy the code and improve performance as it means you only append to the DOM once when the loop completes, instead of within each loop iteration.

Try this:

1var array_of_objects = [{
2  "name": "john",
3  "job": "pilot",
4  "email": "johnpilot@gmail.com",
5  "ol": [{
6    "li": 6,
7    "title": "6 li's"
8  }, {
9    "li": 2,
10    "title": "2 li's"
11  }, {
12    "li": 5,
13    "title": "5 li's"
14  }]
15}, {
16  "name": "mark",
17  "job": "engineer",
18  "email": "markengineer@gmail.com",
19  "ol": [{
20    "li": 2,
21    "title": "2 li's"
22  }, {
23    "li": 7,
24    "title": "7 li's"
25  }, {
26    "li": 2,
27    "title": "2 li's"
28  }, {
29    "li": 1,
30    "title": "1 li's"
31  }]
32}, {
33  "name": "george",
34  "job": "chef",
35  "email": "georgechef@gmail.com",
36  "ol": [{
37    "li": 1,
38    "title": "1 li's"
39  }, {
40    "li": 3,
41    "title": "3 li's"
42  }, {
43    "li": 4,
44    "title": "4 li's"
45  }, {
46    "li": 3,
47    "title": "3 li's"
48  }, {
49    "li": 3,
50    "title": "3 li's"
51  }]
52}]
53
54function iterate(arr) {
55  arr.forEach(i =&gt; {
56    var name = i.name;
57    var job = i.job;
58    var email = i.email;
59    var ol_li = i.ol_li;
60    var str = `&lt;div&gt;
61    &lt;span&gt;${name}&lt;/span&gt;
62    &lt;span&gt;${job}&lt;/span&gt;
63    &lt;span&gt;${email}&lt;/span&gt;
64    &lt;span&gt;ol's should be placed here&lt;/span&gt;
65    &lt;/div&gt;`
66    $("body").append(str);
67  })
68}
69
70iterate(array_of_objects)div {
71  display: flex;
72  flex-direction: column;
73  border: thin solid black;
74  margin: 0.4em;
75  padding: 0.2em;
76}
77
78span:not(:nth-child(4)) {
79  display: flex;
80  flex-direction: column;
81  border: thin solid red;
82  margin: 0.2em;
83  padding: 0.2em;
84}
85
86span:nth-child(4) {
87  display: flex;
88  flex-direction: row;
89  margin: 0.4em;
90  padding: 0.2em;
91}
92
93ol {
94  border: thin solid blue;
95  margin: 0.2em;
96}
97
98li {
99  margin: 0.2em;
100}&lt;script src="https://code.jquery.com/jquery-3.6.0.js"&gt;&lt;/script&gt;var array_of_objects = [{name:"john",job:"pilot",email:"johnpilot@gmail.com",ol:[{li:6,title:"6 li's"},{li:2,title:"2 li's"},{li:5,title:"5 li's"}]},{name:"mark",job:"engineer",email:"markengineer@gmail.com",ol:[{li:2,title:"2 li's"},{li:7,title:"7 li's"},{li:2,title:"2 li's"},{li:1,title:"1 li's"}]},{name:"george",job:"chef",email:"georgechef@gmail.com",ol:[{li:1,title:"1 li's"},{li:3,title:"3 li's"},{li:4,title:"4 li's"},{li:3,title:"3 li's"},{li:3,title:"3 li's"}]}];
101
102function htmlFromData(arr) {
103  return arr.map(obj =&gt; {
104    let olHtml = obj.ol.map(ol =&gt; `&lt;ol&gt;${(new Array(ol.li)).fill(`&lt;li&gt;${ol.title}&lt;/li&gt;`).join('')}&lt;/ol&gt;`).join('');
105    return `&lt;div&gt;
106      &lt;span&gt;${obj.name}&lt;/span&gt;
107      &lt;span&gt;${obj.job}&lt;/span&gt;
108      &lt;span&gt;${obj.email}&lt;/span&gt;
109      &lt;span&gt;${olHtml}&lt;/span&gt;
110    &lt;/div&gt;`    
111  }).join('');
112}
113
114$("body").append(htmlFromData(array_of_objects));
1var array_of_objects = [{
2  "name": "john",
3  "job": "pilot",
4  "email": "johnpilot@gmail.com",
5  "ol": [{
6    "li": 6,
7    "title": "6 li's"
8  }, {
9    "li": 2,
10    "title": "2 li's"
11  }, {
12    "li": 5,
13    "title": "5 li's"
14  }]
15}, {
16  "name": "mark",
17  "job": "engineer",
18  "email": "markengineer@gmail.com",
19  "ol": [{
20    "li": 2,
21    "title": "2 li's"
22  }, {
23    "li": 7,
24    "title": "7 li's"
25  }, {
26    "li": 2,
27    "title": "2 li's"
28  }, {
29    "li": 1,
30    "title": "1 li's"
31  }]
32}, {
33  "name": "george",
34  "job": "chef",
35  "email": "georgechef@gmail.com",
36  "ol": [{
37    "li": 1,
38    "title": "1 li's"
39  }, {
40    "li": 3,
41    "title": "3 li's"
42  }, {
43    "li": 4,
44    "title": "4 li's"
45  }, {
46    "li": 3,
47    "title": "3 li's"
48  }, {
49    "li": 3,
50    "title": "3 li's"
51  }]
52}]
53
54function iterate(arr) {
55  arr.forEach(i =&gt; {
56    var name = i.name;
57    var job = i.job;
58    var email = i.email;
59    var ol_li = i.ol_li;
60    var str = `&lt;div&gt;
61    &lt;span&gt;${name}&lt;/span&gt;
62    &lt;span&gt;${job}&lt;/span&gt;
63    &lt;span&gt;${email}&lt;/span&gt;
64    &lt;span&gt;ol's should be placed here&lt;/span&gt;
65    &lt;/div&gt;`
66    $("body").append(str);
67  })
68}
69
70iterate(array_of_objects)div {
71  display: flex;
72  flex-direction: column;
73  border: thin solid black;
74  margin: 0.4em;
75  padding: 0.2em;
76}
77
78span:not(:nth-child(4)) {
79  display: flex;
80  flex-direction: column;
81  border: thin solid red;
82  margin: 0.2em;
83  padding: 0.2em;
84}
85
86span:nth-child(4) {
87  display: flex;
88  flex-direction: row;
89  margin: 0.4em;
90  padding: 0.2em;
91}
92
93ol {
94  border: thin solid blue;
95  margin: 0.2em;
96}
97
98li {
99  margin: 0.2em;
100}&lt;script src="https://code.jquery.com/jquery-3.6.0.js"&gt;&lt;/script&gt;var array_of_objects = [{name:"john",job:"pilot",email:"johnpilot@gmail.com",ol:[{li:6,title:"6 li's"},{li:2,title:"2 li's"},{li:5,title:"5 li's"}]},{name:"mark",job:"engineer",email:"markengineer@gmail.com",ol:[{li:2,title:"2 li's"},{li:7,title:"7 li's"},{li:2,title:"2 li's"},{li:1,title:"1 li's"}]},{name:"george",job:"chef",email:"georgechef@gmail.com",ol:[{li:1,title:"1 li's"},{li:3,title:"3 li's"},{li:4,title:"4 li's"},{li:3,title:"3 li's"},{li:3,title:"3 li's"}]}];
101
102function htmlFromData(arr) {
103  return arr.map(obj =&gt; {
104    let olHtml = obj.ol.map(ol =&gt; `&lt;ol&gt;${(new Array(ol.li)).fill(`&lt;li&gt;${ol.title}&lt;/li&gt;`).join('')}&lt;/ol&gt;`).join('');
105    return `&lt;div&gt;
106      &lt;span&gt;${obj.name}&lt;/span&gt;
107      &lt;span&gt;${obj.job}&lt;/span&gt;
108      &lt;span&gt;${obj.email}&lt;/span&gt;
109      &lt;span&gt;${olHtml}&lt;/span&gt;
110    &lt;/div&gt;`    
111  }).join('');
112}
113
114$("body").append(htmlFromData(array_of_objects));div {
115  display: flex;
116  flex-direction: column;
117  border: thin solid black;
118  margin: 0.4em;
119  padding: 0.2em;
120}
121
122span:not(:nth-child(4)) {
123  display: flex;
124  flex-direction: column;
125  border: thin solid red;
126  margin: 0.2em;
127  padding: 0.2em;
128}
129
130span:nth-child(4) {
131  display: flex;
132  flex-direction: row;
133  margin: 0.4em;
134  padding: 0.2em;
135}
136
137ol {
138  border: thin solid blue;
139  margin: 0.2em;
140}
141
142li {
143  margin: 0.2em;
144}
1var array_of_objects = [{
2  "name": "john",
3  "job": "pilot",
4  "email": "johnpilot@gmail.com",
5  "ol": [{
6    "li": 6,
7    "title": "6 li's"
8  }, {
9    "li": 2,
10    "title": "2 li's"
11  }, {
12    "li": 5,
13    "title": "5 li's"
14  }]
15}, {
16  "name": "mark",
17  "job": "engineer",
18  "email": "markengineer@gmail.com",
19  "ol": [{
20    "li": 2,
21    "title": "2 li's"
22  }, {
23    "li": 7,
24    "title": "7 li's"
25  }, {
26    "li": 2,
27    "title": "2 li's"
28  }, {
29    "li": 1,
30    "title": "1 li's"
31  }]
32}, {
33  "name": "george",
34  "job": "chef",
35  "email": "georgechef@gmail.com",
36  "ol": [{
37    "li": 1,
38    "title": "1 li's"
39  }, {
40    "li": 3,
41    "title": "3 li's"
42  }, {
43    "li": 4,
44    "title": "4 li's"
45  }, {
46    "li": 3,
47    "title": "3 li's"
48  }, {
49    "li": 3,
50    "title": "3 li's"
51  }]
52}]
53
54function iterate(arr) {
55  arr.forEach(i =&gt; {
56    var name = i.name;
57    var job = i.job;
58    var email = i.email;
59    var ol_li = i.ol_li;
60    var str = `&lt;div&gt;
61    &lt;span&gt;${name}&lt;/span&gt;
62    &lt;span&gt;${job}&lt;/span&gt;
63    &lt;span&gt;${email}&lt;/span&gt;
64    &lt;span&gt;ol's should be placed here&lt;/span&gt;
65    &lt;/div&gt;`
66    $("body").append(str);
67  })
68}
69
70iterate(array_of_objects)div {
71  display: flex;
72  flex-direction: column;
73  border: thin solid black;
74  margin: 0.4em;
75  padding: 0.2em;
76}
77
78span:not(:nth-child(4)) {
79  display: flex;
80  flex-direction: column;
81  border: thin solid red;
82  margin: 0.2em;
83  padding: 0.2em;
84}
85
86span:nth-child(4) {
87  display: flex;
88  flex-direction: row;
89  margin: 0.4em;
90  padding: 0.2em;
91}
92
93ol {
94  border: thin solid blue;
95  margin: 0.2em;
96}
97
98li {
99  margin: 0.2em;
100}&lt;script src="https://code.jquery.com/jquery-3.6.0.js"&gt;&lt;/script&gt;var array_of_objects = [{name:"john",job:"pilot",email:"johnpilot@gmail.com",ol:[{li:6,title:"6 li's"},{li:2,title:"2 li's"},{li:5,title:"5 li's"}]},{name:"mark",job:"engineer",email:"markengineer@gmail.com",ol:[{li:2,title:"2 li's"},{li:7,title:"7 li's"},{li:2,title:"2 li's"},{li:1,title:"1 li's"}]},{name:"george",job:"chef",email:"georgechef@gmail.com",ol:[{li:1,title:"1 li's"},{li:3,title:"3 li's"},{li:4,title:"4 li's"},{li:3,title:"3 li's"},{li:3,title:"3 li's"}]}];
101
102function htmlFromData(arr) {
103  return arr.map(obj =&gt; {
104    let olHtml = obj.ol.map(ol =&gt; `&lt;ol&gt;${(new Array(ol.li)).fill(`&lt;li&gt;${ol.title}&lt;/li&gt;`).join('')}&lt;/ol&gt;`).join('');
105    return `&lt;div&gt;
106      &lt;span&gt;${obj.name}&lt;/span&gt;
107      &lt;span&gt;${obj.job}&lt;/span&gt;
108      &lt;span&gt;${obj.email}&lt;/span&gt;
109      &lt;span&gt;${olHtml}&lt;/span&gt;
110    &lt;/div&gt;`    
111  }).join('');
112}
113
114$("body").append(htmlFromData(array_of_objects));div {
115  display: flex;
116  flex-direction: column;
117  border: thin solid black;
118  margin: 0.4em;
119  padding: 0.2em;
120}
121
122span:not(:nth-child(4)) {
123  display: flex;
124  flex-direction: column;
125  border: thin solid red;
126  margin: 0.2em;
127  padding: 0.2em;
128}
129
130span:nth-child(4) {
131  display: flex;
132  flex-direction: row;
133  margin: 0.4em;
134  padding: 0.2em;
135}
136
137ol {
138  border: thin solid blue;
139  margin: 0.2em;
140}
141
142li {
143  margin: 0.2em;
144}&lt;script src="https://code.jquery.com/jquery-3.6.0.js"&gt;&lt;/script&gt;

Source https://stackoverflow.com/questions/69446880

QUESTION

Same class but only trigger function for the one selected

Asked 2021-Oct-01 at 22:17

Hello everyone I'm having a hard time trying to understand how to make this work.

I have 8 different divs, each one with an img used as button and same class (tm-img) and hidden divs with additional info. What I want is to have displayed only the img at the beginnig and when the user clicks one of the 8 images depending on the one they clicked the hidden divs from that image show. (Whats happening now is tha if I click on one image all hidden divs from all images show not just the one I clicked)

1&lt;div class=&quot;tm-full-container&quot;&gt;
2                &lt;div class=&quot;team-member card-container blue-card&quot;&gt;
3                    &lt;img class='tm-img' onclick='run()' src=&quot;/team_1.png&quot; alt=&quot;&quot;&gt;
4                    &lt;h5 class=&quot;tm-title&quot;&gt;Chef&lt;/h6&gt;
5                
6                &lt;div class=&quot;tm-info&quot;&gt;
7                    &lt;p class=&quot;tm-name&quot;&gt;Rick Jones&lt;/p&gt;
8                    &lt;p class=&quot;tm-position&quot;&gt;Chef&lt;/p&gt;
9                &lt;/div&gt;
10
11                &lt;/div&gt;
12
13                &lt;div class=&quot;tm-full-info&quot;&gt;
14                    &lt;p&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at 
15                        ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia 
16                        tempora temporibus perspiciatis? Assumenda?&lt;/p&gt;
17                &lt;/div&gt;
18            &lt;/div&gt;
19
20&lt;script&gt;
21     function run(){
22      
23      $('.tm-info').toggle();
24      $('.tm-full-info').toggle();
25      $('.tm-title').toggle();
26    
27     }&lt;/script&gt;
28

All other 7 divs look the same with different image and name (Rick).

Thanks in advance.

Example

ANSWER

Answered 2021-Oct-01 at 22:17

You can do something like in below snippet . Use the this keyword so that the clicked element is triggered not all .

You can also for loop to run through all tags and trigger(toggle) clicked event

1&lt;div class=&quot;tm-full-container&quot;&gt;
2                &lt;div class=&quot;team-member card-container blue-card&quot;&gt;
3                    &lt;img class='tm-img' onclick='run()' src=&quot;/team_1.png&quot; alt=&quot;&quot;&gt;
4                    &lt;h5 class=&quot;tm-title&quot;&gt;Chef&lt;/h6&gt;
5                
6                &lt;div class=&quot;tm-info&quot;&gt;
7                    &lt;p class=&quot;tm-name&quot;&gt;Rick Jones&lt;/p&gt;
8                    &lt;p class=&quot;tm-position&quot;&gt;Chef&lt;/p&gt;
9                &lt;/div&gt;
10
11                &lt;/div&gt;
12
13                &lt;div class=&quot;tm-full-info&quot;&gt;
14                    &lt;p&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at 
15                        ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia 
16                        tempora temporibus perspiciatis? Assumenda?&lt;/p&gt;
17                &lt;/div&gt;
18            &lt;/div&gt;
19
20&lt;script&gt;
21     function run(){
22      
23      $('.tm-info').toggle();
24      $('.tm-full-info').toggle();
25      $('.tm-title').toggle();
26    
27     }&lt;/script&gt;
28function funcRun(show) {
29  var showInfo = show.querySelector(".tm-tag-Info");
30  showInfo.classList.toggle("tm-tag-Info-Show")
31}
1&lt;div class=&quot;tm-full-container&quot;&gt;
2                &lt;div class=&quot;team-member card-container blue-card&quot;&gt;
3                    &lt;img class='tm-img' onclick='run()' src=&quot;/team_1.png&quot; alt=&quot;&quot;&gt;
4                    &lt;h5 class=&quot;tm-title&quot;&gt;Chef&lt;/h6&gt;
5                
6                &lt;div class=&quot;tm-info&quot;&gt;
7                    &lt;p class=&quot;tm-name&quot;&gt;Rick Jones&lt;/p&gt;
8                    &lt;p class=&quot;tm-position&quot;&gt;Chef&lt;/p&gt;
9                &lt;/div&gt;
10
11                &lt;/div&gt;
12
13                &lt;div class=&quot;tm-full-info&quot;&gt;
14                    &lt;p&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at 
15                        ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia 
16                        tempora temporibus perspiciatis? Assumenda?&lt;/p&gt;
17                &lt;/div&gt;
18            &lt;/div&gt;
19
20&lt;script&gt;
21     function run(){
22      
23      $('.tm-info').toggle();
24      $('.tm-full-info').toggle();
25      $('.tm-title').toggle();
26    
27     }&lt;/script&gt;
28function funcRun(show) {
29  var showInfo = show.querySelector(".tm-tag-Info");
30  showInfo.classList.toggle("tm-tag-Info-Show")
31}.tm-tag-Info {
32  display: none
33}
34
35.tm-tag-Info-Show {
36  display: block
37}
38
39.tm-tag {
40  border: 2px solid red;
41  margin: 10px;
42  padding: 10px;
43}
44
45.imageFun {
46  width: 100px;
47  height: 100px
48}
1&lt;div class=&quot;tm-full-container&quot;&gt;
2                &lt;div class=&quot;team-member card-container blue-card&quot;&gt;
3                    &lt;img class='tm-img' onclick='run()' src=&quot;/team_1.png&quot; alt=&quot;&quot;&gt;
4                    &lt;h5 class=&quot;tm-title&quot;&gt;Chef&lt;/h6&gt;
5                
6                &lt;div class=&quot;tm-info&quot;&gt;
7                    &lt;p class=&quot;tm-name&quot;&gt;Rick Jones&lt;/p&gt;
8                    &lt;p class=&quot;tm-position&quot;&gt;Chef&lt;/p&gt;
9                &lt;/div&gt;
10
11                &lt;/div&gt;
12
13                &lt;div class=&quot;tm-full-info&quot;&gt;
14                    &lt;p&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at 
15                        ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia 
16                        tempora temporibus perspiciatis? Assumenda?&lt;/p&gt;
17                &lt;/div&gt;
18            &lt;/div&gt;
19
20&lt;script&gt;
21     function run(){
22      
23      $('.tm-info').toggle();
24      $('.tm-full-info').toggle();
25      $('.tm-title').toggle();
26    
27     }&lt;/script&gt;
28function funcRun(show) {
29  var showInfo = show.querySelector(".tm-tag-Info");
30  showInfo.classList.toggle("tm-tag-Info-Show")
31}.tm-tag-Info {
32  display: none
33}
34
35.tm-tag-Info-Show {
36  display: block
37}
38
39.tm-tag {
40  border: 2px solid red;
41  margin: 10px;
42  padding: 10px;
43}
44
45.imageFun {
46  width: 100px;
47  height: 100px
48}&lt;div class="tm-tag" onclick="funcRun(this)"&gt;
49  &lt;h4 class="tm-tag-Hed"&gt;CV for BV&lt;/h4&gt;
50  &lt;span class="tm-tag-Info"&gt;&lt;img alt="imageFun" src="https://www.hdnicewallpapers.com/Walls/Big/Rainbow/Rainbow_on_Mountain_HD_Image.jpg" class="imageFun"&gt;&lt;br&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia tempora temporibus perspiciatis? Assumenda?&lt;/span&gt;
51&lt;/div&gt;
52
53&lt;div class="tm-tag" onclick="funcRun(this)"&gt;
54  &lt;h4 class="tm-tag-Hed"&gt;CV for BV&lt;/h4&gt;
55  &lt;span class="tm-tag-Info"&gt;&lt;img alt="imageFun" src="https://www.hdnicewallpapers.com/Walls/Big/Rainbow/Rainbow_on_Mountain_HD_Image.jpg" class="imageFun"&gt;&lt;br&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia tempora temporibus perspiciatis? Assumenda?&lt;/span&gt;
56&lt;/div&gt;
57
58&lt;div class="tm-tag" onclick="funcRun(this)"&gt;
59  &lt;h4 class="tm-tag-Hed"&gt;CV for BV&lt;/h4&gt;
60  &lt;span class="tm-tag-Info"&gt;&lt;img alt="imageFun" src="https://www.hdnicewallpapers.com/Walls/Big/Rainbow/Rainbow_on_Mountain_HD_Image.jpg" class="imageFun"&gt;&lt;br&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia tempora temporibus perspiciatis? Assumenda?&lt;/span&gt;
61&lt;/div&gt;

Source https://stackoverflow.com/questions/69412110

QUESTION

symbolic link not working with chef recipe

Asked 2021-Sep-04 at 04:02

I want to create symbolic link only if its not present

I have written below recipe

1link '/home/user1/veera' do
2    to '/usr/local/veera-10.0'
3    only_if {test -L /home/user1/veera}
4end
5
6

I tried below condition in recipe

1link '/home/user1/veera' do
2    to '/usr/local/veera-10.0'
3    only_if {test -L /home/user1/veera}
4end
5
6only_if {test -L /home/user1/veera}
7

But it updates the symlink next time when chef runs next time(if it its changed).But i don't want that.

I want to skip this if symlink exist and create only when symlink it doesn't exists.

Also tried this

1link '/home/user1/veera' do
2    to '/usr/local/veera-10.0'
3    only_if {test -L /home/user1/veera}
4end
5
6only_if {test -L /home/user1/veera}
7link '/home/user1/veera' do
8    to '/usr/local/veera-10.0'
9    not_if { File.symlink?('/home/user1/veera') }
10end
11

But its still updating the symlink when changed on next chef run

ANSWER

Answered 2021-Sep-04 at 04:02

The link resource is idempotent in nature, and shouldn't change if the link is already present.

However, for some reason if you want to skip the step, we can use symlink? method from Ruby's File class. This method returns true/false based on whether the target path is a link or not.

Like:

1link '/home/user1/veera' do
2    to '/usr/local/veera-10.0'
3    only_if {test -L /home/user1/veera}
4end
5
6only_if {test -L /home/user1/veera}
7link '/home/user1/veera' do
8    to '/usr/local/veera-10.0'
9    not_if { File.symlink?('/home/user1/veera') }
10end
11File.symlink?('/home/user1/veera')
12

Another potential issue that I noticed, and corrected in the below example is your source path - usr/local/veera-10.0 will most likely be relative to your current working directory. To be sure, use /usr/local/veera-10.0.

So in recipe:

1link '/home/user1/veera' do
2    to '/usr/local/veera-10.0'
3    only_if {test -L /home/user1/veera}
4end
5
6only_if {test -L /home/user1/veera}
7link '/home/user1/veera' do
8    to '/usr/local/veera-10.0'
9    not_if { File.symlink?('/home/user1/veera') }
10end
11File.symlink?('/home/user1/veera')
12link '/home/user1/veera' do
13  to '/usr/local/veera-10.0'
14  not_if { File.symlink?('/home/user1/veera') }
15end
16

Update

As @lamont suggested in his comment, try using the File.exist? test as you want to skip the step if this path exists (whether its a file, dir, or symlink).

1link '/home/user1/veera' do
2    to '/usr/local/veera-10.0'
3    only_if {test -L /home/user1/veera}
4end
5
6only_if {test -L /home/user1/veera}
7link '/home/user1/veera' do
8    to '/usr/local/veera-10.0'
9    not_if { File.symlink?('/home/user1/veera') }
10end
11File.symlink?('/home/user1/veera')
12link '/home/user1/veera' do
13  to '/usr/local/veera-10.0'
14  not_if { File.symlink?('/home/user1/veera') }
15end
16not_if { File.exist?('/home/user1/veera') }
17

Source https://stackoverflow.com/questions/69028264

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Chef

Tutorials and Learning Resources are not available at this moment for Chef

Share this Page

share link

Get latest updates on Chef