Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
13,300 | Given the following text description, write Python code to implement the functionality described.
Description:
Create a function that takes integers, floats, or strings representing
real numbers, and returns the larger variable in its given variable type.
Return None if the values are equal.
Note: If a ... | Python Code:
def compare_one(a, b):
temp_a, temp_b = a, b
if isinstance(temp_a, str): temp_a = temp_a.replace(',','.')
if isinstance(temp_b, str): temp_b = temp_b.replace(',','.')
if float(temp_a) == float(temp_b): return None
return a if float(temp_a) > float(temp_b) else b |
13,301 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 2
Examples and Exercises from Think Stats, 2nd Edition
http
Step1: Given a list of values, there are several ways to count the frequency of each value.
Step2: You can use a Python ... | Python Code:
import numpy as np
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(filename):
from urllib.request import urlretrieve
local, _ = urlretrieve(url, filename)
print("Downloaded " + local)
download("https://github.com/AllenDowney/Thi... |
13,302 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Hierarchical model for Rugby prediction
@Author
Step2: This is a Rugby prediction exercise. So we'll input some data
Step3: What do we want to infer?
We want to infer the latent paremete... | Python Code:
!date
import numpy as np
import pandas as pd
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
%matplotlib inline
import pymc3 as pm, theano.tensor as tt
Explanation: A Hierarchical model for Rugby prediction
@Author: Peadar Coyle
@email: peadarcoyle@googlemail.com
@dat... |
13,303 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sebastian Raschka, 2015
https
Step7: Overview
Please see Chapter 3 for more details on logistic regression.
Implementing logistic regression in Python
The following implementation is simila... | Python Code:
%load_ext watermark
%watermark -a '' -u -d -v -p numpy,pandas,matplotlib
# to install watermark just uncomment the following line:
#%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py
Explanation: Sebastian Raschka, 2015
https://github.com/1iyiwei/pyml
Python Machine Learning... |
13,304 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Problem: | Problem:
import numpy as np
a = np.array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
shift = 3
def solution(xs, n):
e = np.empty_like(xs)
if n >= 0:
e[:n] = np.nan
e[n:] = xs[:-n]
else:
e[n:] = np.nan
e[:n] = xs[-n:]
return e
result = solution(a, shift) |
13,305 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Project Euler
Step2: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected.
Step4: Now define a count_letters(n) that return... | Python Code:
def round_down(n):
s = str(n)
if n <= 20:
return n
elif n < 100:
return int(s[0] + '0'), int(s[1])
elif n<1000:
return int(s[0] + '00'),int(s[1]),int(s[2])
assert round_down(5) == 5
assert round_down(55) == (50,5)
assert round_down(222) == (200,2,2)
def numb... |
13,306 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Workshop 4 - Performance Metrics
In this workshop we study 2 performance metrics(Spread and Inter-Generational Distance) on GA optimizing the POM3 model.
Step2: To compute most measures, da... | Python Code:
%matplotlib inline
# All the imports
from __future__ import print_function, division
import pom3_ga, sys
import pickle
# TODO 1: Enter your unity ID here
__author__ = "<sbiswas4>"
Explanation: Workshop 4 - Performance Metrics
In this workshop we study 2 performance metrics(Spread and Inter-Generational Di... |
13,307 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Prepare the data
Step2: Build the artificial neural-network
Step3: Single layer forward propagation step
$$\boldsymbol{Z}^{[l]} = \boldsymbol{W}^{[l]} \cdot \boldsym... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
Explanation: <a href="https://colab.research.google.com/github/marxav/hello-world-python/blob/master/ann_101_numpy_step_by_step.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Import Pyt... |
13,308 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Some Useful Functions
Import the LArray library
Step1: with total
Add totals to one or several axes
Step2: See with_total for more details and examples.
where
The where function can be use... | Python Code:
from larray import *
# load 'demography_eurostat' dataset
demography_eurostat = load_example_data('demography_eurostat')
# extract the 'population' array from the dataset
population = demography_eurostat.population
population
Explanation: Some Useful Functions
Import the LArray library:
End of explanation... |
13,309 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In this notebook, we experiment with the optimal histogram algorithm. We will implement a simple version based on recursion and you will do the hard job of implementing a dynami... | Python Code:
LARGE_NUM = 1000000000.0
EMPTY = -1
DEBUG = 2
#DEBUG = 1
import numpy as np
def sse(arr):
if len(arr) == 0: # deal with arr == []
return 0.0
avg = np.average(arr)
val = sum( [(x-avg)*(x-avg) for x in arr] )
return val
def calc_depth(b):
return 5 - b
def v_opt_rec(xx, b):
min... |
13,310 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generate Region of Interests (ROI) labeled arrays for simple shapes
This example notebook explain the use of analysis module "skbeam/core/roi" https
Step1: Easily switch between interactive... | Python Code:
import skbeam.core.roi as roi
import skbeam.core.correlation as corr
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib.ticker import MaxNLocator
from matplotlib.colors import LogNorm
import xray_vision.mpl_plotting as mpl_plot
Explanation: Generate Region of Interests (R... |
13,311 | Given the following text description, write Python code to implement the functionality described.
Description:
Count of m digit integers that are divisible by an integer n
Returns count of m digit numbers having n as divisor ; Generating largest number of m digit ; Generating largest number of m - 1 digit ; returning n... | Python Code:
def findCount(m , n ) :
num1 = 0
for i in range(0 , m ) :
num1 =(num1 * 10 ) + 9
num2 = 0
for i in range(0 ,(m - 1 ) ) :
num2 =(num2 * 10 ) + 9
return int(( num1 / n ) -(num2 / n ) )
m = 2 ; n = 6
print(findCount(m , n ) )
|
13,312 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overview of Plotly for Python
Victoria Gregory
4/1/2016
What is Plotly?
plotly.js
Step1: Getting started
Easy to install
Step2: The following code will make a simple line and scatter plot
... | Python Code:
import plotly.tools as tls
tls.embed('https://plot.ly/~AnnaG/1/nfl-defensive-player-size-2013-season/')
tls.embed('https://plot.ly/~chris/7378/relative-number-of-311-complaints-by-city/')
tls.embed('https://plot.ly/~empet/2922/a-scoreboard-for-republican-candidates-as-of-august-17-2015-annotated-heatmap/')... |
13,313 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Idea
Using the vmstat command line utility to quickly determine the root cause of performance problems.
Step1: Data Input
In this version, we use a helper library that I've built to read in... | Python Code:
%less ../dataset/vmstat_loadtest.log
Explanation: Idea
Using the vmstat command line utility to quickly determine the root cause of performance problems.
End of explanation
from ozapfdis.linux import vmstat
stats = vmstat.read_logfile("../dataset/vmstat_loadtest.log")
stats.head()
Explanation: Data Input
I... |
13,314 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Pandas könyvtár
Mérési vagy szimulációs adatainkat gyakran célszerűbb a puszta számokat tartalmazó list vagy numpy.array adatszerkezet helyett a pandas könyvtár DataFrame osztályában tárol... | Python Code:
import pandas as pd
Explanation: A Pandas könyvtár
Mérési vagy szimulációs adatainkat gyakran célszerűbb a puszta számokat tartalmazó list vagy numpy.array adatszerkezet helyett a pandas könyvtár DataFrame osztályában tárolunk, ahol a számok mellett feliratozni is tudjuk a sorokat, illetve oszlopokat, ille... |
13,315 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting started with BigQuery ML
BigQuery ML enables users to create and execute machine learning models in BigQuery using SQL queries. The goal is to democratize machine learning by enablin... | Python Code:
from google.cloud import bigquery
client = bigquery.Client(location="US")
Explanation: Getting started with BigQuery ML
BigQuery ML enables users to create and execute machine learning models in BigQuery using SQL queries. The goal is to democratize machine learning by enabling SQL practitioners to build m... |
13,316 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Section 5.3
Step1: Load data
Step2: Number of reverts per page per bot pair
Group by language, page ID, and botpair_sorted
Grouping by these three columns creates a very simple and useful ... | Python Code:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import glob
import datetime
import pickle
%matplotlib inline
start = datetime.datetime.now()
Explanation: Section 5.3: Reverts per page (setup and exploratory)
This is a data analysis script used to produce finding... |
13,317 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kaggle Dogs and Cats Image Identification Problem
Achieved 98.9% accuracy - average of two test sets. Data taken from the 25k images of the Kaggle cats vs. dogs problem. 16k images were us... | Python Code:
%matplotlib inline
import os
import numpy as np
import matplotlib.pyplot as plt
from keras.applications import Xception
from keras.preprocessing.image import ImageDataGenerator
from keras import models
from keras import layers
from keras import optimizers
import tensorflow as tf
Explanation: Kaggle Dogs an... |
13,318 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parsl Bash Tutorial
This tutorial will show you how to run Bash scripts as Parsl apps.
Load parsl
Import parsl, and check the module version. This tutorial requires version 0.2.0 or above.
... | Python Code:
# Import Parsl
import parsl
from parsl import *
print(parsl.__version__) # The version should be v0.2.1+
Explanation: Parsl Bash Tutorial
This tutorial will show you how to run Bash scripts as Parsl apps.
Load parsl
Import parsl, and check the module version. This tutorial requires version 0.2.0 or above.... |
13,319 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Standard Python/Pandas Opening
Step1: Read in CSV File from Downloads
Step2: Code Below to Extract Input Sample Headers for Github
prod_df_example = prod_df.head(0)
cats_df_example = cats_... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Standard Python/Pandas Opening
End of explanation
prod_df = pd.read_csv('/home/saisons/Code/zazzle-product-analysis/inputs/cl_pr_lst.csv',
dtype={'category_id': np.str, 'product_id'... |
13,320 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plots of the mode of the mutation rate over time
Step1: The distribution of mutation rate modes as a function of population size
Step2: I need to remove the runs where the distribution of ... | Python Code:
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
plot_mu_trajectory(ax, mu_modes[25600][0][:2*10**6])
ax.set_xlabel('generation', fontsize=28);
ax.set_ylabel('mode of the mutation rate, $\mu_{mode}$', fontsize=28);
plt.savefig('mu_mode_trajectoryK25600.pdf')
fig = plt.figure(figsize=(10,10))
ax ... |
13,321 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get Data
Step1: Basic Market Map
Step2: GDP data with grouping by continent
World Bank national accounts data, and OECD National Accounts data files. (The World Bank
Step3: Setting the co... | Python Code:
data = pd.read_csv('../../data_files/country_codes.csv', index_col=[0])
country_codes = data.index.values
country_names = data['Name']
Explanation: Get Data
End of explanation
market_map = MarketMap(names=country_codes,
# basic data which needs to set for each map
... |
13,322 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Initial attemps at profiling had very confusing results; possibly because of module loading and i/o
Here, gypsy will be run and profiled on one plot, with no module loading/io recorded in pr... | Python Code:
%%bash
grep --colour -nr append ../gypsy/*.py
Explanation: Initial attemps at profiling had very confusing results; possibly because of module loading and i/o
Here, gypsy will be run and profiled on one plot, with no module loading/io recorded in profiling
Characterize what is happening
In several places, ... |
13,323 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MatPlotLib Basics
Draw a line graph
Step1: Mutiple Plots on One Graph
Step2: Save it to a File
Step3: Adjust the Axes
Step4: Add a Grid
Step5: Change Line Types and Colors
Step6: Label... | Python Code:
%matplotlib inline
from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-3, 3, 0.01)
plt.plot(x, norm.pdf(x))
plt.show()
Explanation: MatPlotLib Basics
Draw a line graph
End of explanation
plt.plot(x, norm.pdf(x))
plt.plot(x, norm.pdf(x, 1.0, 0.5))
plt.show()
Explan... |
13,324 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Assignment 1
The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later.
This notebook ... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import tarfile
from IPython.display import display, Image
from scipy import ndimage
from... |
13,325 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Raw Data Download
This scripts downloads all of the stage 1 raw data for the Kaggle Data Science Bowl 2017 (https
Step1: Defining function to download and extract all raw data
Step2: Grabb... | Python Code:
from urllib import request
import zipfile, io
from pathlib import Path
import os
import re
from pyunpack import Archive
Explanation: Raw Data Download
This scripts downloads all of the stage 1 raw data for the Kaggle Data Science Bowl 2017 (https://www.kaggle.com/c/data-science-bowl-2017)
We are pulling th... |
13,326 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Contents
We train an LSTM with gumbel-sigmoid gates on a toy language modelling problem.
Such LSTM can than be binarized to reach signifficantly greater speed.
Step1: Generate mtg cards
Reg... | Python Code:
%env THEANO_FLAGS="device=gpu3"
import numpy as np
import theano
import theano.tensor as T
import lasagne
import os
Explanation: Contents
We train an LSTM with gumbel-sigmoid gates on a toy language modelling problem.
Such LSTM can than be binarized to reach signifficantly greater speed.
End of explanation... |
13,327 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generación de trayectorias por medio de LSPB
El objetivo de esta práctica es generar una trayectoria para un robot manipulador, de tal manera que no tenga cambios bruscos de posición o veloc... | Python Code:
from generacion_trayectorias import grafica_trayectoria
%matplotlib inline
Explanation: Generación de trayectorias por medio de LSPB
El objetivo de esta práctica es generar una trayectoria para un robot manipulador, de tal manera que no tenga cambios bruscos de posición o velocidad.
El algoritmo general qu... |
13,328 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
UCI SECOM Dataset
Semiconductor manufacturing process dataset
2018/7/17 Wayne Nixalo
0. Setup
Step1: 1. EDA
Step2: 50 random signals
Step3: All failures (104)
Step4: Random 100 passes
St... | Python Code:
%matplotlib inline
%reload_ext autoreload
%autoreload 2
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import preprocessing, svm
from sklearn.linear_model import LinearRegression, LogisticRegression
PATH = Path('data/datasets/paresh2047/uci-semc... |
13,329 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Careful, these constants may be different for you
Step1: First import the training and testing sets
Step2: Fit the training data.
Step3: Sanity checks
One variable
First we plot the expec... | Python Code:
DATA_PATH = '~/Desktop/sdss_dr7_photometry_source.csv.gz'
import itertools
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn.neighbors
%matplotlib inline
PSF_COLS = ('psfMag_u', 'psfMag_g', 'psfMag_r', 'psfMag_i', 'psfMag_z')
Explanation: Careful, these constants may be ... |
13,330 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 3
Step3: Heat currents
Following Ref. [2], we consider two possible definitions of the heat currents from the qubits into the baths.
The so-called bath heat currents are $j_{\text{B... | Python Code:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
import qutip as qt
from qutip.nonmarkov.heom import HEOMSolver, DrudeLorentzPadeBath, BathExponent
from ipywidgets import IntProgress
from IPython.display import display
# Qubit parameters
epsilon = 1
# System operators... |
13,331 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial / How to use
In this tutorial we create a (simplified) synthetic galaxy image from scratch, along with its associated segmentation map, and then run the statmorph code on it.
Settin... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as ndi
from astropy.visualization import simple_norm
from astropy.modeling import models
from astropy.convolution import convolve
import photutils
import time
import statmorph
%matplotlib inline
Explanation: Tutorial / How to use
In th... |
13,332 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-2', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: NASA-GISS
Source ID: SANDBOX-2
Topic: Atmos
Sub-Topics: Dynamical Core, ... |
13,333 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overview
Use linked DMA channels to perform "scan" across multiple ADC input channels.
After each scan, use DMA scatter chain to write the converted ADC values to a
separate output array for... | Python Code:
from arduino_rpc.protobuf import resolve_field_values
from teensy_minimal_rpc import SerialProxy
import teensy_minimal_rpc.DMA as DMA
import teensy_minimal_rpc.ADC as ADC
# Disconnect from existing proxy (if available)
try:
del proxy
except NameError:
pass
proxy = SerialProxy()
dma_channel_scatter ... |
13,334 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Classification & How To "Frame Problems" for a Neural Network
by Andrew Trask
Twitter
Step1: Lesson
Step2: Project 1
Step3: Transforming Text into Numbers
Step4: Project 2
Step... | Python Code:
def pretty_print_review_and_label(i):
print(labels[i] + "\t:\t" + reviews[i][:80] + "...")
g = open('reviews.txt','r') # What we know!
reviews = list(map(lambda x:x[:-1],g.readlines()))
g.close()
g = open('labels.txt','r') # What we WANT to know!
labels = list(map(lambda x:x[:-1].upper(),g.readlines())... |
13,335 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kinetic Curve Simulation Fit
<p class=lead>This notebook performs fits of simulated Kinetic Curves for different kinetics parameters. A single [template notebook](Simulated Kinetic Curve Fit... | Python Code:
from nbrun import run_notebook
Explanation: Kinetic Curve Simulation Fit
<p class=lead>This notebook performs fits of simulated Kinetic Curves for different kinetics parameters. A single [template notebook](Simulated Kinetic Curve Fit - Template.ipynb) is executed several times, once for each set of parame... |
13,336 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solution of Lahti et al. 2014
Write a function that takes as input a dictionary of constraints and returns a dictionary tabulating the BMI group for all the records matching the constraints.... | Python Code:
import csv
Explanation: Solution of Lahti et al. 2014
Write a function that takes as input a dictionary of constraints and returns a dictionary tabulating the BMI group for all the records matching the constraints. For example, calling:
get_BMI_count({'Age': '28', 'Sex': 'female'})
should return:
{'NA': 3... |
13,337 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Replace NaN with mode
Use sample builtin function to create sample from matrix
Count of Matching Values in two Matrices/Vectors
Cross Validation
Value-based join of two Matrices
Filter Matri... | Python Code:
from systemml import MLContext, dml, jvm_stdout
ml = MLContext(sc)
print (ml.buildTime())
Explanation: Replace NaN with mode
Use sample builtin function to create sample from matrix
Count of Matching Values in two Matrices/Vectors
Cross Validation
Value-based join of two Matrices
Filter Matrix to include o... |
13,338 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h2> Let's import a couple datasets and take them for a spin</h2>
Step1: <h2> Looks like There aren't too many ppm m/z overlaps </h2>
Step2: <h2> So, about 1/4 of the mass-matches have pot... | Python Code:
### import two datasets
def reindex_xcms_by_mzrt(df):
df.index = (df.loc[:,'mz'].astype('str') +
':' + df.loc[:, 'rt'].astype('str'))
return df
# alzheimers
local_path = '/home/irockafe/Dropbox (MIT)/Alm_Lab/'\
'projects'
alzheimers_path = local_path + '/revo_healthcare/data/process... |
13,339 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 1
Step1: Load house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
Step2: Split data into training and testing
... | Python Code:
import graphlab
Explanation: Regression Week 1: Simple Linear Regression
In this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. You will:
* Use graphlab SArray and SFrame functions to compute important summary statistics
* Write a... |
13,340 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Background information on filtering
Here we give some background information on filtering in general,
and how it is done in MNE-Python in particular.
Recommended reading for practical applic... | Python Code:
import numpy as np
from scipy import signal, fftpack
import matplotlib.pyplot as plt
from mne.time_frequency.tfr import morlet
import mne
sfreq = 1000.
f_p = 40.
ylim = [-60, 10] # for dB plots
xlim = [2, sfreq / 2.]
blue = '#1f77b4'
Explanation: Background information on filtering
Here we give some backg... |
13,341 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
K-Nearest Neighbors (KNN)
by Chiyuan Zhang and Sören Sonnenburg
This notebook illustrates the <a href="http
Step1: Let us plot the first five examples of the train data (first row) and... | Python Code:
import numpy as np
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from scipy.io import loadmat, savemat
from numpy import random
from os import path
mat = loadmat(os.path.join(SHOGUN_DATA_DIR, 'multiclass/usps.mat'))
Xall = mat['data']
Yall = np.array(mat['label'].squeeze... |
13,342 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Natasha
Natasha solves basic NLP tasks for Russian language
Step1: Getting started
Doc
Doc aggregates annotators, initially it has just text field defined
Step2: After applying segmenter t... | Python Code:
from natasha import (
Segmenter,
MorphVocab,
NewsEmbedding,
NewsMorphTagger,
NewsSyntaxParser,
NewsNERTagger,
PER,
NamesExtractor,
DatesExtractor,
MoneyExtractor,
AddrExtractor,
Doc
)
segmenter = Segmenter()
morph_vocab = MorphVocab()
emb = NewsEmbe... |
13,343 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Principal Component Analysis
PCA is a dimensionality reduction technique; it lets you distill multi-dimensional data down to fewer dimensions, selecting new dimensions that preserve variance... | Python Code:
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
import pylab as pl
from itertools import cycle
iris = load_iris()
numSamples, numFeatures = iris.data.shape
print(numSamples)
print(numFeatures)
print(list(iris.target_names))
Explanation: Principal Component Analysis
PCA is a dim... |
13,344 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NOTES
Step1: Motor
Lin Engineering
http
Step2: ASI Controller
Applied Scientific Instrumentation
http
Step3: Autosipper
Step4: Communication | Python Code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from IPython.display import display
import ipywidgets as widgets
from __future__ import division
%matplotlib notebook
Explanation: NOTES:
Waiting vs blocking
--> blocking holds up everything (could be selective?)
--> waiting for specif... |
13,345 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TF-Slim Walkthrough
This notebook will walk you through the basics of using TF-Slim to define, train and evaluate neural networks on various tasks. It assumes a basic knowledge of neural net... | Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
import math
import numpy as np
import tensorflow as tf
import time
from datasets import dataset_utils
# Main slim library
from te... |
13,346 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Author
Step1: First let's check if there are new or deleted files (only matching by file names).
Step2: So we have the same set of files in both versions
Step3: Let's make sure the struct... | Python Code:
import collections
import glob
import os
from os import path
import matplotlib_venn
import pandas as pd
rome_path = path.join(os.getenv('DATA_FOLDER'), 'rome/csv')
OLD_VERSION = '335'
NEW_VERSION = '337'
old_version_files = frozenset(glob.glob(rome_path + '/*{}*'.format(OLD_VERSION)))
new_version_files = f... |
13,347 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting sentiment from product reviews
In this notebook, you will use product review data from Amazon.com to predict whether the sentiments about a product (from its reviews) are positive... | Python Code:
import os
import zipfile
import string
import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn.feature_extraction.text import CountVectorizer
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
%matplotlib inline
Explanation:... |
13,348 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex client library
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Once you've installed the Vertex client library and Google clo... | Python Code:
import os
import sys
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install -U google-cloud-aiplatform $USER_FLAG
Explanation: Vertex client library: Hyperparameter tuning text binary classification model
<table ... |
13,349 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Explanation
Observations $s$ are scalar values between -100 and 100. Actions $a$ are scalar... | Python Code:
#@title Default title text
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
13,350 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dictionaries
Dictionaries allow us to store connected bits of information. For example, you might store a person's name and age together.
Previous
Step1: Since the keys and values in dictio... | Python Code:
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
Explanation: Dictionaries
Dictionaries allow us to store connected bits of information. For example, you might store a person's name and age together.
Previous: Basic Terminal Apps |
Home |
Next: More Functions
Contents
What are dictionari... |
13,351 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ATM 623
Step1: Contents
Introducing climlab
Using climlab to implement the zero-dimensional energy balance model
Run the zero-dimensional EBM out to equilibrium
A climate change scenario in... | Python Code:
# Ensure compatibility with Python 2 and 3
from __future__ import print_function, division
Explanation: ATM 623: Climate Modeling
Brian E. J. Rose, University at Albany
Lecture 4: Building simple climate models using climlab
Warning: content out of date and not maintained
You really should be looking at T... |
13,352 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dynamic Flux Balance Analysis (dFBA) in COBRApy
The following notebook shows a simple, but slow example of implementing dFBA using COBRApy and scipy.integrate.solve_ivp. This notebook shows ... | Python Code:
import numpy as np
from tqdm import tqdm
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Dynamic Flux Balance Analysis (dFBA) in COBRApy
The following notebook shows a simple, but slow example of implementing dFBA using COBRApy and scipy.integrate.solve... |
13,353 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<span style="color
Step7: GRU class and functions
Step8: Placeholder and initializers
Step9: Models
Step10: Dataset Preparation | Python Code:
import numpy as np
import tensorflow as tf
from sklearn import datasets
from sklearn.cross_validation import train_test_split
import pylab as pl
from IPython import display
import sys
%matplotlib inline
Explanation: <span style="color:green"> GRU ON 8*8 MNIST DATASET TO PREDICT TEN CLASS
<span style="color... |
13,354 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Array views and slicing
A NumPy array is an object of numpy.ndarray type
Step1: All ndarrays have a .base attribute.
If this attribute is not None, then the array is a view of some other ob... | Python Code:
a = np.arange(3)
type(a)
Explanation: Array views and slicing
A NumPy array is an object of numpy.ndarray type:
End of explanation
a = np.arange(3)
a.base is None
a[:].base is None
Explanation: All ndarrays have a .base attribute.
If this attribute is not None, then the array is a view of some other object... |
13,355 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lists and Tuples
In this notebook, you will learn to store more than one valuable in a single variable. This by itself is one of the most powerful ideas in programming, and it introduces a n... | Python Code:
students = ['bernice', 'aaron', 'cody']
for student in students:
print("Hello, " + student.title() + "!")
Explanation: Lists and Tuples
In this notebook, you will learn to store more than one valuable in a single variable. This by itself is one of the most powerful ideas in programming, and it introduc... |
13,356 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This tutorial is generated from a Jupyter notebook that can be found here.
BOLFI
In practice inference problems often have a complicated and computationally heavy simulator, and one simply ... | Python Code:
import numpy as np
import scipy.stats
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
%precision 2
import logging
logging.basicConfig(level=logging.INFO)
# Set an arbitrary global seed to keep the randomly generated quantities the same
seed = 1
np.random.seed(seed)
import elfi
Explanat... |
13,357 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Test pyIAST for match with competitive Langmuir model
In the case that the pure-component isotherms $N_{i,pure}(P)$ follow the Langmuir model with the same saturation loading $M$
Step1: Gen... | Python Code:
import numpy as np
import pyiast
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
%config InlineBackend.rc = {'font.size': 13, 'lines.linewidth':3,\
'axes.facecolor':'w', 'legend.numpoints':1,\
'figure.figsize': (6.0... |
13,358 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FLUORESCENCE BINDING ASSAY ANALYSIS
Experiment date
Step1: Calculating Molar Fluorescence (MF) of Free Ligand
1. Maximum likelihood curve-fitting
Find the maximum likelihood estimate, $\the... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from lxml import etree
import pandas as pd
import os
import matplotlib.cm as cm
import seaborn as sns
%pylab inline
# Get read and position data of each fluorescence reading section
def get_wells_from_section(path):
reads = path.xpath("*/Well")
we... |
13,359 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sebastian Raschka
back to the matplotlib-gallery at https
Step1: <font size="1.5em">More info about the %watermark extension</font>
Step2: <br>
<br>
Formatting I
Step3: <br>
<br>
m x n su... | Python Code:
%load_ext watermark
%watermark -u -v -d -p matplotlib,numpy
Explanation: Sebastian Raschka
back to the matplotlib-gallery at https://github.com/rasbt/matplotlib-gallery
End of explanation
%matplotlib inline
Explanation: <font size="1.5em">More info about the %watermark extension</font>
End of explanation
i... |
13,360 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Researching a Pairs Trading Strategy
By Delaney Granizo-Mackenzie
Notebook released under the Creative Commons Attribution 4.0 License.
Pairs trading is a nice example of a strategy based on... | Python Code:
import numpy as np
import pandas as pd
import statsmodels
from statsmodels.tsa.stattools import coint
# just set the seed for the random number generator
np.random.seed(107)
import matplotlib.pyplot as plt
Explanation: Researching a Pairs Trading Strategy
By Delaney Granizo-Mackenzie
Notebook released unde... |
13,361 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Applying refutation tests to the Lalonde and IHDP datasets
Import the Dependencies
Step1: Loading the Dataset
Infant Health and Development Program Dataset (IHDP)
The measurements used are ... | Python Code:
import dowhy
from dowhy import CausalModel
import pandas as pd
import numpy as np
# Config dict to set the logging level
import logging.config
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'loggers': {
'': {
'level': 'WARN',
},
}
}
logging.... |
13,362 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
10 Secret trigonometry functions you never heard of!
Are you intrigued? Was the heading sufficiently click-baity? See
Step1: Approach 2
Step2: Speed test
Step3: Roughly 13 X slower than ... | Python Code:
%%cython -a
# cython: boundscheck=False
from math import sin, cos
cdef inline double versine(double x):
return 1.0 - cos(x)
def versine_array_py(double[:] x):
cdef int i, n = x.shape[0]
for i in range(n):
x[i] = versine(x[i])
Explanation: 10 Secret trigonometry functions you never hear... |
13,363 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Engineer Nanodegree
Introduction and Foundations
Project
Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the shi... | Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inline
# Load the datas... |
13,364 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Display of Rich Output
In Python, objects can declare their textual representation using the __repr__ method.
Step1: Overriding the __repr__ method
Step2: IPython expands on this idea and ... | Python Code:
class Ball(object):
pass
b = Ball()
b.__repr__()
print(b)
Explanation: Display of Rich Output
In Python, objects can declare their textual representation using the __repr__ method.
End of explanation
class Ball(object):
def __repr__(self):
return 'TEST'
b = Ball()
print(b)
Explanation: Over... |
13,365 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to "Doing Science" in Python for REAL Beginners
Python is one of many languages you can use for research and HW purposes. In the next few days, we will work through many of the ... | Python Code:
## You can use Python as a calculator:
5*7 #This is a comment and does not affect your code.
#You can have as many as you want.
#Comments help explain your code to others and yourself
#No worries.
5+7
5-7
5/7
Explanation: Introduction to "Doing Science" in Python for REAL Beginners
Python is one of many... |
13,366 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading (and Writing) Files (without Pandas)
This notebook is going to help introduce how to work with text files in Python without relying on the underlying magic of Pandas. In addition to ... | Python Code:
f = open('filespython.txt', 'r')
for line in f:
print(line)
f.close()
Explanation: Reading (and Writing) Files (without Pandas)
This notebook is going to help introduce how to work with text files in Python without relying on the underlying magic of Pandas. In addition to being interesting and use... |
13,367 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sampling from a transformed parameter space
This example shows you how to run (and compare) Bayesian inference using a transformed parameter space.
Searching in a transformed space can impro... | Python Code:
import pints
import pints.toy as toy
import pints.plot
import numpy as np
import matplotlib.pyplot as plt
# Set some random seed so this notebook can be reproduced
np.random.seed(10)
# Load a forward model
model = toy.LogisticModel()
Explanation: Sampling from a transformed parameter space
This example sho... |
13,368 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tally Arithmetic
This notebook shows the how tallies can be combined (added, subtracted, multiplied, etc.) using the Python API in order to create derived tallies. Since no covariance inform... | Python Code:
import glob
from IPython.display import Image
import numpy as np
import openmc
Explanation: Tally Arithmetic
This notebook shows the how tallies can be combined (added, subtracted, multiplied, etc.) using the Python API in order to create derived tallies. Since no covariance information is obtained, it is ... |
13,369 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Development of Python HDBSCAN Compared to the Reference Implementation in Java
Or, why I still use Python for high performance scientific computing
Python is a great high level language ... | Python Code:
import pandas as pd
import numpy as np
reference_timing_series = pd.read_csv('reference_impl_external_timings.csv',
index_col=(0,1), names=('dim', 'size', 'time'))['time']
hdbscan_v01_timing_series = pd.read_csv('hdbscan01_timings.csv',
... |
13,370 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Download hourly EPA emissions
Step1: Final script
This downloads hourly data from the ftp server over a range of years, and saves all of the file names/last update times in a list. The down... | Python Code:
import io, time, json
import requests
from bs4 import BeautifulSoup
import pandas as pd
import urllib, urllib2
import re
import os
import numpy as np
import ftplib
from ftplib import FTP
import timeit
Explanation: Download hourly EPA emissions
End of explanation
# Replace the filename with whatever csv sto... |
13,371 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comprehensions
In addition to sequence operations and list methods, Python includes a more advanced operation called a list comprehension.
List comprehensions allow us to build out lists usi... | Python Code:
# Grab every letter in string
lst = [x for x in 'word']
# Check
lst
Explanation: Comprehensions
In addition to sequence operations and list methods, Python includes a more advanced operation called a list comprehension.
List comprehensions allow us to build out lists using a different notation. You can thi... |
13,372 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div style="width
Step1: Script setup
Step2: Settings
Choose download option
The original data can either be downloaded from the original data sources as specified below or from the opsd-S... | Python Code:
version = '2020-08-25'
Explanation: <div style="width:100%; background-color: #D9EDF7; border: 1px solid #CFCFCF; text-align: left; padding: 10px;">
<b>Renewable power plants: Download and process notebook</b>
<ul>
<li><a href="main.ipynb">Main notebook</a></li>
<li>Download and... |
13,373 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PoS tagging en Español
En este primer ejercicio vamos a jugar con uno de los corpus en español que está disponible desde NLTK
Step1: Fíjate que las etiquetas que se usan en el treebank espa... | Python Code:
import nltk
from nltk.corpus import cess_esp
cess_esp = cess_esp.tagged_sents()
print(cess_esp[0])
Explanation: PoS tagging en Español
En este primer ejercicio vamos a jugar con uno de los corpus en español que está disponible desde NLTK: CESS_ESP, un treebank anotado a partir de una colección de noticias ... |
13,374 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy
The best part about Numpy is that, not only do we get massive speedups because numpy can perform many of its operations at the C-level, the vectorized api makes the code simpler and (t... | Python Code:
%load_ext memory_profiler
%load_ext snakeviz
%load_ext cython
import holoviews as hv
hv.extension('bokeh','matplotlib')
from IPython.core import debugger
ist = debugger.set_trace
Explanation: Numpy
The best part about Numpy is that, not only do we get massive speedups because numpy can perform many of its ... |
13,375 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
13,376 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature
Step1: Config
Automatically discover the paths to various data folders and compose the project structure.
Step2: Identifier for storing these features on disk and referring to them... | Python Code:
from pygoose import *
from gensim.models.wrappers.fasttext import FastText
from scipy.spatial.distance import cosine, euclidean, cityblock
Explanation: Feature: Phrase Embedding Distances
Based on the pre-trained word embeddings, we'll calculate the mean embedding vector of each question (as well as the un... |
13,377 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Software Developer career satisfaction detection - DEMO
Created by Judit Acs
Step1: Load data
We use pandas for data loading and preprocessing.
Data source (kaggle.com)
Step2: Most answers... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.preprocessing import LabelEncoder
from keras.layers import Input, Dense, Dropout
from keras.models import Model
from keras.callbacks import EarlyStopping
Explanation: Software Developer career satisfactio... |
13,378 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
文件系统相关操作
pathlib
The pathlib module was introduced in Python 3.4
比string 类型path 能提供更灵活功能
cheat sheet
Step1: useful functions
.read_text()
Step2: .name
Step3: Find the Last Modified File
S... | Python Code:
from pathlib import Path
import pathlib
save_dir = "./test_dir"
Path(save_dir).mkdir(parents=True, exist_ok=True)
### get current directory
print(Path.cwd())
print(Path.home())
print(pathlib.Path.home().joinpath('python', 'scripts', 'test.py'))
Explanation: 文件系统相关操作
pathlib
The pathlib module was introduce... |
13,379 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I performed feature selection using ExtraTreesClassifier and SelectFromModel in data set that loaded as DataFrame, however i want to save these selected feature while maintaining co... | Problem:
import pandas as pd
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import SelectFromModel
import numpy as np
X, y = load_data()
clf = ExtraTreesClassifier(random_state=42)
clf = clf.fit(X, y)
model = SelectFromModel(clf, prefit=True)
column_names = X.columns[model.get_support(... |
13,380 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Structured data prediction using BigQuery ML </h1>
This notebook illustrates
Step1: Restart the kernel so that the new packages are picked up.
Step2: Create BigQuery output dataset
If... | Python Code:
%pip install google-cloud-bigquery seaborn
Explanation: <h1> Structured data prediction using BigQuery ML </h1>
This notebook illustrates:
<ol>
<li> Training Machine Learning models using BQML
<li> Predicting with model
<li> Using spatial queries in BigQuery
<li> Building a linear regression model with fea... |
13,381 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1><span style="color
Step1: Simulate a gene tree with 14 tips and MRCA of 1M generations
Step2: Simulate sequences on single gene tree and write to NEXUS
When Ne is greater the gene tree... | Python Code:
# conda install ipyrad toytree mrbayes -c conda-forge -c bioconda
import toytree
import ipcoal
import ipyrad.analysis as ipa
Explanation: <h1><span style="color:gray">ipyrad-analysis toolkit:</span> mrbayes</h1>
In these analyses our interest is primarily in inferring accurate branch lengths under a relaxe... |
13,382 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Early Reinforcement Learning
With the advances of modern computing power, the study of Reinforcement Learning is having a heyday. Machines are now able to learn complex tasks once thought to... | Python Code:
# Ensure the right version of Tensorflow is installed.
!pip install tensorflow==2.6 --user
Explanation: Early Reinforcement Learning
With the advances of modern computing power, the study of Reinforcement Learning is having a heyday. Machines are now able to learn complex tasks once thought to be solely in... |
13,383 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
String processing
Let us start by having a look at some of the functionality that is built into Python strings.
The Python string object
The Python string object has many useful features bui... | Python Code:
some_text = " Postman Pat has a cat named Jess. "
Explanation: String processing
Let us start by having a look at some of the functionality that is built into Python strings.
The Python string object
The Python string object has many useful features built into it. Let us look at some of these.
End of exp... |
13,384 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IAF neurons singularity
This notebook describes how NEST handles the singularities appearing in the ODE's of integrate-and-fire model neurons with alpha- or exponentially-shaped current, whe... | Python Code:
import sympy as sp
sp.init_printing(use_latex=True)
from sympy.matrices import zeros
tau_m, tau_s, C, h = sp.symbols('tau_m, tau_s, C, h')
Explanation: IAF neurons singularity
This notebook describes how NEST handles the singularities appearing in the ODE's of integrate-and-fire model neurons with alpha- o... |
13,385 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
JSON examples and exercise
get familiar with packages for dealing with JSON
study examples with JSON strings and files
work on exercise to be completed and submitted
reference
Step1: impo... | Python Code:
import pandas as pd
Explanation: JSON examples and exercise
get familiar with packages for dealing with JSON
study examples with JSON strings and files
work on exercise to be completed and submitted
reference: http://pandas.pydata.org/pandas-docs/stable/io.html#io-json-reader
data source: http://jsonstud... |
13,386 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
bfscraper
a notebook for scraping data from bringfido. Note, mechanize only works with python 2.X.
Step1: Searching for Hotels in a Given City
In this section I will search for hotels in a ... | Python Code:
from bs4 import BeautifulSoup
#import urllib.request
import requests
Explanation: bfscraper
a notebook for scraping data from bringfido. Note, mechanize only works with python 2.X.
End of explanation
url="http://www.bringfido.com/lodging/city/new_haven_ct_us/"
try:
from urllib.request import Request, u... |
13,387 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Какое количество мужчин и женщин ехало на корабле? В качестве ответа приведите два числа через пробел
Step1: 2. Какой части пассажиров удалось выжить? Посчитайте долю выживших пассажиров... | Python Code:
sex_counts = df['Sex'].value_counts()
print('{} {}'.format(sex_counts['male'], sex_counts['female']))
Explanation: 1. Какое количество мужчин и женщин ехало на корабле? В качестве ответа приведите два числа через пробел
End of explanation
survived_df = df['Survived']
count_of_survived = survived_df.value_c... |
13,388 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Minimal word count
The following example is the "Hello, World!" of data processing, a basic implementation of word count. We're creating a simple data processing pipel... | Python Code:
# Run and print a shell command.
def run(cmd):
print('>> {}'.format(cmd))
!{cmd}
print('')
# Install apache-beam.
run('pip install --quiet apache-beam')
# Copy the input file into the local file system.
run('mkdir -p data')
run('gsutil cp gs://dataflow-samples/shakespeare/kinglear.txt data/')
Explana... |
13,389 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Safely refactoring ACLs and firewall rules
Changing ACLs or firewall rules (or filters) is one of the riskiest updates to a network. Even a small error can block connectivity for a la... | Python Code:
# The ACL before refactoring
original_acl =
ip access-list acl
10 deny icmp any any redirect
20 permit udp 117.186.185.0/24 range 49152 65535 117.186.185.0/24 eq 3784
30 permit udp 117.186.185.0/24 range 49152 65535 117.186.185.0/24 eq 3785
40 permit tcp 11.36.216.170/32 11.36.216.169/32 eq bgp
... |
13,390 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature
Step1: Config
Automatically discover the paths to various data folders and compose the project structure.
Step2: Identifier for storing these features on disk and referring to them... | Python Code:
from pygoose import *
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_distances, euclidean_distances
Explanation: Feature: TF-IDF Distances
Create TF-IDF vectors from question texts and compute vector distances between them.
Imports
This utility packa... |
13,391 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Discrete Dynamic Movement Primitives
Arne Böckmann
What are DMPs
<table>
<tr>
<td>
<ul style="list-style-type
Step1: Adding temporal scaling
Add temporal scaling f... | Python Code:
interact(plotPD, g=(-2.0, 6.0, 0.1), y_start=(-1.0, 2.0, 0.1), yd_start=(-50.0, 50.0, 5.0))
Explanation: Introduction to Discrete Dynamic Movement Primitives
Arne Böckmann
What are DMPs
<table>
<tr>
<td>
<ul style="list-style-type:disc">
<li>Dynamical systems</li>
<li>Represe... |
13,392 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Features
https
Step1: Product
~~users~~
~~orders~~
~~order frequency~~
~~reorder rate~~
recency
~~mean/std add_to_cart_order~~
etc.
Step2: User
Products purchased
Orders made
frequency and... | Python Code:
priors = priors.join(orders, on='order_id', rsuffix='_')
priors = priors.join(products, on='product_id', rsuffix='_')
priors.drop(['product_id_', 'order_id_'], inplace=True, axis=1)
Explanation: Features
https://www.kaggle.com/c/instacart-market-basket-analysis/discussion/35468
Here are some feature ideas ... |
13,393 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scattering Function Normalization
Scott Prahl
Jan 2022
Step1: Solid Angles
Solid angles are the 3D analog of 2D angles. A radian $\theta$ is defined as the angle represented by an arc leng... | Python Code:
#!pip install --user miepython
import numpy as np
import matplotlib.pyplot as plt
try:
import miepython
except ModuleNotFoundError:
print('miepython not installed. To install, uncomment and run the cell above.')
print('Once installation is successful, rerun this cell again.')
Explanation: Scatt... |
13,394 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyWCPS
The problem
Step1: The following examples are from the Domain Examples Notebook of GeoPython 2017 (mine is at
Step2: The mechanics of the above should be fairly obvious. The user ne... | Python Code:
!pip install astunparse
import matplotlib.pyplot as plt
%matplotlib inline
# Imports will be simplified as API stabilizes... by now let's eval this...
from pywcps.dsl import *
from pywcps.ast_rewrite import wcps
from pywcps.wcps_client import WCPSClient, emit_fun
# This is a client helper object
# eo = WCP... |
13,395 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Process regresstion tutorial 1
Step1: Problem 1
Step2: Generate a set of $50$ one-dimensional inputs regularly spaced between -5 and 5 and store them in a variable called x, then ... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from numpy.random import multivariate_normal
from numpy.linalg import inv
from numpy.linalg import slogdet
from scipy.optimize import fmin
Explanation: Gaussian Process regresstion tutorial 1:
Int... |
13,396 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem of distribution of epithet docs
Because most epithets do not have many representative documents, I will create another feature table, this time with most of the docs cut out.
Looking... | Python Code:
from cltk.corpus.greek.tlg.parse_tlg_indices import get_epithet_index
import pandas
epithet_frequencies = []
for epithet, _ids in get_epithet_index().items():
epithet_frequencies.append((epithet, len(_ids)))
df = pandas.DataFrame(epithet_frequencies)
df.sort_values(1, ascending=False)
Explanation: Prob... |
13,397 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Abstract
Author
Step1: Notebook Provenance
The time of execution and the versions of the software packegs used are displayed explicitly.
Step2: Local Path Definitions
To make this notebook... | Python Code:
import logging
import os
import sys
import time
from collections import Counter, defaultdict
from operator import itemgetter
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
import numpy as np
import seaborn as sns
import pybel
import pybel_tools as pbt
from pybel.constants import ... |
13,398 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Implementing a Neural Network
from Stanford CS231n assignment 2
In this exercise we will develop a neural network with fully-connected layers to perform classification, and test it ou... | Python Code:
# A bit of setup
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading external modules
# see http://stackoverflo... |
13,399 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
8 Advertising on the Web
"adwords" model, search
"collaborative filtering", suggestion
8.1 Issues in On-Line Advertising
8.1.1 Advertising Opportunities
Auto trading sites allow adverti... | Python Code:
# exerices for section 8.1
Explanation: 8 Advertising on the Web
"adwords" model, search
"collaborative filtering", suggestion
8.1 Issues in On-Line Advertising
8.1.1 Advertising Opportunities
Auto trading sites allow advertisters to post their ads directly on the website.
Display ads are placed... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.