Snippets Collections
job = {
	'title': title,
	'company': company,
	'salary': salary,
	'summary': summary
}

joblist.append(job)

print(*joblist, sep='\n')
#include<iostream>
using namespace std;

typedef struct NODE{
    int data;
    NODE *next;
}NODE;
class LIST{
    NODE *head;
    public:
    LIST();
    LIST& operator+(int);
    LIST& operator-(int);
    bool operator==(LIST&);
    LIST& operator++(int);
    LIST& operator--(int);
    friend ostream& operator<<(ostream&,LIST&);
    ~LIST();
};
int main(){
    LIST l;
    int choice,ele;
    while(1){
        cout<<"1. L = L + ele\n";
        cout<<"2. L = L - ele\n";
        cout<<"3. L = L++ \n";
        cout<<"4. L = L--\n";
        cout<<"-1: Exit\n";
        cin>>choice;
        switch(choice){
            case 1: 
                    cout<<"Enter the value of the element\n";
                    cin>>ele;
                    l = l + ele;
            break;
            case 2:
                    cout<<"Enter the value of the element\n";
                    cin>>ele;
                    l = l - ele;
            break;
            case 3:
                    l = l++;
            break;
            case 4: 
                    l = l--;
            break;
            case -1:
                    goto out;
            default:
                    cout<<"Invalid entry\n";
        }
        cout<<"List: "<<l;
    }
    out:
    return 0;
}

LIST::LIST(){
    head=NULL;
}
bool ispresent(NODE* chain,NODE *end,int key){
    NODE *temp = chain;
    while(temp!=end){
        if(temp->data==key) return true;
        temp = temp->next;
    }
    if(end!=NULL) return end->data == key ? 1:0;
    return false;
}
LIST& LIST::operator--(int){
    NODE *distinct_head = NULL;
    NODE *distinct_connect = NULL;
    NODE *duplicate_head=NULL;
    NODE *duplicate_connect = NULL;
    NODE *temp = head;
    while(temp){
        if(ispresent(distinct_head,distinct_connect,temp->data)){
            if(!duplicate_connect) duplicate_head = temp;
            else duplicate_connect->next = temp;
            duplicate_connect = temp;
        }
        else{
            if(!distinct_connect) distinct_head = temp;
            else distinct_connect->next = temp;
            distinct_connect = temp;
        }
        NODE *store = temp->next;
        temp->next = NULL;
        temp = store;
    }
    distinct_connect->next  = duplicate_head;
    head = distinct_head;
    return *this;
}
LIST& LIST::operator++(int){
    NODE *temp = head;
    while(temp){
        temp->data = temp->data +1;
        temp=temp->next;
    }
    return *this;
}
bool LIST::operator==(LIST &l2){
    NODE *temp1 = head;
    NODE *temp2 = l2.head;
    if(temp1 == NULL && temp2 == NULL) return true;
    if(temp1==NULL || temp2==NULL) return false;
    while(temp1 && temp2){
        if(temp1->data!=temp2->data) return false;
        temp1 = temp1->next;
        temp2 = temp2->next;
    }
    return temp1 || temp2 ? 0:1;
}
LIST& LIST::operator-(int element){
    NODE *temp = head;
    NODE *prev= NULL;
    while(temp){
        if(temp->data==element){
            if(!prev) head=head->next;
            else prev->next = temp->next;
            delete temp;
            return *this;
        }
        prev=temp;
        temp=temp->next;
    }
    return *this;
}
LIST& LIST::operator+(int element){
    NODE *current = new NODE;
    current->data = element;
    current->next = NULL;
    NODE *temp = head;
    if(!temp){
        head = current;
        return *this;
    }
    while(temp->next){
        temp = temp->next;
    }
    temp->next = current;
    return *this;
}
ostream& operator<<(ostream& print,LIST &l){
    NODE *temp= l.head;
    while(temp){
        print<<temp->data<<" ";
        temp = temp->next;
    }
    print<<endl;
    return print;
}
LIST::~LIST(){
    NODE *temp = head;
    while(temp){
        NODE *store = temp->next;
        delete temp;
        temp = store;
    }
}
#You can do it using GloVe library:

#Install it: 

!pip install glove_python

from glove import Corpus, Glove

#Creating a corpus object
corpus = Corpus() 

#Training the corpus to generate the co-occurrence matrix which is used in GloVe
corpus.fit(lines, window=10)

