Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
4,800 | <ASSISTANT_TASK:>
Python Code:
%load data/numbers.txt
# %load code/MRSortByString.py
from mrjob.job import MRJob
class MRSortByString(MRJob):
def mapper(self, _, line):
l = line.split(' ')
print l
yield l[1], l[0]
def reducer(self, key, val):
yield key, [v for ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: examine the sorting code
Step4: How were they sorted?
|
4,801 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
from esiosdata import FacturaElec
from esiosdata.facturapvpc import (TIPO_PEAJE_GEN, TIPO_PEAJE_NOC, TIPO_PEAJE_VHC,
ZONA_IMPUESTOS_PENIN_BALEARES, ZONA_IM... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Cambios de tarifa
Step2: Consumo horario
Step3: Factura a partir de consumo horario
Step4: Reparto de la facturación en otros intervalos
Step... |
4,802 | <ASSISTANT_TASK:>
Python Code:
# Standard lib imports
from glob import glob
from os import remove
# Local lib import
import pycl
import pyBioPlot as pbl
# Third party import
import pandas as pd
import numpy as np
import pylab as pl
import seaborn as sns
import scipy.stats as stats
# Pyplot tweaking
%matplotlib inline
p... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Hendrickson = fRIP with 24 chromatin related protein
Step2: Convert coordinates from hg19 to hg39 with Crossmap and remap on last gencode human... |
4,803 | <ASSISTANT_TASK:>
Python Code:
running_id = 0
output = [[0]]
with open("E:/output.txt") as file_open:
for row in file_open.read().split("\n"):
cols = row.split(",")
if cols[0] == output[-1][0]:
output[-1].append(cols[1])
output[-1].append(True)
else:
outpu... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problems
Step2: Problems
Step3: Problems
Step4: If we want to look at covariates, we need a new approach.
Step5: Once we've fit the data, ... |
4,804 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.DataFrame({'col1': {0: 'a', 1: 'b', 2: 'c'},
'col2': {0: 1, 1: 3, 2: 5},
'col3': {0: 2, 1: 4, 2: 6},
'col4': {0: 3, 1: 6, 2: 2},
'col5': {0: 7, 1: 2, 2: 3},
'col6': {... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,805 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
# import sys
# sys.path.insert(1, "..")
import timml
kh = 2. # m/day
f_ani = 0.05 # anisotropy factor
kv = f_ani*kh
ctop = 800. # resistance top leaky layer in days
ztop = 0. # surface elevation
z_well = -13. # end depth of the wells... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Parameters
Step2: Model
Step3: Build model, solve, and calculate total discharge and distance to the 5 cm drawdown contour.
Step4: Plot an ov... |
4,806 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Below I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits.
Step2: We'll train an autoe... |
4,807 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import cvxopt as opt
from cvxopt import blas, solvers
import pandas as pd
np.random.seed(123)
# Turn off progress printing
solvers.options['show_progress'] = False
## NUMBER OF ASSETS
n_assets = 4
## NUMBER OF OBSERVA... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Assume that we have 4 assets, each with a return series of length 1000. We can use numpy.random.randn to sample returns from a normal distributi... |
4,808 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from google.cloud import bigquery
%%bigquery
SELECT
FORMAT_TIMESTAMP( "%Y-%m-%d %H:%M:%S %Z", pickup_datetime) AS pickup_datetime,
pickup_longitude,
pickup_latitude,
dropoff_longitude,
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <h3> Extract sample data from BigQuery </h3>
Step2: Let's increase the number of records so that we can do some neat graphs. There is no guara... |
4,809 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import HTML
HTML('<iframe src=http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data width=300 height=200></iframe>')
# import load_iris function from datasets module
from sklearn.datasets import load_iris
# save "bunch" object containing iris datase... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Machine learning on the iris dataset
Step2: Machine learning terminology
Step3: Each value we are predicting is the response (also known as
St... |
4,810 | <ASSISTANT_TASK:>
Python Code:
#ts_df =ts_df [0:45]
#str_df=str_df[0:45]
par_df.astype(str,errors='ignore')
modPars_df.astype(str,errors='ignore')
if len(ts_df.columns) == 6:
ts_df.columns = \
['unempl.','totalProfit','totalProd.','plannedP.','price','wage']
# to have shorter names
if len(ts_df.columns) ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Parameters
Step2: Modified parameters
Step3: Time series, data collected at the end of each period
Step4: The origin of the partial_corr sour... |
4,811 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
import numpy as np
import pandas as pd
import first
import thinkstats2
import thinkplot
%matplotlib inline
live, firsts, others = first.MakeFrames()
live.shape
live = live[live.prglngth>=37]
live.shape
live = live.dropna(subset=['agepreg'... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's load up the NSFG data again.
Step2: And select live, full-term births.
Step3: And drop rows with missing data (just for the variables we... |
4,812 | <ASSISTANT_TASK:>
Python Code:
# We will first read the wine data headers
f = open("wine.data")
header = f.readlines()[0]
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import linalg as la
# Read the data file (text format): wine.data, delimiter=',', use columns 0, 1, 10, skip the he... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's first look at two wine characteristics
Step2: PCA on a Subset of the Wine Data
Step3: Let's visualize the normalized data and its princi... |
4,813 | <ASSISTANT_TASK:>
Python Code:
# Import
from __future__ import division
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['figure.figsize'] = (20.0, 10.0)
inline_rc = dict(mpl.rcParams)
from classification_utilities import make_facies_log_plot
import pandas as pd
import numpy as n... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load data
Step2: Data inspection
Step3: Feature imputation
Step4: Feature augmentation
Step5: Generate training, validation and test data sp... |
4,814 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ncc', 'sandbox-2', 'seaice')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "emai... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... |
4,815 | <ASSISTANT_TASK:>
Python Code:
from Bio import motifs
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC, generic_dna, generic_protein
import pandas as pd
import os, sys
for seq_record in SeqIO.parse("../data/fasta/ludwig_eve-striped-2.fasta", "fasta"):
print(seq_record.id)
print(rep... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sequences to Query
Step2: Motifs
Step3: Postion Specific scoring matrix
Step4: Searching for TFBS
Step5: Test Motifs present
|
4,816 | <ASSISTANT_TASK:>
Python Code:
import sys
print(sys.version)
print(sys.executable)
%matplotlib inline
# Import badlands grid generation toolbox
import pybadlands_companion.resizeInput as resize
#help(resize.resizeInput.__init__)
newRes = resize.resizeInput(requestedSpacing = 40)
#help(newRes.regridDEM)
newRes.regridD... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1. Load python class and set required resolution
Step2: 2. Regrid DEM file
Step3: 3. Regrid Rain file
Step4: 4. Regrid Tectonic files
Step5: ... |
4,817 | <ASSISTANT_TASK:>
Python Code:
import os.path as op
import mne
from mne.datasets import sample
data_path = sample.data_path()
# the raw file containing the channel location + types
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
# The paths to Freesurfer reconstructions
subjects_dir = data_path + '/subjects... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Computing the forward operator
Step2: Visualization the coregistration
Step3: Compute Source Space
Step4: The surface based source space src ... |
4,818 | <ASSISTANT_TASK:>
Python Code:
# standard imports
%matplotlib inline
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('bmh')
# setup the popn distribution we're sampling from
mu, sigma = 10, 1
distn = stats.norm(loc=mu, scale=sigma)
# list of sample... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Setup the simulation
Step2: Even for small samples, the sampling deviation of the mean is well behaved
Step3: As one would hope, the sample me... |
4,819 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import ipywidgets as widgets
print(widgets.Button.on_click.__doc__)
from IPython.display import display
button = widgets.Button(description="Click Me!")
display(button)
def on_button_clicked(b):
print("Button clicked.")
button.on_click(on_button... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The Button is not used to represent a data type. Instead the button widget is used to handle mouse clicks. The on_click method of the Button c... |
4,820 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from scipy.optimize import bisect
def supply(price, b):
return np.exp(b * price) - 1
def demand(price, a, epsilon):
return a * price**(-epsilon)
def compute_equilibrium(a, b, epsilon):
plow = 0.1
phigh = 10.0
def excess_supply(price):
retur... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now let's write routines to compute supply and demand as functions of price and parameters
Step2: Next we'll write a function that takes a para... |
4,821 | <ASSISTANT_TASK:>
Python Code:
%lsmagic
import numpy
%timeit A=numpy.random.random((1000,1000))
%%timeit -n 1
A=numpy.random.random((1000,1000))
b = A.sum()
ip = get_ipython()
import time
def sleep_magic(line):
A simple function for sleeping
t = float(line)
time.sleep(t)
ip.register_magic_function?
ip.regi... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Defining your own magic
Step3: Exercise
Step6: Cell Magic
Step7: Excercise
Step9: Executing Notebooks
Step10: A notebook is just a dictiona... |
4,822 | <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.time_frequency import tfr_morlet
from mne.stats import permutation_cluster_test
from mne.datasets import sample
print(__doc__)
da... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set parameters
Step2: Factor to downsample the temporal dimension of the TFR computed by
Step3: Compute statistic
Step4: View time-frequency ... |
4,823 | <ASSISTANT_TASK:>
Python Code:
from builtins import zip
from builtins import str
from builtins import map
from builtins import range
from past.utils import old_div
import cv2
import glob
import matplotlib.pyplot as plt
import numpy as np
import os
import psutil
import scipy
from skimage.external.tifffile import TiffFil... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First download the file and load it in memory to view it. Note that it is not necessary to load the file in memory in order to perform motion co... |
4,824 | <ASSISTANT_TASK:>
Python Code:
import random
def generate_equations(allowed_operators, dataset_size, min_value, max_value):
Generates pairs of equations and solutions to them.
Each equation has a form of two integers with an operator in between.
Each solution is an integer with the result of the ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Learn to calculate with seq2seq model
Step2: To check the corectness of your implementation, use test_generate_equations function
Step3: Final... |
4,825 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
one_dimensional_array = np.array([1.2, 2.4, 3.5, 4.7, 6.1, 7.2, 8.3, 9.5])
print(one_dimensional_array)
two_dimensional_array = np.array([[6, 5], [11, 7], [4, 8]])
print(two_dimensional_array)
sequence_of_integers = np.arange(5, 12)
print(sequence_of_integers)
rand... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Populate arrays with specific numbers
Step2: You can also use np.array to create a two-dimensional matrix. To create a two-dimensional matrix, ... |
4,826 | <ASSISTANT_TASK:>
Python Code:
from symbulate import *
%matplotlib inline
P = BoxModel([1, 2, 5, 10], probs=[0.4, 0.2, 0.3, 0.1])
P.sim(10000).tabulate(normalize=True)
RV(P).sim(10000).plot()
sims = RV(DiscreteUniform(a=1, b=6)).sim(10000)
sims.plot()
DiscreteUniform(a=1, b=6).plot()
print('The simulated mean is: {:.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <a id='discrete'></a>
Step2: <a id='discrete_unif'></a>
Step3: Example. DiscreteUniform(a = 1, b) pmf.
Step4: <a id='bernoulli'></a>
Step5: ... |
4,827 | <ASSISTANT_TASK:>
Python Code:
import geopandas as gpd # read and manage attribute table data
import matplotlib.pyplot as plt # prepare the figure
import colouringmap.mapping_point as mpoint # for drawing points
import colouringmap.mapping_polygon as mpoly # for mapping background polygon
import colouringmap.markerset ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: the file contain some major railway stations.
Step2: Tthe projection of the file is epsg
Step3: And now read the borders file, and do the pro... |
4,828 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import bokeh
from bokeh.io import output_notebook
output_notebook()
import os
DATA_STREETLIGHT_CASES_URL = 'https://data.sfgov.org/api/views/c53t-rr3f/rows.json?accessType=DOWNL... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Transforming Column Names
Step2: Transforming Open and Close Dates
Step3: Adding new features
Step4: Transforming Localization
Step5: Locali... |
4,829 | <ASSISTANT_TASK:>
Python Code:
from pygoose import *
import nltk
from collections import Counter
from nltk.corpus import stopwords
nltk.download('stopwords')
project = kg.Project.discover()
feature_list_id = '3rdparty_dasolmar_whq'
df_train = pd.read_csv(project.data_dir + 'train.csv').fillna('')
df_test = pd.read_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: NLTK tools
Step2: Config
Step3: Identifier for storing these features on disk and referring to them later.
Step4: Read data
Step5: NLTK buil... |
4,830 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='white')
from thinkstats2 import Pmf, Cdf
import thinkstats2
import thinkplot
decorate = thinkplot.config
def choose_bread(mean, std, n):
loaves = np.random.n... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Poincaré's bread
Step2: Here's a sample from the distribution of bread weight if the baker chooses 5 loaves.
Step3: And here's how the observe... |
4,831 | <ASSISTANT_TASK:>
Python Code:
import pyAudioGraph as ag
# choose a wav file on your pc
wav_file = 'AudioFile.wav' # only signed 16/32 bit supported
world = ag.World(nchannels=2, buf_len=512)
# create the diskInUnit
audioStream = ag.AudioStreamWaveFile(wav_file)
diskInNode = ag.Nodes.DiskInNode(world, audioStream)
# ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create the units
Step2: Connect the units
Step3: Append the nodes and then sort the graph
Step4: Run
|
4,832 | <ASSISTANT_TASK:>
Python Code:
import re
import datetime
from pyspark.sql import Row
month_map = {'Jan': 1, 'Feb': 2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7,
'Aug':8, 'Sep': 9, 'Oct':10, 'Nov': 11, 'Dec': 12}
def parse_apache_time(s):
Convert Apache time format into a Python datetime object
Args:
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: version 1.0.1
Step4: (1b) Configuration and Initial RDD Creation
Step5: (1c) Data Cleaning
Step6: Part 2
Step7: (2b) Example
Step9: (2c) Ex... |
4,833 | <ASSISTANT_TASK:>
Python Code:
# If GPU is not available:
# GPU_USE = '/cpu:0'
# config = tf.ConfigProto(device_count = {"GPU": 0})
# If GPU is available:
config = tf.ConfigProto()
config.log_device_placement = True
config.allow_soft_placement = True
config.gpu_options.allocator_type = 'BFC'
# Limit the maximum memor... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Plot training and test accuracy
|
4,834 | <ASSISTANT_TASK:>
Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
!pip install --user google-cloud-bigquery==1.25.0
PROJECT = "your-gcp-project-here" # REPLACE WITH YOUR PROJECT NAME
BUCKET = "your-gcp-bucket-here" # REPLACE WITH YOUR BUCKET
REGION = "us-central1" # REPLACE WITH YOUR BU... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Note
Step2: Explore time series data
Step4: The function clean_data below does three things
Step7: Read data and preprocessing
Step11: Make ... |
4,835 | <ASSISTANT_TASK:>
Python Code:
!date
# Standard Library Python Modules
# Common Python Modules
import matplotlib.pyplot as plt
import numpy as np
import spacepy.plot as spp
import spacepy.toolbox as tb
import pandas as pd
import pymc # this is the MCMC tool
# put plots into this document
%matplotlib inline
# observed ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create simulated data that can be used in this proof of concept
Step2: Now based on the results above we can use this as a prediction of the Y-... |
4,836 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'fio-ronm', 'sandbox-1', 'ocean')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,837 | <ASSISTANT_TASK:>
Python Code:
km = pyclust.KMeans(n_clusters=5)
km.fit(df.iloc[:,0:2].values)
print(km.centers_)
plot_scatter(df.iloc[:,0:2].values, labels=km.labels_, title="Scatter Plot: K-Means")
bkm = pyclust.BisectKMeans(n_clusters=5)
bkm.fit(df.iloc[:,0:2].values)
print(bkm.labels_)
plot_scatter(df.iloc[:,0:2].... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Bisecting K-Means
Step2: Cutting the tree structure
|
4,838 | <ASSISTANT_TASK:>
Python Code:
import json
import requests
CRIME_SOCRATA_VIEW_ID = 'ijzp-q8t2'
def get_data_portal_url(view_id):
return 'http://data.cityofchicago.org/api/views/{view_id}'.format(
view_id=view_id)
def get_dataset_columns(view_id):
Get dataset field names from the Socrata API
Retur... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We're going to download recent crimes from the City of Chicago's data portal.
Step2: It looks like the column named "Date" with an ID of "154... |
4,839 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import scipy.signal
import matplotlib.pyplot as plt
fs = 40000 # sample rate
skip = 3200 * fs * 8 # first transmission seems to have a missing samples from the recorder
skip = 5550 * fs * 8
length = 140 * fs
with open('/home/daniel/Descargas/DSLWP-B_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We load a file containing the relevant GMSK transmission. The recording was done at the Dwingeloo radiotelescope and can be obtained here. Remem... |
4,840 | <ASSISTANT_TASK:>
Python Code:
import magma as m
from mantle import FullAdder
# 2 input
def csa2(I0, I1):
return m.bits(FullAdder()(I0, I1, 0))
# 3 input
def csa3(I0, I1, I2):
return m.bits(FullAdder()(I0, I1, I2))
def popcount8(I):
# Dadda dot notation (of the result)
# o o csa0_0_21 - row 0, b... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: In this example, we are going to use the built-in fulladder from Mantle.
Step2: A common name for a full adder is a carry-sum adder, or csa.
St... |
4,841 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
# Hide info messages from paramiko
import logging
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.WARN)
import time
import random
import threading
import pandas as pd
import numpy as np
import plotly.plotly as py
import plotly.graph_objs as go... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create and launch AWS instances.
Step2: MNIST dataset
Step3: Train a NN to predict the numbers (as simple as it gets)
Step4: Train with some ... |
4,842 | <ASSISTANT_TASK:>
Python Code:
# 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 writing, sof... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: scikit-learn HP Tuning on AI Platform
Step2: The data
Step3: Load the hyperparameter values that are passed to the model during training.
Step... |
4,843 | <ASSISTANT_TASK:>
Python Code:
# Import the necessary stuff
import pandas as pd
# Read the dataset into a Pandas DataFrame
star_wars = pd.read_csv("../data/star_wars.csv", encoding="ISO-8859-1")
# Explore the data by looking at the first 10 rows.
star_wars.head(10)
# NOTE: Lots of NaN, even for stuff like RespondentID.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Cleaning Up Yes/No Columns
Step2: Cleaning Up Checkbox Columns
Step3: Cleaning Up Ranking Columns
Step4: Find the Highest Ranked Movie
Step5:... |
4,844 | <ASSISTANT_TASK:>
Python Code:
#general imports
import pygslib
#get the data in gslib format into a pandas Dataframe
mydata= pygslib.gslib.read_gslib_file('../data/cluster.dat')
# This is a 2D file, in this GSLIB version we require 3D data and drillhole name or domain code
# so, we are adding const... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Getting the data ready for work
Step2: Testing variogram function gamv
|
4,845 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
steps=250
distance=0
x=0
distance_list=[]
steps_list=[]
while x<steps:
distance+=np.random.randint(-1,2)
dis... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Building a tree, regression
Step2: Visualizing the Tree, The Moons
Step3: Algorithms for Setting up Decision Trees
Step4: Computing the Gini ... |
4,846 | <ASSISTANT_TASK:>
Python Code:
kids = resp['numkdhh']
kids
pmf = thinkstats2.Pmf(kids)
thinkplot.Pmf(pmf, label='PMF')
thinkplot.Show(xlabel='# of Children', ylabel='PMF')
def BiasPmf(pmf, label=''):
Returns the Pmf with oversampling proportional to value.
If pmf is the distribution of true values, the result... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Display the PMF.
Step3: Define <tt>BiasPmf</tt>.
Step4: Make a the biased Pmf of children in the household, as observed if you surveyed the ch... |
4,847 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
from qutip import *
import time
#number of states for each mode
N0=8
N1=8
N2=8
K=1.0
#damping rates
gamma0=0.1
gamma1=0.1
gamma2=0.4
alpha=sqrt(3)#initial coherent state param for mode 0
epsilon=0.5j #sqeezing parameter
tfinal=4.0
dt=0.05
tlist=arange(0.0,tfinal+dt,dt)
tauli... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Deviation form thermal
Step2: Software version
|
4,848 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
from tsfresh.feature_extraction import extract_features
# TimeBasedFCParameters contains all functions that use the Datetime index of the timeseries container
from tsfresh.feature_extraction.settings import TimeBasedFCParameters
df = pd.DataFrame({"id": ["a", "a", "... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Build a time series container with Datetime indices
Step2: Right now TimeBasedFCParameters only contains linear_trend_timewise, which performs ... |
4,849 | <ASSISTANT_TASK:>
Python Code:
from functools import reduce
def get_products_of_all_ints_except_at_index(arr):
results = []
if len(arr) < 2:
raise Exception("Arrays too short, can't do it")
for index, value in enumerate(arr):
new_array = arr[0:index] + arr[index+1:]
product... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Apple Stocks
Step2: Need to do better than O(n^2), so it'll probably be either O(n log n) or O(n). Let's try a greedy approach.
|
4,850 | <ASSISTANT_TASK:>
Python Code:
import os
import ipywidgets as widgets
import bqplot.pyplot as plt
from bqplot import LinearScale
image_path = os.path.abspath('../../data_files/trees.jpg')
with open(image_path, 'rb') as f:
raw_image = f.read()
ipyimage = widgets.Image(value=raw_image, format='jpg')
ipyimage
plt.fig... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Using pyplot's imshow to display the image
Step2: Displaying the image inside a bqplot Figure
Step3: Mixing with other marks
Step4: Its trait... |
4,851 | <ASSISTANT_TASK:>
Python Code:
def mul(a, b):
return a*b
mul(2, 3)
mul = lambda a, b: a*b
mul(2, 3)
mul(mul(2, 3), 3)
def transform_and_add(func, a, b):
return func(a) + func(b)
transform_and_add(lambda x: x**2, 1, 2)
def square_and_add(a, b):
return (a**2 + b**2)
def cube_and_add(a, b):
return (a**3 ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Lambda is another way of defining a function
Step2: Why would I want something like this?
Step3: Operators to the rescure
Step4: Lets do some... |
4,852 | <ASSISTANT_TASK:>
Python Code:
def unixTimeToHumanReadable(seconds ) :
ans = ""
daysOfMonth =[31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ]
(currYear , daysTillNow , extraTime , extraDays , index , date , month , hours , minutes , secondss , flag ) =(0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 )
days... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,853 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
from asl_data import AslDb
asl = AslDb() # initializes the database
asl.df.head() # displays the first five rows of the asl database, indexed by video and frame
asl.df.ix[98,1] # look at the data available for an individual frame
asl.df['grnd-ry'] ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The frame represented by video 98, frame 1 is shown here
Step2: Try it!
Step3: Build the training set
Step4: The training data in training is... |
4,854 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import cv2
import matplotlib.pyplot as plt
#image is height: 480, width: 640
#M:u:x:col:width
#N:v:y:row:height
#Calculate (u,v) distance from center of image
def getDValue(u,v,w,h):
return np.sqrt((u - (w/2.0))**2 + (v - (h/2.0))**2)
#Calculate ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Afterwards, we created a function calculate each of the elements of matrix H, the Butterworth filter.
Step2: Below we have a function to create... |
4,855 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'gfdl-cm4', 'seaice')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... |
4,856 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'test-institute-1', 'sandbox-2', 'atmos')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,857 | <ASSISTANT_TASK:>
Python Code:
#Importamos las librerías utilizadas
import numpy as np
import pandas as pd
import seaborn as sns
#Mostramos las versiones usadas de cada librerías
print ("Numpy v{}".format(np.__version__))
print ("Pandas v{}".format(pd.__version__))
print ("Seaborn v{}".format(sns.__version__))
#Abrimos... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Representamos ambos diámetro y la velocidad de la tractora en la misma gráfica
Step2: Con esta tercera aproximación se ha conseguido estabiliza... |
4,858 | <ASSISTANT_TASK:>
Python Code:
x = range(10)
x
[item**2 for item in x]
def square(num):
return num**2
list(map(square, x))
square_lamb = lambda num: num**2
list(map(square_lamb, x))
list(map(lambda num: num**2, x))
[item**2 for item in range(1,20) if item % 2 == 0]
list(map(lambda z: z**2, filter(lambda z: z % 2... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Lambda functions are just anonymous functions and don't need to be created as official functions prior to being used. This makes them useful bec... |
4,859 | <ASSISTANT_TASK:>
Python Code:
## conda install ipyrad -c ipyrad
## conda install -c conda-forge scikit-allel
%matplotlib inline
import ipyrad
import ipyrad.analysis as ipa ## ipyrad analysis toolkit
## Load your assembly
data = ipyrad.load_json("/tmp/ipyrad-test/rad.json")
## Create they pca object
pca = ipa.pc... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Import Python libraries
Step2: Quick guide (tldr;)
Step3: Full guide
Step4: Here we can just load the vcf file directly into the pca analysis... |
4,860 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import os
import re
import math
import random
import pickle
import pandas as pd
import numpy as np
import scipy.stats
#from numba import jit
from datetime import datetime
from joblib import Parallel, delayed
import matplotlib.pyplot as plt
nfeatures = 8 # number of feat... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <a id='sec2.1'></a>
Step2: Extract POI category and visiting frequency.
Step3: <a id='sec2.2'></a>
Step4: <a id='sec2.3'></a>
Step5: Sequenc... |
4,861 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from pylab import *
#### Download the dataset
# Get the script from internet
! wget https://raw.githubusercontent.com/sorki/python-mnist/master/get_data.sh > /dev/null 2>&1
# Run it to dovnload all files in a local dir named 'data'
! bash get_data.sh >/dev/null 2>&1... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let us implement a Hopfield network using images from the MNIST dataset as patterns.
Step2: We now fill a array with all parameters. We only ne... |
4,862 | <ASSISTANT_TASK:>
Python Code:
def countDigit(n ) :
prime =[False ] * 10
prime[2 ] = True
prime[3 ] = True ;
prime[5 ] = True
prime[7 ] = True ;
temp = n
count = 0 ;
while(temp != 0 ) :
d = temp % 10 ;
temp //= 10 ;
if(d > 0 and n % d == 0 and prime[d ] ) :
count += 1
return count
n... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,863 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import scipy as sp
import scipy.sparse
from scipy.sparse import csc_matrix, csr_matrix
import matplotlib.pyplot as plt
import scipy.linalg
import scipy.sparse.linalg
%matplotlib inline
n = 5
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sparsity pattern
Step2: What we need to find out to see how it actually works
Step3: As you see, CSR is faster, and for more unstructured patt... |
4,864 | <ASSISTANT_TASK:>
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 sl... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Creating your first neural network with TF-Slim
Step3: Let's create the model and examine its structure.
Step4: Let's create some 1d regressio... |
4,865 | <ASSISTANT_TASK:>
Python Code:
# Load libraries
import numpy as np # Math
import scipy.io # Import data
import time
import sklearn.neighbors, sklearn.linear_model, sklearn.ensemble, sklearn.naive_bayes # Baseline classification techniques
import matplotlib.pyplot as plt
# Load 400 text documents representing 5 classes
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Question 1a
Step2: Observe the best result. What is the best technique?<br>
Step3: Values of the hyperparameter C
Step4: Question 2b
Step5: ... |
4,866 | <ASSISTANT_TASK:>
Python Code:
import skgstat as skg
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
s = [30, 80, 300]
data1 = skg.data.pancake(N=s[0], seed=42, as_dataframe=True).get('sample')
data2 = skg.data.pancake(N=s[1], seed=42, as_dataframe=True).get('sampl... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 3.1 Load data
Step2: 3.2 Comparing estimators
Step3: The default estimator configured in Variogram is the Mathéron estimator (Mathéron, 1963).... |
4,867 | <ASSISTANT_TASK:>
Python Code:
# connect to PostgreSQL using psycopg2
# !pip install psycopg2-binary
import psycopg2
# Connect to an existing database and create the test table
with psycopg2.connect("dbname=postgres user=postgres host=localhost port=5432 password=mysecretpassword") as pg_conn:
cur = pg_conn.cursor... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Define the query to compute the histogram
Step3: Fetch the histogram data into a pandas dataframe
Step4: Histogram plotting
|
4,868 | <ASSISTANT_TASK:>
Python Code:
#Write your code here
#Solution
def isValidTriangle(arg_1, arg_2, arg_3):
if(arg_1 + arg_2 + arg_3 == 180):
print "YES"
else:
print "NO"
#Write your functions here
import math
#Solutions
def find_hypotenuse(a, b):
return math.sqrt(a*a+b*b)
def find_leg(a,b):
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We can categorize triangles into three categories based on the properties of their angles.
Step2: Distance between two points
Step3: Finding t... |
4,869 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-mm', 'aerosol')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "em... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,870 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
from plydata import call
df = pd.DataFrame({
'w': [1, 2, np.nan, 4, 5],
'x': [np.nan, 2, np.nan, 4, 5],
'y': [np.nan] * 4 + [5],
'z': [np.nan] * 5
})
df
df >> call(pd.DataFrame.dropna)
# You can call method on the dataframe with '.me... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Drop NaN Values
Step2: Drop rows with all NaN values
Step3: Drop rows with NaN values in the x column.
Step4: Drop and keep rows atleast 3 no... |
4,871 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
d = [1, 2, 3, 4, 5]
np.array(d)
d = [1, 2, 3.1415, 4, 5]
np.array(d)
d = [1, 2, 3.1415, 4, 5]
arr = np.array(d)
arr.dtype
arr = np.array([1, 2, 3, 4, 5], dtype='float32')
arr
cmplx = np.array([1.0+2.0j, 3.0+4.0J])
print(cmplx)
cmplx.dtype
arr = np.array([[1., 2., ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The core of the numpy package is the array class. Let's examine that first. We can make an array out of a sequence, like a list.
Step2: data ty... |
4,872 | <ASSISTANT_TASK:>
Python Code:
# Execute this cell to load the notebook's style sheet, then ignore it
from IPython.core.display import HTML
css_file = '../../style/custom.css'
HTML(open(css_file, "r").read())
# Import Libraries
# ----------------
import numpy as np
from numba import jit
import matplotlib
import matpl... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Numerical stability, dispersion and anisotropy of the 2D acoustic finite difference modelling code
Step2: To seperate modelling and visualizati... |
4,873 | <ASSISTANT_TASK:>
Python Code:
# Fake data
# Rising TOC, but *rise rate* decreasing through time
x = np.arange(1990, 2013)
y = np.log(1.5*(x-1989)) + np.random.uniform(low=0, high=1, size=len(x))
df = pd.DataFrame({'TOC':y}, index=x)
df.plot()
# M-K test
res = icpw.mk_test(df['TOC'].values, 'test_stn', 'TOC')
print 'M... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2. Is TOC increasing?
Step3: So there is an increasing overall trend (as we often find in our real data).
Step4: In general, the slopes seem t... |
4,874 | <ASSISTANT_TASK:>
Python Code:
# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.na... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The Dataset
Step2: The data contains the following features
Step3: Most numerical data appear to be fairly complete, with the exception of far... |
4,875 | <ASSISTANT_TASK:>
Python Code::
sns.pairplot(tips , hue = ''sex', palette = 'coolwarm')
<END_TASK>
| <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,876 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from numpy.fft import fft2
from numpy.fft import ifft2
import sys,os
ia898path = os.path.abspath('/etc/jupyterhub/ia898_1s2017/')
if ia898path not in sys.path:
sys.path.append(ia898path)
import ia898.src as ia
f = 5... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Demonstração da recontrução parcial cumulativa das "telhas" primitivas da imagem sintética acima. É exibida cada telha primitiva, fazendo a reco... |
4,877 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head()
rides[:24*10].plot(x='dteday', y='cnt')
dummy_fields = ['seas... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load and prepare the data
Step2: Checking out the data
Step3: Dummy variables
Step4: Scaling target variables
Step5: Splitting the data into... |
4,878 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csir-csiro', 'vresm-1-0', 'land')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,879 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
%matplotlib inline
_df = pd.read_table('DEIMOS/deimos_10K_March2018/deimos.tbl', header=None)
arr = np.empty((len(_df), len(_df.iloc[0][0].split())), dtype='<U50')
for i in range(len(_df)):
i_row = [k for k i... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: if "Remarks" contains "star", the source is classifyed star.
Step2: The distribution of galaxies looks similar to that of the HST COSMOS catalo... |
4,880 | <ASSISTANT_TASK:>
Python Code:
def least_squares(y, tx):
calculate the least squares solution.
#a = tx.T.dot(tx)
#b = tx.T.dot(y)
#return np.linalg.solve(a, b)
w = np.linalg.inv(tx.T @ tx) @ tx.T @ y
return 1 / 2 * np.mean((y - tx.dot(w)) ** 2), w
from helpers import *
def test_your_least_squar... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1 Least squares and linear basis functions models
Step2: Load the data
Step3: Test it here
Step5: 1.2 Least squares with a linear basis funct... |
4,881 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
%matplotlib notebook
gal_im = fits.getdata( # complete
# complete
# complete
plt.colorbar()
plt.tight_layout()
plt.hist( # complete
plt.yscale("log")
unusual_pix = # complete
gal_median_filt = # complete
# c... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problem 1) Visualize the Galaxy Image Data
Step2: Problem 1b
Step3: Problem 1c
Step4: Problem 2) Measuring Radial Intensities
Step5: Probl... |
4,882 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import folium
import seaborn as sns
import datetime
from bcycle_lib.utils import *
%matplotlib inline
plt.rc('xtick', labelsize=14)
plt.rc('ytick', labelsize=14)
# for auto-reloading external modules
# see http://sta... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Loading and cleaning weather data
Step2: The summary above shows descriptive statistics for each of the numeric columns in the table. There is ... |
4,883 | <ASSISTANT_TASK:>
Python Code:
run_id = 'addbbe35-5fd7-4d1b-a37d-3629768532b4'
download_file = run_id + '.tar.gz'
download_url = 'http://csdms.colorado.edu/pub/users/wmt/' + download_file
import requests
r = requests.get(download_url)
with open(download_file, 'w') as fp:
fp.write(r.content)
import tarfile
tar = t... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Download the output and write it to a file on your local machine
Step2: Unpack the file
Step3: Change to the directory containing the unpacked... |
4,884 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import networkx as nx
from netgraph import Graph
# create a modular graph
partition_sizes = [10, 20, 30, 40]
g = nx.random_partition_graph(partition_sizes, 0.5, 0.1)
# create a dictionary that maps nodes to the community they belong to
node_to_community = d... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Alternatively, the best partition into communities can be inferred, for example
|
4,885 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import scipy as sp
import scipy.stats as st
import statsmodels.api as sm
import scipy.optimize as op
import matplotlib.pyplot as plt
%matplotlib inline
filename = '/Users/excalibur/py/nanodegree/intro_ds/final_project/improved-dataset/turnstile_weath... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Class for Creating Training and Testing Samples
Step2: Section 2. Linear Regression
Step3: Only categorical
Step4: <h3 id='2_4'>2.4 What are ... |
4,886 | <ASSISTANT_TASK:>
Python Code:
import json
import os
import time
from google.cloud import aiplatform as vertex_ai
from google.cloud.aiplatform import hyperparameter_tuning as hpt
# Project definitions
PROJECT_ID = '<YOUR PROJECT ID>' # Change to your project id.
REGION = '<LOCATION OF RESOURCES>' # Change to your reg... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Change the following variables according to your definitions.
Step2: Change the following variables ONLY if necessary.
Step3: Initialize Verte... |
4,887 | <ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 2
import pudl
import logging
import sys
from pathlib import Path
import pandas as pd
pd.options.display.max_columns = None
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.For... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set the scope for the Extract-Transform
Step2: Create a locally cached datastore
Step3: EIA-860
Step4: Transform EIA-860 / EIA-860m
Step5: E... |
4,888 | <ASSISTANT_TASK:>
Python Code:
url='https://publications.parliament.uk/pa/cm201516/cmselect/cmwomeq/584/58402.htm'
import pandas as pd
import requests
import requests_cache
requests_cache.install_cache('parli_comm_cache')
from bs4 import BeautifulSoup
#https://www.dataquest.io/blog/web-scraping-tutorial-python/
page ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Observation - from the report contents page, I can navigate via the Back button to https
Step2: Report Contents Page Link Scraper
Step3: Repor... |
4,889 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("white")
#Note the new use of the dtype option here. We can directly tell pandas to use the Speed column as a category in one step.
speeddf = pd.read_csv("../Class04/Class04_speed_data.csv",dtype={'Spe... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The goal, as before, it to build a model to describe the decision boundary between the "fast" and "slow" categories in our label column. We are ... |
4,890 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cccr-iitm', 'iitm-esm', 'seaice')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... |
4,891 | <ASSISTANT_TASK:>
Python Code:
#@title 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 writin... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 심층 합성곱 생성적 적대 신경망
Step2: 데이터셋 로딩 및 준비
Step3: 모델 만들기
Step4: (아직 훈련이 되지않은) 생성자를 이용해 이미지를 생성해봅시다.
Step5: 감별자
Step6: (아직까지 훈련이 되지 않은) 감별자를 사용하여... |
4,892 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import display
from sympy.interactive import printing
printing.init_printing(use_latex='mathjax')
from __future__ import division
import sympy as sym
from sympy import *
x, y, z = symbols("x y z")
k, m, n = symbols("k m n", integer=True)
f, g, h = map(Function, 'fgh')... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <h2>Elementary operations</h2>
Step2: <h2>Algebra<h2>
Step3: <h2>Calculus</h2>
Step5: Illustrating Taylor series
Step6: With this function d... |
4,893 | <ASSISTANT_TASK:>
Python Code:
#some help
!gsutil --help
#list my buckets
#(projectId has been set in the gcloud config
# you can use the parameter -p projectId instead )
!gsutil ls
#more details
!gsutil ls -L
#some help
!gsutil mb --help
#creating a new bucket class regional en region wurope-west2
!gsutil mb -c re... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: let's create a new bucket
Step2: everything is better with labels
Step3: Upload a nice foto there
Step4: The Photo is there on the internet!... |
4,894 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
def newfig(title='?', xlabel='?', ylabel='?', xlim=None, ylim=None,
xscale='linear', yscale='linear', size_inches=(14, 8)):
'''Setup a new axis for plotting'''
fig, ax = plt.subplots()
fig.set_size_inches(s... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Convenience function to set up a graph
Step2: Implementation
Step3: Show individual waves, assuming $s=0$ at $t=0$ ($theta = 0$)
Step4: Show ... |
4,895 | <ASSISTANT_TASK:>
Python Code:
import os
import yaml
import json
from download_and_process_functions import get_sha_hash
output_path = 'output'
files = [
'conventional_power_plants_DE.csv', 'conventional_power_plants_DE.xlsx',
'conventional_power_plants_EU.csv', 'conventional_power_plants_EU.xlsx',
'conven... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 7.1 Write checksums
Step2: 7.1 Write the results to file
|
4,896 | <ASSISTANT_TASK:>
Python Code:
import h2o
h2o.init(nthreads=-1)
import os.path
PATH = os.path.expanduser("~/h2o-3/")
test_df = h2o.import_file(PATH + "bigdata/laptop/mnist/test.csv.gz")
train_df = h2o.import_file(PATH + "bigdata/laptop/mnist/train.csv.gz")
y = "C785"
x = train_df.names[0:784]
train_df[y] = train_df[y]... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Specify the response and predictor columns
Step2: Train Deep Learning model and validate on test set
Step3: Inspect the model in Flow
Step4: ... |
4,897 | <ASSISTANT_TASK:>
Python Code:
print aces_gene_names[:10]
alist = list(aces_gene_names[:10])
gn1 = 'Entrez_5982'
gn2 = 'Entrez_76'
print alist.index(gn1)
print alist.index(gn2)
aces_gene_names = list(aces_gene_names)
edges_set = set([]) # (gene_idx_1, gene_idx_2)
# gene_idx_1 < gene_idx_2
# idx in aces_gene_names, star... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 9900 genes in the network. 4181 of those are always expressed.
|
4,898 | <ASSISTANT_TASK:>
Python Code:
%%capture
!pip install git+https://github.com/biothings/biothings_explorer#egg=biothings_explorer
# import modules from biothings_explorer
from biothings_explorer.hint import Hint
from biothings_explorer.user_query_dispatcher import FindConnection
import nest_asyncio
nest_asyncio.apply()... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next, import the relevant modules
Step2: Step 1
Step3: Step 2
Step4: Here, we formulate a FindConnection query with "CML" as the input_ojb, "... |
4,899 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo(id="P-0CJpO3spg", width="100%")
import networkx as nx
G_er = nx.erdos_renyi_graph(n=30, p=0.2)
nx.draw(G_er)
len(G_er.edges())
len(G_er.edges()) / 435
import pandas as pd
from nams.functions import ecdf
import matplotlib.pyplot as p... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: In this chapter, we are going to take a look at how to perform statistical inference on graphs.
Step2: You can verify that there's approximatel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.