text_prompt stringlengths 168 30.3k | code_prompt stringlengths 67 124k |
|---|---|
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now we can write some C code. The %%microblaze magic provides an environment where we can write the code and it takes a single argument - the Mi... | <ASSISTANT_TASK:>
Python Code:
from pynq.overlays.base import BaseOverlay
base = BaseOverlay('base.bit')
%%microblaze base.PMODA
int add(int a, int b) {
return a + b;
}
add(4,6)
%%microblaze base.PMODA
float arg_passing(float a, char b, unsigned int c) {
return a + b + c;
}
arg_passing(1, 2, 3)
%%microblaze... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cccr-iitm', 'sandbox-3', 'ocean')
# 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: Key Phrase Extraction - Keybert
Step2: Sentiment Analysis - Huggingface
Step3: Zero Shot Classification - Huggingface
Step4: Few Shot Classif... | <ASSISTANT_TASK:>
Python Code:
!pip install transformers
!pip install torch
!pip install keybert
from keybert import KeyBERT
kw_model = KeyBERT()
document='''
My electricity isn't working, and I've not had any power for five hours, can you send someone to fix it please.
'''
kw_model.extract_keywords(document, keyphras... |
<SYSTEM_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 dataset
Step2: Degree-days work on daily data, so we want to resample our dataset to the daily mean.
Step3: Compute degree days
Step4:... | <ASSISTANT_TASK:>
Python Code:
import opengrid as og
import pandas as pd
plt = og.plot_style()
# A dataset with hourly weather variables for Brussels (2016) is included in OpenGrid.
# Note that the data contains also the last week of 2015.
# This is required in order for the degree-days computation to work for the ... |
<SYSTEM_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 arm library-- see the Chapter 3.1 notebook if you need help.
Step2: Display a regression line as a function of one input variable, Pg ... | <ASSISTANT_TASK:>
Python Code:
%%R
# I had to import foreign to get access to read.dta
library("foreign")
kidiq <- read.dta("../../ARM_Data/child.iq/kidiq.dta")
# I won't attach kidiq-- i generally don't attach to avoid confusion(s)
#attach(kidiq)
%%R
library("arm")
%%R
fit.2 <- lm(kidiq$kid_score ~ kidiq$mom_iq)
plo... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Learning Embeddings with SeqToSeq
Step2: We need to define the "alphabet" for our SeqToSeq model, the list of all tokens that can appear in seq... | <ASSISTANT_TASK:>
Python Code:
!pip install --pre deepchem
import deepchem
deepchem.__version__
import deepchem as dc
tasks, datasets, transformers = dc.molnet.load_muv(split='stratified')
train_dataset, valid_dataset, test_dataset = datasets
train_smiles = train_dataset.ids
valid_smiles = valid_dataset.ids
tokens = ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Most objects knows how to show() themselves
Step2: Most things are list-like
Step3: Since a directory is a list of files, it makes sence that ... | <ASSISTANT_TASK:>
Python Code:
from radiopadre import ls, settings
dd = ls() # calls radiopadre.ls() to get a directory listing, assigns this to dd
dd # standard notebook feature: the result of the last expression on the cell is rendered in HTML
dd.show()
print "Calling .show() on an object rende... |
<SYSTEM_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 fake dataset
Step2: Hyperparameters
Step3: Visualize training sequences
Step4: The model definition
Step5: <div style="text-align
S... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import utils_datagen
import utils_display
from matplotlib import pyplot as plt
import tensorflow as tf
print("Tensorflow version: " + tf.__version__)
DATA_SEQ_LEN = 1024*128
data = np.concatenate([utils_datagen.create_time_series(waveform, DATA_SEQ_LEN) for waveform in... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: array.T returns the transpose of an array.
Step2: Stacking and Splitting Arrays
Step3: Similarly, two arrays having the same number of rows ca... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
# Reshape a 1-D array to a 3 x 4 array
some_array = np.arange(0, 12).reshape(3, 4)
print(some_array)
# Can reshape it further
some_array.reshape(2, 6)
# If you specify -1 as a dimension, the dimensions are automatically calculated
# -1 means "whatever dimension is need... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Anytime you see a statement that starts with import, you'll recognize that the programmer is pulling in some sort of external functionality not ... | <ASSISTANT_TASK:>
Python Code:
import random
x = [3, 7, 2, 9, 4]
print("Maximum: {}".format(max(x)))
print("Minimum: {}".format(min(x)))
import random # For generating random numbers, as we've seen.
import os # For interacting with the filesystem of your computer.
import re # For regular expressions. Un... |
<SYSTEM_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 model does a poor job of fitting to our data. If I fit a non-parametric model, like the Nelson-Aalen model, to this data, the Exponential's... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from lifelines.datasets import load_waltons
waltons = load_waltons()
T, E = waltons['T'], waltons['E']
from lifelines import ExponentialFitter
fig,... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Basic rich display
Step2: Use the HTML object to display HTML in the notebook that reproduces the table of Quarks on this page. This will requi... | <ASSISTANT_TASK:>
Python Code:
from IPython.display import Image
assert True # leave this to grade the import statements
Image(url='http://ecx.images-amazon.com/images/I/31ESVCFE0SL.jpg',embed=True,width=600,height=600)
assert True # leave this to grade the image display
%%html
<table>
<tr>
<th>Name</th>
<th>Symbol</... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Displacement operation
Step2: Optical quantum states in the fock basis
Step4: Displace and measure - the generalized Q function
Step6: Iterat... | <ASSISTANT_TASK:>
Python Code:
# imports
import numpy as np
from qutip import Qobj, rand_dm, fidelity, displace, qdiags, qeye, expect
from qutip.states import coherent, coherent_dm, thermal_dm, fock_dm
from qutip.random_objects import rand_dm
from qutip.visualization import plot_wigner, hinton, plot_wigner_fock_distri... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: values from Okanoya paper below (KOUMURA_OKANOYA_NOTE_ERROR_RATES) are taken from this table
| <ASSISTANT_TASK:>
Python Code:
TRAIN_DUR_IND_MAP = {
k:v for k, v in zip(
sorted(curve_df['train_set_dur'].unique()),
sorted(curve_df['train_set_dur_ind'].unique())
)
}
SAVE_FIG = True
sns.set("paper")
KOUMURA_OKANOYA_NOTE_ERROR_RATES = {
120. : 0.84,
480. : 0.46,
}
KOUMURA_OKANOYA_X =... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Create the dataset
Step3: Review the dataset
Step4: Using BQML
Step5: Get training statistics and examine training info
Step6: We can also e... | <ASSISTANT_TASK:>
Python Code:
PROJECT = !(gcloud config get-value core/project)
PROJECT = PROJECT[0]
%env PROJECT = {PROJECT}
%env REGION = "us-central1"
from google.cloud import bigquery
from IPython import get_ipython
bq = bigquery.Client(project=PROJECT)
def create_dataset():
dataset = bigquery.Dataset(bq.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: Load LendingClub dataset
Step2: Exploring some features
Step3: Here, we see that we have some feature columns that have to do with grade of th... | <ASSISTANT_TASK:>
Python Code:
import graphlab
graphlab.canvas.set_target('ipynb')
loans = graphlab.SFrame('lending-club-data.gl/')
loans.column_names()
loans['grade'].show()
loans['sub_grade'].show()
loans['home_ownership'].show()
# safe_loans = 1 => safe
# safe_loans = -1 => risky
loans['safe_loans'] = loans['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: Load data
Step2: Fit the best model
Step3: A better way. Use a model_selection tool
| <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
from sklearn import __version__ as sklearn_version
print('Sklearn version:', sklearn_version)
from sklearn import datasets
all_data = datasets.california_housing.fetch_california_housing()
print(all_data.DESCR)
# Randomize, separate train & test 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: Running
Step2: async-apply
Step3: We can see that we created a new task and it's pending. Note that the API is async, meaning it won't wait un... | <ASSISTANT_TASK:>
Python Code:
from celery import Celery
from time import sleep
celery = Celery()
celery.config_from_object({
'BROKER_URL': 'amqp://localhost',
'CELERY_RESULT_BACKEND': 'amqp://',
'CELERYD_POOL_RESTARTS': True, # Required for /worker/pool/restart API
})
@celery.task
def add(x, y):
retur... |
<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: Downsampling
Step3: Weighted classes and output bias
Step4: We'll take all of the fraud examples from this dataset, and a subset of non-fraud.... | <ASSISTANT_TASK:>
Python Code:
import itertools
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
import xgboost as xgb
from tensorflow import keras
from tensorflow.keras import Sequential
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing 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: 2) What genres are most represented in the search results?
Step2: ANSWER
Step3: 3) Use a for loop to determine who BESIDES Lil Wayne has the h... | <ASSISTANT_TASK:>
Python Code:
data = response.json()
data.keys()
artist_data = data['artists']
artist_data.keys()
lil_names = artist_data['items']
#lil_names = list of dictionaries = list of artist name, popularity, type, genres etc
for names in lil_names:
if not names['genres']:
print(names['name'], 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: Loading data files
Step2: The files are all in Unicode, to simplify we will turn Unicode characters to ASCII, make everything lowercase, and tr... | <ASSISTANT_TASK:>
Python Code:
import unicodedata, string, re, random, time, math, torch, torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
import keras, numpy as np
from keras.preprocessing import sequence
SOS_token = 0
EOS_token = 1
class Lang:
def __init_... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Change the following cell as necessary
Step2: Confirm below that the bucket is regional and its region equals to the specified region
Step3: C... | <ASSISTANT_TASK:>
Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
import os
from google.cloud import bigquery
# Change with your own bucket and project below:
BUCKET = "<BUCKET>"
PROJECT = "<PROJECT>"
REGION = "<YOUR REGION>"
OUTDIR = "gs://{bucket}/taxifare/data".format(bucket=BUCKET)... |
<SYSTEM_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 the data
Step2: Fit the models
| <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort
# Denis A. Engemann
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from scipy import linalg
from sklearn.decomposition import PCA, FactorAnalysis
from sklearn.covariance import ShrunkCovariance, LedoitWolf
from sklearn.mod... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Explore The Data
Step2: Count Labels
Step3: Top 50 Labels
Step4: Sig/ Labels
Step5: See correlation among labels
Step6: Obtain Baseline Wit... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
from random import randint
from matplotlib import pyplot as plt
import re
pd.set_option('max_colwidth', 1000)
df = pd.read_csv('https://storage.googleapis.com/issue_label_bot/k8s_issues/000000000000.csv')
df.labels = df.labels.apply(lambda x: eval(x)... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load in house sales data
Step2: If we want to do any "feature engineering" like creating new features or adjusting existing ones we should do t... | <ASSISTANT_TASK:>
Python Code:
import graphlab
sales = graphlab.SFrame('../Data/kc_house_data.gl/')
# In the dataset, 'floors' was defined with type string,
# so we'll convert them to int, before using it below
sales['floors'] = sales['floors'].astype(int)
import numpy as np # note this allows us to refer to 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: Exercice 1 - manipulation des bases
Step2: Nombre de joueurs par équipe
Step3: Les joueurs ayant couvert le plus de distance
Step4: On voit u... | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
from pyensae.datasource import download_data
files = download_data("td2a_eco_exercices_de_manipulation_de_donnees.zip",
url="https://github.com/sdpython/ensae_teaching_cs/raw/master/_doc/notebooks/td2a_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: Compiling Expressions
Step2: Multiple matches
Step3: The finditer() function returns an iterator that produces Match object instances of the s... | <ASSISTANT_TASK:>
Python Code:
import re
pattern = 'text'
text = 'Does this text match the pattern?'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print('Found "{}"\n in "{}"\n from {} to {} ("{}")'.format(
match.re.pattern, match.string, s, e, text[s:e]))
import re
regexes = [re.compile(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:
Step2: 2. Explore Natality dataset
Step3: 3. Training on Cloud ML Engine
Step4: 3. Get a saved model directory
Step5: 4. Testing an evaluation pipel... | <ASSISTANT_TASK:>
Python Code:
# change these to try this notebook out
BUCKET = 'cloudonair-ml-demo'
PROJECT = 'cloudonair-ml-demo'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
%%bash
gcloud config set project $PROJECT
gcloud config set com... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Running pyBadlands
| <ASSISTANT_TASK:>
Python Code:
from pyBadlands.model import Model as badlandsModel
# Initialise model
model = badlandsModel()
# Define the XmL input file
model.load_xml('test','mountain.xml')
start = time.time()
model.run_to_time(10000000)
print 'time', time.time() - start
<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: Initializing DNA object and storing data to it
Step2: Smoothening of Helical Axis
Step3: Extraction of original and smoothed helical axis post... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import dnaMD
%matplotlib inline
## Initialization
fdna = dnaMD.DNA(60) #Initialization for 60 base-pairs free DNA
## If HDF5 file is used to store/save data use these:
# fdna = dnaMD.DNA(60, filename='odna.h5') #Initialization fo... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set Up Verta
Step2: Imports
Step3: Download the IMDB dataset
Step4: Explore the data
Step5: Let's also print the first 2 labels.
Step6: Bui... | <ASSISTANT_TASK:>
Python Code:
# Python 3.6
!pip install verta
!pip install matplotlib==3.1.1
!pip install tensorflow==2.0.0-beta1
!pip install tensorflow-hub==0.5.0
!pip install tensorflow-datasets==1.0.2
HOST = 'app.verta.ai'
PROJECT_NAME = 'Text-Classification'
EXPERIMENT_NAME = 'basic-clf'
# import os
# os.environ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cmcc', 'sandbox-1', 'landice')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "em... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csir-csiro', 'sandbox-3', 'atmoschem')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("na... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's start by loading some pre-generated data meant to represent radial velocity observations of a single luminous source with two faint compan... | <ASSISTANT_TASK:>
Python Code:
import astropy.table as at
import astropy.units as u
from astropy.visualization.units import quantity_support
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
import thejoker as tj
# set up a random number generator to ensure reproducibility
rnd = np.random.default_rn... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Mairhuber-Curtis Theorem
Step2: Halton points vs pseudo-random points in 2D
Step3: Interpolation with Distance Matrix from Halton points
Step4... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import ghalton
import matplotlib.pyplot as plt
%matplotlib inline
from ipywidgets import interact
from scipy.spatial import distance_matrix
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Setup
Step2: Define the network
Step3: Load the model parameters and metadata
Step4: Trying it out
Step5: Helper to fetch and preprocess ima... | <ASSISTANT_TASK:>
Python Code:
!wget https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/vgg_cnn_s.pkl
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import lasagne
from lasagne.layers import InputLayer, DenseLayer, DropoutLayer
from lasagne.layers.dnn import Conv2DDNNLayer as ConvLayer... |
<SYSTEM_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 first prepare set up the credentials required to access the devices.
Step2: We'll now run the circuit on the simulator for 128 shots (so we ... | <ASSISTANT_TASK:>
Python Code:
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
from qiskit import IBMQ, available_backends, get_backend
from qiskit.wrapper.jupyter import *
import matplotlib.pyplot as plt
%matplotlib ... |
<SYSTEM_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 Fermi distribution
Step3: In this equation
Step4: Write a function plot_fermidist(mu, kT) that plots the Fermi distribution $F(\... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import Image
from IPython.html.widgets import interact, interactive, fixed
Image('fermidist.png')
def fermidist(energy, mu, kT):
Compute the Fermi distribution at energy, mu and kT.
F = 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: Text
Step2: Listing 8.1
Step5: Listing 8.2
Step6: Listing 8.3
Step7: Listing 8.4
Step8: Listing 8.6
Step11: Listing 8.7
| <ASSISTANT_TASK:>
Python Code:
class Square:
def __init__(self):
self.side = 1
Bob = Square() # Bob is an instance of Square.
Bob.side #Let’s see the value of side
Bob.side = 5 #Assing a new value to side
Bob.side #Let’s see the new value of side
Krusty = Square()
Krusty.side
class Square:
def __in... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: People needing to divide a fiscal year starting in July, into quarters, are in luck with pandas. I've been looking for lunar year and other per... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
rng_years = pd.period_range('1/1/2000', '1/1/2018', freq='Y')
head_count = np.random.randint(10,35, size=19)
new_years_party = pd.DataFrame(head_count, index = rng_years,
columns=["Attenders"])
new_years_party
np.ro... |
<SYSTEM_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: Hyperparameters
Step3: Training a baseline LSTM
Step4: Training a Bayesian LSTM
Step5: From the training curves and t... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import seaborn as sns
import pandas as pd
import tensorflow as tf
import edward2 as ed
import matplotlib.pyplot as plt
from tqdm import tqdm
from sklearn.model_selection import train_test_split, ParameterGrid
from tensorflow.keras.preprocessing import sequence
import em... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Download & Process Security Dataset
Step2: Analytic I
| <ASSISTANT_TASK:>
Python Code:
from openhunt.mordorutils import *
spark = get_spark()
sd_file = "https://raw.githubusercontent.com/OTRF/Security-Datasets/master/datasets/atomic/windows/defense_evasion/host/empire_wdigest_downgrade.tar.gz"
registerMordorSQLTable(spark, sd_file, "sdTable")
df = spark.sql(
'''
SELECT `@... |
<SYSTEM_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 datasets from MongoDB collections
Step2: Import packages
Step3: Validate tf and tfio imports
Step4: Download and setup the MongoDB... | <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: 2 - Overview of the Problem set
Step2: We added "_orig" at the end of image datasets (train and test) because we are going to preprocess them. ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
%matplotlib inline
# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_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: Read in Google Scraper search results table
Step2: Programatically identify unique images
Step3: Add the hash to each row in our data datafram... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (15, 3)
plt.rcParams['font.family'] = 'sans-serif'
pd.set_option('display.width', 5000)
pd.set_option('display.max_columns', 60)
cols = ['re... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: To access the 3D final velocity use
Step2: Individual voxels in these 3D volumetric data cube can be accessed as follows
Step3: where i,j and ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
velocity = np.load('borg_sdss_velocity.npz')
#3D probabilistic maps for velocity field
vx_mean=velocity['vx_mean']
vx_var=velocity['vx_var']
vy_mean=velocity['vy_mean']
vy_var=velocity['vy_var']
vz_mean=velocity['vz_mean']
vz_var=velocity['vz_var']
k=10;j=127;i=243
vx... |
<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: Define VAE
Step7: 1D Gaussian
Step8: Plot the data to verify
Step9: Merge and shuffle them, use VAE to train on data
Step10: Reconstruct Dat... | <ASSISTANT_TASK:>
Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
import time
from tensorflow.python.client import timeline
import matplotlib.pyplot as plt
%matplotlib inline
FLAGS = tf.app.flags.FLAGS
#... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: NumPy
Step2: Requests
Step3: Pandas (optional)
Step4: SciPy (optional)
Step5: 2) Importar scidb-py
Step6: conectarse al servidor de Base de... | <ASSISTANT_TASK:>
Python Code:
import sys
sys.version_info
import numpy as np
np.__version__
import requests
requests.__version__
import pandas as pd
pd.__version__
import scipy
scipy.__version__
import scidbpy
scidbpy.__version__
from scidbpy import connect
sdb = connect('http://localhost:8080')
import urllib.r... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercise. Write a snippet of code to verify that the vertex IDs are dense in some interval $[1, n]$. That is, there is a minimum value of $1$, s... | <ASSISTANT_TASK:>
Python Code:
import sqlite3 as db
import pandas as pd
def get_table_names (conn):
assert type (conn) == db.Connection # Only works for sqlite3 DBs
query = "SELECT name FROM sqlite_master WHERE type='table'"
return pd.read_sql_query (query, conn)
def print_schemas (conn, table_names=None, 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: To obtain these curves, we sort the predictions made by the classifier from the smallest to the biggest for each group and put them on a $[0, 1]... | <ASSISTANT_TASK:>
Python Code:
fig, ax = plt.subplots(1, 1, figsize=(8, 5))
plot_quantiles(logits, groups, ax)
ax.tick_params(axis='both', which='major', labelsize=16)
ax.set_title(f'Baseline Quantiles', fontsize=22)
ax.set_xlabel('Quantile Level', fontsize=18)
ax.set_ylabel('Prediction', fontsize=18)
N = 24
rng = jax... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Des méthodes peuvent être enchaînées sur les corps célestes présents dans planets.
Step2: La méthode utc permet d'entrer des données temporelle... | <ASSISTANT_TASK:>
Python Code:
from skyfield.api import load, utc
ts = load.timescale()
# chargement des éphémérides
planets = load('de421.bsp')
earth = planets['earth']
sun = planets['sun']
moon = planets['moon']
# Position de la Terre au 1er janvier 2017
earth.at(ts.utc(2017, 1, 1))
import datetime
now = datetime.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: Enoncé 1
Step2: Pour cette question, quelques élèves ont vérifié que n était plus petit que 2014 d'abord. Ce n'est pas vraiment la peine.
Step3... | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
def mul2014(n):
return 1 if n % 2014 == 0 else 0
print(mul2014(2014), mul2014(2015))
import math
min ( math.cos(i) for i in range(1,11) )
list(range(0,10))
def symetrie(s):
i=0
j=len(s)-1
while i < j :
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Stats Quality for 2016 College Nationals
Step2: Since we should already have the data downloaded as csv files in this repository, we will not n... | <ASSISTANT_TASK:>
Python Code:
import usau.reports
import usau.fantasy
from IPython.display import display, HTML
import pandas as pd
pd.options.display.width = 200
pd.options.display.max_colwidth = 200
pd.options.display.max_columns = 200
def display_url_column(df):
Helper for formatting url links
df.url = df.url.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: Tokenizing
Step2: Stop words
Step3: Stemming
Step4: Part of Speech Tagging
Step6: Chunking
| <ASSISTANT_TASK:>
Python Code:
import nltk
from nltk import tokenize
# TODO: we don't relly want to download packages each time when we lauch this script
# so it'll better to check somehow whether we have packages or not - or Download on demand
# nltk.download()
example = 'Hello Mr. Smith, how are you doing today? The... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's go over the columns
Step2: Now suppose we want a DataFrame of the Blaze Data Object above, but only want the asof_date, repurchase_units,... | <ASSISTANT_TASK:>
Python Code:
# import the dataset
from quantopian.interactive.data.eventvestor import share_repurchases
# or if you want to import the free dataset, use:
# from quantopian.interactive.data.eventvestor import share_repurchases_free
# import data operations
from odo import odo
# import other libraries 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: import the new haven report card module
Step2: now determine the root directory for the repo
Step3: read in the issue data from file (to speed... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import nhrc2
from nhrc2.backend import get_neighborhoods as get_ngbrhd
from nhrc2.backend import read_issues as ri
import pandas as pd
import numpy as np
nhrc2dir = '/'.join(str(nhrc2.__file__).split('/')[:-1])+'/'
scf_df_cat = ri.re... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Import the file into pandas, and drop all rows without a GPS fix
Step2: Find the Lat/Lon bounding box and create a new map from the osmapping l... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import osmapping
import glob
%matplotlib inline
dname = '/Users/astyler/projects/torquedata/'
trips = []
fnames = glob.glob(dname+'*.csv')
for fname in fnames:
trip = pd.read_csv(fname, na_values=['-'],encoding... |
<SYSTEM_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 tricky histogram with pre-counted data
Step2: Q
Step3: As you can see, the default histogram does not normalize with binwidth and simply s... | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import altair as alt
import pandas as pd
import matplotlib
matplotlib.__version__
bins = [0, 1, 3, 5, 10, 24]
data = {0.5: 4300, 2: 6900, 4: 4900, 7: 2000, 15: 2100}
data.keys()
# TODO: draw a histogram with weigh... |
<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: Problem setting
Step5: Graph Laplacian
Step6: Fourier basis
Step8: Ground truth graph filter
Step9: Graph signals
Step10: Non-parametrized ... | <ASSISTANT_TASK:>
Python Code:
import time
import numpy as np
import scipy.sparse, scipy.sparse.linalg, scipy.spatial.distance
import matplotlib.pyplot as plt
%matplotlib inline
tol = 1e-10
M = 100 # nodes
k = 4 # edges per vertex
def graph_random():
Random connections and weights.
I = np.arange(0, M).repeat... |
<SYSTEM_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. Read the data
Step2: Let's look at the first five rows
Step3: What is the size of the table?
Step4: What are the types of the data?
Step5:... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
%matplotlib inline
import seaborn as sns
from matplotlib import pyplot as plt
import numpy as np
sns.set_style("darkgrid")
%cd C:\Users\Profesor\Documents\curso_va_2015\va_course_2015
df = pd.read_csv("../MC1 2015 Data/park-movement-Fri.csv")
df.head()
df.shape
df.... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Note
Step3: Details of the "Happy" dataset
Step4: You have now built a function to describe your model. To train and test this model, there ar... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from keras import layers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.models import Model
fro... |
<SYSTEM_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: add_constraints
Step3: update
Step4: optimize
Step5: Test example #1
Step6: Test example #2
Step7: Test example #3
Ste... | <ASSISTANT_TASK:>
Python Code:
from gachon_lp_solver import GachonLPSolver # gachon_lp_solver 파일(모듈)에서 GachonLPSolver class를 import
lpsover = GachonLPSolver("test_example") #GachonLPSolver class의 첫 번째 argument인 model_name에 "test_example" 를 할당함
lpsover.model_name
import numpy as np
import importlib
import gachon_lp_so... |
<SYSTEM_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.1 Smoothing operator
Step2: 1.2 Interpolation Operator
Step3: 1.3 Restriction
Step4: 1.4 Bottom Solver
Step5: Thats it! Now we can see it ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
def Jacrelax(nx,ny,u,f,iters=1):
'''
under-relaxed Jacobi iteration
'''
dx=1.0/nx; dy=1.0/ny
Ax=1.0/dx**2; Ay=1.0/dy**2
Ap=1.0/(2.0*(Ax+Ay))
#Dirichlet BC
u[ 0,:] = -u[ 1,:]
u[-1,:] = -u[-2,:]
u[:, 0] = -u[:, 1]
u[:,-1] = -u[:,-2]
for it in rang... |
<SYSTEM_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 for potential hosts
Step2: The first question is
Step3: That looks right to me. I think this is RA and DEC, but I don't think I need ... | <ASSISTANT_TASK:>
Python Code:
import collections
import io
from pprint import pprint
import sqlite3
import sys
import warnings
import astropy.io.votable
import astropy.wcs
import matplotlib.pyplot
import numpy
import requests
import requests_cache
%matplotlib inline
sys.path.insert(1, '..')
import crowdastro.data
impo... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Introduction for the two-level system
Step2: The emission can be decomposed into a so-called coherent and incoherent portion. The coherent port... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import numpy as np
from qutip import *
# define system operators
gamma = 1 # decay rate
sm_TLS = destroy(2) # dipole operator
c_op_TLS = [np.sqrt(ga... |
<SYSTEM_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 see that by numbers we have a good coefficient correlation between the true values and the predicted ones
Step2: Kind of gaussian distributi... | <ASSISTANT_TASK:>
Python Code:
def getModel(alpha):
return Ridge(alpha=alpha, fit_intercept=True, normalize=False, copy_X=True, random_state=random_state)
model = getModel(alpha=0.01)
cvs = cross_val_score(estimator=model, X=XX, y=yy, cv=10)
cvs
cv_score = np.mean(cvs)
cv_score
def gpOptimization(n_jobs=n_jobs, cv=... |
<SYSTEM_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: 이번에는 n_features 즉, 독립 변수가 2개인 표본 데이터를 생성하여 스캐터 플롯을 그리면 다음과 같다. 종속 변수 값은 점의 명암으로 표시하였다.
Step3: 만약 실제로 y값에 영향을 미치는 독립 변수... | <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import make_regression
X, y, c = make_regression(n_samples=10, n_features=1, bias=0, noise=0, coef=True, random_state=0)
print("X\n", X)
print("y\n", y)
print("c\n", c)
plt.scatter(X, y, s=100)
plt.show()
X, y, c = make_regression(n_samples=50, n_features=1, bias=10... |
<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: Live Predictions
Step3: TensorFlow.js
Step4: Convert Model
Step5: Predict in JS
Step6: 2. A static web server
Step7: 3. Port forwarding
| <ASSISTANT_TASK:>
Python Code:
# In Jupyter, you would need to install TF 2 via !pip.
%tensorflow_version 2.x
## Load models from Drive (Colab only).
models_path = '/content/gdrive/My Drive/amld_data/models'
data_path = '/content/gdrive/My Drive/amld_data/zoo_img'
## Or load models from local machine.
# models_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: SHO
Step2: The bound states (below the cutoff) are clearly linear in energy (as expected), then above that we see the ∞-well solutions.
Step3: ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from scipy.linalg import eigh, inv
import matplotlib.pyplot as plt
%matplotlib inline
N = 1000
x, dx = np.linspace(-1,1,N,retstep=True)
#dx = dx*0.1
# Finite square well
V_0 = np.zeros(N)
V_0[:] = 450
V_0[int(N/2 - N/6):int(N/2+N/6)] = 0
plt.plot(x,V_0)
plt.ylim(V.min()... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Clearly, the OM10 catalog is extended in MAGI/z space well beyond the CFHT reference.
| <ASSISTANT_TASK:>
Python Code:
plt.scatter(db.lenses['ZLENS'],db.lenses['APMAG_I'],color='Orange',marker='.',label='OM10')
plt.scatter(data[:,2],data[:,6],color='Blue',marker='.',label='CFHTLS')
plt.scatter(matched['ZLENS'],matched['APMAG_I'],color='Lime',marker='.',label='Matched OM10',alpha=.05)
plt.title('CFHTLS vs.... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Skewed split train test
Step2: La répartition train/test est loin d'être statisfaisante lorsqu'il existe une classe sous représentée.
Step3: U... | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
import numpy, numpy.random
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neural_netwo... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Cross correlation
Step3: Edge detection
Step4: Now we apply a vertical edge detector. It fires on the 1-0 and 0-1 boundaries.
Step5: It fails... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(seed=1)
import math
try:
import torch
except ModuleNotFoundError:
%pip install -qq torch
import torch
from torch import nn
from torch.nn import functional as F
!mkdir figures # for saving plots
import warnings
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: Importing modules
Step2: Some Editing tricks
Step3: Very quick plotting (just for export really)
Step4: Try export > html, > pdf (requires pa... | <ASSISTANT_TASK:>
Python Code:
!ls
!pip install --user pandas matplotlib sklearn seaborn
!pip install version_information
%load_ext version_information
%version_information pandas, sklearn
!pip install watermark
%load_ext watermark
%watermark -a "Gerrit Gruben" -d -t -v -p numpy,pandas -g
from somemodule import hello
... |
<SYSTEM_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 TFIDF scores for corpus without pivoted document length normalisation
Step2: Get TFIDF scores for corpus with pivoted document length norma... | <ASSISTANT_TASK:>
Python Code:
#
# Download our dataset
#
import gensim.downloader as api
nws = api.load("20-newsgroups")
#
# Pick texts from relevant newsgroups, split into training and test set.
#
cat1, cat2 = ('sci.electronics', 'sci.space')
#
# X_* contain the actual texts as strings.
# Y_* contain labels, 0 for ca... |
<SYSTEM_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: 在这个模式中, (?
| <ASSISTANT_TASK:>
Python Code:
import re
comment = re.compile(r"/\*(.*?)\*/")
text1 = '/* this is a comment */'
text2 = '''/* this is a
multiline comment */
'''
comment.findall(text1)
comment.findall(text2)
comment = re.compile(r'/\*((?:.|\n)*?)\*/')
comment.findall(text2)
comment = re.compile(r'/\*(.*?)\*/', re.DOTA... |
<SYSTEM_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 import
Step2: Convenience function for reading the data in
Step3: Getting a list of all user_ids in the sample.
Step4: Pick a subset of ... | <ASSISTANT_TASK:>
Python Code:
import collections
import itertools
import operator
import random
import heapq
import matplotlib.pyplot as plt
import ml_metrics as metrics
import numpy as np
import pandas as pd
import sklearn
import sklearn.decomposition
import sklearn.linear_model
import sklearn.preprocessing
%matplotl... |
<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: Half Adder
Step4: myHDL Testing
Step5: Verilog Code
Step7: Verilog Testbench
Step9: Full Adder From Exspresion
Step11: myHDL Testing
Step12... | <ASSISTANT_TASK:>
Python Code:
from myhdl import *
from myhdlpeek import Peeker
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sympy import *
init_printing()
import itertools
#https://github.com/jrjohansson/version_information
%load_ext version_information
%version_inform... |
<SYSTEM_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 Numpy on the cluster
Step2: DataFrame --> GraphFrame
Step3: Loading the Data - Edges
Step4: Make the graph
Step5: Graph Analytics
Step6:... | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
# from pyspark import SparkContext, SparkConf
# from pyspark.mllib.clustering import KMeans, KMeansModel
# # http://spark.apache.org/docs/2.0.0/api/python/pyspark.mllib.html#pyspark.mllib.evaluation.RankingMetrics
# from pyspark.mllib.evaluation impor... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csiro-bom', 'sandbox-1', '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: Adding volumes from HathiTrust
Step2: Working with Extracted Features
Step3: Now we'll feed these paths into the FeatureReader method which wi... | <ASSISTANT_TASK:>
Python Code:
%%capture
!pip install htrc-feature-reader
import os
from htrc_features import FeatureReader
from datascience import *
import pandas as pd
%matplotlib inline
!rm -rf local-folder/
!rm -rf local-folder/
!rm -rf data/coo*
!rm -rf data/mdp*
!rm -rf data/uc1*
download_output = !htid2rsync --... |
<SYSTEM_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: Example 2
| <ASSISTANT_TASK:>
Python Code:
def rgb2hsv(rgb_img):
import numpy as np
r = rgb_img[:,:,0].ravel()
g = rgb_img[:,:,1].ravel()
b = rgb_img[:,:,2].ravel()
hsv_map = map(rgb2hsvmap, r, g, b)
hsv_img = np.array(list(hsv_map)).reshape(rgb_img.shape)
return hsv_img
def rgb2hsvm... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2nd
Step2: Full batch gradient descent with unnormalized features
Step3: Full batch gradient descent with feature normalization
Step4: Mini-B... | <ASSISTANT_TASK:>
Python Code:
# Let's try to find the equation y = 2 * x
# We have 6 examples:- (x,y) = (0.1,0.2), (1,2), (2, 4), (3, 6), (-4, -8), (25, 50)
# Let's assume y is a linear combination of the features x, x^2, x^3
# We know that Normal Equation gives us the exact solution so let's first use that
N = 6
x =... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Logging into your account on CGC
Step2: Finding the project
Step3: Listing bam files in the project
Step4: Get the app to run
Step5: Set up ... | <ASSISTANT_TASK:>
Python Code:
import sevenbridges as sbg
from sevenbridges.errors import SbgError
from sevenbridges.http.error_handlers import *
import re
import datetime
import binpacking
print("SBG library imported.")
print sbg.__version__
prof = 'default'
config_file = sbg.Config(profile=prof)
api = sbg.Api(config... |
<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: Functions
Step4: This code starts by splitting the (2D Array) histograms into the pixel values (column 0) and pixel counts (column 1), and norm... | <ASSISTANT_TASK:>
Python Code:
import ee
ee.Authenticate()
ee.Initialize()
def lookup(source_hist, target_hist):
Creates a lookup table to make a source histogram match a target histogram.
Args:
source_hist: The histogram to modify. Expects the Nx2 array format produced by ee.Reducer.autoHistogram.
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csir-csiro', 'sandbox-2', '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: Exception handling with lists
| <ASSISTANT_TASK:>
Python Code:
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,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: We want to use Theano so that we can use it's auto-differentiation, since I'm too lazy to work out the derivatives of these functions by hand!
... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import os
import numpy as np
import pandas as pd
import torch, torch.nn as nn, torch.nn.functional as F
from matplotlib import pyplot as plt
import seaborn as sns
sns.set()
EPSILON = 1.0e-12
SAVE_PLOTS = True
# Softmax function
def f_softmax(logits, axis=1):
ex = ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: noteStore
Step2: my .__MASTER note__ is actually pretty complex....so parsing it and adding to it will take some effort. But let's give it a t... | <ASSISTANT_TASK:>
Python Code:
import settings
from evernote.api.client import EvernoteClient
dev_token = settings.authToken
client = EvernoteClient(token=dev_token, sandbox=False)
userStore = client.get_user_store()
user = userStore.getUser()
print user.username
import EvernoteWebUtil as ewu
ewu.init(settings.authToke... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Import TensorFlow and enable Eager execution
Step2: Load the MNIST dataset
Step3: Use tf.data to create batches and shuffle the dataset
Step4:... | <ASSISTANT_TASK:>
Python Code:
# to generate gifs
!pip install imageio
from __future__ import absolute_import, division, print_function
# Import TensorFlow >= 1.9 and enable eager execution
import tensorflow as tf
tfe = tf.contrib.eager
tf.enable_eager_execution()
import os
import time
import numpy as np
import glob
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:
| <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.DataFrame({'datetime': ['2021-04-10 01:00:00', '2021-04-10 02:00:00', '2021-04-10 03:00:00', '2021-04-10 04:00:00', '2021-04-10 05:00:00'],
'col1': [25, 25, 25, 50, 100],
'col2': [50, 50, 100, 50, 100],
'... |
<SYSTEM_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-se a nossa função
Step2: Método da Bisecção
Step3: Método da Falsa Posição
Step4: Método de Newton-Raphson
Step5: Método da Secante
S... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
%matplotlib inline
f = lambda x: np.sin(x)
df = lambda x: np.cos(x)
my_stop = 1.e-4
my_nitmax = 100000
my_cdif = 1.e-6
def bi(a, b, fun, eps, nitmax):
c = (a + b) / 2
it = 1
while np.abs(fun(c)) > eps and it < nitmax:
if fun(a)*fun(c) < 0: b = 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: This example shows how scan is used
Step3: <a id="generating-inputs-and-targets"></a>
Step13: <a id="defining-the-rnn-model-from-scratch"></a>... | <ASSISTANT_TASK:>
Python Code:
from __future__ import division, print_function
import tensorflow as tf
def fn(previous_output, current_input):
return previous_output + current_input
elems = tf.Variable([1.0, 2.0, 2.0, 2.0])
elems = tf.identity(elems)
initializer = tf.constant(0.0)
out = tf.scan(fn, elems, initializ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Running Example
Step2: When using data sets it's good practice to cite the originators of the data, you can get information about the source of... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import GPy
import pods
from IPython.display import display
data = pods.datasets.olympic_sprints()
X = data['X']
y = data['Y']
print data['info'], data['details']
print data['citation']
print data['output_info']
#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: Introducing Principal Component Analysis
Step2: We can see that there is a definite trend in the data. What PCA seeks to do is to find the Prin... | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
plt.style.use('seaborn')
np.random.seed(1)
X = np.dot(np.random.random(size=(2, 2)), np.random.normal(size=(2, 200))).T
plt.plot(X[:, 0], X[:, 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: Simple producer test
Step2: Simple producer test
Step3: Simple consumer test
| <ASSISTANT_TASK:>
Python Code:
# Run this cell only if you want to add python module to spark context and have run through steps of option b)
sc.addPyFile("/home/ubuntu/kafka-python-1.3.3/dist/kafka_python-1.3.3-py2.7.egg")
kafka_broker='10.0.1.160:9092' # replace argument with your kafka broker ip (if you have multi... |
<SYSTEM_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 our data is in a nice numpy ndarray. We can access it using the numpy methods. For example
Step2: We can also print specific rows of data... | <ASSISTANT_TASK:>
Python Code:
import numpy as np # get numpy package
data = np.genfromtxt(fname='33182_Breakout_Modeling_Data_5mindata.csv', # data filename
dtype=None, # figure out the data type by column
delimiter=',', # delimit on commas
names=True, # first line contain... |
<SYSTEM_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: Array of desired pressure levels
Step3: Interpolate The Data
Step4: Plotting the Data for 700 hPa.
| <ASSISTANT_TASK:>
Python Code:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
from netCDF4 import Dataset, num2date
from metpy.cbook import get_test_data
from metpy.interpolate import log_interpolate_1d
from metpy.plots import add_metpy_logo, add_timestamp
from metpy.units... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
| <ASSISTANT_TASK:>
Python Code::
import nltk
nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
def lemmatize_words(text):
words = text.split()
words = [lemmatizer.lemmatize(word,pos='v') for word in words]
return ' '.join(words)
df['text'] = df['text'].apply(le... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The variable x is a string in Python
Step2: Its translation into ASCII is unusable by parsers
Step3: Encoding as UTF-8 doesn't help much - use... | <ASSISTANT_TASK:>
Python Code:
x = "Rinôçérôse screams flow not unlike an encyclopædia, \
'TECHNICIÄNS ÖF SPÅCE SHIP EÅRTH THIS IS YÖÜR CÄPTÅIN SPEÄKING YÖÜR ØÅPTÅIN IS DEA̋D' to Spın̈al Tap."
type(x)
repr(x)
ascii(x)
x.encode('utf8')
x.encode('ascii','ignore')
import unicodedata
# NFKD a robust way to handle norma... |
<SYSTEM_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: 还有专门针对不规则张量的方法和运算,包括工厂方法、转换方法和值映射运算。有关支持的运算列表,请参阅 tf.ragged 包文档。
Step4: 与普通张量一样,您可以使用 Python 算术和比较运算符来执行逐元素运算。有关更多信息,请... | <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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.