text_prompt
stringlengths
168
30.3k
code_prompt
stringlengths
67
124k
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Una vez importadas las funciones de nuestra librería, podemos empezar declarando variables (o constantes) conocidas para nosotros. Step2: Nota ...
<ASSISTANT_TASK:> Python Code: # Esta libreria tiene las funciones principales que utilizaremos from sympy import var, Matrix, Function, sin, cos, pi, trigsimp # Esta libreria contiene una funcion que la va a dar un formato "bonito" a nuestras ecuaciones from sympy.physics.mechanics import mechanics_printing mechanics_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <p style="text-align Step2: <p style="text-align Step3: <p style="text-align Step4: <p style="text-align Step5: <p style="text-align Step6: ...
<ASSISTANT_TASK:> Python Code: current_number = 2 while current_number <= 16: twice_number = current_number + current_number print(f"{current_number} and {current_number} are {twice_number}") current_number = twice_number current_number = 2 while current_number <= 16: twice_number = current_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: Title Step2: Resources Step3: Run the model on a single batch of data, and inspect the output Step4: Compile the model for training
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Plugin setup Step2: Model setup Step3: Spectral fitting Step4: It seems that the effective area between GBM and BAT do not agree! Step5: Let...
<ASSISTANT_TASK:> Python Code: %matplotlib inline %matplotlib notebook from threeML import * import os gbm_dir = "gbm" bat_dir = "bat" bat = OGIPLike('BAT', observation=os.path.join(bat_dir,'gbm_bat_joint_BAT.pha'), response=os.path.join(bat_dir,'gbm_bat_joint_BAT.rsp')) bat.set_active_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: Did you try it, and get an error saying Problem loading page or Unable to connect? So did I. It’s because we forgot to spin up the dev server fi...
<ASSISTANT_TASK:> Python Code: %cd ../examples/superlists/ !python3 functional_tests.py %%writefile functional_tests.py from selenium import webdriver from selenium.webdriver.common.keys import Keys import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Fire...
<SYSTEM_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 in Classifications Step2: Count sources that were missed in PS1 PSC v1 Step3: Loop over reason some stars are missing Step4: What's goin...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib import pyplot as plt from matplotlib.ticker import MultipleLocator from matplotlib import rcParams from matplotlib.legend import Legend import seaborn as sns rcParams["font.family"] = "sans-serif" rcPar...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Pipe Fitting App Step2: Slab Fitting App
<ASSISTANT_TASK:> Python Code: %matplotlib inline from geoscilabs.gpr.GPRlab1 import downloadRadargramImage, PipeWidget, WallWidget from SimPEG.utils import download URL = "http://github.com/geoscixyz/geosci-labs/raw/main/images/gpr/ubc_GPRdata.png" radargramImage = downloadRadargramImage(URL) PipeWidget(radargramImag...
<SYSTEM_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.0 시작하기 Step2: MNIST 데이터셋을 로드하여 준비합니다. 샘플 값을 정수에서 부동소수로 변환합니다 Step3: 층을 차례대로 쌓아 tf.keras.Sequential 모델을 만듭니다. 훈련에 사용할 옵티마이저(optimizer)와 ...
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Validating Models Step2: Let's fit a K-neighbors classifier Step3: Now we'll use this classifier to predict labels for the data Step4: Finall...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division %matplotlib inline import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn') from sklearn.datasets import load_digits digits = load_digits() X = digits.data y = digits.target from sklearn.neighbors import KNeighborsClassi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 利用 Keras 来训练多工作器(worker) Step2: 准备数据集 Step3: 构建 Keras 模型 Step4: 让我们首先尝试用少量的 epoch 来训练模型,并在单个工作器(worker)中观察结果,以确保一切正常。 随着训练的迭代,您应该会看到损失(loss)下...
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Introdução à Programação em Python Step2: Para resolver o primeiro item, utilizamos o comando while que significa enquanto Step3: Reparem que ...
<ASSISTANT_TASK:> Python Code: def DivResto(num, base): Retorna o quociente e resto da divisão de num por base return num//base, num%base dec = 14 bin = "" # string vazia div, resto = DivResto(dec,2) dec = div bin = str(resto) + bin print(bin) # repete mais uma vez, pois temos outro dígito div, rest...
<SYSTEM_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 models and API of astropy.modeling.models is explained in the astropy documentation in more detail. Step2: Likelihoods and Posteriors Step3...
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 # ignore warnings to make notebook easier to see online # COMMENT OUT THESE LINES FOR ACTUAL ANALYSIS import warnings warnings.filterwarnings("ignore") %matplotlib inline import matplotlib.pyplot as plt try: import seaborn as sns sns.set_palette(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Since there's a bit of variance year-to-year and especially difference in 2020 with Hawkeye, grab a month from each year Step2: Calculate the f...
<ASSISTANT_TASK:> Python Code: from pybaseball import statcast, utils import matplotlib.pyplot as plt import numpy as np import pandas as pd from pybaseball.plotting import plot_bb_profile # Grab 1 month per year dfs = [] for year in range(2015, 2021): print(f"Starting year {year}") dfs.append(statcast(start_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: mapValues Step2: When using mapValues(), the x in the above lambda function refers to the element value, not including the element key. Step3: ...
<ASSISTANT_TASK:> Python Code: # create an example RDD map_exp_rdd = sc.textFile('../../data/mtcars.csv') map_exp_rdd.take(4) # split auto model from other feature values map_exp_rdd_1 = map_exp_rdd.map(lambda x: x.split(',')).map(lambda x: (x[0], x[1:])) map_exp_rdd_1.take(4) # remove the header row header = map_exp_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: Then it's time to load some data to estimate segregation. We use the data of 2000 Census Tract Data for the metropolitan area of Sacramento, CA,...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import geopandas as gpd from pysal.explore import segregation import pysal.lib s_map = gpd.read_file(pysal.lib.examples.get_path("sacramentot2.shp")) s_map.columns gdf = s_map[['geometry', 'HISP_', 'TOT_POP']] gdf['composition'] = gdf['HISP_'] / gdf['TOT_POP'] gdf.pl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Loading the data Step2: Splitting data between train/test Step3: split used for convenience on the average by movie baseline Step4: cleaning ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from random import random import math import numpy as np import copy from scipy import stats import matplotlib.pyplot as plt import pickle as pkl from scipy.spatial import distance import seaborn as sns sns.set_style('darkgrid') def loadMovieLens(path='./data/movielens...
<SYSTEM_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 Data Step2: Select Based On The Result Of A Select
<ASSISTANT_TASK:> Python Code: # Ignore %load_ext sql %sql sqlite:// %config SqlMagic.feedback = False %%sql -- Create a table of criminals CREATE TABLE criminals (pid, name, age, sex, city, minor); INSERT INTO criminals VALUES (412, 'James Smith', 15, 'M', 'Santa Rosa', 1); INSERT INTO criminals VALUES (234, 'Bill Ja...
<SYSTEM_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 knee is located by passing x and y values to knee_locator. Step2: There are plotting functions to visualize the knee point on the raw data ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from kneed.data_generator import DataGenerator as dg from kneed.knee_locator import KneeLocator import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline import numpy as np x = [3.07, 3.38, 3.55, 3.68, 3.78, 3.81, 3.85, 3.88, 3.9, 3.93] y = [0.0, 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: Date/Time data handling Step2: In addition to datetime there are simpler objects for date and time information only, respectively. Step3: Havi...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt # Set some Pandas options pd.set_option('display.notebook_repr_html', False) pd.set_option('display.max_columns', 20) pd.set_option('display.max_rows', 25) from datetime import datetime now = dateti...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Start with initializing a euclidean N-dimensional algebra and assign our pseudoscalar to $I$, pretty standard. Step2: Anti-symmetric Step3: Wh...
<ASSISTANT_TASK:> Python Code: import numpy as np def func2Mat(f,I): ''' Convert a function acting on a vector into a matrix, given the space defined by psuedoscalar I ''' A = I.basis() B = [f(a) for a in A] M = [float(b | a) for a in A for b in B] return np.array(M).reshape(len(B), le...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Toy example Step2: Plotting parameters Step3: We run a an optimization loop with standard settings Step4: We see that some minima is found an...
<ASSISTANT_TASK:> Python Code: print(__doc__) import numpy as np np.random.seed(1234) import matplotlib.pyplot as plt from skopt.learning import ExtraTreesRegressor from skopt import Optimizer from skopt.plots import plot_gaussian_process noise_level = 0.1 # Our 1D toy problem, this is the function we are trying 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: Functions in the module accept the following arguments. Step2: We can also plot the posterior distribution. Step3: We will load the classifica...
<ASSISTANT_TASK:> Python Code: import numpy as np Acc_nbc = np.loadtxt('Data/nbc_anneal.csv', delimiter=',', skiprows=1) Acc_aode = np.loadtxt('Data/aode_anneal.csv', delimiter=',', skiprows=1) names = ("AODE", "NBC") x=np.zeros((len(Acc_nbc),2),'float') x[:,0]=Acc_aode/100 x[:,1]=Acc_nbc/100 #we consider the differe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Search individuals method Step2: Note Step3: In this case, the Family ID can be exchanged through the protocol, although the named field is no...
<ASSISTANT_TASK:> Python Code: from ga4gh.client import client c = client.HttpClient("http://1kgenomes.ga4gh.org") #Obtain dataSet id REF: -> `1kg_metadata_service` dataset = c.search_datasets().next() counter = 0 for individual in c.search_individuals(dataset_id=dataset.id): if counter > 5: break co...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Read input tables Step2: Block tables to get candidate set Step3: Debug blocking output Step4: Match tuple pairs in candidate set Step5: Sel...
<ASSISTANT_TASK:> Python Code: import py_entitymatching as em import profiler import pandas as pd ## Read input tables A = em.read_csv_metadata('dblp_demo.csv', key='id') B = em.read_csv_metadata('acm_demo.csv', key='id') len(A), len(B), len(A) * len(B) A.head(2) B.head(2) # If the tables are large we can downsample 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:
<ASSISTANT_TASK:> Python Code: from collections import defaultdict def gcd(a , b ) : if(b == 0 ) : return a  return gcd(b , a % b )  def splitArray(arr , N ) : mp = defaultdict(int ) for i in range(N ) : mp[arr[i ] ] += 1  G = 0 for i in mp : G = gcd(G , mp[i ] )  if(G > 1 ) : 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:
<ASSISTANT_TASK:> Python Code: import pandas as pd data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]} df = pd.DataFrame(data) s = 'spike' def g(df, s): spike_cols = [col for col in df.columns if s in col and col != s] return spike_cols result = g(df.copy(),s) <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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'snu', 'sandbox-3', 'landice') # 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: 对于所有Matplotlib图,我们首先创建一个图形和一个轴。以最简单的形式,可以如下创建图形和轴: Step2: 在Matplotlib中,图形(类plt.Figure的一个实例)可以被认为是一个包含所有代表轴,图形,文本和标签的对象的容器。轴(类plt.Axes的实例)就是我们在上...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt #使用seaborn-whitegrid风格 plt.style.use('seaborn-whitegrid') import numpy as np fig = plt.figure() ax = plt.axes() fig = plt.figure() ax = plt.axes() x = np.linspace(0, 10, 1000) ax.plot(x, np.sin(x)); plt.plot(x, np.sin(x)); plt.plot(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: Running Compliance Checker on the Scripps Pier shore station data
<ASSISTANT_TASK:> Python Code: import compliance_checker print(compliance_checker.__version__) # First import the compliance checker and test that it is installed properly. from compliance_checker.runner import CheckSuite, ComplianceChecker # Load all available checker classes. check_suite = CheckSuite() check_suite.lo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Loading datasets Step2: The GMQLDataset Step3: Filtering the dataset regions based on a predicate Step4: From this operation we can learn sev...
<ASSISTANT_TASK:> Python Code: import gmql as gl dataset1 = gl.get_example_dataset("Example_Dataset_1") dataset2 = gl.get_example_dataset("Example_Dataset_2") dataset1.schema dataset2.schema filtered_dataset1 = dataset1.reg_select((dataset1.chr == 'chr3') & (dataset1.start >= 30000)) filtered_dataset_2 = dataset2[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: Load the files Step2: First visualize the cluster
<ASSISTANT_TASK:> Python Code: import numpy as np import h5py import matplotlib.pyplot as plt %matplotlib inline # Now nexa modules| import sys sys.path.append("../") from visualization.data_clustering import visualize_data_cluster_text_to_image # First we load the file file_location = '../results_database/text_wall_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step 1 Step1: Step 2 Step2: Step 3 Step3: 2. Applying Sobel filters on HMDI input with Python Step 1 Step4: Step 2 Step5: Step 3 Step7: 3. Applyin...
<ASSISTANT_TASK:> Python Code: from pynq import Overlay Overlay("vbx.bit").download() from pynq.drivers import HDMI from pynq.drivers.video import VMODE_1920x1080,VMODE_1280x720 vmode=VMODE_1280x720 #vmode=VMODE_1920x1080 hdmi_out = HDMI('out',video_mode=vmode) hdmi_in = HDMI('in', video_mode=vmode,frame_list=hdmi_ou...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Learning Curves Step2: They all come from the same underlying process. But if you were asked to make a prediction, you would be more likely to ...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.svm import SVR from sklearn import cross_validation rng = np.random.RandomState(42) n_samples = 200 kernels = ['linear', 'poly', 'rbf'] true_fun = lambda X: X ** 3 X = np.sort(5 * (rng.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: What is a SparkSession? Step2: Check the SparkSession variable Step3: What is a Dataframe? Step4: Create another Dataframe Step5: Check the ...
<ASSISTANT_TASK:> Python Code: from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("Python Spark SQL basic example") \ .master("spark://helk-spark-master:7077") \ .enableHiveSupport() \ .getOrCreate() spark first_df = spark.range(10).toDF("numbers") first_df.show() dog_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: The diffusion follows Fick's law of diffusion Step2: We will solve the partial differential equation (PDE) using method of lines. We discretize...
<ASSISTANT_TASK:> Python Code: reactions = [ ('k', {'A': 1}, {'B': 1, 'A': -1}), ] names, params = 'A B'.split(), ['k'] D = [8e-9, 8e-9] # He diffusion constant in water at room temperature import sympy as sym x, h = sym.symbols('x h') d2fdx2 = sym.Function('f')(x).diff(x, 2) d2fdx2.as_finite_difference([x-h, 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: 1. Constructing API GET Request Step2: You often want to send some sort of data in the URL’s query string. This data tells the API what informa...
<ASSISTANT_TASK:> Python Code: # Import required libraries import requests import json from __future__ import division import math import csv import matplotlib.pyplot as plt # set key key="be8992a420bfd16cf65e8757f77a5403:8:44644296" # set base url base_url="http://api.nytimes.com/svc/search/v2/articlesearch" # set re...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Your Turn Step2: Notes Step3: Then, given the gradient of MSE wrt to w and b, we can define how we update the parameters via SGD Step4: The w...
<ASSISTANT_TASK:> Python Code: import keras.backend as K import numpy as np import matplotlib.pyplot as plt %matplotlib inline from kaggle_data import load_data, preprocess_data, preprocess_labels X_train, labels = load_data('../data/kaggle_ottogroup/train.csv', train=True) X_train, scaler = preprocess_data(X_train) Y_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Beside the usual model in previous sections, let’s create a model that run a Backend instance to simulate and obtain results. Step4: Let’s defi...
<ASSISTANT_TASK:> Python Code: !pip install -q sciunit import sciunit, random from sciunit import Test from sciunit.capabilities import Runnable from sciunit.scores import BooleanScore from sciunit.models import RunnableModel from sciunit.models.backends import register_backends, Backend class RandomNumBackend(Backen...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Init Step2: Downloading genomes Step3: Indexing genomes Step4: Simulating a gradient community Step6: Simulating isotope incorporation Step7...
<ASSISTANT_TASK:> Python Code: workDir = "/home/nick/notebook/SIPSim/t/M.bark_M.ext/" import os import sys %load_ext rpy2.ipython %%R library(ggplot2) library(dplyr) library(tidyr) !cd $workDir; \ seqDB_tools accession-GI2fasta < M.barkeri_refseq.txt > M.barkeri.fna !cd $workDir; \ seqDB_tools accession-GI2fa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Here is a code sample showing how to read the data and draw a colored plot.
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import cm %matplotlib notebook # Load the csv with pandas df = pd.read_csv('hipgalv.LSR.csv', index_col=0) #print(df) # Use matplotlib's default "Reds" colormap. More colormaps and information here: # ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If you evaluate a Python expression that returns a value, that value is displayed as output of the code cell. This only happens, however, for t...
<ASSISTANT_TASK:> Python Code: print('hello, world.') # Would show 9 if this were the last line, but it is not, so shows nothing 4 + 5 # I hope we see 11. 5 + 6 a = 5 + 6 a import numpy as np import scipy.integrate import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_formats = {'svg',} #...
<SYSTEM_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"><h4>Note</h4><p>Before applying SSP (or any artifact repair strategy), be sure to observe Step2: The example data...
<ASSISTANT_TASK:> Python Code: import os import numpy as np import matplotlib.pyplot as plt import mne from mne.preprocessing import (create_eog_epochs, create_ecg_epochs, compute_proj_ecg, compute_proj_eog) sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.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: View the spark context, the main entry point to the Spark API Step2: DataFrames Step3: Create a new DataFrame that contains “young users” only...
<ASSISTANT_TASK:> Python Code: !pyspark sc users = context.load("s3n://path/to/users.json", "json") young = users.filter(users.age<21) young = users[users.age<21] young.select(young.name, young.age+1) young.groupBy("gender").count() young.join(logs, logs.userId == users.userId, "left_outer") young.registerTempT...
<SYSTEM_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 - Problem Statement Step2: The model is stored in a python dictionary where each variable name is the key and the corresponding value is a te...
<ASSISTANT_TASK:> Python Code: import os import sys import scipy.io import scipy.misc import matplotlib.pyplot as plt from matplotlib.pyplot import imshow from PIL import Image from nst_utils import * import numpy as np import tensorflow as tf %matplotlib inline model = load_vgg_model("pretrained-model/imagenet-vgg-ve...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Instantiate AnyPath for different addresses Step2: Next, let's see how what files are present in each location. Step3: We capture all contents...
<ASSISTANT_TASK:> Python Code: from paralleldomain.utilities.any_path import AnyPath absolute_path = "/home/nisseknudsen/Data/testset_dgp" absolute_anypath = AnyPath(path=absolute_path) relative_path = "testset_dgp" relative_anypath = AnyPath(path=relative_path) s3_path = "s3://pd-sdk-c6b4d2ea-0301-46c9-8b63-ef20c0d01...
<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: Why do we need to improve the traing method? Step4: Now let's train the data set the way before, to validate our new class. Step5: Now a sine ...
<ASSISTANT_TASK:> Python Code: %pylab inline %config InlineBackend.figure_format = 'retina' import numpy as np from random import random from IPython.display import FileLink, FileLinks def σ(z): return 1/(1 + np.e**(-z)) def σ_prime(z): return np.e**(z) / (np.e**z + 1)**2 def Plot(fn, *args, **kwargs): argL...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Matplotlib magic Step2: There are many ways to import matplotlib, but the most common way is Step3: Q1 Step4: Let's look at the first few row...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import warnings warnings.filterwarnings('ignore') %matplotlib inline import matplotlib.pyplot as plt df = pd.read_csv('imdb.csv', delimiter='\t') df.head() df.head(2) df['Year'].head(3) df[['Year','Rating']].head(3) df[:10] df[['Year','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: Step2: Note Step3: Note
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import datetime from matplotlib import pyplot as plt import seaborn as sns from sklearn.preprocessing import MinMaxScaler df = pd.read_csv('data/pm25.csv') print(df.shape) df.head() df.isnull().sum()*100/df.shape[0] df.dropna(subset=['pm2.5'], axis=0...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Download the HI-mass data of Westmeier et al. 2017 Step2: There are 31 galaxies in this sample, hence the array has 31 rows. This data can be r...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pydftools as df from pydftools.plotting import mfplot import numpy as np from urllib.request import Request, urlopen # For getting the data online from IPython.display import display, Math, Latex, Markdown, TextDisplayObject req = Request('http://quantumholism.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: Import your saliency model into pysaliency Step2: If you have an LSUN submission file prepared, you can load it with pysaliency.SaliencyMapMode...
<ASSISTANT_TASK:> Python Code: # TODO: Add ModelFromDirectory for log densities # TODO: Change defaults for saliency map convertor (at least in LSUN subclass) # TODO: Write fit functions optimize_for_information_gain(model, stimuli, fixations) my_model = pysaliency.SaliencyMapModelFromDirectory(stimuli_salicon_train, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Closed Form Matting Energy Step2: Now that TensorFlow Graphics is installed, let's import everything needed to run the demos contained in this ...
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The object new_data has been reprojected to Alberts and a linear model have been fitted with residuals stored as residuals Step2: The empirical...
<ASSISTANT_TASK:> Python Code: from external_plugins.spystats import tools %run ../HEC_runs/fit_fia_logbiomass_logspp_GLS.py from external_plugins.spystats import tools hx = np.linspace(0,800000,100) new_data.residuals[:10] gvg.plot(refresh=False,legend=False,percentage_trunked=20) plt.title("Semivariogram of residua...
<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: Import SystemML API Step3: Import numpy, sklearn, and define some helper functions Step5: Example 1 Step6: Examine execution plans, and incre...
<ASSISTANT_TASK:> Python Code: !pip show systemml from systemml import MLContext, dml, dmlFromResource ml = MLContext(sc) print ("Spark Version:" + sc.version) print ("SystemML Version:" + ml.version()) print ("SystemML Built-Time:"+ ml.buildTime()) ml.execute(dml(s = 'Hello World!').output("s")).get("s") import sys,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Functions for convolution, pooling, droput, etc. Step2: 2> Dropout Layer Step3: 3> Pooling Layer Step4: 4> Normalization Layer Step5: 5> Con...
<ASSISTANT_TASK:> Python Code: # Import files import os import sys import numpy as np import matplotlib as plt import tensorflow as tf import time import random import math import pandas as pd import sklearn from scipy import misc import glob import pickle %matplotlib inline plt.pyplot.style.use('ggplot') # RELU GLORO...
<SYSTEM_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 API Key on Kaggle
<ASSISTANT_TASK:> Python Code: !pip install --user --upgrade kaggle import IPython IPython.Application.instance().kernel.do_shutdown(True) #automatically restarts kernel !ls ./kaggle.json import os current_dir=!pwd current_dir=current_dir[0] os.environ['KAGGLE_CONFIG_DIR']=current_dir !${HOME}/.local/bin/kaggle datase...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Diabetes dataset Step2: Our goal is to fit a linear model using Elastic Net regularisation, which predicts the disease progression for a given ...
<ASSISTANT_TASK:> Python Code: from prox_elasticnet import ElasticNet, ElasticNetCV import matplotlib.pyplot as plt import numpy as np %matplotlib inline np.random.seed(319159) from sklearn.datasets import load_diabetes diabetes = load_diabetes() X = diabetes.data y = diabetes.target prop_train = 0.8 n_pts = len(y) 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: Focusing on one of the periapse tables for now
<ASSISTANT_TASK:> Python Code: df = df[df.BIN_PATTERN_INDEX == 'LINEAR linear_0006'] # now can drop that column df = df.drop('BIN_PATTERN_INDEX', axis=1) bin_tables = df.BIN_TBL.value_counts() bin_tables for ind in bin_tables.index: print(ind) print(df[df.BIN_TBL==ind].orbit_segment.value_counts()) df = df[df....
<SYSTEM_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 have to 'preconfigure' the pipeline, because we need to build up the list of targets so that we correctly set up the later stages of the pipe...
<ASSISTANT_TASK:> Python Code: pipe = Pipeline(linkname = 'dSphs') configfile = 'config/master_dSphs.yaml' pipe.preconfigure(configfile) pipe.update_args(dict(config=configfile)) pipe.linknames pipe['data'] pipe['data'].linknames pipe.print_status() pipe.print_status(recurse=True) pipe['data']['analyze-roi'] pipe[...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: import numpy as np a = np.arange(12).reshape(3, 4) a = np.delete(a, 2, axis = 0) <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: Step2: Creating your first neural network with TF-Slim Step3: Let's create the model and examine its structure. Step4: Let's create some 1d regressio...
<ASSISTANT_TASK:> Python Code: from __future__ import absolute_import from __future__ import division from __future__ import print_function import matplotlib %matplotlib inline import matplotlib.pyplot as plt import math import numpy as np import tensorflow as tf import time from datasets import dataset_utils # Main sl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The k-means algorithm is one of the most popular clustering algorithms and very simple with respect to the implementation. Clustering has the go...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib as mpl mpl.use('TkAgg') import matplotlib.pyplot as plt import sklearn.datasets as sk from matplotlib import animation from matplotlib.animation import PillowWriter # Disable if you don't want to save any GIFs. %matplotlib inline data_selection = 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: Step2: Compute and display the Mandelbrot set using Spark SQL using plain old-fashioned ASCII graphics for the output Step4: Mandelbrot in SQL, displa...
<ASSISTANT_TASK:> Python Code: # the function definition def mandelbrot(cR, cI, maxIterations): zR = cR zI = cI i = 1 # Iterative formula for Mandelbrot set: z => z^2 + c # Escape point: |z|^2 >= 4. Note: z nd c are complex numbers while (zR*zR + zI*zI < 4.0 and i < maxIterations): 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: Vamos agora fazer um teste, calculando o histograma usando a função np.histogram e depois calculando as estatísticas da imagem Step2: Os valore...
<ASSISTANT_TASK:> Python Code: def h2stats(h): import numpy as np #import ia898.src as ia hn = 1.0*h/h.sum() # compute the normalized image histogram v = np.zeros(6) # number of statistics # compute statistics n = len(h) # number of gray values v[0] = np.sum((np.arange(n)*hn)) # mean v[...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: import numpy as np a = np.arange(1,11) accmap = np.array([0,1,0,0,0,-1,-1,2,2,1]) add = np.max(accmap) mask = accmap < 0 accmap[mask] += add+1 result = np.bincount(accmap, weights = a) <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: Classification with linear discrimant analysis Step2: Look at performance over time
<ASSISTANT_TASK:> Python Code: # Authors: Martin Billinger <martin.billinger@tugraz.at> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import ShuffleSpl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Eulerian Cycles Step2: Differences between network types Step3: Some context on these networks is given below, first for MIT8. It stems from a...
<ASSISTANT_TASK:> Python Code: from networkit import * %matplotlib inline cd ~/workspace/NetworKit G = readGraph("input/PGPgiantcompo.graph", Format.METIS) # 2-2) and 2-3) Decide whether graph is Eulerian or not # Load/generate 3 graphs of different types mit8 = readGraph("input/MIT8.edgelist", Format.EdgeListTabZero...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Pytorch Introduction Step2: Here we start defining the linear regression model, recall that in linear regression, we are optimizing for the squ...
<ASSISTANT_TASK:> Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', '..', 'notebook_format')) from formats import load_style load_style(css_style='custom2.css', plot_style=False) os.chdir(path)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Question Step2: Classification accuracy Step3: Null accuracy Step4: Comparing the true and predicted response values Step5: Conclusion Step6...
<ASSISTANT_TASK:> Python Code: # read the data into a Pandas DataFrame import pandas as pd url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data' col_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label'] pima = pd.read_csv...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Trap 1 Step2: Now, let's see what happens if we move the import of random outside the scope of get_random_array
<ASSISTANT_TASK:> Python Code: # Import Node and Function module from nipype import Node, Function # Create a small example function def add_two(x_input): return x_input + 2 # Create Node addtwo = Node(Function(input_names=["x_input"], output_names=["val_output"], funct...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: MPI and cluster computing Step2: Executes with mpiexec Step3: Coding for multiple "personalities" (nodes, actually) Step4: Collective communi...
<ASSISTANT_TASK:> Python Code: %%file hellompi.py Parallel Hello World from mpi4py import MPI import sys size = MPI.COMM_WORLD.Get_size() rank = MPI.COMM_WORLD.Get_rank() name = MPI.Get_processor_name() sys.stdout.write( "Hello, World! I am process %d of %d on %s.\n" % (rank, size, name)) !mpiexec -n 4 python...
<SYSTEM_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 for STEM Teachers<br/>Oregon Curriculum Network Step3: <div align="center">graphic by Kenneth Snelson</div>
<ASSISTANT_TASK:> Python Code: import json series_types = ["Don't Know", "Other nonmetal", "Alkali metal", "Alkaline earth metal", "Nobel gas", "Metalloid", "Halogen", "Transition metal", "Post-transition metal", "Lanthanoid", "Actinoid"] class Element...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Noisy Likelihoods Step4: We'll again define our prior (via prior_transform) to be uniform in each dimension from -10 to 10 and 0 everywhere els...
<ASSISTANT_TASK:> Python Code: # system functions that are always useful to have import time, sys, os # basic numeric setup import numpy as np from numpy import linalg # inline plotting %matplotlib inline # plotting import matplotlib from matplotlib import pyplot as plt # seed the random number generator rstate = np.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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 2...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nuist', 'sandbox-2', 'seaice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "em...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd np.random.seed(123) birds = np.random.choice(['African Swallow', 'Dead Parrot', 'Exploding Penguin'], size=int(5e4)) someTuple = np.unique(birds, return_counts=True) def g(someTuple): return pd.DataFrame(np.column_stack(someTuple),columns=['birdT...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Tabular data Step2: Normalization Step3: Categorical data Step5: Exercises Step6: Text
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd %matplotlib inline from sklearn import linear_model x = np.array([[0, 0], [1, 1], [2, 2]]) y = np.array([0, 1, 2]) print(x,y) clf = linear_model.LinearRegression() clf.fit(x, y) print(clf.coef_) x_missing = np.array([...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's start with the temperature, T = 300 &deg;C. Step2: Next we'll create variables for $Q_n = 37,600 \frac{J}{mol}$ and the universal gas con...
<ASSISTANT_TASK:> Python Code: import pint from math import exp, sqrt u = pint.UnitRegistry() Q_ = u.Quantity T = Q_(300, u.degC) print('T = {}'.format(T)) T.ito('degK') print('T = {}'.format(T)) T = T.magnitude * u.kelvin print(T) Qn = 37600 * u.J/u.mol R = 8.31 * u.J/(u.mol*u.kelvin) PN1 = 0.10 PN2 = 5.0 CN1 = (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: In this example notebook, we will walk through the creation of logsums from Step2: We'll also load the saved model from the mode choice estimat...
<ASSISTANT_TASK:> Python Code: import larch, numpy, pandas, os from larch import P, X larch.__version__ hh, pp, tour, skims = larch.example(200, ['hh', 'pp', 'tour', 'skims']) exampville_mode_choice_file = larch.example(201, output_file='exampville_mode_choice.html') m = larch.read_metadata(exampville_mode_choice_fil...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Block Paradigms Step2: df contains about 5 minutes of data recorded at 1000Hz. There are 4 channels, EDA, ECG, RSP and the Photosensor used to ...
<ASSISTANT_TASK:> Python Code: # Import packages import neurokit as nk import pandas as pd import numpy as np import matplotlib import seaborn as sns # Plotting preferences %matplotlib inline matplotlib.rcParams['figure.figsize'] = [14.0, 10.0] # Bigger figures sns.set_style("whitegrid") # White background sns.set_pa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Tf-idf and document similarity Step2: Lets cluster! Step3: But what did we get?
<ASSISTANT_TASK:> Python Code: df = pd.read_csv('../data/wiki/wiki.csv.gz', encoding='utf8', index_col=None) df['text'] = df.text.str[:3000] totalvocab_stemmed = [] totalvocab_tokenized = [] for doc_text in df.text: allwords_stemmed = tokenize_and_stem(doc_text) #for each item in 'synopses', tokenize/stem total...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: You can also list and download other datasets interactively just typing Step2: The fileids method provided by all the datasets in nltk.corpus g...
<ASSISTANT_TASK:> Python Code: import nltk nltk.download("movie_reviews") from nltk.corpus import movie_reviews len(movie_reviews.fileids()) movie_reviews.fileids()[:5] movie_reviews.fileids()[-5:] negative_fileids = movie_reviews.fileids('neg') positive_fileids = movie_reviews.fileids('pos') len(negative_fileids), ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: select interested category to compare using DS-FDR Step2: output the list of differential abundant taxa (True indicates statistical significanc...
<ASSISTANT_TASK:> Python Code: !qiime tools import \ --input-path ../data/deblur-feature-table.biom \ --type 'FeatureTable[Frequency]' \ --source-format BIOMV210Format \ --output-path ../data/dblr_haddad.qza !qiime dsfdr permutation-fdr \ --i-table ../data/dblr_haddad.qza \ --m-metadata-file ../data/metadata_rare2k.tx...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Enable inline plotting in the Jupyter Notebook Step2: Intro to H2O Data Munging Step3: View the top of the H2O frame. Step4: View the bottom ...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy from numpy.random import choice from sklearn.datasets import load_boston from h2o.estimators.random_forest import H2ORandomForestEstimator import h2o h2o.init() # transfer the boston data from pandas to H2O boston_data = load_boston() X = pd.DataFrame(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: Generate Data Step2: It's easier if we select the correct X and Y axis. Usually, The Y axis would be the value we want to predict and X would b...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np from scipy import stats import collections import time from sklearn.linear_model import SGDRegressor total_bills = np.random.randint(100, size=1000) tips = total_bills * 0.10 x = pd.Series(tips, name='tips') y = pd.Series(total_...
<SYSTEM_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, let's load the data. Write the path to your iris.csv file (i.e. the one from Lab 02) in the cell below Step2: Execute the cell below to l...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd path_to_csv = "data/iris.csv" df = pd.read_csv(path_to_csv, index_col=['species', 'sample_number']) df.head() df.plot(kind='hist'); versicolor = df.loc['versicolor'] versicolor.plot(kind='hist'); versicolor.plot(kind='hist', subplots=True, layou...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lerne Lineare Regression auf Daten Step2: <span style="color Step3: <span style="color Step4: <span style="color
<ASSISTANT_TASK:> Python Code: #Importiere Python Libraries %matplotlib inline import pylab as pl import seaborn as sns sns.set(font_scale=1.7) from plotly.offline import init_notebook_mode, iplot from plotly.graph_objs import * import plotly.tools as tls #Set to True init_notebook_mode(connected=True) import scipy as ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Steps Step4: Craigslist data table columns Step5: Local data files Step16: Create FIPS look-up tables Step17: Get data for a single region Step18: ...
<ASSISTANT_TASK:> Python Code: import pandas as pd import psycopg2 import paramiko import os import numpy as np import json import zipfile DATA_DIR=os.path.join('..','data') Path to local data directory #read postgres connection parameters with open('postgres_settings.json') as settings_file: settings = json....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Then, we define a function that will be mapped onto each job. This function takes the initial Step2: Then, we load the ChemKED file and generat...
<ASSISTANT_TASK:> Python Code: import cantera as ct import numpy as np from multiprocessing import Pool from pyked import ChemKED # Suppress warnings from loading the mechanism file ct.suppress_thermo_warnings() def run_simulation(T, P, X): gas = ct.Solution('LLNL_sarathy_butanol.cti') gas.TPX = T, P, X re...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: A resonator object takes the path of the data file as an argument (mandatory). The path can be retrieved by using the file UUID and qkit's file ...
<ASSISTANT_TASK:> Python Code: ## start qkit and import the necessary classes; here we assume a already configured qkit environment import qkit qkit.start() from qkit.analysis.resonator import Resonator r = Resonator(qkit.fid.measure_db['XXXXXX']) r.fit_lorentzian(f_min = 5.0e9) ## set lower frequency boundary r.fit...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Rabbit Redux Step3: Now update run_simulation with the following changes Step4: Test your changes in run_simulation Step6: Next, update plot_...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from modsim import * system = System(t0 = 0, t_end = 10, adult_pop0 = 10, birth_rate = 0.9, death_rate = 0.5) system def run_simulation(system): Runs a proportional growth model. Adds TimeSe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Looking at the vectors Step2: Here's the first 25 "words" in glove. Step3: This is how you can look up a word vector. Step4: Just for fun, le...
<ASSISTANT_TASK:> Python Code: def get_glove(name): with open(path+ 'glove.' + name + '.txt', 'r') as f: lines = [line.split() for line in f] words = [d[0] for d in lines] vecs = np.stack(np.array(d[1:], dtype=np.float32) for d in lines) wordidx = {o:i for i,o in enumerate(words)} save_array(res_pat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: parameters to set Step2: generate data Step3: plot timeseries. Can take a minute to appear due to plot size and complexity. Step4: functions ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib matplotlib.rc('xtick', labelsize=14) matplotlib.rc('ytick', labelsize=14) from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: df_raw['2yf1y'] = df_raw[['1y','3y']].apply(lambda x
<ASSISTANT_TASK:> Python Code: df_raw.tail() def getForward(v,t1=1,t2=2): return (np.power(np.power(1+v[1]/100,t2)/np.power(1+v[0]/100,t1),1/(t2-t1))-1)*100 ind1 = 0 ind2 = 1 v2 = df_raw.iloc[-1,ind2] v1 = df_raw.iloc[-1,ind1] t1 = int(df_raw.columns[ind1].strip('y')) t2 = int(df_raw.columns[ind2].strip('y')) 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: We can see that simulating the data as an AR(1) model is not effective in giving us anything similar the aquired data. This is due to the fact ...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import scipy.io as sio from sklearn import datasets, linear_model %matplotlib inline def set_data(p, x): temp = x.flatten() n = len(temp[p:]) x_T = temp[p:].reshape((n, 1)) X_p = np.ones((n, p + 1)) for i in range(1, 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: Basic rich display Step3: Use the HTML object to display HTML in the notebook that reproduces the table of Quarks on this page. This will requi...
<ASSISTANT_TASK:> Python Code: from IPython.display import Image from IPython.display import HTML from IPython.display import display assert True # leave this to grade the import statements Image(url='http://upload.wikimedia.org/wikipedia/commons/4/43/The_Earth_seen_from_Apollo_17_with_transparent_background.png') ass...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: To get different sections of a string, we can use groups via parenthesis Step2: If parenthesis are actually part of the pattern, they need to b...
<ASSISTANT_TASK:> Python Code: import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') phoneNumRegex.search('My number is 415-555-4242') # returns a match object mo = phoneNumRegex.search('My number is 415-555-4242') # store match object mo.group() # print matched strings in match object phoneNumRegex = re.com...
<SYSTEM_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 Multiplication Step2: Of course, trivial identities are applied. Step3: In the case of word labels, adjacent words are not fused Step4:...
<ASSISTANT_TASK:> Python Code: import vcsn ctx = vcsn.context('law_char, q') def exp(e): return ctx.expression(e) exp('a*b') * exp('ab*') exp('<2>a') * exp('<3>\e') exp('<2>a') * exp('\z') exp('a') * exp('b') # Two one-letter words exp('ab') # One two-letter word exp('(a)(b)') # Two one-letter words exp('ab') *...
<SYSTEM_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...
<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: Host and user information Step2: List of file prefixes for micrograph images and XML metadata Step3: For each name in the list
<ASSISTANT_TASK:> Python Code: import mdcs user='admin' pswd='admin' host='http://127.0.0.1:8000' template_name='TEM-Tutorial' name_list=[ "Al6061_DF_343C", "Al6061_SAED_343C", "Al6061-BF-343C", "CoAl-W-900-1000h-SAED", "CoAlW-900-1000h", "TRIP700-750C-carbide-SAED", "TRIP700-carbide-750C-...
<SYSTEM_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...
<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 = (10, 20) DON'T MODIFY 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: What is our independent variable? What is our dependent variable? Step2: Median reaction time, congruent condition Step3: Notice that not a si...
<ASSISTANT_TASK:> Python Code: # Imports import pandas as pd import numpy as np import seaborn as sns from matplotlib import pyplot as plt from scipy.stats import ttest_rel, norm # Read in data df = pd.read_csv('stroopdata.csv') IQR_congruent = df['Congruent'].quantile(0.75) - df['Congruent'].quantile(0.25) IQR_incong...