glove = Glove(no_components=5, learning_rate=0.05) 
glove.fit(corpus.matrix, epochs=30, no_threads=4, verbose=True)
glove.add_dictionary(corpus.dictionary)
glove.save('glove.model')
 Save

 
 
 #for Fasttext
 from gensim.models import FastText
from gensim.test.utils import common_texts  # some example sentences
>>>
print(common_texts[0])
['human', 'interface', 'computer']
print(len(common_texts))
9
model = FastText(vector_size=4, window=3, min_count=1)  # instantiate
model.build_vocab(sentences=common_texts)
model.train(sentences=common_texts, total_examples=len(common_texts), epochs=10)  # train
model2 = FastText(vector_size=4, window=3, min_count=1, sentences=common_texts, epochs=10)

import numpy as np
>>>
np.allclose(model.wv['computer'], model2.wv['computer'])
True


from gensim.test.utils import datapath
>>>
corpus_file = datapath('lee_background.cor')  # absolute path to corpus
model3 = FastText(vector_size=4, window=3, min_count=1)
model3.build_vocab(corpus_file=corpus_file)  # scan over corpus to build the vocabulary
>>>
total_words = model3.corpus_total_words  # number of words in the corpus
model3.train(corpus_file=corpus_file, total_words=total_words, epochs=5)


from gensim.utils import tokenize
from gensim import utils
>>>
>>>
class MyIter:
    def __iter__(self):
        path = datapath('crime-and-punishment.txt')
        with utils.open(path, 'r', encoding='utf-8') as fin:
            for line in fin:
                yield list(tokenize(line))
>>>
>>>
model4 = FastText(vector_size=4, window=3, min_count=1)
model4.build_vocab(sentences=MyIter())
total_examples = model4.corpus_count
model4.train(sentences=MyIter(), total_examples=total_examples, epochs=5)
from gensim.test.utils import get_tmpfile
>>>
fname = get_tmpfile("fasttext.model")
>>>
model.save(fname)
model = FastText.load(fname)


# https://radimrehurek.com/gensim/models/fasttext.html
In [1]: df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]})
        df

Out[1]: 
   a  b
0  A  1
1  A  2
2  B  5
3  B  5
4  B  4
5  C  6

In [2]: df.groupby('a')['b'].apply(list)
Out[2]: 
a
A       [1, 2]
B    [5, 5, 4]
C          [6]
Name: b, dtype: object

In [3]: df1 = df.groupby('a')['b'].apply(list).reset_index(name='new')
        df1
Out[3]: 
   a        new
0  A     [1, 2]
1  B  [5, 5, 4]
2  C        [6]
colors = ['red', 'green', 'blue']
for idx, color in enumerate(colors):
	print(idx, color)
> 0 red
> 1 green
> 2 blue
JavaScript

for (let i=0; i < arrayName.length; i++){
  console.log(arrayName[i])
}

i.e.):

movies = ['legally blonde', 'Ms. & Ms. Smith', 'The Incredibles'];

for (let i=0; i < movies.length; i++){
  console.log(movies[i])
}

Python

for singular_array_name in array_name_pluralized:
	print(singular_array_name)

i.e.):

movies = ['legally blonde', 'Ms. & Ms. Smith', 'The Incredibles']

for movie in movies:
	print(movie)
@mixin auto-numbers($numbered-element, $sep, $counter: item, $nested-parent: false ){
    $sel: ();
    @if $nested-parent {
        $sel: append($sel, unquote($nested-parent));

        #{$nested-parent}{
            list-style: none;
            margin-left: 0;
        }
    }
    $sel: append($sel, unquote('&'), comma);

    #{$sel}{
        counter-reset: #{$counter};
        > #{$numbered-element}{
            &:before{
                counter-increment: #{$counter};
                content: if($nested-parent, counters(#{$counter}, "#{$sep} ") "#{$sep} ", counter(#{$counter}) "#{$sep} ") ;
            }
        }
    }
}
  .rounded-list a{
    position: relative;
    display: block;
    padding: .4em .4em .4em 2em;
    *padding: .4em;
    margin: .5em 0;
    background: #ddd;
    color: #444;
    text-decoration: none;
    border-radius: .3em;
    transition: all .3s ease-out;
  }

  .rounded-list a:hover{
    background: #eee;
  }

  .rounded-list a:hover:before{
    transform: rotate(360deg);
  }

  .rounded-list a:before{
    content: counter(li);
    counter-increment: li;
    position: absolute;
    left: -1.3em;
    top: 50%;
    margin-top: -1.3em;
    background: #87ceeb;
    height: 2em;
    width: 2em;
    line-height: 2em;
    border: .3em solid #fff;
    text-align: center;
    font-weight: bold;
    border-radius: 2em;
    transition: all .3s ease-out;
  }
