Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
7,100
<ASSISTANT_TASK:> Python Code: import os import re import psycopg2 import getpass from collections import OrderedDict # database config sqluser=getpass.getuser() # keep sqlpass blank if using peer authentication sqlpass='' # database sqldb='mimic' sqlschema='public,mimiciii' query_schema = 'set search_path to ' + sqlsc...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Benchmark all concepts in make-concepts.sql Step2: Benchmark all concepts in make-concepts.sql Step3: Compare parallel with no parallel
7,101
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import sys,os ia898path = os.path.abspath('/etc/jupyterhub/ia898_1s2017/') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia nb = ia.nbshow(2) f = mpimg...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Plotamos seu histograma e calculamos a transformação de contraste que equaliza o histograma baseado Step2: A aplicação da transformação T em f ...
7,102
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import antipackage import github.ellisonbg.misc.vizarray as va def checkerboard(size): Return a 2d checkboard of 0.0 and 1.0 as a NumPy array a = np.zeros((size,size)) a[::2,::2] = 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: Step2: Checkerboard Step3: Use vizarray to visualize a checkerboard of size=20 with a block size of 10px. Step4: Use vizarray to visualize a checkerb...
7,103
<ASSISTANT_TASK:> Python Code: import re from pyknow import * class Producto(Fact): Producto que ha comprado un cliente. >>> Producto(nombre="pepsi", tipo="refresco de cola", cantidad=1) pass class Cupon(Fact): Cupón a generar para la próxima compra del cliente. >>> Cupon(tipo="2x1",...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step5: Hechos Step8: Objetivo 1 Step9: Pruebas Step12: Objetivo 2 Step13: Pruebas Step14: Si compramos ambos productos de un pack no se nos debe g...
7,104
<ASSISTANT_TASK:> Python Code: print(9876543) name = 12345 number = 100000 print("ID before: " + str(id(number))) number = 123456 print("ID after: " + str(id(number))) number = 100000 print("ID before: " + str(id(number))) number = number + 1 print("ID after: " + str(id(number))) print(f"ID of number ({number}): " ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <p style="text-align Step2: <p style="text-align Step3: <p style="text-align Step4: <p style="text-align Step5: <p style="text-align Step6: ...
7,105
<ASSISTANT_TASK:> Python Code: import os import numpy as np import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The tutorial tut-events-vs-annotations describes in detail the Step2: Reading and writing events from/to a file Step3: When writing event arra...
7,106
<ASSISTANT_TASK:> Python Code: from nbloader import Notebook loaded_notebook = Notebook('test.ipynb') loaded_notebook.run_all() loaded_notebook.ns['a'] loaded_notebook.ns['b'] loaded_notebook.run_tag('add_one') print(loaded_notebook.ns['a']) loaded_notebook.run_tag('add_one') print(loaded_notebook.ns['a']) loaded_...
<SYSTEM_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 above commad loades a notebook as an object. This can be done inside a jupyter notebook or a regular python script. Step2: After loaded_not...
7,107
<ASSISTANT_TASK:> Python Code: import mysql.connector import pandas as pd df= pd.read_csv('C:/Users/Alex/Documents/eafit/semestres/X semestre/programacion/taller2.tsv', sep = '\t') df[:1] CREATE TABLE enfermedad ( id_enfermedad int PRIMARY KEY, nombre varchar(255) ); create table plataforma ( id_plataforma int primar...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: La idea de este taller es manipular archivos (leerlos, parsearlos y escribirlos) y hacer lo mismo con bases de datos estructuradas. Step2: Qué ...
7,108
<ASSISTANT_TASK:> Python Code: import mariadb import json with open('../credentials.json', 'r') as crd_json_fd: json_text = crd_json_fd.read() json_obj = json.loads(json_text) credentials = json_obj["Credentials"] username = credentials["username"] password = credentials["password"] table_name = "publications" ...
<SYSTEM_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. Counting publications. Step2: 3. Distinct Affiliations Step3: 3. TF-IDF and K-Means?
7,109
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import sqlite3 %matplotlib inline # Connect to the MIMIC database conn = sqlite3.connect('data/mimicdata.sqlite') # Create our test query test_query = SELECT subject_id, hadm_id, admittime, dischtime, admission_type,...
<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: Connect to the database Step4: Load the chartevents data Step5: Review the patient's heart rate Step6: In a similar way, we can select rows f...
7,110
<ASSISTANT_TASK:> Python Code: %pylab inline figsize(8, 6) import sys sys.path.insert(0, "../") import pandas import numpy from folding_group import FoldingGroupClassifier from rep.data import LabeledDataStorage from rep.report import ClassificationReport from rep.report.metrics import RocAuc from sklearn.metrics impo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Import Step2: Reading initial data Step3: Data preprocessing Step4: Define mask for non-B events Step5: Define features Step6: Test that B-...
7,111
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np df = pd.read_csv('preparation.csv',delimiter=',') df.shape !ls 59400*0.8 dftrain = pd.read_csv('preparation.csv',delimiter=',',nrows=47520) dfpayment = pd.read_csv('trainingset.csv',delimiter=',',nrows=47520) dftrain.tail() dftrain['terrain'] = '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: take 80% as train dataframe, and leave 20% as a validator/to check the accuracy of our prediction before applying the model to the real test dat...
7,112
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes import pandas as pd import metpy.calc as mpcalc from metpy.cbook import get_test_data from metpy.plots import Hodograph, SkewT from metpy.units import units col_names = ['pressure', 'height', 'te...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Getting Data Step2: Thermodynamic Calculations Step3: Basic Skew-T Plotting Step4: Advanced Skew-T Plotting Step5: Adding a Hodograph
7,113
<ASSISTANT_TASK:> Python Code: print("The answer should be three: " + str(1+2)) !nvidia-smi #imports import h5py import pandas as pd import numpy as np import pprint as pp import tensorflow as tf from tensorflow.contrib import rnn import math import matplotlib.pyplot as plt import warnings import prepareData as pr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's execute the cell below to display information about the GPUs running on the server. Step2: 2. Lab Overview Step3: Data Preparation Step4...
7,114
<ASSISTANT_TASK:> Python Code: # Loads the training and test data sets (X_train, y_train), (X_test, y_test) = mnist.load_data() first_image = X_train[0, :, :] # To interpret the values as a 28x28 image, we need to reshape # the numpy array, which is one dimensional. plt.imshow(first_image, cmap=plt.cm.Greys); num_class...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Multilayer Perceptron Step2: Different Ways to Summarize Model Step3: Train Classifier Step4: Model Evaluation Step5: Predicting a Couple of...
7,115
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier iris = load_iris() X, y = iris.data, iris.target classifier = KNeighborsClassifier() y from sklearn.model_selection import train_test_split train_X, test_X, train_y, test_y = train_test_split(X, y, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Si pensamos la forma en que normalmente se aplica el aprendizaje automático, la idea de una partición de entrenamiento y test tiene sentido. Los...
7,116
<ASSISTANT_TASK:> Python Code: from chemspipy import ChemSpider # Tip: Store your security token as an environment variable to reduce the chance of accidentally sharing it import os mytoken = os.environ['CHEMSPIDER_SECURITY_TOKEN'] cs = ChemSpider(security_token=mytoken) comp = cs.get_compound(2157) comp print(comp....
<SYSTEM_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 connect to ChemSpider by creating a ChemSpider instance using your security token Step2: All your interaction with the ChemSpider database...
7,117
<ASSISTANT_TASK:> Python Code: from google.cloud import aiplatform REGION = "us-central1" PROJECT = !(gcloud config get-value project) PROJECT = PROJECT[0] # Set `PATH` to include the directory containing KFP CLI PATH = %env PATH %env PATH=/home/jupyter/.local/bin:{PATH} %%writefile ./pipeline_vertex/pipeline_vertex_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: Step2: Understanding the pipeline design Step3: Compile the pipeline Step4: Let us make sure that the ARTIFACT_STORE has been created, and let us cre...
7,118
<ASSISTANT_TASK:> Python Code: def maxProfit(a , b , n ) : maxP = - 1 for i in range(0 , n + 1 ) : sumA = sum(a[: i ] ) sumB = sum(b[i : ] ) maxP = max(maxP , sumA + sumB )  return maxP  if __name__== "__main __": a =[2 , 3 , 2 ] b =[10 , 30 , 40 ] print(maxProfit(a , b , 4 ) )  <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:
7,119
<ASSISTANT_TASK:> Python Code: from obspy import UTCDateTime from obspy.clients.fdsn import Client as FDSN_Client from obspy import read_inventory client = FDSN_Client("GEONET") inventory = client.get_stations(latitude=-42.693,longitude=173.022,maxradius=0.5, starttime = "2016-11-13 11:05:00.000",endtime = "2016-11-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: Define GeoNet FDSN client Step2: Accessing Station Metadata Step3: The following examples dive into retrieving different information from the ...
7,120
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage from lr_utils import load_dataset %matplotlib inline # Loading the data (cat/non-cat) train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 2 - Overview of the Problem set Step2: We added "_orig" at the end of image datasets (train and test) because we are going to preprocess them. ...
7,121
<ASSISTANT_TASK:> Python Code: r = Symbol('r',positive=True) V = 1/r F = - diff(V, r) F epos = np.array([[0.0, 1.0, 0.0], [0.2, 0.3, 0.0]]) npos = np.array([[0.0, 0.0, .0]]) def compute_bare_force(npos, epos, F, r): forces = np.zeros_like(npos) for ion_idx,ion_pos in enumerate(npos): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: One solution is to smooth the contribution inside some cutoff radius $R_c$. Step2: The goal is to fit a constant function with a polynomial tha...
7,122
<ASSISTANT_TASK:> Python Code: ph_sel_name = "DexDem" data_id = "12d" # ph_sel_name = "all-ph" # data_id = "7d" from fretbursts import * init_notebook() from IPython.display import display data_dir = './data/singlespot/' import os data_dir = os.path.abspath(data_dir) + '/' assert os.path.exists(data_dir), "Path '%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 software and filenames definitions Step2: Data folder Step3: List of data files Step4: Data load Step5: Laser alternation selection Ste...
7,123
<ASSISTANT_TASK:> Python Code: %matplotlib inline import csv import io import urllib.request import matplotlib.pyplot as plt import numpy as np from datetime import datetime url = 'http://radwatch.berkeley.edu/sites/default/files/dosenet/etch_roof.csv' response = urllib.request.urlopen(url) reader = csv.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: For this example, I will bin DoseNet data from our device on the Etcheverry Roof and average the data. Afterwards, I will plot the data to show...
7,124
<ASSISTANT_TASK:> Python Code: dx = 0.3 x = np.arange(0, 10, dx) # returns [0, dx, 2dx, 3dx, 4dx, 5dx, ...] print(x) f1 = np.sin(x) f2 = x**2/100 f3 = np.log(1+x)-1 fs = [f1, f2, f3] for i in range(3): plt.plot(x, fs[i]) df1 = np.cos(x) df2 = x/50 df3 = 1/(1+x) dfs = [df1, df2, df3] def derivative(f, dx): return (...
<SYSTEM_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 us see if we can calculate these derivatives numerically. Step2: That worked pretty well, but we can do even better by using central di...
7,125
<ASSISTANT_TASK:> Python Code: class Item(object): def __init__(self, name, description, location): self.name = name self.description = description self.location = location def update_location(self, new_location): pass class Equipment(Item): pass c...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step5: Composition Step6: This has the basic functionality implemented but there are some improvements we can make. Step7: The API documentation for...
7,126
<ASSISTANT_TASK:> Python Code: %reload_ext watermark %watermark -p networkx import networkx as nx from networkx.algorithms.community import k_clique_communities, girvan_newman import matplotlib.pyplot as plt %matplotlib inline GA = nx.read_gexf('../data/ga_graph.gexf') gn_comm = girvan_newman(GA) first_iteration_comm ...
<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: Girvan Newman Algorithm Step3: K-Clique Communities Step4: Karate Club Time Step5: Validation
7,127
<ASSISTANT_TASK:> Python Code: !pip install --user apache-beam[gcp] import os import googleapiclient.discovery import shutil from google.cloud import bigquery from matplotlib import pyplot as plt import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras.callbacks import TensorBoard ...
<SYSTEM_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 the kernel before proceeding further (On the Notebook menu - Kernel - Restart Kernel). Step2: Re-train our model with trips_last_5min f...
7,128
<ASSISTANT_TASK:> Python Code: import gzip import cPickle as pickle with gzip.open("../data/train.pklz", "rb") as train_file: train_set = pickle.load(train_file) with gzip.open("../data/test.pklz", "rb") as test_file: test_set = pickle.load(test_file) with gzip.open("../data/questions.pklz", "rb") as questions_...
<SYSTEM_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 training set Step2: It means that user 0 tried to solve question number 1 which has 77 tokens for question and he or she answered at 61st ...
7,129
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import numpy as np import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, source_induced_power print(__doc__) 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: Set parameters
7,130
<ASSISTANT_TASK:> Python Code: import kfp import kfp.gcp as gcp import kfp.dsl as dsl import kfp.compiler as compiler import kfp.components as comp import datetime import kubernetes as k8s # Required Parameters PROJECT_ID='<ADD GCP PROJECT HERE>' GCS_BUCKET='gs://<ADD STORAGE LOCATION HERE>' # Optional Parameters, but...
<SYSTEM_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 client Step2: Writing the program code Step3: Create a Docker container Step4: Build docker image Step5: If you want to use docker to...
7,131
<ASSISTANT_TASK:> Python Code: test_data_df.head() train_data_df.Sentiment.value_counts() import numpy as np np.mean([len(s.split(" ")) for s in train_data_df.Text]) import re, nltk from sklearn.feature_extraction.text import CountVectorizer from nltk.stem.porter import PorterStemmer stemmer = PorterStemmer...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's count how many labels do we have for each sentiment class. Step2: Finally, let's calculate the average number of words per sentence. We c...
7,132
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact def char_probs(s): Find the probabilities of the unique characters in the string s. Parameters ---------- s : str A string of characters. ...
<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: Character counting and entropy Step4: The entropy is a quantiative measure of the disorder of a probability distribution. It is used extensivel...
7,133
<ASSISTANT_TASK:> Python Code: from siphon.simplewebservice.ndbc import NDBC data_types = NDBC.buoy_data_types('46042') print(data_types) df = NDBC.realtime_observations('46042') df.tail() df = df.dropna(axis='columns', how='all') df.head() # Your code goes here # supl_obs = # %load solutions/get_obs.py import pan...
<SYSTEM_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, we'll just stick with the standard meteorological data. The "realtime" data from NDBC contains approximately 45 days of data from ...
7,134
<ASSISTANT_TASK:> Python Code: %matplotlib inline import sys sys.path.append('../..') from matplotlib import pylab pylab.rcParams['figure.figsize'] = 16, 10 import functools import numpy import scipy import scipy.special import time from crocodile.clean import * from crocodile.synthesis import * from crocodile.simulate...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Generate baseline coordinates for an observation with the VLA over 6 hours, with a visibility recorded every 10 minutes. The phase center is fix...
7,135
<ASSISTANT_TASK:> Python Code: import QuantLib as ql import matplotlib.pyplot as plt %matplotlib inline ql.__version__ # option data maturity_date = ql.Date(15, 1, 2016) spot_price = 127.62 strike_price = 130 volatility = 0.20 # the historical vols or implied vols dividend_rate = 0.0163 option_type = ql.Option.Call ...
<SYSTEM_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 consider a European and an American call option for AAPL with a strike price of \$130 maturing on 15th Jan, 2016. Let the spot price be \...
7,136
<ASSISTANT_TASK:> Python Code: from __future__ import print_function # only need this line for Python 2.7 ... by importing print() we also get support for unpacking within print # * for unpacking is not recognized in this context in Python 2.7 normally # arguments on print and behavior of print in this exam...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: As a point of curiosity though ... how would we do it using math instead of relying on print tricks which probably convert the numbers to string...
7,137
<ASSISTANT_TASK:> Python Code: from osgeo import gdal import numpy as np import matplotlib.pyplot as plt %matplotlib inline import warnings warnings.filterwarnings('ignore') # %load ../neon_aop_python_functions/raster2array.py # raster2array.py reads in the first band of geotif file and returns an array and associated...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We also need to import the following functions created in previous lessons Step2: Calculate Hillshade Step3: Now that we have a function to ge...
7,138
<ASSISTANT_TASK:> Python Code: %reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.io import * from fastai.conv_learner import * from fastai.column_data import * # PATH = Path('data/nietzsche/') PATH = 'data/nietzsche/' get_data("https://s3.amazonaws.com/text-datasets/nietzsche.txt", f'{PATH}nietzsche....
<SYSTEM_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. Setup Step2: Sometimes it's useful to have a zero value in the dataset, eg Step3: Map from chars to indices and back again Step4: idx will...
7,139
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.2,<2.3" %matplotlib inline import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_binary() times1 = np.linspace(0,1,201) times2 = np.linspace(90,91,201) b.add_dataset('lc', time...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: As always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details. Step2: Now we'll create empty lc...
7,140
<ASSISTANT_TASK:> Python Code: import ee from IPython import display import math from matplotlib import pyplot import numpy from osgeo import gdal import tempfile import tensorflow as tf import urllib import zipfile ee.Initialize() input_image = ee.Image('LANDSAT/LT5_L1T_TOA_FMASK/LT50100551998003CPE00') def print_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: Initialize the Earth Engine client. This assumes that you have already configured Earth Engine credentials in this Datalab instance. If not, see...
7,141
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import sygma import omega import stellab #loading the observational data module STELLAB stellab = stellab.stellab() # OMEGA parameters for MW mass_loading = 1 # How much mass is ejected from the galaxy per stellar mass formed nb_1a_per_m = 3.0e-3 # Nu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Simulation of the Milky Way Step2: Comparison of chemical evolution prediction with observation Step3: Tracing back to simple stellar populati...
7,142
<ASSISTANT_TASK:> Python Code: a = 5 b = a + 3.1415 c = a / b print(a, b, c) s = 'Ice cream' # A string f = [1, 2, 3, 4] # A list d = 3.1415928 # A floating point number i = 5 # An integer b = True # A boolean value type(s) isinstance(s, str) ...
<SYSTEM_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, we did not need to declare variable types (like in fortran), we could just assign anything to a variable and it works. This is the power o...
7,143
<ASSISTANT_TASK:> Python Code: %matplotlib inline from pymc3 import * import numpy as np import matplotlib.pyplot as plt size = 200 true_intercept = 1 true_slope = 2 x = np.linspace(0, 1, size) # y = a + b*x true_regression_line = true_intercept + true_slope * x # add noise y = true_regression_line + np.random.normal...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Generating data Step2: Estimating the model Step3: This should be fairly readable for people who know probabilistic programming. However, woul...
7,144
<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: <table class="tfo-notebook-buttons" align="left"> Step2: Some imports we will need for the tutorial. We will use tensorflow_federated, the open...
7,145
<ASSISTANT_TASK:> Python Code: from flexx.webruntime import launch rt = launch('http://flexx.rtfd.org', 'xul', title='Test title') from flexx.pyscript import py2js print(py2js('square = lambda x: x**2')) def foo(n): res = [] for i in range(n): res.append(i**2) return res print(py2js(foo)) def foo(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: flexx.pyscript Step2: flexx.react Step3: A signal can have multiple upstream signals. Step4: Dynamism provides great flexibility Step5: flex...
7,146
<ASSISTANT_TASK:> Python Code: from google.colab import drive drive.mount('/content/gdrive') ! mkdir gdrive/MyDrive/rf_keras %cd gdrive/MyDrive/rf_keras ! ls ! git clone https://github.com/google-research/receptive_field.git ! ls %cd receptive_field/ ! ls ! pip install . ! pip install tensorflow import tensorflow.comp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Computing receptive field parameters of tf.keras.applications models. Step2: Bonus stuff
7,147
<ASSISTANT_TASK:> Python Code: import warnings warnings.filterwarnings('ignore') %matplotlib inline %pylab inline import matplotlib.pyplot as plt import pandas as pd print(pd.__version__) import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) print(tf.__version__) # let's see what compute devices we have av...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Loading and validating our model Step2: Descison Boundaries for 2 Dimensions Step3: Converting our Keras Model to TensorFlow.js Step4: Use th...
7,148
<ASSISTANT_TASK:> Python Code: import nltk from tethne.readers import zotero import matplotlib.pyplot as plt from nltk.corpus import stopwords import gensim import networkx as nx import pandas as pd from collections import defaultdict, Counter wordnet = nltk.WordNetLemmatizer() stemmer = nltk.SnowballStemmer('english')...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: 1.7. Finding concepts in texts - Latent Dirichlet Allocation Step3: We will represent our documents as a list of lists. Each sub-list contains ...
7,149
<ASSISTANT_TASK:> Python Code: import tensorflow as tf import numpy as np import os from collections import Counter from nltk.tokenize import TweetTokenizer import codecs from random import randint tf.__version__ with codecs.open(os.path.join('../data', 'sent.csv'), 'r', encoding='utf-8') as f: corpus_line_by_line ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Vanilla Generative Adversarial <img src="http Step3: State of art weight Initialization strategy Step4: Discriminator Step5: Generator Step6:...
7,150
<ASSISTANT_TASK:> Python Code: print("A", "B", "A|B", "A&B", "not A") for A in [False, True]: for B in [False, True]: print(A, B, A or B, A and B, not A) number = 987 rbase = 16 result = "" while number > 0: remainder = number % rbase result = str(remainder) + result number = number // rbase pr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Opdracht 2 Step2: Opdracht 3 Step3: Opdracht 4
7,151
<ASSISTANT_TASK:> Python Code: from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") %%microblaze base.PMODA #include "xparameters.h" #include "xtmrctr.h" #include "gpio.h" #include "timer.h" #include <pmod_grove.h> #define TCSR0 0x00 #define TLR0 0x04 #define TCR0 0x08 #define TCSR1 0x10 #define 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: 1. Use Microblaze to control the ultrasonic ranger Step2: 2. Do one-time distance measurement
7,152
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('../') import numpy as np from anemoi import MiniZephyr25D, SimpleSource, AnalyticalHelmholtz import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_format...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Error plots for MiniZephyr vs. the AnalyticalHelmholtz response Step2: Relative error of the MiniZephyr solution (in %)
7,153
<ASSISTANT_TASK:> Python Code: for i in range(10): print(i) for i in range(300, 306): print(i) for i in range(15, 26, 3): print(i) numbers = list(range(10)) print(numbers[3:]) words = "Be yourself; everyone else is already taken".split() for i in range(len(words)): print(words[i]) for word in 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: Here, range() will return a number of integers, starting from zero, up to (but not including) the number which we pass as an argument to the fun...
7,154
<ASSISTANT_TASK:> Python Code: %run "../Functions/1. Google form analysis.ipynb" %run "../Functions/4. User comparison.ipynb" #getAllResponders() setAnswerTemporalities(gform) # small sample #allData = getAllUserVectorData( getAllUsers( rmdf1522 )[:10] ) # complete set #allData = getAllUserVectorData( getAllUsers( rm...
<SYSTEM_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 vectors of users Step2: getAllUserVectorData Step3: Correlation Matrix Step4: List of users and their sessions Step5: List of sessions ...
7,155
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'cmcc-cm2-hr4', 'land') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "em...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
7,156
<ASSISTANT_TASK:> Python Code: # Toy Features Dictionary features = {"sq_footage": [ 1000, 2000, 3000, 4000, 5000], "house_type": ["house", "house", "apt", "apt", "townhouse"]} feat_cols = [ tf.feature_column.numeric_column('sq_footage'), tf.feature_column.indicator_column( tf.feature...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Feature Column Definition Step2: Inspect Transformed Data Step3: Excercise 1 Step4: Excercise 2 Step5: Excercise 3
7,157
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 不毛の高原 Step2: TensorFlow Quantum をインストールします。 Step3: 次に、TensorFlow とモジュールの依存関係をインポートします。 Step5: 1. 概要 Step7: ここでは、1 つのパラメータ $\theta_{1,1}$ の勾配...
7,158
<ASSISTANT_TASK:> Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG ! pip3 install -U google-cloud-storage $USER_FLAG if not os.getenv("IS_TESTING...
<SYSTEM_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: Restart the kernel Step3: Before you begin Step4: Region Step5:...
7,159
<ASSISTANT_TASK:> Python Code: import pandas as pd from datetime import datetime s = pd.Series([0.13, 0.21, 0.15, 'NaN', 0.29, 0.09, 0.24, -10], dtype='f', index = [datetime(2015,11,16,15,41,23), datetime(2015,11,16,15,42,22), datetime(2015,11,16,15,43,25), datetime(2015,11,16,15,44,20), datetime(2015...
<SYSTEM_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 Step2: As you can see, it's dealt with our missing value nicely - this is one of the nice things about Pandas. Step3: Note this also go...
7,160
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd from statsmodels.graphics.tsaplots import plot_predict from statsmodels.tsa.arima_process import arma_generate_sample from statsmodels.tsa.arima.model import ARIMA np.random.seed(12345) arparams = np.array([0.75, -0.25]) maparams ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Generate some data from an ARMA process Step2: The conventions of the arma_generate function require that we specify a 1 for the zero-lag of th...
7,161
<ASSISTANT_TASK:> Python Code: import numpy as np from pandas import date_range import bqplot.pyplot as plt from bqplot import * security_1 = np.cumsum(np.random.randn(150)) + 100. security_2 = np.cumsum(np.random.randn(150)) + 100. fig = plt.figure(title='Security 1') axes_options = {'x': {'label': 'Index'}, 'y': {'l...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Basic Line Chart Step2: We can explore the different attributes by changing each of them for the plot above Step3: In a similar way, we can al...
7,162
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np def blight_model(): # Your code here return # Your answer here df_train = pd.read_csv('train.csv', encoding = "ISO-8859-1") df_test = pd.read_csv('test.csv', encoding = "ISO-8859-1") df_train.columns list_to_remove = ['balance_due',...
<SYSTEM_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: Train, keep, test split Step3: Train a NeuralNet and see the performance
7,163
<ASSISTANT_TASK:> Python Code: reviews_test = pd.read_csv('data/reviews_test.csv', header=0, encoding='utf-8') reviews_train = pd.read_csv('data/reviews_train.csv', header=0, encoding='utf-8') X_train_raw = reviews_train.comment y_train_raw = reviews_train.reting X_test_raw = reviews_test.comment y_test_raw = reviews_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: Загрузка модели word2vec Step2: Подготовка данных Step3: Обучение модели Step4: Результаты
7,164
<ASSISTANT_TASK:> Python Code: # Share functions used in multiple notebooks %run Shared-Functions.ipynb # Load up the packages to investigate the data import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm as cm %matplotlib inline import seaborn as sns import os # OS-independent wa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: ACKNOWLEDGEMENT Step2: This means that the dataset has 97 rows and 2 columns. Let's see what the data looks like. Step3: Step 1 Step4: The co...
7,165
<ASSISTANT_TASK:> Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst !pip install tensorflow==1.15.3 import numpy as np import seaborn as sns import pandas as pd import tensorflow as tf SEQ_LEN = 10 def create_time_series(): freq = (np.random.random() * 0.5) + 0.1 # 0.1 to 0.6 ampl = 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: <h2> RNN </h2> Step2: <h3> Input Fn to read CSV </h3> Step3: Reading data using the Estimator API in tf.estimator requires an input_fn. This i...
7,166
<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) reviews.head() labels.head() from collections import Counter tota...
<SYSTEM_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...
7,167
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf %matplotlib notebook import matplotlib import matplotlib.pyplot as plt import codecs import os import collections from six.moves import cPickle from six import text_type import time from __future__ import print_function class Args(): def _...
<SYSTEM_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 needed for Jupiter Step2: Imports needed for utilities Step4: Args, to define all parameters Step5: Load the data Step6: Let's see ho...
7,168
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Keras imports from keras.models import Sequential from keras.layers import Dense, Activation from keras.optimizers import SGD # Build the model with keras model = Sequential() model.add( Dense( ou...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Defining the model with keras Step2: Training the network Step3: and define a function to look at the predictions of the model (which for the ...
7,169
<ASSISTANT_TASK:> Python Code: # Install required package (Katib SDK). !pip install kubeflow-katib==0.13.0 from kubeflow.katib import KatibClient from kubernetes.client import V1ObjectMeta from kubeflow.katib import V1beta1Experiment from kubeflow.katib import V1beta1AlgorithmSpec from kubeflow.katib import V1beta1Alg...
<SYSTEM_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 required packages Step2: Define your Experiment Step3: You can print the Experiment's info to verify it before submission. Step4: Crea...
7,170
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.dpi']=150 # Gravity Recovery and Climate Experiment (GRACE) Data # Source: http://grace.jpl.nasa.gov/ # Current surface mass change data, measuring equivalent water thickness in cm, versus time # This data fetcher use...
<SYSTEM_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 scale factor Step2: Plot EWD $\times$ scale factor
7,171
<ASSISTANT_TASK:> Python Code: from __future__ import print_function # Python 2/3 compatibility import numpy as np import pandas as pd from IPython.display import Image ## Your Turn ## Your Turn ## Choosing an Estimator # http://scikit-learn.org/stable/tutorial/machine_learning_map/index.html Image("http://sci...
<SYSTEM_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: Vectorize Step3: Model Step4: Model Tuning Step5: Feeling Good? - Let's Update Kaggle Submission Steps
7,172
<ASSISTANT_TASK:> Python Code: problem_name = "librispeech_clean" asr_problem = problems.problem(problem_name) encoders = asr_problem.feature_encoders(None) model_name = "transformer" hparams_set = "transformer_librispeech_tpu" hparams = trainer_lib.create_hparams(hparams_set,data_dir=data_dir, problem_name=problem_nam...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Define path to checkpoint Step2: Define transcribe function Step3: Decoding prerecorded examples Step5: Recording your own examples
7,173
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (15.0, 8.0) # First, we need to know what's in the data file. !head R11ceph.dat class Cepheids(object): def __init__(self,filename): # Read in the data and store it 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: A Look at Each Host Galaxy's Cepheids Step2: OK, now we are all set up! Let's plot some data.
7,174
<ASSISTANT_TASK:> Python Code: # 2001 census area units path = hp.DATA_DIR/'collected'/'Geographical Table.csv' f = pd.read_csv(path, dtype={'SAU': str}) f = f.rename(columns={ 'SAU': 'au2001', 'SAU.Desc': 'au_name', 'TA': 'territory', 'Region': 'region', }) del f['Water'] f.head() # rental area units...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Process area units and rental areas into GeoJSON Step2: Create geodata for rental areas Step3: Choose representative points for rental areas u...
7,175
<ASSISTANT_TASK:> Python Code: # we assume that we have the dynet module in your path. # OUTDATED: we also assume that LD_LIBRARY_PATH includes a pointer to where libcnn_shared.so is. from dynet import * model = Model() NUM_LAYERS=2 INPUT_DIM=50 HIDDEN_DIM=10 builder = LSTMBuilder(NUM_LAYERS, INPUT_DIM, HIDDEN_DIM, mo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: An LSTM/RNN overview Step2: Note that when we create the builder, it adds the internal RNN parameters to the model. Step3: If our LSTM/RNN was...
7,176
<ASSISTANT_TASK:> Python Code: #graphistry # To specify Graphistry account & server, use: # graphistry.register(api=3, username='...', password='...', protocol='https', server='hub.graphistry.com') # For more options, see https://github.com/graphistry/pygraphistry#configure #splunk SPLUNK = { 'host': 'SPLUNK.MYSI...
<SYSTEM_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: Helpers Step3: Splunk Step4: Bro/Zeek Step5: Graphistry Step7: Notebook intro Step9: 1. Hunting through encrypted traffic S...
7,177
<ASSISTANT_TASK:> Python Code: import pandas as pd fname = "../data/periods.csv" df = pd.read_csv(fname) df df[df.name=="Permian"].start df.loc[df.name=='Cretaceous', 'start'] = 145.0 df.loc[df.name=='Cretaceous', 'start'] df.to_csv("../data/pdout.csv") import csv with open(fname) as f: reader = csv.reader(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: We can get the start of the Permian like this Step2: Let's fix the start of the Cretaceous Step3: After you have changed or added to a DataFra...
7,178
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 # plot the predicted values and actual values (for the test data) def plot_result(test_df, pred_df, dt_col="timestamp", value_col="value", past_seq_len=1): # target column of dataframe is "value" # default past sequence length is 1 pred_valu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 0. Helper function definations Step2: 1. load data Step3: Now we download the dataset and load it into a pandas dataframe. Step4: Below are s...
7,179
<ASSISTANT_TASK:> Python Code: import numpy as np import sympy as sp from devito import * #NBVAL_IGNORE_OUTPUT from examples.seismic import Model, plot_velocity shape = (301, 501) # Number of grid point (nx, ny, nz) spacing = (10., 10) # Grid spacing in m. The domain size is now 3km by 5km origin = (0., 0) # What i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We will create a simple velocity model here by hand for demonstration purposes. This model essentially consists of three layers, each with a dif...
7,180
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) from bigmali.grid import Grid from bigmali.prior import TinkerPrior from bigmali.hyperparameter import get import numpy as np from scipy.stats import lognorm from numpy.random import norma...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Probability Functions Step3: Results Step4: Turning into Probabilistic Catalogue
7,181
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() from pyquickhelper.helpgen import NbImage NbImage("images/dicho.png") def recherche_dichotomique(element, liste_triee): a = 0 b = len(liste_triee)-1 m = (a+b)//2 while a < b : if liste_triee[m] == el...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lorsqu'on décrit n'importe quel algorithme, on évoque toujours son coût, souvent une formule de ce style Step2: Version itérative Step3: Vers...
7,182
<ASSISTANT_TASK:> Python Code: simplify(diff(x**n,x)) from sympy import * init_printing() x,n = symbols('x n') funkcije = [1,x**n,sin(x),cos(x), exp(x),log(x)] tabela = [[f,diff(f,x)] for f in funkcije] tabela from pandas import DataFrame DataFrame(tabela,columns={"$f(x)$","$f'(x)$"}) # za lepši izpis uporabimo funkci...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lepši izpis tabele dobimo, če uporabimo knjižnico za delo s tabelami in podatki Pandas. Step2: Pravila za odvajanje Step3: Naloga
7,183
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy import integrate def trapz(f, a, b, N): Integrate the function f(x) over the range [a,b] with N points. x = np.linspace(a,b,N+1) h = np.diff(x)[1] y = f(x) m = .5 * (y[1:(len(y)-1)] + y[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: Step2: Trapezoidal rule Step3: Now use scipy.integrate.quad to integrate the f and g functions and see how the result compares with your trapz functio...
7,184
<ASSISTANT_TASK:> Python Code: # Authors: Tal Linzen <linzen@nyu.edu> # Denis A. Engemann <denis.engemann@gmail.com> # Jona Sassenhagen <jona.sassenhagen@gmail.com> # # License: BSD (3-clause) import pandas as pd import mne from mne.stats import linear_regression, fdr_correction from mne.viz import pl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Psycholinguistically relevant word characteristics are continuous. I.e., Step2: We observe that there appears to be a monotonic dependence of E...
7,185
<ASSISTANT_TASK:> Python Code: data_in_shape = (3, 6) layer_0 = Input(shape=data_in_shape) layer_1 = TimeDistributed(Dense(4))(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) weights = [] for i, w in enumerate(model.get_weights()): np.random.seed(4000 +...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: [wrappers.TimeDistributed.1] wrap a Conv2D layer with 6 3x3 filters (input Step2: export for Keras.js tests
7,186
<ASSISTANT_TASK:> Python Code: import numpy as np import numpy.ma as ma from scipy.integrate import odeint mag = lambda r: np.sqrt(np.sum(np.power(r, 2))) def g(y, t, q, m, n,d, k): n: the number of particles d: the number of dimensions (for fun's sake I want this to work for k-dimensional sy...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Point Charge Dynamics Step2: Let's define our time intervals, so that odeint knows which time stamps to iterate over. Step3: Some other consta...
7,187
<ASSISTANT_TASK:> Python Code: %matplotlib inline # Import the necessary libraries import csv, os from shapely.geometry import Point, mapping import fiona, shapely from fiona import Collection import numpy as np print "fiona version: {}".format(fiona.__version__) print "shapely version: {}".format(shapely.__version__) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Reading csv and printing as dictionary Step2: Use shapely to make points Step3: Geopandas reading a geopackage Step4: Write geopandas datafra...
7,188
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import scipy.ndimage.filters as scnf import sys # Add a new path with needed .py files. sys.path.insert(0, 'C:\Users\Dominik\Documents\GitRep\kt-2015-DSPHandsOn\MedianFilter\Python') import gitInformation gitInformation.printInformation()...
<SYSTEM_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 am trying to remove white noise from the original wave with different filters. Step2: Smooth the signal with a moving averege filter. Step3: ...
7,189
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('../input') from flight_revenue_simulator import simulate_revenue, score_me def pricing_function(days_left, tickets_left, demand_level): Sample pricing function price = demand_level - 10 return price simulate_revenue(days_left=7, tickets_left=50, p...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: In case you want to check your understanding of the simulator logic, here is a simplified version of some of the key logic (leaving out the code...
7,190
<ASSISTANT_TASK:> Python Code: import pandas as pd df = pd.DataFrame([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]],columns=['A','B','C','D','E']) def g(df): df.index += 1 df_out = df.stack() df.index -= 1 df_out.index = df_out.index.map('{0[1]}_{0[0]}'.format) return df_out.to_frame().T df = g(df.copy...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
7,191
<ASSISTANT_TASK:> Python Code: # Copyright 2016 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # !pip install --upgrade google-api-python-client import io, os, subprocess, sys, time, datetime, requests, itchat from itchat.content import * from googleapiclient.discovery import build # H...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 导入需要用到的一些功能程序库: Step2: Using Google Cloud Platform's Machine Learning APIs Step3: 图片二进制base64码转换 (Define image pre-processing functions) Step4...
7,192
<ASSISTANT_TASK:> Python Code: import os import sys sys.path.append(os.environ["SPARK_HOME"] + "/python/lib/py4j-0.9-src.zip") sys.path.append(os.environ["SPARK_HOME"] + "/python/lib/pyspark.zip") from pyspark import SparkConf, SparkContext from pyspark import SparkFiles from pyspark import StorageLevel from pyspark im...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Spark does lazy evaluation. If we have a chain of transformations, Spark won't execute them untill an action is invoked. Step3: Actions S...
7,193
<ASSISTANT_TASK:> Python Code: import math import numpy as np import h5py import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.python.framework import ops from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict %matplotlib inline np.random.seed(1) y_hat = tf.constant(36, ...
<SYSTEM_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 that you have imported the library, we will walk you through its different applications. You will start with an example, where we compute fo...
7,194
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] view_sentence_range = (0, 10) DON'T MODIFY ANYTHING IN THIS CELL import num...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: TV Script Generation Step3: Explore the Data Step6: Implement Preprocessing Functions Step9: Tokenize Punctuation Step11: Preprocess all the...
7,195
<ASSISTANT_TASK:> Python Code: node1 = tf.constant(3.0, tf.float32) node2 = tf.constant(4.0) # also tf.float32 implicitly print(node1, node2) sess = tf.Session() print(sess.run([node1, node2])) a = tf.placeholder(tf.float32) b = tf.placeholder(tf.float32) adder_node = a + b # + provides a shortcut for tf.add(a, b) add...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: New functionalities
7,196
<ASSISTANT_TASK:> Python Code: %matplotlib inline import IPython.html.widgets as widgets import IPython.display as display import matplotlib.pyplot as plt import matplotlib.pylab as pylab import pandas as pd pd.set_option('display.float_format', lambda x: '%.4f' % x) pylab.rcParams['figure.figsize'] = 14, 8 pd.set_opti...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's see how the dataset is structured. Step2: Now let's plot the price, CAPE, and 1YPE data. We'll normalize the price data, adjusting for 20...
7,197
<ASSISTANT_TASK:> Python Code: # Necessary imports import os import time from nbminer.notebook_miner import NotebookMiner from nbminer.cells.cells import Cell from nbminer.features.features import Features from nbminer.stats.summary import Summary from nbminer.stats.multiple_summary import MultipleSummary from nbminer...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Combined Clustering Step2: Prediction of group
7,198
<ASSISTANT_TASK:> Python Code: import pandas import numpy as np import matplotlib.pyplot as plt df_lit = pandas.read_csv("../Data/childrens_lit.csv.bz2", sep='\t', index_col=0, encoding = 'utf-8', compression='bz2') #drop rows where the text is missing. df_lit = df_lit.dropna(subset=['text']) #view the dataframe df_lit...
<SYSTEM_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='fit'></a> Step2: <a id='dtd'></a> Step3: Merge back in with the original dataframe. Step4: Now we can sort the dataframe for the topic...
7,199
<ASSISTANT_TASK:> Python Code: data_in_shape = (5, 5, 5, 2) conv = Conv3D(4, (3,3,3), strides=(1,1,1), padding='valid', data_format='channels_last', dilation_rate=(1,1,1), activation='linear', use_bias=True) layer_0 = Input(shape=data_in_shape) layer_1 = conv(layer_0) model = Model(inputs=la...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: [convolutional.Conv3D.1] 2 3x3x3 filters on 4x4x4x2 input, strides=(1,1,1), padding='valid', data_format='channels_last', dilation_rate=(1,1,1),...