Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
9,600
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) img = mnist.train.images[2] plt.imshow(img.reshape((28, 28)), cmap='...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Below I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits. Step2: We'll train an autoe...
9,601
<ASSISTANT_TASK:> Python Code: import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../../data') # training data train_income=['Low','Medium','Low','High','Low','High','Medium','Medium','High','Low','Medium', 'Medium','High','Low','Medium'] train_age = ['Old','Young','Old','Young','Old','Young','Young','Old','...
<SYSTEM_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 want to create a decision tree from the above training dataset. The first step for that is to encode the data into numeric values and bind th...
9,602
<ASSISTANT_TASK:> Python Code: import numpy as np a = np.array( [2,3,4,-1,-2] ) print('Dimensões: a.shape=', a.shape ) print('Tipo dos elementos: a.dtype=', a.dtype ) print('Imprimindo o array completo:\n a=',a ) b = np.array( [ [1.5, 2.3, 5.2], [4.2, 5.6, 4.4] ] ) print('Um array bidimensional, dimens...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Veja a seguir uma matriz bidimensional de dados ponto flutuante de 2 linhas e 3 colunas. Observe que a tupla do shape aumenta para a esquerda, S...
9,603
<ASSISTANT_TASK:> Python Code: N = 0.001 R = 100 ml = ModelMaq(kaq=5, z=[10, 0], Saq=2e-4, tmin=1e-3, tmax=1e4) ca = CircAreaSink(ml, 0, 0, 100, tsandN=[(0, 0.001)]) ml.solve() ml.xsection(-200, 200, 0, 0, t=[0.1, 1, 10], figsize=(12, 4), sstart=-200) x = np.linspace(-200, 200, 200) qx = np.zeros_like(x) for t in [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: Circular area-sink and well Step2: Two layers
9,604
<ASSISTANT_TASK:> Python Code: # generic scientific/ipython header from __future__ import print_function from __future__ import division import os, sys import copy import numpy as np # Parent dictionary of in-common Movetypes-with-Odds to be used as the basis for each parameter's moves parentMovesWithOdds = {} parentM...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Biasing Moves Step2: Make 'moves with weights' dictionaries specialized for each parameter type Step3: Make master dict-of-dicts so that param...
9,605
<ASSISTANT_TASK:> Python Code: import deepchem as dc import numpy as np class PongEnv(dc.rl.GymEnvironment): def __init__(self): super(PongEnv, self).__init__('Pong-v0') self._state_shape = (80, 80) @property def state(self): # Crop everything outside the play area, reduce the image size, # and...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next we create a network to implement the policy. We begin with two convolutional layers to process Step2: We will optimize the policy using t...
9,606
<ASSISTANT_TASK:> Python Code: #example task: print each character in a word #one way to do is use a series of print statements word = 'lead' print(word[0]) print(word[1]) print(word[2]) print(word[3]) word = 'tin' print(word[0]) print(word[1]) print(word[2]) print(word[3]) #better approach word = 'lead' for char in 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: This is a bad appoach b/c Step2: uses a for loop to repeat operations Step3: Let's trace the execution Step4: finding the length of a strin...
9,607
<ASSISTANT_TASK:> Python Code: # Import NumPy and seed random number generator to make generated matrices deterministic import numpy as np np.random.seed(2) # Create a matrix with random entries A = np.random.rand(4, 4) print(A) # Compute eigenvectors of A evalues, evectors = np.linalg.eig(A) print("Eigenvalues: {}".f...
<SYSTEM_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 compute the eigenvectors and eigenvalues using the NumPy function linalg.eig Step2: The matrix A is non-symmetric, hence it is no surpri...
9,608
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd #used for reading/writing data import numpy as np #numeric library library from matplotlib import pyplot as plt #used for plotting import sklearn #machine learning library wineData = pd.read_csv('data/winequality/winequality-red.csv', sep=';') wine...
<SYSTEM_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 inspect the contents of the data Step2: All columns except the last one are the input parameters of the system, obtained from real vines...
9,609
<ASSISTANT_TASK:> Python Code: %matplotlib inline from wmf import wmf from fwm import utils import numpy as np import pylab as pl DEM=wmf.read_map_raster('raster/dem2.tif',True) DIR=wmf.read_map_raster('raster/dir.tif',True) wmf.cu.nodata=-9999.0; wmf.cu.dxp=30.0 DIR[DIR<=0]=wmf.cu.nodata.astype(int) DIR=wmf.cu.dir_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: Lectura de mapas de direcciones y de elevación Step2: Trazado de la cuenca y preparación de la misma Step3: Parámetros físicos. Step4: Prepar...
9,610
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 3, figsize=(13,4)) x = np.linspace(0, 2*np.pi, 30*np.pi).astype(np.float32) ax[0].plot(x, np.sin(x), label='sin') ax[1].plot(x, np.cos(x), label='cos') ax[2].plot(x, np.tan(x), label='tan') ax[0].plot(x, np.arcs...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Contents Step2: <a id='More_trigonometric_functions'></a>
9,611
<ASSISTANT_TASK:> Python Code: # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py from os.path import basename, exists def download(url): filename = basename(url) ...
<SYSTEM_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 <<_TheEuroProblem>> I presented a problem from David MacKay's book, Information Theory, Inference, and Learning Algorithms Step2: And we use...
9,612
<ASSISTANT_TASK:> Python Code: from sklearn import datasets iris = # complete fig, ax = plt.subplots() ax.scatter( # complete # complete # complete # complete from sklearn.cluster import # complete Kcluster = # complete Kcluster.fit( # complete fig, ax = plt.subplots() ax.scatter( # complete # complete # complete # ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Problem 1b Step2: Problem 2) $k$-means clustering Step3: Problem 2b Step4: Problem 2c Step5: Problem 2d Step6: That doesn't look right at...
9,613
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from data_helper_functions import * from IPython.display import display pd.options.display.max_columns = 999 %matplotlib inline with np.load('data/X.npz') as data: #old X, don't use, start at "Now with all channels..." X = data['X'] ...
<SYSTEM_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 Forest seems to be giving the best results, so we'll stick with that for now Step2: Maybe I should only use the AOD values since the sen...
9,614
<ASSISTANT_TASK:> Python Code: !git clone https://github.com/google-research/google-research.git import sys import os import tarfile import urllib import zipfile sys.path.append('./google-research') # TF streaming from kws_streaming.models import models from kws_streaming.models import utils from kws_streaming.models ...
<SYSTEM_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 of streaming and non streaming inference with TF/TFlite Step4: Load wav file Step5: Prepare batched model Step6: Run inference with ...
9,615
<ASSISTANT_TASK:> Python Code: import random from bisect import bisect_left import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns %matplotlib inline class PropSelection(object): def __init__(self, n): self._n = n self._frequencies = [0] * n def copy_f...
<SYSTEM_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 Proportional Selection Base Class Step2: Linear Walk Step3: Bisecting Search Step4: Stochastic Acceptance Step5: First Demonstration Step6...
9,616
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf with open('../sentiment-network/reviews.txt', 'r') as f: reviews = f.read() with open('../sentiment-network/labels.txt', 'r') as f: labels = f.read() reviews[:2000] from string import punctuation all_text = ''.join([c for c in reviews if...
<SYSTEM_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....
9,617
<ASSISTANT_TASK:> Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Intermediate Python - Objects Step2: You can create your own object using the class keyword. Step3: Why did we use the keyword class and not o...
9,618
<ASSISTANT_TASK:> Python Code: from plotSlope import slope data = pd.read_csv(os.path.join('data','EU_GDP_2007_2013.csv'),index_col=0,na_values='-') (data/1000).head() f = slope(data/1000,kind='interval',height= 12,width=20,font_size=12,dpi=150,savename='EU_interval.png',title = u'title') color = {"France":'b','Germ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load data from file into a data frame Step2: Plot it Step3: Other example
9,619
<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...
9,620
<ASSISTANT_TASK:> Python Code: # Author: Roman Goj <roman.goj@gmail.com> # # License: BSD (3-clause) import mne from mne.event import make_fixed_length_events from mne.datasets import sample from mne.time_frequency import csd_epochs from mne.beamformer import tf_dics from mne.viz import plot_source_spectrogram print(__...
<SYSTEM_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 raw data Step2: Time-frequency beamforming based on DICS
9,621
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd # RMS Titanic data visualization code from titanic_visualizations import survival_stats from IPython.display import display %matplotlib inline # Load the dataset in_file = 'titanic_data.csv' full_data = pd.read_csv(in_file) # Print the first few ent...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the ship Step3: The very same sample of th...
9,622
<ASSISTANT_TASK:> Python Code: import os os.environ['PYPMJ_CONFIG_FILE'] = '/path/to/your/config.cfg' import sys sys.path.append('..') import pypmj as jpy import numpy as np jpy.load_extension('materials') jpy.MaterialData? jpy.MaterialData.materials.keys() GaAs = jpy.MaterialData(material = 'gallium_arsenide') 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: Now we can import pypmj and numpy. Since the parent directory, which contains the pypmj module, is not automatically in our path, we need to app...
9,623
<ASSISTANT_TASK:> Python Code: from astropy.io import ascii import matplotlib import matplotlib.pyplot as plt import numpy as np %matplotlib inline tbl = ascii.read('n121_match.cat') def transform(v,i): c1f555 = [-0.09,-0.124] c2f555 = [0.034,0.018] c1f814 = [0.06,0.001] c2f814 = [-0.099,0.013] for j in range(8): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <hr> Step2: Se obtuvo la isócrona de la imagen (línea verde). Al menos pasa cerca de los puntos obtenidos por fotometría. Step3: <hr>
9,624
<ASSISTANT_TASK:> Python Code: import sys import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import statsmodels.sandbox.stats.multicomp as mc import multiprocessing as mp %matplotlib inline import os os.environ['OMP_NUM_THREADS'] = str(1) import warnings warnings.filterwarnings('ignore') imp...
<SYSTEM_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.0 Basic parameters Step2: 1.0 Run information transfer mapping procedure Step4: 1.2 Perform network-to-network information transfer mapping ...
9,625
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nuist', 'sandbox-2', 'atmos') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "ema...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
9,626
<ASSISTANT_TASK:> Python Code: # boilerplate code from __future__ import print_function import os from io import BytesIO import numpy as np from functools import partial import PIL.Image from IPython.display import clear_output, Image, display, HTML import tensorflow as tf #!wget https://storage.googleapis.com/downloa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <a id='loading'></a> Step6: To take a glimpse into the kinds of patterns that the network learned to recognize, we will try to generate images ...
9,627
<ASSISTANT_TASK:> Python Code: !pip3 install meetup-api pandas pytest matplotlib clarifai import meetup.api import pandas as pd API_KEY = '' event_id='' def get_members(event_id): client = meetup.api.Client(API_KEY) rsvps=client.GetRsvps(event_id=event_id, urlname='_ChiPy_') member_id = ','.join([str(i['me...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: This part of the exercise is straight from the previous team project. We use the meetup.com api to load get the ChiPy members who RSVP-ed for on...
9,628
<ASSISTANT_TASK:> Python Code: M = np.array(((2.0, 0.0), ( 0.0, 1.0))) K = np.array(((3.0,-2.0), (-2.0, 2.0))) p = np.array(( 0.0, 1.0)); w = 2.0 print_mat(M, pre='\\boldsymbol{M}=m\\,', fmt='%d') print_mat(K, pre='\\boldsymbol{K}=k\\,', fmt='%d') print_mat(p[:,None], pre=r'\boldsymbol{p}(t) = p_0\,', fmt='%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: Computing the eigenvalues and the eigenvectors Step2: The @ operator stands, in this context, for matrix multiplication. Step3: Modal Response...
9,629
<ASSISTANT_TASK:> Python Code: import pandas as pd import matplotlib.pyplot as plt df3 = pd.read_csv('../data/df3') %matplotlib inline df3.plot.scatter(x='a',y='b',c='red',s=50 df3.info() df3.head() df3.plot.scatter(x='a',y='b',c='red',s=50,figsize=(12,3)) df3['a'].plot.hist() plt.style.use('ggplot') df3['a'].plot.h...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Recrea la siguiente grafica de puntos de b contra a. Step2: Crea un histograma de la columna 'a'. Step3: Las graficas se ven muy bien, pero de...
9,630
<ASSISTANT_TASK:> Python Code: # remove after testing %load_ext autoreload %autoreload 2 import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from urllib.request import urlopen from sklearn.decomposition import PCA from mclearn.viz import (plot_class_distribution, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Distribution of Classes Step2: Maps of Classes Step3: Here are the distribution map of galaxies, stars, and quasars, respectively. Step4: Pho...
9,631
<ASSISTANT_TASK:> Python Code: from scipy import stats import numpy as np np.random.seed(42) x = np.random.normal(0, 1, 1000) y = np.random.normal(0, 1, 1000) statistic, p_value = stats.ks_2samp(x, y) <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:
9,632
<ASSISTANT_TASK:> Python Code: import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline iris= sns.load_dataset('iris') iris.head() grd = sns.PairGrid(data=iris) #then you can assign what you want plotted for diagonal, above diagonal, below diagonal. # when mapping, pass just function pointers, dont cal...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Pairgrids Step2: lmplot() for scatter and regression per category Step3: FacetGrid Step4: Suppose we want to visualize total_bill by time of ...
9,633
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.datasets import make_blobs from sklearn.svm import LinearSVC x = np.linspace(-2.0, 2.0, num=100) def huberizedHingeLoss(x, h): if x > 1+h: ret...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Explain how the huberized hinge loss relates to the regular hinge loss and to the misclassification error loss. Step2: 2.1.3 Numerical checks ...
9,634
<ASSISTANT_TASK:> Python Code: import cv2 from PIL import Image import math import copy #the usual data science stuff import os,sys import glob import matplotlib.pyplot as plt import numpy as np import pandas as pd %matplotlib inline ladyboy_big_input = '../data/ladyboy_big/' ladyboy_big_output = '../data/processed/lad...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ladyboy Step2: Ladyboy Big Step3: Girl
9,635
<ASSISTANT_TASK:> Python Code: # Package imports import os import pandas as pd import numpy as np import statistics from ipywidgets import interact import ipywidgets as widgets # Bokeh Plots from bokeh.io import output_notebook, push_notebook, show from bokeh.plotting import figure output_notebook() # Hide warnings imp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Choose a file to check Step2: Load and prepare data Step3: Time Series Step4: Measured vs Calibrated Step5: Differences
9,636
<ASSISTANT_TASK:> Python Code: import os import matplotlib.pyplot as plt from eniric import config, precision # Load a spectrum from astropy.io import fits test_data = config.paths["phoenix_raw"] print(test_data) wav = fits.getdata(os.path.join(test_data, "WAVE_PHOENIX-ACES-AGSS-COND-2011.fits")) flux = fits.getdata( ...
<SYSTEM_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 precision has not been scaled to a specific flux/SNR level. Step2: Scaling Effects
9,637
<ASSISTANT_TASK:> Python Code: import warnings warnings.filterwarnings("ignore", category=FutureWarning) import os, sys sys.path = [os.path.abspath("../../")] + sys.path from deep_learning4e import * from notebook4e import * psource(SimpleRNNLearner) from keras.datasets import imdb data = imdb.load_data(num_words=5000...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: train_data and val_data are needed when creating a simple rnn learner. Both attributes take lists of examples and the targets in a tuple. Please...
9,638
<ASSISTANT_TASK:> Python Code: # Import the library we need, which is Pandas import pandas as pd # Read the csv file of Monthwise Quantity and Price csv file we have. df = pd.read_csv('MonthWiseMarketArrivals_clean.csv') df.shape df.head() # Get the typeof each column df.dtypes # Changing the date column to a Time ...
<SYSTEM_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 will find the variable df used quite often to store a dataframe Step2: Understand Data Structure and Types Step3: Data Structure Step4: S...
9,639
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS from IPython.display import display from ipywidgets import * from mpl_toolkits.mplot3d import Axes3D import plotBL HTML('../style/code_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: Import section specific modules Step2: 4.5.2 $uv$ coverage Step3: From the list above, you can select different configurations corresponding ...
9,640
<ASSISTANT_TASK:> Python Code: !pip install -q tf-nightly-gpu-2.0-preview import tensorflow as tf print(tf.__version__) (x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() x_train.shape import numpy as np # add empty color dimension x_train = np.expand_dims(x_train, -1) x_test = np.expand...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Alternative Step2: Checking our results (inference)
9,641
<ASSISTANT_TASK:> Python Code: fbvary_results = [] for file in glob.glob('runs/evolved_mu_f_b_vary?replicate?datetime.datetime(2019, 5, *).hdf5'): try: fbvary_results.append(popev.PopulationReader(file)) except OSError: pass favary_results = [] for file in glob.glob('runs/evolved_mu_f_a_vary?rep...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Graphs of population distribution and trajectories for base parameter set Step2: Given a delta_f of .03 and a K of 1 million, we expect it woul...
9,642
<ASSISTANT_TASK:> Python Code: import pandas as pd diff_raw = pd.read_csv( "../../buschmais-spring-petclinic_fork/git_diff.log", sep="\n", names=["raw"]) diff_raw.head(16) index_row = diff_raw.raw.str.startswith("index ") ignored_diff_rows = (index_row.shift(1) | index_row.shift(2)) diff_raw = diff_raw[~(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: The output is the commit data that I've describe above where each in line the text file represents one row in the DataFrame (without blank lines...
9,643
<ASSISTANT_TASK:> Python Code: import coral as cor # alternative you can import each module by itself e.g. from coral import design dir(cor) # dir lists everything in a module/object. Ignore the double underscore items. dna = cor.DNA("ATGC") print "DNA: {}".format(dna) # You can also run methods on the object - in 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: Top-level Step2: As you can see above, to make DNA, RNA, or Peptide objects you just invoke the correct sequence. command and give it a valid s...
9,644
<ASSISTANT_TASK:> Python Code: import datetime import os import shutil import numpy as np import pandas as pd import tensorflow as tf from google.cloud import aiplatform from matplotlib import pyplot as plt from tensorflow import keras from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.layers 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: Load raw data Step2: Use tf.data to read the CSV files Step3: Build a simple keras DNN model Step4: Next, we create the DNN model. The Sequen...
9,645
<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...
9,646
<ASSISTANT_TASK:> Python Code: from IPython.display import Image from IPython.display import HTML from IPython.display import IFrame assert True # leave this to grade the import statements Image(url = 'http://newsroom.unl.edu/releases/downloadables/photo/20090923solenoid.jpg', width = 600, height = 600) assert True # ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Basic rich display Step2: Use the HTML object to display HTML in the notebook that reproduces the table of Quarks on this page. This will requi...
9,647
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from simmit import smartplus as sim import os v = np.random.rand(6) trace = sim.tr(v) print v print trace v = np.random.rand(6) v_dev = sim.dev(v) print v print v_dev v = np.random.rand(6) Mises_sig = sim.Mises_stres...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: tr(vec) Step2: dev(vec) Step3: Mises_stress(vec) Step4: Mises_strain(vec) Step5: eta_stress(vec) Step6: eta_strain(vec) Step7: v2t_stress(...
9,648
<ASSISTANT_TASK:> Python Code: def findquadrant(point,size): y,x = point halfsize = size/2 if x < -halfsize: if y > halfsize: return [0,0] if y < -halfsize: return [2,0] return [1,0] if x > halfsize: if y > halfsize: return [0,2] if y < -halfsize: return [2,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: randomwalk each point for 1 day equivalent Step2: make a grid from a scatter of many points Step3: Find maximum time step without leaking mosq...
9,649
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.metrics import silhouette_samples, silhouette_score # We resort to a third party library to plot silhouette diagrams ! 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: Goal Step2: The anomalies are the minority. Step3: In unsupervised approaches, the label is not used Step4: All the methods we will use, exce...
9,650
<ASSISTANT_TASK:> Python Code: %matplotlib inline from __future__ import print_function import os import os.path as osp import numpy as np import pysptools.ml as ml import pysptools.skl as skl from sklearn.model_selection import train_test_split home_path = os.environ['HOME'] source_path = osp.join(home_path, 'dev-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: X_train and y_train sets are built Step2: We set an hypothesis and call the Gradient Boosting cross validation Step3: Same but this time we ca...
9,651
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt f=lambda x: np.sqrt(x[:,0]**2 + x[:,1]**2) #definición de norma2 density=1e-5 density_p=int(2.5*10**3) x=np.arange(-1,1,density) y1=np.sqrt(1-x**2) y2=-np.sqrt(1-x**2) x_p=np.random.uniform(-1,1,(density_p,2)) ind=f(x_p)<1 x_p_subset=x_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: Norma $2$ Step2: Norma $1$ Step3: Norma $\infty$ Step4: ```{admonition} Observación Step5: en este caso $D=\left[\begin{array}{cc} \frac{1}{...
9,652
<ASSISTANT_TASK:> Python Code: from bs4 import BeautifulSoup from urllib.request import urlopen html_str = urlopen("http://static.decontextualize.com/widgets2016.html").read() document = BeautifulSoup(html_str, "html.parser") h3_tag = document.find_all('h3') print(type(h3_tag)) [tag.string for tag in h3_tag] print(len...
<SYSTEM_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, in the cell below, use Beautiful Soup to write an expression that evaluates to the number of &lt;h3&gt; tags contained in widgets2016.html....
9,653
<ASSISTANT_TASK:> Python Code: import gensim import os import collections import smart_open import random # Set file names for train and test data test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data']) lee_train_file = test_data_dir + os.sep + 'lee_background.cor' lee_test_file = test_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: What is it? Step2: Define a Function to Read and Preprocess Text Step3: Let's take a look at the training corpus Step4: And the testing corpu...
9,654
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os from pprint import pprint import shutil import subprocess import urllib.request import h5py import numpy as np import matplotlib.pyplot as plt import openmc.data # Download ENDF file url = 'https://t2.lanl.gov/nis/data/data/ENDFB-VII.1-neutron/Gd/157' filenam...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: ENDF Step2: We can access the parameters contained within File 32 in a similar manner to the File 2 parameters from before. Step3: The newly c...
9,655
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from quantities import ms, s, Hz from elephant.spike_train_generation import homogeneous_poisson_process, homogeneous_gamma_process help(homogeneous_poisson_process) t_start = 275.5 * ms print(t_start) t_start2 = 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: The function requires four parameters Step2: The nice thing about Quantities is that once the unit is specified you don't need to worry about r...
9,656
<ASSISTANT_TASK:> Python Code: import pandas as pd # pandas for handling mixed data sets import numpy as np # numpy for basic math and matrix operations import matplotlib.pyplot as plt # pyplot for plotting # scikit-learn for machine learning and data preprocessing from sklearn.decompositio...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Perform basic feature extraction Step2: Compress x1 and x2 into a single principal component Step3: Principal components analysis finds vector...
9,657
<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 # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplotlib inline plt.rcPa...
<SYSTEM_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...
9,658
<ASSISTANT_TASK:> Python Code: %pylab nbagg import sygma as s reload(s) s.__file__ from scipy.integrate import quad from scipy.interpolate import UnivariateSpline import numpy as np s1=s.sygma(iolevel=0,mgal=1e11,dt=1e7,tend=1.3e10,sn1a_rate='power_law',beta_pow=-1, imf_type='salpeter',imf_bdys=[1,30],hards...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Power law & Maoz Step2: Maoz and power law with -1 is the same as visible below. Step3: Gaussian Step4: gauss_dtd=[4e9,3.2e9] (as mentioned i...
9,659
<ASSISTANT_TASK:> Python Code: !git clone https://github.com/google-research/google-research.git import sys import os import tarfile import urllib import zipfile sys.path.append('./google-research') # TF streaming from kws_streaming.models import models from kws_streaming.models import utils from kws_streaming.layers....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example of model training Step4: Set path to data Step5: Set path to a model with config Step6: Model training Step7: Run model evaluation
9,660
<ASSISTANT_TASK:> Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG ! pip3 install -U google-cloud-storage $USER_FLAG if not os.getenv("IS_TESTING...
<SYSTEM_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: Before you begin Step4: Region Step5:...
9,661
<ASSISTANT_TASK:> Python Code:: mean_absolute_error(y_test, predictions) <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:
9,662
<ASSISTANT_TASK:> Python Code: import math import torch import gpytorch from matplotlib import pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 train_x1 = torch.rand(50) train_x2 = torch.rand(50) train_y1 = torch.sin(train_x1 * (2 * math.pi)) + torch.randn(train_x1.size()) * 0.2 train_y2 = torch.cos...
<SYSTEM_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 training data Step2: Set up a Hadamard multitask model Step3: Training the model Step4: Make predictions with the model
9,663
<ASSISTANT_TASK:> Python Code: # Load library import pandas as pd # Create dates dates = pd.Series(pd.date_range('2/2/2002', periods=3, freq='M')) # View data dates # Show days of the week dates.dt.weekday_name <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: Create Date And Time Data Step2: Show Days Of The Week
9,664
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn seaborn.set_style('whitegrid') def r2(actual, predicted): if isinstance(actual, list): actual = np.array(actual) if isinstance(predicted, list): predicted = np....
<SYSTEM_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'll get a perfect R2=1 if actual and predicted values are the same Step2: Now if we're a bit off on our predictions R2 will be still pretty h...
9,665
<ASSISTANT_TASK:> Python Code: %install_ext https://raw.githubusercontent.com/meduz/ipython_magics/master/tikzmagic.py %load_ext tikzmagic %%tikz \filldraw [fill=white] (0,0) circle [radius=1cm]; \foreach \angle in {60,30,...,-270} { \draw[line width=1pt] (\angle:0.9cm) -- (\angle:1cm); } \draw (0,0) -- (90:0.8cm); ...
<SYSTEM_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 이상 360 미만의 구간내에서 균일 분포(uniform distribution) 모형을 가진다고 가정하면 답은 0(zero)이다. Step2: 누적 밀도 함수 즉 cdf는 다음과 같은 특징을 가진다. Step3: 이...
9,666
<ASSISTANT_TASK:> Python Code: document = ET.parse( './data/mondial_database.xml' ) import pandas as pd root = document.getroot() #get infant mortality of each country, add to heap if under capacity #otherwise check if new value is greater than smallest. inf_mort = dict() for element in document.iterfind('country'): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Not all the entries have an infant mortality rate element. So we need to make sure loop loops for the element named 'infant_mortality'. Step2: ...
9,667
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt def modl(t,A,o,l,d): return A*np.exp(-1*t)*np.cos(o*t)+d thetabest,thetacov=opt.curve_fit(modl,tdata,ydata,np.array((6,1,1,0)),dy,absolute_sigma=True) assert True # leave this to grade ...
<SYSTEM_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
9,668
<ASSISTANT_TASK:> Python Code: # import sqlite3 here #open connection to database # 1st challenge: Write a sql query to search for the name: zoidberg # Note: It will return 0 # Add the zoidberg data to the database below. remeber to commit() # Search for zoidberg again. This time, you should get the results below: # ...
<SYSTEM_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 returned empty because there is no zoidberg in our list. Step2: Next Step3: Next Step4: There is a problem with the above
9,669
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Image Classification Step2: Explore the Data Step5: Implement Preprocess Functions Step8: One-hot encode Step10: Randomize Data Step12: Che...
9,670
<ASSISTANT_TASK:> Python Code: import medusa from medusa.test import create_test_ensemble ensemble = create_test_ensemble("Staphylococcus aureus") ensemble.base_model.objective.expression ensemble.base_model.objective = 'EX_cpd00011_e' print(ensemble.base_model.objective.expression) ensemble.base_model.objective = 'bi...
<SYSTEM_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 current objective function is the biomass reaction (bio1)--to change this, just set the objective to another reaction. Let's change the obje...
9,671
<ASSISTANT_TASK:> Python Code: # Import helpful libraries and setup our project, bucket, and region import os PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 # Do ...
<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: <h2> Create ML dataset using Dataflow </h2> Step3: Let's pull a sample of our data into a dataframe to see what it looks like. Step4: Let's ch...
9,672
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import interp2d from qutip import * # shared parameters gamma = 1 # decay rate tlist = np.linspace(0, 13, 300) taulist = tlis...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Introduction Step2: Setup the operators, Hamiltonian, and initial state Step3: Calculate the emission flux Step4: Visualize the emission flux...
9,673
<ASSISTANT_TASK:> Python Code: TMPrimaryHeader = BitStruct('transfer_frame_version_number' / BitsInteger(2), 'spacecraft_id' / BitsInteger(10), 'virtual_channel_id' / BitsInteger(3), 'ocf_flag' / Flag, 'maste...
<SYSTEM_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 frames from CSV file. proxy_time is set by the client when sending the frame (using groundstation PC clock). server_time is set by the serv...
9,674
<ASSISTANT_TASK:> Python Code: class Stack(): def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def isEmpty(self): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Stack examples
9,675
<ASSISTANT_TASK:> Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.6 import tensorflow as tf import pandas as pd import numpy as np import shutil print(tf.__version__) # In CSV, label is the first col...
<SYSTEM_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 data created in the previous chapter. Step2: <h2> Train and eval input functions to read from Pandas Dataframe </h2> Step3: Our input fun...
9,676
<ASSISTANT_TASK:> Python Code: df_ranking=pd.read_csv('article_uni.csv', index_col=0) print(df_ranking.shape) df_ranking.head() df.article_uni.replace('The London School of Economics and Political Science (United-Kingdom)', 'London School of Economics and Political Science', inplace=True) from sklearn.preprocessing...
<SYSTEM_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=pd.pivot_table(df,index=["article_uni"],values=["article_rating"],aggfunc=[len,np.mean], columns='year') Step2: b=df[df.article_pub_date>=dat...
9,677
<ASSISTANT_TASK:> Python Code: import re def tokenize(s): '''Transform the string s into a list of tokens. The string s is supposed to represent an arithmetic expression. ''' lexSpec = r'''([ \t]+) | # blanks and tabs ([1-9][0-9]*|0) | # 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: The function tokenize receives a string s as argument and returns a list of tokens. Step2: Implementing the Recursive Descend Parser Step3: Th...
9,678
<ASSISTANT_TASK:> Python Code: import numpy as np ## This is a list of everything in the module np.__all__ an_array = np.array([0,1,2,3,4,5,6]) print an_array print print type(an_array) print help(an_array) A = np.zeros((4,4)) print A print print A.shape print print A.diagonal() print A[0,0] = 2.0 print A np.fill_diago...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Speed Step2: Views of the data (are free) Step3: Exercise Step4: Broadcasting is a way of looping on arrays which have "compatible" but unequ...
9,679
<ASSISTANT_TASK:> Python Code: # Standard Python libraries from __future__ import absolute_import, division, print_function, unicode_literals import os import time import numpy as np import glob import matplotlib.pyplot as plt import PIL import imageio from IPython import display import sklearn import seaborn as sns sn...
<SYSTEM_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 in 1d <a class="anchor" id="linreg-1d"></a> Step2: Linear regression for boston housing <a class="anchor" id="linreg-boston">...
9,680
<ASSISTANT_TASK:> Python Code: class SimpleClass(): def __init__(self, str_input): print("SIMPLE" + str_input) class ExtendedClass(SimpleClass): def __init__(self): print('EXTENDED') s = ExtendedClass() class ExtendedClass(SimpleClass): def __init__(self): super().__init__(" My Str...
<SYSTEM_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 child class will use its own initialization method, if not specified otherwise. Step2: If we want to use initialization from the parent cla...
9,681
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display, SVG from IPython.display import Javascript s = <svg width="100" height="100"> <circle cx="50" cy="50" r="20" fi...
<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: Interact with SVG display Step5: Write a function named draw_circle that draws a circle using SVG. Your function should take the parameters of ...
9,682
<ASSISTANT_TASK:> Python Code: # Import spaCy and load the language library. Remember to use a larger model! import spacy nlp = spacy.load('en_core_web_md') # Choose the words you wish to compare, and obtain their vectors word1 = nlp.vocab['wolf'].vector word2 = nlp.vocab['dog'].vector word3 = nlp.vocab['cat'].vector #...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: CHALLENGE Step2: Task #2 Step3: CHALLENGE
9,683
<ASSISTANT_TASK:> Python Code: # Load a text file of integers: y = np.loadtxt("yelp_data/upvote_labels.txt", dtype=np.int) # Load a text file with strings identifying the 1000 features: featureNames = open("yelp_data/upvote_features.txt").read().splitlines() featureNames = np.array(featureNames) # Load a csv of floats,...
<SYSTEM_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 the Yelp Question in HW1, please normalize the data so that it has the same L2 norm. We will grade it either way, but please state clearly wh...
9,684
<ASSISTANT_TASK:> Python Code: from erddapy import ERDDAP e = ERDDAP( server="https://gliders.ioos.us/erddap", protocol="tabledap", response="csv", ) e.dataset_id = "whoi_406-20160902T1700" e.variables = [ "depth", "latitude", "longitude", "salinity", "temperature", "time", ] e.cons...
<SYSTEM_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 populate the object a dataset id, variables of interest, and Step2: Longer introduction Step3: All the get_<methods> will return a...
9,685
<ASSISTANT_TASK:> Python Code: %matplotlib inline import sys import os import shutil import numpy as np from subprocess import check_output # Import flopy import flopy # Set the name of the path to the model working directory dirname = "P4-3_Hubbertville" datapath = os.getcwd() modelpath = os.path.join(datapath, dirna...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setup a New Directory and Change Paths Step2: Define the Model Extent, Grid Resolution, and Characteristics Step3: Create the MODFLOW Model Ob...
9,686
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-lr', 'ocean') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contrib...
<SYSTEM_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...
9,687
<ASSISTANT_TASK:> Python Code: a = {"x" : 1, "z" : 3} b = {"y" : 2, "z" : 4} from collections import ChainMap c = ChainMap(a, b) print(c["x"]) print(c["y"]) print(c["z"]) len(c) list(c.keys()) list(c.values()) c["z"] = 10 c["w"] = 40 del c["x"] a del c["y"] values = ChainMap() values["x"] = 1 # Add a new mapping 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: Step1: 现在假设你必须在两个字典中执行查找操作(比如先从 a 中找,如果找不到再在 b 中找)。 一个非常简单的解决方案就是使用 collections 模块中的 ChainMap 类。比如: Step2: 讨论 Step3: 如果出现重复键,那么第一次出现的映射值会被返回。 因此,例子程序...
9,688
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Barachant <alexandre.barachant@gmail.com> # # License: BSD (3-clause) from mne import (io, compute_raw_covariance, read_events, pick_types, Epochs) from mne.datasets import sample from mne.preprocessing import Xdawn from mne.viz import plot_epochs_image print(__doc__)...
<SYSTEM_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 and read data Step2: Now, we estimate a set of xDAWN filters for the epochs (which contain only Step3: Epochs are denoised by c...
9,689
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy import constants import scipy.integrate import scipy.special as func from MeshedFields import * import pygmsh Ra = 0.020 Ri = 0.002 lca = 0.003 lci = 0.0003 geom = pygmsh.built_in.Geometry() # we create the initial geometry as a streched ellipse to create # ...
<SYSTEM_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 meshed screen with a central hole Step2: The screen is placed at the origin. A beam is assumed to propagate in z direction<br> Step3: ...
9,690
<ASSISTANT_TASK:> Python Code: # improve on the "stopword" filters here # # :-) (ask me about a smilie lexicon) # not-so-simple words? (ask me about a regex for compound words) # python variables names with underscores? (regex) f = os.path.join(DATA_PATH, 'text.csv.gz') df.to_csv(f, encoding='utf8', compression='gzip',...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Make sure you can read it back in!
9,691
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from formulae import design_matrices rng = np.random.default_rng(7355608) SIZE = 10 data = pd.DataFrame( { "y1": rng.normal(size=SIZE), "y2": rng.choice(["A", "B", "C"], size=SIZE), "x": rng.normal(size=SIZE), "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: Let's simulate some data to use throughout examples here. The number of observations isn't too important. We keep it low to understand what is g...
9,692
<ASSISTANT_TASK:> Python Code: mnist = mx.test_utils.get_mnist() image = np.reshape(mnist['train_data'],(60000,28*28)) label = image image_test = np.reshape(mnist['test_data'],(10000,28*28)) label_test = image_test [N,features] = np.shape(image) #number of examples and features f, (ax1, ax2, ax3, ax4) = plt.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: We can optionally save the parameters in the directory variable 'model_prefix'. We first create data iterators for MXNet, with each batch of dat...
9,693
<ASSISTANT_TASK:> Python Code: %load_ext google.cloud.bigquery %%bigquery daily_flakiness select job, start_date, round(sum(if(flaked=1,passed,runs))/sum(runs),3) build_consistency, round(1-sum(flaked)/count(distinct commit),3) commit_consistency, round (sum(flaked)/count(distinct commit),3) flake...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Compute daily flakiness of kubeflow presubmit tests Step2: Daily flake rate of all presubmit tests over time Step3: Daily build and commit co...
9,694
<ASSISTANT_TASK:> Python Code: y, sr = librosa.load('audio/simple_piano.wav') ipd.Audio(y, rate=sr) est_onsets = librosa.onset.onset_detect(y=y, sr=sr, units='time') est_onsets ref_onsets = numpy.array([0, 0.270, 0.510, 1.02, 1.50, 2.02, 2.53, 3.01]) librosa.display.waveplot(y, sr=sr, alpha...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Detect Onsets Step2: Load a fictional reference annotation. Step3: Plot the estimated and reference onsets together. Step4: Evaluate Step5: ...
9,695
<ASSISTANT_TASK:> Python Code: # only necessary if you're running Python 2.7 or lower from __future__ import print_function, division from six.moves import range # import matplotlib and define our alias from matplotlib import pyplot as plt # plot figures within the notebook rather than externally %matplotlib inline # 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: Overview Step2: Problem Step3: Now that our data is in an accessible format, let's try and get it into something we can do math with. Copy ov...
9,696
<ASSISTANT_TASK:> Python Code: import os CWD = os.getcwd() import girder_client from pandas import read_csv from imageio import imread from histomicstk.annotations_and_masks.masks_to_annotations_handler import ( get_contours_from_mask, get_single_annotation_document_from_contours, get_annotation_documents_f...
<SYSTEM_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. Connect girder client and set parameters Step2: Let's inspect the ground truth codes file Step3: Read and visualize mask Step4: 2. Get con...
9,697
<ASSISTANT_TASK:> Python Code: # Load image import cv2 import numpy as np from matplotlib import pyplot as plt # Load image as grayscale image_bgr = cv2.imread('images/plane_256x256.jpg') image_gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY) image_gray = np.float32(image_gray) # Set corner detector parameters bloc...
<SYSTEM_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 image Step2: Define Corner Parameters Step3: Detect Corners Step4: Mark Corners Step5: View Image
9,698
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np import theano import theano.tensor as T from carl.distributions import Normal p = Normal(mu=0.0, sigma=1.0) reals = np.linspace(-5, 5, num=1000) pdf = p.pdf(X=reals.reshape(-1, 1)) # X is a 2D array of shape n_sam...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Base API Step2: Advanced API Step3: Note Step4: By construction, p.mu is a Theano symbolic expression which depends on several inputs, in thi...
9,699
<ASSISTANT_TASK:> Python Code: from sklearn.ensemble import RandomForestClassifier from IPython.display import YouTubeVideo, HTML YouTubeVideo("XOEN9W05_4A") #The Donald Bren School of Information and Computer Sciences - University of California, Irvine info_file = 'http://archive.ics.uci.edu/ml/machine-learning-datab...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Watch the video of the type of activity that was recorded Step2: The data is extracted from the .zip file on the UCI website Step3: The datase...