# numpy and matplotlib imported, seed set

# Simulate random walk 500 times
all_walks = []
for i in range(500) :
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)
        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)
        if np.random.rand() <= 0.001 :
            step = 0
        random_walk.append(step)
    all_walks.append(random_walk)

# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))

# Select last row from np_aw_t: ends
ends = np_aw_t[-1, :]

# Plot histogram of ends, display plot
plt.hist(ends)
plt.show()
# Numpy is imported; seed is set

# Initialize all_walks (don't change this line)
all_walks = []

# Simulate random walk 10 times
for i in range(10):

    # Code from before
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)

        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)
        random_walk.append(step)

    # Append random_walk to all_walks
    all_walks.append(random_walk)

# Print all_walks
print(all_walks)


#####################################################################
# numpy and matplotlib imported, seed set

# Simulate random walk 250 times
all_walks = []
for i in range(250) :
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)
        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)

        # Implement clumsiness
        if np.random.rand() <= 0.001 :
            step = 0

        random_walk.append(step)
    all_walks.append(random_walk)

# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))
plt.plot(np_aw_t)
plt.show()


# Numpy is imported, seed is set

# Initialization
random_walk = [0]

for x in range(100) :
    step = random_walk[-1]
    dice = np.random.randint(1,7)

    if dice <= 2:
        step = max(0, step - 1)
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    random_walk.append(step)

# Import matplotlib.pyplot as plt
import matplotlib.pyplot as plt

# Plot random_walk
plt.plot(random_walk)

# Show the plot
plt.show()
# Numpy is imported, seed is set

# Initialize random_walk
random_walk = [0]

# Complete the ___
for x in range(100) :
    # Set step: last element in random_walk
   
    step = random_walk[-1]

    # Roll the dice
    dice = np.random.randint(1,7)

    # Determine next step
    if dice <= 2:
        step = step - 1
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    # append next_step to random_walk
    random_walk.append(step)

# Print random_walk
print(random_walk)

#Not Going below zero
# Numpy is imported, seed is set

# Initialize random_walk
random_walk = [0]

for x in range(100) :
    step = random_walk[-1]
    dice = np.random.randint(1,7)

    if dice <= 2:
        # Replace below: use max to make sure step can't go below 0
        step = max(0, step - 1)
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    random_walk.append(step)

print(random_walk)
# Numpy is imported, seed is set

# Starting step
step = 50
# Roll the dice
dice = np.random.randint(1,7)
# Finish the control construct
if dice <= 2 :
    step = step - 1
elif dice <= 5 :
    step = step + 1
else:
    step = step + np.random.randint(1,7)

# Print out dice and step
print(dice)
print(step)
# Import numpy as np
import numpy as np

# Set the seed
np.random.seed(123)

# Generate and print random float
print(np.random.rand())

#Roll The Dice
# Import numpy and set seed
import numpy as np
np.random.seed(123)

# Use randint() to simulate a dice
print(np.random.randint(1,7))
# Use randint() again
print(np.random.randint(1,7))


# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Use .apply(str.upper)


cars['COUNTRY'] = cars['country'].apply(str.upper)
print(cars)
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Adapt for loop
for lab, row in cars.iterrows() :
    print(lab + ": " + str(row['cars_per_cap']))

#Something new

# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Code for loop that adds COUNTRY column
for lab, row in cars.iterrows():
    cars.loc[lab,'COUNTRY'] = row['country'].upper()


# Print cars
print(cars)
#Iterating over a Pandas DataFrame is typically done with the iterrows()
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Iterate over rows of cars
for lab,row in cars.iterrows():
    print(lab)
    print(row)
# Import numpy as np

import numpy as np
#for x in my_array : #in 1D Numpy array
#for x in np.nditer(my_array) : #for 2D Numpy array

# For loop over np_height

for x in np_height:
    print(str(x) + " inches")

# For loop over np_baseball
for x in (np.nditer(np_baseball)):
    print(x)
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin',
          'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }
          
# Iterate over europe
for key, value in europe.items() :
    print('the capital of ' + str(key) + ' is ' + str(value))
# house list of lists
house = [["hallway", 11.25], 
         ["kitchen", 18.0], 
         ["living room", 20.0], 
         ["bedroom", 10.75], 
         ["bathroom", 9.50]]
         
# Build a for loop from scratch
for x in house :
    #x[0] to access name of room
    #x[1] to access area in sqm
    print('the ' + x[0] + " is " + str(x[1]) + " sqm")
