Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
10,400 | <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: Get started with TensorBoard
Step2: Using the MNIST dataset as the example, normalize the data and write a function that creates a simple Keras... |
10,401 | <ASSISTANT_TASK:>
Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
with open('anna.txt', 'r') as f:
text=f.read()
vocab = set(text)
vocab_to_int = {c: i for i, c in enumerate(vocab)}
int_to_vocab = dict(enumerate(vocab))
chars = np.array([vocab_to_int[c] for 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: First we'll load the text file and convert it into integers for our network to use.
Step3: Now I need to split up the data into batches, and in... |
10,402 | <ASSISTANT_TASK:>
Python Code:
ipd.SVG("https://upload.wikimedia.org/wikipedia/commons/2/27/MozartExcerptK331.svg")
ipd.YouTubeVideo('dP9KWQ8hAYk')
ipd.Image("https://upload.wikimedia.org/wikipedia/commons/a/a5/Perfect_octave_on_C.png")
ipd.Image("https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Pitch_class_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sheet music consists of notes. A note has several properties including pitch, timbre, loudness, and duration.
Step2: A pitch class (Wikipedia) ... |
10,403 | <ASSISTANT_TASK:>
Python Code:
# Imports
import numpy as np
import spherical_functions as sf
import quaternion
import matplotlib.pyplot as plt
#%% Basic test with Euler angles
alpha, beta, gamma = 0.1, 0.2, 0.3
ell,mp,m = 3,2,1
wD_euler = sf.Wigner_D_element(alpha, beta, gamma, ell, mp, m)
print(wD_euler)
#%% With quat... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Benchmark vs ePSproc_wignerD.m (Matlab)
Step2: > For conjugate version, differences on order of 1e-15. OK.
Step3: > Compare with Matlab code -... |
10,404 | <ASSISTANT_TASK:>
Python Code:
xs = np.array([1, 2, 3, 4, 5, 6])
ys = np.array([5, 4, 6, 5, 6, 7])
plt.scatter(xs, ys)
plt.show()
from sklearn.linear_model import LinearRegression
#we always assume that x is a 2d array of datapoints and features and y is a 1D array of outputs
xs = xs.reshape((6, 1)) # 6 datapoints 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: If slope is large, then that feature is more important. If slope is zero then the feature does is not important and prediction does not depend o... |
10,405 | <ASSISTANT_TASK:>
Python Code:
# BASE ------------------------------------
from datetime import datetime as dt
nb_start = dt.now()
# Be mindful when you have this activated.
# import warnings
# warnings.filterwarnings('ignore')
import json
from pathlib import Path
from time import sleep
# Display libs
from IPython.disp... | <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: Inserts for Jupyter
Step3: Import data
Step4: Main
Step5: Make use of IPython stuff
Step6: For more nested json's or dictionaries, it's best... |
10,406 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import scipy.stats as sps
import matplotlib.pyplot as plt
%matplotlib inline
def matrix_multiplication(A, B):
'''Возвращает матрицу, которая является результатом
матричного умножения матриц A и B.
'''
# Запоминаем размерности: мы умножаем матрицу ... | <SYSTEM_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. Напишите функцию, реализующую матричное умножение. При вычислении разрешается создавать объекты размерности три. Запрещается пользоват... |
10,407 | <ASSISTANT_TASK:>
Python Code:
averagespectrum = PCAsynthetic.get_hyper_peaks(spectralmatrix, threshold = 0.01)
plt.plot(averagespectrum)
featurematrix = PCAsynthetic.makefeaturematrix(spectralmatrix, averagespectrum)
featurematrix[10:13,:]
featurematrix_std = PCAsynthetic.stdfeature(featurematrix, axis = 0)
#along 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: 2. Make a feature matrix, n x p, where n = number of samples, p = number of features
Step2: 3. Standardize
Step3: 4. Sklearn PCA
Step4: 5. Ma... |
10,408 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import open_cp.retrohotspot
import open_cp.data
import open_cp.predictors
import open_cp.evaluation
n = 1000
times = np.random.random(n) * 365
times = times * (np.timedelta64(1, "D") / np.timedelta64(1, "s")) * np.timed... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Repeat
Step2: You might argue that 5 samples is too small...
Step3: We have added a "reproducible" mode, whereby we don't sample at random poi... |
10,409 | <ASSISTANT_TASK:>
Python Code:
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
# Import these from ncempy.algo
from ncempy.algo import gaussND
from ncempy.algo import peak_find
# Create coordinates with a random offset
coords = peak_find.lattice2D_2((1, 0), (0, 1), 2, 2, (0, 0), (5, 5))
coords ... | <SYSTEM_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 sample 2D Image
Step2: Find the center pixel of each peak
Step3: Use Gaussian fitting for sub-pixel fitting
Step4: Plot to compare t... |
10,410 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'messy-consortium', 'sandbox-1', 'landice')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor... | <SYSTEM_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... |
10,411 | <ASSISTANT_TASK:>
Python Code:
## Functions
import sys,os
import copy
path = os.path.abspath('../dev/')
if path not in sys.path:
sys.path.append(path)
import bib_mri as FW
import numpy as np
import scipy as scipy
import scipy.misc as misc
import matplotlib as mpl
import matplotlib.pyplot as plt
from numpy import g... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Introduction
Step2: Shape signature for comparison
Step3: Autoencoder
Step4: Testing in new datasets
Step5: Pixel-based test
|
10,412 | <ASSISTANT_TASK:>
Python Code:
# Import the pandas module
import pandas as pd
# Set the url as a variable; this is the URL we generated above
theURL = 'https://waterdata.usgs.gov/nc/nwis/water_use?format=rdb&rdb_compression=value&wu_area=County&wu_year=ALL&wu_county=ALL&wu_category=IN&wu_county_nms=--ALL%2BCounties--&w... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: So there's one catch
Step2: Another way around this is to invoke the skip rows option when reading the CSV. If you look at the file we are impo... |
10,413 | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
import numpy as np
!curl -O https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
!tar -xf aclImdb_v1.tar.gz
!ls aclImdb
!ls aclImdb/test
!ls aclImdb/train
!cat aclImdb/train/pos/6248_7.txt
!rm -r aclImdb/train/unsup
batch_size = 32
raw_train_ds = 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: Load the data
Step2: The aclImdb folder contains a train and test subfolder
Step3: The aclImdb/train/pos and aclImdb/train/neg folders contain... |
10,414 | <ASSISTANT_TASK:>
Python Code:
try:
import verta
except ImportError:
!pip install verta
HOST = "app.verta.ai"
PROJECT_NAME = "Film Review Embeddings"
EXPERIMENT_NAME = "TF Hub and Annoy"
# import os
# os.environ['VERTA_EMAIL'] =
# os.environ['VERTA_DEV_KEY'] =
from __future__ import print_function
import os... | <SYSTEM_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 example features
Step2: Imports
Step3: Run Workflow
Step4: Instantiate Client
Step5: Build Nearest Neighbor Embedding Index
Step7: Def... |
10,415 | <ASSISTANT_TASK:>
Python Code:
letters = 'abcdefghijklmnopqrstuvwxyz'
Foobar = namedtuple('Foobar', ('foo', 'bar'))
items = [Foobar(c+c, c+c+c) for c in letters]
items[:3]
xx = SelectOne(items)
yy = xx.foo
zz = xx.bar
xx.reset(seed=12345)
print_generated_sequence(xx, num=10, sep='\n')
print_generated_sequence(yy, 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: Let's define a generator xx which selects random elements from items, and two other generators yy and zz which extract individual attributes fro... |
10,416 | <ASSISTANT_TASK:>
Python Code:
### Task 1: Select what features you'll use.
### features_list is a list of strings, each of which is a feature name.
### The first feature must be "poi".
names = np.array(my_dataset.keys())
print names.shape, names[:5], "\n"
features_list = my_dataset.itervalues().next().keys()
features_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1:
Step2:
Step3: Initial Results
|
10,417 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head()
rides[:24*10].plot(x='dteday', y='cnt')
dummy_fields = ['seas... | <SYSTEM_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 prepare the data
Step2: Checking out the data
Step3: Dummy variables
Step4: Scaling target variables
Step5: Splitting the data into... |
10,418 | <ASSISTANT_TASK:>
Python Code:
import tohu
from tohu.v5.primitive_generators import *
from tohu.v5.utils import print_generated_sequence
print(f'Tohu version: {tohu.__version__}')
g = Constant('quux')
print_generated_sequence(g, num=10, seed=12345)
g1 = Boolean()
g2 = Boolean(p=0.8)
print_generated_sequence(g1, num=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: Constant
Step2: Boolean
Step3: Integer
Step4: Float
Step5: HashDigest
Step6: HashDigest hex strings (lowercase)
Step7: HashDigest byte str... |
10,419 | <ASSISTANT_TASK:>
Python Code:
!pip install -I "phoebe>=2.2,<2.3"
%matplotlib inline
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger()
b = phoebe.default_binary()
b['requiv_max@component@primary']
b['requiv_max@constraint@primary']
print(b.filter(q... | <SYSTEM_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. See Building a System for more details.
Step2: Detached Systems
Step3: ... |
10,420 | <ASSISTANT_TASK:>
Python Code:
import statsmodels.api as sm
import statsmodels.formula.api as smf
import statsmodels.tools.eval_measures as eval_measures
import seaborn as sns
import scipy.stats as stats
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets, model_sele... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We load the boston house-prices dataset and X are our features and y is the target variable medv (Median value of owner-occupied homes in $1000s... |
10,421 | <ASSISTANT_TASK:>
Python Code:
import os
import subprocess
import tempfile
import tensorflow as tf
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
assert tf.VERSION.split('.') >= ['1','4']
%matplotlib inline
mpl.rcParams['figure.figsize'] = 12, 6
mpl.rcParams['image.cmap'] = 'viridis'
logdir... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Start TensorBoard
Step2: Build Synthetic Data
Step3: Build Datasets
Step4: Generate a plot from an Estimator
Step5: Using numeric_column wit... |
10,422 | <ASSISTANT_TASK:>
Python Code:
# Import two classes from the boxsdk module - Client and OAuth2
from boxsdk import Client, OAuth2
# Define client ID, client secret, and developer token.
CLIENT_ID = None
CLIENT_SECRET = None
ACCESS_TOKEN = None
# Read app info from text file
with open('app.cfg', 'r') as app_cfg:
CLIE... | <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: The Python SDK is organized into layers
Step3: We now have a fully authenticated SDK client!
Step4: Now let's look at some different objects, ... |
10,423 | <ASSISTANT_TASK:>
Python Code:
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class MyClass(object):
pass
single1 = Singleton()
single2 = Si... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2 使用类(class)装饰器
Step2: 3 使用GetInstance方法,非线程安全
|
10,424 | <ASSISTANT_TASK:>
Python Code:
import graphlab
images = graphlab.SFrame('https://static.turi.com/datasets/caltech_101/caltech_101_images')
# Only do this if you have a GPU
#pretrained_model = graphlab.load_model('https://static.turi.com/models/imagenet_model_iter45')
#images['extracted_features'] = pretrained_model.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: Part II
Step2: Now, let's inspect the images SFrame. The 'extracted_features' column contains vector representations of the data, as we expect... |
10,425 | <ASSISTANT_TASK:>
Python Code:
import os, urllib
def download(url):
filename = url.split("/")[-1]
if not os.path.exists(filename):
urllib.urlretrieve(url, filename)
download('http://data.mxnet.io/data/caltech-256/caltech-256-60-train.rec')
download('http://data.mxnet.io/data/caltech-256/caltech-256-60-v... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next we define the function which returns the data iterators
Step2: We then download a pretrained 50-layer ResNet model and load into memory. N... |
10,426 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from isochrones import get_ichrone
bands = ['J', 'H', 'K', 'G', 'BP', 'RP']
mist = get_ichrone('mist', bands=bands)
from itertools import product
primary_masses = [0.8, 1.0]
mass_ratios = [0.5, 0.9]
feh_grid = [-0.25, 0.0]
age = 9.7
distance = 500
AV = 0.
m1, m2, feh, 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: Use a StarCatalog to organize data
Step2: Fit models
Step3: Analyze samples
|
10,427 | <ASSISTANT_TASK:>
Python Code:
# built-in functions
seq = 'ATCCTGCTAAA'
print(len(seq))
# your own function
def gc_content(seq):
gc = 0
for base in seq:
if (base == 'C') or (base == 'G'):
gc += 1
return gc
print(gc_content('ATCCTGCTAAA'))
print(gc_content('GGGCCCCTTTA'))
import math
pri... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Session 3
Step2: Ex 3.1
Step3: cvs module
Step4: Ex 3.2
Step5: Writing your own module
Step6: Ex 3.3
Step7: Ex 3.4
|
10,428 | <ASSISTANT_TASK:>
Python Code:
%%capture
!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip
!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip
!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip
!unzip Data.zip -d ../
!unz... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Chapter 12
Step2: Note the syntax used
Step3: In this case we wouldn't have to specify where our machine should find the randint() function
St... |
10,429 | <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: ... |
10,430 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
s = pd.Series([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0.98,0.93],
index=['146tf150p','havent','home','okie','thanx','er','anything','lei','nite','yup','thank','ok','where','beerage','anytime','too','done','645','tick','blank'])
import numpy as np
def g(s):
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:
|
10,431 | <ASSISTANT_TASK:>
Python Code:
def gen_periodic_data( # complete
y = # complete
return y
x = # complete
y = gen_periodic_data( # complete
fig, ax = plt.subplots()
ax.scatter( # complete
# complete
# complete
fig.tight_layout()
def phase_plot( # complete
phases = # complete
# complete
# comple... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problem 1b
Step2: Problem 1c
Step3: Problem 1d
Step4: Problem 2) A Brief Review of Fourier Analysis
Step5: The common Fourier pairs are espe... |
10,432 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import make_regression
import pyro.distributions as dist
from pyro.infer import MCMC, NUTS, Predictive
from pyro.infer.mcmc.util import summary
from pyro.distributions import constraints
import 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: Data generation
Step2: Model definition
Step3: Inference
Step4: After sampling let's see how well our model fits the data. We compute sampled... |
10,433 | <ASSISTANT_TASK:>
Python Code:
%%bash
cd cifar10
MODEL_NAME="cifar10"
VERSION_NAME="v1"
JOB_DIR="gs://dost_deeplearning_cifar10/cifar10_train_1499931245" # Change this to your own
gcloud ml-engine models create $MODEL_NAME
gcloud ml-engine versions create \
$VERSION_NAME \
--model $MODEL_NAME \
--origin $JOB_DIR/... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Predict with your deployed model
Step2: It should output 6 which is the label index for the frog class.
Step3: Run server
|
10,434 | <ASSISTANT_TASK:>
Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
view_sentence_range = (0, 10)
DON'T MODIFY ANYTHING IN THIS CELL
import 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: TV Script Generation
Step3: Explore the Data
Step6: Implement Preprocessing Functions
Step9: Tokenize Punctuation
Step11: Preprocess all the... |
10,435 | <ASSISTANT_TASK:>
Python Code:
# Based on Ivezic, Figure 6.5
# Author: Jake VanderPlas
# License: BSD
# The figure produced by this code is published in the textbook
# "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
# For more information, see http://astroML.github.com
# To report a bug or 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: Nearest-neighbors are both pretty simple and pretty powerful. But you can imagine that they could also be really slow if you have either a lot ... |
10,436 | <ASSISTANT_TASK:>
Python Code:
# TODO:总的记录数
n_records = len(data)
# # TODO:被调查者 的收入大于$50,000的人数
n_greater_50k = len(data[data.income.str.contains('>50K')])
# # TODO:被调查者的收入最多为$50,000的人数
n_at_most_50k = len(data[data.income.str.contains('<=50K')])
# # TODO:被调查者收入大于$50,000所占的比例
greater_percent = (n_greater_50k / n_recor... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 准备数据
Step2: 转换倾斜的连续特征
Step3: 对于高度倾斜分布的特征如'capital-gain'和'capital-loss',常见的做法是对数据施加一个<a href="https
Step4: 规一化数字特征
Step5: 练习:数据预处理
Step6: 混洗... |
10,437 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
from numpy import sqrt,pi,cos,sin,arange,random
from qutip import *
H = Qobj([[1],[0]])
V = Qobj([[0],[1]])
P45 = Qobj([[1/sqrt(2)],[1/sqrt(2)]])
M45 = Qobj([[1/sqrt(2)],[-1/sqrt(2)]])
R = Qobj([[1/sqrt(2)],[-1j/sqrt(2)]])
L = Qobj([[1/sqrt(2)],[1j/sqrt(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: Q
Step2: Q
Step3: Q
Step4: Example
Step5: Q
|
10,438 | <ASSISTANT_TASK:>
Python Code:
# conda install ipyrad -c conda-forge -c bioconda
import ipyrad.analysis as ipa
ipa.__version__
# path to an HDF5 formatted seqs file
SEQSFILE = "/tmp/oaks.seqs.hdf5"
# download example seqs file if not already present (~500Mb, takes ~5 minutes)
URL = "https://www.dropbox.com/s/c1u89nwuu... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Required input data files
Step2: The scaffold table
Step3: Selecting scaffolds
Step4: Subsetting scaffold windows
Step5: Filtering missing d... |
10,439 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
import sklearn as sk
from cluster import Clusters
import os
filename = 'Cluster_Data_2.csv'
path = '../Clean Data'
fullpath = os.path.join(path, filename)
cluster = Cl... | <SYSTEM_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 the figures above, it is difficult to determine an optimal number of clusters. The silhouette score clearly shows that we need more than 5 ... |
10,440 | <ASSISTANT_TASK:>
Python Code:
for ccdNum in [2,3]:
exts = 4*(ccdNum-1) + arange(1,5)
figure(figsize=(10,6))
for pnum,ext in enumerate(exts,start=1):
subplot(2,2,pnum)
for t,lbl,clr in zip([t15,t16],#,s15[b15],s16[b16],s15[o15],s16[o16]],
['2015','2016'],#,'2015b... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Joe F. found that the gradient features do still exist in 2016 biases, by visually inspecting all of the bias images. They are, however, at a ve... |
10,441 | <ASSISTANT_TASK:>
Python Code:
%pip install -U missing_or_updating_package --user
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
# Get your GCP project id from gcloud
shell_output=!gcloud config list --format 'value(core.project)' 2>/de... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Restart the Kernel
Step2: Before you begin
Step3: Otherwise, set your project id here.
Step4: Authenticate your GCP account
Step5: Create a ... |
10,442 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import numpy as np
# Import pylab to provide scientific Python libraries (NumPy, SciPy, Matplotlib)
%pylab --no-import-all
#import pylab as pl
# import the Image display module
from IPython.display import Image
import math
np.array([1,2,3,4,5,6])
np.array([1,2,3,4,5,6],'d')... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: You can pass in a second argument to array that gives the numeric type. There are a number of types listed here that your matrix can be. Some of... |
10,443 | <ASSISTANT_TASK:>
Python Code:
# inline plotting/interaction
%pylab inline
# replace the line above with the line below for command line scripts:
# from pylab import *
from sympy import * # symbolic python
init_printing() # pretty printing
import numpy as np # numeric python
import time # timing, for performance monito... | <SYSTEM_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 models and using the algorithm presented in Ref [2]
Step2: A simple model
Step3: Parametrizing the transition rates
Step4: Calculati... |
10,444 | <ASSISTANT_TASK:>
Python Code:
# Import the neccesary tools to generate surfaces
from pymatgen.core.surface import SlabGenerator, generate_all_slabs, Structure, Lattice
# Import the neccesary tools for making a Wulff shape
from pymatgen.analysis.wulff import WulffShape
import os
# Let's start with fcc Ni
lattice = Latt... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Calculating the surface energy
Step2: When generating a slab of LiFePO4, we also want to be careful
Step3: There are a couple of rules before... |
10,445 | <ASSISTANT_TASK:>
Python Code:
# hack to get the path right
import sys
sys.path.append('..')
import ztf_sim
from astropy.time import Time
import pandas as pd
import numpy as np
import astropy.units as u
import pylab as plt
ztf_sim.fields.generate_test_field_grid()
f = ztf_sim.fields.Fields()
f.fields.head()
f.alt_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: First we'll generate a test field grid. You only need to do this the first time you run the simulator.
Step2: Let's load the Fields object wit... |
10,446 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
def soliton(x, t, c, a):
i=(((c**(1/2))/2)*(x-c*t-a))
return ((1/2)*c*(np.cos(i)**(-2)))
assert np.all... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Using interact for animation with data
Step2: To create an animation of a soliton propagating in time, we are going to precompute the soliton d... |
10,447 | <ASSISTANT_TASK:>
Python Code:
pes = toys.LinearSlope(m=[0.0], c=[0.0]) # flat line
topology = toys.Topology(n_spatial=1, masses=[1.0], pes=pes)
integrator = toys.LeapfrogVerletIntegrator(0.1)
options = {
'integ': integrator,
'n_frames_max': 1000,
'n_steps_per_frame': 1
}
engine = toys.Engine(options=option... | <SYSTEM_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 addition to the standard setup as above, we need a way to randomize the snapshots. For this simple example, we actually won't randomize them ... |
10,448 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from tsgettoolbox import tsgettoolbox
df = tsgettoolbox.nwis_dv(sites="02325000", startDT="2000-01-01", parameterCd="00060")
df.head() # The .head() function gives the first 5 values of the time-series
from tstoolbox import tstoolbox
tstoolbox.plot(input_ts=df, ofile... | <SYSTEM_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 say that I want flow (parameterCd=00060) for site '02325000'. All of the tsgettoolbox functions create a pandas DataFrame.
Step2: 'tstoo... |
10,449 | <ASSISTANT_TASK:>
Python Code:
data_inorder = pd.read_csv('Data\\adder_inorder_data.csv')
data_inorder = data_inorder[['Steps', 'MSE']]
data_inorder = data_inorder.sort_values(['Steps'])
data_inorder.head(9)
data_rnd_0 = pd.read_csv('Data\\adder_random_0_data.csv')
data_rnd_0 = data_rnd_0[['Steps', 'MSE']]
data_rnd_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: adder(n)
|
10,450 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
from scipy.stats import entropy
from tabulate import tabulate
from pymongo import MongoClient
import matplotlib.pyplot as plt
plt.style.use('seaborn')
plt.rcParams["figure.figsize"] = (20,8)
db = MongoClient()['stores']
TOTAL_NUMBE... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sizes per distributor
Step2: Print joint table with first 60 sizes.
Step3: Calculate entropy
Step4: Create new collection from data only with... |
10,451 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import os
import glob
import librosa
import numpy as np
DATABASE_PATH = '/Users/pierrerouanet/Downloads/data-speech_commands_v0.02'
labels = {'cat', 'dog', 'house', 'happy', 'zero'}
labels
# We will use only N occurences per word
N = 25
mfccs = []
true_labels = []
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: We will use the data-speech-commands database composed of 105,000 WAVE audio files of people saying thirty different words. We will use only a s... |
10,452 | <ASSISTANT_TASK:>
Python Code:
from osgeo import ogr, osr, gdal
# opening the geotiff file
ds = gdal.Open('G:\BTP\Satellite\Data\Test2\LE07_L1GT_147040_20050506_20170116_01_T2\LE07_L1GT_147040_20050506_20170116_01_T2_B1.TIF')
col, row, band = ds.RasterXSize, ds.RasterYSize, ds.RasterCount
print(col, row, band)
xoff, 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: Latitude, Longitude for any pixel in a GeoTiff File
Step3: These global coordinates are in a projected coordinated system, which is a represent... |
10,453 | <ASSISTANT_TASK:>
Python Code:
# The first step is to import the dataset into a pandas dataframe.
import pandas as pd
#path = 'C:/Users/hrao/Documents/Personal/HK/Python/ml-20m/ml-20m/'
path = '/Users/Harish/Documents/HK_Work/Python/ml-20m/'
movies = pd.read_csv(path+'movies.csv')
movies.shape
tags = pd.read_csv(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: Exploring the dataset
Step2: Based on the above exploratory commands, I believe that the following questions can be answered using the dataset
... |
10,454 | <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: TensorFlow Addons 图像:运算
Step2: 准备和检查图像
Step3: 检查图像
Step4: 制作黑白版本
Step5: 使用 tfa.image
Step6: 旋转
Step7: 变换
Step8: YIQ 中的随机 HSV
Step9: 调整 Y... |
10,455 | <ASSISTANT_TASK:>
Python Code:
from probability import *
from utils import print_table
from notebook import psource, pseudocode, heatmap
psource(ProbDist)
p = ProbDist('Flip')
p['H'], p['T'] = 0.25, 0.75
p['T']
p = ProbDist(freqs={'low': 125, 'medium': 375, 'high': 500})
p.varname
(p['low'], p['medium'], p['high'])
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: CONTENTS
Step2: The first parameter of the constructor varname has a default value of '?'. So if the name is not passed it defaults to ?. The k... |
10,456 | <ASSISTANT_TASK:>
Python Code:
import math
print(math.log(0.2) + math.log(0.5))
print(math.log(0.2 * 0.5))
print(math.log(math.exp(0.2) * math.exp(0.7)))
print(0.2 + 0.7)
<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: $$
|
10,457 | <ASSISTANT_TASK:>
Python Code:
# Create a sample of Gaussian draws
np.random.seed(0)
x_data = np.random.randn(1000)
x_sc = LinearScale()
y_sc = LinearScale()
hist = Bins(sample=x_data, scales={'x': x_sc, 'y': y_sc}, padding=0,)
ax_x = Axis(scale=x_sc, tick_format='0.2f')
ax_y = Axis(scale=y_sc, orientation='vertical')... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Give the Hist mark the data you want to perform as the sample argument, and also give 'x' and 'y' scales.
Step2: The midpoints of the resulting... |
10,458 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import h5py
import numpy as np
import sklearn.preprocessing
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import astropy.io.fits as fits
import matplotlib
import matplotlib.pyplot as plt
import spectraldl.ondrejov as ondrejov
import spectraldl.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: PCA
Step2: If identificator are plotted to the scatter plot
Step3: Conclusions
Step4: Scaling Features
Step5: t-SNE
Step6: LAMOST
|
10,459 | <ASSISTANT_TASK:>
Python Code:
!pip install meterstick
!git clone https://github.com/google/meterstick.git
import sys, os
sys.path.append(os.getcwd())
import itertools
import numpy as np
import pandas as pd
from meterstick import confidence_interval_display
np.random.seed(42)
metrics = ('Click', 'Latency', 'a very 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: or from GitHub for the latest version.
Step2: Demo Starts
|
10,460 | <ASSISTANT_TASK:>
Python Code:
# Grab every letter in string
lst = [x for x in 'word']
# Check
lst
# Square numbers in range and turn into list
lst = [x**2 for x in range(0,11)]
lst
# Check for even numbers in a range
lst = [x for x in range(11) if x % 2 == 0]
lst
# Convert Celsius to Fahrenheit
celsius = [0,10,20.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: This is the basic idea of a list comprehension. If you're familiar with mathematical notation this format should feel familiar for example
Step2... |
10,461 | <ASSISTANT_TASK:>
Python Code:
# Load libraries
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
from sklearn.feature_selection import SelectFromModel
# Load data
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Create random forest classifier
clf = RandomForestClassifier(ra... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load Iris Flower Data
Step2: Create Random Forest Classifier
Step3: Select Features With Importance Greater Than Threshold
Step4: View Select... |
10,462 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bnu', 'bnu-esm-1-1', 'land')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "emai... | <SYSTEM_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... |
10,463 | <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... |
10,464 | <ASSISTANT_TASK:>
Python Code:
price = 300
import math
math.sqrt( price )
import math
math.sqrt( price )
stock_index = "SP500"
stock_index[2:]
stock_index = "SP500"
price = 300
print('The {quote} is at {price} today'.format(quote=stock_index,price=price))
stock_info = {'sp500':{'today':300,'yesterday': 250}, 'info':... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Task #2
Step2: Task #3
Step3: Task #4
Step4: Task #5
Step5: Task #5
Step6: Task #6
Step7: Task #7
|
10,465 | <ASSISTANT_TASK:>
Python Code:
%run "../src/start_session.py"
%run "../src/recurrences.py"
import oeis
d = IndexedBase('d')
n, k = symbols('n k')
pascal_recurrence_spec = recurrence_spec(recurrence_eq=Eq(d[n+1, k+1], d[n, k] + d[n, k+1]),
recurrence_symbol=d,
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Pascal array $\mathcal{P}$
Step2: OEIS content about $\mathcal{P}$
|
10,466 | <ASSISTANT_TASK:>
Python Code:
import modin.config as cfg
cfg.StorageFormat.put('omnisci')
# Note: Importing notebooks dependencies. Do not change this code!
import numpy as np
import pandas
import sys
import modin
pandas.__version__
modin.__version__
# Implement your answer here. You are also free to play with the siz... | <SYSTEM_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 that we have created a toy example for playing around with the DataFrame, let's print it out in different ways.
|
10,467 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'uhh', 'sandbox-3', 'land')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "email"... | <SYSTEM_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... |
10,468 | <ASSISTANT_TASK:>
Python Code:
print(iris.DESCR[:172] + ' ...')
print(iris.feature_names)
print(iris.data[45:54])
print(iris.target[45:54])
print(iris.target_names)
lfeat = iris.feature_names
df_iris = pd.DataFrame(iris.data, columns = lfeat)
model = DecisionTreeClassifier()
data = df_iris[lfeat].values
df_iris["Speci... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Recap - Decision Tree Classifier
|
10,469 | <ASSISTANT_TASK:>
Python Code:
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import time
from pprint import pprint
# importing Qiskit
from qiskit import Aer, IBMQ
from qiskit.backends.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, Quant... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Theoretical background
Step2: Three-qubit W state, step 1
Step3: Three-qubit W state
Step4: Three-qubit W state, full circuit
Step5: Now you... |
10,470 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Below I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits.
Step2: We'll train an autoe... |
10,471 | <ASSISTANT_TASK:>
Python Code:
# A bit of setup
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.neural_net import TwoLayerNet
from __future__ import print_function
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] =... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Implementing a Neural Network
Step2: We will use the class TwoLayerNet in the file cs231n/classifiers/neural_net.py to represent instances of o... |
10,472 | <ASSISTANT_TASK:>
Python Code:
dirPath = os.path.realpath('.')
fileName = 'assets/coolingExample.xlsx'
filePath = os.path.join(dirPath, fileName)
df = pd.read_excel(filePath,header=0)
cols = df.columns
# Create a trace
trace = go.Scatter(
x = df[cols[0]],
y = df[cols[1]]
)
data = [trace]
# Edit the layout
layo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Creating the plot
|
10,473 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome()
url = "http://rate.am/en/armenian-dram-exchange-rates/banks/cash"
browser.get(url) #will wait until page is fully loaded
browser.find_element_by_xpath("//label[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: Starting from here we introduce several Selenium tricks for manipulating the page (such as clicking the Page Down key on the keyboard).
Step2: ... |
10,474 | <ASSISTANT_TASK:>
Python Code:
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
import tensorflow as tf
from tensorflow.python.framework import ops
from cnn_utils import *
%matplotlib inline
np.random.seed(1)
# Loading the data (sig... | <SYSTEM_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 next cell to load the "SIGNS" dataset you are going to use.
Step2: As a reminder, the SIGNS dataset is a collection of 6 signs represen... |
10,475 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
np.random.seed(1337)
import warnings
warnings.filterwarnings("ignore")
import time as tm
import pandas as pd
from keras.models import Sequential, Model
from keras.constraints import maxnorm
from keras.layers import Dense, Dropout, Activation
from keras.utils import np_u... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load dataset
Step2: Utilities function
Step3: Extract data
Step4: Modified imputation method using MLPRegressor
Step5: Feature Augmentation ... |
10,476 | <ASSISTANT_TASK:>
Python Code:
# ! pip install hypernetx -q
# ! pip install graphistry -q
import pandas as pd
class HyperNetXG:
def __init__(self, graphistry):
self.graphistry = graphistry
def normalize_id(self, id):
t = type(id)
if t == float or t == int:
return '_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Lib
Step2: Demo
Step3: hypernetx_to_graphistry_bipartite
Step4: hypernetx_to_graphistry_nodes
|
10,477 | <ASSISTANT_TASK:>
Python Code:
Instructions:
+ Use the upper() method on room and store the result in room_up.
Use the dot notation.
+ Print out room and room_up. Did both change?
+ Print out the number of o's on the variable room by calling count()
on room and passing the letter "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: Lecture
Step3: 2. List Methods -- 100xp, status
Step5: 3. List Methods II -- 100xp, status
|
10,478 | <ASSISTANT_TASK:>
Python Code:
from pynq.overlays.base import BaseOverlay
base = BaseOverlay("base.bit")
from pynq.lib import Pmod_ALS
# ALS sensor is on PMODB
my_als = Pmod_ALS(base.PMODB)
my_als.read()
my_als.start_log()
my_als.stop_log()
log = my_als.get_log()
%matplotlib inline
import matplotlib.pyplot as plt
pl... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2. Starting logging light once every second
Step2: 3. Modifying the light
Step3: 4. Plot values over time
|
10,479 | <ASSISTANT_TASK:>
Python Code:
# from a list
a = set([1,2,3,4])
a
# using curly braces
a = {1,2,3,4}
a
# using a tuple
a = set((1,2,3,4))
a
# start with and empty set and add elements to it
a = set()
a.add('hello')
a
# be careful in assigning a string as an element to a set. If assigned as below, it'll be broken up and... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Adding, Updating, and Removing elements from a set
Step2: Set Membership & Length
Step3: Set Intersection, Disjoint, Union, and Difference
Ste... |
10,480 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from astropy.table import Table
from astropy.coordinates import SkyCoord
from astropy import units as u
from astropy.table import hstack
import matplotlib.pyplot as plt
import numpy as np
from astroML.plotting import hist
# for astroML installation see https://www.astr... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <a id='dataReading'></a>
Step2: Simple positional match using ra/dec
Step3: apply standard cuts as in old catalog
Step4: now match to Gaia DR... |
10,481 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook
from sklearn import datasets, svm, metrics, utils
from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original', data_home='./data')
mnist.data, mnist.target = utils.shuffle(mnist.data, mnist.targe... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Fetching the MNIST dataset
Step2: It's 70000 examples of handwritten digits of size 28x28 pixels, labeled from 0 to 9.
Step3: Pick the first 1... |
10,482 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import sys
from salib import extend
class EF(object):
Class EF represents the 6 end forces acting on a 2-D, planar, beam element.
def __init__(self,c0=0.,v1=0.,m2=0.,c3=0.,v4=0.,m5=0.):
Initialize an instance with the 6 end forces. If the fir... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step7: Class EF
Step8: Now define properties so that the individual components can be accessed like name atrributes,
Step14: Class MemberLoad
Step15:... |
10,483 | <ASSISTANT_TASK:>
Python Code:
# Load libraries
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
import warnings
# Suppress Warning
warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd")
# Load data
boston = load_boston()
X = boston.data
y = boston... | <SYSTEM_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 Boston Housing Dataset
Step2: Fit A Linear Regression
Step3: View Intercept Term
Step4: View Coefficients
|
10,484 | <ASSISTANT_TASK:>
Python Code:
!git config --global user.name "joaquin" # replace joaquin by your name
!git config --global user.email "user@gmail.com" # replace j by your email
# Put here your preferred editor. If this is not set, git will honor the $EDITOR environment variable
# On Windows: Notepad works, Notepad++,... | <SYSTEM_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 how you will edit text files (it will often ask you to edit messages and other information, and thus wants to know how you like to edit your... |
10,485 | <ASSISTANT_TASK:>
Python Code:
from pygoose import *
from collections import defaultdict
import seaborn as sns
import nltk
nltk.download('stopwords')
project = kg.Project.discover()
feature_list_id = 'wm_intersect'
df_train = pd.read_csv(project.data_dir + 'train.csv').fillna('none')
df_test = pd.read_csv(project.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: Config
Step2: Identifier for storing these features on disk and referring to them later.
Step3: Load Data
Step4: Build features
Step5: Visua... |
10,486 | <ASSISTANT_TASK:>
Python Code:
central_source = np.zeros((21, 21))
central_source[10,10] = 1.
gaussian_test = ndimage.gaussian_filter(central_source, 1.4)
imshow(gaussian_test)
colorbar()
from scipy.special import rel_entr
kl_div_same_dist = np.sum(rel_entr(gaussian_test, gaussian_test))
print("The KL Divergence of th... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Run some basic tests
Step2: Test 2
Step3: 2.2 Wider Gaussian
Step4: Test 3
Step5: As expected we see that the KL-divergence when comparing t... |
10,487 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('..')
import socnet as sn
import numpy as np
from scipy.stats.stats import pearsonr
from scipy.optimize import minimize
def cost(c, A, mask):
row = np.matrix(c)
C = np.multiply(row.transpose(), row)
correlation, _ = pearsonr(C[~mask].flat, A[~mask].... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Definindo função que calcula coreness
Step2: Definindo função que calcula PageRank
Step3: Lista de todos os códigos de países, para facilitar ... |
10,488 | <ASSISTANT_TASK:>
Python Code:
import pylab
from qiskit_aqua import run_algorithm
from qiskit_aqua.input import get_input_instance
from qiskit.tools.visualization import circuit_drawer, plot_histogram
with open('3sat3-5.cnf', 'r') as f:
sat_cnf = f.read()
print(sat_cnf)
algorithm_cfg = {
'name': 'Grover'
}
or... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We have a SAT problem to which we want to find solutions using Grover and SAT oracle combination. The SAT problem is specified in the DIMACS CNF... |
10,489 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from time import sleep # used for polling jobs
# importing the QISKit
from qiskit import Aer, IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import register, execute
# import tomography library
import qiskit.tools.qcvv.tomog... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: State tomography of an entangled Bell-state
Step2: Visualization of the ideal state
Step3: We may visualize the final state using the plot_sta... |
10,490 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import tensorflow as tf
with open('../sentiment-network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment-network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
from string import punctuation
all_text = ''.join([c for c in reviews if... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Data preprocessing
Step2: Encoding the words
Step3: Encoding the labels
Step4: Okay, a couple issues here. We seem to have one review with ze... |
10,491 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csiro-bom', 'sandbox-3', 'seaice')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name",... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... |
10,492 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
!pip install git+https://github.com/google-research/tensorflow_constrained_optimization
import tensorflow_constrained_optimization as tfco
def create_dataset(num_queries, num_docs):
# Create a synthetic 2-dimen... | <SYSTEM_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 will need the TensorFlow Constrained Optimization (TFCO) library.
Step2: Constrained Optimization Problem
Step3: Plotting Functions
Step4: ... |
10,493 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import math
from IPython import display
try:
import torch
except ModuleNotFoundError:
%pip install -qq torch
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils import data
import collection... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step4: Data
Step11: Show first 3 training examples and their labels (“0”, “1”, and “2” correspond to “entailment”, “contradiction”, and “neutral”, res... |
10,494 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
seeds_dataset = pd.read_csv('seeds_dataset.csv', header=None)
seeds_dataset[:5]
# Initialize a network:
def initialize_network(n_inputs, n_hidden, n_outputs):
network = list()
hidden_layer = [{'weights':[random() for i in range(n_inputs + 1)]} for i in range(... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Below is a sample of the first 5 rows of the seeds dataset.
Step2: Tutorial
Step3: Let's test out this function.
Step4: Running the example, ... |
10,495 | <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: MS-COCO 데이터세트 다운로드 및 준비
Step3: 선택 사항
Step4: InceptionV3를 사용하여 이미지 전처리하기
Step5: InceptionV3 초기화 및 사전 훈련된 Imagenet 가중치 로드하... |
10,496 | <ASSISTANT_TASK:>
Python Code:
import sys
import math
import numpy as np
import matplotlib as mpl
print('System: {}'.format(sys.version))
for package in (np, mpl):
print('Package: {} {}'.format(package.__name__, package.__version__))
import matplotlib.pyplot as plt
%matplotlib inline
ff = np.linspace(0.01, 6., 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 will produce some plots based on a frequency range to illustrate the concepts
Step2: Back to top
Step3: Back to top
Step4: Back to top
Ste... |
10,497 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pylab as plt
import numpy as np
from astrometry.util.fits import *
from astrometry.util.plotutils import *
from collections import Counter
from astrometry.libkd.spherematch import *
from astrometry.util.starutil import *
from glob import glob
import fitsio
T4 = ... | <SYSTEM_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 all tractor catalogs
Step2: Find matched/unmatched sources (not currently doing anything with these)
Step3: Find matched (nearest-neighbo... |
10,498 | <ASSISTANT_TASK:>
Python Code:
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import hyperspy.api as hs
experimental_data = hs.load("data/sample_with_g.hspy", lazy=True)
experimental_data
experimental_data.center_direct_beam(method="blur", half_square_width=50, sigma=1.5)
# Define the affine... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <a id="load"></a> 1. Load, inspect, calibrate data
Step2: Centering the dataset
Step3: Affine transformation
Step4: Scale calibration
Step5: ... |
10,499 | <ASSISTANT_TASK:>
Python Code:
reset -fs
import keras
# What is the backend / execution engine?
keras.backend.backend()
# Import data
from keras.datasets import mnist
# Setup train and test splits
(x_train, y_train), (x_test, y_test) = mnist.load_data()
from random import randint
from matplotlib import pyplot
%matplot... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <center><img src="images/tf_logo.jpg" width="70%"/></center>
Step2: Munge data
Step3: RTFM - https
Step4: <center><img src="images/dense.png"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.