text_prompt
stringlengths
168
30.3k
code_prompt
stringlengths
67
124k
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ordinal Genres Step2: We add in some boolean genre classifiers to make our analysis more fine-grained. Rather than saying "we predict this vide...
<ASSISTANT_TASK:> Python Code: import pandas as pd from os import path from sklearn.ensemble import RandomForestClassifier import numpy as np from sklearn.ensemble import ExtraTreesClassifier import sklearn # Edit path if need be (shouldn't need to b/c we all have the same folder structure) CSV_PATH_1 = '../Videos/all_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Checking for skew in data Step2: Skewness Step3: Q-QPlot Step4: Through our analysis, we conclude that the only feature in the necessity of b...
<ASSISTANT_TASK:> Python Code: features.applymap(np.isreal).apply(pd.value_counts) features.apply(lambda x: stats.shapiro(x)) numeric_feats = features.dtypes[features.dtypes != "object"].index skewness = features[numeric_feats].apply(lambda x: skew(x.dropna())) #compute skewness print skewness def show_qqplot(x, dat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Arbitrary-precision floating-point arithmetic Step2: Complex function plots Step3: Use the points argument to increase the resolution. Step4: ...
<ASSISTANT_TASK:> Python Code: # import python packages here... import mpmath mpmath.plot([mpmath.cos, mpmath.sin], [-4, 4]) mpmath.plot(lambda x: mpmath.exp(x) * mpmath.li(x), [1, 4]) mpmath.cplot(lambda z: z, [-10, 10], [-10, 10]) mpmath.cplot(lambda z: z, [-10, 10], [-10, 10], points=100000) mpmath.cplot(mpmath.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: Only 10 out of 505 users are experts! Step2: Length ot text
<ASSISTANT_TASK:> Python Code: # Set up paths/ os import os import sys this_path=os.getcwd() os.chdir("../data") sys.path.insert(0, this_path) # Load datasets import pandas as pd df = pd.read_csv("MedHelp-posts.csv",index_col=0) df.head(2) df_users = pd.read_csv("MedHelp-users.csv",index_col=0) df_users.head(2) # 1 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: Draw points Step2: Initialize the 2-D Array Step3: Run the Dynamic Programming algorithm
<ASSISTANT_TASK:> Python Code: import numpy as np file = "tsp.txt" # file = "test2.txt" data = open(file, 'r').readlines() n = int(data[0]) graph = {} for i,v in enumerate(data[1:]): graph[i] = tuple(map(float, v.strip().split(" "))) dist_val = np.zeros([n,n]) for i in range(n): for k in range(n): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1) Peeking into the Data Step2: II. Preparing data Step3: 2) Getting rif of referees and grouping data by soccer player Step4: III. Unsupervi...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from IPython.display import Image import matplotlib.pyplot as plt # Import the random forest package from sklearn.ensemble import RandomForestClassifier from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score filename ="Crowd...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 2D transformations Step2: Rotation around the origin Step3: 3D transformations Step4: Rotation around the x axis Step5: Rotation around a gi...
<ASSISTANT_TASK:> Python Code: # Import directives #%pylab notebook %pylab inline pylab.rcParams['figure.figsize'] = (6, 6) #import warnings #warnings.filterwarnings('ignore') import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d from ipywidgets import interact def plot...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Import the BigBang modules as needed. These should be in your Python environment if you've installed BigBang correctly. Step2: Also, let's impo...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import bigbang.mailman as mailman import bigbang.graph as graph import bigbang.process as process from bigbang.parse import get_date reload(process) import pandas as pd import datetime import matplotlib.pyplot as plt import numpy as np import math import pytz import 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: creates in memory an object with the name "ObjectCreator". Step2: But still, it's an object, and therefore Step3: you can copy it Step4: you ...
<ASSISTANT_TASK:> Python Code: from pprint import pprint %%HTML <p style="color:red;font-size: 150%;">Classes are more than that in Python. Classes are objects too.</p> %%HTML <p style="color:red;font-size: 150%;">Yes, objects.</p> %%HTML <p style="color:red;font-size: 150%;">As soon as you use the keyword class, Pytho...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-2', 'atmos') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data Import (2005 - 2015) Step2: 2014 Data Step3: 2013 Data Step4: 2012 Data Step5: 2011 Data Step6: 2010 Data Step7: 2009 Data Step8: 20...
<ASSISTANT_TASK:> Python Code: import sys # system module import pandas as pd # data package import matplotlib.pyplot as plt # graphics module import datetime as dt # date and time module import numpy as np # foundation for pa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'messy-consortium', 'sandbox-1', 'atmos') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Notice that in the previous example, the function takes no arguments and returns nothing. It just does the task that it's supposed to. Step2: N...
<ASSISTANT_TASK:> Python Code: def hi(): print('Hello world!') hi() def cobbDouglas(A,alpha,k): ''' Computes output per worker y given A, alpha, and a value of capital per worker k Args: A (float): TFP alpha (float): Cobb-Douglas parameter ...
<SYSTEM_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: PROBLEM Step3: The Problem class has six methods. Step4: The Node class has nine methods. The first is the __init__ method. S...
<ASSISTANT_TASK:> Python Code: from search import * from notebook import psource, heatmap, gaussian_kernel, show_map, final_path_colors, display_visual, plot_NQueens # Needed to hide warnings in the matplotlib sections import warnings warnings.filterwarnings("ignore") %matplotlib inline import networkx as nx import ma...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Stars I actually observed Step2: Data for the observed stars Step3: Comparison of stars observed with Catalina Step4: Issues Step5: Possible...
<ASSISTANT_TASK:> Python Code: d = triand['dh'].data d_cut = (d > 15) & (d < 21) triand_dist = triand[d_cut] c_triand = _c_triand[d_cut] print(len(triand_dist)) plt.hist(triand_dist['<Vmag>'].data) ptf_triand = ascii.read("/Users/adrian/projects/streams/data/observing/triand.txt") ptf_c = coord.SkyCoord(ra=ptf_triand[...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Doc.sents is a generator Step2: However, you can build a sentence collection by running doc.sents and saving the result to a list Step3: <font...
<ASSISTANT_TASK:> Python Code: # Perform standard imports import spacy nlp = spacy.load('en_core_web_sm') # From Spacy Basics: doc = nlp(u'This is the first sentence. This is another sentence. This is the last sentence.') for sent in doc.sents: print(sent) print(doc[1]) print(doc.sents[1]) doc_sents = [sent for 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: Load the file, and from the file pull our the engine (which tells us what the timestep was) and the move scheme (which gives us a starting point...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function %matplotlib inline import openpathsampling as paths import numpy as np import matplotlib.pyplot as plt import os import openpathsampling.visualize as ops_vis from IPython.display import SVG # note that this log will overwrite the log from the previou...
<SYSTEM_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 previous weeks we have covered preprocessing our data, dimensionality reduction, clustering, regression and classification. This week we will...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd %matplotlib inline import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model, decomposition, datasets from sklearn.metrics import accuracy_score digits = datasets.load_digits() X_digits = dig...
<SYSTEM_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 stay practical, it is important to understand that you won't be assigning True and False values to variables as much as you will be receiving...
<ASSISTANT_TASK:> Python Code: # Declaring both Boolean values a = True b = False # Capturing True from an expression x = 2 < 3 # Capturing False from an expression y = 5 > 9 # Example of assigning None, and changing it. some_obj = None if 2 < 3: some_obj = True <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: ... and then only emits the last item in its sequence publish_last Step2: ... via multicast Step3: ... and then emits the complete sequence, e...
<ASSISTANT_TASK:> Python Code: rst(O.publish) def emit(obs): log('.........EMITTING........') sleep(0.1) obs.on_next(rand()) obs.on_completed() rst(title='Reminder: 2 subscribers on a cold stream:') s = O.create(emit) d = subs(s), subs(s.delay(100)) rst(title='Now 2 subscribers on a PUBLIS...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: There are many available Python packages providing APIs for Graphviz. In no particular order Step2: Render Step3: We can also set properties o...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import pydot # Create a graph and set defaults dot = pydot.Dot() dot.set('rankdir', 'TB') dot.set('concentrate', True) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: First, load the emission model. Step2: List the resolved wavelengths for convenience. Step3: and calculate the contribution functions. Step4: ...
<ASSISTANT_TASK:> Python Code: import os import numpy as np import pandas from scipy.optimize import curve_fit import scipy.linalg import scipy.stats from scipy.interpolate import interp1d,splev,splrep from scipy.ndimage import map_coordinates,gaussian_filter import matplotlib.pyplot as plt import matplotlib.colors fro...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: A little searching leads us to the Portland housing prices dataset that's used as an example in the lecture. We load the dataset from the CSV fi...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from sklearn.preprocessing import scale houses = pd.read_csv('house_prices.csv') plt.figure(1) plt.subplot(211) plt.xlabel('sq. feet') plt.ylabel('price (\'000)') plt.scatter(...
<SYSTEM_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 response and predictor columns Step2: Convert the number to a class Step3: Train Deep Learning model and validate on test set Step...
<ASSISTANT_TASK:> Python Code: import h2o h2o.init() import os.path PATH = os.path.expanduser("~/h2o-3/") test_df = h2o.import_file(PATH + "bigdata/laptop/mnist/test.csv.gz") train_df = h2o.import_file(PATH + "/bigdata/laptop/mnist/train.csv.gz") y = "C785" x = train_df.names[0:784] train_df[y] = train_df[y].asfactor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Sunspots Data Step2: Does our model obey the theory? Step3: This indicates a lack of fit.
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from scipy import stats import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.graphics.api import qqplot print(sm.datasets.sunspots.NOTE) dta = sm.datasets.sunspots.load_pandas().data dta.index = pd.Index(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'll use pip to install biopython Step2: Parsing Sequence Records Step3: Let's take a look at what the contents of this file look like Step4:...
<ASSISTANT_TASK:> Python Code: !curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py import conda_installer conda_installer.install() !/root/miniconda/bin/conda info -e !pip install --pre deepchem import deepchem deepchem.__version__ !pip install biopython 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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'sandbox-3', 'ocnbgchem') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Violations of graphical excellence and integrity
<ASSISTANT_TASK:> Python Code: from IPython.display import Image # Add your filename and uncomment the following line: Image(filename='bad graph.jpg') <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: 事前作成された Estimator Step2: データセット Step3: 次に、Keras と Pandas を使用して、Iris データセットをダウンロードして解析します。トレーニング用とテスト用に別々のデータセットを維持することに注意してください。 Step4: データを検...
<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: Interpolation functions and matrices Step2: The interpolation matrix is a matrix with the interpolation Step3: The local derivatives matrix is...
<ASSISTANT_TASK:> Python Code: from sympy import * init_session() def const_model(E, nu, const="plane_stress"): if const == "plane_stress": fac = E/(1 - nu**2) C = fac*Matrix([ [1, nu, 0], [nu, 1, 0], [0, 0, (1 - nu)/2]]) elif const == "plane_strain": ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: General configuration Step2: Area limits Step3: Load data Step4: Filter catalogues Step5: Additional data Step6: Sky coordinates Step7: Cl...
<ASSISTANT_TASK:> Python Code: import numpy as np from astropy.table import Table, join from astropy import units as u from astropy.coordinates import SkyCoord, search_around_sky from IPython.display import clear_output import pickle import os import sys sys.path.append("..") from mltier1 import (get_center, Field, Mul...
<SYSTEM_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 just repeat the calculations we did in the previous notebook RadiativeConvectiveEquilibrium.ipynb Step2: Stratospheric ozone Step3...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import netCDF4 as nc import climlab ncep_filename = 'air.mon.1981-2010.ltm.nc' # This will try to read the data over the internet. #ncep_url = "http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis.derive...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Instead of manually defining the graphene system with associated atomic coordinates and lattice vectors we use the build-in sisl capability of d...
<ASSISTANT_TASK:> Python Code: import sisl import numpy as np import matplotlib.pyplot as plt %matplotlib inline graphene = sisl.geom.graphene() print(graphene) H = sisl.Hamiltonian(graphene) print(H) H[0, 0] = 0.0 H[1, 1] = 0.0 H[0, 1] = -2.7 H[1, 0] = -2.7 H[0, 1, (-1, 0)] = -2.7 H[0, 1, (0, -1)] = -2.7 H[1, 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: Step3: Evanescent wave intensity Step4: Solution
<ASSISTANT_TASK:> Python Code: %matplotlib inline # %load depthprobe_ex.py import numpy as np import bornagain as ba from bornagain import deg, angstrom, nm # layer thicknesses in angstroms t_Ti = 130.0 * angstrom t_Pt = 320.0 * angstrom t_Ti_top = 100.0 * angstrom t_TiO2 = 30.0 * angstrom # beam data ai_min = 0.0 * d...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Image Classification Step2: Explore the Data Step4: Implement Preprocess Functions Step6: One-hot encode Step7: Randomize Data Step8: Check...
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' tar_gz_path = 'cifar-10-python.tar...
<SYSTEM_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 Snapshot Policy Step2: Diff all snapshots in a policy
<ASSISTANT_TASK:> Python Code: import re import time import pprint from qumulo.rest_client import RestClient rc = RestClient("qumulo.test", 8000) rc.login("admin", "*********"); def create_policy_for_diff(rc, policy_name, path='/', minutes=10): try: dets = rc.fs.get_file_attr(path=path) except: ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: This is the word list Step2: ...and this is the mapping from id to word Step3: We download the reviews using code copied from keras.datasets S...
<ASSISTANT_TASK:> Python Code: from keras.datasets import imdb idx = imdb.get_word_index() idx_arr = sorted(idx, key=idx.get) idx_arr[:10] idx2word = {v: k for k, v in idx.iteritems()} path = get_file('imdb_full.pkl', origin='https://s3.amazonaws.com/text-datasets/imdb_full.pkl', md5_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Investment Universe Step2: Run Strategy Step3: View log DataFrames Step4: Generate strategy stats - display all available stats Step5: View ...
<ASSISTANT_TASK:> Python Code: import datetime import matplotlib.pyplot as plt import pandas as pd import pinkfish as pf import strategy # Format price data. pd.options.display.float_format = '{:0.2f}'.format pd.set_option('display.max_rows', None) %matplotlib inline # Set size of inline plots '''note: rcParams can't 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: download dataset Step2: Copy files to valid and sample Step3: Arrangement files
<ASSISTANT_TASK:> Python Code: %%bash source activate root # you need to change here to your env name pip install kaggle-cli %%bash source activate root # you need to change here to your env name rm -rf data mkdir -p data pushd data kg download unzip -q train.zip unzip -q test.zip popd from glob import glob i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Text Parsing. Counting authors in a journal issue Step2: Now we scan all the text file. For each empty line we create a new entry (we'll correc...
<ASSISTANT_TASK:> Python Code: def get_val(line): Get the value after the key for a RIS formatted line >>> get_val('AU - Garcia-Pino, Abel') 'Garcia-Pino, Abel' >>> get_val('AU - Uversky, Vladimir N.') 'Uversky, Vladimir N.' >>> get_val('SP - 6933') '6933' >>> get_val('EP -...
<SYSTEM_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 Market
<ASSISTANT_TASK:> Python Code: import random as rnd class Supplier(): def __init__(self): self.wta = [] # the supplier has n quantities that they can sell # they may be willing to sell this quantity anywhere from a lower price of l # to a higher price of u def set_quantity(self,n,l,u): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The Adult Data Set is commonly used to benchmark machine learning algorithms. The goal is to use demographic features, or variables, to predict ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import pymc3 as pm import matplotlib.pyplot as plt import seaborn import warnings warnings.filterwarnings('ignore') data = pd.read_csv("data.csv", header=None, skiprows=1, names=['age', 'workclass', 'fnlwgt', 'edu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Markers Step2: Exercise 3.2 Step3: Linestyles Step4: It is a bit confusing, but the line styles mentioned above are only valid for lines. Whe...
<ASSISTANT_TASK:> Python Code: %load exercises/3.1-colors.py t = np.arange(0.0, 5.0, 0.2) plt.plot(t, t, , t, t**2, , t, t**3, ) plt.show() t = np.arange(0.0, 5.0, 0.2) plt.plot(t, t, , t, t**2, , t, t**3, ) plt.show() xs, ys = np.mgrid[:4, 9:0:-1] markers = [".", "+", ",", "x", "o", "D", "d", "", "8", "s", "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: ... and import them, along with their numerical environments, jax and numpy. Step2: Regularized OT in a nutshell Step3: To test both solvers, ...
<ASSISTANT_TASK:> Python Code: !pip install ott-jax !pip install POT # import JAX and OTT import jax import jax.numpy as jnp import ott from ott.geometry import pointcloud from ott.core import sinkhorn # import OT, from POT import numpy as np import ot # misc import matplotlib.pyplot as plt plt.rc('font', size = 20) 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: TFL レイヤーを使用した Keras モデルの作成 Step2: 必要なパッケージをインポートします。 Step3: UCI Statlog (心臓) データセットをダウンロードします。 Step4: このガイドのトレーニングに使用するデフォルト値を設定します。 Step5: ...
<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: Step2: Download the data from the source website if necessary. Step4: Read the data into a string. Step5: Build the dictionary and replace rare words...
<ASSISTANT_TASK:> Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. %matplotlib inline from __future__ import print_function import collections import math import numpy as np import os import random import tensorflow as tf import zipfile from matpl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 读取没有head的数据 Step2: 可以指定header Step3: 创建一个具有等级结构的DataFrame对象,可以添加index_col选项,数据文件格式 Step4: Regexp 解析TXT文件 Step5: 读取有字母分隔的数据 Step6: 读取文本文件跳过一...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd csvframe=pd.read_csv('myCSV_01.csv') csvframe # 也可以通过read_table来读写数据 pd.read_table('myCSV_01.csv',sep=',') pd.read_csv('myCSV_02.csv',header=None) pd.read_csv('myCSV_02.csv',names=['white','red','blue','green','animal']) pd.read_csv('myCSV_03.csv'...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Step 1 Step2: Include an exploratory visualization of the dataset Step3: Step 2 Step4: Model Architecture Step5: Train, Validate and Test th...
<ASSISTANT_TASK:> Python Code: # Load pickled data import pickle # TODO: Fill this in based on where you saved the training and testing data data_dir = "data/" training_file = data_dir + "train.p" validation_file = data_dir + "valid.p" testing_file = data_dir + "test.p" with open(training_file, mode='rb') as f: tra...
<SYSTEM_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 es similar a un arreglo de numpy(ndarray) con la excepción de que estos poseen un axis labels. Step2: Ejercicio 1 Step3: Data Frames s...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np #importar los modulos pandas y numpy con los alias convencionales from pandas import Series, DataFrame #Crear una serie desde un ndarray s = pd.Series(np.arange(0,5), index=['a', 'b', 'c', 'd', 'e']) s s.index type(s) s0 = Series(np.random.random(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: For benchmarking we will perfom a GF simulation. Step2: Simulation of a temporal GMRF with DFT Step3: Now let's build the circulant matrix for...
<ASSISTANT_TASK:> Python Code: # Load Biospytial modules and etc. %matplotlib inline import sys sys.path.append('/apps') sys.path.append('..') #sys.path.append('../../spystats') import django django.setup() import pandas as pd import matplotlib.pyplot as plt import numpy as np ## Use the ggplot style plt.style.use('ggp...
<SYSTEM_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: Convert Spark Dataframe to Pandas Dataframe Step3: Verctorize the features Step4: Fit Linear Regression Model Step5: View m...
<ASSISTANT_TASK:> Python Code: !ls -ltr /data spark df = spark.read.format("csv").option("header","true")\ .option("inferSchema","true").load("/data/Combined_Cycle_Power_Plant.csv") df.show() df.cache() df.limit(10).toPandas().head() from pyspark.ml.feature import * vectorizer = VectorAssembler() vectorizer.setInpu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Filters Step2: For Filters to be applied to a query, they must be either supplied with the query call or attached to a DataStore, more specific...
<ASSISTANT_TASK:> Python Code: from taxii2client import Collection from stix2 import CompositeDataSource, FileSystemSource, TAXIICollectionSource # create FileSystemStore fs = FileSystemSource("/tmp/stix2_source") # create TAXIICollectionSource colxn = Collection('http://127.0.0.1:5000/trustgroup1/collections/91a7b528-...
<SYSTEM_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. How Faithful is Old Faithful? Step2: Some of Old Faithful's eruptions last longer than others. When it has a long eruption, there's general...
<ASSISTANT_TASK:> Python Code: # Run this cell, but please don't change it. # These lines import the Numpy and Datascience modules. import numpy as np from datascience import * # These lines do some fancy plotting magic. import matplotlib %matplotlib inline import matplotlib.pyplot as plt plt.style.use('fivethirtyeight...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Question 1 Step2: Question 6
<ASSISTANT_TASK:> Python Code: # Load libraries # Math import numpy as np # Visualization %matplotlib notebook import matplotlib.pyplot as plt plt.rcParams.update({'figure.max_open_warning': 0}) from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy import ndimage # Print output of LFR code import subproc...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setting the requirements for a simulation Step2: Now that you have made your geometry class, time to load it up Step3: The physics list Step4:...
<ASSISTANT_TASK:> Python Code: %pylab inline from Geant4 import * from IPython.display import Image class MyDetectorConstruction(G4VUserDetectorConstruction): "My Detector Construction" def __init__(self): G4VUserDetectorConstruction.__init__(self) self.solid = {} self...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: make sure none of the phyla are NA (checking 160304 update to load_data.py Step2: Test filter and reduce functions using a high threshold, whic...
<ASSISTANT_TASK:> Python Code: import matplotlib as mpl mpl.use('TkAgg') import matplotlib.pyplot as plt %matplotlib inline import bacteriopop_utils import feature_selection_utils import load_data loaded_data = data = load_data.load_data() loaded_data.shape loaded_data[loaded_data['phylum'].isnull()].head(3) loaded_da...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Functions for Getting, Mapping, and Plotting Data Step2: Function for Basic Statistics Step3: Formulas Implemented Step4: Section 1. Statisti...
<ASSISTANT_TASK:> Python Code: import inflect # for string manipulation import numpy as np import pandas as pd import scipy as sp import scipy.stats as st import matplotlib.pyplot as plt %matplotlib inline filename = '/Users/excalibur/py/nanodegree/intro_ds/final_project/improved-dataset/turnstile_weather_v2.csv' # 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: Scipy's syntax Step2: TODO Step3: Hand write the model Step4: Automatically make the model
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import scipy.optimize plt.plot([1, 2, 3], [10, 30, 20], "o-") plt.xlabel("Unit of time (t)") plt.ylabel("Price of one unit of energy (c)") plt.title("Cost of energy on the market") plt.show(); # Price of energy on the market price = [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: seleccion utilizando los corchetes Step2: Reemplazar valores Step3: Tomar en cuenta que los cambios tambien se realizaron al arreglo original ...
<ASSISTANT_TASK:> Python Code: import numpy as np # crear un arreglo arr = np.arange(0,11) # desplegar el arreglo arr #obtener el valor del indice 8 arr[8] #obtener los valores de un rango arr[1:5] #obtener los valores de otro rango arr[0:5] # reemplazar valores en un rango determinado arr[0:5]=100 # desplegar el arr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: I-TASSER Step2: TMHMM
<ASSISTANT_TASK:> Python Code: import os import os.path as op # Step 2 itasser_download_link = 'my_download_link' # Step 3 itasser_version_number = '5.1' # Step 4 itasser_archive = itasser_download_link.split('/')[-1] os.mkdir(op.expanduser('~/software/itasser/')) os.chdir(op.expanduser('~/software/itasser/')) !wget $...
<SYSTEM_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 Classical 2D Force density equations Step2: We consider now the equilibrium of the node $i$ joining nodes $j, k, l$ through members $m, n, r$...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline NN = 6 NF = 5 MM = 5 C = np.zeros((MM, NN)) C[0, 0] = 1; C[0, 1] = -1 # element 1 C[1, 0] = 1; C[1, 2] = -1 # element 2 C[2, 0] = 1; C[2, 3] = -1 # ele...
<SYSTEM_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 libraries Step2: Configure GCP environment settings Step3: Authenticate your GCP account Step4: Build the ANN index Step5: Build the ...
<ASSISTANT_TASK:> Python Code: !pip install -q scann import tensorflow as tf import numpy as np from datetime import datetime PROJECT_ID = 'yourProject' # Change to your project. BUCKET = 'yourBucketName' # Change to the bucket you created. REGION = 'yourTrainingRegion' # Change to your AI Platform Training region. E...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Drop columns that are not important Step2: Convert string date to type date, then convert it to number of days since user became a host till da...
<ASSISTANT_TASK:> Python Code: from pymongo import MongoClient import pandas as pd from datetime import datetime client = MongoClient() client = MongoClient('localhost', 27017) db = client.airbnb cursor = db.Rawdata.find() data = pd.DataFrame(list(cursor)) data.head(1) data.columns data = data.drop("listing_url",axis=...
<SYSTEM_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 Dataset Step2: Visualize an Image sample Step3: Preprocess the Data Step4: The MNIST dataset contains grayscale images where the col...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function from numpy import random from keras.datasets import mnist # helps in loading the MNIST dataset from keras.models import Sequential from keras.layers import Input, Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Depending on the structure of the model, you need at least Step2: Reading in the data, we'll extract these values we need from the dataframe. S...
<ASSISTANT_TASK:> Python Code: import spvcm.api as spvcm #package API spvcm.both.Generic # abstract customizable class, ignores rho/lambda, equivalent to MVCM spvcm.both.MVCM # no spatial effect spvcm.both.SESE # both spatial error (SE) spvcm.both.SESMA # response-level SE, region-level spatial moving average spvcm.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: Using a dict for Series Step2: DataFrame Step3: Interpolation / filling of values when reindex (Series)
<ASSISTANT_TASK:> Python Code: import pandas as pd from pandas import Series, DataFrame series_1 = Series([-2, -1, 0, 1, 2, 3, 4, 5]) series_1 series_1.values series_1.index series_2 = Series([1, 2, 3], index=['a', 'b', 'c']) series_2 series_2.index series_2['a'] series_2[['a', 'b']] series_2[series_2 > 1] series_2 * 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: Importing network and node-specific annotation Step2: We then import node-specific annotation directly from the eXamine repository on github. T...
<ASSISTANT_TASK:> Python Code: # HTTP Client for Python import requests # Cytoscape port number PORT_NUMBER = 1234 BASE_URL = "https://raw.githubusercontent.com/ls-cwi/eXamine/master/data/" # The Base path for the CyRest API BASE = 'http://localhost:' + str(PORT_NUMBER) + '/v1/' #Helper command to call a command via HT...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Notifier Step2: As some of the loops are running hundreds of iterations per second, we should take special care of speed of updating Step3: Mo...
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 import sys import warnings warnings.filterwarnings("ignore") import torch import numpy as np from tqdm import tqdm_notebook, tqdm sys.path.append('../..') from batchflow import Notifier, Pipeline, Dataset, I, W, V, L, B from batchflow.monitor import * # ...
<SYSTEM_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 group everything by movie ID, and compute the total number of ratings (each movie's popularity) and the average rating for every movi...
<ASSISTANT_TASK:> Python Code: import pandas as pd r_cols = ['user_id', 'movie_id', 'rating'] ratings = pd.read_csv('e:/sundog-consult/udemy/datascience/ml-100k/u.data', sep='\t', names=r_cols, usecols=range(3)) ratings.head() import numpy as np movieProperties = ratings.groupby('movie_id').agg({'rating': [np.size, 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: Preparing the data Step2: Counting word frequency Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) from collections import Counter total_counts = Counter() for inde...
<SYSTEM_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 input data Step2: Add entities to energy system Step3: Optimize energy system and plot results Step4: Adding the gas sector Step5: Ad...
<ASSISTANT_TASK:> Python Code: from oemof.solph import EnergySystem import pandas as pd # initialize energy system energysystem = EnergySystem(timeindex=pd.date_range('1/1/2016', periods=168, freq='H')) # import e...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Problem 1a Step2: Something is wrong here - the choice of bin centers and number of bins suggest that there is a 0% probability that middle ag...
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_linnerud linnerud = load_linnerud() chinups = linnerud.data[:,0] fig, ax = plt.subplots() ax.hist( # complete ax.set_xlabel('chinups', fontsize=14) ax.set_ylabel('N', fontsize=14) fig.tight_layout() fig, ax = plt.subplots() ax.hist(# complete ax.hist(# ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Open and read data from the DEM Step2: If the previous two lines worked, zb should be a 2D numpy array that contains the DEM elevations. There ...
<ASSISTANT_TASK:> Python Code: from osgeo import gdal import numpy as np betasso_dem_name = '/Users/gtucker/Dev/dem_analysis_with_gdal/czo_1m_bt1.img' geo = gdal.Open(betasso_dem_name) zb = geo.ReadAsArray() zb[np.where(zb<0.0)[0],np.where(zb<0.0)[1]] = 0.0 import matplotlib.pyplot as plt %matplotlib inline plt.imsh...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Language Translation Step3: Explore the Data Step7: Implement Preprocessing Function Step9: Preprocess all the data and save it Step11: Chec...
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) view_sentence_range = (0, 10) DON'T MODIFY AN...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data Step2: Centered model Step3: Non-centered Step4: Funnel of hell
<ASSISTANT_TASK:> Python Code: %matplotlib inline import sklearn import scipy.stats as stats import scipy.optimize import matplotlib.pyplot as plt import seaborn as sns import time import numpy as np import os import pandas as pd !pip install -U pymc3>=3.8 import pymc3 as pm print(pm.__version__) import theano.tensor 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: Pendulum Step3: Now here's a version of make_system that takes a Condition object as a parameter. Step4: Let's make a System Step6: To write ...
<ASSISTANT_TASK:> Python Code: # If you want the figures to appear in the notebook, # and you want to interact with them, use # %matplotlib notebook # If you want the figures to appear in the notebook, # and you don't want to interact with them, use # %matplotlib inline # If you want the figures to appear in separate...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Control Runs Here Step2: Make a directory for saving results Step3: Load Metadata & Image Data Step4: Don't Change the lines below here Step5...
<ASSISTANT_TASK:> Python Code: from pyCHX.chx_packages import * %matplotlib notebook plt.rcParams.update({'figure.max_open_warning': 0}) plt.rcParams.update({ 'image.origin': 'lower' }) plt.rcParams.update({ 'image.interpolation': 'none' }) import pickle as cpk from pyCHX.chx_xpcs_xsvs_jupyter_V1 import * import it...
<SYSTEM_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 three buses of AC and heat carrier each Step2: Add three lines in a ring Step3: Connect the electric to the heat buses with heat pumps wit...
<ASSISTANT_TASK:> Python Code: import pypsa import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set(rc={"figure.figsize": (9, 5)}) network = pypsa.Network() for i in range(3): network.add("Bus", "electric bus {}".format(i), v_nom=20.0) network.add("Bus", "heat bus {...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <a id='tree'></a> Step2: <a id='stamp'></a> Step3: <a id='lim'></a> Step4: Sensitivity with respect to the subsample Step5: Sensitivity with...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline X_train = np.linspace(0, 1, 100) X_test = np.linspace(0, 1, 1000) @np.vectorize def target(x): return x > 0.5 Y_train = target(X_train) + np.random.randn(*X_train.shape) * 0.1 Y_test = target(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: 在python中計算cosine similarity最快的方法是什麼? Step2: 結論 Step3: logging Step4: 如果從某個module呼叫時,就用
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy import spatial def sim1(n): v1 = np.random.randint(0, 100, n) v2 = np.random.randint(0, 100, n) return 1 - spatial.distance.cosine(v1, v2) def sim2(n): v1 = np.random.randint(0, 100, n) v2 = np.random.randint(0, 100, n) return np.dot(...
<SYSTEM_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 would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps Step2: Inline Qu...
<ASSISTANT_TASK:> Python Code: # Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplotlib inline plt.rcPa...
<SYSTEM_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...
<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*30].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: <a href="http Step2: <a href="http Step3: <a href="http Step4: <a href="http Step5: <a href="http Step6: <a href="http Step7: <a href="htt...
<ASSISTANT_TASK:> Python Code: import IPython print("pyspark version:" + str(sc.version)) print("Ipython version:" + str(IPython.__version__)) # map x = sc.parallelize([1,2,3]) # sc = spark context, parallelize creates an RDD from the passed object y = x.map(lambda x: (x,x**2)) print(x.collect()) # collect copies RDD...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Importing a library akin to getting lab equipment out of a locker and setting up on bench Step2: numpy.loadtex() is a function call, runs loadt...
<ASSISTANT_TASK:> Python Code: import numpy #assuming the data file is in the data/ folder numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',') data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',') print(data) weight_kg = 55 #assigns value 55 to weight_kg print(weight_kg) #we can print to ...
<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: II. <a name="logisticregression"> Logistic regression demo Step3: We'll be using the scipy function optimize.minimize to calculate the classif...
<ASSISTANT_TASK:> Python Code: import setup_mysql_database import numpy as np # numerical libraries import scipy as sp import pandas as pd # for data analysis import pandas.io.sql as sql # for interfacing with MySQL database from scipy import linalg # linear algebra libraries from scipy import optimize from __future__...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: N = 4 def performQueries(l , r , prefix ) : l -= 1 r -= 1 flag = False count = 0 for i in range(26 ) : cnt = prefix[r ][i ] if(l > 0 ) : cnt -= prefix[l - 1 ][i ]  if(cnt % 2 == 1 ) : flag = True count += cnt - 1  else : count += cnt   if(flag ) : ...
<SYSTEM_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 function fixpoint2 takes two arguments
<ASSISTANT_TASK:> Python Code: def fixpoint(S0, f): Result = S0.copy() # don't change S0 while True: NewElements = { x for o in Result for x in f(o) } if NewElements.issubset(Result): return Result Result |= NewElements def 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: Положим $L=3.2$ м — длина нити, $g=9.8$ м/c — величина ускорения свободного падения, $M=3$ кг — масса балистического маятника. Step2: Посчитаем...
<ASSISTANT_TASK:> Python Code: import numpy as np import scipy as ps import pandas as pd import matplotlib.pyplot as plt %matplotlib inline data = pd.read_excel('lab-1-1.xlsx', 'table-1') data.head(len(data)) u = data.values[:, 2] print(u.mean()) print(u.std()) <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: Bioframe provides multiple methods to convert data stored in common genomic file formats to pandas dataFrames in bioframe.io. Step2: The schema...
<ASSISTANT_TASK:> Python Code: import bioframe df = bioframe.read_table( 'https://www.encodeproject.org/files/ENCFF001XKR/@@download/ENCFF001XKR.bed.gz', schema='bed9' ) display(df[0:3]) df = bioframe.read_table( "https://www.encodeproject.org/files/ENCFF401MQL/@@download/ENCFF401MQL.bed.gz", schema...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Analysis Step2: Prolog queries Step3: SQL queries Step4: ORM
<ASSISTANT_TASK:> Python Code: %load_ext noworkflow %now_set_default graph.height=200 %%now_run -e Tracer def f(x, y=3): "Calculate x!/(x - y)!" return x * f(x - 1, y - 1) if y else 1 a = 10 b = a - 2 c = f(b) print(c) trial = _ trial.dot %%now_prolog {trial.id} var_name({trial.id}, Id, 'b'), slice({trial.id}...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Vamos a crear nuestro primer ejemplo de textblob a través del objeto TextBlob. Piensa en estos textblobs como una especie de cadenas de texto de...
<ASSISTANT_TASK:> Python Code: from textblob import TextBlob texto = '''In new lawsuits brought against the ride-sharing companies Uber and Lyft, the top prosecutors in Los Angeles and San Francisco counties make an important point about the lightly regulated sharing economy. The consumers who participate deserve 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: Data is generated from a simple model Step2: We propose a minimal single hidden layer perceptron model with a single hidden unit and no bias. T...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn from torch.nn import Parameter from torch.nn.functional import mse_loss from torch.autograd import Variable from torch.nn.functional import relu def sample_from_ground_truth(n_samples=100, std=0.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: Preparing the data Step2: Counting word frequency Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) from collections import Counter total_counts = Counter() for _, r...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If you get an error stating that database "homework2" does not exist, make sure that you followed the instructions above exactly. If necessary, ...
<ASSISTANT_TASK:> Python Code: import pg8000 conn = pg8000.connect(database="homework2") conn.rollback() cursor = conn.cursor() statement = "SELECT movie_title FROM uitem WHERE scifi = 1 AND horror = 1 ORDER BY release_date DESC" cursor.execute(statement) for row in cursor: print(row[0]) cursor = conn.cursor() 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: A Convenience Function Step2: The Assignment Step3: Copy the wheat_type series slice out of X, and into a series called y. Then drop the origi...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') # Look Pretty def plotDecisionBoundary(model, X, y): fig = plt.figure() ax = fig.add_subplot(111) padding = 0.6 resolution = 0.0025 colors = ['royal...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Search for interesting rules
<ASSISTANT_TASK:> Python Code: from orangecontrib.associate.fpgrowth import * import pandas as pd from numpy import * questions = correctedScientific.columns correctedScientificText = [[] for _ in range(correctedScientific.shape[0])] for q in questions: for index in range(correctedScientific.shape[0]): r ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load the needed dataset Step2: Create the needed variables for the conversion function. Step3: Create the wide-format dataframe
<ASSISTANT_TASK:> Python Code: # To access the Travel Mode Choice data import statsmodels.datasets # To perform the dataset conversion import pylogit as pl # Access the dataset mode_data = statsmodels.datasets.modechoice.load_pandas() # Get a pandas dataframe of the mode choice data long_df = mode_data["data"] # Look ...
<SYSTEM_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. 随机变量 Random Variable Step2: 一个现实生活中的例子。一家钻井公司探索九个矿井,预计每个开采成功率为0.1;九个矿井全部开采失败的概率是多少? Step3: 将试验次数增加,可以模拟出更加逼近准确值的结果。 Step4: 5. 均匀分布 Uniform...
<ASSISTANT_TASK:> Python Code: import math import numpy as np import pandas as pd from pandas import Series, DataFrame # 引入绘图包 import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') %matplotlib inline # 投掷硬币10次,正面朝上的次数;重复100次 n, p = 10, .5 np.random.binomial(n, p, 100) sum(np.random.binomial...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Importamos las librerías creadas para trabajar Step2: Generamos los datasets de todos los días Step3: Se procesan las listas anteriores, se co...
<ASSISTANT_TASK:> Python Code: import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import ext_datos as ext import procesar as pro import time_plot as tplt dia1 = ext.extraer_data('dia1') cd .. dia2 = ext.extraer_data('dia2') cd .. dia3 = ext.extraer_data('dia3') cd .. dia4 = ext.extraer_data('dia4'...
<SYSTEM_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 table has all the ingest data from 2019-01-01 to 2020-06-01. We can now explore it grouping the data by IOOS Regional Association (RA). Step...
<ASSISTANT_TASK:> Python Code: from datetime import date from erddapy import ERDDAP server = "http://osmc.noaa.gov/erddap" e = ERDDAP(server=server, protocol="tabledap") e.dataset_id = "ioos_obs_counts" e.variables = ["time", "locationID", "region", "sponsor", "met", "wave"] e.constraints = { "time>=": "2019-09", ...