Row {
    Button(onClick = {
        coroutineScope.launch {
            // 0 is the first item index
            scrollState.animateScrollToItem(0)
        }
    }) {
        Text("Scroll to the top")
    }

    Button(onClick = {
        coroutineScope.launch {
            // listSize - 1 is the last index of the list
            scrollState.animateScrollToItem(listSize - 1)
        }
    }) {
        Text("Scroll to the end")
    }
}
fruit = {
  "elderberries": 1,
  "figs": 1,
  "apples": 2,
  "durians": 3,
  "bananas": 5,
  "cherries": 8,
  "grapes": 13
}

table_data = []
for k, v in fruit.items():
   table_data.append([k, v])
PSA: How to View Variables in Lists
by 
Bradford Shelley
 Forum Level 2
created 4y ago (edited 3y ago ) in Developer Community
After having to play around with variables quite a bit in a recent project, I thought I'd share how to display variables on a list of Requested Items / Catalog Tasks. This applies to lists and related lists, as reports have their own method of displaying variables. Important note: This was performed on Fuji. Your experience may differ on older versions of ServiceNow.

Step 1 Identify the variables you'd like to display on your list, then copy the sys_id for each variable. This is as simple as heading to the Catalog Item, and jumping into the variable(s) in question. We'll need the sys_id to add the column into the list.

Step 2 Head over to System UI -> Lists

Step 3 Identify the list you'd like to display the variable(s) on. We're looking for one of two things here. Either the name of the view of the list you'd like to include the variable(s) on (I highly recommend creating a new view instead of using the Default view for this, as most likely the variables will apply to certain catalog items instead of every single one), or for a related list look at the Parent and Relationship columns for the table and name of the tab for the related list. Head into the list when you've found it.



Step 4 Create a new List Element(s) from the related list at, using "variables.sys_id" (no quotes) in the actual Element field on the List Element form. Create a new List Element for each variable you wish to add.



Step 5 Head over to the list where variables were just added. They won't show up immediately, so don't panic. Edit the list layout, and move around the variables to the spots you'd like them in the list (even if the position is already how you'd like it, move a variable one position up/down, then move it back and save). At this point, the variables should be visible!

Hope this helps at least one person out there. Take care!
# Python program to illustrate 
# Finding common member in list  
# using 'in' operator 
list1=[1,2,3,4,5] 
list2=[6,7,8,9] 
for item in list1: 
    if item in list2: 
        print("overlapping")       
else: 
    print("not overlapping") 
star

Sun May 15 2022 06:41:38 GMT+0000 (UTC) https://stackoverflow.com/questions/13443588/how-can-i-format-a-list-to-print-each-element-on-a-separate-line-in-python

#python #print #list #newline
star

Sat May 07 2022 12:46:49 GMT+0000 (UTC)

#c++ #list #oop
star

Thu Apr 21 2022 17:21:57 GMT+0000 (UTC) https://medium.com/analytics-vidhya/word-vectorization-using-glove-76919685ee0b

#pandas #list #group
star

Wed Apr 20 2022 18:10:53 GMT+0000 (UTC) https://stackoverflow.com/questions/22219004/how-to-group-dataframe-rows-into-list-in-pandas-groupby

#pandas #list #group
star

Wed Jan 05 2022 04:40:37 GMT+0000 (UTC) https://gabri.me/blog/sass-mixin-for-auto-numbering-with-css

#list #mixin
star

Sat Jan 01 2022 04:12:55 GMT+0000 (UTC) https://catalin.red/css3-ordered-list-styles/

#css #list
star

Fri Nov 26 2021 10:42:38 GMT+0000 (UTC)

#list #forloop #for #loop #dicegame
star

Fri Nov 26 2021 10:06:16 GMT+0000 (UTC)

#list #forloop #for #loop ##dictionary
star

Fri Nov 26 2021 09:45:49 GMT+0000 (UTC)

#list #forloop #for #loop ##dictionary
star

Sun Jun 20 2021 19:49:37 GMT+0000 (UTC) https://developer.android.com/courses/pathways/compose

#lazycolumn #list #jetpackcompose
star

Fri Oct 30 2020 20:19:26 GMT+0000 (UTC) https://www.geeksforgeeks.org/python-membership-identity-operators-not-not/

#python #in #list
star

Mon Mar 23 2020 07:13:49 GMT+0000 (UTC) https://www.30secondsofcode.org/python/s/max-by/

#python #python #math #list

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension