Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
1,000
<ASSISTANT_TASK:> Python Code: from sksurv.datasets import load_veterans_lung_cancer data_x, data_y = load_veterans_lung_cancer() data_y import pandas as pd pd.DataFrame.from_records(data_y[[11, 5, 32, 13, 23]], index=range(1, 6)) %matplotlib inline import matplotlib.pyplot as plt from sksurv.nonparametric import kap...
<SYSTEM_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 easily see that only a few survival times are right-censored (Status is False), i.e., most veteran's died during the study period (Status...
1,001
<ASSISTANT_TASK:> Python Code: # To use Planet's CLI from this Notebook, begin your line as follows: !planet data # < add your own code here > # To use Planet's API, you'll probably begin by importing your favorite HTTP toolkit, e.g.: import requests from requests.auth import HTTPBasicAuth # Your Planet API key is ava...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Option 2 Step2: Option 3 Step3: Step 3. Extract the Coefficients Step4: Note that the coefficients are all of order 1e-5, and that the coeffi...
1,002
<ASSISTANT_TASK:> Python Code: # Use the functions from another notebook in this notebook %run Shared-Functions.ipynb # Import our usual libraries import numpy as np import pandas as pd import math import matplotlib.pyplot as plt %matplotlib inline import os # Load the housing prices dataset file_url = data_dir + os.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: The Business Problem Step2: Step 1 Step3: Exercise 1 Step4: Step 2 Step5: Step 2b Step6: Step 3 Step7: And here's what the expression for ...
1,003
<ASSISTANT_TASK:> Python Code: dtarget = lambda x: multivariate_normal.pdf(x, mean=(3, 10), cov=[[1, 0], [0, 1]]) x1 = np.linspace(-6, 12, 101) x2 = np.linspace(-11, 31, 101) X, Y = np.meshgrid(x1, x2) Z = np.array(map(dtarget, zip(X.flat, Y.flat))).reshape(101, 101) plt.figure(figsize=(10,7)) plt.contour(X, Y, Z) 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: Step3: The surface of interest will be $U(q) = -\log{f(q)}$ Step4: Tuning parameters Step5: Banana-shaped target distribution Step9: NUTS Sampler St...
1,004
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cams', 'sandbox-2', 'seaice') # 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: 2...
1,005
<ASSISTANT_TASK:> Python Code: MAIL_SERVER = "mail.****.com" FROM_ADDRESS = "noreply@****.com" TO_ADDRESS = "my_friend@****.com" from sender import Mail mail = Mail(MAIL_SERVER) mail.fromaddr = ("Geheime aanbidder", FROM_ADDRESS) mail.send_message("Raspberry Pi heeft een boontje voor je", to=TO_ADDRESS, body="Hey lekk...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Een mail verzenden is, mits het inladen van de juiste bibliotheek, een fluitje van een cent... Step2: ... maar als we het wat verder doordrijve...
1,006
<ASSISTANT_TASK:> Python Code: from IPython.display import HTML, Javascript HTML(<canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas>) Javascript( var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 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: Balle rebondissante Step3: Le code Javscript qui suit va être ajouté à celui du notebook. Il s'active dès que le curseur passe au-dessus du cad...
1,007
<ASSISTANT_TASK:> Python Code: !pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro # first, we need some imports import os from IPython.display import set_matplotlib_formats from matplotlib import pyplot as plt import numpy as np import pandas as pd from jax import numpy as jnp from jax import random from j...
<SYSTEM_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: Look at the data info, we know that there are missing data at Age, Cabin, and Embarked columns. Although Cabin is an important f...
1,008
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd #Some helper functions for plotting and drawing lines def plot_points(X, y): admitted = X[np.argwhere(y==1)] rejected = X[np.argwhere(y==0)] plt.scatter([s[0][0] for s in rejected], [s[0][1] for s in reject...
<SYSTEM_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 and plotting the data Step2: TODO Step3: Training function Step4: Time to train the algorithm!
1,009
<ASSISTANT_TASK:> Python Code: %%time # flag to indicate whether we're inside a <text> tag as we iterate over the file line by line in_text = False # Set of tags to remove text_to_remove = set(['<code>', '</code>', '<code/>', '<br>', '<br/>', '</br>']) with open('EFWritingData.xml') as f_in, open('EFWritingData_new.xml...
<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: Extract Records from XML Step3: Save the Records as a Pandas DataFrame
1,010
<ASSISTANT_TASK:> Python Code: import tensorflow as tf from tensorflow import keras import keras_cv from tensorflow.keras import layers from keras_cv import utils from keras_cv.layers import BaseImageAugmentationLayer import matplotlib.pyplot as plt tf.autograph.set_verbosity(0) def imshow(img): img = img.astype(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: First, let's implement some helper functions to visualize intermediate results Step2: BaseImageAugmentationLayer Introduction Step3: Our layer...
1,011
<ASSISTANT_TASK:> Python Code: %pylab --no-import-all inline from scipy.stats import linregress, pearsonr all_sets = list() for i in range(0, 8, 2): x, y = np.loadtxt("anscombe.dat", usecols=(i, i+1), skiprows=1, unpack=True) all_sets.append((x, y)) print(all_sets[0][0]) print(all_sets[0][1]) def show_stat(da...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lecture des données Step2: Calcul des propriétés statistiques Step3: Représentation graphique des données
1,012
<ASSISTANT_TASK:> Python Code: # Load library import pandas as pd # Create datetimes time_index = pd.date_range('01/01/2010', periods=5, freq='M') # Create data frame, set index df = pd.DataFrame(index=time_index) # Create feature df['Stock_Price'] = [1,2,3,4,5] # Calculate rolling mean df.rolling(window=2).mean() # ...
<SYSTEM_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 Date Data Step2: Create A Rolling Time Window Of Two Rows
1,013
<ASSISTANT_TASK:> Python Code: #!pip install -I "phoebe>=2.3,<2.4" import matplotlib matplotlib.rcParams['text.usetex'] = True matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' from matplo...
<SYSTEM_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: First we'll define the system parameters Step3: And then create t...
1,014
<ASSISTANT_TASK:> Python Code: import os import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split from sklearn import cross_validation, metrics from sklearn.naive_bayes import BernoulliNB from time import time from sklearn import preprocessing from sklearn.pipeline import Pipeline fr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We load the data in a Pandas dataframe as always and specify our column names. Step2: We'll have a look at our dataset Step3: Now this data co...
1,015
<ASSISTANT_TASK:> Python Code: %%bash source activate secapr_env secapr locus_selection -h import sys sys.path.append("../../src") import plot_contig_data_function as secapr_plot contig_input_file = '../../data/processed/target_contigs/match_table.txt' alignment_folder = '../../data/processed/alignments/contig_alignme...
<SYSTEM_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 function will compile the average read-coverage for each locus and sample and will select the n loci with the best coverage accross all sam...
1,016
<ASSISTANT_TASK:> Python Code: import pandas as pd import pastas as ps import matplotlib.pyplot as plt ps.set_log_level("ERROR") ps.show_versions() # Load input data head = pd.read_csv("../data/B32C0639001.csv", parse_dates=['date'], index_col='date', squeeze=True) evap = ps.read_knmi("../data/et...
<SYSTEM_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 first example model Step2: 2. Creating and calibrating the model Step3: 3. Computing and visualizing the SGI Step4: Second Example Step5:...
1,017
<ASSISTANT_TASK:> Python Code: MoocVideo("GQLfs4i22ms", src_location="2.1-intro") # matplotlib.rcParams['axes.color_cycle'] = 'k' f = plt.figure(figsize=[9, 3.5]) ax0 = f.add_subplot(1, 2, 1) ax0.set_xlabel('$k$') ax0.set_xticks([-1.0, 0.0, 1.0]) ax0.set_ylabel('$E$') ax0.set_xlim([-1.03, 1.03]) ax0.set_ylim([-1.0, 1....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Small parameters Step2: The need for spin Step3: We now see that we resolved the first problem Step4: Of course we didn't break bulk-edge cor...
1,018
<ASSISTANT_TASK:> Python Code: t = np.arange(0,np.pi, 1/30000) freq = 2 # in Hz phi = 0 amp = 1 k = 2*np.pi*freq*t + phi cwv = amp * np.exp(-1j* k) # complex sine wave fig, ax = plt.subplots(2,1, figsize=(8,4), sharex=True) ax[0].plot(t, np.real(cwv), lw=1.5) ax[0].plot(t, np.imag(cwv), lw=0.5, color='orange') ax[0].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: A complex wave is a time series of imaginary numbers. As a such, it has a real part, and an imaginary part for every time. To visualized a compl...
1,019
<ASSISTANT_TASK:> Python Code: # Import Pandas and Numpy import pandas as pd import numpy as np # Make Series of count data and visaulize series counts = pd.Series([223, 43, 53, 24, 43]) counts # What datatype is the counts object? type(counts) # Make Series of count data with Gene Symbols rna_counts = pd.Series([50...
<SYSTEM_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.4 Data Structures Step2: What datatype is the counts object? Step3: 2.3 Series - String indexes Step4: 2.4 Series - Dictionary Step5: Make...
1,020
<ASSISTANT_TASK:> Python Code: %%time import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib import cm import functions as f import matplotlib_charting as mp #plt.style.use('bmh') #plt.style.use('fivethirtyeight') sns.set_style('whitegrid') %matplotlib inline pd.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: read and assign dictionary values for computed datasets Step2: view of first 5 rows of calculated dataset corresponding to proposal 1 Step3: a...
1,021
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt from string import punctuation import urllib.request files=['negative.txt','positive.txt'] path='http://www.unc.edu/~ncaren/haphazard/' for file_name in files: urllib.request.urlretrieve(path+file_name,file_name) pos_sent = open("posi...
<SYSTEM_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 homework we are going to use new data downloaded in the last week. The file names are Step2: So, for example, the file name for Barac...
1,022
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import dateutil.parser import datetime from urllib.request import urlopen, Request import simplejson as json def extract_reference_time(API_data_loc): Find reference time that corresponds to most complete forecast. ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Plotting HYCOM Global Ocean Forecast Data Step2: Let's choose a location near Oahu, Hawaii... Step3: Important! You'll need to replace apikey ...
1,023
<ASSISTANT_TASK:> Python Code: from sklearn.feature_extraction import DictVectorizer import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from pandas.plotting import scatter_matrix data = pd.read_csv("bank-additional-full.csv") data = pd.read_csv("bank-additional-full.csv", 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: Import Dataset Step2: See Data Step3: Looks good now. Step4: vectorise features such that text based classifications are transformed one hot ...
1,024
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() import numpy mat = numpy.zeros((5, 5)) for i in range(mat.shape[0]): for j in range(mat.shape[1]): mat[i, j] = i * 10 + j mat mat[2, 3], mat[2][3] %timeit mat[2, 3] %timeit mat[2][3] mat[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: accéder à un élément en particulier Step2: Les deux écritures ont l'air identique puisqu'elle retourne le même résultat. Néanmoins, mat[2][3] c...
1,025
<ASSISTANT_TASK:> Python Code: import pandas as pd # redefining the example dataframe data = {'country': ['Belgium', 'France', 'Germany', 'Netherlands', 'United Kingdom'], 'population': [11.3, 64.3, 81.3, 16.9, 64.9], 'area': [30510, 671308, 357050, 41526, 244820], 'capital': ['Brussels', 'Paris...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <div class="alert alert-info" style="font-size Step2: Reversing this operation, is reset_index Step3: Selecting data based on the index Step4:...
1,026
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nerc', 'hadgem3-gc31-hh', 'land') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
1,027
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn') from module_code.data import get_fremont_data df = get_fremont_data() df.head() df.resample('W').sum().plot() # ugly looking graphs. Change to seaborn. # resample daily and find the rolling sum of 365 days. ax = 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: What we got was the annual trend Step2: West side congested in the morning while the east side is congested in the everning.
1,028
<ASSISTANT_TASK:> Python Code: %pip --quiet install objax import jax.numpy as jn import numpy as np import objax # Providing explicit values jn.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) arr = np.array([1.0, 2.0, 3.0]) jn.array(arr) another_tensor = jn.array([[1.0, 2.0, 3.0], [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: After Objax is installed, you can import all necessary modules Step2: Tensors Step3: From a NumPy array Step4: From another JAX tensor Step5:...
1,029
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'gfdl-am4', 'aerosol') # 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...
1,030
<ASSISTANT_TASK:> Python Code: import os, math, time, pickle, subprocess from importlib import reload from collections import OrderedDict, defaultdict import numpy as np import pandas as pd pd.set_option('display.width', 180) import epitopepredict as ep from epitopepredict import base, sequtils, plotting, peptutils, 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: load ref genomes Step2: find orthologs in each genome Step3: predict MHC-I and MHC-II epitopes Step4: conservation Step5: Find conserved pre...
1,031
<ASSISTANT_TASK:> Python Code: def tokenize(input): pass def normalize(input): pass sample = "Hello, Mom!" tokens = tokenize(sample) # print(tokens) normalized = [normalize(token) for token in tokens] print(normalized) def tokenize(input): # tokenize on white space return input.split() def normalize(input)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Examples Step2: Use NLTK word tokenization and normalize as POS Step3: Use NLTK word tokenization and strip vowels and punctuation to normaliz...
1,032
<ASSISTANT_TASK:> Python Code: sc !ls -lh combined.csv !wc combined.csv !head combined.csv !gshuf -n 100000 -o sample.csv combined.csv !wc sample.csv !head sample.csv !csvsort --no-header-row -c1 sample.csv > sample-sorted.csv !head sample-sorted.csv subjects_sample = sc.textFile("sample.csv") subjects_sample.cou...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Great, we're good to go. Now let's take a look at the data. See the README in this directory for background on how we generated the CSV file w...
1,033
<ASSISTANT_TASK:> Python Code: %matplotlib notebook %matplotlib inline import numpy as np import matplotlib.pyplot as plt import particlesim.api import particlesim.test_total_potential as test import particlesim.total_potential as pot import time import particlesim.helpers_for_tests as create from mpl_toolkits.mplot3d ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Potential Calculation Step2: Longrange Potential Step3: Parameter for Na+ and Cl- Step4: Calculate Lennard Jones Potential of Na+ and Cl- Ste...
1,034
<ASSISTANT_TASK:> Python Code: from kafka import KafkaConsumer import uuid import json consumer = KafkaConsumer(bootstrap_servers='', value_deserializer=lambda s: json.loads(s, encoding='utf-8'), auto_offset_reset='smallest', group_id=uuid.uu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Simple graph analytics for the Twitter stream Step2: Building the directed graph Step3: Most retweeted users Step4: Top 10 Pageranked users S...
1,035
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pylab as plt from scipy.integrate import odeint from scipy.integrate import solve_ivp from scipy.misc import derivative import seaborn as sns def set_up_fonts(): sns.reset_orig() import matplotlib matplotlib.rcParams["pdf.fonttype"] = 42 ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Display variables Step2: Defining the Euler updates (gradient descent) Step3: Dirac GAN
1,036
<ASSISTANT_TASK:> Python Code: from pandas import Series, DataFrame import pandas as pd from pandas import Series a = [4, 5, 2, -4] obj = Series(a) obj obj2=obj+obj obj2 obj.values obj.index # 注意,如果使用python 2,显示的结果可能在形式上有点不同。 obj2 = Series([4, 5, 2 ,-4], index=['d', 'b', 'a', '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: 这有点像之前那样的,我们约定 np 代表 numpy。因为 Series 和 DataFrame 用的次数非常多,所以将其引入命名空间会更加方便 Step2: 从上面我们可以看到,Series 的字符串表现形式为:索引在左边,值在右边。因为我们上面没有为数据指定特殊的索引,所以系统会自...
1,037
<ASSISTANT_TASK:> Python Code: # In case you are not familiar with Jupyter Notebook, click here and press Ctrl+Enter to run this cell. import projectk as vm vm print(dir(vm)) vm.stack vm.dictate("123") vm.stack vm.dictate("456").stack vm.dictate("code hi! print('Hello World!!') end-code"); # define the "hi!" coma...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Python standard function dir(obj) gets all member names of an object. Lest's see what are in the FORTH kernel vm Step2: I only want you to see ...
1,038
<ASSISTANT_TASK:> Python Code: # Import the libraries that we'll be using import numpy as np import pandas as pd import hydropy as hp # Set the notebook to plot graphs in the output cells. %matplotlib inline # Use HydroCloud.org to find a stream gauge to investigate. # Click on the red points to find the site number. ...
<SYSTEM_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 USGS data into a dataframe
1,039
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import torch %matplotlib inline import matplotlib.pyplot as plt import numdifftools as nd from scipy.optimize import minimize import numpy as np %matplotlib inline import matplotlib.pyplot as plt from scipy.stats import multivariate_normal ### BEGIN...
<SYSTEM_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: BEGIN Solution Step5: <br>
1,040
<ASSISTANT_TASK:> Python Code: from pubchempy import get_compounds for compound in get_compounds('glucose', 'name'): print(compound.cid) print(compound.isomeric_smiles) from pubchempy import Compound vioxx = Compound.from_cid(5090) print vioxx.molecular_formula print vioxx.molecular_weight print vioxx.xlogp <...
<SYSTEM_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 how does this work behind the scenes?
1,041
<ASSISTANT_TASK:> Python Code: ##Do all of the imports and setup inline plotting %matplotlib notebook import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA from scipy.interpolate import InterpolatedUnivariateSpline from ripser import ripser from persim import plot_diagrams import scip...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <h1>Audio Applications</h1> Step2: <h1>Biphonation Overview</h1> Step3: The code below will extract a subsection of the signal and perform a s...
1,042
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf with open('reviews.txt', 'r') as f: reviews = f.read() with open('labels.txt', 'r') as f: labels = f.read() reviews[:1000] from string import punctuation all_text = ''.join([c for c in reviews if c not in punctuation]) reviews = all_text...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data preprocessing Step2: Encoding the words Step3: Encoding the labels Step4: If you built labels correctly, you should see the next output....
1,043
<ASSISTANT_TASK:> Python Code: #!pip install -I "phoebe>=2.4,<2.5" 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', times=[0,1], dataset='lc01', overwrite=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: As always, let's do imports and initialize a logger and a new Bundle. Step2: Passband Options Step3: As you might expect, if you want to pass ...
1,044
<ASSISTANT_TASK:> Python Code: # !pip install pycuda %reset -f import pycuda from pycuda import compiler import pycuda.driver as cuda import numpy import numpy as np from pycuda.compiler import SourceModule cuda.init() print("%d device(s) found." % cuda.Device.count()) for ordinal in range(cuda.Device.count(...
<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: Simple addition on the GPU Step3: Plot the Sigmoid function Step4: Timing Numpy vs. PyCUDA ...
1,045
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline def distance_meme_longueur(m1, m2): if len(m1) != len(m2): raise ValueError("m1 et m2 sont de longueurs différentes") d = 0 for c1, c2 in zip(m1, m2): if c1 != c2: 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: Enoncé Step2: On vérifie que la fonctionne jette bien une exception lorsque les chaînes de caractères sont de longueurs différentes. Step3: Q2...
1,046
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline from sklearn.datasets import load_files corpus = load_files("../data/") doc_count = len(corpus.data) print("Doc count:", doc_count) assert doc_count is 56, "Wrong number of documents loaded, should ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Input Step2: Vectorizer Step3: Models Step4: Pipelines Step5: Gridsearch Step6: Training Step7: Evaluation Step8: Visual Inspection Step9...
1,047
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import pastas as ps import matplotlib.pyplot as plt ps.show_versions() # Default Settings cutoff = 0.999 meanstress = 1 up = True responses = {} exp = ps.Exponential(up=up, meanstress=meanstress, cutoff=cutoff) responses["Exponential"] = exp gamma =...
<SYSTEM_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 use of response functions Step2: Scaling of the step response functions Step3: Parameter settings Step4: Comparison to classical analytic...
1,048
<ASSISTANT_TASK:> Python Code: class Car: Our Car class def __init__(self, year, make, model, top_speed, acceleration ): Car Constructor function self.year = year self.make = make ...
<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: Simulating a Drag Race Step15: Running the Race Step17: Let's Race! Step18: Now, let's build a race with these cars. Step19: The race is rea...
1,049
<ASSISTANT_TASK:> Python Code: import pandas as pd import pandas as pd import matplotlib.pyplot as plt # package for doing plotting (necessary for adding the line) import statsmodels.formula.api as smf # package we'll be using for linear regression %matplotlib inline df = pd.read_csv('../data/hanford.csv') df df.des...
<SYSTEM_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. Read in the hanford.csv file Step2: County Step3: 3. Calculate the basic descriptive statistics on the data Step4: 4. Calculate the coeffi...
1,050
<ASSISTANT_TASK:> Python Code: import os # Setup the API Key from the `PL_API_KEY` environment variable PLANET_API_KEY = os.getenv('PL_API_KEY') # If you're following along with this notebook, you can enter your API Key on the following line, and uncomment it: # PLANET_API_KEY = 'YOUR_KEY_HERE' assert PLANET_API_KEY, '...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Check data api connection Step3: Data API Search Step5: Geometry helper Step6: Make a geometry dict for coordinates in San Francisco Step7: ...
1,051
<ASSISTANT_TASK:> Python Code: # database parameters ts_length = 100 data_dir = '../db_files' db_name = 'default' dir_path = data_dir + '/' + db_name + '/' # clear file system for testing if not os.path.exists(dir_path): os.makedirs(dir_path) filelist = [dir_path + f for f in os.listdir(dir_path)] for f in filelist...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Initialize database Step2: Generate data Step3: Insert data Step4: Inspect data Step5: Does the data match? Step6: Did the triggers work? S...
1,052
<ASSISTANT_TASK:> Python Code: from keras.models import Sequential from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate from keras.models import Model from keras.layers.normalization import BatchNormalization from keras.layers.pooling import MaxPooling2D, AveragePooling2D from keras.layers.mer...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 0 - Naive Face Verification Step3: Expected Output Step4: Expected Output Step5: Here're some examples of distances between the encodings be...
1,053
<ASSISTANT_TASK:> Python Code: from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Flower power Step2: ConvNet Codes Step3: Below I'm running images through the VGG network in batches. Step4: Building the Classifier Step5: ...
1,054
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import os import logging import json import warnings try: raise ImportError import pyLDAvis.gensim CAN_VISUALIZE = True pyLDAvis.enable_notebook() from IPython.display import display except ImportError: ValueError("SKIP: please...
<SYSTEM_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 up corpus Step2: Set up two topic models Step3: Using U_Mass Coherence Step4: View the pipeline parameters for one coherence model Step5:...
1,055
<ASSISTANT_TASK:> Python Code: import datetime import six print( "packages imported at " + str( datetime.datetime.now() ) ) %pwd %run ../django_init.py # start to support python 3: from __future__ import unicode_literals from __future__ import division #===============================================================...
<SYSTEM_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 - virtualenv jupyter kernel Step2: Setup - Initialize Django Step3: Setup R
1,056
<ASSISTANT_TASK:> Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt import pymks from pymks.datasets import make_cahn_hilliard n = 41 n_samples = 400 dt = 1e-2 np.random.seed(99) = make_cahn_hilliard(n_samples=n_samples, size=(n, n), dt=dt) from pymk...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Modeling with MKS Step2: The function make_cahnHilliard generates n_samples number of random microstructures, X, and the associated updated mic...
1,057
<ASSISTANT_TASK:> Python Code: # 为这个项目导入需要的库 import numpy as np import pandas as pd from time import time from IPython.display import display # 允许为DataFrame使用display() # 导入附加的可视化代码visuals.py import visuals as vs # 为notebook提供更加漂亮的可视化 %matplotlib inline # 导入人口普查数据 data = pd.read_csv("census.csv") # 成功 - 显示第一条记录 display(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 练习:数据探索 Step2: 准备数据 Step3: 对于高度倾斜分布的特征如'capital-gain'和'capital-loss',常见的做法是对数据施加一个<a href="https Step4: 规一化数字特征 Step5: 练习:数据预处理 Step6: 混洗和切...
1,058
<ASSISTANT_TASK:> Python Code: import csv import pprint with open('ballots.csv') as ballots_file: reader = csv.reader(ballots_file) ballots = list(reader) pprint.pprint(ballots, width=30) from collections import defaultdict candidates = { 'A': 0, 'B': 1, 'C': 2, 'D': 3 } def calc_pairwise_...
<SYSTEM_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 first step in the Schulze method is to calculate the pairwise preferences of the voters regarding the candidates. Step2: The second step i...
1,059
<ASSISTANT_TASK:> Python Code: # Python imports import numpy as np # Matrix and vector computation package import sklearn.datasets # To generate the dataset import matplotlib.pyplot as plt # Plotting library from matplotlib.colors import colorConverter, ListedColormap # Some plotting functions from mpl_toolkits.mplo...
<SYSTEM_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 the plot below, it's not linear separatable. Step2: Model and Cost Function Step3: Cost Function Step4: Momentum Step5: Code ...
1,060
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline data = pd.read_csv('weights_heights.csv', index_col='Index') data.plot(y='Height', kind='hist', color='red', title='Height (inch.) distribution') plt.show() 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: Считаем данные по росту и весу (weights_heights.csv, приложенный в задании) в объект Pandas DataFrame Step2: Чаще всего первое, что надо надо с...
1,061
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pylab as plt import numpy as np import math from numba import jit, njit, vectorize def add(x, y): # add code here # add code here # add code here numba_add = jit(add) # add code here %timeit add(1,2) # add code here # add code here # add code ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: What is Numba? Step2: Now, test the function, first with two scalar integers Step3: 1b) With Numpy, we can use our function to add not just sc...
1,062
<ASSISTANT_TASK:> Python Code: YouTubeVideo("IFACrIx5SZ0", start = 85, end = 95) from sklearn.datasets import load_iris iris = load_iris() x_ind = 0 y_ind = 1 X = iris.data[:,(x_ind, y_ind)] labels = iris.target print X.shape print labels.shape # this formatter will label the colorbar with the correct target names fo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: But I don't want scare people with spooky, scary math Step2: For this example, we will only use the Sepal Length and Sepal Width feature, so we...
1,063
<ASSISTANT_TASK:> Python Code: import tellurium as te; te.setDefaultPlottingEngine('matplotlib') %matplotlib inline antimony_model = '''J0: -> y; -x;J1: -> x; y;x = 1.0;y = 0.2;''' r = te.loada(antimony_model) r.simulate(0,100,1000) r.plot() import tellurium as te model = '''''' model_backup = ''' model example # ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Everything in a single tool - tellurium Step2: Antimony is a language that is analog to SBML Systems Biology Markup Language but human-readable...
1,064
<ASSISTANT_TASK:> Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. %matplotlib inline from __future__ import print_function import collections import math import numpy as np import os import random import tensorflow as tf import zipfile from matpl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Download the data from the source website if necessary. Step4: Read the data into a string. Step5: Build the dictionary and replace rare words...
1,065
<ASSISTANT_TASK:> Python Code: from phantasy.apps import Wire, WireScannerData from phantasy import Line import numpy as np # e.g.1 #data = np.loadtxt('data/case2/data_cor_2.dat') #direction = (-45, 0.2, 120) #h0, v0 = 15, -10 # e.g.2 data = np.loadtxt('data/case1/datafiles/demo3.dat') direction = (225, 0.2, 120) h0, ...
<SYSTEM_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 we know that wire AB is D_wire, wire CD is V_wire and wire EF is H_wire, build new wires with data Step2: Build wires from external data fil...
1,066
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt # YOUR CODE HERE data = np.load('decay_osc.npz') time=data['tdata'] y=data['ydata'] dy=data['dy'] plt.errorbar(time, y, dy, fmt='.k', ecolor='lightgray') plt.xlabel('x') plt.yl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Fitting a decaying oscillation Step2: Now, using curve_fit to fit this model and determine the estimates and uncertainties for the parameters
1,067
<ASSISTANT_TASK:> Python Code: # Basic imports import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime as dt import scipy.optimize as spo import sys from time import time from sklearn.metrics import r2_score, median_absolute_error %matplotlib inline %pylab inline pylab.rcParams[...
<SYSTEM_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, let's try to instantiate the best predictor that was found Step2: Let's see the range of the test set (to check that no data from the re...
1,068
<ASSISTANT_TASK:> Python Code: def my_func(a: int, b: str = 'hello') -> tuple: return (a, b) my_func(1, 'wut') my_func.__annotations__ from pynads.utils.decorators import annotate @annotate(type="Int -> String -> (Int, String)") def my_func(a, b='hello'): return (a, b) my_func.__annotations__ print(my_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: That's so much line noise. Like what. Look at that default assignment. Like, I get why the annotations are inlined with the signature. But they'...
1,069
<ASSISTANT_TASK:> Python Code: import os,sys import numpy %matplotlib inline import matplotlib.pyplot as plt sys.path.insert(0,'../utils') from mkdesign import create_design_singlecondition from nipy.modalities.fmri.hemodynamic_models import spm_hrf,compute_regressor from make_data import make_continuous_data data=make...
<SYSTEM_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 add on an activation signal to both voxels Step2: How can we address this problem? A general solution is to first run a general linea...
1,070
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd from itertools import product # from IPython.core.display import HTML # css = open('media/style-table.css').read() + open('media/style-notebook.css').read() # HTML('<style>{}</style>'.format(css)) one_toss = np.array(['H', 'T']) tw...
<SYSTEM_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 shown earlier in slide,<br> Step2: As you can see above, Product spaces(Probability spaces) get large very quickly. Step3: A Function on t...
1,071
<ASSISTANT_TASK:> Python Code: # Imports import sys import pandas as pd import csv %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (20.0, 10.0) # %load util.py #!/usr/bin/python # Util file to import in all of the notebooks to allow for easy code re-use # Calculate Percent of Attende...
<SYSTEM_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 the Data Step2: Sanitizing the Data Step3: Analysis and Visualization (V1) Step4: Analysis and Visualization (V2) Step5: HOLY SHIT
1,072
<ASSISTANT_TASK:> Python Code: from IPython.nbformat import current with open('test_slides.ipynb') as f: nb = current.read(f,'json') nb.worksheets[0].cells[18:19] print "Hola Scipy..." from numpy.random import randn data = {i : randn() for i in range(10)} data >>> from numpy.random import randn >>> 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: Genera archivos con la extensión .ipynb que se guardan en el directorio local. Step2: La representación de los objetos es más legible Step3: y...
1,073
<ASSISTANT_TASK:> Python Code: from euler import timer, Seq from math import sqrt def d(n): return (range(2, int(sqrt(n))+1) >> Seq.filter (lambda x: n%x == 0) >> Seq.map (lambda x: x if x*x == n else n/x + x) >> Seq.sum) + 1 def isAmicable(a): b = d(a) return (a == 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: Names scores Step2: Non-abundant sums Step3: Lexicographic permutations Step4: 1000-digit Fibonacci number Step5: Reciprocal cycles Step6: ...
1,074
<ASSISTANT_TASK:> Python Code: from cobra import Model, Reaction, Metabolite model = Model('example_model') reaction = Reaction('R_3OAS140') reaction.name = '3 oxoacyl acyl carrier protein synthase n C140 ' reaction.subsystem = 'Cell Envelope Biosynthesis' reaction.lower_bound = 0. # This is the default reaction.upper...
<SYSTEM_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 need to create metabolites as well. If we were using an existing model, we could use Model.get_by_id to get the appropriate Metabolite object...
1,075
<ASSISTANT_TASK:> Python Code: import os.path as op import mne from mne.datasets import sample data_path = sample.data_path() raw_empty_room_fname = op.join( data_path, 'MEG', 'sample', 'ernoise_raw.fif') raw_empty_room = mne.io.read_raw_fif(raw_empty_room_fname) raw_fname = op.join(data_path, 'MEG', 'sample', 'sa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Source estimation method such as MNE require a noise estimations from the Step2: The definition of noise depends on the paradigm. In MEG it is ...
1,076
<ASSISTANT_TASK:> Python Code: from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str statement_path = 'ras_pathway.txt' txt = open(statement_path, 'rt').read() print(txt) from indra import reach rp = reach.process_text(txt, offline=False) st = rp.statements from indra....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: II. Process text into INDRA statements using REACH parser Step2: III. Assemble an INDRA model Step3: What do the statements look like? Step4: ...
1,077
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'pre_score': [4, 24, 31, 2, 3], 'mid_score': [25, 94, 57, 62, 70], 'post_score': [5, 43, 23, 23, 51]} df = pd.DataFrame(raw_...
<SYSTEM_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 dataframe Step2: Make plot
1,078
<ASSISTANT_TASK:> Python Code: from scipy.integrate import quad import math f = lambda x: (12*x+1)/(1+math.cos(x)**2) a, b = 1993, 2017 quad(f, a, b) def romberg_rec(f, xmin, xmax, n=8, m=None): if m is None: # not m was considering 0 as None m = n assert n >= m if n == 0 and m == 0: retu...
<SYSTEM_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 try it with this function $f(x)$ on $[a,b]=[1993,2015]$ Step2: The first value is the numerical value of the integral $\int_{a}^{b} f(x) \m...
1,079
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt strike = 100 forward = 110 vol = 50 def call(k=100): def payoff(spot): if spot > k: return spot - k else: return 0 return payoff payoff = call(k=strike) #payoff(110) N = 10000 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: Those are our option and market parameters Step2: We now define our payoff function using a closure Step3: We now generate a set of Standard G...
1,080
<ASSISTANT_TASK:> Python Code: # first lets import the DATA class from skcriteria import Data data = Data( # the alternative matrix mtx=[[250, 120, 20, 800], [130, 200, 40, 1000], [350, 340, 15, 600]], # optimal sense criteria=[max, max, min, max], # names of alternatives...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create the model Step2: By default the call SIMUS() create a solver that internally uses the PuLP solver to solve the linear programs. Other av...
1,081
<ASSISTANT_TASK:> Python Code: import torch import torchvision import wandb import time from torch import nn from einops import rearrange from argparse import ArgumentParser from pytorch_lightning import LightningModule, Trainer, Callback from pytorch_lightning.loggers import WandbLogger from torch.optim import Adam fr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: CNN Encoder using PyTorch Step2: CNN Decoder using PyTorch Step3: PyTorch Lightning AutoEncoder Step4: Arguments Step5: Weights and Biases C...
1,082
<ASSISTANT_TASK:> Python Code: # import necessary libraries import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG ! pip3 install -U google-cloud-storage $USER_FLAG if 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: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Step3: Set up your Google Cloud project Step4...
1,083
<ASSISTANT_TASK:> Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfil...
<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: The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this...
1,084
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dis...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: TensorFlow Addons 損失 Step2: データを準備する Step3: モデルを構築する Step4: トレーニングして評価する
1,085
<ASSISTANT_TASK:> Python Code: # pandas import pandas as pd from pandas import DataFrame import re import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') %matplotlib inline # machine learning from sklearn.linear_model import LogisticRegression from sklearn.ensemble import Ra...
<SYSTEM_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,086
<ASSISTANT_TASK:> Python Code: import pandas as pd df = pd.DataFrame({'UserId': [1, 1, 1, 2, 3, 3], 'ProductId': [1, 4, 7, 4, 2, 1], 'Quantity': [6, 1, 3, 2, 7, 2]}) def g(df): l = int(0.2 * len(df)) dfupdate = df.sample(l, random_state=0) dfupdate.Quantity = 0 df.u...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
1,087
<ASSISTANT_TASK:> Python Code: import osmnx as ox import matplotlib.pyplot as plt %matplotlib inline # Specify the name that is used to seach for the data place_name = "Brasil, Ceará, Fortaleza" # Fetch OSM street network from the location graph = ox.graph_from_place(place_name) type(graph) # Plot the streets fig, ax ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Como podemos ver os dados que recuperamos é um objeto de dados especial chamado networkx.classes.multidigraph.MultiDiGraph. Step2: Agora podem...
1,088
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import make_regression from sklearn.cross_validation import train_test_split X, y, true_coefficient = make_regression(n_samples=80, n_features=30, n_informative=10, noise=100, coef=True, random_state=5) X_train, X_test, y_train, y_test = train_test_split(X, y, random...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Linear Regression Step2: Ridge Regression (L2 penalty) Step3: Lasso (L1 penalty) Step4: Linear models for classification Step5: Multi-Class ...
1,089
<ASSISTANT_TASK:> Python Code: import numpy as np np.random.seed(57442) x1 = np.random.random(10) x2 = np.random.random(10) np.testing.assert_allclose(x1.dot(x2), dot(x1, x2)) np.random.seed(495835) x1 = np.random.random(100) x2 = np.random.random(100) np.testing.assert_allclose(x1.dot(x2), dot(x1, x2)) import numpy 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: Part B Step2: Part C Step3: Part D Step4: Part E Step5: Part F Step6: Part G
1,090
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib import matplotlib.pyplot as plt import numpy as np from PIL import Image A = np.ones((100, 200)) A[33:33 + 4, 33:133] = 0.0 A[78:78 + 4, 33:133] = 0.0 A[33:78+4, 33:33+4] = 0.0 A[33:78+4, 129:129+4] = 0.0 plt.imshow(A, cmap='gray', interpolation='none...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Note Step2: Performing the SVD and counting the number of singular values that are greater than $10^{-9}$ Step3: With only three nonzero singu...
1,091
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import itertools from scipy import stats from statsmodels.stats.descriptivestats import sign_test from statsmodels.stats.weightstats import zconfint %pylab inline mouses_data = pd.read_csv('mirror_mouses.txt', header = None) mouses_data.columns = ['...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Загрузка данных Step2: Одновыборочные критерии Step3: Критерий знаков Step4: Критерий знаковых рангов Вилкоксона Step5: Перестановочный крит...
1,092
<ASSISTANT_TASK:> Python Code: import os from lightning import Lightning from numpy import random, asarray, linspace, corrcoef from colorsys import hsv_to_rgb from sklearn import datasets import networkx as nx lgn = Lightning(ipython=True, host='http://public.lightning-viz.org') n = 100 G = nx.random_regular_graph(3,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Connect to server Step2: <hr> Random binary network Step3: <hr> Random weighted network Step4: <hr> Lobster network Step5: <hr> Coloring by ...
1,093
<ASSISTANT_TASK:> Python Code: import pandas as pd import re import os import numpy as np import simulation_utils from scipy.interpolate import interp1d experimentdata = pd.read_table( '../processeddata/platereader/measured_yfprates_for_initiation_simulations.tsv', sep='\t', index_col=0) ''' # Uncomment th...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Fit Run 2 stall strength to reproduce measured single mutant YFP rates for Run 3 initiation mutant simulations Step2: Fit Run 2 stall strength ...
1,094
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pylab as plt import seaborn as sns from numpy.linalg import inv, lstsq sns.set_context('notebook') %matplotlib inline N, S = 100, 1000 mean = [0,0] rho = .1 cov = [[1, rho], [rho, 1]] alpha, beta = 2, 3 def simulate_data(mean, cov, alpha, beta, si...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If you want to embed plots inside IPython notebook, you need to turn on this option. Step2: Generate the data Step3: Parameters of the joint d...
1,095
<ASSISTANT_TASK:> Python Code: import os import pickle import time from collections import defaultdict import matplotlib.pyplot as plt import numpy as np from scipy.sparse import csc_matrix, csr_matrix, dok_matrix from scipy.optimize import curve_fit %matplotlib inline n_e = 325729 def getWWWdataset(n_e = 325729, shuf...
<SYSTEM_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 WWW dataset with sparse matrices Step2: Compute growth rate of WWW dataset with varying size of nodes Step3: Fit the growth curve Step4: ...
1,096
<ASSISTANT_TASK:> Python Code: # Import packages import pandas as pd import numpy as np from ipywidgets import interact import matplotlib.pyplot as plt %matplotlib inline def probability_setosa( petal_length, petal_width, w0, w1, w2 ): "Return the probability that a given specimen belongs to the species setosa" ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Defining the model Step2: Training the network Step3: We then define a function that plots the prediction of the model for a given set of weig...
1,097
<ASSISTANT_TASK:> Python Code: import pandas as pd pd.set_option('display.max_columns', 500) import zipfile with zipfile.ZipFile('../datasets/KaggleCredit2.csv.zip', 'r') as z: f = z.open('KaggleCredit2.csv') data = pd.read_csv(f, index_col=0) data.head() data.shape data.isnull().sum(axis=0) data.dropna(inplac...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Drop na Step2: Create X and y
1,098
<ASSISTANT_TASK:> Python Code: import pandas as pd df1 = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'city': ['bj', 'bj', 'sh', 'sh', 'sh'], 'district': ['ft', 'ft', 'hp', 'hp', 'hp'], 'date': ['2019/1/1', '2019/1/1', '2019/1/1', '2019/1/1', '2019/1/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:
1,099
<ASSISTANT_TASK:> Python Code: from operator import mul from functools import reduce import subprocess import numpy as np import sympy as sp import matplotlib.pyplot as plt from pyodesys.results import Result from pyodesys.symbolic import SymbolicSys from pyodesys.native import native_sys from pyodesys.native.util 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: Step2: Overriding root-finding in the generated C++ code -- Chemical kinetics Step3: There are some linking issues with boost's program options in the...