Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
10,600 | <ASSISTANT_TASK:>
Python Code:
import plotly.plotly as py
from data_prep import *
py.sign_in('charleyjoo', 'rx9n91vitl')
%matplotlib inline
plt.ioff()
set_directory()
conn = dbi.connect('crash_database')
get_tables(conn)
conn.close()
crash_data = get_data()
crash_data.head()
plot_x_vs_y()
fig = plot_scatter(x='Ave... | <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: Explore the Database
Step2: Show the names of all tables in the database.
Step3: Get the crash data table as a dataframe and show the first fi... |
10,601 | <ASSISTANT_TASK:>
Python Code:
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, apply_inverse
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjec... | <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 the source estimate
Step2: Plot the activation in the direction of maximal power for this data
Step3: The normal is very similar
Step4: ... |
10,602 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
def fx(X):
X = np.atleast_2d(X)
# Return objective & gradient
return np.sum(np.square(X), axis=1)[:,None], 2*X
from gpflowopt.domain import ContinuousParameter
domain = ContinuousParameter('x1', -2, 2) + ContinuousParameter('x2', -1, 2)
domain
from gpflowo... | <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: Domain
Step2: Optimize
Step3: And here is how we optimize it Monte-Carlo. We can pass the same function as the gradients are automatically dis... |
10,603 | <ASSISTANT_TASK:>
Python Code:
# import the dataset
from quantopian.interactive.data.eventvestor import shareholder_meetings
# or if you want to import the free dataset, use:
# from quantopian.data.eventvestor import shareholder_meetings_free
# import data operations
from odo import odo
# import other libraries we will... | <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 go over the columns
Step2: Now suppose we want a DataFrame of the Blaze Data Object above, but only want the record_date, meeting_date, a... |
10,604 | <ASSISTANT_TASK:>
Python Code:
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
img_RGB = cv2.imread('demo1.jpg')
plt.imshow(cv2.cvtColor(img_RGB, cv2.COLOR_BGR2RGB))
print('Shape_RGB:', img_RGB.shape)
print('Type_RGB:', img_RGB.dtype)
print('RGB intensity at 300,250:',img_RGB[300,250])
img_RGB_lineinte... | <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: Read image and Check inspect values of image at different locations
Step2: RGB pixel intensity 0-255
Step3: RGB line intensity 0-255
|
10,605 | <ASSISTANT_TASK:>
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 numpy as np
import tensorflow as tf
import time
from six.moves import cPickle as pickle
from six.moves import range
pickle_file = 'not... | <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 reload the data we generated in 1_notmnist.ipynb.
Step2: Reformat into a shape that's more adapted to the models we're going to train
Ste... |
10,606 | <ASSISTANT_TASK:>
Python Code:
import nltk
from nltk.corpus import names
import random
name = [(n,'M') for n in names.words('male.txt')] + [(n,'F') for n in names.words('female.txt')]
random.shuffle(name)
name[:10]
def gender_feature(name): return {'last_letter': name[-1]}
featuresets = [(gender_feature(n), g) for (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: 準備一個function,用來產生feature,這裡的feature是用最後的英文字母。
Step2: 嘗試不同的feature,例如加入第一個字母,或加入姓名的長度。
Step3: Document Classification
Step4: Part-of-Speech Ta... |
10,607 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
datapath = '../../../test/convergence/output/'
# load results
path = datapath + 'task1/'
files = !ls {path}
results = {name: np.fromfile(path + name) for name in files if name!='dt'}
dts = np.fromfile(path + 'dt')
tvec... | <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: Task 1 - 1D non-stiff SDE
Step2: The following plot shows $x(t)$ for
Step3: Task 2 - 1D stiff SDE
Step4: The plot of $x(t)$ shows that the ex... |
10,608 | <ASSISTANT_TASK:>
Python Code:
import pyspark
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import LogisticRegressionWithSGD
from pyspark.mllib.tree import DecisionTree
sc = pyspark.SparkContext()
sc
raw_rdd = sc.textFile("./titanic.csv")
raw_rdd.count()
raw_rdd.take(5)
head... | <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 we create a SparkContext, the main object in the Spark API. This call may take a few seconds to return as it fires up a JVM under the cove... |
10,609 | <ASSISTANT_TASK:>
Python Code:
import math
def multiple35(n):
n3 = (n - 1) // 3
sum3 = 3 * n3 * (n3 + 1) // 2
n5 = (n - 1) // 5
sum5 = 5 * n5 * (n5 + 1) // 2
n15 = (n - 1) // 15
sum15 = 15 * n15 * (n15 + 1) // 2
return sum3 + sum5 - sum15
print(multiple35(1000))
def fib(limit):
a = 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: Problem 2 - Even Fibonacci numbers
Step2: While k = 1, 2, 3...
Step3: Problem 3 - Largest prime factor
Step4: Problem 4 - Largest palindrome ... |
10,610 | <ASSISTANT_TASK:>
Python Code:
import bnn
#get
!wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
!wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
#unzip
!gzip -d t10k-images-idx3-ubyte.gz
!gzip -d t10k-labels-idx1-ubyte.gz
#read labels
labels = []
with open("/home/xilinx/jupyter_no... | <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. LFC and MNIST
Step2: 2. Hardware Inference
Step3: Case 2
Step4: 3. Software accelerated inference
Step5: Start inference
Step6: As it ca... |
10,611 | <ASSISTANT_TASK:>
Python Code:
%run setup.ipynb
%matplotlib inline
# load in selected missense variants
tbl_variants_selected = etl.frompickle('../data/tbl_variants_missense_selected.pkl')
tbl_variants_selected.nrows()
# load in haplotypes
callset_haps = np.load('../data/haps_phase1.npz')
haps = allel.HaplotypeArray(ca... | <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: Pairwise LD for functional SNPs
Step2: Compute and plot allele frequencies
Step3: Compute and plot pairwise LD
|
10,612 | <ASSISTANT_TASK:>
Python Code:
# There are several libraries to install
#!pip3 install tensorflow numpy matplotlib scikit-image
%matplotlib inline
import itertools
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import skimage
from skimage import io, transform
from pylab import rcParams
rcPar... | <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: Load image
Step3: Model
Step4: Architecture
Step5: Training
Step6: Evaluation
|
10,613 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('..')
import socnet as sn
sn.graph_width = 320
sn.graph_height = 180
g = sn.load_graph('4-dijkstra.gml', has_pos=True)
for n, m in g.edges():
g.edge[n][m]['label'] = g.edge[n][m]['c']
sn.show_graph(g, elab=True)
class Heap(object):
def __init__(self, ... | <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 seguir, vamos configurar as propriedades visuais
Step2: Por fim, vamos carregar e visualizar um grafo
Step3: Algoritmo de Dijkstra
Step4: E... |
10,614 | <ASSISTANT_TASK:>
Python Code:
t = (1,2.0,'Three')
t
t[0]
# Slicing
t[1:]
# Reversing a tuple
t[::-1]
t[0] = 10
t[3] = 4
t.append(4)
# Finding the index of the value: 2.0
t.index(2.0)
# Number of values in a tuple
t.count('Three')
t = ('hello', {'element': 'Oxygen', 'weight': 15.999}, 1234)
t
# accessing the 2nd v... | <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: You can slice a tuple like you do in Lists.
Step2: Remember that we are slicing the tuple for display purpose only. We cannot change a tuple.
S... |
10,615 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import load_linnerud
linnerud = load_linnerud()
chinups = linnerud.data[:,0]
plt.hist( # complete
plt.hist( # complete
# complete
# complete
plt.hist(# complete
plt.hist(chinups, histtype = '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: Problem 1) Density Estimation
Step2: Problem 1a
Step3: Already with this simple plot we see a problem - the choice of bin centers and number ... |
10,616 | <ASSISTANT_TASK:>
Python Code:
# Set up Spark Context
from pyspark import SparkContext, SparkConf
SparkContext.setSystemProperty('spark.executor.memory', '4g')
conf = SparkConf()
conf.set('spark.sql.autoBroadcastJoinThreshold', 200*1024*1024) # 200MB for map-side joins
conf.set('spark.executor.instances', 12)
sc = Sp... | <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: And now we create a HiveContext to enable Spark to access data from HIVE
Step2: Let's take a look at the dataset - first 5 rows
Step3: Explori... |
10,617 | <ASSISTANT_TASK:>
Python Code:
!!gcc -c sample.c
!!gcc -shared -o sample.dll sample.o -Wl,--out-implib,libsample.a
import ctypes
ctypes.util.find_library('sample.o')
_mod = ctypes.cdll.LoadLibrary('sample')
in_mandel = _mod.in_mandel
in_mandel.argtypes = (ctypes.c_double, ctypes.c_double, ctypes.c_int)
in_mandel.res... | <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: Wrapping into py 3.4
Step2: Load the dll
Step3: Define a wrapper to the dll function
Step4: Use it
|
10,618 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inm', 'inm-cm4-8', '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... |
10,619 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'cnrm-cm6-1', 'toplevel')
# 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: 2... |
10,620 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import *
Image('three_receiver_cal/pics/macgyver.jpg', width='50%')
import skrf as rf
%matplotlib inline
from pylab import *
rf.stylely()
from skrf.calibration import TwoPortOnePath
from skrf.media import RectangularWaveguide
from skrf import two_port_reflect as tp... | <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: Example
Step2: Correction Options
Step3: Full Correction (TwoPortOnePath)
|
10,621 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nuist', 'sandbox-2', 'ocean')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "ema... | <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... |
10,622 | <ASSISTANT_TASK:>
Python Code:
import requests
url = 'http://www.github.com/ibm'
response = requests.get(url)
print(response.status_code)
import requests
url = 'http://www.github.com/ibm'
response = requests.get(url)
print(response.status_code)
if response.status_code == 200:
print('Response status - OK ')
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: Get header information
Step2: Get the body Information
Step3: Using a Web API to Collect Data
Step5: Step 2
Step7: Step 3
Step9: Step 3
Ste... |
10,623 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import nsfg
import first
import analytic
import thinkstats2
import thinkplot
thinkplot.PrePlot(3)
for lam in [2.0, 1, 0.5]:
xs, ps = thinkstats2.RenderExpoCdf(lam, 0, 3.0, 50)
label = r'$\lambda... | <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: Exponential distribution
Step2: Here's the distribution of interarrival times from a dataset of birth times.
Step3: Here's what the CCDF looks... |
10,624 | <ASSISTANT_TASK:>
Python Code:
import numpy
from matplotlib import pyplot
%matplotlib inline
from matplotlib import rcParams
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 16
# The Computer Language Benchmarks Game
# http://benchmarksgame.alioth.debian.org/
#
# originally by Kevin Carson
# modified by Tupteq... | <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, there's a number of issues with this code, as noted in comments on the original post. Instead of addressing those here, I'll point to Konra... |
10,625 | <ASSISTANT_TASK:>
Python Code:
from sklearn.linear_model import LinearRegression
# here we just downloaded the data from the library
from sklearn.datasets import load_boston
# Load the data from the the boston house-prices dataset
boston_data = load_boston()
x = boston_data['data']
y = boston_data['target']
# Make 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: Load the data
Step2: Linear Regression
Step3: Prediction
|
10,626 | <ASSISTANT_TASK:>
Python Code:
# Refer: https://docs.datacommons.org/api/pandas/
!pip install datacommons_pandas datacommons geopandas plotly descartes --upgrade --quiet
# Import Data Commons
import datacommons as dc
import datacommons_pandas as dpd
# Import other required libraries
import matplotlib.pyplot as plt
impo... | <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: Querying Statistics from Data Commons
Step2: Now, that a GEO_LEVEL is selected for viewing different statistics, we shall fetch all the places ... |
10,627 | <ASSISTANT_TASK:>
Python Code:
!wget https://zenodo.org/record/49903/files/vocab.npy
!wget https://zenodo.org/record/49903/files/word_vectors.npy
#from lda2vec_model import LDA2Vec
#from chainer import serializers
#import numpy as np
#import pandas as pd
#import pickle
#
#features = pd.read_pickle("../data/features.pd... | <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: You don't need to run the code below unless you've trained your own model. Otherwise, just download the word vectors from the URL above.
Step2: ... |
10,628 | <ASSISTANT_TASK:>
Python Code:
def get_lincoln():
for filepath in sorted(glob.glob('Lincoln/*.txt')):
with open(filepath, 'r', encoding='latin') as f:
doc = f.read()
yield {'filepath': filepath, 'doc': doc}
def get_TCP():
for filepath in sorted(glob.glob('TCP-ECCO/*.txt')):
... | <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: Intialize swhoosh index
Step2: Add documents to swhoosh index
Step3: Save and close, then reload swoosh index
Step4: Wrap Index in an IndexRe... |
10,629 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
x = [-1, 2, 5, 100]
y = [123, 456, 789, 1255]
result = np.polyfit(x, y, 2)
<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:
|
10,630 | <ASSISTANT_TASK:>
Python Code:
from astroquery.sdss import SDSS
pos = coords.SkyCoord('0h8m05.63s +14d50m23.3s', frame='icrs')
xid = SDSS.query_region(pos, spectro=True)
print(xid)
# complete the code below
favSTARquery = SELECT p.objid, p.ra, p.dec, p.psfMag_u, # [MORE THINGS FOR YOU TO INSERT HERE]
... | <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: Part A) Make an SDSS query
Step3: Notice that the IPython notebook has a nice interface for the table data and that our features are listed in ... |
10,631 | <ASSISTANT_TASK:>
Python Code:
# Fake data parameters
r_actual = 1/7
s_actual = 2/17
data_set_size = 50000
# a number of draws from the summed geometric distributions
time_draws = (np.random.geometric(r_actual, size=data_set_size)
+ np.random.geometric(s_actual, size=data_set_size)
)
time_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: Infer the Readiness and Selection parameters
Step2: I didn't understand this error message at the time, and I moved on to another attempt. But ... |
10,632 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
np.random.seed(113) #set seed before any keras import
import pandas as pd
import random
from sklearn.model_selection import train_test_split
from collections import defaultdict
from keras.preprocessing import sequence
from collections import Counter
seed=0
corpus = pd.... | <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: Dataset
Step2: Test and dev set label distribution
Step3: Baseline
Step4: Results
Step5: Neural network
Step7: Text representation
Step8: ... |
10,633 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import laberinto.algen as ag
import laberinto.laberinto as lab
import numpy as np
import matplotlib.pyplot as plt
mapa1 = lab.Map()
mapa1.draw_tablero()
mapa1.create_camino()
ejemplo = mapa1.list_caminos[0]
ag.calculate_traits(ejemplo, ejemplo.dict_genes)
lab.calculat... | <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: Pintemos el laberinto!
Step2: Queda chulo, ¿verdad?
Step3: Un viajero que intentara seguir estas indicaciones, estaría en un buen apuro. ¡Incl... |
10,634 | <ASSISTANT_TASK:>
Python Code:
%%time
texts = []
docIds=[]
actuallyTrained=0;
temp=0;
for i in sen.find():
if temp<1000:
temp=temp+1
try:
raw = ''.join(i['document']).lower()
tokens = tokenizer.tokenize(raw)
stopped_tokens = [i for i in tokens if not i in en_stop]... | <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 result into multidimensinal array in order to feed in k-means model,
Step2: build a dictionary for ['docId','cluster #']
|
10,635 | <ASSISTANT_TASK:>
Python Code:
# code for loading the format for the notebook
import os
# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir(os.path.join('..', '..', 'notebook_format'))
from formats import load_style
load_style(plot_style=False)
os.chdir(path)
# 1. magic for inline pl... | <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: Submodular Optimization & Influence Maximization
Step2: Spread Process - Independent Cascade (IC)
Step4: We calculate the expected spread of a... |
10,636 | <ASSISTANT_TASK:>
Python Code:
model = keras.models.load_model('example_keras_mnist_model.h5')
model.summary()
dataset = mnist.load_data()
train_data = dataset[0][0] / 255
train_data = train_data[..., np.newaxis].astype('float32')
train_labels = np_utils.to_categorical(dataset[0][1]).astype('float32')
test_data = data... | <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 the dataset and looking at the first five samples of the test data.
Step2: Doing the inference
|
10,637 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy import optimize
from scipy import spatial
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
sns.set(rc={"figure.figsize": (15, 6)})
sns.set_palette(sns.color_palette(... | <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: Motivations
Step2: A naive analysis would claim that there are no clear differences between the two groups and thus would conclude that the "Jo... |
10,638 | <ASSISTANT_TASK:>
Python Code:
import seaborn as sns
import metapack as mp
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
from publicdata.chis import *
%matplotlib inline
sns.set_context('notebook')
# Opening a source package presumes you are working with 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: Estimates Using Pivot
Step2: Summing across responses yields the total popluation, which we can use to calculate percentages.
Step3: Estimates... |
10,639 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from qutip import *
delta = 0.0 * 2 * np.pi
epsilon = 0.5 * 2 * np.pi
gamma = 0.25
times = np.linspace(0, 10, 100)
H = delta/2 * sigmax() + epsilon/2 * sigmaz()
H
psi0 = (2 * basis(2, 0) + basis(2, 1)).unit()
c_ops = [... | <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: Two-level system
Step2: Harmonic oscillator
Step3: Zero temperature
Step4: Finite temperature
Step5: Storing states instead of expectation v... |
10,640 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
test_df = pd.read_csv('test_20180320.csv')
import json
headers_df = pd.io.json.json_normalize(test_df['Headers'].apply(json.loads))
merged_test_df = pd.merge(test_df, headers_df, left_index=True, right_index=True)
import datetime
merged_test_df['Ti... | <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: Then import json and use json_normalize to convert the Headers data into columns of the csv. Merge this back with the original data.
Step2: Con... |
10,641 | <ASSISTANT_TASK:>
Python Code:
# Set up feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.sql_advanced.ex3 import *
print("Setup Complete")
from google.cloud import bigquery
# Create a "Client" object
client = bigquery.Client()
# Construct a reference to the "github_repos" datas... | <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: Exercises
Step2: Run the next code cell to print the table schema.
Step5: Write a query to find the individuals with the most commits in this ... |
10,642 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import cobra
import cobra.test
# "ecoli" and "salmonella" are also valid arguments
model = cobra.test.create_test_model("textbook")
print(len(model.reactions))
print(len(model.metabolites))
print(len(model.genes))
model
model.reactions[29]
model.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: The reactions, metabolites, and genes attributes of the cobrapy model are a special type of list called a cobra.DictList, and each one is made u... |
10,643 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
%matplotlib inline
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from ... | <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 convert categorical feature 'Sex' to numerical via one-hot encoding
Step2: Analysis
Step3: Classification
Step4: K-Neighbors
Step5:... |
10,644 | <ASSISTANT_TASK:>
Python Code:
import mne
import numpy as np
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
data_path = sample.data_path()
meg_path = data_path / 'MEG' / 'sample'
evokeds = mne.read_evokeds(meg_path / 'sample_audvis-ave.fif')
left_auditory = evokeds[0].... | <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 source space
Step2: Fixed dipole orientations
Step3: Restricting the dipole orientations in this manner leads to the following
Step4: The... |
10,645 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
class Plan:
def __init__(self): pass
# Plan 1 = Cigna HDHP/HSA
p1 = Plan()
p1.family_deductible = 4000.00 # Same deductible for both family and individual
p1.individual_deductible = 4000.00... | <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: Helper functions
Step2: Plan cost functions
Step3: Sanity Tests
Step4: Cost less than HSA
Step5: Cost greater than HSA and deductible
Step6:... |
10,646 | <ASSISTANT_TASK:>
Python Code:
def maximum(x, y):
if x > y:
return x
else:
return y
assert maximum(3, 3) == 3
assert maximum(1, 2) == 2
assert maximum(3, 2) == 3
def max_of_three(x, y, z):
if x > y and x > z:
return x
elif y > x and y > z:
return y
elif z > x and z >... | <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. Define a function max_of_three that takes three numbers as arguments and returns the largest of them.
Step2: 3. Define a function length tha... |
10,647 | <ASSISTANT_TASK:>
Python Code:
import tohu
from tohu.v4.primitive_generators import *
from tohu.v4.dispatch_generators import *
from tohu.v4.utils import print_generated_sequence
print(f'Tohu version: {tohu.__version__}')
g = Constant('quux')
print_generated_sequence(g, num=10, seed=12345)
g1 = Boolean()
g2 = Boolean... | <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: Constant
Step2: Boolean
Step3: Integer
Step4: Float
Step5: HashDigest
Step6: HashDigest hex strings (lowercase)
Step7: HashDigest byte str... |
10,648 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
from os.path import join
from pylab import rcParams
import matplotlib.pyplot as plt
rcParams['figure.figsize'] = (13, 6)
plt.style.use('ggplot')
#import nilmtk
from nilmtk import DataSet, TimeFrame, MeterGroup, HDFDataStore
from ni... | <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: Show versions for any diagnostics
Step2: Load dataset
Step3: Period of interest 4 days during holiday
Step4: Training
Step5: Set two days fo... |
10,649 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
def rfam_uri(family_id):
return 'http://rfam.xfam.org/family/%s/alignment?acc=%s&format=fastau&download=0'%(family_id,family_id)
def rfam_uri(family_id):
return '%s.fa'%(family_id)
rfam_id = 'RF00005' #tRNA
rfam_id = 'RF00871' #microRNA mir-689
rfam_id = 'RF022... | <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 an interface for data acquisition, either from file or from remote
Step2: write a parser for FASTA format
Step3: write a converter that ta... |
10,650 | <ASSISTANT_TASK:>
Python Code:
# enable showing matplotlib image inline
%matplotlib inline
# autoreload module
%load_ext autoreload
%autoreload 2
# load local package
import sys
import os
sys.path.append(os.path.join(os.getcwd(), "../../../")) # load project root
from sklearn import preprocessing
import make_model as... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Steps
Step1: Make Training Data
Step2: 会議を分類するモデルにはSVMを使用します。これで、有効な特徴量を探していきます。
Step3: ここからいくつか特徴量を選択し、モデルを作成します。今回はデータが少ないこともあり、なるべくシンプルなモデルとし特徴量を2... |
10,651 | <ASSISTANT_TASK:>
Python Code:
from pyha.components.fsk_modulator import FSKModulator
samples_per_symbol = 64 # this is so high to make stuff plottable
symbols = [1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0]
data = []
for x in symbols:
data.extend([x] * samples_... | <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: Demodulator
Step2: Matched filtering
|
10,652 | <ASSISTANT_TASK:>
Python Code:
df = pd.read_csv('https://archive.org/download/scikit-chem_example_files/iris.csv',
header=None); df
smi = skchem.read_smiles('https://archive.org/download/scikit-chem_example_files/example.smi')
[method for method in skchem.io.__dict__ if method.startswith('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: Analogously with scikit-chem
Step2: Currently available
Step3: scikit-chem also adds convenience methods onto pandas.DataFrame objects.
Step4:... |
10,653 | <ASSISTANT_TASK:>
Python Code:
import os
import numpy as np
import cv2
import matplotlib.pyplot as plt
import utils
import tensorflow as tf
%matplotlib inline
a = tf.constant(5.)
b = tf.constant(1.2345)
with tf.Session() as sess:
print('a={0}, b={1}'.format(sess.run(a), sess.run(b)))
print('a+b={0}'.format(se... | <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 model by compiling a computation graph with tensorflow
Step2: 2), basic ops within a tf session
Step3: 3), define some placeholder whi... |
10,654 | <ASSISTANT_TASK:>
Python Code:
def longestGP(A , N ) :
if(N < 2 ) :
return N
length = 1
common_ratio = 1
maxlength = 1
for i in range(N - 1 ) :
if(A[i + 1 ] % A[i ] == 0 ) :
if(A[i + 1 ] // A[i ] == common_ratio ) :
length = length + 1
maxlength = max(maxlength , length )
else :
common... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
10,655 | <ASSISTANT_TASK:>
Python Code:
# load default libraries
import os, sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# make sure gdal is correctly installed
from osgeo import gdal
import gc
%matplotlib inline
def raster2array(rasterfn):
raster = gdal.Open(rasterfn)
band = raster.GetRas... | <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: Get quantiles from the input raster data (global threshold from raw data)
Step2: The number of non-zero values is notably different from esri's... |
10,656 | <ASSISTANT_TASK:>
Python Code:
#Import the necessary modules and perform the necessary tests
import scipy as sc
import pylab as gr
sc.test("all",verbose=0)
%matplotlib inline
def SIR(U,t,p):
x,y,z=U
yNew= p["alpha"] * y * x
zNew= p["beta"] * y
dx = -yNew
dy = yNew - zNew
dz = zNew
return 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: Setup a python function that specifies the dynamics
Step2: The function SIR above takes three arguments, $U$, $t$, and $p$ that represent the s... |
10,657 | <ASSISTANT_TASK:>
Python Code:
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 ... | <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: Step 2
Step2: Step 3
Step3: Step 4
Step4: Done!
|
10,658 | <ASSISTANT_TASK:>
Python Code:
print("Student 1 answers question 1.")
print("Student 2 answers question 1.")
print("Student 3 answers question 1.")
print("Student 1 answers question 2.")
print("Student 3 answers question 2.")
print("Student 4 answers question 2.")
<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:
Step1: Question 2
|
10,659 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division, print_function, unicode_literals
[10.5, 5.2, 3.25, 7.0]
import numpy as np
video = np.array([10.5, 5.2, 3.25, 7.0])
video
video.size
video[2] # 3rd element
%matplotlib inline
import matplotlib.pyplot as plt
u = np.array([2, 5])
v = np.array([3, 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: Vectors
Step2: Since we plan to do quite a lot of scientific calculations, it is much better to use NumPy's ndarray, which provides a lot of co... |
10,660 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import openmc
import numpy as np
import matplotlib.pyplot as plt
# Define fuel and B4C materials
fuel = openmc.Material()
fuel.add_element('U', 1.0, enrichment=4.5)
fuel.add_nuclide('O16', 2.0)
fuel.set_density('g/cm3', 10.0)
b4c = openmc.Material()
b4c.add_element('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: To begin, let us first create a simple model. The model will be a slab of fuel material with reflective boundaries conditions in the x- and y-di... |
10,661 | <ASSISTANT_TASK:>
Python Code:
%tikz \draw (0,0) rectangle (1,1);
%%tikz --scale 2 --size 300,300 -f jpg
\draw (0,0) rectangle (1,1);
\filldraw (0.5,0.5) circle (.1);
%%tikz --scale 2 --size 300,300 -f svg
\draw (0,0) rectangle (1,1);
\filldraw (0.5,0.5) circle (.1);
%%tikz -s 400,400 -sc 1.2 -f png
\draw [style=help ... | <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: An example for scaling and exporting to a graphics format
Step2: An additional flag -svgsc allows scaling of the final image in the notebook vi... |
10,662 | <ASSISTANT_TASK:>
Python Code:
# Import some libraries that will be necessary for working with data and displaying plots
# To visualize plots in the notebook
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.io # To read matlab files
import pylab
X = np.array([... | <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 quick note on the mathematical notation
Step2: 4.1. Represent a scatter plot of the data points
Step3: 4.2. Compute the ML estimate
Step4: ... |
10,663 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import scipy.io
import scipy.signal as signal
from matplotlib import pyplot as plt
from pyeeg import dfa as dfa
def readFilePerceptualCrossing(filename):
data = scipy.io.loadmat(filename)
size = len(data['dataSeries'])
series = [data['dat... | <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 display the box-plot of the velocity to check if there are differences between groups.
Step2: 3. Fractal analysis
Step3: Now, we displa... |
10,664 | <ASSISTANT_TASK:>
Python Code:
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/Thin... | <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: Hypothesis testing
Step2: And here's an example that uses it to compute the p-value of an experiment where we toss a coin 250 times and get 140... |
10,665 | <ASSISTANT_TASK:>
Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim.py module
from modsim import *
m = UNITS... | <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: Bungee jumping
Step3: Now here's a version of make_system that takes a Params object as a parameter.
Step4: Let's make a System
Step6: drag_f... |
10,666 | <ASSISTANT_TASK:>
Python Code:
from myhdl import *
from myhdlpeek import Peeker
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sympy import *
init_printing()
import random
#https://github.com/jrjohansson/version_information
%load_ext version_information
%version_informati... | <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: Counter Specs
Step2: myHDL modules bitvector type behavior
Step3: down counting behavior
Step5: Up-Counter
Step7: myHDL testing
Step8: Veri... |
10,667 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
g = 9.81 # m/s^2
l = 0.5 # length of pendulum, in meters
tmax = 50. # seconds
t = np.linspace(0, tmax, int(... | <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: Damped, driven nonlinear pendulum
Step4: Write a function derivs for usage with scipy.integrate.odeint that computes the derivatives for the da... |
10,668 | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
import random
values = [ [random.random() for i in range(0,20)] for _ in range(0,100000) ]
col = [ "col%d" % i for i in range(0,20) ]
import pandas
df = pandas.DataFrame( values, columns = col )
df.to_csv("df_text.txt", sep... | <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: Exercice 1
Step2: Etape 2
Step3: Etape 3
Step4: Exercice 2
Step5: Ce module est équivalent au module json sur les types standard du lang... |
10,669 | <ASSISTANT_TASK:>
Python Code:
import suspect
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
data = suspect.io.load_rda("/home/jovyan/suspect/tests/test_data/siemens/SVS_30.rda")
import scipy.signal
window = scipy.signal.tukey(data.np * 2)[data.np:]
data = window * data
plt.plot(data.spectrum()... | <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: For this tutorial, we will be using the SVS_30.rda data included in the Suspect test data collection, so that we don't have to worry about chann... |
10,670 | <ASSISTANT_TASK:>
Python Code:
from google.colab import auth
auth.authenticate_user()
!pip install -q amplpy ampltools gspread --upgrade
MODULES=['ampl', 'coin']
from ampltools import cloud_platform_name, ampl_notebook
from amplpy import AMPL, register_magics
if cloud_platform_name() is None:
ampl = AMPL() # Use ... | <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
Step2: Google Colab & Kaggle interagration
Step3: Use %%ampl_eval to evaluate AMPL commands
Step4: Define the model
Step5: Instatiate ... |
10,671 | <ASSISTANT_TASK:>
Python Code:
# Import libraries.
import csv
import httplib2
from apiclient.discovery import build
import urllib
import json
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
# This API key is provided by google as described in the tu... | <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 from a Fusion Table
Step2: Load JSON Data into a Dataframe
Step3: Select and Clean Up Data
Step4: Now we can quickly convert both c... |
10,672 | <ASSISTANT_TASK:>
Python Code:
df = unpickle_object("FINAL_DATAFRAME_PROJ_5.pkl")
df.head()
def linear_extrapolation(df, window):
pred_lst = []
true_lst = []
cnt = 0
all_rows = df.shape[0]
while cnt < window:
start = df.iloc[cnt:all_rows-window+cnt, :].index[0].date()
end = df.iloc[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: Naïve Model Caveats
Step2: Nested TS VS. FB Prophet TS
Step3: Percent change model!
Step4: From the above, it seems that our model is not tun... |
10,673 | <ASSISTANT_TASK:>
Python Code:
import word2vec
word2vec.word2phrase('/Users/drodriguez/Downloads/text8', '/Users/drodriguez/Downloads/text8-phrases', verbose=True)
word2vec.word2vec('/Users/drodriguez/Downloads/text8-phrases', '/Users/drodriguez/Downloads/text8.bin', size=100, verbose=True)
word2vec.word2clusters('/... | <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: Run word2phrase to group up similar words "Los Angeles" to "Los_Angeles"
Step2: This will create a text8-phrases that we can use as a better in... |
10,674 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
from __future__ import division
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
import sys
# 使用insert 0即只使用github,避免交... | <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: 1. 多支股票使用相同的因子进行择时
Step3: 使用ABuPickTimeExecute.do_symbols_with_same_factors()函数对多支股票使用相同的买... |
10,675 | <ASSISTANT_TASK:>
Python Code:
# ### uncomment below if you want...
# ## ... copious amounts of logging info
# import logging
# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
# rootLogger = logging.getLogger()
# rootLogger.setLevel(logging.INFO)
# ## ... or auto-reload of ge... | <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, we define a super simple parser
Step2: And put everything together in a review generator that provides tokenized sentences and the numbe... |
10,676 | <ASSISTANT_TASK:>
Python Code:
live, firsts, others = first.MakeFrames()
formula = 'totalwgt_lb ~ agepreg'
model = smf.ols(formula, data=live)
results = model.fit()
regression.SummarizeResults(results)
##Results are also available as parameters:
inter = results.params['Intercept']
slope = results.params['agepreg']
slop... | <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: spurious - result for which there is no obvious mechanism that would explain it. e.g. why would first babies be lighter than others? Perhaps be... |
10,677 | <ASSISTANT_TASK:>
Python Code:
from Bio import SeqIO
help(SeqIO)
# we show the first 3 only
from Bio import SeqIO
for i, seq_record in enumerate(SeqIO.parse("data/ls_orchid.fasta", "fasta")):
print(seq_record.id)
print(repr(seq_record.seq))
print(len(seq_record))
if i == 2:
break
#we show 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: The 'catch' is that you have to work with SeqRecord objects (see Chapter 4), which contain a Seq object (Chapter 3) plus annotation like an iden... |
10,678 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import time
import itertools
import h5py
import numpy as np
from scipy.stats import norm
from scipy.stats import expon
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import seaborn as sns
sns.set(style="ticks", color_codes=... | <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: Here we upload the data obtained from Brownian Dynamics simulations of isotropic diffusion on a 2D potential.
Step2: Trajectory analysis
Step3:... |
10,679 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
%matplotlib inline
def select_cols(df):
cols = ['cntry', 'tvtot', 'tvpol', 'rdtot', 'rdpol', 'nwsptot', 'nwsppol', 'netuse',
'rlgblg', 'rlgdgr', '... | <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 following function selects the columns I need.
Step2: Read data from Cycle 1.
Step3: Read data from Cycle 2.
Step4: Read data from Cycle ... |
10,680 | <ASSISTANT_TASK:>
Python Code:
import datetime
import matplotlib.pyplot as plt
import pandas as pd
import pinkfish as pf
import strategy
# Format price data.
pd.options.display.float_format = '{:0.2f}'.format
pd.set_option('display.max_rows', None)
%matplotlib inline
# Set size of inline plots
'''note: rcParams can't 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: Some global data
Step2: Run Strategy
Step3: View log DataFrames
Step4: Generate strategy stats - display all available stats
Step5: View Per... |
10,681 | <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.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_1samp_test
from mne.datasets import 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: Set parameters
Step2: Compute statistic
Step3: View time-frequency plots
|
10,682 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
white_house = pd.read_csv("../data/2015_white_house.csv")
print(white_house.shape)
print(white_house.iloc[-1])
white_house
%matplotlib notebook
import matplotlib.pyplot as plt
plt.hist(white_house["Salary"])
plt.show()
# Calculate the length of each employee's title 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: So far we have imported a dataset from a CSV file into a Pandas DataFrame using the read_csv() function. Then we displayed the data, first as a... |
10,683 | <ASSISTANT_TASK:>
Python Code:
!scala -version
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName('1.3. BigQuery Storage & Spark MLlib - Python')\
.config('spark.jars', 'gs://spark-lib/bigquery/spark-bigquery-latest.jar') \
.getOrCreate()
spark.version
spark.conf.set("spark.sql.repl.e... | <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 Spark Session
Step2: Enable repl.eagerEval
Step3: Read the data from BigQuery as a Spark Dataframe
Step5: Limit no of rows and cache d... |
10,684 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
# fix random seed for reproducibility
np.random.seed(23)
# load data
def load_data(path='Class13_mnist.pkl.gz'):
import gzip
from six.moves import cPickle
import sys
#path = get_file(path, origin='https://s3.amazonaws.com/img-datasets/mnist.pkl.gz')
... | <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: So we now have 60,000 training images and 10,000 test images. Each image is $28 \times 28$ pixels and has an output label indicating what number... |
10,685 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import warnings
from scipy.optimize import minimize
import emcee
import corner
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format='retina'
N = 200
m = np.pi
b = np.e
x = np.random.uniform(0,20,N)
y_var = .5*x
epilson = np.random.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: Let us examine a regression problem wherein we wish model two continous variables; one in terms of the other. Here underlying relationship betwe... |
10,686 | <ASSISTANT_TASK:>
Python Code:
from numpy import matrix
A = matrix([[72, 0, 0, 9, 0, 0],
[ 0, 2.88, 0, 0, 0, -4.5],
[ 0, 0, 18, 9, 0, 0],
[ 9, 0, 9, 12, 0, 0],
[ 0, 0, 0, 0, 33, 0],
[ 0, -4.5, 0, 0, 0, 33]])
b = matrix(... | <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: Con lo que, trivialmente, podemos ver su solución por medio de la implementación mas simple
Step2: Sin embargo, deseamos implementar un método ... |
10,687 | <ASSISTANT_TASK:>
Python Code:
import math
q = 0.6
P_mars = 2.0 * 10 ** -6
A_left = 7.6 # cm^2
L_left = 131.2 # cm
A_right = 6.3 # cm^2
L_right = 126.1 # cm
def solar_torque(P, A, L, q):
Calculates the solar torque (T) based on the Solar Pressure (P), spacecraft Area (A),
distance from centroid of ... | <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: Solar Torques
Step4: Magnetic Torques
Step5: Since both the magnetic torques are less than the solar torques, their sum is also less.
|
10,688 | <ASSISTANT_TASK:>
Python Code:
data = pd.read_csv('lab1v1.csv')
P, D, S = data['Price'].values, data['Demand'].values, data['Supply'].values
data
def plot(*args, x='Quantity', y='Price', **kw):
plt.figure(figsize=(15, 10))
plt.plot(*args)
plt.xlabel(x)
plt.ylabel(y)
plt.legend(kw['legend'])
plt.... | <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: Approximation
Step2: We'll try to approximate our demand function with
Step3: Now let's approximate our supply function with
Step4: Elasticit... |
10,689 | <ASSISTANT_TASK:>
Python Code:
# Ensure python 3 compatibility
from __future__ import division, print_function, absolute_import, unicode_literals
# Import necessary libraries:
# General utilities:
from os import path
# Computation:
import numpy as np
import h5py
# Visualization:
import matplotlib.pyplot as plt
# Finall... | <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: G-Mode filtering and inspection using pycroscopy
Step2: Make the data pycroscopy compatible
Step3: Open the .h5 file and extract some basic pa... |
10,690 | <ASSISTANT_TASK:>
Python Code:
# Загружаем трейновую выборку и ответы
import pandas as pd
raw_train_dataframe = pd.read_table('train.csv', sep=',')
train_dataframe = raw_train_dataframe.drop('id', axis=1)
import numpy as np
train_sample = train_dataframe.drop('label', axis=1).values
train_sample_answers = train_datafra... | <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: Получилось так
|
10,691 | <ASSISTANT_TASK:>
Python Code:
test_stationary(usa_log)
from statsmodels.tsa.seasonal import seasonal_decompose
decomposition = seasonal_decompose(usa)
trend = decomposition.trend
seasonal = decomposition.seasonal
residual = decomposition.resid
plt.subplot(411)
plt.plot(usa, label='Original')
plt.legend(loc='best')
pl... | <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: Because the p-value is now smaller than 0.05, we have necessary evidence to reject the null hypothesis of the Dickey-Fuller test. This shows tha... |
10,692 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import TextVectorization
# Example training data, of dtype `string`.
training_data = np.array([["This is the 1st sample."], ["And here's the 2nd sample."]])
# Create a TextVectorization l... | <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: Introduction
Step2: Example
Step3: Example
Step4: Example
Step5: Building models with the Keras Functional API
Step6: After defining your i... |
10,693 | <ASSISTANT_TASK:>
Python Code:
from quantopian.pipeline import Pipeline
from quantopian.research import run_pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters import Q1500US
universe = Q1500US()
from quantopian.pipeline.data import morningstar
sector = morningstar.... | <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 Securities we want.
Step2: There are two main benefits of the Q500US and Q1500US. Firstly, they greatly reduce the risk of an order... |
10,694 | <ASSISTANT_TASK:>
Python Code:
x, fs = librosa.load('simple_loop.wav')
IPython.display.Audio(x, rate=fs)
spectral_centroids = librosa.feature.spectral_centroid(x, sr=fs)
plt.plot(spectral_centroids[0])
spectral_bandwidth = librosa.feature.spectral_bandwidth(x, sr=fs)
plt.plot(spectral_bandwidth[0])
spectral_contrast ... | <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: librosa.feature.spectral_bandwidth
Step2: librosa.feature.spectral_contrast
Step3: librosa.feature.spectral_rolloff
|
10,695 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
import tensorflow as tf
!mkdir data
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
data_dir = 'data/'
if not isdir(data_... | <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
Step2: These SVHN files are .mat files typically used with Matlab. However, we can load them in with scipy.io.loadmat which we... |
10,696 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import json
#fields for csv
site_fields = ['id', 'name', 'geometry','accuracy']
observation_fields = ['entered', 'values','observer_id', 'site_id', 'type_id', 'parentobs_id']
df = pd.read_csv('C:/Users/Peter/Documents/scc/challenge/obs_types/analysi... | <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: soil samples from analysis.csv
Step2: For soil samples, type=31 and values fields are as follows
|
10,697 | <ASSISTANT_TASK:>
Python Code:
# Authors: Jona Sassenhagen <jona.sassenhagen@gmail.com>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne.io import Raw
from mne.preprocessing import ICA
from mne.preprocessing.ica import corrmap
from mne.datasets import sample
print(__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: Setup paths and prepare epochs data
Step2: 1) Fit ICA to all "subjects".
|
10,698 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'fio-ronm', 'sandbox-3', 'ocnbgchem')
# 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... |
10,699 | <ASSISTANT_TASK:>
Python Code:
input_file_name = './movies.csv'
n_most_popular = 15 # Parametro N
import pandas as pd
import ast
import numpy as np
def get_items(arg_string):
return [d['name'] for d in ast.literal_eval(arg_string)]
#get_items("[{'iso_3166_1': 'DE', 'name': 'Germany'}, {'iso_3166_1': 'US', '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: Importazione dei moduli pandas e ast e numpy.
Step2: 1) Definizione della funzione get_items()
Step3: 2) Lettura del file csv con Pandas
Step4... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.