Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
500
<ASSISTANT_TASK:> Python Code: from google.cloud import storage import pandas as pd import torch import torch.optim as optim import torch.nn as nn from torch.utils.data import Dataset from torch.utils.data import DataLoader from torch.utils.data import random_split # Public bucket holding the census data bucket = stor...
<SYSTEM_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 code to download the data from GCS (in this case, using the publicly hosted data). You will then be able to use the data when training your ...
501
<ASSISTANT_TASK:> Python Code: %matplotlib inline import seaborn as snb import numpy as np import matplotlib.pyplot as plt def create_plot(): x = np.arange(0.0, 10.0, 0.1) plt.plot(x, x**2) plt.xlabel("$x$") plt.ylabel("$y=x^2$") create_plot() plt.show() def save_to_file(filename, fig=None): ...
<SYSTEM_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 quatratic plot Step3: Save the figure Step4: And it can be easily saved with
502
<ASSISTANT_TASK:> Python Code: import math import datetime ## to deal with dates from IPython.display import Image # will return True if a year is a leap year on Mars def is_leap_year_mars(year): if year % 3000 == 0: return False elif year % 1000 == 0: return True elif year % 100 == 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: 火星历法 Step2: 所以,一年的总天数,我们可以这样表示 Step3: 测试一下这两个函数。 Step4: 火星月日的计算 Step5: 测试此函数 Step6: 可以看到函数正确的返回了月日以及错误信息。 Step7: 火星元年与校准日期 Step8: 注意到 flo...
503
<ASSISTANT_TASK:> Python Code: !git clone https://bitbucket.org/luisfernando/html2pdf.git %%! echo "Install Xvfd:" sudo apt-get install xvfb echo "Install Fonts:" sudo apt-get install xfonts-100dpi xfonts-75dpi xfonts-scalable xfonts-cyrillic echo "Install wkhtmltopdf:" sudo apt-get install wkhtmltopdf %%! source acti...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: python-wkhtmltopdf (Any Platform) Step2: Render a URL Step4: Render a HTML string
504
<ASSISTANT_TASK:> Python Code: import larch, numpy, pandas, os from larch import P, X larch.__version__ hh, pp, tour, skims, emp = larch.example(200, ['hh', 'pp', 'tour', 'skims', 'emp']) logsums_file = larch.example(202, output_file='logsums.pkl.gz') logsums = pandas.read_pickle(logsums_file) raw = tour.merge(hh, 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: In this example notebook, we will walk through the estimation of a tour Step2: For this destination choice model, we'll want to use the mode c...
505
<ASSISTANT_TASK:> Python Code: # scientific python import numpy as np import scipy as sp # interactive plotting %pylab inline # Create a random array of size 3 x 5 X = np.random.random((3, 5)) # Create an array of zeros of size 3 x 5 np.zeros((3, 5)) # Create an array of ones of size 3 x 5 np.ones((3, 5)) # Create th...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The previous command is one of the "magics" of Jupyter. As indicated by the message you have gotten, it imports numpy and matplotlib. Step2: Ac...
506
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import lsst.sims.maf.db as db import lsst.sims.maf.metrics as metrics import lsst.sims.maf.slicers as slicers import lsst.sims.maf.metricBundles as metricBundles from lsst.sims.maf.metrics import BaseMetric class Coad...
<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: Writing a new metric Step5: To understand this, you need to know a little bit about "classes" and "inheritance". Step6: So then how do we use...
507
<ASSISTANT_TASK:> Python Code: # As usual, a bit of setup from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Batch Normalization Step2: Batch normalization Step3: Batch Normalization Step4: Batch Normalization Step5: Fully Connected Nets with Batch ...
508
<ASSISTANT_TASK:> Python Code: df.dtypes #dtype: Data type for data or columns print("The data type is",(type(df['Plate ID'][0]))) df['Vehicle Year'] = df['Vehicle Year'].replace("0","NaN") #str.replace(old, new[, max]) df.head() # Function to use for converting a sequence of string columns to an array of datetime 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: 2. I don't think anyone's car was built in 0AD. Discard the '0's as NaN. Step2: 3. I want the dates to be dates! Read the read_csv documentatio...
509
<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: On-Device Training with TensorFlow Lite Step2: Note Step3: The train function in the code above uses the GradientTape class to record operatio...
510
<ASSISTANT_TASK:> Python Code: # You can use any Python source file as a module by executing an import statement in some other Python source file. # The import statement combines two operations; it searches for the named module, then it binds the results of that search # to a name in the local scope. import numpy as np...
<SYSTEM_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...
511
<ASSISTANT_TASK:> Python Code: from pylab import * from copy import deepcopy from matplotlib import animation, rc from IPython.display import HTML %matplotlib inline rc('text', usetex=True) font = {'family' : 'normal', 'weight' : 'bold', 'size' : 15} matplotlib.rc('font', **font) E1, E2, E3 = 0., 20....
<SYSTEM_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. Superexchange in a three-level system. Step2: (b) Step3: 2. The one-dimensional soft-core potential. Step4: 3. Ionization from a one-dimen...
512
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib import seaborn as sns pd.options.display.max_columns = 999 %matplotlib inline matplotlib.rcParams['savefig.dpi'] = 1.5 * matplotlib.rcParams['savefig.dpi'] # Read the data inside: loan2011 = 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: Underwrting Step2: Let's take a peek at the data. Step3: How many morgages have been prepaid in these three years? Step4: Remember prepay inc...
513
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('Sample-HRM-p50-genotyping.csv') plt.plot(df.iloc[:, 0],df.iloc[:,1:]) plt.show() df_melt=df.loc[(df.iloc[:,0]>75) & (df.iloc[:,0]<88)] df_data=df_melt.iloc[:,1:] plt.plot(df_melt....
<SYSTEM_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 and Plot Melting Data Step2: Select melting range Step3: Normalizing Step4: Melting Temp Step5: Calculate and Show Diff Plot Step6: Cl...
514
<ASSISTANT_TASK:> Python Code: import autofig import numpy as np #autofig.inline() t = np.linspace(0,10,31) x = np.random.rand(31) y = np.random.rand(31) z = np.random.rand(31) autofig.reset() autofig.plot(x, y, z, i=t, xlabel='x', ylabel='y', zlabel='z') mplfig = autofig.draw() autofig.reset() autofig.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: By default, autofig uses the z dimension just to assign z-order (so that positive z appears "on top") Step2: To instead plot using a projected ...
515
<ASSISTANT_TASK:> Python Code: try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import cirq qubit = cirq.NamedQubit("myqubit") # creates an equal superposition of |0> and |1> when simulated circuit = cirq.Circuit(cirq.H(qubit)) # 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: A qubit is the basic unit of quantum information, a quantum bit
516
<ASSISTANT_TASK:> Python Code: # numpy is generally imported as 'np' import numpy as np print(np) print(np.__version__) # an explicit list of numbers anarray = np.array([2, 3, 5, 7, 11, 13, 17, 19, 23]) # an array of zeros of shape(3, 4) zeroarray = np.zeros((3, 4)) # a range from 0 to n-1 rangearray = np.arange(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: Step1: Documentation Step2: Experiment Step3: Exercise Step4: You can also index multidimensional arrays in a logical way using an enhanced indexing...
517
<ASSISTANT_TASK:> Python Code: %matplotlib inline import chap01soln resp = chap01soln.ReadFemResp() resp.columns import thinkstats2 hist = thinkstats2.Hist(resp.totincr) import thinkplot thinkplot.Hist(hist, label='totincr') thinkplot.Show() hist = thinkstats2.Hist(resp.age_r) thinkplot.Hist(hist, label='age_r') thi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 응답자 가족에 대한 총소득 <tt>totincr</tt> 히스토그램을 생성하시오. 코드를 해석하기 위해서, codebook을 살펴보시오. Step2: 히스토그램을 화면에 표시하시오. Step3: 인터뷰 당시 응답자 나이 변수, <tt>age_r</tt>에...
518
<ASSISTANT_TASK:> Python Code: products = pd.read_csv('../../data/amazon_baby_subset.csv') products['sentiment'] products['sentiment'].size products.head(10).name print ('# of positive reviews =', len(products[products['sentiment']==1])) print ('# of negative reviews =', len(products[products['sentiment']==-1])) # 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: Train-Validation split Step2: Convert Frame to NumPy array Step3: Building on logistic regression with no L2 penalty assignment Step4: Adding...
519
<ASSISTANT_TASK:> Python Code: import os import fiona import matplotlib.pyplot as plt from planet import api import rasterio from rasterio import features as rfeatures from rasterio.enums import Resampling from rasterio.plot import show import shapely from shapely.geometry import shape as sshape # if your Planet API Ke...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Obtain Analytics Raster Step2: Download Quad Raster Step3: We want to save each all of the images in one directory. But all of the images for ...
520
<ASSISTANT_TASK:> Python Code: import striplog striplog.__version__ text = "wet silty fine sand with tr clay" from striplog import Lexicon lex_dict = { 'lithology': ['sand', 'clay'], 'grainsize': ['fine'], 'modifier': ['silty'], 'amount': ['trace'], 'moisture': ['wet', 'dry'], 'abbreviati...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We have some text Step2: To read this with striplog, we need to define a Lexicon. This is a dictionary-like object full of regular expressions,...
521
<ASSISTANT_TASK:> Python Code: labVersion = 'cs190_week2_word_count_v_1_0' wordsList = ['cat', 'elephant', 'rat', 'rat', 'cat'] wordsRDD = sc.parallelize(wordsList, 4) # Print out the type of wordsRDD print type(wordsRDD) # TODO: Replace <FILL IN> with appropriate code def makePlural(word): Adds an 's' to `word`....
<SYSTEM_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 Step3: (1b) Pluralize and test Step4: (1c) Apply makePlural to the base RDD Step5: (1d) Pass a lambda function to map Step6: (1e) ...
522
<ASSISTANT_TASK:> Python Code: import csv import re with open('../data/bee_list.txt') as f: csvr = csv.DictReader(f, delimiter = '\t') species = [] authors = [] for r in csvr: species.append(r['Scientific Name']) authors.append(r['Taxon Author']) len(species) len(authors) au = authors...
<SYSTEM_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, we read the file, and store the columns Scientific Name and Taxon Author in two lists Step2: How many species? Step3: Pick one of the au...
523
<ASSISTANT_TASK:> Python Code: import numpy as np sigma = np.array([1/3, 1/2, 0, 0, 1/6]) np.where(sigma > 0) # Recall Python indexing starts at 0 sigma = np.array([0, 0, 1, 0]) np.where(sigma > 0) # Recall Python indexing starts at 0 A = np.array([[1, 1, 0], [2, 3, 0]]) sigma_c = np.array([0, 0, 1]) (np.dot(A, sigm...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Definition of nondegenerate games Step2: This leads to the following algorithm for identifying Nash equilibria Step3: If you recall the degene...
524
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('C:\Anaconda2\envs\dato-env\Lib\site-packages') import graphlab sales = graphlab.SFrame('kc_house_data_small.gl/') import numpy as np # note this allows us to refer to numpy as np instead def get_numpy_data(data_sframe, features, output): data_sframe['cons...
<SYSTEM_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: Import useful functions from previous notebooks Step3: We will also need the normalize_features() function fro...
525
<ASSISTANT_TASK:> Python Code: f = spot.formula('a U Gb') a = f.translate('ba') a propset = spot.atomic_prop_collect_as_bdd(f, a) ta = spot.tgba_to_ta(a, propset, True, True, False, False, True) ta.show('.A') ta = spot.tgba_to_ta(a, propset, True, True, False, False, False) ta.show('.A') spot.minimize_ta(ta).show('....
<SYSTEM_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, gather all the atomic proposition in the formula, and create an automaton with changesets Step2: Then, remove dead states, and remove stu...
526
<ASSISTANT_TASK:> Python Code: import os import numpy as np from vertebratesLib import * split = "SPLIT1" summaryTree,summarySpecies,splitPositions = get_split_data(split) print summaryTree.shape def get_sentence(position,splitPositions,summary,ignore=False): splitIndex = np.where(splitPositions==position)[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: a sentence of words is represented as the transitions for a given position Step2: Simple test run with lda package Step3: Recall that the Diri...
527
<ASSISTANT_TASK:> Python Code: g.plot_reward(smoothing=100) g.__class__ = KarpathyGame np.set_printoptions(formatter={'float': (lambda x: '%.2f' % (x,))}) x = g.observe() new_shape = (x[:-2].shape[0]//g.eye_observation_size, g.eye_observation_size) print(x[:-4].reshape(new_shape)) print(x[-4:]) g.to_html() %pwd <END_...
<SYSTEM_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 what the agent is seeing
528
<ASSISTANT_TASK:> Python Code: from numpy import * v = array([1,2,3,4]) v M = array([[1, 2], [3, 4]]) M type(v), type(M) v.shape M.shape v.size, M.size shape(M) size(M) M.dtype M[0,0] = "hello" M[0,0]=5 M = array([[1, 2], [3, 4]], dtype=complex) M x = arange(0, 10, 1) # argumenti: početak, kraj, korak x # 10 nij...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Kreiranje nizova pomoću numpy modula Step2: Možemo koristiti i funkcije numpy.shape, numpy.size Step3: Koja je razlika između numpy.ndarray ti...
529
<ASSISTANT_TASK:> Python Code: import pandas as pd pd.set_option('display.max_columns', 999) import pandas.io.sql as psql # plot a figure directly on Notebook import matplotlib.pyplot as plt %matplotlib inline a = pd.read_csv("data/ADMISSIONS.csv") a.columns = map(str.lower, a.columns) a.groupby(['marital_status']).co...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Agenda Step2: Load the admissions table (2/3) Step3: Profile the table (3/3) Step4: Agenda Step5: Agenda Step6: Prepare an input text in st...
530
<ASSISTANT_TASK:> Python Code: import string import pandas as pd import numpy as np import seaborn as sns def get_random_numerical_data(size, *amplitudes): n = len(amplitudes) data = np.random.random((size, n)) * np.array(amplitudes).reshape(1, n) return pd.DataFrame(data=data, columns=pd.Series(list(strin...
<SYSTEM_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 some random data Step2: Plotting all features directly with Seaborn Step3: Changing the y-scale to log doesn't help much Step5: Plotting ...
531
<ASSISTANT_TASK:> Python Code: # Ensure compatibility with Python 2 and 3 from __future__ import print_function, division %matplotlib inline import numpy as np import matplotlib.pyplot as plt import xarray as xr import climlab from climlab import constants as const import cartopy.crs as ccrs # use cartopy to make so...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Contents Step2: Make two maps Step3: Make a contour plot of the zonal mean temperature as a function of time Step4: <a id='section2'></a> Ste...
532
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head() rides[:24*10].plot(x='dteday', y='cnt') dummy_fields = ['seas...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load and prepare the data Step2: Checking out the data Step3: Dummy variables Step4: Scaling target variables Step5: Splitting the data into...
533
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import keras from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train.shape import matplotlib.pyplot as plt %matplotlib inline randix = np.random.randint(0,60000) plt.imshow(x_train[randix]) print("Label is {...
<SYSTEM_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 us load up a sample dataset. Step6: Now construct a KNN classifier Step7: Calculate accuracy on this very small subset. Step8: Let's time...
534
<ASSISTANT_TASK:> Python Code: import pyspark from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.classification import LogisticRegressionWithSGD from pyspark.mllib.tree import DecisionTree sc = pyspark.SparkContext() raw_rdd = sc.textFile("datasets/COUNT/titanic.csv") raw_rdd.count() raw_rdd.tak...
<SYSTEM_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 create a SparkContext, the main object in the Spark API. This call may take a few seconds to return as it fires up a JVM under the cove...
535
<ASSISTANT_TASK:> Python Code: stuff = { 'apple': 1.97, 'banana': 2.99, 'cherry': 3.99, } # Common pattern of .format use: use numerical indexes for name, price in stuff.items(): print('The price of {0} is {1}.'.format(name, price)) # Common pattern of .format use: use parameter names for name, price 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: In 'The price of {0} is {1}' above, Step2: Something that sucks about the above print, Step3: It reminds me of shell syntax. For example, Step...
536
<ASSISTANT_TASK:> Python Code: import tensorflow as tf x = tf.Variable(0) x.assign(114514) <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:
537
<ASSISTANT_TASK:> Python Code: # == Basic import == # # No annoying warnings import warnings warnings.filterwarnings('ignore') # plot within the notebook %matplotlib inline import numpy as np from scipy import stats import matplotlib.pyplot as mpl def plot_guassians(loc=1, scale=2): plot the pdf and the cdf of 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: Step2: Reminder Step3: => Probability of random drawing a point within given limits [a,b]= CDF[b] - CDF[a] Step4: Note about error bars Step5: let's...
538
<ASSISTANT_TASK:> Python Code: import pandas tss = pandas.read_csv("NSQD_Res_TSS.csv") medians = ( tss.groupby(by=['parameter', 'units', 'season']) .median()['res'] .reset_index() ) medians index_cols = [ 'epa_rain_zone', 'location_code', 'station_name', 'primary_landuse', 'start_date', '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: Compute the medians for each season without dropping duplicates Step2: Compute the medians for each season after dropping duplicate records
539
<ASSISTANT_TASK:> Python Code: import gym import tensorflow as tf import numpy as np # Create the Cart-Pole game environment env = gym.make('CartPole-v0') env.reset() rewards = [] for _ in range(100): env.render() state, reward, done, info = env.step(env.action_space.sample()) # take a random action rewar...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Note Step2: We interact with the simulation through env. To show the simulation running, you can use env.render() to render one frame. Passing ...
540
<ASSISTANT_TASK:> Python Code: y = [2, 3, 1] x = np.arange(len(y)) xlabel = ['A', 'B', 'C'] plt.bar(x, y, align='center') #보통은 이 명령어를 쳐야 가운데를 기준으로 x가 정렬, 설정 없으면 left가 디폴트 plt.xticks(x, xlabel); people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') y_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(pe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: xerr 인수나 yerr 인수를 지정하면 에러 바(error bar)를 추가할 수 있다. Step2: 두 개 이상의 바 차트를 한번에 그리는 경우도 있다. Step3: 또는 bottom 인수로 바의 위치를 조정하여 겹친 바 차트(stacked bar ch...
541
<ASSISTANT_TASK:> Python Code: def area(p0, p1, p2): "Calculate the area of a triangle given three points coordinates in the format (x, y)" # Check if all the points have two coordinates if len(p0) == 2 and len(p1) == 2 and len(p2) == 2: return abs((p0[0]*(p1[1]-p2[1]) + p1[0]*(p2[1]-p0[1]) + p2[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: Step2: Exercise 06.2 (selecting data structures) Step3: Exercise 06.3 (indexing) Step4: Optional (advanced) Step5: Exercise 06.4 (dictionaries) Step...
542
<ASSISTANT_TASK:> Python Code: import importlib autograd_available = True # if automatic differentiation is available, use it try: import autograd except ImportError: autograd_available = False pass if autograd_available: import autograd.numpy as np from autograd import elementwise_grad as egrad...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Specify the function to minimize as a simple python function.<br> Step2: Plot the function and its derivative Step3: Simple gradient descent s...
543
<ASSISTANT_TASK:> Python Code: from sklearn import datasets import pandas as pd from sklearn.datasets import load_digits digits = load_digits() #dataset de clasificacion brio= pd.read_csv('C:/Users/Alex/Documents/eafit/semestres/X semestre/programacion/briofitos.csv') #dataset regresion #digits.DESCR digits.target 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: Brio es un dataframe que entrega informacion de numero promedio y numero total de especies de briofitos que se encuentran a lo largo de un gradi...
544
<ASSISTANT_TASK:> Python Code: from dx import * import seaborn as sns; sns.set() # constant short rate r = constant_short_rate('r', 0.02) # market environments me_gbm = market_environment('gbm', dt.datetime(2015, 1, 1)) me_jd = market_environment('jd', dt.datetime(2015, 1, 1)) me_sv = market_environment('sv', dt.date...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Risk Factors Step2: Three risk factors ares modeled Step3: Assumptions for the geometric_brownian_motion object. Step4: Assumptions for the j...
545
<ASSISTANT_TASK:> Python Code: from nltk.corpus import stopwords as nltk_stop_words from nltk.corpus import words from sklearn.feature_extraction.text import CountVectorizer from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression #from sklearn.model_selection import cross_val_score fr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Определим необходимые функции. Step2: Обучение и классификация выбранным классификатором, сохранение результатов в файл с временной меткой в н...
546
<ASSISTANT_TASK:> Python Code: import os import pandas as pd from google.cloud import bigquery PROJECT = !(gcloud config get-value core/project) PROJECT = PROJECT[0] BUCKET = PROJECT # defaults to PROJECT REGION = "us-central1" # Replace with your REGION os.environ["PROJECT"] = PROJECT os.environ["BUCKET"] = BUCKET ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Replace the variable values in the cell below. Note, AutoML can only be run in the regions where it is available. Step2: Create a Dataset from ...
547
<ASSISTANT_TASK:> Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG ! pip3 install -U google-cloud-storage $USER_FLAG ! pip3 install $USER_FLAG kfp go...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Install the latest GA version of google-cloud-pipeline-components...
548
<ASSISTANT_TASK:> Python Code: import os import sys import urllib2 import collections import matplotlib.pyplot as plt import math from time import time, sleep %pylab inline spark_home = os.environ.get('SPARK_HOME', None) if not spark_home: raise ValueError("Please set SPARK_HOME environment variable!") # Add 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: Prepare the pySpark Environment Step2: Initialize Spark Context Step3: Load and Analyse Data Step4: Ratings Histogram Step5: Most popular mo...
549
<ASSISTANT_TASK:> Python Code: ## Import libraries necessary for monitor data processing. ## from matplotlib import pyplot as plt import numpy as np import os import pandas as pd import pickle from spins.invdes.problem_graph import log_tools ## Define filenames. ## # `save_folder` is the full path to the directory cont...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Option 1 Step2: Option 2 Step3: Option 3
550
<ASSISTANT_TASK:> Python Code: import graphlab products = graphlab.SFrame('amazon_baby_subset.gl/') products.head() products['sentiment'] products.head(10)['name'] print '# of positive reviews =', len(products[products['sentiment']==1]) print '# of negative reviews =', len(products[products['sentiment']==-1]) 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: Load review dataset Step2: One column of this dataset is 'sentiment', corresponding to the class label with +1 indicating a review with positiv...
551
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import networkx as nx Gu = nx.Graph() for i, j in [(1, 2), (1, 4), (4, 2), (4, 3)]: Gu.add_edge(i,j) nx.draw(Gu, with_labels = True) import networkx as nx Gd = nx.DiGraph() for i, j in [(1, 2), (1, 4), (4, 2), (4, 3)]: Gd.add_edg...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Directed Step2: <img src = './img/networks.png' width = 1000> Step3: Undirected network Step4: Directed network Step5: For a sample of N val...
552
<ASSISTANT_TASK:> Python Code: choice = raw_input("Choose option 1, 2, or 3: ") #prompts user to input something on the command line, saves it in a variable. see below! if (choice == "1"): print "You have chosen option 1: cake" elif (choice == "2"): print "You have chosen option 2: ice cream" elif (choice == "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: Nested if/else
553
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np import pandas as pd def make_data(N, f=0.3, rseed=1087): rand = np.random.RandomState(rseed) x = rand.randn(N) x[int(f*N):] += 5 return x x = make_data(1000) hist = plt...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Motivation for KDE - Histograms Step2: Standard count-based histogram can be viewed from the plt.hist() function. normed parameter of this func...
554
<ASSISTANT_TASK:> Python Code: def findSum(n , a , b ) : sum = 0 for i in range(0 , n , 1 ) : if(i % a == 0 or i % b == 0 ) : sum += i   return sum  if __name__== ' __main __' : n = 10 a = 3 b = 5 print(findSum(n , a , b ) )  <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:
555
<ASSISTANT_TASK:> Python Code: from systemml import MLContext, dml, jvm_stdout ml = MLContext(sc) print (ml.buildTime()) prog = holdOut = 1/3 kFolds = 1/holdOut nRows = 6; nCols = 3; X = matrix(seq(1, nRows * nCols), rows = nRows, cols = nCols) # X data y = matrix(seq(1, nRows), rows = nRows, cols = 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: Step2: Cross Validation<a id="CrossValidation" /> Step4: Value-based join of two Matrices<a id="JoinMatrices"/> Step6: Filter Matrix to include only ...
556
<ASSISTANT_TASK:> Python Code: import datetime print( "packages imported at " + str( datetime.datetime.now() ) ) %pwd %ls %run ../django_init.py from context_text.models import Article # how many articles in "grp_month"? article_qs = Article.objects.filter( tags__name__in = [ "grp_month" ] ) grp_month_count = article...
<SYSTEM_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 - virtualenv jupyter kernel Step2: Data characterization Step3: Reliability data creation - prelim_month Step4: Example snapshot of con...
557
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import pymc3 as pm from pymc3.gp.util import plot_gp_dist import theano.tensor as tt import matplotlib.pyplot as plt import seaborn as sns sns.set_style('dark') seasonal_pitch_raw = pd.read_csv('../private_data/seasonal_pitch_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: Data import and cleaning Step2: The data are messed up; name fields contain commas in a comma-separated file so two extra columns are created. ...
558
<ASSISTANT_TASK:> Python Code: # Ejemplo de lista, los valores van entre corchetes una_lista = [4, "Hola", 6.0, 99 ] # Ejemplo de tupla, los valores van entre paréntesis una_tupla = (4, "Hola", 6.0, 99) print ("Lista: " , una_lista) print ("Tupla: " , una_tupla) # Las tuplas y las listas aceptan operadores de comparaci...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <br /> Step2: Los elementos de las secuencias, tanto listas como tuplas, son hetereogéneos, así que es posible definir listas que contienen val...
559
<ASSISTANT_TASK:> Python Code: import os import datetime import numpy import scipy.signal from astropy.io import fits import matplotlib.pyplot as plt import matplotlib.dates as md %matplotlib inline paths = ['/home/roman/mnt/server-space/storage/bolidozor/ZVPP/ZVPP-R6/snapshots/2017/09/'] times = numpy.ndarray((0,2))...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: SYSDATE1 Step2: Plotter Step3: <br>
560
<ASSISTANT_TASK:> Python Code: import boto3 import pandas as pd import numpy as np import matplotlib.pyplot as plt import io import os import sys import time import json from IPython.display import display from time import strftime, gmtime import sagemaker from sagemaker.predictor import csv_serializer from sagemaker 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: Now let's set the S3 bucket and prefix that you want to use for training and model data. This bucket should be created within the same region as...
561
<ASSISTANT_TASK:> Python Code: import music21 from music21.chord import Chord from music21.duration import Duration from music21.instrument import Instrument from music21.note import Note, Rest from music21.stream import Stream from music21.tempo import MetronomeMark from music21.volume import Volume import os data_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: We're about to create a Note object which represents a single note and both its pitch and duration. Step2: If we have MuseScore installed, we c...
562
<ASSISTANT_TASK:> Python Code: range(0,10) x =range(0,10) type(x) start = 0 #Default stop = 20 x = range(start,stop) x x = range(start,stop,2) #Show x for num in range(10): print num for num in xrange(10): print num <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: Great! Notice how it went up to 20, but doesn't actually produce 20. Just like in indexing. What about step size? We can specify that as a third...
563
<ASSISTANT_TASK:> Python Code: import graphlab graphlab.canvas.set_target("ipynb") sf = graphlab.SFrame.read_csv("/Users/chengjun/bigdata/w15", header=False) sf dir(sf['X1']) bow = sf['X1']._count_words() type(sf['X1']) type(bow) bow.dict_has_any_keys(['limited']) bow.dict_values()[0][:20] sf['bow'] = bow type(sf['bo...
<SYSTEM_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 Data Step2: Transformations Step3: Text cleaning Step4: Topic modeling Step5: Initializing from other models Step6: Seeding the mo...
564
<ASSISTANT_TASK:> Python Code: from __future__ import absolute_import from __future__ import division from __future__ import print_function # Import data from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('data_dir', '/tmp/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: Definition of the neural network Step2: Train the network Step3: Learning exercise Step4: Extracting the test images and labels as numpy arra...
565
<ASSISTANT_TASK:> Python Code: import json import urllib.request from time import sleep def search_magazine(key='JUMPrgl', n_pages=25): 「ユニークID」「雑誌巻号ID」あるいは「雑誌コード」にkey含む雑誌を, n_pages分取得する関数です. url = 'https://mediaarts-db.bunka.go.jp/mg/api/v1/results_magazines?id=' + \ key + '&page=' ...
<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: 雑誌巻号検索結果の取得 Step3: Web APIでは,パラメータidで「ユニークID」「雑誌巻号ID」あるいは「雑誌コード」を,pageで検索結果の取得ページ番号(1ページあたり100件,デフォルトは1)を指定することができます.ここで,週刊少年ジャンプは「雑誌巻号ID」にJUMP...
566
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head() rides[:24*10].plot(x='dteday', y='cnt') dummy_fields = ['seas...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load and prepare the data Step2: Checking out the data Step3: Dummy variables Step4: Scaling target variables Step5: Splitting the data into...
567
<ASSISTANT_TASK:> Python Code: # Import numpy, pandas, linearsolve, scipy.optimize, matplotlib.pyplot import numpy as np import pandas as pd import linearsolve as ls from scipy.optimize import root,fsolve,broyden1,broyden2 import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline alpha = 0.36 beta = ...
<SYSTEM_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 parameters Step2: Compute exact steady state Step3: Linear model Step4: Nonlinear model
568
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np import statsmodels.formula.api as smf from pandas.io import wb file1 = '/users/susan/desktop/PISA/PISA2012clean.csv' # file location df1 = pd.read_csv(file1) #pandas remote data access API for 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: Creating the Dataset Step2: Excluding Outliers Step3: Plotting the Data Step4: Regression Analysis
569
<ASSISTANT_TASK:> Python Code: [telepyth] token = 3916589616287113937 import telepyth %telepyth 'line magic' %%telepyth 'cell magic' 'some code here' %telepyth %%telepyth raise Exception('in title.') raise Exception('in cell') %%telepyth ' '.join(('Title', 'message')) forty_two = '42' pi = 3.1415926 int(forty_two)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Once telepyth package is imported, it tries to load settings from .telepythrc. Step2: Actually telepyth provides both line magic and cell magic...
570
<ASSISTANT_TASK:> Python Code: # from kmapper import jupyter import kmapper as km import numpy as np from sklearn.datasets import fetch_20newsgroups from sklearn.cluster import AgglomerativeClustering from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD from sklearn...
<SYSTEM_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: Projection Step3: Mapping Step4: Interpretable inverse X Step5: Visualization
571
<ASSISTANT_TASK:> Python Code: get_ipython().magic('load_ext autoreload') get_ipython().magic('autoreload 2') import logging import matplotlib.pyplot as plt import numpy as np import os import timeit logging.basicConfig(format= "%(relativeCreated)12d [%(filename)s:%(funcName)20s():%(lineno)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: Below is a function that will compute and apply the transformation and its inverse. The underlying noise model is scaled Poisson plus Gaussian, ...
572
<ASSISTANT_TASK:> Python Code: import re # List of patterns to search for patterns = [ 'term1', 'term2' ] # Text to parse text = 'This is a string with term1, but it does not have the other term.' for pattern in patterns: print 'Searching for "%s" in: \n"%s"' % (pattern, text), #Check for match if re.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: Now we've seen that re.search() will take the pattern, scan the text, and then returns a Match object. If no pattern is found, a None is returne...
573
<ASSISTANT_TASK:> Python Code: import sys from packages.learntools.deep_learning.exercise_1 import load_my_image, apply_conv_to_image, show, print_hints # Detects light vs. dark pixels: horizontal_line_conv = [[1, 1], [-1, -1]] vertical_line_conv = [[-1, -1], [1, 1]] co...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example Convolution Step2: Vertical Line Detector Step3: Now create a list that contains your convolutions, then apply them to the image data ...
574
<ASSISTANT_TASK:> Python Code: #from IPython.core.display import display, HTML #display(HTML("<style>.container { width:95% !important; }</style>")) %%time import pandas as pd import functions as f import list_builder as lb %%time %run build_program_files sample3 %%time %run make_skeleton %%time %run standalone pre...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: RESTART kernel prior to running after any changes to spreadsheet input files... Step2: build program files Step3: generate skeleton Step4: ca...
575
<ASSISTANT_TASK:> Python Code: %pylab inline import GPyOpt from numpy.random import seed func = GPyOpt.objective_examples.experimentsNd.alpine1(input_dim=5) mixed_domain =[{'name': 'var1', 'type': 'continuous', 'domain': (-5,5),'dimensionality': 3}, {'name': 'var2', 'type': 'discrete', 'domain': (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: Now we define the domain of the function to optimize as usual. Step2: Now, we run the optimization for 20 iterations or a maximum of 60 seconds...
576
<ASSISTANT_TASK:> Python Code: !pwd dbf_path = ps.examples.get_path('NAT.dbf') print(dbf_path) csv_path = ps.examples.get_path('usjoin.csv') shp_path = ps.examples.get_path('NAT.shp') print(shp_path) f = ps.open(shp_path) f.header f.by_row(14) #gets the 14th shape from the file all_polygons = f.read() #reads in 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: PySAL has a command that it uses to get the paths of its example datasets. Let's work with a commonly-used dataset first. Step2: For the purpos...
577
<ASSISTANT_TASK:> Python Code: # Lasagne is pre-release, so it's interface is changing. # Whenever there's a backwards-incompatible change, a warning is raised. # Let's ignore these for the course of the tutorial import warnings warnings.filterwarnings('ignore', module='lasagne') import theano import theano.tensor as 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: Toy example Step2: Ingredients Step3: DenseLayer Step4: get_output Step5: Tasting Step6: Baking Step7: Real-world example (MNIST ConvNet) ...
578
<ASSISTANT_TASK:> Python Code: import gammalib import ctools import cscripts obsfile = 'obs_crab_selected.xml' select = ctools.ctselect() select['usethres'] = 'DEFAULT' select['inobs'] = '$HESSDATA/obs/obs_crab.xml' select['emin'] = 'INDEF' # no manual energy selection select['rad'] = 2 # by default selec...
<SYSTEM_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 step of your analysis consists in selecting the relevant events from the observations. In this step you can select a specific energy r...
579
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('..') from twords.twords import Twords import matplotlib.pyplot as plt %matplotlib inline import pandas as pd # this pandas line makes the dataframe display all text in a line; useful for seeing entire tweets pd.set_option('display.max_colwidth', -1) twit_mars ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Collect Tweets by search term Step2: Collect Tweets from user Step3: If you want to sort the tweets by retweets or favorites, you'll need to c...
580
<ASSISTANT_TASK:> Python Code: # Data for manual OHE # Note: the first data point does not include any value for the optional third feature #from pyspark import SparkContext #sc =SparkContext() sampleOne = [(0, 'mouse'), (1, 'black')] sampleTwo = [(0, 'cat'), (1, 'tabby'), (2, 'mouse')] sampleThree = [(0, 'bear'), (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: (1b) Vetores Esparsos Step2: (1c) Atributos OHE como vetores esparsos Step4: (1d) Função de codificação OHE Step5: (1e) Aplicar OHE em uma...
581
<ASSISTANT_TASK:> Python Code: class DoppelDict(dict): def __setitem__(self, key, value): super().__setitem__(key, [value] * 2) dd = DoppelDict(one=1) dd # 继承 dict 的 __init__ 方法忽略了我们覆盖的 __setitem__方法,'one' 值没有重复 dd['two'] = 2 # `[]` 运算符会调用我们覆盖的 __setitem__ 方法 dd dd.update(three=3) #继承自 dict 的 update 方法也不会调用...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 原生类型的这种行为违背了面向对象编程的一个基本原则:始终应该从实例(self)所属的类开始搜索方法,即使在超类实现的类中调用也是如此。在这种糟糕的局面中,__missing__ 却能按照预期工作(3.4 节),但这是特例 Step2: 直接子类化内置类型(如 dict,list,str...
582
<ASSISTANT_TASK:> Python Code: # Import deriva modules and pandas DataFrame (for use in examples only) from deriva.core import ErmrestCatalog, get_credential from pandas import DataFrame # Connect with the deriva catalog protocol = 'https' hostname = 'www.facebase.org' catalog_number = 1 credential = None # If you need...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Implicit DataPaths Step2: DataPath-like methods Step3: It is important to remember that the attributes(...) method returns a result set based ...
583
<ASSISTANT_TASK:> Python Code: # Authors: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import mne from mne.datasets import sample from mne.minimum_norm import (make_inverse_resolution_matrix, get_cross_talk, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Visualize Step2: CTF
584
<ASSISTANT_TASK:> Python Code: %config InlineBackend.figure_format = "retina" from matplotlib import rcParams rcParams["savefig.dpi"] = 100 rcParams["figure.dpi"] = 100 rcParams["font.size"] = 20 import numpy as np def log_prob(x, mu, cov): diff = x - mu return -0.5 * np.dot(diff, np.linalg.solve(cov, diff)) ...
<SYSTEM_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 easiest way to get started with using emcee is to use it for a project. To get you started, here’s an annotated, fully-functional example th...
585
<ASSISTANT_TASK:> Python Code: ## from __future__ import print_function # uncomment if using python 2 from os.path import join import pandas as pd import numpy as np from datetime import datetime %matplotlib inline url = 'http://casas.wsu.edu/datasets/twor.2009.zip' zipfile = url.split('/')[-1] dirname = '.'.join(zi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set up various parameters and variables that will be used in this script Step2: Download the dataset, and unzip it using the following commands...
586
<ASSISTANT_TASK:> Python Code: !pip install -q git+https://github.com/tensorflow/docs from tensorflow import keras from tensorflow.keras import layers from tensorflow_docs.vis import embed import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import imageio batch_size = 64 num_channels = 1 num_cl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Imports Step2: Constants and hyperparameters Step3: Loading the MNIST dataset and preprocessing it Step4: Calculating the number of input cha...
587
<ASSISTANT_TASK:> Python Code: import matplotlib as mpl mpl # I normally prototype my code in an editor + ipy terminal. # In those cases I import pyplot and numpy via import matplotlib.pyplot as plt import numpy as np # In Jupy notebooks we've got magic functions and pylab gives you pyplot as plt and numpy as np # %pyl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Where's the plot to this story? Step2: Interactive mode on or off is a preference. See how it works for your workflow. Step3: Some Simple Plot...
588
<ASSISTANT_TASK:> Python Code: # Required imports and setup from rootpy.plotting import Hist, Canvas, set_style import rootpy.plotting.root2matplotlib as rplt from root_numpy import array2hist from IPython.parallel import Client client = Client('ipcontroller-client.json', sshserver="--redacted--.unimelb.edu.au") set_st...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Write the analysis code Step2: Execute the analysis on a single local core Step3: That took about 1.5 minutes... Looking at the plot of the di...
589
<ASSISTANT_TASK:> Python Code: from pynq import Overlay from pynq.iop import Pmod_OLED from pynq.iop import PMODA ol = Overlay("base.bit") ol.download() pmod_oled = Pmod_OLED(PMODA) pmod_oled.clear() pmod_oled.write('Welcome to the\nPynq-Z1 board!') pmod_oled.clear() pmod_oled.write('Python and Zynq\nproductivity & 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: You should now see the text output on the OLED, so let's try another message Step2: Finally, capture some text from IPython shell calls and pri...
590
<ASSISTANT_TASK:> Python Code: %pylab inline import numpy as np import matplotlib.pyplot as plt #Import the curve fitter from the scipy optimize package from scipy.optimize import curve_fit #create the data to be plotted x = np.linspace(0, 2*np.pi, 300) y = np.sin(x) #Now plot it plt.plot(x,y,'b--') plt.plot(x[110:18...
<SYSTEM_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 an array of points that represent a sine curve between 0 and 2$\pi$. Step2: Plot the data over the full range as a dashed line and then ...
591
<ASSISTANT_TASK:> Python Code: def aquire_audio_data(): D, T = 4, 10000 y = np.random.normal(size=(D, T)) return y y = aquire_audio_data() start = time.perf_counter() x = wpe(y) end = time.perf_counter() print(f"Time: {end-start}") channels = 8 sampling_rate = 16000 delay = 3 iterations = 5 taps = 10 file...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example with real audio recordings Step2: Audio data Step3: iterative WPE Step4: Power spectrum
592
<ASSISTANT_TASK:> Python Code: try: from google.cloud import aiplatform except ImportError: !pip3 install -U google-cloud-aiplatform --user print("Please restart the kernel and re-run the notebook.") import os import shutil import pandas as pd import tensorflow as tf from datetime import datetime from matp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If the above command resulted in an installation, please restart the notebook kernel and re-run the notebook. Step2: Load raw data Step3: Use ...
593
<ASSISTANT_TASK:> Python Code: f = numpy.exp(1) f_hat = 2.71 # Error print "Absolute Error = ", numpy.abs(f - f_hat) print "Relative Error = ", numpy.abs(f - f_hat) / numpy.abs(f) # Precision p = 3 n = numpy.floor(numpy.log10(f_hat)) + 1 - p print "%s = %s" % (f_hat, numpy.round(10**(-n) * f_hat) * 10**n) import sympy...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Truncation Error and Taylor's Theorem Step2: Lets plot this numerically for a section of $x$. Step3: Example 2 Step5: Symbols and Definitions...
594
<ASSISTANT_TASK:> Python Code: import modeled.netconf modeled.netconf.__requires__ import modeled from modeled import member class Input(modeled.object): The input part of a Turing Machine program rule. state = member[int]() symbol = member[str]() class Output(modeled.object): The output part of 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: Step7: To install in development mode Step8: To check if the Turing Machine works, it needs an actual program. Step9: Instantiate the Turing Machine ...
595
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pycuda.gpuarray as gpuarray from pycuda.curandom import rand as curand from pycuda.compiler import SourceModule import pycuda.driver as cuda try: ctx.pop() ctx.detach() except: print ("No CTX!") cuda....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Jądro Elementwise Step3: Algorytm z pętlą wewnątrz jądra CUDA Step4: Porównanie z wersją CPU Step5: Wizualizacja wyników
596
<ASSISTANT_TASK:> Python Code: mean = np.array([0.05/252 + 0.02/252, 0.03/252 + 0.02/252]) volatility = np.array([0.2/np.sqrt(252), 0.05/np.sqrt(252)]) variance = np.power(volatility,2) correlation = np.array( [ [1, 0.25], [0.25,1] ] ) covariance = np.zeros((2,2)) for i in range(len(variance)): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Build and run ERC Strategy
597
<ASSISTANT_TASK:> Python Code: baselines= Unique cookies to view page per day: 40000 Unique cookies to click "Start free trial" per day: 3200 Enrollments per day: 660 Click-through-probability on "Start free trial": 0.08 Probability of enrolling, given click: 0.20625 Probability of payment, given enroll: 0.53 Probabili...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Overview Step2: Since we have 5000 sample cookies instead of the original 40000, we can adjust accordingly using calculate probability. For the...
598
<ASSISTANT_TASK:> Python Code: offset = [-190., -47.]*u.arcsec for ind, orbit in enumerate(orbits): midTime = (0.5*(orbit[1] - orbit[0]) + orbit[0]) sky_pos = planning.get_skyfield_position(midTime, offset, load_path='./data', parallax_correction=True) print("Orbit: {}".format(ind)) print("Orbit start:...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Loop over each orbit and correct the pointing for the same heliocentric pointing position.
599
<ASSISTANT_TASK:> Python Code: import phoebe from phoebe import u b = phoebe.default_binary() print(b.filter(qualifier='teff')) lhs = b.get_parameter(qualifier='teff', component='secondary') rhs = 0.5 * b.get_parameter(qualifier='teff', component='primary') rhs b.add_constraint(lhs, rhs) print(b.filter(qualifier='teff...
<SYSTEM_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 case, the two positional arguments to b.add_constraint must be the left-hand side of the expression (which will become the constrained p...