Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
14,200
<ASSISTANT_TASK:> Python Code: data_in_shape = (3, 6) rnn = GRU(4, activation='tanh', recurrent_activation='hard_sigmoid') layer_0 = Input(shape=data_in_shape) layer_1 = rnn(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) weights = [] for i, w in enumerate(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: [recurrent.GRU.1] units=5, activation='sigmoid', recurrent_activation='sigmoid' Step2: [recurrent.GRU.2] units=4, activation='tanh', recurrent_...
14,201
<ASSISTANT_TASK:> Python Code: if os.path.exists('dress_sf_processed.sf'): reference_sf = graphlab.SFrame('dress_sf_processed.sf') else: reference_sf = graphlab.SFrame('https://static.turi.com/datasets/dress_sf_processed.sf') reference_sf.save('dress_sf_processed.sf') if os.path.exists('dress_nn_model'): ...
<SYSTEM_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. Create a Predictive Service (One time) <a id='create'></a> Step2: Load an already created service Step3: Query the model <a id='query'></a>...
14,202
<ASSISTANT_TASK:> Python Code: import re format_pat= re.compile( r"(?P<host>[\d\.]+)\s" r"(?P<identity>\S*)\s" r"(?P<user>\S*)\s" r"\[(?P<time>.*?)\]\s" r'"(?P<request>.*?)"\s' r"(?P<status>\d+)\s" r"(?P<bytes>\S*)\s" r'"(?P<referer>.*?)"\s' r'"(?P<user_agent>.*?)"\s*' ) logPath = "...
<SYSTEM_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's the full path to the log file I'm analyzing; change this if you want to run this stuff yourself Step2: Now we'll whip up a little script...
14,203
<ASSISTANT_TASK:> Python Code: import os import numpy as np import matplotlib.pyplot as plt from astropy.table import Table, vstack from astropy.io import fits import multiprocessing nproc = multiprocessing.cpu_count() // 2 from desispec.io.util import write_bintable from desitarget from desiutil.log import get_logger...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Establish the I/O path, random seed, and path to the dust maps and desired healpixel. Step2: All or none of the output files can be overwritten...
14,204
<ASSISTANT_TASK:> Python Code: import pandas as pd %matplotlib inline df = pd.read_csv('stroopdata.csv') df['diff'] = df['Incongruent'] - df['Congruent'] df df.describe() df.plot.scatter(x='Congruent',y='Incongruent'); (df.Incongruent - df.Congruent).plot.hist(); %%R n = 24 mu = 7.964792 s = 4.864827 CL = 0.95 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: The experiment takes participants with two test, congruent task and incongruent task. Congruent task is word with agreeing text and font color, ...
14,205
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import numpy as np import psycopg2 import psycopg2.extras from itertools import chain from collections import Counter, defaultdict import requests import imageio import matplotlib.pyplot as plt import numpy as np from PIL import Image, ImageDraw from io import...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The fetch_image function below fetches an image from wikipedia given a wikipedia id for that image Step2: The code here relies on wikipedia hav...
14,206
<ASSISTANT_TASK:> Python Code: #import pandas and numpy libraries import pandas as pd import numpy as np import sys #sys needed only for python version #import gaussian naive bayes from scikit-learn import sklearn as sk #seaborn for pretty plots import seaborn as sns #display versions of python and packages print('\npy...
<SYSTEM_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 dataset doesn't include column names, and the values are text characters Step2: Added column names from the UCI documentation Step3: The d...
14,207
<ASSISTANT_TASK:> Python Code: names_df = pd.read_csv("./IMA_mineral_names.txt", sep=',', header=None, names=['names']) names_df['names'] = names_df['names'].str.strip().str.lower() names_df['len'] = names_df['names'].str.len() names_df['tuple'] = names_df['names'].apply(lambda x: tuple(sorted(set(x)))) names_df['setle...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Remove duplicates Step2: Create letter table Step3: Find argmin in the letter distribution Step4: Recursion Step5: The effective ratio crite...
14,208
<ASSISTANT_TASK:> Python Code: !pip install tensorflow-gpu %env CUDA_DEVICE_ORDER=PCI_BUS_ID %env CUDA_VISIBLE_DEVICES=0,1 import os print(os.environ["CUDA_DEVICE_ORDER"]) print(os.environ["CUDA_VISIBLE_DEVICES"]) import tensorflow as tf from tensorflow.python.client import device_lib device_lib.list_local_devices() tf...
<SYSTEM_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 https Step2: From https
14,209
<ASSISTANT_TASK:> Python Code: for st_type, ways in abq_st_types.iteritems(): for name in ways: better_name = update_name(name, mapping) if name != better_name: print name, "=>", better_name Honolulu: Kalakaua Ave => Kalakaua Avenue Lusitania St. => Lusitania Street ... Albuquerque: Vall...
<SYSTEM_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: <hr> Step3: Number of documents Step4: Number of node nodes. Step5: Number of way nodes. Step6: Total Number of contributors. S...
14,210
<ASSISTANT_TASK:> Python Code: #%matplotlib notebook # imports from importlib import reload import numpy as np import os from pkg_resources import resource_filename from matplotlib import pyplot as plt from scipy import interpolate from astropy import units from astropy.table import Table from astropy.cosmology import ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: DM -- Piece by piece (as coded) Step2: Cumulative plot
14,211
<ASSISTANT_TASK:> Python Code: import numpy as np import ipyvolume as ipv V = np.zeros((128,128,128)) # our 3d array # outer box V[30:-30,30:-30,30:-30] = 0.75 V[35:-35,35:-35,35:-35] = 0.0 # inner box V[50:-50,50:-50,50:-50] = 0.25 V[55:-55,55:-55,55:-55] = 0.0 ipv.figure() ipv.volshow(V, level=[0.25, 0.75], opacity=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: Visualizating a scan of a male head
14,212
<ASSISTANT_TASK:> Python Code: %pylab %matplotlib inline %run jupyter_helpers %run yc_framework figure_width = 16 eval_date = create_date('2017-01-03') def generate_pricing_curvemap(eval_date): random.seed(0) pricing_curvemap = CurveMap() t = linspace(eval_date+0, eval_date+365*80, 7) def createCurve(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: Pricing Curve Map Step2: Interpolation Modes Step3: Curve Builder Step4: Instrument Repricing Step5: Display price ladder for a specific cur...
14,213
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import sys sys.path.insert(0, "../..") from insights.combiners.httpd_conf import get_tree from insights.parsr.query import * conf = get_tree() conf["Alias"] conf["Directory"] conf["Directory"]["Options"] conf["Directory", "/"] conf["Directory", "/"...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: conf now contains the consolidated httpd configuration tree from my machine. The API that follows is exactly the same for nginx, multipath, logr...
14,214
<ASSISTANT_TASK:> Python Code: mktcaps = {'AAPL':538.7,'GOOG':68.7,'IONS':4.6}# Dictionary wird initialisiert print(type(mktcaps)) print(mktcaps) print(mktcaps.values()) print(mktcaps.keys()) print(mktcaps.items()) c=mktcaps.items() print c[0] mktcaps['AAPL'] #Gibt den Wert zurück der mit dem Schlüssel "AAPL" verknüpft...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <h3>Beispiel Step2: <h3>Beispiel Step3: <h2>Beispiel Studenten - mit dictionary</h2> Step4: <h2>Schrittweiser Aufbau eines Studentenverezichn...
14,215
<ASSISTANT_TASK:> Python Code: try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq --pre print("installed cirq.") from typing import Iterable, List, Optional, Sequence import matplotlib.pyplot as plt import numpy as np import os import cirq import cirq_google as 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: Note Step2: Defining the circuit Step3: This line is now broken up into a number of segments of a specified length (number of qubits). Step4: ...
14,216
<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: Text classification with TensorFlow Lite Model Maker Step2: Import the required packages. Step3: Get the data path Step4: You can also upload...
14,217
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import sys # Modify the path sys.path.append("..") import pandas as pd import yellowbrick as yb import matplotlib.pyplot as plt from yellowbrick.classifier import ROCAUC from sklearn.model_selection import train_test_split occupancy = pd.read_csv('data/occu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Binary Classification with 1D Coefficients or Feature Importances Step2: Looks good; everything works! Step3: Some of these generate the Index...
14,218
<ASSISTANT_TASK:> Python Code: import numpy as np np.random.seed(3908544) # Generate two random datasets. data1 = np.random.normal(loc = 0, scale = 58, size = 1000) data2 = 200 * np.random.random(1000) - 100 # What are their means and variances? print("Dataset 1 :: {:.2f} (avg) :: {:.2f} (std)".format(data1.mean(), dat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Both datasets contain 1000 random numbers. Both datasets have very nearly the same mean and same standard deviation. Step2: Behold Step3: If y...
14,219
<ASSISTANT_TASK:> Python Code: a_df = pd.DataFrame([ { "Name": "A 회사 직원 (1)", "Age": 30, }, { "Name": "A 회사 직원 (2)", "Age": 29, } ]) b_df = pd.DataFrame([ { "Name": "B 회사 직원 (1)", "Age": 33, }, ...
<SYSTEM_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 회사가 합병해서 하나의 DF으로 만들자. Step2: append 2. concat 이 있어. Step3: pd.concat Step4: 카카오(A)와 다음(B) 합병 했는데 누가 어디 출신인지 알고 싶다. Step5: df[STR] =>...
14,220
<ASSISTANT_TASK:> Python Code: from simulator import Simulator, Map, Agent import numpy as np class config: metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 10, 'world_width': 300, 'world_height': 300, 'screen_width': 600, 'screen_height': 600, 'dt': 1.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: In bugbot simulation, either map or agents are subclass of Geom2d which is a wrapper over Geom defined in OpenAI Gym. You can define a Geom2d us...
14,221
<ASSISTANT_TASK:> Python Code: from helpers import load_data # load dataset x, y = load_data() def build_k_indices(y, k_fold, seed): build k indices for k-fold. num_row = y.shape[0] interval = int(num_row / k_fold) np.random.seed(seed) indices = np.random.permutation(num_row) k_indices = [indice...
<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: Cross-Validation and Bias-Variance decomposition Step5: Bias-Variance Decomposition
14,222
<ASSISTANT_TASK:> Python Code: % matplotlib inline import os, sys, time import math, random import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from joblib import Parallel, delayed %run 'ssvm.ipynb' check_protocol = True traj_group_test = dict() test_ratio = 0.3 for key in sor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Run notebook ssvm.ipynb Step2: Sanity check for evaluation protocol
14,223
<ASSISTANT_TASK:> Python Code: import kfp import kfp.gcp as gcp import kfp.dsl as dsl import kfp.compiler as compiler import kfp.components as comp import datetime import kubernetes as k8s # Required Parameters PROJECT_ID='<ADD GCP PROJECT HERE>' GCS_BUCKET='gs://<ADD STORAGE LOCATION HERE>' # Optional Parameters, but...
<SYSTEM_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 client Step2: Build reusable components Step3: Create a Docker container Step4: Build docker image Step5: If you want to use docker t...
14,224
<ASSISTANT_TASK:> Python Code: # Planet class definition at the end of Part 1 # code to make sure constructors and get methods all work <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: Test your code to make sure that the class definition worked.
14,225
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display def random_line(m, b, sigma, size=10): Create a line y = m*x + b + N(0,sigma**2) between x=[-1.0,1.0] Param...
<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: Line with Gaussian noise Step5: Write a function named plot_random_line that takes the same arguments as random_line and creates a random line ...
14,226
<ASSISTANT_TASK:> Python Code: import vcsn %%automaton a1 context = "lal_char(abc), z" $ -> 0 0 -> 1 <2>a 0 -> 2 <3>a 1 -> 1 a 1 -> 3 <4>a 2 -> 2 a 2 -> 4 a 3 -> $ 4 -> $ a1.minimize() %%automaton a context = "lal_char, z" $ -> 0 $ -> 1 <2> 0 -> 0 a 0 -> 1 b 0 -> 2 <3>a,b 0 -> 3 b 1 -> 1 a, b 1 -> 2 a, <2>b 1 -> 3 <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: Weighted Step2: The following example is taken from lombardy.2005.tcs, Fig. 4. Step3: Signature Step4: Moore Step5: Brzozowski Step6: Hopcr...
14,227
<ASSISTANT_TASK:> Python Code: %pylab inline import os import os.path import re import astropy.table import astropy.units as u from astropy.io import fits from astropy import wcs def read_raytracing(num_sections=14, num_groups=12): # Initialize the result arrays. wavelength = np.zeros(num_sections) ba...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Preprocess Ray Tracing Results Step2: Reproduce the plot on the geometric_blur tab of the DESI-0347-v13 spreadsheet. For reference, the fiber d...
14,228
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import quantecon as qe # matplotlib settings plt.rcParams['axes.xmargin'] = 0 plt.rcParams['axes.ymargin'] = 0 def approx_lq(s_star, x_star, f_star, Df_star, DDf_star, g_star, Dg_star, discount): Return an approximating LQ insta...
<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: We consider a dynamic maximization problem with Step3: Optimal Economic Growth Step4: Function definitions Step5: Steady state Step6: (s_sta...
14,229
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np ?plt.scatter() from matplotlib import markers markers.MarkerStyle.markers.keys() x = np.random.rand(100) y = np.random.rand(100) plt.scatter(x, y, label = 'The Dots', c = u'r', marker = u'o') plt.grid(True) plt.box(Fal...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Scatter plots Step2: Histogram
14,230
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.integrate import odeint from IPython.html.widgets import interact, fixed g = 9.81 # m/s^2 l = 0.5 # length of pendulum, in meters tmax = 50. # seconds t = np.linspace(0, tmax, int(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Damped, driven nonlinear pendulum Step4: Write a function derivs for usage with scipy.integrate.odeint that computes the derivatives for the da...
14,231
<ASSISTANT_TASK:> Python Code: # Import libraries import numpy as np import pandas as pd # Read student data student_data = pd.read_csv("student-data.csv") print "Student data read successfully!" # Note: The last column 'passed' is the target/label, all other are feature columns # TODO: Compute desired values - replac...
<SYSTEM_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, can you find out the following facts about the dataset? Step2: 3. Preparing the Data Step3: Preprocess feature columns Step4: Split data...
14,232
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer queries, documents = load_data() assert type(queries) == list assert type(documents) == list tfidf = TfidfVectorizer() tfidf.fit_transform(documents) from sklearn.metrics.pairwise import 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:
14,233
<ASSISTANT_TASK:> Python Code: import pints import pints.toy as toy import pints.plot import numpy as np import matplotlib.pyplot as plt # Use the toy logistic model model = toy.LogisticModel() real_parameters = [0.015, 500] times = np.linspace(0, 1000, 100) org_values = model.simulate(real_parameters, times) # Add ind...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Visualisation of the data Step2: Plotting autocorrelation of the residuals Step3: The figure shows no significant autocorrelation in the resid...
14,234
<ASSISTANT_TASK:> Python Code: import time import numpy as np import matplotlib.pyplot as plt import pandas as pd %matplotlib inline # config directory must have "__init__.py" file # from the 'config' directory, import the following classes: from config import Motor, ASI_Controller, Autosipper from config import utils...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Autosipper Step2: Manifold Step3: Micromanager Step4: Preset Step5: ACQUISITION Step6: MM Get info Step7: Video Step8: SNAP CV2 Step9: E...
14,235
<ASSISTANT_TASK:> Python Code: from IPython.display import * SVG('three_receiver_cal/pics/vnaBlockDiagramForwardRotated.svg') ls three_receiver_cal/data/ import skrf as rf %matplotlib inline from pylab import * rf.stylely() raw = rf.read_all_networks('three_receiver_cal/data/') # list the raw measurements raw.keys...
<SYSTEM_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 fully correct an arbitrary two-port, the device must be measured in two orientations, call these forward and reverse. Because there is no sw...
14,236
<ASSISTANT_TASK:> Python Code: fertility_df, life_expectancy_df, population_df_size, regions_df, years, regions_list = process_data() sources = {} region_name = regions_df.Group region_name.name = 'region' for year in years: fertility = fertility_df[year] fertility.name = 'fertility' life = life_expectancy_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: sources looks like this Step2: Build the plot Step3: Build the axes Step4: Add the background year text Step5: Add the bubbles and hover Ste...
14,237
<ASSISTANT_TASK:> Python Code: #import sys #sys.path.insert(0,'/path/to/pydensecrf/') import pydensecrf.densecrf as dcrf from pydensecrf.utils import unary_from_softmax, create_pairwise_bilateral import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['image.interpolation'] = 'nearest' plt.rc...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Unary Potential Step2: Run inference with unary potential Step3: Pairwise terms Step4: Run inference of complete DenseCRF
14,238
<ASSISTANT_TASK:> Python Code: # Author: Jussi Nurminen (jnu@iki.fi) # # License: BSD (3-clause) import mne import os from mne.datasets import multimodal fname_raw = os.path.join(multimodal.data_path(), 'multimodal_raw.fif') print(__doc__) raw = mne.io.read_raw_fif(fname_raw) print(raw.acqparser) cond = raw.acqparse...
<SYSTEM_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 file Step2: Check DACQ defined averaging categories and other info Step3: Extract epochs corresponding to a category Step4: Get epoc...
14,239
<ASSISTANT_TASK:> Python Code: d = pq('<span><p class="hello">Hi</p><p>Bye</p></span>') for each in d.children(): print each.text r = requests.get(sampleurl1) r.raise_for_status() r.content blurb = pq(r.content) for detail in blurb('dt'): print detail.text #blurb().text() r = requests.get(sampleurl2) r.raise_fo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Sample Step2: again Step3: pyqyery get Details sample
14,240
null
null
14,241
<ASSISTANT_TASK:> Python Code: import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, fea...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Training a decision tree on this starter data Step2: Counts of actual and predicted values Step3: Which turn out to match up very poorly. No t...
14,242
<ASSISTANT_TASK:> Python Code: # For use in Quantopian Research, exploring interactively from quantopian.interactive.data.quandl import cboe_vvix as dataset # import data operations from odo import odo # import other libraries we will use import pandas as pd # Let's use blaze to understand the data a bit using Blaze ds...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's go over the columns Step2: <a id='pipeline'></a> Step3: Now that we've imported the data, let's take a look at which fields are availabl...
14,243
<ASSISTANT_TASK:> Python Code: help('learning_lab.03_interface_properties') from importlib import import_module script = import_module('learning_lab.03_interface_properties') from inspect import getsource print(getsource(script.main)) print(getsource(script.demonstrate)) run ../learning_lab/03_interface_properties.py...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Implementation Step2: Execution Step3: HTTP
14,244
<ASSISTANT_TASK:> Python Code: enunciado = list([r'\frac{7!}{6!}',r'\frac{{8!}}{{9!}}',r'\frac{{9!}}{{5!\cdot 4!}}',r'\frac{{m!}}{{(m - 1)!}}', r'\frac{{( {m + 1} )!}}{{( {m - 1} )!}}']) enunciado enunciado = list([r'\frac{7!}{6!}',r'\frac{{8!}}{{9!}}',r'\frac{{9!}}{{5!\cdot 4!}}',r'\frac{{m!}}{{(m - 1)!}}', r'\frac{{(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ejercicio
14,245
<ASSISTANT_TASK:> Python Code: __author__ = 'shivam_gaur' import requests from bs4 import BeautifulSoup import re from pymongo import MongoClient # Global Config Variables client_key = '&key=<insert_your_39_character_api_key_here>' _URL_ = 'https://maps.googleapis.com/maps/api/geocode/xml?address=' count = 0 # same he...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Declaring the important helper functions and global variables Step2: Connecting to the Mongo DB client running on the same machine. Step3: Hel...
14,246
<ASSISTANT_TASK:> Python Code: # setup SymPy from sympy import * x, y, z, t = symbols('x y z t') init_printing() # define the matrices A and B, and the vecs v and w A = Matrix([[1,3], [4,5]]) B = Matrix([[-1,0], [ 3,3]]) v = Matrix([[1,2]]).T # the .T makes v a column vector w = Matrix([[-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: Definitions
14,247
<ASSISTANT_TASK:> Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].uppe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Note Step2: Lesson Step3: Project 1 Step4: We'll create three Counter objects, one for words from positive reviews, one for words from negati...
14,248
<ASSISTANT_TASK:> Python Code: # importando el modulo de regex de python import re # compilando la regex patron = re.compile(r'\bfoo\b') # busca la palabra foo # texto de entrada texto = bar foo bar foo barbarfoo foofoo foo bar # match nos devuelve None porque no hubo coincidencia al comienzo del texto print(patr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Buscando coincidencias Step3: Ahora que ya tenemos el objeto de expresión regular compilado podemos utilizar alguno de los siguientes métodos p...
14,249
<ASSISTANT_TASK:> Python Code: import magma as m from mantle import DFF class Register(m.Generator): Generate an n-bit register Interface --------- I : In(Bits[width]), O : Out(Bits[width]) @staticmethod def generate(width: int): T = m.Bits[width] class _Register(m...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Register - col and join Step3: fork Step5: There is a lot going on in this function. Step7: scan
14,250
<ASSISTANT_TASK:> Python Code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False) DO NOT MODIFY THIS CELL def fully_connected(prev_layer, num_units): Create a fully connectd layer with the given layer...
<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: Batch Normalization using tf.layers.batch_normalization<a id="example_1"></a> Step6: We'll use the following function to create convolutional l...
14,251
<ASSISTANT_TASK:> Python Code: # TODO: You Must Change the setting bellow MYSQL = { 'user': 'root', 'passwd': '', 'db': 'coupon_purchase', 'host': '127.0.0.1', 'port': 3306, 'local_infile': True, 'charset': 'utf8', } DATA_DIR = '/home/nasuno/recruit_kaggle_datasets' # ディレクトリの名前に日本語(マルチバイト文...
<SYSTEM_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や変数の初期化 Step2: 2. データベースへのデータの格納 Step3: 次に、データのインサートです。 Step4: テーブルの作成に利用したCREATE TABLE文には、 Step5: 実行すると、それぞれのレコードでWarningが発生します...
14,252
<ASSISTANT_TASK:> Python Code: aapl = data.DataReader('AAPL', 'yahoo', '2000-01-01') print(aapl.head()) plt.plot(aapl.Close) ibm = data.DataReader('AAPl', 'yahoo', '2000-1-1') print(ibm['Adj Close'].head()) %matplotlib inline ibm['Adj Close'].plot(figsize=(10,6)) plt.ylabel('price') plt.xlabel('year') plt.title('Pric...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: $\Rightarrow$ various different price series Step2: $\Longrightarrow$ There was a stock split 7 Step3: Define new financial instruments Step4:...
14,253
<ASSISTANT_TASK:> Python Code: import os from urllib.request import urlretrieve import numpy as np import matplotlib.pyplot as plt from SeisCL import SeisCL url = "http://sw3d.cz/software/marmousi/little.bin/velocity.h@" if not os.path.isfile("velocity.h@"): urlretrieve(url, filename="velocity.h@") vel = np.fromfil...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: For inversion, we often want a coaser grid. We must also pad the model for the absorbing boundary and create the vs and rho paramters. Step2: W...
14,254
<ASSISTANT_TASK:> Python Code: # import requirements import pandas as pd import nltk #import gensim import spacy # New York Times data ## read subset of data from csv file into panadas dataframe df = pd.read_csv('1_100.csv') ## for now, chosing one article to illustrate preprocessing article = df['full_text'][939] # S...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <h2>Data</h2> Step2: Let's take a peek at the raw text of this article to see what we are dealing with! Step3: <h2>Preprocessing Text</h2> Ste...
14,255
<ASSISTANT_TASK:> Python Code: from IPython.display import Audio,Image, YouTubeVideo YouTubeVideo('S5SG9km2f_A', height=450, width=900) %matplotlib inline import warnings warnings.simplefilter('ignore') import numpy as np import matplotlib.pyplot as plt import pandas import geopandas from pygridgen import Gridgen from...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Main Tutorial Step2: Loading and plotting the boundary data Step3: Generating a grid with pygridgen, plotting with pygridtools Step4: Interac...
14,256
<ASSISTANT_TASK:> Python Code: running_id = 0 output = [[0]] with open("E:/output.txt") as file_open: for row in file_open.read().split("\n"): cols = row.split(",") if cols[0] == output[-1][0]: output[-1].append(cols[1]) output[-1].append(True) else: outpu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Problems Step2: Problems Step3: Problems Step4: If we want to look at covariates, we need a new approach. Step5: Once we've fit the data, ...
14,257
<ASSISTANT_TASK:> Python Code: %tensorflow_version 1.x !curl -Lo deepchem_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py import deepchem_installer %time deepchem_installer.install(version='2.3.0') !wget https://raw.githubusercontent.com/deepchem/deepchem/master/dataset...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We need to load a dataset of estimated aqueous solubility measurements [1] into deepchem. The data is in CSV format and contains SMILES strings,...
14,258
<ASSISTANT_TASK:> Python Code: import LFPy import MEAutility as mu import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec cellParameters = { 'morphology' : 'morphologies/L5_Mainen96_LFPy.hoc', 'tstart' : -50, # ignore startup transients 'tstop' : 100, 'dt' : 2**-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: Create some dictionarys with parameters for cell Step2: Create an helper function to instantiate a cell object given a set of parameters Step3:...
14,259
<ASSISTANT_TASK:> Python Code: #If you haven't already, make sure you install the `dfcx-scrapi` library !pip install dfcx-scrapi from dfcx_scrapi.tools.copy_util import CopyUtil creds_path = '<YOUR_CREDS_FILE>' agent_id = '<YOUR_AGENT_ID>' source_flow = 'Default Start Flow' target_flow = 'My Target Flow' cu = CopyUt...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Imports Step2: User Inputs Step3: Get Flows Map from Agent Step4: Get All Pages from Source Flow Step5: Extract Subset of Pages To Copy Step...
14,260
<ASSISTANT_TASK:> Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns %matplotlib inline # TODO 1: Read in the advertising.csv file and set it to a data frame called ad_data. # TODO: Your ...
<SYSTEM_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 Dataset Step2: Check the head of ad_data Step3: Use info and describe() on ad_data Step4: Let's check for any null values. Step5: E...
14,261
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'dwd', 'sandbox-2', 'aerosol') # 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...
14,262
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import string as str train_data = pd.read_csv('train_data.csv',header = 0) y = train_data["Target"] y = y.values #convert to ndarray train_data = train_data.drop("Target",1) x = train_data.values x = np.c_[np.ones(x.shape[0]),x] def calculateCost (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: x ==> Array of Feature Values Step2: If anyone's wondering why I didn't transpose my Parameters array, one dimensional arrays do not need to be...
14,263
<ASSISTANT_TASK:> Python Code: from fretbursts import * sns = init_notebook() import lmfit; lmfit.__version__ import phconvert; phconvert.__version__ url = 'http://files.figshare.com/2182604/12d_New_30p_320mW_steer_3.hdf5' download_file(url, save_dir='./data') filename = "./data/12d_New_30p_320mW_steer_3.hdf5" import...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Downloading the sample data file Step2: Selecting a data file Step3: Data load and Burst search Step4: For convenience we can set the correct...
14,264
<ASSISTANT_TASK:> Python Code: from cave.cavefacade import CAVE #cave = CAVE(["workflow-result"], "test_jupyter", ["."], file_format='BOHB') cave = CAVE(folders=["./smac3/example_output/run_1", "./smac3/example_output/run_2"], output_dir="cave_on_jupyter", ta_exec_dir=["./smac3"], 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: We can use the CAVE-object to generate general information in tables Step2: Performance Analysis Step3: Only available for instances, CAVE can...
14,265
<ASSISTANT_TASK:> Python Code: # %reload_ext autoreload # %autoreload 2 %matplotlib inline import torch import torchvision import numpy as np # import mnist_loader # train, valid, test = mnist_loader.load_data(path='data/mnist/') # torchvision datasets are PIL.Image images of range [0,1]. Must trsfm them # to Tensors...
<SYSTEM_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. Data Loading Step2: 2. Network Definition Step3: 3. Loss Function & Optimizer Definitions Step4: 4. Training Step5: Step6: NOTE Step7: ...
14,266
<ASSISTANT_TASK:> Python Code: # import math lib from math import pi # import Qiskit from qiskit import Aer, IBMQ, execute from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools from qiskit.tools.visualization import plot_histogram # To use local qasm simulator backend = Aer.get...
<SYSTEM_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 section, we first judge the version of Python and import the packages of qiskit, math to implement the following code. We show our algor...
14,267
<ASSISTANT_TASK:> Python Code: truth = "This is some text.\nMore text, but on a different line!\nInsert your favorite meme here.\n" pred = read_file_contents("q1data/file1.txt") assert truth == pred retval = -1 try: retval = read_file_contents("nonexistent/path.txt") except: assert False else: assert retval...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: B Step2: C Step3: D
14,268
<ASSISTANT_TASK:> Python Code: !pip install --upgrade pymongo from pprint import pprint as pp import pandas as pd import matplotlib.pyplot as plt import matplotlib %matplotlib inline matplotlib.style.use('ggplot') %%bash sudo apt-get update sudo apt-get install -y mongodb-clients %%bash cat << END | mongo --host mongo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Usaremos la librería pymongo para python. La cargamos a continuación. Step2: La conexión se inicia con MongoClient en el host descrito en el fi...
14,269
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm dta = sm.datasets.macrodata.load_pandas().data index = pd.Index(sm.tsa.datetools.dates_from_range("1959Q1", "2009Q3")) print(index) dta.index = index del dta["year"] del dta["quarter"] prin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Hodrick-Prescott Filter Step2: Baxter-King approximate band-pass filter Step3: We lose K observations on both ends. It is suggested to use K=1...
14,270
<ASSISTANT_TASK:> Python Code: # Make a dictionary with {} and : to signify a key and a value my_dict = {'key1':'value1','key2':'value2'} # Call values by their key my_dict['key2'] my_dict = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']} #Lets call items from the dictionary my_dict['key3'] # Can call ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Its important to note that dictionaries are very flexible in the data types they can hold. For example Step2: We can effect the values of a key...
14,271
<ASSISTANT_TASK:> Python Code: import sys, os from adaptivemd import Project, Event, FunctionalEvent, Trajectory project = Project('tutorial') print project.tasks print project.trajectories print project.models engine = project.generators['openmm'] modeller = project.generators['pyemma'] pdb_file = project.files['in...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's open our test project by its name. If you completed the previous example this should all work out of the box. Step2: Open all connections...
14,272
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import plotly.plotly as py import plotly.graph_objs as go df = pd.read_csv('./asset/sydney_housing_market.txt', sep='\t') df.head() pd.pivot_table(df, index=['type']) pd.pivot_table(df, index=['type'], aggfunc={'distance_to_CBD':np.mean, 'sold':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: Import data Step2: Pivot Table Step3: Note that the default aggregation function is np.mean. We can specify the aggregation function in the ag...
14,273
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncar', 'sandbox-3', 'toplevel') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "e...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 2...
14,274
<ASSISTANT_TASK:> Python Code: !which howdoi !howdoi --help #注意我这里是在jupyter notebook里面直接使用的,所以需要加感叹号。如果是在terminal上,不需要加叹号。 !howdoi --num-answers 3 python lambda function list comprehension !howdoi --num-answer 3 python numpy array create !ls /Users/ywfang/FANG/git/howdoi_ywfang/howdoi !sed -n '70,120p' /Users/ywfa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 通过帮助文档,我们可以了解到HowDoI大概的工作模式以及它的一些功能,例如可以colorize the output,get multiple answers, Step2: Read HowDoI's code Step3: 通过浏览howdoi.py,我们发现这里面定义了很多新...
14,275
<ASSISTANT_TASK:> Python Code: from array import array import reprlib import math import numbers import functools import operator import itertools class Vector: typecode = 'd' def __init__(self, components): self._components = array(self.typecode, components) def __iter__(self): 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: 因为 Vector 实例是可迭代对象,而且 Vector.__init__ 的参数是可迭代对象,所以我们的 __neg__ 和 _pos__ 的实现短小精悍 Step2: 虽然每个 +one_third 表达式都会使用 one_third 的值创建一个新的 Decimal 实例,但是会...
14,276
<ASSISTANT_TASK:> Python Code: import yaml # Set `PATH` to include the directory containing TFX CLI and skaffold. PATH = %env PATH %env PATH=/home/jupyter/.local/bin:{PATH} !python -c "import tfx; print('TFX version: {}'.format(tfx.__version__))" !python -c "import kfp; print('KFP version: {}'.format(kfp.__version__))...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Validate lab package version installation Step2: Note Step3: Note Step4: The config.py module configures the default values for the environme...
14,277
<ASSISTANT_TASK:> Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].uppe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lesson Step2: Project 1
14,278
<ASSISTANT_TASK:> Python Code: from pandas import DataFrame, read_csv from estnltk import Text from estnltk.taggers import EventTagger event_vocabulary = DataFrame([['Harv', 'sagedus'], ['tugev peavalu', 'sümptom']], columns=['term', 'type']) eve...
<SYSTEM_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 1 Step2: or file event vocabulary.csv in csv format Step3: or list of dicts Step4: There must be one key (column) called term in even...
14,279
<ASSISTANT_TASK:> Python Code: import numpy as np from sklearn.model_selection import cross_val_score, train_test_split from sklearn import datasets from sklearn import svm iris = datasets.load_iris() # Split the iris data into train/test data sets with 40% reserved for testing X_train, X_test, y_train, y_test = 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: A single train/test split is made easy with the train_test_split function in the cross_validation library Step2: K-Fold cross validation is jus...
14,280
<ASSISTANT_TASK:> Python Code: # run h2o Kmeans # Import h2o library import h2o from h2o.estimators import H2OKMeansEstimator # init h2o cluster h2o.init(strict_version_check=False, url="http://192.168.59.147:54321") # load data import pandas as pd data = pd.read_csv("../../smalldata/chicago/chicagoAllWeather.csv") da...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data - Chicago Weather dataset Step2: Traditional K-means Step3: Constrained K-means reduced data using Aggregator - changed size 1/2 of origi...
14,281
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from sklearn.cluster import KMeans p, X = load_data() assert type(X) == np.ndarray km = KMeans() km.fit(X) d = km.transform(X)[:, p] indexes = np.argsort(d)[::][:100] closest_100_samples = X[indexes] <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:
14,282
<ASSISTANT_TASK:> Python Code: import h5py import numpy as np h5file = h5py.File("/Users/users/breddels/src/vaex/data/helmi-dezeeuw-2000-10p.hdf5", "r") FeH = h5file["/data/FeH"] # FeH is your regular numpy array (with some extras) print("mean FeH", np.mean(FeH), "length", len(FeH)) print(FeH.attrs["ucd"], FeH.attrs["...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: More information about a column can be found using
14,283
<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: 텐서플로 허브와 전이학습 Step2: ImageNet 분류기 Step3: 싱글 이미지 실행시키기 Step4: 차원 배치를 추가하세요, 그리고 이미지를 모델에 통과시키세요. Step5: 그 결과는 로지트의 1001 요소 벡터입니다. 이는 이미지에 대한 ...
14,284
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from IPython.display import HTML import ipywidgets as widgets from IPython.display import display L = 200 dx = .5 U = lambda x:(0.*x) buttonrunsim = widgets.Button(description="Simulate") buttongen...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Código que controla las simulaciones Step2: Rutinas que generan inicializan y generan la simulación Step3: Rutinas que conectan los controles ...
14,285
<ASSISTANT_TASK:> Python Code: import graphlab graphlab.canvas.set_target('ipynb') loans = graphlab.SFrame('lending-club-data.gl/') loans.column_names() loans['grade'].show() loans['home_ownership'].show() # safe_loans = 1 => safe # safe_loans = -1 => risky loans['safe_loans'] = loans['bad_loans'].apply(lambda 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: Load LendingClub dataset Step2: Exploring some features Step3: Here, we see that we have some feature columns that have to do with grade of th...
14,286
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from pennies.market.interpolate import CubicSplineWithNodeSens def f(x): return np.sin(x) x = 0.5 * np.arange(10) y = f(x) for i in range(len(x)): print('({}, {}'.format(x[i],y[i])) cs_sens = CubicSplineWithN...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: y = sin(x) Step2: Sensitivity to nodes
14,287
<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: SavedModel 形式の使用 Step2: 実行例として、グレース・ホッパーの画像と Keras の次元トレーニング済み画像分類モデルを使用します(使いやすいため)。カスタムモデルも使用できますが、これについては後半で説明します。 Step3: この画像の予測トップは「軍服」です...
14,288
<ASSISTANT_TASK:> Python Code: import os, csv, lzma import numpy as np import open_cp.sources.chicago import geopandas as gpd import pyproj import shapely.geometry #datadir = os.path.join("/media", "OTHERDATA") datadir = os.path.join("..", "..", "..", "..", "Data") open_cp.sources.chicago.set_data_directory(datadir) p...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get our favourite, the southside Step2: Process the data
14,289
<ASSISTANT_TASK:> Python Code: a = 10 print(a) import time time.sleep(10) import sys from ctypes import CDLL # This will crash a Linux or Mac system # equivalent calls can be made on Windows # Uncomment these lines if you would like to see the segfault # dll = 'dylib' if sys.platform == 'darwin' else 'so.6' # libc = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: There are two other keyboard shortcuts for running code Step2: If the Kernel dies you will be prompted to restart it. Here we call the low-leve...
14,290
<ASSISTANT_TASK:> Python Code: # Download example dataset from msmbuilder.example_datasets import FsPeptide fs_peptide = FsPeptide(verbose=False) fs_peptide.cache() # Work in a temporary directory import tempfile import os os.chdir(tempfile.mkdtemp()) from msmbuilder.dataset import dataset xyz = dataset(fs_peptide.dat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The dataset object Step2: Featurization Step3: Preprocessing Step4: Intermediate kinetic model Step5: tICA Histogram Step6: Clustering Step...
14,291
<ASSISTANT_TASK:> Python Code: %matplotlib inline import openmc uo2 = openmc.Material(1, "uo2") print(uo2) mat = openmc.Material() print(mat) help(uo2.add_nuclide) # Add nuclides to uo2 uo2.add_nuclide('U235', 0.03) uo2.add_nuclide('U238', 0.97) uo2.add_nuclide('O16', 2.0) uo2.set_density('g/cm3', 10.0) zirconium...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Defining Materials Step2: On the XML side, you have no choice but to supply an ID. However, in the Python API, if you don't give an ID, one wil...
14,292
<ASSISTANT_TASK:> Python Code: import zipfile from io import BytesIO import cv2 import gdown import matplotlib.pyplot as plt import numpy as np import requests import tensorflow as tf import tensorflow_hub as hub from PIL import Image from sklearn.preprocessing import MinMaxScaler from tensorflow import keras RESOLUTI...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Constants Step2: Data utilities Step3: Load a test image and display it Step4: Load a model Step5: More about the model Step6: attention_sc...
14,293
<ASSISTANT_TASK:> Python Code: m.layer_names channel = m.monitor.channels["valid_y_nll"] hl.Curve(zip(channel.epoch_record, channel.val_record),label="valid_y_nll") channel = m.monitor.channels["valid_y_nll"] plt.plot(channel.epoch_record, channel.val_record) ch1 = m.monitor.channels["valid_y_nll"] ch2 = m.monitor.cha...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Hard to see whether it is still learning...
14,294
<ASSISTANT_TASK:> Python Code: # Authors: Teon Brooks <teon.brooks@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) from mne.report import Report from mne.datasets import sample from mne import read_evokeds from matplotlib import pyplot as plt data_path = sample.data_path() meg_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: Do standard folder parsing (this can take a couple of minutes) Step2: Add a custom section with an evoked slider
14,295
<ASSISTANT_TASK:> Python Code: import pickle import numpy as np import matplotlib.pyplot as plt import scipy.sparse.linalg as spsla import tectosaur as tct with open('wenchuan_mesh.pkl', 'rb') as f: m = pickle.load(f) m.n_tris(), m.n_tris('surf'), m.n_tris('fault') plt.figure(figsize = (10,10)) plt.triplot(m.pts...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: And the premade mesh that we're going to use Step2: m is now a CombinedMesh object which is a handy class for tracking different subsets of a m...
14,296
<ASSISTANT_TASK:> Python Code: from datetime import datetime print "Notebook last modified/run: {}".format(datetime.now()) from math import factorial kNumBits = 1.e12 # 'n' in the equation, above. kBER = 1.e-12 # 'p-sub-A'. def prob(m): 'Probabillity of observing m errors.' return pow(kBER, m) * 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: Contents <a id="contents"/> Step2: I had to give up, after 5 hours, and interrupt the code, above. What happened?! Step3: The problem is the r...
14,297
<ASSISTANT_TASK:> Python Code: import os import shutil import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard from tensorflow.keras.layers import Dense, Flatten, Softmax print(tf.__version__) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exploring the data Step2: Each image is 28 x 28 pixels and represents a digit from 0 to 9. These images are black and white, so each pixel is a...
14,298
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd from os.path import join from pylab import rcParams import matplotlib.pyplot as plt rcParams['figure.figsize'] = (13, 6) plt.style.use('ggplot') #import nilmtk from nilmtk import DataSet, TimeFrame, MeterGroup, HDFDataStore from ni...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: show versions for any diagnostics Step2: Load dataset Step3: Let us perform our analysis on selected 2 days Step4: Hart Training Step5: Hart...
14,299
<ASSISTANT_TASK:> Python Code: %matplotlib inline import openpathsampling as paths import numpy as np import matplotlib.pyplot as plt import pandas as pd from openpathsampling.visualize import PathTreeBuilder, PathTreeBuilder from IPython.display import SVG, HTML def ipynb_visualize(movevis): Default settings to sh...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Single Replica TIS Step2: Open the storage and load things from it. Step3: One of the points of SRTIS is that we use a bias (which comes from ...