Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
2,000 | <ASSISTANT_TASK:>
Python Code:
def power(x , y , mod ) :
res = 1
while(y ) :
if(y & 1 ) :
res =(res * x ) % mod
x =(x * x ) % mod
y =(y >> 1 )
return(res % mod )
def ncr(n , r , mod ) :
res = 1
for i in range(1 , r + 1 ) :
res =(res *(n - i + 1 ) ) % mod
inv = power(i , mod - 2 , 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:
|
2,001 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.DataFrame({'Sp':['MM2','MM2','MM4','MM4','MM4'],
'Mt':['S4','S4','S2','S2','S2'],
'Value':['bg','dgd','rd','cb','uyi'],
'count':[10,1,2,8,8]})
def g(df):
return df[df.groupby(['Sp', 'Mt'])['count'].tr... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
2,002 | <ASSISTANT_TASK:>
Python Code:
# 将函数作为值返回
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f = lazy_sum(1, 3, 5, 7, 9)
print(f())
# 进制转换函数
print(int(12345))
print(int('1000',base=2))
print(int('1A',base=16))
import functools
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: 闭包
Step2: 虽然默认参数还是很容易使用,但是如果我们在某个场景需要大量调用的话,还是有点不方便,特别是对于有很多参数的函数来说,会让程序显得复杂。还记得之前那个 max min 的程序举例么?我们可以用偏函数来解决整个问题。
Step3: map() 函数
Step4: r... |
2,003 | <ASSISTANT_TASK:>
Python Code:
from os import system
from os.path import join, expandvars
from joblib import Parallel, delayed
from glob import glob
from tax_credit.framework_functions import (recall_novel_taxa_dirs,
parameter_sweep,
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Preparing data set sweep
Step2: Preparing the method/parameter combinations and generating commands
Step3: Now enter the template of the comma... |
2,004 | <ASSISTANT_TASK:>
Python Code:
%%bash
pip install sh --upgrade pip # needed to execute shell scripts later
import os
PROJECT = 'PROJECT' # REPLACE WITH YOUR PROJECT ID
REGION = 'us-central1' # REPLACE WITH YOUR REGION e.g. us-central1
# do not change these
os.environ['PROJECT'] = PROJECT
os.environ['BUCKET'] = 'recser... | <SYSTEM_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 environment variables
Step2: Setup Google App Engine permissions
Step3: Part One
Step4: 2. Create empty BigQuery dataset and load sampl... |
2,005 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
!head -n 30 open_exoplanet_catalogue.txt
data = np.genfromtxt(fname = 'open_exoplanet_catalogue.txt', delimiter = ',')
data[np.isnan(data)] = 0
assert data.shape==(1993,24)
fig = plt.figure(figsize=(7,7))
plt.hist(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: Exoplanet properties
Step2: Use np.genfromtxt with a delimiter of ',' to read the data into a NumPy array called data
Step3: Looked this up on... |
2,006 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.weightstats import *
from statsmodels.stats.proportion import proportion_confint
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.core... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <b>
Step2: Сохраняется ли связь между признаками, если разбить выборку на северные и южные города? Посчитайте значения корреляции Пирсона между... |
2,007 | <ASSISTANT_TASK:>
Python Code:
graph = {'A': {'B': 14, 'C': 9, 'D': 7},
'B': {'A': 14, 'C': 2, 'F': 9},
'C': {'A': 9, 'B': 2, 'D': 7, 'E': 11},
'D': {'A': 7, 'C':10, 'E':15},
'E': {'C': 11, 'D':15, 'F': 6},
'F': {'B': 9, 'E': 6}
}
graph['C']['B']
# equivalently:
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: For example, to get the cost of the edge connecting C and B, we can use the dictionary as follows
|
2,008 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import itertools
from scipy import stats
from statsmodels.stats.descriptivestats import sign_test
from statsmodels.stats.weightstats import zconfint
%pylab inline
mouses_data = pd.read_csv('mirror_mouses.txt', header = None)
mouses_data.columns = ['... | <SYSTEM_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: Критерий знаков
Step4: Критерий знаковых рангов Вилкоксона
Step5: Перестановочный крит... |
2,009 | <ASSISTANT_TASK:>
Python Code:
%reload_ext autoreload
%autoreload 2
%matplotlib inline
from fastai.conv_learner import *
PATH = 'data/planet/'
# Data preparation steps if you are using Crestle:
os.makedirs('data/planet/models', exist_ok=True)
os.makedirs('/cache/planet/tmp', exist_ok=True)
!ln -s /datasets/kaggle/plane... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Multi-label versus single-label classification
Step2: In single-label classification each sample belongs to one class. In the previous example,... |
2,010 | <ASSISTANT_TASK:>
Python Code:
USE_VISUAL=False
#
# Either use this cell, in which case you will be using VPython
# Note: VPython only works if you have it installed on your local
# computer. Also, stopping a VPython simulation appears to restart the kernel. Save first!
#
import numpy as np
if USE_VISUAL:
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: Eigenvectors
Step2: We can also sort out what's happening using the matrix formulation developed in the slides. The eigenvalue problem
Step4: ... |
2,011 | <ASSISTANT_TASK:>
Python Code:
import os
import numpy as np
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_evk_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis-ave.fif')
evokeds_list = mne.read_evokeds(sample_data_evk_file, baselin... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Instead of creating the ~mne.Evoked object from an ~mne.Epochs object,
Step2: To make our life easier, let's convert that list of ~mne.Evoked
S... |
2,012 | <ASSISTANT_TASK:>
Python Code:
import time
from IPython.display import IFrame
SERVER = 'labs.graphistry.com'
current_time = str(int(time.time()))
dataset='Facebook'
# We add the current time to the end of the workbook name to ensure it is unique
workbook = 'popularCommunities' + current_time
current_time = str(int(t... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set the location of the graphistry server
Step2: Let's first take a look at a subgraph of Facebook's social network, and create a new workbook ... |
2,013 | <ASSISTANT_TASK:>
Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset if ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Image Classification
Step2: Explore the Data
Step5: Implement Preprocess Functions
Step8: One-hot encode
Step10: Randomize Data
Step12: Che... |
2,014 | <ASSISTANT_TASK:>
Python Code:
#codes here
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("https://raw.githubusercontent.com/Yorko/mlcourse.ai/master/data/telecom_churn.csv")
df.head()
#codes here
df.dtypes
#codes here
plt.figure(figsize=(10,5))
plt.hist(... | <SYSTEM_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. Check the types of the variable that you take into account along the way.
Step2: 3. Draw the histogram of total day minutes and total intl c... |
2,015 | <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: 下载图像并选择风格图像和内容图像:
Step3: 将输入可视化
Step4: 创建一个简单的函数来显示图像:
Step5: 使用 TF-Hub 进行快速风格迁移
Step6: 定义内容和风格的表示
Step7: 现在,加载没有分类部分的 VGG19... |
2,016 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
my_list = [1,2,3]
my_list
np.array(my_list)
my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
my_matrix
np.array(my_matrix)
np.arange(0,10)
np.arange(0,11,2)
np.zeros(3)
np.zeros((5,5))
np.ones(3)
np.ones((3,3))
np.linspace(0,10,3)
np.linspace(0,5,20)
np.linspace(0,5,21)
np.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: NumPy has many built-in functions and capabilities. We won't cover them all but instead we will focus on some of the most important aspects of N... |
2,017 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cccr-iitm', 'sandbox-2', 'atmoschem')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("nam... | <SYSTEM_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... |
2,018 | <ASSISTANT_TASK:>
Python Code:
%%javascript
IPython.load_extensions('calico-document-tools');
!date
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import pyqtgraph as pg
import numpy as np
help(pg.opengl.GLLinePlotItem)
help(pg.opengl.GLGridItem)
help(pg.QtGui.QGraphicsRectItem)
image_shape = (4... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Objective
Step2: Figure out what makeARGB is doing
Step3: Make a semi-transparent rectangle (image)
Step4: What is np.vstack.transpose() doin... |
2,019 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import pandas as pd
%matplotlib inline
# Read data from data/coffees.csv
data = pd.read_csv("data/coffees.csv")
data
# .head()
data.head()
# .loc or .iloc
data.loc[2]
# [] indexing on a series
data.coffees[:5]
print("Dataset length :")
# len()
print(len(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: Note
Step2: Note
Step3: Note
Step4: Let's just look at the first few rows.
Step5: We have an index, and three columns
Step6: Definitely... |
2,020 | <ASSISTANT_TASK:>
Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(filename):
from urllib.request import urlretrieve
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Click here to run this case study on Colab
Step3: Hand washing
Step4: The following array represents the range of possible spending.
Step6: c... |
2,021 | <ASSISTANT_TASK:>
Python Code:
from ipysankeywidget import SankeyWidget
from ipywidgets import Layout
layout = Layout(width="300", height="200")
def sankey(margin_top=10, **value):
Show SankeyWidget with default values for size and margins
return SankeyWidget(layout=layout,
margins=dict... | <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: <i class="fa fa-gears fa-2x fa-fw text-info"></i> A convenience factory function
Step3: Rank assignment
Step4: Reversed nodes
Step5: Variatio... |
2,022 | <ASSISTANT_TASK:>
Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
view_sentence_range = (0, 10)
DON'T MODIFY AN... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Language Translation
Step3: Explore the Data
Step6: Implement Preprocessing Function
Step8: Preprocess all the data and save it
Step10: Chec... |
2,023 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
from importlib import reload
import numpy as np
import matplotlib.pyplot as plt
from keras import models, layers, optimizers
from keras.layers import Dense, Input, Conv1D, Reshape, Flatten
from keras.models import Model
from keras.opti... | <SYSTEM_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 Model
Step2: Load Data
Step5: Test train
|
2,024 | <ASSISTANT_TASK:>
Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inlin... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Data Exploration
Step2: Implementation
Step3: Question 1
Step4: Question 2
Step5: Question 3
Step6: Observation
Step7: Implementation
Step... |
2,025 | <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: TF Lattice Custom Estimators
Step2: Importing required packages
Step3: Downloading the UCI Statlog (Heart) dataset
Step4: Setting the default... |
2,026 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
DATAFILE = '/home/data/archive.ics.uci.edu/BankMarketing/bank.csv'
###DATAFILE = 'data/bank.csv' ### using locally
df = pd.read_csv(DATAFILE, sep=';')
list(df.columns)
### use sets and '-' difference operation '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: Step 1
Step2: Let's look at the distribution of numerical features...
Step3: Now, let's look at the categorical variables and their distributi... |
2,027 | <ASSISTANT_TASK:>
Python Code:
import datacube
dc = datacube.Datacube(app='load-data-example')
data = dc.load(product='ls5_nbar_albers', x=(149.25, 149.5), y=(-36.25, -36.5),
time=('2008-01-01', '2009-01-01'))
data
data = dc.load(product='ls5_nbar_albers', x=(1543137.5, 1569137.5), y=(-4065537.5, -4096... | <SYSTEM_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
Step2: Load data via a products native co-ordinate system
Step3: Load specific measurements of a given product
Step4: Additional... |
2,028 | <ASSISTANT_TASK:>
Python Code:
# print("Hello World)
# Lots...
# and lots...
# of comments...
print("this works") # this works because the "#" symbol is placed AFTER the bit of code we want to run!
"abc" * 4 # ???
"a" * 3 # string * number repeats the character. Thus "a" * 2 = "aa" and "az" * 2 = "azaz".
print( ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Woah !? Nothing happened!? Why is that?
Step2: You can also place comments after some code, in which case the code executes. Here, let me sho... |
2,029 | <ASSISTANT_TASK:>
Python Code:
f = open("files/simple-file.txt")
for l in f.readlines():
print(l,end="")
f.close()
with open("files/simple-file.txt") as f:
for l in f:
print(l.strip())
with open("files/simple-file.txt.gz") as f:
for l in f:
print(l.strip())
import gzip
with gzip.open("fi... | <SYSTEM_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
Step2: python
Step3: Use the gzip module
|
2,030 | <ASSISTANT_TASK:>
Python Code:
import os, sys
sys.path = [os.path.abspath("../../")] + sys.path
from perception4e import *
from notebook4e import *
import matplotlib.pyplot as plt
plt.imshow(gray_scale_image, cmap='gray', vmin=0, vmax=255)
plt.axis('off')
plt.show()
gray_img = gen_gray_scale_picture(100, 5)
plt.imsho... | <SYSTEM_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 take a look at it
Step2: You can also generate your own grayscale images by calling gen_gray_scale_picture and pass the image size and gr... |
2,031 | <ASSISTANT_TASK:>
Python Code:
# Load libraries
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
import numpy as np
# Load data
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Make class highly imbalanced by removing first 40... | <SYSTEM_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 Dataset
Step2: Make Classes Imbalanced
Step3: Standardize Features
Step4: Train A Logistic Regression With Weighted Classes
|
2,032 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
raw_data = pd.read_csv("heightWeightData.txt", header=None, names=["gender", "height", "weight"])
raw_data.info()
raw_data.head()
male_data = raw_data[raw_data.gender == 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: First, just read in data, and take a peek. The data can be found on GitHub.
Step2: We're told that for gender, 1 is male, and 2 is female. Part... |
2,033 | <ASSISTANT_TASK:>
Python Code:
# Load the libraries
import numpy as np
import pandas as pd
from scipy import stats
from sklearn import linear_model
# Load the data again!
df = pd.read_csv("data/Weed_Price.csv", parse_dates=[-1])
df.sort(columns=['State','date'], inplace=True)
df1 = df[df.State=="California"].copy()
df1... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Correlation
Step2: Exercise Find correlation between percent_white and highQ
Step3: Exercise Find mean prices of HighQ weed for states that ar... |
2,034 | <ASSISTANT_TASK:>
Python Code:
def maxSetBitCount(s , k ) :
maxCount = 0
n = len(s )
count = 0
for i in range(k ) :
if(s[i ] == '1' ) :
count += 1
maxCount = count
for i in range(k , n ) :
if(s[i - k ] == '1' ) :
count -= 1
if(s[i ] == '1' ) :
count += 1
maxCount = max(maxCount ,... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
2,035 | <ASSISTANT_TASK:>
Python Code:
# Run cell with Ctrl + Enter
# Import main pycoQC module
from pycoQC.Barcode_split import Barcode_split
# Import helper functions from pycoQC
from pycoQC.common import jhelp, head, ls
jhelp(Barcode_split)
Barcode_split (
summary_file="./data/Guppy-2.2.4-basecall-1D-DNA_sequencing_su... | <SYSTEM_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 Barcode_split
Step2: Basic usage
Step3: With externaly provided barcodes
Step4: If no barcode an error is raised
|
2,036 | <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... |
2,037 | <ASSISTANT_TASK:>
Python Code:
!pip install -I "phoebe>=2.0,<2.1"
%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.set_value('sma@binary', 20)
b.set_value('q', 0.8)
b.set_value('ecc', 0.8)
b.set_valu... | <SYSTEM_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: And let's make our system... |
2,038 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn.datasets as data
%matplotlib inline
sns.set_context('poster')
sns.set_style('white')
sns.set_color_codes()
plot_kwds = {'alpha' : 0.5, 's' : 80, 'linewidths':0}
moons, _ = data.make_moons(n_samples=50... | <SYSTEM_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 next thing we'll need is some data. To make for an illustrative example we'll need the data size to be fairly small so we can see what is go... |
2,039 | <ASSISTANT_TASK:>
Python Code:
A = np.array([[1, 3, -2], [3, 5, 6], [2, 4, 3]])
A
b = np.array([[5], [7], [8]])
b
Ainv = np.linalg.inv(A)
Ainv
x = np.dot(Ainv, b) # 앞에
x
np.dot(A, x) - b #수치적인 에러떄문에 0이 나오지않는다. inverse 명령은 실생활에서 사용하지않는다. 역행렬이 뭔지 알고싶을때만 쓴다.
x, resid, rank, s = np.linalg.lstsq(A, b) # 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: 위 해결 방법에는 두 가지 의문이 존재한다. 우선 역행렬이 존재하는지 어떻게 알 수 있는가? 또 두 번째 만약 미지수의 수와 방정식의 수가 다르다면 어떻게 되는가?
Step2: 행렬식과 역행렬 사이에는 다음의 관계가 있다.
|
2,040 | <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: Scikit-Learn Model Card Toolkit Demo
Step2: Did you restart the runtime?
Step3: Load data
Step4: Plot data
Step5: Train model
Step6: Evalua... |
2,041 | <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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Environment Preparation
Step2: Install Analytics Zoo
Step3: You can install the latest pre-release version using pip install --pre --upgrade a... |
2,042 | <ASSISTANT_TASK:>
Python Code:
with open('example_run.csv') as f: s = f.read()
N = 10
runs = [[1/N for _ in range(N)]]
for line in s.split('\n'):
line = line.strip('[]')
if len(line) > 0:
li = [float(i) for i in line.split(',')]
runs.append(li)
for i, r in enumerate(runs):
plt.bar(list(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: In the next plots you will see that at the beginning the likelihood for the fault location is evenly distributed. There was no observation made.... |
2,043 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import load_iris
iris = load_iris()
test_idx = [0, 50, 100]
train_y = np.delete(iris.target, test_idx)
train_X = np.delete(iris.data, test_idx, axis=0)
test_y = iris.target[test_idx]
test_X = iri... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Choosing a dataset
Step2: Splitting the dataset
Step3: Decision Tree Classifier
Step4: Visualize the decision tree
Step5: Evaluating the mod... |
2,044 | <ASSISTANT_TASK:>
Python Code:
1 % 2
# code goes here
# code for 1
import numpy as np
random_number = np.random.randint(35, 76, 1)
# put your code below here
# code for 2
import numpy as np
data = np.random.randint(0, 10, 100) # generate 100 integers between 0 & 10 (both included)
# put your code below here
# Belo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercises
Step2: Boolean expressions
Step3: For loop example
Step4: Exercises
|
2,045 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
# Import libraries
from __future__ import absolute_import, division, print_function
# Ignore warnings
import warnings
warnings.filterwarnings('ignore')
import sys
sys.path.append('tools/')
import numpy as np
import pandas as pd
import math
# Graphing Libraries
import 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:
Step3: Uniform Sample
Step4: Dice
Step5: Coin
Step7: We can simulate the act of rolling dice by just pulling out rows
Step9: Modeling the Law of Av... |
2,046 | <ASSISTANT_TASK:>
Python Code:
%%bash
cat /root/src/main/python/debug/debug_model_cpu.py
%%bash
cat /root/src/main/python/debug/debug_model_gpu.py
<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: Run the following in the Terminal (CPU)
|
2,047 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
pd.set_option('max_rows', 5)
from learntools.core import binder; binder.bind(globals())
from learntools.pandas.creating_reading_and_writing import *
print("Setup complete.")
# Your code goes here. Create a dataframe matching the above diagram and assign it to the vari... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercises
Step2: 2.
Step3: 3.
Step5: 4.
Step6: 5.
Step7: In the cell below, write code to save this DataFrame to disk as a csv file with th... |
2,048 | <ASSISTANT_TASK:>
Python Code:
#|all_slow
#|all_multicuda
from fastai.vision.all import *
from fastai.text.all import *
from fastai.tabular.all import *
from fastai.collab import *
from accelerate import notebook_launcher
from fastai.distributed import *
# from accelerate.utils import write_basic_config
# write_basic_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Important
Step2: Image Classification
Step3: Image Segmentation
Step4: Text Classification
Step5: Tabular
Step6: Collab Filtering
Step7: K... |
2,049 | <ASSISTANT_TASK:>
Python Code:
import sys, os
from numpy import *
from matplotlib.pyplot import *
%matplotlib inline
matplotlib.rcParams['savefig.dpi'] = 100
%load_ext autoreload
%autoreload 2
from rnnlm import RNNLM
# Gradient check on toy data, for speed
random.seed(10)
wv_dummy = random.randn(10,50)
model = RNNLM(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: (e)
Step2: Prepare Vocabulary and Load PTB Data
Step3: Load the datasets, using the vocabulary in word_to_num. Our starter code handles this f... |
2,050 | <ASSISTANT_TASK:>
Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
# Chris Holdgraf <choldgraf@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
import mne
from mne.viz import plot_alignment, snapshot_brain_montage
print(__doc__)... | <SYSTEM_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 load some ECoG electrode locations and names, and turn them into
Step2: Now that we have our electrode positions in MRI coordinates, we c... |
2,051 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from qutip import *
N = 15
w0 = 1.0 * 2 * np.pi
A = 0.1 * 2 * np.pi
times = np.linspace(0, 15, 301)
gamma = 0.25
ntraj = 150
nsubsteps = 50
a = destroy(N)
x = a + a.dag()
y = -1.0j*(a - a.dag())
H = ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Introduction
Step2: Heterodyne implementation #1
Step3: $D_{2}^{(1)}[A]\rho = \frac{1}{\sqrt{2}} \sqrt{\gamma} \mathcal{H}[a] \rho =
Step4: T... |
2,052 | <ASSISTANT_TASK:>
Python Code:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
%matplotlib inline
import qp
import numpy as np
import scipy.stats as sps
P = qp.PDF(funcform=sps.norm(loc=0.0, scale=1.0))
x, sigma = 2.0, 1.0
Q = qp.PDF(funcform=sps.norm(loc=x, scale=sigma))
infinity = 100.0
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: i.e. Two equal-width Gaussians overlapping at their 1-sigma points have a KLD of 2 nats.
Step2: i.e. Two concentric 1D Gaussian PDFs differing... |
2,053 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
n = 100
prob =... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <b>
Step2: <b>
Step3: <b>
|
2,054 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-3', 'ocean')
# 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... |
2,055 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.interpolate import interp1d
# YOUR CODE HERE
raise NotImplementedError()
assert isinstance(x, np.ndarray) and len(x)==40
assert isinstance(y, np.ndarray) and len(y)==40
assert isinstanc... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2D trajectory interpolation
Step2: Use these arrays to create interpolated functions $x(t)$ and $y(t)$. Then use those functions to create the ... |
2,056 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
# Import neurom module
import neurom as nm
# Import neurom visualization module
from neurom import viewer
# Load a single morphology
neuron = nm.load_neuron('../test_data/valid_set/Neuron.swc')
# Load a population of morphologies from a set of files
pop = nm.load_neu... | <SYSTEM_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. Loading a morphology or a population
Step2: 2. Morphology visualization
Step3: 3. Morphology analysis
Step4: 3.2 Analyze different types o... |
2,057 | <ASSISTANT_TASK:>
Python Code:
# Setup plotting
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
# Set Matplotlib defaults
plt.rc('figure', autolayout=True)
plt.rc('axes', labelweight='bold', labelsize='large',
titleweight='bold', titlesize=18, titlepad=10)
plt.rc('animation', html='html5')
# S... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First, load the Hotel Cancellations dataset.
Step2: 1) Define Model
Step3: 2) Add Optimizer, Loss, and Metric
Step4: Finally, run this cell t... |
2,058 | <ASSISTANT_TASK:>
Python Code:
import pymatgen.core as mg
si = mg.Element("Si")
print("Atomic mass of Si is {}".format(si.atomic_mass))
print("Si has a melting point of {}".format(si.melting_point))
print("Ionic radii for Si: {}".format(si.ionic_radii))
print("Atomic mass of Si in kg: {}".format(si.atomic_mass.to("kg... | <SYSTEM_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 Element, Specie and Composition objects
Step2: You can see that units are printed for atomic masses and ionic radii. Pymatgen comes with ... |
2,059 | <ASSISTANT_TASK:>
Python Code:
from google.cloud import aiplatform
REGION = "us-central1"
PROJECT_ID = !(gcloud config get-value project)
PROJECT_ID = PROJECT_ID[0]
# Set `PATH` to include the directory containing KFP CLI
PATH = %env PATH
%env PATH=/home/jupyter/.local/bin:{PATH}
!cat trainer_image_vertex/Dockerfile
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Understanding the pipeline design
Step2: Let's now build and push this trainer container to the container registry
Step3: To match the ml fram... |
2,060 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division, print_function
import pylab as plt
import matplotlib.pyplot as mpl
from pymatgen.core import Element, Composition
%matplotlib inline
import csv
with open("ICSD/icsd-ternaries.csv", "r") as f:
csv_reader = csv.reader(f, dialect = csv.excel_tab)
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: We import all the data and check the unique compositions by string matching of the pymatgen formulas. We then make a list out of all the unique ... |
2,061 | <ASSISTANT_TASK:>
Python Code:
def checkPalindrome(str ) :
n = len(str )
count = 0
for i in range(0 , int(n / 2 ) ) :
if(str[i ] != str[n - i - 1 ] ) :
count = count + 1
if(count <= 1 ) :
return True
else :
return False
str = "abccaa "
if(checkPalindrome(str ) ) :
print("Yes ")
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
2,062 | <ASSISTANT_TASK:>
Python Code:
from gensim.corpora.wikicorpus import WikiCorpus
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from pprint import pprint
import multiprocessing
wiki = WikiCorpus("enwiki-latest-pages-articles.xml.bz2")
#wiki = WikiCorpus("enwiki-YYYYMMDD-pages-articles.xml.bz2")
class Tagged... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Preparing the corpus
Step2: Define TaggedWikiDocument class to convert WikiCorpus into suitable form for Doc2Vec.
Step3: Preprocessing
Step4: ... |
2,063 | <ASSISTANT_TASK:>
Python Code:
# Imports
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import glob
import csv
import calendar
import webbrowser
from datetime import datetime
# Constants
DATA_FOLDER = 'Data/'
'''
Functions needed to solve task 1
'''
#function to import excel ... | <SYSTEM_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 1. Compiling Ebola Data
Step2: Task 2. RNA Sequences
Step3: Creating and filling the DataFrame
Step4: 3. Cleaning and reindexing
Step5: ... |
2,064 | <ASSISTANT_TASK:>
Python Code:
def least_squares(y, tx):
calculate the least squares solution.
a = tx.T.dot(tx)
b = tx.T.dot(y)
return np.linalg.solve(a, b)
from helpers import *
def test_your_least_squares():
height, weight, gender = load_data_from_ex02(sub_sample=False, add_outlier=False)
x, ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1 Least squares and linear basis functions models
Step2: Load the data
Step3: Test it here
Step5: 1.2 Least squares with a linear basis funct... |
2,065 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn')
# Import the example plot from the figures directory
from fig_code import plot_sgd_separator
plot_sgd_separator()
from fig_code import plot_linear_regression
plot_linear_regression()
from IPython.core.display im... | <SYSTEM_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 may seem like a trivial task, but it is a simple version of a very important concept.
Step2: Again, this is an example of fitting a model ... |
2,066 | <ASSISTANT_TASK:>
Python Code:
import datetime
import Image
import gc
import numpy as np
import os
import random
from scipy import misc
import string
import time
# Set some Theano config before initializing
os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=cpu,floatX=float32,allow_gc=False,openmp=True"
import theano
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: Load Training and Test Data
Step2: Transformations
Step4: Split Training/Test Sets
Step5: Define the Model
Step6: Our model is a convolution... |
2,067 | <ASSISTANT_TASK:>
Python Code:
print("Hello World")
# sample function
def add(op1, op2):
return op1 + op2
# Integers
var1 = 10
var2 = 20
var3 = add(var1, var2)
print(var3)
# Floats
var1, var2 = 1.5, 2.6 # multiple assignment
print(add(var1, var2))
# Strings
var1 = "ABCD"
var2 = "EFGH"
var3 = add(var1, var2)
print(... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Two major version branches
Step2: Mis-Conceptions
Step3: Automatic Memory Management
Step4: General Purpose
|
2,068 | <ASSISTANT_TASK:>
Python Code:
import time
import numpy as np
import Online_temporal_clustering_JSI_release as OTC
import Utilities_JSI_release as Util
from sklearn.preprocessing import scale
###########################################
# parameters
np.random.seed(2)
tolerance = 22
activePool = 3
minDur = 16
OTC.deltaT ... | <SYSTEM_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: Clustering
Step3: Validation and Visualization
|
2,069 | <ASSISTANT_TASK:>
Python Code:
import locale
import glob
import os.path
import requests
import tarfile
import sys
import codecs
import smart_open
dirname = 'aclImdb'
filename = 'aclImdb_v1.tar.gz'
locale.setlocale(locale.LC_ALL, 'C')
if sys.version > '3':
control_chars = [chr(0x85)]
else:
control_chars = [unich... | <SYSTEM_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 text data is small enough to be read into memory.
Step2: Set-up Doc2Vec Training & Evaluation Models
Step3: Le and Mikolov notes that comb... |
2,070 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import sys
from sklearn import linear_model
import matplotlib.pyplot as plt
%matplotlib inline
dtype_dict = {'bathrooms':float, 'waterfront':int, 'sqft_above':int, 'sqft_living15':float, 'grade':int, 'yr_renovated':int, 'price':float, 'bedrooms':flo... | <SYSTEM_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... |
2,071 | <ASSISTANT_TASK:>
Python Code:
# Train log-transform model
training_samples = []
logz = np.log(0.001 + z)
vw = pyvw.vw("-b 2 --loss_function squared -l 0.1 --holdout_off -f vw.log.model --readable_model vw.readable.log.model")
for i in range(len(logz)):
training_samples.append("{label} | x:{x} y:{y}".format(label=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: Although the model is relatively unbiased in the log-domain where we trained our model, in the original domain there is underprediction as we ex... |
2,072 | <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.
# YOUR... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exploring the Fermi distribution
Step3: In this equation
Step4: Write a function plot_fermidist(mu, kT) that plots the Fermi distribution $F(\... |
2,073 | <ASSISTANT_TASK:>
Python Code:
import collections
import glob
import os
from os import path
import matplotlib_venn
import pandas as pd
rome_path = path.join(os.getenv('DATA_FOLDER'), 'rome/csv')
OLD_VERSION = '343'
NEW_VERSION = '344'
old_version_files = frozenset(glob.glob(rome_path + '/*{}*'.format(OLD_VERSION)))
new... | <SYSTEM_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 let's check if there are new or deleted files (only matching by file names).
Step2: Cool, no new nor deleted files.
Step3: Let's make su... |
2,074 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
#read csv as data frame
df_gdp_raw = pd.read_csv("../data/countries_GDP.csv")
#select columns and use these that have data in 'Unamed:0', which
#actually is the country code
df_gdp = df_gdp_raw[[0,1,3,4]][df_gdp_raw['Unnamed: 0'].notnull()]
#rename 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: Exercice
Step2: Exercice
Step3: Exercice
Step4: Exercice
Step5: Exercice
Step6: Exercice
Step7: Exercice
Step8: Exercice
|
2,075 | <ASSISTANT_TASK:>
Python Code:
from pygchem import datasets
bmk_root = '/home/bovy/geoschem'
%cd {bmk_root}/1yr_benchmarks/v10-01/v10-01c/Run1
filename = 'bpch/ctm.bpch.v10-01c-geosfp-Run1.20120801'
dataset = datasets.load(filename)
print dataset[-20:]
filename = 'netcdf/v10-01c-geosfp-Run1.20120801.nc'
clb = 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: NOTE
Step2: Loading datasets
Step3: Simple (unconstrained) loading
Step4: The line below print the list of the 20 lasts data fields of the li... |
2,076 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
data_dir = "/Users/seddont/Dropbox/Tom/MIDS/W209_work/Tom_project/"
# Get sample of the full database to understand what columns we want
smp = pd.read_csv(data_dir+"en.openfoodfacts.org.products.csv", sep = "\t", nrows = 100)
for c in smp.columns:
print(c)
# 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: Working from the full database, because the usda_imports_filtered.csv file in the shared drive does not have brand information, which will be us... |
2,077 | <ASSISTANT_TASK:>
Python Code:
# <help>
# <api>
from collections import defaultdict
import datetime
import pandas as pd
import numpy as np
def load_data(clean=True, us=True):
df = pd.read_sql_table('frontpage_texts', 'postgres:///frontpages')
df_newspapers = pd.read_sql_table('newspapers', 'postgres:///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: Fonts
Step2: Denver Post
Step3: Unigram "percent of page" analysis
Step4: Now we run this method across all the newspapers, across all days!
... |
2,078 | <ASSISTANT_TASK:>
Python Code:
# Required to see plots when running on mybinder
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Python standard-libraries to download data from the web
from urllib.parse import urlencode
from urllib.request import urlretri... | <SYSTEM_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 first thing is getting the coordinates for an object of interest, in this case NCG5406
Step2: We can now get a picture from the SDSS DR12 i... |
2,079 | <ASSISTANT_TASK:>
Python Code:
import os
import pytesmo.validation_framework.temporal_matchers as temporal_matchers
import pytesmo.validation_framework.metric_calculators as metrics_calculators
from datetime import datetime
from pytesmo.io.sat.ascat import AscatH25_SSM
from pytesmo.io.ismn.interface import ISMN_Interfa... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Initialize ASCAT reader
Step2: Initialize ISMN reader
Step3: Create the variable jobs which is a list containing either cell numbers (for a ce... |
2,080 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import json
loans = pd.read_csv('lending-club-data.csv')
loans.head(2)
loans['safe_loans'] = loans['bad_loans'].apply(lambda x : +1 if x==0 else -1)
loans = loans.drop('bad_loans', axis=1)
features = ['grade', # grade of the loan
... | <SYSTEM_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: As before, we reassign the labels to have +1 for a safe loan, and -1 for a risky (bad) loan.
Step3: We will be... |
2,081 | <ASSISTANT_TASK:>
Python Code:
# Import modules
import sys
import math
import numpy as np
from matplotlib import pyplot as plt
from scipy import linalg
from scipy import sparse
A = np.array([1, -4, 2, 3, 2, 2]).reshape(3, 2)
b = np.array([-3, 15, 9])
x = linalg.lstsq(A, b)
print(x[0])
A = np.array([1, 1, 1, -1, 1, 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: 4.1 Least Squares and the normal equations
Step2: Example
Step3: The best line is $y = \frac{7}{4} + \frac{3}{4}t$
Step4: Example
Step5: Ex... |
2,082 | <ASSISTANT_TASK:>
Python Code:
# set_datalab_project_id('my-project-id')
from google.datalab.stackdriver import monitoring as gcm
groups_dataframe = gcm.Groups().as_dataframe()
# Sort the dataframe by the group name, and reset the index.
groups_dataframe = groups_dataframe.sort_values(by='Group name').reset_index(drop... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: List the Stackdriver groups
Step2: Extract the first group
Step3: Load the CPU metric data for the instances a given group
Step4: Plot the th... |
2,083 | <ASSISTANT_TASK:>
Python Code:
import requests
import json
r = requests.get('http://3d-kenya.chordsrt.com/instruments/2.geojson?start=2017-03-01T00:00&end=2017-05-01T00:00')
if r.status_code == 200:
d = r.json()['Data']
else:
print("Please verify that the URL for the weather station is correct. You may just hav... | <SYSTEM_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 the collected data can be viewed simply by issuing the following command
Step2: This code is useful for looking at a specific measurement d... |
2,084 | <ASSISTANT_TASK:>
Python Code:
import cobra.test
from cobra.flux_analysis import gapfill
model = cobra.test.create_test_model("salmonella")
universal = cobra.Model("universal_reactions")
for i in [i.id for i in model.metabolites.f6p_c.reactions]:
reaction = model.reactions.get_by_id(i)
universal.add_reaction(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: In this model D-Fructose-6-phosphate is an essential metabolite. We will remove all the reactions using it, and at them to a separate model.
Ste... |
2,085 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import tensorflow as tf
from tensorflow import feature_column
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split
print("TensorFlow version:... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Lab Task 1
Step2: Split the dataframe into train, validation, and test
Step3: Lab Task 2
Step4: Understand the input pipeline
Step5: Lab Tas... |
2,086 | <ASSISTANT_TASK:>
Python Code:
!pip install -I "phoebe>=2.1,<2.2"
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger()
b = phoebe.default_binary()
times = np.linspace(0,1,51)
b.add_dataset('lc', times=times, dataset='lc01')
b.add_dataset('orb', times=ti... | <SYSTEM_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: Default Animations
Step3:... |
2,087 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from nsaba.nsaba import Nsaba
from nsaba.nsaba.visualizer import NsabaVisualizer
import numpy as np
import os
import matplotlib.pyplot as plt
import pandas as pd
import itertools
%load_ext line_profiler
# Simon Path IO
data_dir = '../../data_dir'
os.chdir(data_dir)
Nsab... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Coordinates to gene expression
Step2: Visualization Methods (testing)
|
2,088 | <ASSISTANT_TASK:>
Python Code:
import time
import numpy as np
import tensorflow as tf
import utils
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import zipfile
dataset_folder_path = 'data'
dataset_filename = 'text8.zip'
dataset_name = 'Text8 Dataset'
class DLProgress(tq... | <SYSTEM_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 text8 dataset, a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the data folder. ... |
2,089 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import load_files
corpus = load_files("../data/")
doc_count = len(corpus.data)
print("Doc count:", doc_count)
assert doc_count is 56, "Wrong number of documents loaded, should ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Input
Step2: Vectorizer
Step3: Decided for BOW vectors, containing lemmatized words. BOW results (in this case) in better cluster performance ... |
2,090 | <ASSISTANT_TASK:>
Python Code:
descripciones = {
'P0306' : 'Programas de modernización catastral',
'P0307' : 'Disposiciones normativas sustantivas en materia de desarrollo urbano u ordenamiento territorial',
'P1001' : 'Promedio diario de RSU recolectados',
'P1003' : 'Número de municipios con disponibilidad de servicios... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: En el caso del parámetro P1003, los datos se extraen desde 3 archivos. Estos archivos son una base de datos para cada servicio relacionado con l... |
2,091 | <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... |
2,092 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import os
import sys
import random
import networkx as nx
## Paths from the file
PROJECT = os.path.join(os.getcwd(), "..")
FIXTURES = os.path.join(PROJECT, "fixtures")
DATASET = os.path.join(FIXTURES, 'activity.csv')
## Append the path for the logbook utilities
sys... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Graph Structured Pairwise Comparisons
Step2: Edge structured comparisons only yield nodes so long as the itersection of the node's neighborhood... |
2,093 | <ASSISTANT_TASK:>
Python Code:
G = nx.Graph()
G.add_nodes_from(['a', 'b', 'c'])
G.add_edges_from([('a','b'), ('b', 'c')])
nx.draw(G, with_labels=True)
G.add_node('d')
G.add_edge('c', 'd')
G.add_edge('d', 'a')
nx.draw(G, with_labels=True)
# Load the network.
G = nx.read_gpickle('Synthetic Social Network.pkl')
nx.draw(... | <SYSTEM_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 think of another problem
Step2: The set of relationships involving A, B and C, if closed, involves a triangle in the graph. The set of re... |
2,094 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
def ellipse(s, r, c, theta=0):
rows, cols = s[0], s[1]
rr0, cc0 = c[0], c[1]
rr, cc = np.meshgrid(range(rows), range(cols), indexing='ij')
rr = rr - rr0
cc = cc - cc0
cos = np.cos(theta)
sen = np.sin(theta)
i = cos/r[1]
j = sen/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: Examples
Step2: Measuring time
|
2,095 | <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: NumPy
Step2: Requests
Step3: Pandas (optional)
Step4: SciPy (optional)
Step5: 2) Importar scidbpy
Step6: conectarse al servidor de Base de ... |
2,096 | <ASSISTANT_TASK:>
Python Code:
import ipywidgets as widgets
import os
image_path = os.path.abspath('../data_files/trees.jpg')
with open(image_path, 'rb') as f:
raw_image = f.read()
ipyimage = widgets.Image(value=raw_image, format='jpg')
ipyimage
from bqplot import *
# Create the scales for the image coordinates
sc... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Displaying the image inside a bqplot Figure
Step2: Mixing with other marks
Step3: Its traits (attributes) will also respond dynamically to a c... |
2,097 | <ASSISTANT_TASK:>
Python Code:
!brew ls --versions gcc
!compgen -c | grep ^gcc
import os
os.environ['CC'] = 'gcc-6'
%%cython -f
# distutils: extra_compile_args = -fopenmp
# distutils: extra_link_args = -fopenmp
# cython: boundscheck = False
from libc.math cimport log
from cython.parallel cimport prange
def f1(double... | <SYSTEM_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 gcc command maps back to clang. The "real" GCC is different
Step2: My "real" GCC command is gcc-5
Step3: <div style="margin-top
Step4: Ma... |
2,098 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'uhh', 'sandbox-2', 'ocnbgchem')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "e... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
2,099 | <ASSISTANT_TASK:>
Python Code:
# make some Python3 functions available on Python2
from __future__ import division, print_function
import sys
print(sys.version_info)
import theano
print(theano.__version__)
import keras
print(keras.__version__)
# FloydHub: check data
%ls /input/dogscats/
# check current directory
%pwd
%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: Finetuning and Training
Step2: Use a pretrained VGG model with our Vgg16 class
Step4: The original pre-trained Vgg16 class classifies images i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.