Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
2,300 | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
import time
from sklearn.datasets import make_classification
from sklearn.neighbors import KNeighborsClassifier
def what_to_measure(n, n_features, n_classes=3, n_clusters_per_class=2, n_informative=8,
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Q1
Step2: dimension
Step3: observations
Step4: Q2
Step5: Seul l'algorithme brute accepte les features sparses.
Step6: La dimension augmen... |
2,301 | <ASSISTANT_TASK:>
Python Code:
import pymks
%matplotlib inline
%load_ext autoreload
%autoreload 2
import numpy as np
import matplotlib.pyplot as plt
from pymks_share import DataManager
manager = DataManager('pymks.me.gatech.edu')
X, y = manager.fetch_data('random hexagonal orientations')
print(X.shape)
print(y.shape)... | <SYSTEM_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 start off we need to obtain data from somewhere. In order to make things easy the pymks_share package is used to import data.
Step2: The X v... |
2,302 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import random
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt, pi, erf
import scipy.stats
# Make some data -> this is problem setup
# Do NOT copy this because it only generates random data
# This does not perform regression
x = np.linspace(0,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:
Step1: Least Squares Linear Regression
Step2: Notice that we didn't get exactly the correct answer. The points were generated with a slope of 2.5 and ... |
2,303 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import scipy.linalg as la
import matplotlib.pyplot as plt
import csv
# read the data from the csv file
data = np.genfromtxt('m80.csv', delimiter='')
data_mean = np.mean(data,0)
# and plot out a few profiles and the mean depth.
plt.figure()
rows = [ ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Principal Component/EOF analysis
Step2: EOF analysis
Step3: Applying the SVD
Step4: And begin by looking at the spectrum of singular values $... |
2,304 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
from urllib import request
FREMONT_URL = 'https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD'
request.urlretrieve(FREMONT_URL, 'Fremont.csv')
# magic function to show the content of the file
%more Fremont.csv
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: Downloading Data
Step2: Principal Component Analysis
Step3: Comparing with Day of Week
|
2,305 | <ASSISTANT_TASK:>
Python Code:
# all import here
from __future__ import print_function
import os
import pandas as ps # using panda to convert jsonstat dataset to pandas dataframe
import jsonstat # import jsonstat.py package
import matplotlib as plt # for plotting
%matplotlib inline
url = 'http://json-stat.org/sa... | <SYSTEM_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 or use cached file oecd-canada-col.json. Caching file on disk permits to work off-line and to speed up the exploration of the data.
Ste... |
2,306 | <ASSISTANT_TASK:>
Python Code:
# Create a dataframe from the json file in the filepath
raw = pd.io.json.read_json('LocationHistory.json')
df = raw['locations'].apply(pd.Series)
# Create a list from the latitude column, multiplied by -E7
df['latitude'] = df['latitudeE7'] * 1e-7
# Create a list from the longitude colu... | <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: This gives us a pandas dataframe with columns of the latitude and longitude for each recorded point in my location history. There are several ot... |
2,307 | <ASSISTANT_TASK:>
Python Code:
import graphlab
loans = graphlab.SFrame('lending-club-data.gl/')
loans['safe_loans'] = loans['bad_loans'].apply(lambda x : +1 if x==0 else -1)
loans = loans.remove_column('bad_loans')
features = ['grade', # grade of the loan
'term', # the term of ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load the lending club dataset
Step2: Like the previous assignment, we reassign the labels to have +1 for a safe loan, and -1 for a risky (bad) ... |
2,308 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
# All the imports
from __future__ import print_function, division
import pom3_ga, sys
import pickle
# TODO 1: Enter your unity ID here
__author__ = "latimko"
def normalize(problem, points):
Normalize all the objectives
in each point and return them
meta = ... | <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: To compute most measures, data(i.e objectives) is normalized. Normalization is scaling the data between 0 and 1. Why do we normalize?
Step11: D... |
2,309 | <ASSISTANT_TASK:>
Python Code:
from scipy import interpolate
import numpy as np
x = np.array([[0.12, 0.11, 0.1, 0.09, 0.08],
[0.13, 0.12, 0.11, 0.1, 0.09],
[0.15, 0.14, 0.12, 0.11, 0.1],
[0.17, 0.15, 0.14, 0.12, 0.11],
[0.19, 0.17, 0.16, 0.14, 0.12],
... | <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,310 | <ASSISTANT_TASK:>
Python Code:
# For our first piece of code, we need to import the package
# that connects to Reddit. Praw is a thin wrapper around reddit's
# web APIs and works well
import praw
# Now we specify a "unique" user agent for our code
# This is primarily for identification, I think, and some
# user-agen... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Creating a Reddit Application
Step2: Capturing Reddit Posts
Step3: Leveraging Reddit's Voting
Step4: Following Multiple Subreddits
Step5: Ac... |
2,311 | <ASSISTANT_TASK:>
Python Code:
!pip3 install ocaml
import ocaml
answer_to_life = %ocaml 40 + 2
print(answer_to_life)
print(type(answer_to_life)) # a real integer!
%load_ext watermark
%watermark -v -p ocaml
%%ocaml
print_endline "Hello world from OCaml running in Jupyter (from IPython)!";;
%%bash
echo "Hello world ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Then you can use basic OCaml expressions and standard library... from IPython or Jupyter notebook with IPython kernel, without having to install... |
2,312 | <ASSISTANT_TASK:>
Python Code:
# Copyright 2022 Google LLC
#
# 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 applicabl... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <table align="left">
Step2: Install the latest version of the Vertex AI client library.
Step3: Run the following command in your notebook envi... |
2,313 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
from ipywidgets import * # az interaktivitásért felelős csomag
t=linspace(0,2*pi,100);
plot(t,sin(t))
def freki(omega):
plot(t,sin(omega*t))
freki(2.0)
interact(freki,omega=(0,10,0.1));
def func(x):
print(x)
interact(func,x=(0,10));
interact(func,x=False... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Mostanra már tudjuk, hogy hogyan ábrázoljunk egy matematikai függvényt
Step2: Írjunk egy függvényt, ami egy megadott frekvenciájú jelet rajzol ... |
2,314 | <ASSISTANT_TASK:>
Python Code:
# Estimated coefficients for the linear regression problem.
# If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features),
# while if only one target is passed, this is a 1D array of length n_features.
regressor.coef_
regressor.intercept_ #... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Outro estudo
Step2: And finally, let’s plot our data points on a 2-D graph to eyeball our dataset and see if we can manually find any relations... |
2,315 | <ASSISTANT_TASK:>
Python Code:
print('Hello World!')
%matplotlib inline
Origin: Plotting a utilty function.
Filename: example_utility.py
Author: Tyler Abbot
Last modified: 8 September, 2015
import numpy as np
import matplotlib.pyplot as plt
# Define the input variable
c = np.linspace(0.01, 10.0, 100.0)
# Calculate ut... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: That's it! It is that easy. In fact, you can save this single line of code in a file ending in .py and then run it and you would get the same ... |
2,316 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
from astroquery.gaia import Gaia
from astropy import table
from astropy.table import Table
from astropy.wcs import WCS
from astropy.io import fits
from astropy.nddata import NDData
from photutils.psf imp... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First, we turn to GAIA. While the current DR2 does not explicitly mark catalog entries as multiple systems or extended sources, we can just look... |
2,317 | <ASSISTANT_TASK:>
Python Code:
!pip install git+https://github.com/google-research/sofima
import functools as ft
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import PIL
%mkdir tiles
!gsutil -m rsync -r gs://sofima-sample-data/fmi-friedrich-dp tiles
# Define the tile space. This... | <SYSTEM_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 preparation
Step2: Coarse tile position optimization
Step3: Next, we use the information from the previous step to set up and solve a sim... |
2,318 | <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: RandomPyEnvironment を作成し、構造化した観測を生成して実装を検証しましょう。
Step4: 観測をディクショナリとして定義しましたので、観測を処理する前処理レイヤーを作成する必要があります。
Step... |
2,319 | <ASSISTANT_TASK:>
Python Code:
# Function to sum up numbers in a dictionary
# def download file
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data'
filename = 'breast-cancer-wisconsin.csv'
# execute download file
# pandas, read
# \ allows multi lin... | <SYSTEM_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 Science Tutorial
Step2: Now we'll specify the url of the file and the file name we will save to
Step3: And make a call to <code>download_... |
2,320 | <ASSISTANT_TASK:>
Python Code:
# Share functions used in multiple notebooks
%run Shared-Functions.ipynb
# Import our usual libraries
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
%matplotlib inline
import os
# OS-independent way to navigate the file system
# Data directory is one 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: The Business Problem
Step2: We have information about 47 homes in this dataset. Each house is described by two characteristics or "features". T... |
2,321 | <ASSISTANT_TASK:>
Python Code:
# Set-up default environment
%run '../ipython_startup.py'
# Import additional libraries
import sas7bdat as sas
import cPickle as pickle
import statsmodels.formula.api as smf
from ase_cisEq import marenEq
from ase_cisEq import marenPrintTable
from ase_normalization import meanCenter
from 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: Import clean data set
Step2: Additional cleaning
Step3: Raw Counts
Step4: Plot Distribution of cis- and trans-effects
Step8: Plot cis- and t... |
2,322 | <ASSISTANT_TASK:>
Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
pip freeze | grep kfp || pip install kfp
from os import path
import kfp
import kfp.compiler as compiler
import kfp.components as comp
import kfp.dsl as dsl
import kfp.gcp as gcp
import kfp.notebook
HOST = # TODO: fill 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: Setup a Kubeflow cluster on GCP
Step2: Create an experiment
Step3: Let's look at the experiments that are running on this cluster. Since you j... |
2,323 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
from sklearn.svm import LinearSVC
model = LinearSVC()
model_name = type(model).__name__
<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:
|
2,324 | <ASSISTANT_TASK:>
Python Code:
import logging
from collections import namedtuple
import numpy as np
from pandas import DataFrame
from IPython.display import HTML
from numpy.linalg import inv
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import Polynom... | <SYSTEM_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: 我们仅使用RM(平均房间数)和Price(按1000美元计的房价中位数)两个指标。
Step3: 为了方便描述,我们这里引入一些符号。$x^{(i)}$ 用来表示输入变量,比如这里的平均房间数,它也被称为特征features。$y^{(i)}$ 用来... |
2,325 | <ASSISTANT_TASK:>
Python Code:
import random
import graphistry as g
import pandas as pd
from random import choice
from string import ascii_letters
from IPython.display import IFrame
g.__version__
# To specify Graphistry account & server, use:
# graphistry.register(api=3, username='...', password='...', protocol='https... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Check the version of the Graphistry module
Step2: 800K Edges, 1K Nodes (no attributes)
Step3: 800K Edges, 1K Nodes (5 integer node and edge at... |
2,326 | <ASSISTANT_TASK:>
Python Code:
tags = {}
for event, elem in ET.iterparse("sample.osm"):
if elem.tag not in tags:
tags[elem.tag]= 1
else:
tags[elem.tag] += 1
print tags
tags_details = {}
keys = ["amenity","shop","sport","place","service","building"]
def create_tags_details(binder, list_keys, fil... | <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: What I will do to get a better view of the file?
Step5: What questions I want to answer?
Step8: One street type needs to be cleaned ('AVE'). W... |
2,327 | <ASSISTANT_TASK:>
Python Code:
import os
from lightning import Lightning
from numpy import random, asarray, argmin
from colorsys import hsv_to_rgb
import networkx as nx
lgn = Lightning(ipython=True, host='http://public.lightning-viz.org')
G = nx.random_geometric_graph(100, 0.2)
pos = asarray(nx.get_node_attributes(G,... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Connect to server
Step2: <hr> Random spatial graphs
Step3: We can add a color to each node. Here we color the same graph based on distance fro... |
2,328 | <ASSISTANT_TASK:>
Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import time
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
#import reader
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: Create a single layer RNN with LSTMs and train it with a toy dataset.
Step2: Now we are going to increase the depth of our RNN. Let's train an ... |
2,329 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
np.testing.assert_allclose(1.5, flexible_mean(1.0, 2.0))
np.testing.assert_allclose(0.0, flexible_mean(-100, 100))
np.testing.assert_allclose(1303.359375, flexible_mean(1, 5452, 43, 34, 40.23, 605.2, 4239.2, 12.245))
assert make_dict(one = "two", three = "four") == {"o... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: B
Step2: C
Step3: D
|
2,330 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from numpy.linalg import norm
from matplotlib import pyplot as plt
rng = np.random.default_rng()
def gradientDescent(f,grad,stepsize,x0,maxiter=1e3):
x = x0.copy()
fHist = []
for k in range(int(maxiter)):
x -= stepsize*grad(x)
fHist.append( f(x) )
ret... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Solvers
Step2: Undeterdetermined case (expect gradient descent to give sublinear convergence)
Step3: Question for thought
|
2,331 | <ASSISTANT_TASK:>
Python Code:
def rounded_avg(n, m):
if m < n:
return -1
summation = 0
for i in range(n, m+1):
summation += i
return bin(round(summation/(m - n + 1)))
<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:
|
2,332 | <ASSISTANT_TASK:>
Python Code:
from pybrain.tools.shortcuts import buildNetwork
net = buildNetwork(2, 1, outclass=pybrain.SigmoidLayer)
print net.params
def print_pred2(dataset, network):
df = pd.DataFrame(dataset.data['sample'][:dataset.getLength()],columns=['X', 'Y'])
prediction = np.round(network.activateOnD... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: AND Neural Network
Step2: Question
Step3: Plotting the NN Output
Step4: <br/>
Step5: XOR NN Output Plot
Step6: The Little Red Riding Hood N... |
2,333 | <ASSISTANT_TASK:>
Python Code:
def make_notes_and_rests(counts, denominator, time_signatures):
Makes notes and rests with repeating pattern of durations.
Output sums to time signatures.
Returns staff.
durations = [_.duration for _ in time_signatures]
total_duration = sum(duration... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Encapsulation, part 1
Step3: 2. A function to attach time signatures
Step5: 3. A function to pitch notes
Step7: 4. A function to attach artic... |
2,334 | <ASSISTANT_TASK:>
Python Code:
import goslate # pip install goslate
from bs4 import BeautifulSoup # pip install beautifulsoup4
import urllib2 # pip install requests
inventary_dict = {'milk': 23, 'coockies': 12, 'chocolate': 26, 'yogourt': 5}
print "This is the original dictionary:"
print inventary_dict
print " "
prin... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1.- Introduction to Python dictionaries
Step2: Note
Step3: EXERCISE
Step4: EXERCISE
Step5: 2.- Downloading a webpage
Step6: BeautifulSoup... |
2,335 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
# read in the data
url = 'https://raw.githubusercontent.com/albahnsen/PracticalMachineLearningClass/master/datasets/hitters.csv'
hitters = pd.read_csv(url)
# remove rows with missing values
hitters.dropna(inplace=True)
hitters.head()
# encode categor... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Predicting if salary is high with a decision tree
Step2: For feature 1 calculate possible splitting points
Step3: split the data using split 5... |
2,336 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from scipy.misc import derivative
import itertools
%matplotlib widget
import matplotlib.pyplot as plt
def CobbDouglas(x, alpha, h=1e-10, deriv=False):
'''
Compute the utility of an individual with Cobb-Douglas preferences
Additionally it returns the exact 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: Let's compute the utility for "all" values of $x$ in $[0,10]^M$ and plot them.
Step2: Demands
Step3: This is an equilibrium, but of course in ... |
2,337 | <ASSISTANT_TASK:>
Python Code:
import dlib
import cv2
cap = cv2.VideoCapture(0)
ret, img = cap.read()
print(ret)
cv2.imshow('image', img)
cv2.waitKey(2000)
detector = dlib.get_frontal_face_detector()
dets = detector(img, 1)
len(dets)
dets[0]
dlib.rectangle?
print(dets[0].left())
print(dets[0].top())
print(dets... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: これでdlibとcv2が使えるようになりました。dlib.あるいはcv2.の後に関数名を付けることでそれぞれの機能を呼び出せます。早速WebCAMを使えるようにしましょう。
Step2: カメラのタリーが光りましたか? 光らない場合は括弧の中の数字を1や2に変えてみて下さい。
Step... |
2,338 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
#Create fake income/age clusters for N people in k clusters
def createClusteredData(N, k):
pointsPerCluster = float(N)/k
X = []
y = []
for i in range (k):
incomeCentroid = np.random.uniform(20000.0, 200000.0)
ageCentroid = np.random.unifo... | <SYSTEM_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'll use linear SVC to partition our graph into clusters
Step2: By setting up a dense mesh of points in the grid and classifying all of th... |
2,339 | <ASSISTANT_TASK:>
Python Code:
import os
os.chdir(os.getcwd() + '/..')
# Run some setup code for this notebook
import random
import numpy as np
import matplotlib.pyplot as plt
from utils.data_utils import load_CIFAR10
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcPara... | <SYSTEM_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: Extract Features
Step3: Train SVM on features
Step4: Inline question 1
|
2,340 | <ASSISTANT_TASK:>
Python Code:
import cvxpy as cp
import numpy as np
import matplotlib.pyplot as plt
def loss_fn(X, Y, beta):
return cp.norm2(cp.matmul(X, beta) - Y)**2
def regularizer(beta):
return cp.norm1(beta)
def objective_fn(X, Y, beta, lambd):
return loss_fn(X, Y, beta) + lambd * regularizer(beta)
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: Writing the objective function
Step2: Generating data
Step3: Fitting the model
Step4: Evaluating the model
Step5: Regularization path and fe... |
2,341 | <ASSISTANT_TASK:>
Python Code:
from dolfin import *
from rbnics import *
from sampling import LinearlyDependentUniformDistribution
@PullBackFormsToReferenceDomain()
@AffineShapeParametrization("data/t_bypass_vertices_mapping.vmp")
class Stokes(StokesProblem):
# Default initialization of members
def __init__(se... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 3. Affine decomposition
Step2: 4. Main program
Step3: 4.2. Create Finite Element space (Taylor-Hood P2-P1)
Step4: 4.3. Allocate an object of ... |
2,342 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import os
import numpy as np
import matplotlib.pyplot as plt
from keras.applications import Xception
from keras.preprocessing.image import ImageDataGenerator
from keras import models
from keras import layers
from keras import optimizers
import tensorflow as tf
base_dir... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Get train, validation and 2 test data sets - data had previously been split by a Python script.
Step2: Set up base model - had success for this... |
2,343 | <ASSISTANT_TASK:>
Python Code:
!pip install --user apache-beam[gcp]==2.16.0
!pip install --user tensorflow-transform==0.15.0
!pip download tensorflow-transform==0.15.0 --no-deps
%%bash
pip freeze | grep -e 'flow\|beam'
import tensorflow as tf
import tensorflow_transform as tft
import shutil
print(tf.__version__)
# c... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: NOTE
Step2: <b>Restart the kernel</b> (click on the reload button above).
Step8: Input source
Step9: Let's pull this query down into a Pandas... |
2,344 | <ASSISTANT_TASK:>
Python Code:
# <!-- collapse=True -->
# Importando las librerías que vamos a utilizar
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cross_validation import train_test_split
from sklearn.feature_selection import SelectKBest
from sklearn.fea... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Con estas manipulaciones lo que hicimos es cargar en memoria el dataset que prepocesamos anteriormente, le agregamos la nueva columna AGE2, ya q... |
2,345 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
%%time
Employees = pd.read_excel('/home/data/AdventureWorks/Employees.xls')
print("shape:", Employees.shape)
%%time
Territory = pd.read_excel('/home/data/AdventureWorks/SalesTerritory.xls')
print("shape:", Territory.shape)
%%time
Customers = pd.read_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Filtering (with)
Step2: 2a. Show me a list of employees that have a lastname that begins with "R".
Step3: 2b. Show me a list of employees that... |
2,346 | <ASSISTANT_TASK:>
Python Code:
import desc.monitor
import pandas as pd
%load_ext autoreload
%autoreload 2
truth_db_conn = desc.monitor.StarCacheDBObj(database='../data/star_cache.db')
truth_db_conn.columns
worker = desc.monitor.TrueStars(truth_db_conn, '../../kraken_1042_sqlite.db')
# Just use one visit here 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: Get cached CatSim stars
Step2: Use Opsim to calculate expected flux in visits.
Step3: Save to a sqlite database
|
2,347 | <ASSISTANT_TASK:>
Python Code:
from numpy import cos,sin #避免使用
import numpy as np #np.method()
r1 = range(5)
r2 = np.arange(5)
r3 = xrange(5)
print r1,r2,r3
for i in r1:
print i,
print '\n'
for i in r2:
print i,
print '\n'
for i in r3:
print i,
print type(r1),type(r2),type(r3)
print np.arange(0,5),np.arang... | <SYSTEM_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: IPython能够支持自动补全和帮助:
Step3: 论numpy的正确打开方式:少用原生语法、多用ufunc和broadcasting,少用数据转换
Step4: 为了比较性能,使用ipython的“魔法函数”timeit,或者datetim... |
2,348 | <ASSISTANT_TASK:>
Python Code:
% matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
import shutil
DATA_DIR = '../data/pmf'
data = pd.read_csv(os.path.join(DATA_DIR, 'jester-dataset-v1-dense-first-1000.csv'))
data.head()
# Extract the ratings from the DataFrame
all_ratings... | <SYSTEM_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 must be a decent batch of jokes. From our exploration above, we know most ratings are in the range -1 to 10, and positive ratings are more ... |
2,349 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
def get_LINEAR_lightcurve(lcid):
from astroML.datasets import fetch_LINEAR_sample
LINEAR_sample = fetch_LINEAR_sample()
data = pd.DataFrame(LINEAR_sample[lcid],
columns=['t', 'mag', 'magerr'])
data.to_csv('LINEAR_{0}.csv'.format(... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Visualizing the Data
Step2: Peak Precision
Step3: Looks like $2.58023 \pm 0.00006$ hours
Step4: Required Grid Spacing
|
2,350 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import importlib, utils2; importlib.reload(utils2)
from utils2 import *
np.set_printoptions(4)
cfg = K.tf.ConfigProto(gpu_options={'allow_growth': True})
K.set_session(K.tf.Session(config=cfg))
def tokenize(sent):
return [x.strip() for x in re.split('(\W+)?', sent)... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: A memory network is a network that can retain information; it can be trained on a structured story and will learn how to answer questions about ... |
2,351 | <ASSISTANT_TASK:>
Python Code:
import yaml
import random
with open("answers.yaml", "r") as conf:
config = yaml.load(conf)
def get_answer(message):
lower_msg = message.lower()
for key in config['answers']:
if key in lower_msg:
return random.choice(config['answers'][key])
import rand... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Решение задачи на sleepsort
Step2: Асинхронность и параллельность
Step3: Ключевые слова async и await
Step4: Упражнение
Step5: Django
Step6:... |
2,352 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib
import pylab as plt
import scipy.misc as pim
from scipy import stats
% matplotlib inline
font = {'weight' : 'bold',
'size' : 12}
matplotlib.rc('font', **font)
x,y = np.loadtxt('TSI2.txt', usecols=[0,1], dtype='float', unpack='True',delimiter... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Lectura y grafica de los datos de 'TSI2.tx'
Step2: Transformada de fourier de los datos
Step3: Análisis
|
2,353 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
def well2d(x, y, nx, ny, L=1.0):
Compute the 2d quantum well wave function.
sci=2/L*np.sin((nx*np.pi*x)/L)*np.sin((ny*np.pi*y)/L)
return sci
psi = well2d(np.linspace(0,1,10), np.linspace(0,1,10), 1, 1)
asse... | <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: Contour plots of 2d wavefunctions
Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib can be used for effective visuali... |
2,354 | <ASSISTANT_TASK:>
Python Code:
## Load data
df = pd.read_csv('../../data/dga_data_small.csv')
df.drop(['host', 'subclass'], axis=1, inplace=True)
print(df.shape)
df.sample(n=5).head() # print a random sample of the DataFrame
df[df.isDGA == 'legit'].head()
# Google's 10000 most common english words will be needed to der... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Part 1 - Feature Engineering
Step2: Tasks - A - Feature Engineering
Step3: Tasks - B - Feature Engineering
Step4: Breakpoint
Step5: Visualiz... |
2,355 | <ASSISTANT_TASK:>
Python Code:
l = [1,2,3]
l.count(2)
print type(1)
print type([])
print type(())
print type({})
# Create a new object type called Sample
class Sample(object):
pass
# Instance of Sample
x = Sample()
print type(x)
class Dog(object):
def __init__(self,breed):
self.breed = breed
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Remember how we could call methods on a list?
Step2: What we will basically be doing in this lecture is exploring how we could create an Object... |
2,356 | <ASSISTANT_TASK:>
Python Code:
# below is to make plots show up in the notebook
%matplotlib inline
# Code Block 1
import numpy as np
from matplotlib.pyplot import figure, legend, plot, show, title, xlabel, ylabel, ylim
from landlab.plot.imshow import imshow_grid
# Code Block 2
# setup grid
from landlab import RasterMo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We will create a grid with 41 rows and 5 columns, and dx is 5 m (a long, narrow, hillslope). The initial elevation is 0 at all nodes.
Step2: No... |
2,357 | <ASSISTANT_TASK:>
Python Code:
digit =[0 ] *(100000 )
def findDigits(n ) :
count = 0
while(n != 0 ) :
digit[count ] = n % 10 ;
n = n // 10 ;
count += 1
return count
def OR_of_Digits(n , count ) :
ans = 0
for i in range(count ) :
ans = ans | digit[i ]
return ans
def AND_of_Digits(n ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
2,358 | <ASSISTANT_TASK:>
Python Code:
import graphlab
'''Check GraphLab Create version'''
from distutils.version import StrictVersion
assert (StrictVersion(graphlab.version) >= StrictVersion('1.8.5')), 'GraphLab Create must be version 1.8.5 or later.'
from em_utilities import *
wiki = graphlab.SFrame('people_wiki.gl/').head... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We also have a Python file containing implementations for several functions that will be used during the course of this assignment.
Step2: Load... |
2,359 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
s = np.random.uniform(8,10., 100000)
count, bins, ignored = plt.hist(s, 30)
#print (count, bins, ignored)
import numpy as np
import matplotlib.pyplot as plt
mean = [0, 0]
cov = [[1, 10], [5, 10]] # covariancia diagonal
x, y = np.random.m... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Simulando jogo de dados
Step2: Simulando decaimento radiativo
Step3: Simulando um andar de bebado
Step4: Integração Monte Carlo
|
2,360 | <ASSISTANT_TASK:>
Python Code:
#@title Colab setup and imports
from matplotlib.lines import Line2D
from matplotlib.patches import Circle
import matplotlib.pyplot as plt
import numpy as np
try:
import brax
except ImportError:
from IPython.display import clear_output
!pip install git+https://github.com/google/brax... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Brax Config
Step2: We visualize this system config like so
Step3: Brax State
Step4: Brax Step Function
Step5: Joints
Step6: Here is our sys... |
2,361 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.set_option('max_columns', 50)
%matplotlib inline
series = pd.Series([1, "number", 6, "Happy Series!"])
series
dictionary = {'Favorite Food': 'mexican', 'Favorite city': 'Portland', 'Hometown': 'Mexico City'}
favori... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Series from a dictionary
Step2: Accesing an item from a series
Step3: BOOLEAN indexing for selection
Step4: Not null function
Step5: Data Fr... |
2,362 | <ASSISTANT_TASK:>
Python Code:
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: BERT End to End (Fine-tuning + Predicting) in 5 minutes with Cloud TPU
Step2: Prepare and import BERT modules
Step3: Prepare for training
Step... |
2,363 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division
import graphlab
import math
import string
products = graphlab.SFrame('amazon_baby.gl/')
products
products[269]
def remove_punctuation(text):
import string
return text.translate(None, string.punctuation)
review_without_puctuation = products['rev... | <SYSTEM_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 preperation
Step2: Now, let us see a preview of what the dataset looks like.
Step3: Build the word count vector for each review
Step4: N... |
2,364 | <ASSISTANT_TASK:>
Python Code:
# librerias
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.formula.api as sm
%matplotlib inline
plt.style.use('ggplot')
# leer archivo
data = pd.read_csv('../data/dataFromAguascalientestTest.csv')
# verificar su contenido
data.head()
# diferencia... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Regresion Lineal
Step2: Regresion lineal con p y pearsonr
Step3: OLS Regression
Step4: Histogramas seaborn
|
2,365 | <ASSISTANT_TASK:>
Python Code:
from bokeh.io import output_notebook, show
from bokeh.layouts import row
from bokeh.plotting import figure
import numpy as np
import cotede
from cotede import datasets, qctests
output_notebook()
data = cotede.datasets.load_ctd()
print("The variables are: ", ", ".join(sorted(data.keys()))... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Data
Step2: This CTD was equipped with backup sensors to provide more robustness.
Step3: Considering the unusual magnitudes and variability ne... |
2,366 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
import math
import sklearn
import sklearn.datasets
from opt_utils import load_params_and_grads, initialize_parameters, forward_propagation, backward_propagation
from opt_utils import compute_cost, predict, predict_dec, 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:
Step2: 1 - Gradient Descent
Step4: Expected Output
Step6: Expected Output
Step8: Expected Output
Step10: Expected Output
Step12: Expected Output
S... |
2,367 | <ASSISTANT_TASK:>
Python Code:
import numpy as np # np.array (and used internally in cvxpy)
import cvxpy as cvx
import sys
print("Using CVX version", cvx.__version__)
print(" and python version", sys.version)
A = np.array([[1, 6,11, 5,10, 4, 9, 3, 8, 2],
[2, 7, 1, 6,11, 5,10, 4, 9, 3],
[3, 8... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problem 1
Step2: Problem 2
Step3: Problem 3
Step4: Problem 4
Step5: Problem 5
Step6: Problem 6
Step7: Problem 7
Step8: Problem 8
|
2,368 | <ASSISTANT_TASK:>
Python Code:
!pip install unidecode
# Import TensorFlow >= 1.9 and enable eager execution
import tensorflow as tf
# Note: Once you enable eager execution, it cannot be disabled.
tf.enable_eager_execution()
import numpy as np
import re
import random
import unidecode
import time
path_to_file = tf.ker... | <SYSTEM_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: Download the dataset
Step3: Read the dataset
Step4: Creating dictionaries to map from ch... |
2,369 | <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import fetch_mldata
from sklearn.utils import shuffle
mnist = fetch_mldata('MNIST original', data_home='./mnist_data')
X, y = shuffle(mnist.data[:60000], mnist.target[:60000])
X_small = X[:100]
y_small = y[:100]
# Note: using only 10% of the training data
X_large = 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: Instantiate the estimator and the SearchCV objects
Step2: Fit the BayesSearchCV object locally
Step3: Everything up to this point is what you ... |
2,370 | <ASSISTANT_TASK:>
Python Code:
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
documents = [
"Human machine interface for lab abc computer applications",
"A survey of user opinion of computer system response time",
"The EPS user interface managemen... | <SYSTEM_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 create a small corpus of nine short documents [1]_
Step2: This is a tiny corpus of nine documents, each consisting of only a singl... |
2,371 | <ASSISTANT_TASK:>
Python Code:
!pip install -r requirements.txt
import argparse
import logging
import joblib
import sys
import pandas as pd
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
from xgboost import XGBRegressor
loggi... | <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: Define a function to split the input file into training and testing datasets.
Step6: Define functions to train, evaluate, and save the trained ... |
2,372 | <ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 2
%pdb off
# set DISPLAY = True when running tutorial
DISPLAY = False
# set PARALLELIZE to true if you want to use ipyparallel
PARALLELIZE = False
import warnings
warnings.filterwarnings('ignore')
dataset_file= "../datasets/pdbbind_core_df.pkl.gz"
from dee... | <SYSTEM_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 see what dataset looks like
Step2: One of the missions of deepchem is to form a synapse between the chemical and the algorithmic worlds
S... |
2,373 | <ASSISTANT_TASK:>
Python Code:
# Definitions of parameters of the circuit
# Capacitance of generator [F]
C = 1e-6
# Parallel resistance (discharging the capacitor in the generator forming the tail of the impulse) [Ohm]
R1 = 4
# Series resistance (forming the head) [Ohm]
R2 = 150
# Inductance of the loop [H]
L = 1e-3
#... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Case1
Step2: Case 2
Step3: Case 3
Step4: Case 4
|
2,374 | <ASSISTANT_TASK:>
Python Code:
%run -i initilization.py
from pyspark.sql import functions as F
from pyspark.ml import clustering
from pyspark.ml import feature
from pyspark.sql import DataFrame
from pyspark.sql import Window
from pyspark.ml import Pipeline
from pyspark.ml import classification
from pyspark.ml.evaluati... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Add some parameters in order to generate a dataset
Step3: An initial method to semi supervised learning
Step4: Create the labled dataset, and ... |
2,375 | <ASSISTANT_TASK:>
Python Code:
%run db2odata.ipynb
%run db2.ipynb
%sql connect reset
%sql connect
%sql -sampledata
%sql SELECT * FROM EMPLOYEE
%odata register
%odata RESET TABLE EMPLOYEE
s = %odata -e SELECT lastname, salary from employee where salary > 50000
s = %odata -e SELECT * FROM EMPLOYEE
%odata 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: DB2 Extensions
Step2: <a id='top'></a>
Step3: If you connected to the SAMPLE database, you will have the EMPLOYEE and DEPARTMENT tables availa... |
2,376 | <ASSISTANT_TASK:>
Python Code:
from pyspark import SparkConf, SparkContext
from collections import OrderedDict
partitions = 48
parcsv = sc.textFile("/lustre/janus_scratch/dami9546/lustre_timeseries.csv", partitions)
parcsv.take(5)
filtered = parcsv.filter(lambda line: len(line.split(';')) == 6)
def cast(line):
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:
Step1: Each of these lines contains 6 semi-colon delimited columns
Step2: As seen above, the lines are Unicode, but in anticipation of necessary trans... |
2,377 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
PROJECT = !gcloud config get-value project
PROJECT = PROJECT[0]
%env PROJECT=$PROJECT
pd.options.display.max_columns = 50
%%bigquery --project $PROJECT
#standardsql
SELECT *
EXCEPT
(table_catalog, table_schema, is_generated, generation_expression, is_stored,
... | <SYSTEM_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 eCommerce data and identify duplicate records
Step2: Next examine how many rows are in the table.
Step3: Now take a quick at few rows ... |
2,378 | <ASSISTANT_TASK:>
Python Code:
Environment setup
%matplotlib inline
%cd /lang_dec
import warnings; warnings.filterwarnings('ignore')
import hddm
import numpy as np
import matplotlib.pyplot as plt
from utils import model_tools
# Import patient data (as pandas dataframe)
patients_data = hddm.load_csv('/lang_dec/data/pati... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Patient Data Analysis
Step2: Reaction Time & Accuracy
Step4: Does the drift rate depend on stimulus type?
Step5: Convergence Checks
Step6: P... |
2,379 | <ASSISTANT_TASK:>
Python Code:
from typing import Optional
import gdsfactory as gf
from gdsfactory.component import Component
from gdsfactory.components.bend_euler import bend_euler
from gdsfactory.components.coupler90 import coupler90 as coupler90function
from gdsfactory.components.coupler_straight import (
couple... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: gdsfactory in 5 minutes
Step3: Lets define a ring function that also accepts other component specs for the subcomponents (straight, coupler, be... |
2,380 | <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: FGSM을 이용한 적대적 샘플 생성
Step2: 사전 훈련된 MobileNetV2 모델과 ImageNet의 클래스(class) 이름들을 불러옵니다.
Step3: 원본 이미지
Step4: 이미지를 살펴봅시다.
Step5: 적대적 이미지 생성하기
Step... |
2,381 | <ASSISTANT_TASK:>
Python Code:
import os
import larch # !conda install larch -c conda-forge # for estimation
import pandas as pd
os.chdir('test')
modelname = "nonmand_tour_freq"
from activitysim.estimation.larch import component_model
model, data = component_model(modelname, return_data=True)
type(model)
model.keys... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We'll work in our test directory, where ActivitySim has saved the estimation data bundles.
Step2: Load data and prep model for estimation
Step3... |
2,382 | <ASSISTANT_TASK:>
Python Code:
!pip install -I "phoebe>=2.2,<2.3"
%matplotlib inline
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger()
b = phoebe.default_binary()
b.add_dataset('lc', times=np.linspace(0,1,101), dataset='lc01')
print(b['exptime'])
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: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details.
Step2: Relevant Parameters
Step3... |
2,383 | <ASSISTANT_TASK:>
Python Code:
np.random.seed(10)
p, q = (np.random.rand(i, 2) for i in (4, 5))
p_big, q_big = (np.random.rand(i, 80) for i in (100, 120))
print(p, "\n\n", q)
def naive(p, q):
result = np.zeros((p.shape[0], q.shape[0]))
for i in range(p.shape[0]):
for j in range(q.shape[0]):
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Solution
Step2: Use matching indices
Step3: Use a library
Step4: Numpy Magic
Step5: Compare methods
|
2,384 | <ASSISTANT_TASK:>
Python Code:
import requests
lil_response = requests.get('https://api.spotify.com/v1/search?query=lil&type=artist&type=track&market=US&limit=50')
#print(response.text)
lil_data = lil_response.json()
lil_data.keys()
#print(lil_data)
lil_data['artists'].keys()
lil_artists = lil_data['artists']['items']
... | <SYSTEM_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? Edit your previous printout to also display a list of their genres in the format "GEN... |
2,385 | <ASSISTANT_TASK:>
Python Code:
import vcsn
q = vcsn.context('lal_char(ab), q')
def std(e):
return q.expression(e).standard()
a = std('(ab)*')+std('(ab)*')
a
a.has_twins_property()
a = std('(<2>ab)*+(ab)*')
a
a.has_twins_property()
a = std("(aa)*+(ab)*")
a
a.has_twins_property()
%%automaton a
context = "lal_cha... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Consider the following $\mathbb{Q}$ automaton
Step2: State $1$ and $3$ are siblings
Step3: Conversely, the following automaton does not have t... |
2,386 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.read_csv('/opt/names/fec_contrib/contribDB_2000.csv', nrows=100)
df.columns
from ethnicolr import census_ln, pred_census_ln
df = pd.read_csv('/opt/names/fec_contrib/contribDB_2000.csv', usecols=['amount', 'contributor_type', 'contributor_lname', 'contributor_f... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load and Subset on Individual Contributors
Step2: What proportion of contributions were by blacks, whites, Hispanics, and Asians?
Step3: What ... |
2,387 | <ASSISTANT_TASK:>
Python Code:
app = cylinder_app();
display(app)
app = plot_layer_potentials_app()
display(app)
app = MidpointPseudoSectionWidget();
display(app)
app = DC2DPseudoWidget()
display(app)
app = DC2DfwdWidget()
display(app)
<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: 2. Potential differences and Apparent Resistivities
Step2: 3. Building Pseudosections
Step3: DC pseudo-section app
Step4: 4. Parametric Inver... |
2,388 | <ASSISTANT_TASK:>
Python Code:
# system
import os
import sys
# 3rd party lib
import pandas as pd
from sklearn.cluster import KMeans
from fuzzywuzzy import fuzz # stirng matching
print('Python verison: {}'.format(sys.version))
print('\n############################')
print('Pandas verison: {}'.format(pd.show_versions()))... | <SYSTEM_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 file
Step2: Access data of multiIndex dataframe
Step3: Dataframe that i want to match
Step5: string matching funciton
Step6: show all s... |
2,389 | <ASSISTANT_TASK:>
Python Code:
from PIL import Image
im = Image.open('2d.png')
width, height = im.size
intensity = np.array([[1 for j in range(width)] for i in range(height)])
for x in range(0, height):
for y in range(0, width):
RGB = im.getpixel((y, x))
intensity[x][y] = (0.2126 * (255-RGB[0]) + ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Initialize an intensity array.
Step2: Below, we retrieve each pixel and then calculate darkness value. The perceived brightness is given by
Ste... |
2,390 | <ASSISTANT_TASK:>
Python Code:
class Car(object):
wheels = 4
def __init__(self, make, model):
self.make = make
self.model = model
mustang = Car('Ford', 'Mustang')
print(mustang.wheels)
# 4
print(Car.wheels)
# 4
class Car(object):
...
def make_car_sound():
print('VRooooommmm!')
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Static Methods
Step2: Our make_car_sound static method does not work on an instance of our Car class because the instance tries to pass a self ... |
2,391 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import sys,os
ia898path = os.path.abspath('/etc/jupyterhub/ia898_1s2017/')
if ia898path not in sys.path:
sys.path.append(ia898path)
import ia898.src as ia
f = mpimg.imread('../data/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: Ordena os pixels da imagem original, sabendo-se seu endereço (posição em fsi).
Step2: Cria uma imagem de mesmas dimensões, porém com os pixels ... |
2,392 | <ASSISTANT_TASK:>
Python Code:
# Start with the usual.
import hydrofunctions as hf
%matplotlib inline
hf.__version__
# request data for our two sites for a three-year period.
sites = ['01589330', '01581830']
request = hf.NWIS(sites, start_date='2002-01-01', end_date='2005-01-01', file='Urban_Rural.parquet')
request # 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: Description of the two sites
|
2,393 | <ASSISTANT_TASK:>
Python Code:
print ("hello World")
!python textfiles\hello.py # ! accesses the operating system without leaving the notebook
%quickref # brings up some info about jupyter magics
import math # now I'm just playing around, not following Socratica
def pythag(a,b):
return math.sqrt(a**2 + 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: Next, copy or type the same line of code into a text file and save the file as hello.py.
Step2: Play around with what you have learned . . .
St... |
2,394 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import sklearn.datasets, sklearn.linear_model, sklearn.neighbors
import sklearn.manifold, sklearn.cluster
import matplotlib.pyplot as plt
import seaborn as sns
import sys, os, time
import scipy.io.wavfile, scipy.signal
import cv2
%matplotlib inline
import matplotlib as ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Topic Purpose
Step3: Practical
|
2,395 | <ASSISTANT_TASK:>
Python Code:
workflow = parse('/Users/dcl9/Code/python/mmap-cwl/mmap.cwl')
# This function will find dockerImageId anyhwere in the tree
def find_key(d, key, path=[]):
if isinstance(d, list):
for i, v in enumerate(d):
for f in find_key(v, key, path + [str(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: Yes, that works
Step2: extract docker image names
Step3: Docker IO
|
2,396 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division, print_function
import pandas as pd
import numpy as np
data_dir = 'data/'
# Load Original Data / contains data + labels 10 k
train = pd.read_csv("../data/train.data")#.drop('id',axis =1 )
# Your validation data / we provide also a validation dataset, conta... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Trainning and testing the model with cross validation.
Step2: The next cell may take some time.
Step3: Trainning the model on the complete tra... |
2,397 | <ASSISTANT_TASK:>
Python Code:
class Song:
Represent a Song in our lyrics site.
Parameters
----------
name : str
The name of the song.
lyrics : str
The lyrics of the song.
artists : list of str or str, optional
Can be either a list, or a string separated by commas.
At... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step7: <img src="images/logo.jpg" style="display
Step8: <p style="text-align
Step10: <p style="text-align
Step11: <p style="text-align
Step12: <p s... |
2,398 | <ASSISTANT_TASK:>
Python Code:
import collections
import glob
import os
from os import path
import matplotlib_venn
import pandas
rome_path = path.join(os.getenv('DATA_FOLDER'), 'rome/csv')
OLD_VERSION = '331'
NEW_VERSION = '332'
old_version_files = frozenset(glob.glob(rome_path + '/*{}*'.format(OLD_VERSION)))
new_versi... | <SYSTEM_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: So we have the same set of files in both versions
Ste... |
2,399 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook
def plot_p_and_g():
phi = np.linspace(-0.1, 1.1, 200)
g=phi**2*(1-phi)**2
p=phi**3*(6*phi**2-15*phi+10)
# Changed 3 to 1 in the figure call.
plt.figure(1, figsize=(12,6))
plt.subplot(121)
p... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We start by using the ordinary free energy of the pure components
Step2: $$L(\phi,\nabla\phi) = \int_V \Big[ ~~f(\phi,T) + \frac{\epsilon^2_\ph... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.