Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
4,200 | <ASSISTANT_TASK:>
Python Code:
%load_ext watermark
%watermark -a 'Sebastian Raschka' -v -p tensorflow,numpy
# Note that executing the following code
# cell will download the MNIST dataset
# and save all the 60,000 images as separate JPEG
# files. This might take a few minutes depending
# on your machine.
import numpy... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Chunking an Image Dataset for Minibatch Training using NumPy NPZ Archives
Step2: Note that the names of the subdirectories correspond directly ... |
4,201 | <ASSISTANT_TASK:>
Python Code:
# These are the libraries we are going to use in the lab.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
# class for ploting
class plot_error_surfaces(object):
# Constructor
def __init__(self, w_range, b_range, X, Y, n_samples = 30, go ... | <SYSTEM_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 class <code>plot_error_surfaces</code> is just to help you visualize the data space and the parameter space during training and has nothing ... |
4,202 | <ASSISTANT_TASK:>
Python Code:
# Author: Mathurin Massias <mathurin.massias@gmail.com>
# Yousra Bekhti <yousra.bekhti@gmail.com>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import os.path as op
import mne
fr... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load somatosensory MEG data
Step2: Run iterative reweighted multidict TF-MxNE solver
Step3: Generate stc from dipoles
Step4: Show the evoked ... |
4,203 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import csv
my_reader = csv.DictReader(open('data/eu_revolving_loans.csv', 'r'))
for line in my_reader:
print(line)
import pandas as pd
df = pd.read_csv('data/eu_revolving_loans.csv')
df.head()
df = pd.read_csv('data/eu_revolving_loans.csv', hea... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: DicReader returns a "generator" -- which means that we only have 1 chance to read the returning row dictionaries.
Step2: Since the data is tabu... |
4,204 | <ASSISTANT_TASK:>
Python Code:
def Enumerate(y, x):
# print(y)
if y == 0:
return -1
if x == y*y:
return y
return Enumerate(y-1, x)
print(Enumerate(16, 16))
print(Enumerate(15, 15))
1/10+1/10+1/10 == 3/10
def Abs(x):
if x < 0:
return -x
return x
def Istess(a,b):
retu... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: DOMANDA
Step2: NOTA
Step3: Il metodo di Newton
Step4: DOMANDA
|
4,205 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import seaborn as sns
from stemgraphic import stem_graphic
texas = pd.read_csv('salaries.csv')
texas.describe(include='all')
%time ax = texas.Annual_salary.hist()
%time g = sns.distplot(texas.Annual_salary)
%time g = sns.distplot(texas.Annual_sala... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Pandas histogram
Step2: Let's try with seaborn's distplot.
Step3: Ah yes. We have to do some data munging before we can use it, removing the N... |
4,206 | <ASSISTANT_TASK:>
Python Code:
# First, import hydrofunctions.
import hydrofunctions as hf
minimum_request = hf.NWIS('01585200')
minimum_request
minimum_request.df()
# For example, let's mistpye one of our parameters that worked so well above:
notSoGoodNWIS = hf.NWIS('01585200', 'xx', period='P200D')
# Let's ask f... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: What can we specify?
Step2: Since we only specified the where, the NWIS will assume the following elements
Step3: Here's what the data look li... |
4,207 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
log = pd.read_csv("../../../software-data/projects/linux/linux_blame_log.csv.gz")
log.head()
log.info()
top10 = log['author'].value_counts().head(10)
top10
%matplotlib inline
top10.plot.pie();
log['timestamp'] = pd.to_datetime(log['timestamp'])
log.head()
log['age'] =... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: No-Go Areas
Step2: Wissensinseln
Step3: Wissensanteile berechnen
Step4: Maximales Wissen pro Datei identifizieren
Step5: Visualisierung erst... |
4,208 | <ASSISTANT_TASK:>
Python Code:
!pip install sseclient
import json
import pyspark
import socket
import threading
import time
from pyspark.streaming import StreamingContext
from sseclient import SSEClient
def relay():
events = SSEClient('https://stream.wikimedia.org/v2/stream/recentchange')
s = socket.sock... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Like last week, we're going to use pyspark, a Python package that wraps Apache Spark and makes its functionality available in Python. We'll also... |
4,209 | <ASSISTANT_TASK:>
Python Code:
with open("ICSD/spacegroups.dat",'r') as f:
dat=csv.reader(f,dialect='excel-tab',quoting=csv.QUOTE_NONE)
list=[element.strip() for row in dat for element in row ]
list1=[[int(list[i*2]),list[i*2+1]] for i in range(len(list)/2)]
dict_space={}
for i in range(len(list1)):
dic... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now we shall parse all the data from the ICSD ternary file and try and map all the space groups to their space-group numbers, after doing some c... |
4,210 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib_venn import venn2
venn2(subsets = (0.45, 0.15, 0.05), set_labels = ('A', 'B'))
import pandas as pd
df = pd.DataFrame([[6,1,3,'Fradulent'],[14,29,47,'Not Fradulent']],
columns=['Fire', 'Auto','Other','St... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Conditional Probability
|
4,211 | <ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib nbagg
import sys, copy, os
from scipy import optimize
sys.path.append("truss-master")
try:
import truss
print("Truss is correctly installed")
except:
print("Truss is NOT correctly... | <SYSTEM_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 short truss tutorial is available here
Step2: Detailed results at the nodes
Step3: Detailed results on the bars
Step4: Dead (or structural)... |
4,212 | <ASSISTANT_TASK:>
Python Code:
!pip install ipython-sql
%load_ext sql
%sql sqlite:///./lab06.sqlite
import sqlalchemy
engine = sqlalchemy.create_engine("sqlite:///lab06.sqlite")
connection = engine.connect()
!pip install -U okpy
from client.api.notebook import Notebook
ok = Notebook('lab06.ok')
%%sql
DROP TABLE I... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Rapidgram
Step3: Question 1
Step5: Question 2
Step7: Question 3
Step9: Question 4
Step11: Question 5
Step13: Do you think this query will ... |
4,213 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division
import numpy as np
import pandas as pd
import scipy as sc
from scipy import stats
from statsmodels.stats.proportion import proportion_confint
from statsmodels.sandbox.stats.multicomp import multipletests
from itertools import combinations
%matplotlib inlin... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Давайте рассмотрим всех пользователей из контрольной группы (treatment = 1). Для таких пользователей мы хотим проверить гипотезу о том, что штат... |
4,214 | <ASSISTANT_TASK:>
Python Code:
data
y = "b"
x = ["x","y"]
train, valid, test = data.split_frame([0.75, 0.15])
from h2o.estimators import H2ODeepLearningEstimator
m = H2ODeepLearningEstimator(model_id="DL_defaults", hidden=[20,20,20,20,20,20,20,20,20,20], activation='tanh',epochs=10000)
m.train(x,y,train)
m
import nump... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Rendering our results
Step2:
|
4,215 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from bigbang.archive import Archive
arx = Archive("scipy-user",archive_dir="../archives")
act = arx.get_activity()
cutoff = 20
def filtered_participants(cutoff):
xc = act.sum() > cutoff
return act.columns[xc]
filtered_participants(cutoff)[:10]
from scipy.stat... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Resources for this
Step2: Get the activity of a list
Step4: Since are going to be computing correlations between N different time series data ... |
4,216 | <ASSISTANT_TASK:>
Python Code:
ppl_path = '../../pyfas/test/test_files/'
fname = 'FC1_rev01.ppl'
ppl = fa.Ppl(ppl_path+fname)
ppl.filter_data('PT')
pd.DataFrame(ppl.filter_data('PT'), index=("Profiles",)).T
pd.DataFrame(ppl.filter_data("TM"), index=("Profiles",)).T
pd.DataFrame(ppl.filter_data("PT"), index=("Profile... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Profile selection
Step2: The same outpout can be reported as a pandas dataframe
Step3: Dump to excel
Step4: Our targets are
Step5: The ppl o... |
4,217 | <ASSISTANT_TASK:>
Python Code:
from IPython.core.display import HTML
css_file = 'https://raw.githubusercontent.com/ngcm/training-public/master/ipython_notebook_styles/ngcmstyle.css'
HTML(url=css_file)
%matplotlib inline
import numpy
from matplotlib import pyplot
from mpl_toolkits.mplot3d.axes3d import Axes3D
from matp... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Basics of Molecular Dynamics
|
4,218 | <ASSISTANT_TASK:>
Python Code:
# Import and print the installed version of TensorFlow
import tensorflow as tf
print(tf.version.VERSION)
# Helper functions
def training_plot(metrics, history):
f, ax = plt.subplots(1, len(metrics), figsize=(5*len(metrics), 5))
for idx, metric in enumerate(metrics):
ax[idx].plot(... | <SYSTEM_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 Helper Functions
Step2: Train and evaluate a Neural Network (NN) model
Step3: Training the neural network
Step4: First, train your m... |
4,219 | <ASSISTANT_TASK:>
Python Code:
def json_to_map(s):
Convert a string containing JSON into a dictionary,
Skip flattening for now.
try:
return json.loads(s)
except:
return {}
json_to_map_udf = udf(json_to_map, MapType(StringType(), StringType()))
print(json_to_map('{ "solr_long_lat": "... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Need a udf that returns a mapType of string
Step2: Now let's write this out and go back and join to the main DF for some summaries
Step3: How ... |
4,220 | <ASSISTANT_TASK:>
Python Code:
import os
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import pylab, mlab, gridspec
from IPython.core.pylabtools import figsize, getfigs
from IPython.display import display, HTML
from pylab import *
# GLOBALS
# working directory
CWD = o... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Data Summary
Step2: NOTES
|
4,221 | <ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
#%config InlineBackend.figure_format = 'svg'
#%config InlineBackend.figure_format = 'pdf'
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import fsic.util as util
import fsic.data as data
import fsic.kernel as kern... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: This notebook is to test the optimization of the test locations V, W in NFSIC.
Step2: Grid search for Gaussian widths. Random test locations
St... |
4,222 | <ASSISTANT_TASK:>
Python Code:
from opentire import OpenTire
from opentire.Core import TireState
from opentire.Core import TIRFile
from pprint import pprint
import numpy as np
import matplotlib.pyplot as plt
openTire = OpenTire()
myTireModel = openTire.createmodel('PAC2002')
state = TireState()
state['FZ'] = 1500
sta... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Initialize the OpenTire factory and create a Pacejka 2002 tire model
Step2: Initialize the tire state
Step3: Solving for the tire forces will ... |
4,223 | <ASSISTANT_TASK:>
Python Code:
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
vgg_dir = 'tensorflow_vgg/'
# Make sure vgg exists
if not isdir(vgg_dir):
raise Exception("VGG directory doesn't exist!")
class DLProgress(tqdm):
last_block = 0
def hook(self, block_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Flower power
Step2: ConvNet Codes
Step3: Below I'm running images through the VGG network in batches.
Step4: Building the Classifier
Step5: ... |
4,224 | <ASSISTANT_TASK:>
Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
from time import time
from sklearn.metrics import r2_score, median_absolute_error
%matplotlib inline
%pylab inline
pylab.rcParams[... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's first define the list of parameters to use in each dataset.
Step2: Now, let's define the function to generate each dataset.
|
4,225 | <ASSISTANT_TASK:>
Python Code:
instructors = ['Dave', 'Jim', 'Dorkus the Clown']
if 'Dorkus the Clown' in instructors:
print('#fakeinstructor')
if 'Jim' in instructors:
print("Congratulations! Jim is teaching, your class won't stink!")
else:
pass
for instructor in instructors:
print(instructor)
for ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: There is a special do nothing word
Step2: For
Step3: You can combine loops and conditionals
Step4: range()
Step6: <hr>
Step8: To call the f... |
4,226 | <ASSISTANT_TASK:>
Python Code:
def name_of_function(arg1,arg2):
'''
This is where the function's Document String (docstring) goes
'''
# Do stuff here
#return desired result
def say_hello():
print 'hello'
say_hello()
def greeting(name):
print 'Hello %s' %name
greeting('Jose')
def add_num(... | <SYSTEM_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 begin with def then a space followed by the name of the function. Try to keep names relevant, for example len() is a good name for a length()... |
4,227 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, FancyArrow, Rectangle
from matplotlib.pyplot import cm
%matplotlib inline
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
Return new colormap... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step6: We start by defining a series helper functions which we will use in creating the plot below.
Step7: Finally we can plot the actual figure.
|
4,228 | <ASSISTANT_TASK:>
Python Code:
!pip install git+https://github.com/openai/baselines >/dev/null
!pip install gym >/dev/null
import numpy as np
import random
import gym
from gym.utils import seeding
from gym import spaces
def state_name_to_int(state):
state_name_map = {
'S': 0,
'A': 1,
'B': 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:
Step2: Environment
Step3: Try out Environment
Step4: Train model
Step5: Visualizing Results
Step6: Enjoy model
|
4,229 | <ASSISTANT_TASK:>
Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import tensorflow as tf
import numpy as np
from DLT2T.utils import trainer_utils as utils
from DLT2T.visualization import attention
%%javascript
require.config({
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: Data
Step2: Model
Step3: Session
Step4: Visualization
Step5: Test translation from the dataset
Step6: Visualize Custom Sentence
Step7: Int... |
4,230 | <ASSISTANT_TASK:>
Python Code:
#Find a list of users with at least 20 reviews
user_list = []
for user in users.find():
if user['review_count'] >= 20:
user_list.append(user['_id'])
else:
pass
user_reviews = dict.fromkeys(user_list, 0)
for review in reviews.find():
try:
if user_review... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create a new dictionary with the following structure and then export as a json object
|
4,231 | <ASSISTANT_TASK:>
Python Code:
# import the csv module from the Python standard library
# https://docs.python.org/3/library/csv.html
import csv
# import the BeautifulSoup class from the (external) bs4 package
from bs4 import BeautifulSoup
# import variables from a local file, my_module.py
# alias to `mm` using the `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:
Step1: Indentation
Step2: You can also add an else statement (and a colon) with an indented block of code you want to run if the condition resolves to... |
4,232 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from theano import tensor as T
from theano import function
from theano.gradient import jacobian
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['figure.figsize'] = 8, 6
plt.style.use('ggplot')
%matplotlib inline
xx = np.linspace(0, 100, 100)
yy = ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Introduction to Derivatives
Step2: Derivative of $f$
Step3: Chain rule of differentiation
Step4: Enter Theano
Step5: Exercise
Step6: Multiv... |
4,233 | <ASSISTANT_TASK:>
Python Code:
import random
from deap import algorithms, base, creator, tools
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
def evalOneMax(individual):
return (sum(individual),)
toolbox = base.Toolbox()
toolbox.register("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: Defining the elements
Step2: Running the experiment
Step3: Lets run only 10 generations
Step4: Essential features
Step5: The first individua... |
4,234 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)
from datetime import datetime
import Methods as models
import Predictors as predictors
import stock_tools as st
import matplotlib.pyplot as plt
import xgboost as xgb
from sklearn.grid_search import GridSearchCV
from sklearn.metrics ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: This is the file which gives the methodology behind the use of xgboost. xgboost can be found at https
Step2: Make testing and training data for... |
4,235 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('..')
from twords.twords import Twords
import matplotlib.pyplot as plt
%matplotlib inline
import pandas as pd
# this pandas line makes the dataframe display all text in a line; useful for seeing entire tweets
pd.set_option('display.max_colwidth', -1)
twit = Two... | <SYSTEM_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 sort tweets by favorites or retweets, need to convert unicode to integers
Step2: For some reason the search did not include Trump's username... |
4,236 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib
import pylab as plt
import scipy.misc as pim
from scipy import stats
% matplotlib inline
tam = 256 # tamaño matriz
dx = 0.01 # resolución (m/pixel)
x = np.arange(-dx*tam/2,dx*tam/2,dx) # coordenadas espaciales
X , Y = np.meshgrid(x,x) # espacio bidime... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Interpretación de la FT de una imagen
Step2: Note que solo aparecen aproximadamente dos deltas de Dirac en el espacio frecuencial. De forma aná... |
4,237 | <ASSISTANT_TASK:>
Python Code:
from default import *
import os, sys
model = Seq2Seq(build=False)
model.load(os.path.join('data', 'seq2seq_E049.pt'))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
model.eval()
# loading test dataset
test_iter = loadTestData(os.path.join('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: Run the default solution on dev
Step2: Evaluate the default output
|
4,238 | <ASSISTANT_TASK:>
Python Code:
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step3: Feature Sets
Step4: Task 1
Step8: Features that have strong positive or negative correlations with the target will add information to our mode... |
4,239 | <ASSISTANT_TASK:>
Python Code::
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=0.4,
ran... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,240 | <ASSISTANT_TASK:>
Python Code:
# Import the libraries we need for this lab
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import torch
from torch.utils.data import Dataset, DataLoader
import torch.nn as nn
# Create class for plotting and the function for plotting
class plot_error_... | <SYSTEM_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 class <code>plot_error_surfaces</code> is just to help you visualize the data space and the parameter space during training and has nothing ... |
4,241 | <ASSISTANT_TASK:>
Python Code:
import qkit
from qkit.storage import store
## for random data
from numpy.random import rand
from numpy import linspace,arange
import time
## number of points
nop = 101
h5d = store.Data(name='NewFancyData',mode = "a")
print(h5d.get_filepath())
h5d.add_comment("New data has been created... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: ... some imports to create some random data ...
Step2: Create a data file object
Step3: h5d is now an empty hdf5 file, holding only some qkit... |
4,242 | <ASSISTANT_TASK:>
Python Code:
#Starting out the basics.
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
slums= pd.read_csv("hyderabad_slum_master.csv")
slums.head() #The dataset is a spatialised one, hence the_geom column.
slums.columns
totalpopulation=slums['population'].sum()
print("The 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: Now let's look at the columns in the database.
Step2: So there are the following things in the dataset.
Step3: A quarter of the city's popula... |
4,243 | <ASSISTANT_TASK:>
Python Code:
definitely broken syntax :)
print "after broken syntax" # Will this be executed?
def i_contain_broken_syntax():
definitely broken syntax :)
print "after broken syntax" # Will this be executed?
def f():
print("This is a little demonstration")
print("that the Jupyter Noteboo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: No the syntax error in the first line leads to immediate termination of the program by raising a SyntaxError Excpetion.
Step2: apparently not t... |
4,244 | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
labels = [0, 6, 5, 4, 2]
def g(labels):
return tf.one_hot(indices=labels, depth=10, on_value=1, off_value=0, axis=-1)
result = g(labels.copy())
<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:
|
4,245 | <ASSISTANT_TASK:>
Python Code:
from sympy import init_printing
from sympy import Eq, I
from sympy import re, im
from sympy import symbols
from sympy.solvers import solve
from IPython.display import display
from sympy import latex
om = symbols('omega')
omI = symbols('omega_i', real=True)
omStar = symbols('omega_S... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The pure drift wave
Step2: The difference in the two solutions are just the sign of the square-root
Step3: This is cumbersome to work with.
St... |
4,246 | <ASSISTANT_TASK:>
Python Code:
import ruamel.yaml
ruamel.yaml
ruamel
dir(ruamel)
inp = \
# example
name:
# details
family: Goda # Very uncommon
given: Satish # One of the siblings (Comman name)
print(inp)
help(ruamel.yaml.load)
code = ruamel.yaml.load(inp, Loader=ruamel.yaml.RoundTripLoader)
code
code['... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Examples
Step4: Anchors and References
Step7: Full example
Step9: Inserting Keys and Comments
|
4,247 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.DataFrame({'Date':['2019-01-01','2019-02-08','2019-02-08', '2019-03-08']})
df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df['Date'].dt.strftime('%b-%Y')
<END_TASK> | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,248 | <ASSISTANT_TASK:>
Python Code:
path = untar_data(URLs.IMDB_SAMPLE)
df = pd.read_csv(path/'texts.csv')
df.head(2)
ss = L(list(df.text))
ss[0]
def delim_tok(s, delim=' '): return L(s.split(delim))
s = ss[0]
delim_tok(s)
def apply(func, items): return list(map(func, items))
%%timeit -n 2 -r 3
global t
t = apply(delim_t... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We'll start with the simplest approach
Step2: ...and a general way to tokenize a bunch of strings
Step3: Let's time it
Step4: ...and the same... |
4,249 | <ASSISTANT_TASK:>
Python Code:
from bs4 import BeautifulSoup
import requests
req = requests.get("http://pythonscraping.com/pages/page3.html")
bs = BeautifulSoup(req.text, "html.parser")
bs.find({"span"})
bs.findAll({"span"})
for filho in bs.find("table", {"id":"giftList"}).children:
print(filho)
for irmao in bs.f... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Lidando com filhos e outros descendentes
Step2: Lidando com irmãos
|
4,250 | <ASSISTANT_TASK:>
Python Code:
# Specifically for the iPython Notebook environment for clearing output.
from IPython.display import clear_output
# Global variables
board = [' '] * 10
game_state = True
announce = ''
# Note: Game will ignore the 0 index
def reset_board():
global board,game_state
board = [' '] * ... | <SYSTEM_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 make a function that will reset the board, in this case we'll store values as a list.
Step2: Now create a function to display the board, I... |
4,251 | <ASSISTANT_TASK:>
Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
class UniqueChars(object):
def has_unique_chars(self, string):
# Implemente aqui sua solução
%%writefile missao1.py
from nose.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Missão
Step2: Teste da Solução
|
4,252 | <ASSISTANT_TASK:>
Python Code:
from oommffield import Field, read_oommf_file
cmin = (0, 0, 0)
cmax = (100e-9, 100e-9, 5e-9)
d = (5e-9, 5e-9, 5e-9)
dim = 3
def m_init(pos):
x, y, z = pos
return (x+1, x+y+2, z+2)
field = Field(cmin, cmax, d, dim=dim, value=m_init)
#PYTEST_VALIDATE_IGNORE_OUTPUT
%matplotli... | <SYSTEM_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 create a three-dimansional vector field with domain that spans between
Step2: Now, we can create a vector field object and initialise it so ... |
4,253 | <ASSISTANT_TASK:>
Python Code:
xyz = pd.read_hdf('xyz.hdf5', 'xyz')
twobody = pd.read_hdf('twobody.hdf5', 'twobody')
from scipy.integrate import cumtrapz
def pcf(A, B, a, twobody, dr=0.05, start=0.5, end=7.5):
'''
Pair correlation function between two atom types.
'''
distances = twobody.loc[(twobody['s... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The Pair Correlation Function (or Radial Distribution Function)
Step2: Compute!
Step3: Plot!
Step4: Save the everything for later
|
4,254 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 18})
import sys
import logging
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
np.random.seed(43)
def ar_1_process(n_samples, c, phi, eps):
'''
Generate a correlated random sequence wit... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Introduction
Step2: We can see that the auto-covariance function starts at a high value and decreases quickly into a long noisy tail which fluc... |
4,255 | <ASSISTANT_TASK:>
Python Code:
import pandas
import pandasql
def num_rainy_days(filename):
'''
This function should run a SQL query on a dataframe of
weather data.
The SQL query should return:
- one column and
- one row - a count of the `number of days` in the dataframe where
the rain colum... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Quiz 1 - Number of rainy days
Step3: count(*)
Step5: fog max(maxtempi)
Step7: More about SQL's CAST function
Step8: Quiz 5 - Fixing Turnsti... |
4,256 | <ASSISTANT_TASK:>
Python Code:
# Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
training_file = 'train.p'
testing_file = 'test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.l... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Step 1
Step2: Set Validation features
Step3: Step 2
Step4: Setup TensorFlow
Step5: Features and Labels
Step6: Question 1
Step7: Step 3
Ste... |
4,257 | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
print(tf.version.VERSION)
device_name = tf.test.gpu_device_name()
if device_name != '/device:GPU:0':
raise SystemError('GPU device not found')
print('Found GPU at: {}'.format(device_name))
import matplotlib.pylab as plt
import numpy as np
import tensorflow as 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: Image and patch generation functions
Step2: Train a regression model to predict density
Step3: Plots for book
Step4: Actual image
|
4,258 | <ASSISTANT_TASK:>
Python Code:
x1 = M @ x
x1
x2 = M @ x1
x2
xc = x.copy()
# Write loop here
#grade (enter your code in this cell - DO NOT DELETE THIS LINE)
def power_iteration(M, x):
# Perform power iteration and return steady state vector xstar
xc = x.copy()
return xc
power_iteration(M, np.array([0.5,... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: This doesn't give us any new information, so lets see what happens when we multiply the state vector again
Step2: Now, we have "simulated" the ... |
4,259 | <ASSISTANT_TASK:>
Python Code:
# coding: utf-8
import os
from cheshire3.baseObjects import Session
from cheshire3.document import StringDocument
from cheshire3.internal import cheshire3Root
from cheshire3.server import SimpleServer
session = Session()
session.database = 'db_dickens'
serv = SimpleServer(session, 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: Querying
Step2: A query can be printed as CQL or as XCQL
Step3: To search the database using this particular query, one needs to use the searc... |
4,260 | <ASSISTANT_TASK:>
Python Code:
sns.barplot(x='Pclass',y='Survived',data=train, hue='Sex')
sns.barplot(x='Sex',y='Survived',data=train, hue='Pclass')
sns.swarmplot(x='Survived',y='Age',hue='Pclass',data=train)
sns.swarmplot(x='Survived',y='Age',hue='Sex',data=train)
sns.swarmplot(x='Sex',y='Age',data=train)
sns.poi... | <SYSTEM_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 plot explains the above facts in a different representation.
Step2: The plot explains the distribution of survivors across age and class. M... |
4,261 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import dask.dataframe as dd
import swifter
import perfplot
import matplotlib.pyplot as plt
import psutil
ncores = psutil.cpu_count()
npartitions = ncores*2
data = pd.read_feather("../../swifter_data/data/status")
data = pd.read_csv('status.csv')
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: These data (~71 million rows) were taken from https
Step2: Function Definitions
Step3: Non-vectorized function
Step4: Non-vectorized string f... |
4,262 | <ASSISTANT_TASK:>
Python Code:
# Import BEA API key or set manually to variable api_key
try:
items = os.getcwd().split('/')[:3]
items.append('bea_api_key.txt')
path = '/'.join(items)
with open(path,'r') as api_key_file:
api_key = api_key_file.readline()
except:
api_key = None
# Dictionary of... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Deflator data
Step2: Per capita income data
Step3: Load Easterlin's data
|
4,263 | <ASSISTANT_TASK:>
Python Code:
import random
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.data_utils import load_CIFAR10
from cs231n.gradient_check import grad_check_sparse
# plotting setting
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
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:
Step5: Load CIFAR-10 data
Step7: Softmax Classifier
Step8: Sanity Check
Step10: Vectorized loss function
Step12: Stochastic Gradient Descent
|
4,264 | <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: Customization basics
Step2: Tensors
Step3: Each tf.Tensor has a shape and a datatype
Step4: The most obvious differences between NumPy arrays... |
4,265 | <ASSISTANT_TASK:>
Python Code:
# Inicializacao
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
def nova_mlp(entradas, saidas, camadas):
lista_de_camadas = [entradas] + camadas + [saidas]
pesos = []
for i in xrange(len(lista_de_camadas)-1):
pesos.append(np.random.random((li... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: ## Resultados da regularização
|
4,266 | <ASSISTANT_TASK:>
Python Code:
import gym
import tensorflow as tf
import numpy as np
# Create the Cart-Pole game environment
env = gym.make('CartPole-v0')
env.reset()
rewards = []
for _ in range(100):
env.render()
state, reward, done, info = env.step(env.action_space.sample()) # take a random action
rewar... | <SYSTEM_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: We interact with the simulation through env. To show the simulation running, you can use env.render() to render one frame. Passing ... |
4,267 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import Image
Image(filename='pgm_mock_data.png')
from scipy.stats import norm
import numpy as np
np.random.seed(1)
alpha1 = norm(10.709, 0.022).rvs()
alpha2 = norm(0.359, 0.009).rvs()
alpha3 = 2.35e14
alpha4 = norm(1.10, 0.06).rvs()
S = norm(0.155, 0.0009).rvs()
sigm... | <SYSTEM_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 distributions are
Step2: Next we load data from the Millennium Simulation and extract a $60 \times 60 \text{ arcmin}^2$ field of view.
Ste... |
4,268 | <ASSISTANT_TASK:>
Python Code:
import hashlib
import os
import pickle
from urllib.request import urlretrieve
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm
from zipfil... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step3: The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this... |
4,269 | <ASSISTANT_TASK:>
Python Code:
# Dependencies
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Make testing data
def q_make_data(signal_size, n_repeats, n_timepoints):
signal = np.random.randn(n_timepoints)
data = np.random.randn(n_repeats, ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problem 1 - Data Quality (6 pts)
Step2: (a) - Signal to Noise Ratio (SNR) (1 pt)
Step3: (b) - Explainable Variance (EV) (1 pt)
Step4: (c) - T... |
4,270 | <ASSISTANT_TASK:>
Python Code:
%pylab notebook
%precision 4
Zeq = 20.0 + 100.0j # [Ohm]
Rc = 100.0e3 # [Ohm]
Xm = 20.0e3 # [Ohm]
Zload = 2.0 + 0.7j # [Ohm]
Xload = -3.0j # [Ohm]
Vp = 7967.0 # [V]
a = 8000/230.0
a
Zloadp = a**2 * Zload
Zloadp
Isp = Vp/ (Zeq + Zload... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Description
Step2: SOLUTION
Step3: Thus the load impedance referred to the primary side is
Step4: The referred secondary current is $I_s' = \... |
4,271 | <ASSISTANT_TASK:>
Python Code:
gene0 = [100, 200, 50, 400]
gene1 = [50, 0, 0, 100]
gene2 = [350, 100, 50, 200]
expression_data = [gene0, gene1, gene2]
import numpy as np
a = np.array(expression_data)
print(a)
def print_info(a):
print('number of elements:', a.size)
print('number of dimensions:', a.ndim)
pr... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Why is this a bad idea?
Step2: We are going to
Step3: Example
Step4: Example
Step5: Getting a copy
Step6: Advanced operations
Step7: This ... |
4,272 | <ASSISTANT_TASK:>
Python Code:
import redis
r = redis.Redis(decode_responses=True)
r.ping()
r.set("full_name", "john doe")
r.exists("full_name")
r.get("full_name")
r.set("full_name", "overridee!")
r.get("full_name")
r.setex("important_key", 100, "important_value")
r.ttl("important_key")
dict_data = {
"employee... | <SYSTEM_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 most basic usage of set and get
Step2: We can override the existing value by calling set method for the same key
Step3: It is also possibl... |
4,273 | <ASSISTANT_TASK:>
Python Code:
MAX_TIME = 80. # max time waiting at traffic light
class TrafficLightPath:
'''Class that computes the probabilities of a traffic light path over itself and the
future (children) traffic lights.
'''
p = 0 # probability of this path
T = 0 # expected time of... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now let's try the path for a single path of 2 lights and 1 wand and assuming a waiting time of 0 seconds. This is, he will not consider for how ... |
4,274 | <ASSISTANT_TASK:>
Python Code:
# Use this for interactive plots
%matplotlib notebook
import matplotlib.pyplot as plt
import pandas as pd
pd.Series([1,2,3,4]).plot()
!grep Guido data/week1/LICENSE.txt
!cat data/week1/LICENSE.txt data/week1/LICENSE.txt | wc -w
!cat data/week1/LICENSE.txt data/week1/LICENSE.txt | head
%%... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: When asking the professor a question, use the STAR approach
Step2: The wait command forces the system to finish processing the child process be... |
4,275 | <ASSISTANT_TASK:>
Python Code:
import ctcsound
cs = ctcsound.Csound()
ret = cs.compile_("csound", "-o", "dac", "examples/02-a.orc", "examples/02-a.sco")
if ret == ctcsound.CSOUND_SUCCESS:
cs.perform()
cs.reset()
ret = cs.compile_("csound", "examples/02-a.csd")
if ret == ctcsound.CSOUND_SUCCESS:
cs.perform... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Doing it the classical way, we compile an orchestra and a score file, passing also some flags. Note that the first argument, indicating the prog... |
4,276 | <ASSISTANT_TASK:>
Python Code:
setup_data_dir(data_dir)
make_subnetwork_directory(data_dir, network_name)
download_op_and_cl_files(data_dir, network_name)
download_master_edgelist(data_dir)
download_scdb(data_dir)
# create the raw case metadata data frame in the raw/ folder
make_subnetwork_raw_case_metadata(data_di... | <SYSTEM_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 download
Step2: get the master edgelist from CL
Step3: download scdb data from SCDB
Step4: network data
Step5: make graph
Step6: NLP d... |
4,277 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function # For py 2.7 compat
from IPython.html import widgets
from IPython.utils.traitlets import Unicode
class HelloWidget(widgets.DOMWidget):
_view_name = Unicode('HelloView', sync=True)
%%javascript
require(["widgets/js/widget", "widgets/js/manager"],... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Building a Custom Widget
Step2: sync=True traitlets
Step3: Define the view
Step4: Render method
Step5: Test
Step6: Making the widget statef... |
4,278 | <ASSISTANT_TASK:>
Python Code:
from lsst.cwfs.instrument import Instrument
from lsst.cwfs.algorithm import Algorithm
from lsst.cwfs.image import Image, readFile, aperture2image, showProjection
import lsst.cwfs.plots as plots
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
fieldXY = [0,0]
I1 = Ima... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Define the image objects. Input arguments
Step2: Define the instrument. Input arguments
Step3: Define the algorithm being used. Input argument... |
4,279 | <ASSISTANT_TASK:>
Python Code:
## Using magic commands for set up and showing working versions
%matplotlib inline
%load_ext version_information
%version_information tensorflow, numpy, pandas, matplotlib
import tensorflow as tf
import pandas as pd
import numpy as np
np.random.seed(7)
tf.set_random_seed(7)
init_data = 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: Lets set our seeds for the environment and pull in our data.
Step2: Now lets take a look at the data we are given.
Step3: As we can see we hav... |
4,280 | <ASSISTANT_TASK:>
Python Code:
#Put the csv into an RDD (at first, each row in the RDD is a string which
#correlates to a line in the csv
retailData = sc.textFile("OnlineRetail.csv")
print retailData.take(2)
from pyspark.mllib.recommendation import ALS, Rating
import re
#Remove the header from the RDD
header = retailD... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Prepare and shape the data
Step2: Build the recommendation model
Step3: Test the model
Step4: This doesn't give us that good of a representat... |
4,281 | <ASSISTANT_TASK:>
Python Code:
from numpy import sin,cos,pi,sqrt,angle,exp,deg2rad,arange,rad2deg
import matplotlib.pyplot as plt
from qutip import *
%matplotlib inline
H = Qobj([[1],[0]])
V = Qobj([[0],[1]])
def P(theta):
The projection operator for a state at angle theta
theta_ket = cos(theta)*H + sin(theta)... | <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: First define the projection operator for a state at angle $\theta$
Step3: Create the projection operators for each of the angles, two for Alice... |
4,282 | <ASSISTANT_TASK:>
Python Code:
# Change these to try this notebook out
BUCKET = "cloud-training-demos-ml"
PROJECT = "cloud-training-demos"
REGION = "us-central1"
SEQ_LEN = 50
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
os.environ['SEQ_LEN'] = str(SEQ_LEN)
os.env... | <SYSTEM_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> Simulate some time-series data </h3>
Step2: <h3> Train model locally </h3>
Step3: <h3> Cloud ML Engine </h3>
Step4: Monitor training wit... |
4,283 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from bigbang.git_repo import GitRepo;
from bigbang import repo_loader;
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
repos = repo_loader.get_org_repos("codeforamerica")
repo = repo_loader.get_multi_repo(repos=repos)
full_info = repo.commit_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: Nodes will be Author objects, each of which holds a list of Commit objects.
Step2: We create a list of authors, also separately keeping track o... |
4,284 | <ASSISTANT_TASK:>
Python Code:
import os
import sys
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install -U google-cloud-aiplatform $USER_FLAG
! pip3 install -U google-cloud-storage $USER_FLAG
if not os.getenv("IS_TESTING... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Step3: Before you begin
Step4: Region
Step5:... |
4,285 | <ASSISTANT_TASK:>
Python Code:
# load shapefile of all admin areas / countries as geodataframe
gdf = gpd.read_file('data/geo/countries/countries_nf2.shp'); gdf.head(3)
# filter out countries not internationally recognized
country_filter1 = gdf['WB_A3'] != '-99'
gdf = gdf.drop_duplicates(subset='WB_A3')
gdf = gdf[countr... | <SYSTEM_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 city boundaries
Step2: Get zonal stats for each metro cluster
|
4,286 | <ASSISTANT_TASK:>
Python Code:
theta1, theta2 = nn.load_weight('ex3weights.mat')
theta1.shape, theta2.shape
X, y = nn.load_data('ex3data1.mat',transpose=False)
X = np.insert(X, 0, values=np.ones(X.shape[0]), axis=1) # intercept
X.shape, y.shape
a1 = X
z2 = a1 @ theta1.T # (5000, 401) @ (25,401).T = (5000, 25)
z2.sha... | <SYSTEM_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 original data is 90 degree off. So in data loading function, I use transpose to fix it.
Step2: feed forward prediction
Step3: accuracy
|
4,287 | <ASSISTANT_TASK:>
Python Code:
from polyglot.transliteration import Transliterator
from polyglot.downloader import downloader
print(downloader.supported_languages_table("transliteration2"))
%%bash
polyglot download embeddings2.en pos2.en
from polyglot.text import Text
blob = We will meet at eight o'clock on Thursday... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Languages Coverage
Step2: Downloading Necessary Models
Step4: Example
Step5: We can query all the tagged words
Step6: Command Line Interface... |
4,288 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.datasets import mnist, cifar10
from keras.models import Sequential, Graph
from keras.layers.core import Dense, Dropout, Activation, Flatten, Reshape
from keras.optimizers import SGD... | <SYSTEM_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 MNIST dataset, flatten the images, convert the class labels, and scale the data.
Step2: I. OverFeat adaptation of AlexNet (2012)
Step3... |
4,289 | <ASSISTANT_TASK:>
Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
import phoebe
from phoebe import u # units
logger = phoebe.logger()
b = phoebe.default_binary()
b.add_dataset('rv')
print(b.get_dataset(kind='rv', check_visible=False))
print(b.get_parameter(qualifier='times', component='primary'))
b.set_value('time... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: As always, let's do imports and initialize a logger and a new Bundle.
Step2: Dataset Parameters
Step3: For information on the included passban... |
4,290 | <ASSISTANT_TASK:>
Python Code:
from six.moves import cPickle as pickle
import matplotlib.pyplot as plt
import os
from random import sample, shuffle
import numpy as np
files = os.listdir('pickle')
dataset = dict()
for file_name in files:
with open('pickle/'+file_name, 'rb') as f:
save = pickle.load(f)
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2. Read pickle files
Step2: 3. Group dataset
Step3: 4. Label the data
Step4: 5. Convert one-hot code
Step5: 6. Save data
Step6: 7. Pick som... |
4,291 | <ASSISTANT_TASK:>
Python Code:
# imports a library 'pandas', names it as 'pd'
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# enables inline plots, without it plots don't show up in the notebook
%matplotlib inline
# various options in pandas
pd.set_option('display.max_col... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: What problem does pandas solve?
Step2: Load a data set
Step3: pandas can load a lot more than csvs, this tutorial shows how pandas can read ex... |
4,292 | <ASSISTANT_TASK:>
Python Code:
# PySCeS model instantiation using the `example_model.py` file
# with name `mod`
mod = pysces.model('example_model')
mod.SetQuiet()
# Parameter scan setup and execution
# Here we are changing the value of `Vf2` over logarithmic
# scale from `log10(1)` (or 0) to log10(100) (or 2) for a
# 1... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Results that can be accessed via scan_results
Step2: e.g. The first 10 data points for the scan results
Step3: Results can be saved using the ... |
4,293 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import netCDF4
import numpy as np
import pylab as plt
plt.rcParams['figure.figsize'] = (14, 5)
ncdata = netCDF4.Dataset('http://thredds.met.no/thredds/dodsC/arome25/arome_metcoop_default2_5km_latest.nc')
x_wind_v = ncdata.variables['x_wind_10m'] # x component wrt the 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: Accessing netcdf file via thredds
Step3: Calculating wind speed in one grid cell over the prognosis time
Step4: Plotting wind speed
Step5: Cl... |
4,294 | <ASSISTANT_TASK:>
Python Code:
classifier_algorithm = "Decision Tree"
import collections
import exploringShipLogbooks
import numpy as np
import os.path as op
import pandas as pd
import exploringShipLogbooks.wordcount as wc
from fuzzywuzzy import fuzz
from sklearn import preprocessing
from sklearn.naive_bayes import Mul... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load and clean data
Step2: Find definite slave data in CLIWOC data set
Step3: Clean CLIWOC data
Step4: cliwoc_data (unclassified) = 0
Step5: ... |
4,295 | <ASSISTANT_TASK:>
Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
from time import time
from sklearn.metrics import r2_score, median_absolute_error
%matplotlib inline
%pylab inline
pylab.rcParams[... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's get the data.
Step2: Let's find the best params set for some different models
Step3: - Linear Predictor
Step4: - Random Forest model
|
4,296 | <ASSISTANT_TASK:>
Python Code:
from metakernel import register_ipython_magics
register_ipython_magics()
%%processing
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
class GOL {
int w = 8;
int columns, rows;
// Game of life board
int[][] board;
GOL() {
// Initialize rows, columns and 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: Links
|
4,297 | <ASSISTANT_TASK:>
Python Code:
# Load the modules
import gammalib
import ctools
import cscripts
# Define the ctools install directory
import os
ct_dir = os.environ['CTOOLS']
os.environ['CALDB'] = ct_dir + '/share/caldb/'
# Configure some preliminary variables
inmodel = ct_dir + '/share/models/crab.xml'
caldb = 'prod2... | <SYSTEM_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 the likelhood profiles
Step2: Now that we have a fitted SED, we can generate a plot from the results. A simple way to accomplish this ... |
4,298 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pandas.io.sql as pd_sql
import sqlite3 as sql
%matplotlib inline
con = sql.connect("titanic.db")
# Use pandas to open the csv.
# You'll have to put in the filepath
# It should look something like "../titanic... | <SYSTEM_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 a sqlite database for you to store the data once it's ready
Step2: =>YOUR TURN!
Step3: Exploring the Tabular Data
Step4: What do you ... |
4,299 | <ASSISTANT_TASK:>
Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import os
import tarfile
import urllib
from IPython.display import display, Image
from scipy import ndimage
fr... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The lab... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.