Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
15,600
<ASSISTANT_TASK:> Python Code: import numpy as np p = np.poly1d([6., 1., -2.]) p(0), p(1), p(10) p.order p.roots # Comprobando las raíces p(p.roots) np.poly1d([2.,-3.,7.]).roots import matplotlib.pyplot as plt xvalues = np.linspace(-10.,10.,100) plt.plot(xvalues, p(xvalues), '-') plt.show() y = p(xvalues) + np.r...
<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: La clase poly1D representa polinomios unidimensionales con base en sus coeficientes. Sea el polinomio Step2: Se puede evaluar el valor de $p(x)...
15,601
<ASSISTANT_TASK:> Python Code: # Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt from __future__ import print_function # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a 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: We would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps Step2: Inline Qu...
15,602
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) view_sentence_range = (0, 10) DON'T MODIFY AN...
<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: Language Translation Step3: Explore the Data Step6: Implement Preprocessing Function Step8: Preprocess all the data and save it Step10: Chec...
15,603
<ASSISTANT_TASK:> Python Code: debug_flag = False import datetime import glob import logging import lxml import os import six import xml import xmltodict import zipfile # paper identifier paper_identifier = "Newsday" archive_identifier = "Newsday_20171006230211_00001" # source source_paper_folder = "/mnt/hgfs/project...
<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 - Imports Step2: Setup - working folder paths Step3: Setup - logging Step4: Setup - virtualenv jupyter kernel Step5: Setup - Initializ...
15,604
<ASSISTANT_TASK:> Python Code: from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.pipeline import Pipeline from sklearn.cross_validation import cross_val_score n_samples = 1000 np.random.seed(0) X = np.sort(np.random.rand(n_samples)) y = np.cos(1.5 * np.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: 정규화 하이퍼 모수 최적화 Step2: One Standard Error Rule
15,605
<ASSISTANT_TASK:> Python Code: from rmtk.vulnerability.derivation_fragility.equivalent_linearization.miranda_2000_firm_soils import miranda_2000_firm_soils from rmtk.vulnerability.common import utils %matplotlib inline capacity_curves_file = "../../../../../../rmtk_data/capacity_curves_Sa-Sd.csv" capacity_curves = uti...
<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 capacity curves Step2: Load ground motion records Step3: Load damage state thresholds Step4: Obtain the damage probability matrix Step5:...
15,606
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import pastas as ps ps.set_log_level("ERROR") %matplotlib inline # This notebook has been developed using Pastas version 0.9.9 and Python 3.7 print("Pastas version: {}".format(ps.__version__)) print("Pandas 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: Step 2. Reading the time series Step2: Step 3. Creating the model Step3: Step 4. Adding stress models Step4: Step 5. Solving the model Step5:...
15,607
<ASSISTANT_TASK:> Python Code: odds = [1, 3, 5, 7] print('odds are:', odds) print('first element:', odds[0]) print('last element:', odds[3]) print('"-1" element:', odds[-1]) odds[0] = 10 print('first element:', odds[0]) salsa = ['peppers', 'onions', 'cilantro', 'tomatoes'] my_salsa = salsa salsa[0] = 'hot peppers' ...
<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 access elements of a list using indices – numbered positions of elements in the list. These positions are numbered starting at 0, so the ...
15,608
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from itertools import product from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import matplotlib.pyplot as plt %matplotlib notebook # Illustrating the use of itertools product for ix,va...
<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: Explaination of the conditions Step3: Studying the trade off
15,609
<ASSISTANT_TASK:> Python Code: mu = pymc.Uniform('mu', 0, 1e5) deaths = pymc.Poisson('deaths', mu = 2.0*mu, observed=True, value=[3]) model = pymc.MCMC((mu, deaths)) model.sample(10000, burn=100, burn_till_tuned=True) print(model.summary()) pymc.Matplot.plot(model) mu = pymc.Gamma('mu', 3.0, 5.0) deaths = pymc.Poisson...
<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: This does not match the example very well. The example is centered around 0.9
15,610
<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...
15,611
<ASSISTANT_TASK:> Python Code: %matplotlib inline # sanity check for python setup import sys print(sys.executable) print(sys.path) import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.cluster import KMeans from sklearn import datasets np.random.seed(5) centers=[...
<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: 1b. KNN (K=5) Step2: 2. Evaluation procedure 2 - Train/test split
15,612
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np from scipy.spatial import cKDTree from scipy.spatial.distance import cdist from metpy.gridding.gridding_functions import calc_kappa from metpy.gridding.interpolation import barnes_point, cressman_point from metpy.gridding.triangles import...
<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: Generate random x and y coordinates, and observation values proportional to x * y. Step2: Set up a cKDTree object and query all of the observat...
15,613
<ASSISTANT_TASK:> Python Code: %pylab notebook VB = 120.0 # Battery voltage (V) r = 0.3 # Resistance (ohms) l = 1.0 # Bar length (m) B = 0.6 # Flux density (T) F = arange(0,51,10) # Force (N) F # Lets print the variable to check. # Can you exaplain why "arange(0,50,10)" gives not the 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: Define all the parameters Step2: Select the forces to apply to the bar Step3: Calculate the currents flowing in the motor Step4: Calculate th...
15,614
<ASSISTANT_TASK:> Python Code: # local from fludashboard.libs.flu_data import prepare_keys_name import matplotlib.pyplot as plt import pandas as pd import numpy as np df_hist = pd.read_csv('../data/historical_estimated_values.csv', encoding='utf-8') df_inci = pd.read_csv('../data/current_estimated_values.csv', encodin...
<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 show the current year incidence up to given week.<br> Step2: UF Step3: Entries with dfthresholds['se típica do inicio do s...
15,615
<ASSISTANT_TASK:> Python Code: from deriva.core import ErmrestCatalog, get_credential scheme = 'https' hostname = 'dev.facebase.org' catalog_number = 1 credential = get_credential(hostname) assert scheme == 'http' or scheme == 'https', "Invalid http scheme used." assert isinstance(hostname, str), "Hostname not set."...
<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: This example uses a development server with a throw away catalog. You will not have sufficient permissions to be able to run this example. This ...
15,616
<ASSISTANT_TASK:> Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # Jona Sassenhagen <jona.sassenhagen@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import mne from mne.stats import spatio_temp...
<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: Read epochs for the channel of interest Step3: Find the FieldTrip neighbor definition to setup sensor connectivity Step4...
15,617
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt class Plan: 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 p1.family_oopmax = 6000...
<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:...
15,618
<ASSISTANT_TASK:> Python Code: #!pip install -I "phoebe>=2.3,<2.4" import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_binary() b.add_dataset('lc', dataset='lc01') b.add_dataset('mesh', times=[0], columns=['intensities*']) print(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: As always, let's do imports and initialize a logger and a new bundle. Step2: Relevant Parameters Step3: If you have a logger enabled, PHOEBE w...
15,619
<ASSISTANT_TASK:> Python Code: import numpy as np A = np.array([[1,1,1], [3,1,2], [2,3,4]]) b = np.array([6, 11, 20]) A b x = np.linalg.solve(A, b) x A = np.matrix([[1,1,1], [3,1,2], [2,3,4]]) A np.linalg.inv(A) A = np.matrix([[1,2,2],[2,4,1],[3,6,4]]) A np.linalg.matrix_rank(A) A = np.matrix([[1,2,3], [4,5,6], [7,...
<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: Gaussian Elimination Step2: Gaussian-Jordan Elimination Step3: Column space Step4: Projection Matrix
15,620
<ASSISTANT_TASK:> Python Code: some_digits = X[36001] some_digits_img = some_digits.reshape(28, 28) plt.imshow(some_digits_img, cmap=matplotlib.cm.binary, interpolation='Nearest') plt.axis("off") plt.show() ### checking out its label y[36001] # MNIST dataset is already split into train(first 60000) and test(last 10000)...
<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 try to train a BINARY classification Step2: A good place to start is with a Stochastic Gradient Descent (SGD) classifier, using Scikit-Le...
15,621
<ASSISTANT_TASK:> Python Code: import numpy as np import PIL.Image im = PIL.Image.open("/Users/valeriaalvarez/Documents/rh.jpeg") col,row = im.size A = np.zeros((row*col, 5)) pixels = im.load() print(pixels[187,250]) for i in range(col): for j in range(row): #print("i=%d, j=%d" % (i,j)) r,g...
<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: - Realizar la descomposición SVD Step2: - Verificar la descomposición SVD Step3: con el método anterior, no logré imprimir la imagen con el im...
15,622
<ASSISTANT_TASK:> Python Code: %matplotlib inline import math, sys, os, numpy as np import torch from matplotlib import pyplot as plt, rcParams, animation, rc from ipywidgets import interact, interactive, fixed from ipywidgets.widgets import * rc('animation', html='html5') rcParams['figure.figsize'] = 3, 3 %precision 4...
<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: Components of Learning Step2: You want to find parameters (weights) a and b such that you minimize the error btwn the points and the line a * x...
15,623
<ASSISTANT_TASK:> Python Code: % matplotlib inline import os import numpy as np import nibabel as nib from nipy.labs.utils.simul_multisubject_fmri_dataset import surrogate_3d_dataset import nipy.algorithms.statistics.rft as rft from __future__ import print_function, division import math import matplotlib.pyplot as 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: Simulate very large RF Step2: Show part of the RF (20x20x1) Step3: Save RF Step4: Run fsl cluster to extract local maxima Step5: Read and pr...
15,624
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure() ax = fig.add_subplot(111) N = 10 x = np.random.rand(N) y = np.random.rand(N) z = np.random.rand(N) circles, triangles, dots = ax.plot(x, 'ro', y, 'g^', z, '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: 1. 动画 Step2: 2. 三维绘图 Step3: 3. 绘制等高线图 Step4: 4. 结合三维绘图和等高线图
15,625
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) s s = pd.Series([1,3,5,np.nan,6,8]) s d = {'a' : 0., 'b' : 1., 'c' : 2.} pd.Series(d) <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: 数据结构 Step2: From dict
15,626
<ASSISTANT_TASK:> Python Code: !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 from biothings_explorer.hint import Hint ht = Hin...
<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 the relevant modules Step2: Step 1 Step3: Step 2 Step4: The df object contains the full output from BioThings Explorer. Each row ...
15,627
<ASSISTANT_TASK:> Python Code: %matplotlib inline from sympy.interactive import printing printing.init_printing() from frame import * import sympy as sp import numpy as np import scipy.sparse as sparse import scipy.sparse.linalg as linalg class Frame_Buckling(LinearFrame): def N_local_stress(self,element): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step5: Project on frame buckling Step6: Essai sur exercice 2 Step7: Essai sur d'autres structures Step8: Structure avec deux forces et sans étage re...
15,628
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint # This is the numerical solver def rhs(Y,t,omega): # this is the function of the right hand side of the ODE y,ydot = Y return ydot,-omega*omega*y t_arr=np.linspace(0,2*np.pi,...
<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 start with a second order linear equation, that has the usual harmonic oscillator solutions. Step2: Now, I would like to test how accurate t...
15,629
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pickle as pkl 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') def model_inputs(real_dim, z_dim): inputs_real = tf.placeholde...
<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: Model Inputs Step2: Generator network Step3: Discriminator Step4: Hyperparameters Step5: Build network Step6: Discriminator and Generator L...
15,630
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd titanic_data = pd.read_csv('train.csv') titanic_data.head(5) titanic_data.info() titanic_data.Age = titanic_data.Age.fillna(np.mean(titanic_data.Age)) titanic_data.info() survivors = titanic_data[titanic_data.Survived == 1] survivor_prob = (len(su...
<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 and filling data Step2: Filling all NaN ages with the mean of all the ages and confirming with .info() method. We later compensate for...
15,631
<ASSISTANT_TASK:> Python Code: import pkg_resources import sys import os import time from urllib.request import urlretrieve import indra.util.get_version import indra.java_vm # make sure INDRA is in charge of the JVM import pybel import pybel_tools from pybel_tools.visualization import to_jupyter %%bash java -showvers...
<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: Environment Step2: Dependencies Step3: Data Step4: Conversion
15,632
<ASSISTANT_TASK:> Python Code: # the output of plotting commands is displayed inline within frontends, # directly below the code cell that produced it %matplotlib inline from time import time # this python library provides generic shallow (copy) and deep copy (deepcopy) operations from copy import deepcopy # import ...
<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 RF parameters for the comparison with ASTRA Step2: Initializing SpaceCharge Step3: Comparison with ASTRA
15,633
<ASSISTANT_TASK:> Python Code: def print_full(x): pd.set_option('display.max_rows', len(x)) print(x) pd.reset_option('display.max_rows') def get_energy(): import pandas as pd import numpy as np energy = pd.read_excel('Energy Indicators.xls', skiprows=16, skip_footer=38, usecols=range(2,6), names...
<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 (6.6%) Step2: <br> Step3: Question 4 (6.6%) Step4: Question 5 (6.6%) Step5: Question 6 (6.6%) Step6: Question 7 (6.6%) Step7: Q...
15,634
<ASSISTANT_TASK:> Python Code: # Preview first 5 edges list(g.edges(data=True))[0:5] # Preview first 10 nodes list(g.nodes(data=True))[0:10] ## Summary Stats print('# of edges: {}'.format(g.number_of_edges())) print('# of nodes: {}'.format(g.number_of_nodes())) # Define node positions data structure (dict) for plotti...
<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: Nodes Step2: Visualize Step3: Colors Step4: Solving the Chinese Postman Problem is quite simple conceptually Step6: CPP Step 2 Step8: Step ...
15,635
<ASSISTANT_TASK:> Python Code: permutation = np.random.permutation(len(iris_target)) iris_data = np.take(iris_data, permutation, axis=0) iris_target = np.take(iris_target, permutation) # Function to plot data def plot_data(colors, names, data, target): plt.figure(figsize=(8, 8)) N = len(names) for color, 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: Create an incremental PCA object Step2: IoTPy
15,636
<ASSISTANT_TASK:> Python Code: # A bit of setup import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.neural_net import TwoLayerNet %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.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: Implementing a Neural Network Step2: We will use the class TwoLayerNet in the file cs231n/classifiers/neural_net.py to represent instances of o...
15,637
<ASSISTANT_TASK:> Python Code: year = 2015 print(year) print(year) year = 2016 %reset print(year) import cv2 import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np # another magic function, this allows you to view plots in the notebook %matplotlib inline first = ["tags/first0.png", "tags/firs...
<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 notebook allows you to prototype code and plots quickly without having to reload data in each time. Can can be useful if you're experimentin...
15,638
<ASSISTANT_TASK:> Python Code: !pip install git+https://github.com/google/starthinker from starthinker.util.configuration import Configuration CONFIG = Configuration( project="", client={}, service={}, user="/content/user.json", verbose=True ) FIELDS = { 'auth_write':'service', # Authorization used for w...
<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. Set Configuration Step2: 3. Enter GA360 Segmentology Recipe Parameters Step3: 4. Execute GA360 Segmentology
15,639
<ASSISTANT_TASK:> Python Code: # Python 2 only: print 'Hello' # Python 2 and 3: print('Hello') # Python 2 only: print 'Hello', 'Guido' # Python 2 and 3: from __future__ import print_function # (at top of module) print('Hello', 'Guido') # Python 2 only: print >> sys.stderr, 'Hello' # Python 2 and 3: from __future__ ...
<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 print multiple strings, import print_function to prevent Py2 from interpreting it as a tuple Step2: Raising exceptions Step3: Raising excep...
15,640
<ASSISTANT_TASK:> Python Code: import time import sqlite3 as sql import os import sys sys.path.append("/Users/kurner/Documents/classroom_labs") class NoConnection(Exception): pass class SQL_DB: # a database # class level parameters backend = 'sqlite3' user_initials = 'KTU' timezone = int(tim...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step5: So far, this class hasn't done any work. We'll use the context manager to make the actual connection, using this DB object. Step6: In the "wit...
15,641
<ASSISTANT_TASK:> Python Code: import sys import matplotlib.pyplot as plt import datetime as dt import numpy as np from mpl_toolkits.basemap import Basemap import pandas as pd import seaborn as sns from scipy.stats.stats import pearsonr prin...
<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: Reading in the Data/Data Cleaning Step2: Plot 1 Step3: Plot 2 Step4: Plot 3 Step5: Plot 4 Step6: Plot 5 Step7: Plot 6 Step8: Appendix Ste...
15,642
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np t = np.linspace(0, 10.0, 100) plt.plot(t, np.sin(t)) plt.xlabel('Time') plt.ylabel('Signal') plt.title('My Plot'); # supress text output f = plt.figure(figsize=(9,6)) # 9" x 6", default is 8" x 5.5" plt.plot(t, np.sin...
<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: Overview Step2: Basic plot modification Step3: Here is a list of the single character color strings Step4: To change the plot's limits, use x...
15,643
<ASSISTANT_TASK:> Python Code: # To support both python 2 and python 3 from __future__ import division, print_function, unicode_literals # Common imports import numpy as np import os # to make this notebook's output stable across runs np.random.seed(42) # To plot pretty figures %matplotlib inline import matplotlib 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: Voting classifiers Step2: Bagging ensembles Step3: Random Forests Step4: Out-of-Bag evaluation Step5: Feature importance Step6: AdaBoost St...
15,644
<ASSISTANT_TASK:> Python Code: import nixio as nix import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from utils.notebook import print_stats from utils.video_player import Playback nix_file = nix.File.open('data/tracking_data.h5', nix.FileMode.ReadOnly) print_stats(nix_file.blo...
<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: Storing of video data Step2: Tracking data Step3: Addtional Information
15,645
<ASSISTANT_TASK:> Python Code: %matplotlib inline # To generate the vector fields import dolfin as df import mshr import numpy as np import plot_vtk_matplotlib as pvm # Matplotlib parameters can be tuned with rc.Params # This library has modified values. For example: # matplotlib.rcParams['font.size'] = 22 mesh = mshr...
<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: Generate 2D Vector Field using Dolfin Step2: Now we can save the data in a VTK file. By default, Fenics saves XML files (instead of binary) usi...
15,646
<ASSISTANT_TASK:> Python Code: import numpy as np from sklearn.model_selection import train_test_split from tensorflow import keras # Set up code checking from learntools.core import binder binder.bind(globals()) from learntools.deep_learning.exercise_8 import * print("Setup Complete") img_rows, img_cols = 28, 28 num_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: 1) Increasing Stride Size in A Layer Step2: You have the same code in the cell below, but the model is now called fashion_model_1. Change the ...
15,647
<ASSISTANT_TASK:> Python Code: # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' PROJECTNUMBER = '663413318684' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['PROJECTNUMBER'] = PROJECTNUMBER os.environ[...
<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: Exploring dataset Step3: <h2> Creating a ML dataset using BigQuery </h2> Step4: <h2> Creating a scikit-learn model using random forests </h2> ...
15,648
<ASSISTANT_TASK:> Python Code: import torch from torch import nn import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.figure(figsize=(8,5)) # how many time steps/data pts are in one batch of data seq_length = 20 # generate evenly spaced data pts time_steps = np.linspace(start=0, stop=np.pi, num=seq...
<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: Define the RNN Step2: Check the input and output dimensions Step3: Training the RNN Step4: Loss and Optimization Step5: Defining the trainin...
15,649
<ASSISTANT_TASK:> Python Code: from crpropa import * import numpy as np import matplotlib.pyplot as plt # define densities FER = Ferriere() NAK = Nakanishi() COR = Cordes() R = np.linspace(0, 30*kpc, 300) phi = np.linspace(0, 2*np.pi, 180) n_FER_HI = np.zeros((R.shape[0],phi.shape[0])) n_FER_HII = np.zeros((R.shape[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: Model Ferrière Step2: Model Cordes Step3: Model Nakanishi Step4: Advanced use of DensityList
15,650
<ASSISTANT_TASK:> Python Code: x = 1 y = 2 x + y x def add_numbers(x, y): return x + y add_numbers(1, 2) def add_numbers(x,y,z=None): if (z==None): return x+y else: return x+y+z print(add_numbers(1, 2)) print(add_numbers(1, 2, 3)) def add_numbers(x, y, z=None, flag=False): if (flag): ...
<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: <br> Step2: <br> Step3: <br> Step4: <br> Step5: <br> Step6: <br> Step7: <br> Step8: <br> Step9: <br> Step10: <br> Step11: <br> Step12:...
15,651
<ASSISTANT_TASK:> Python Code: # set up all the data for the rest of the notebook import json from collections import Counter from itertools import chain from IPython.display import HTML def vote_table(votes): Render a crappy HTML table for easy display. I'd use Pandas, but that seems like complete overkill 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: Analyzing Shreddit's Q2 Top 5 voting Step3: Equal Placement Ballots Step4: And here's the top ten from my computed tally Step5: Weighted Tall...
15,652
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) from collections import Counter total_counts = Counter() for _, r...
<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: Preparing the data Step2: Counting word frequency Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in...
15,653
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('../deeprl') import gym env = gym.make('MountainCar-v0') print env.action_space print env.observation_space print env.observation_space.low print env.observation_space.high print env.goal_position %matplotlib inline import numpy as np import matplotlib.pyplot...
<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 OpenAI Gym Step2: A gym environment contains all relevant data describing the problem. We can directly inspect the action space and the o...
15,654
<ASSISTANT_TASK:> Python Code: from math import pi %run matplotlib_setup.ipy from matplotlib import pyplot import numpy as np import kwant lat=kwant.lattice.square() L,W=30,16 def myshape(R): return ( (R[0]**2 + R[1]**2) > (L-W/2)**2 and (R[0]**2 + R[1]**2) < (L+W/2)**2) H=kwant.Builde...
<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 see that the Aharonov-Bohm effect contains several harmonics Step2: Now run it, don't forget to change the x-scale of the plot.
15,655
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from properimage import single_image as s %matplotlib inline pixel = np.random.random((128,128))*5. # Add some stars to it star = [[35, 38, 35], [38, 90, 39], [35, 39, 34]] for i in range(25): x, y = np.random.randint(...
<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 see that the img object created automatically produces an output Step2: If you would like to acces the data inside the object img just a...
15,656
<ASSISTANT_TASK:> Python Code: !gvim data/SF_Si_bulk/invar.in %cd data/SF_Si_bulk/ %run ../../../../../Code/SF/sf.py cd ../../../ from __future__ import print_function import numpy as np import matplotlib.pyplot as plt # plt.rcParams['figure.figsize'] = (9., 6.) %matplotlib inline sf_c = np.genfromtxt( 'data/SF...
<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 I can run my script Step2: Not very elegant, I know. It's just for demo pourposes. Step3: I have first to import a few modules/set up a fe...
15,657
<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: Feature Engineering using TFX Pipeline and TensorFlow Transform Step2: Install TFX Step3: Did you restart the runtime? Step4: Set up variable...
15,658
<ASSISTANT_TASK:> Python Code: import os import math from zipfile import ZipFile from urllib.request import urlretrieve import numpy as np import pandas as pd import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.layers import StringLookup import matplotlib.pyplo...
<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: Prepare the data Step2: Create train and eval data splits Step3: Define dataset metadata and hyperparameters Step4: Train and evaluate the mo...
15,659
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'csiro-bom', 'sandbox-1', 'landice') # 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...
15,660
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from matplotlib import colors from matplotlib.font_manager import FontProperties %matplotlib inline from keras.models import model_from_json from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.la...
<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 I load the pre-generated artificial data required for the LSTM training and testing. Note that I have used 3000 and 300 images for training ...
15,661
<ASSISTANT_TASK:> Python Code: # Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE...
<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: TF-Hub CORD-19 Swivel 埋め込みを探索する Step2: 埋め込みを分析する Step3: 埋め込みが異なる用語の意味をうまく捉えていることが分かります。それぞれの単語は所属するクラスタの他の単語に類似していますが(「コロナウイルス」は「SARS」や「MERS」と...
15,662
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt from netgraph import Graph edges = [(0, 1), (1, 1)] Graph(edges, node_color='red', node_size=4.) plt.show() import numpy as np import matplotlib.pyplot as plt from netgraph import Graph Graph([(0, 1), (1, 2), (2, 0)], edge_color={(0, 1) : 'g', (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: Using a dictionary mapping individual nodes or individual edges to a property Step2: By directly manipulating the node and edge artists.
15,663
<ASSISTANT_TASK:> Python Code: %pylab inline matplotlib.style.use('ggplot') # dataframes! import pandas # Construct dataframe columns = ['eggs','sausage','bacon'] indices = ['Novel A', 'Novel B', 'Novel C'] dtm = [[50,60,60],[90,10,10], [20,70,70]] dtm_df = pandas.DataFrame(dtm, columns = columns, index = indices) # 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: Create a DTM with a Few Pseudo-Texts Step2: Visualize Step3: Vectors Step4: Vector Semantics Step5: Word2Vec Step6: Corpus Description Step...
15,664
<ASSISTANT_TASK:> Python Code: %matplotlib inline from cmt.components import Cem cem = Cem() print cem.get_output_var_names() cem.get_input_var_names() angle_name = 'sea_surface_water_wave__azimuth_angle_of_opposite_of_phase_velocity' print "Data type: %s" % cem.get_var_type(angle_name) print "Units: %s" % cem.get_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: Import the Cem class, and instantiate it. In Python, a model with a BMI will have no arguments for its constructor. Note that although the class...
15,665
<ASSISTANT_TASK:> Python Code: df = pd.read_csv('data/test_data2.csv', encoding='latin-1') print(len(df)) df.head() df['Released'] = pd.to_datetime(df['Released']) df['Year'] = pd.DatetimeIndex(df['Released']).year df['Month'] = pd.DatetimeIndex(df['Released']).month df.head() import plotly.plotly as py from plotly.to...
<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: Convert dates to datetime objects Step2: fig = FF.create_scatterplotmatrix(df_a, diag='box', index='Prod_Budget', Step3: Log Transform
15,666
<ASSISTANT_TASK:> Python Code: # Let's handle units from astropy import units as u # Structure to map healpix' levels to their angular sizes # healpix_levels = { 0 : 58.63 * u.deg, 1 : 29.32 * u.deg, 2 : 14.66 * u.deg, 3 : 7.329 * u.deg, 4 : 3.665 * u.deg, 5 : 1.832 * u.deg, 6 : ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step4: The libraries we can use to generate/manipulate Healpix/MOC maps are Step5: Let's do the same with healpix_util now Step6: MOCpy for visualizi...
15,667
<ASSISTANT_TASK:> Python Code: import tensorflow as tf from tensorflow.python.client import timeline import pylab import numpy as np import os %matplotlib inline %config InlineBackend.figure_format = 'retina' tf.logging.set_verbosity(tf.logging.INFO) tf.reset_default_graph() config = tf.ConfigProto( log_device_plac...
<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: Reset TensorFlow Graph Step2: Create TensorFlow Session Step3: Generate Model Version (current timestamp) Step4: Load Model Training and Test...
15,668
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from math import pi def y(x): return np.cos(pi*x) x = np.linspace(-1, 1, 100) X = np.random.uniform(-1, 1, 25) X_data = X.reshape(25, 1) y_obs_list = [] for i in range(len(X)): y_o...
<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 will begin by stating our "true model", defined as $y = \cos(\pi x)$. Step2: We now add some random "noise" to it in order to generate 25 d...
15,669
<ASSISTANT_TASK:> Python Code: from veneer.manage import start, create_command_line, kill_all_now import veneer veneer_install = 'D:\\src\\projects\\Veneer\\Compiled\\Source 4.1.1.4484 (public version)' source_version = '4.1.1' cmd_directory = 'E:\\temp\\veneer_cmd' path = create_command_line(veneer_install,source_vers...
<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: Also as before, we need a copy of the Veneer client for each copy of the server Step2: The catchment Step3: Describing the PEST 'Job' Step4: ...
15,670
<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...
15,671
<ASSISTANT_TASK:> Python Code: from IPython.display import display from sympy import symbols, simplify, sympify, expand from sympy import init_printing from sympy import Eq, Function from clebschVector import ClebschVec from clebschVector import div, grad, gradPerp, advVec from common import rho, theta, poisson from co...
<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: Calculation of the $E\times B$ advection Step2: Defining $\mathbf{u}_E$ Step3: NOTE Step4: Calculation of $\mathbf{u}E\cdot\nabla \left(n\nab...
15,672
<ASSISTANT_TASK:> Python Code: from nipype import Node, Workflow from nipype.interfaces.fsl import SliceTimer, MCFLIRT, Smooth # Initiate a node to correct for slice wise acquisition slicetimer = Node(SliceTimer(index_dir=False, interleaved=True, time_repetiti...
<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, we can import the interfaces that we want to use for the preprocessing. Step2: Next, we will put the three interfaces into a node and defi...
15,673
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.model_selection import train_test_split from sklearn.ensemble import VotingCla...
<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: Exploratory Data Analysis Step2: Observations Step3: Training and Validation Split Step4: Image Downloading Step5: Function to download test...
15,674
<ASSISTANT_TASK:> Python Code: %matplotlib inline # All the imports from __future__ import print_function, division from math import * import random import sys import matplotlib.pyplot as plt # TODO 1: Enter your unity ID here __author__ = "tchhabr" class O: Basic Class which - Helps dynamic updates ...
<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: Genetic Algorithm Workshop Step11: The optimization problem Step12: Great. Now that the class and its basic methods is defined, we move on to ...
15,675
<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 classes from thinkbayes2 from thinkbayes2 import Pmf, Suite import ...
<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: Interpreting medical tests Step2: Assumptions and interpretation Step3: So there is a 1.56% chance that this patient has cancer, given that th...
15,676
<ASSISTANT_TASK:> Python Code: import json my_tweets = json.load(open('my_tweets.json')) for id_, tweet_info in my_tweets.items(): print(id_, tweet_info) break def run_vader(nlp, textual_unit, lemmatize=False, parts_of_speech_to_consider=set(), verbose=...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Exercise 3 Step4: Exercise 3a
15,677
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy import linalg import mne from mne.datasets import sample from mne.viz import plot_sparse_source_estimates data_path = sample.data_path() fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' ave_fname = data_path + '/MEG/sample/sample_audv...
<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: Auxiliary function to run the solver Step4: Define your solver Step5: Apply your custom solver Step6: View in 2D and 3D ("glass" brain like 3...
15,678
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline def LSCE(x, y): beta_1 = np.sum((x - np.mean(x))*(y-np.mean(y))) / np.sum((x-np.mean(x))*(x-np.mean(x))) beta_0 = np.mean(y) - beta_1 * np.mean(x) return beta_0, beta_1 advertising = pd.r...
<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 difference between the population regression line adn the least squres lien many seem quite confusing. The answer is using a sample to estim...
15,679
<ASSISTANT_TASK:> Python Code: import math def isPower(x , y ) : res1 = math . log(y ) // math . log(x ) res2 = math . log(y ) // math . log(x ) return(res1 == res2 )  def check(n ) : x =(n + 7 ) // 8 if(( n + 7 ) % 8 == 0 and isPower(10 , x ) ) : return True  else : return False   n = 73 ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
15,680
<ASSISTANT_TASK:> Python Code: # make our x array x = np.linspace(-4, 4, 801) # f(x) = x^2 def f(x): return x**2 # derivative of x^2 is 2x def f_prime(x): return 2*x # take a look at the curve plt.plot(x, f(x), c='black') sns.despine(); # starting position on the curve x_start = -4.0 # looking at the values 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: Step1: Let's assume we start at the top of the curve, at x = -4, and want to get down to x=0. Step2: In this algorithm, alpha is known as the "learnin...
15,681
<ASSISTANT_TASK:> Python Code: import numpy as np import seaborn as sns import pandas as pd from matplotlib import pyplot as plt, animation %matplotlib notebook #%matplotlib inline sns.set_context("paper") # interactive imports import plotly import cufflinks as cf cf.go_offline(connected=True) plotly.offline.init_noteb...
<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: Information Theory Step2: Maximum entropy for a discrete random variable is obtained with a uniform distribution. For a continuous random varia...
15,682
<ASSISTANT_TASK:> Python Code: from pseudo_spectral_projection import gauss_quads gauss_nodes = [nodes for nodes, _ in gauss_quads] from monte_carlo_integration import sobol_samples sobol_nodes = [sobol_samples[:, :nodes.shape[1]] for nodes in gauss_nodes] from matplotlib import pyplot pyplot.rc("figure", figsize=[12,...
<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 number of Sobol samples to use at each order is arbitrary, but for Step2: Evaluating model solver Step3: Select polynomial expansion Step4...
15,683
<ASSISTANT_TASK:> Python Code: import larch, pandas, os, gzip larch.__version__ from larch.data_warehouse import example_file with gzip.open(example_file("arc"), 'rt') as previewfile: print(*(next(previewfile) for x in range(70))) itin = pandas.read_csv(example_file("arc"), index_col=['id_case','id_alt']) itin.in...
<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 example itinerary choice described here is based on data derived from a ticketing database Step2: The first line of the file contains colum...
15,684
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division %matplotlib inline %precision 6 import warnings warnings.filterwarnings('ignore') from thinkbayes2 import Pmf, Cdf import thinkplot import numpy as np from numpy.fft import fft, ifft from inspect import getsourcelines def show_code(func): ...
<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: Playing dice with the universe Step2: Initially the "probabilities" are all 1, so the total probability in the Pmf is 6, which doesn't make a l...
15,685
<ASSISTANT_TASK:> Python Code: %pylab inline from pyseidon import * Station? station=Station('http://ecoii.acadiau.ca/thredds/dodsC/ecoii/test/Station3D_dngrid_BF_20130730_20130809.nc') print station.Grid.name flowDir, velNorm = station.Util2D.flow_dir('GP_120726_BPa') flowDir, velNorm = station.Util2D.flow_dir('GP...
<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. PySeidon - Station object initialisation Step2: Star here means all. Usually this form of statements would import the entire library. In th...
15,686
<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...
15,687
<ASSISTANT_TASK:> Python Code: import pandas as pd # Start by importing the tweets data X = pd.read_csv('../datasets/tweets.csv') X.shape X.columns X.info() X.head(5) min(X.Avg) max(X.Avg) X.Avg.hist(); corpusTweets = X.Tweet.tolist() # get a list of all tweets, then is easier to apply preprocessign to each item #...
<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: It contains 1181 tweets (as text) and one manually labeled sentiment. Step2: 2 means very positive, 0 is neutral and -2 is very negative Step3:...
15,688
<ASSISTANT_TASK:> Python Code: import logging from conf import LisaLogging LisaLogging.setup() # Generate plots inline %matplotlib inline import os # Support to access the remote target import devlib from env import TestEnv # RTApp configurator for generation of PERIODIC tasks from wlgen import RTA, Ramp # Setup targ...
<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 required modules Step2: Target Configuration Step3: Workload Execution and Power Consumptions Samping Step4: Power Measurements Data
15,689
<ASSISTANT_TASK:> Python Code: import pandas as pd ef = pd.read_excel('EIA CO2 factors.xlsx', header=1, skip_footer=1, index_col='EIA Fuel Code') ef.columns = [name.strip() for name in ef.columns] ef['Link'] = 'https://www.eia.gov/electricity/annual/html/epa_a_03.html' ef.rename_axis({'Factor (Kilogr...
<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: Add EPA emission factors for fossil fuels not included in the EIA file Step2: Add non-fossil emission factors for a total emission factor colum...
15,690
<ASSISTANT_TASK:> Python Code: import numpy as np #For numerical programming and multi-dimensional arrays from pandas import date_range #For date-rate generation from bqplot import LinearScale, Lines, Axis, Figure, DateScale, ColorScale security_1 = np.cumsum(np.random.randn(150)) + 100. security_2 = np.cumsum(np.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: Random Data Generation Step2: Basic Line Chart Step3: The x attribute refers to the data represented horizontally, while the y attribute refer...
15,691
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn as sbn import pandas as pd from uuid import uuid4 from lpde.geometry import WidthOf, Window, PointAt, BoundingBox, Mapper, Grid from lpde.estimators import ParallelEstimator from lpde.estimators.datatypes import Event, Degr...
<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: Notebook settings Step2: Density Estimation Step3: Create mock data streams Step4: Timings of density estimation Step5: Timings
15,692
<ASSISTANT_TASK:> Python Code: import math import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage import tensorflow as tf from tensorflow.python.framework import ops from cnn_utils import * %matplotlib inline np.random.seed(1) # Loading the data (sig...
<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 the next cell to load the "SIGNS" dataset you are going to use. Step2: As a reminder, the SIGNS dataset is a collection of 6 signs represen...
15,693
<ASSISTANT_TASK:> Python Code: import numpy as np import scanpy.api as sc from anndata import AnnData from numpy.random import negative_binomial, binomial, seed seed(1234) # n_cluster needs to be smaller than n_simulated_cells, n_marker_genes needs to be smaller than n_simulated_genes n_simulated_cells=1000 n_simulate...
<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, data following a (zero-inflated) negative binomial (ZINB) distribution is created for testing purposes. Test size and distribution parame...
15,694
<ASSISTANT_TASK:> Python Code: # pip install cartoframes import pandas as pd stores_df = pd.read_csv('http://libs.cartocdn.com/cartoframes/files/starbucks_brooklyn.csv') stores_df.head() from cartoframes.auth import set_default_credentials set_default_credentials('creds.json') from cartoframes.data.services import G...
<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 other ways to install CARTOframes, check out the Installation guide. Step2: To display your stores as points on a map, you first have to co...
15,695
<ASSISTANT_TASK:> Python Code: def parse_barcodes(bcfile, bc_id='BC'): res = {} with open(bcfile, 'r') as fi: for line in fi: fields = line.strip().split(',') if fields[0].startswith(bc_id): res[fields[0]] = fields[1] return res def parse_exp_config(expfile, 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: Read the counts table Step2: Normalize to UTR length Step3: Notation Step4: Principal Component Analisys (PCA) Step5: Aside Step6: +BCM sam...
15,696
<ASSISTANT_TASK:> Python Code: %matplotlib inline import nsfg df = nsfg.ReadFemPreg() df df.birthord.value_counts().sort_index() df.prglngth.value_counts().sort_index() df.agepreg.hist(by=df.birthord) df.totalwgt_lb.mean() df['totalwgt_kg'] = df.totalwgt_lb / 2.20462 df.totalwgt_kg.mean() df.finalwgt.value_counts...
<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: Print value counts for <tt>birthord</tt> and compare to results published in the codebook Step2: Print value counts for <tt>prglngth</tt> and c...
15,697
<ASSISTANT_TASK:> Python Code: path = get_file('nietzsche.txt', origin="https://s3.amazonaws.com/text-datasets/nietzsche.txt") text = open(path).read() print('corpus length:', len(text)) chars = sorted(list(set(text))) vocab_size = len(chars)+1 print('total chars:', vocab_size) chars.insert(0, "\0") ''.join(chars[1:-6...
<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: Sometimes it's useful to have a zero value in the dataset, e.g. for padding Step2: Map from chars to indices and back again Step3: idx will be...
15,698
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline before = np.loadtxt('Data/questionnaire_before.txt',delimiter=',') after = np.loadtxt('Data/questionnaire_after.txt',delimiter=',') form = np.loadtxt('Data/questionnaire_form.txt',delimiter=',') questions = np.array(ran...
<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: As you can see above, the data as provided were arranged with rows for each question, and the responses of each individual as the columns. Step2...
15,699
<ASSISTANT_TASK:> Python Code: success = True # We'll use this to keep track of the various tests failures = [] try: import numpy as np import scipy print "numpy and scipy imported -- success!" except: success = False msg = "* There was a problem importing numpy or scipy. You will definitely need 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: You should see a simple plot below the next cell. Step5: There should be a Basemap plot displayed below this cell.