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: Grading Step2: Word embedding Step3: How to work with Google's word2vec embeddings? Step5: From word to text embeddings Step6: To check the ...
<ASSISTANT_TASK:> Python Code: import sys sys.path.append("..") from common.download_utils import download_week3_resources download_week3_resources() from grader import Grader grader = Grader() import gensim wv_embeddings = ######### YOUR CODE HERE ############# def check_embeddings(embeddings): error_text = "So...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now we move onto the ISPAQ-specific ones. Because of the directory structure and where this example lives, we need to add the main ispaq directo...
<ASSISTANT_TASK:> Python Code: import sys import os import logging import pandas as pd from obspy import UTCDateTime path_parent = os.path.dirname(os.getcwd()) sys.path.insert(1, f'{path_parent}/ispaq/') import concierge from user_request import UserRequest import PDF_aggregator logger = logging.getLogger(__name__) 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: Here we have to find the 'NaN' values and fill them with the mean. Probably it's not the best way to complete the info where we have empty value...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd #load the files train = pd.read_csv('input/train.csv') test = pd.read_csv('input/test.csv') data = pd.concat([train, test]) #size of training dataset train_samples = train.shape[0] test_samples = test.shape[0] # remove the Id feature data.drop(['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: Step 1. Step 2. Step 3. Step 4. Step1: 1.3. Descriptive Statistics Step2: 1.4. Data Cleaning Step3: 2. Implementation of machine learning pipeline....
<ASSISTANT_TASK:> Python Code: # import dependencies for creating a data frame from pyspark.sql import SparkSession from pyspark.sql import Row from pyspark.sql.types import * import csv # Create SparkSession spark = SparkSession.builder.getOrCreate() # create RDD from csv files trainRDD = spark.read.csv("hdfs://salt...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 微分 Step2: 极限 Step3: 求和 Step4: 替换 Step5: expression.subs({x Step6: 方程 Step7: sy.solve(方程,未知数) # 方程求解 ,返回值为list 方程求解 Step8: sy.roots(...
<ASSISTANT_TASK:> Python Code: sy.integrate(6*x**5, x) sy.integrate(x**3, (x, 0, 10)) #定积分 sy.integrate(6*x**5+y, x,y) #双重不定积分 sy.integrate(x**3+y, (x, -1, 1),(y,1,3) ) #双重定积分 print f(x).diff(x) sy.diff(sy.sin(x), x) # 解析微分 sy.diff(sy.sin(2*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: Nomenclature Step2: The type of an enumeration member is the enumeration it belongs to Step3: Alternative way to create an Enum
<ASSISTANT_TASK:> Python Code: from enum import Enum class MyEnum(Enum): first = 1 second = 2 third = 3 print(MyEnum.first) print(repr(MyEnum.first)) type(MyEnum.first) SecondEnum = Enum('SecondEnum', 'first, second, third') print(SecondEnum.first) <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: The focus of this post is to expand on an extremely useful, vectorizable isomorphism between indices, that comes up all the time Step2: This br...
<ASSISTANT_TASK:> Python Code: import numpy as np np.random.seed(1234) x = np.random.choice(10, replace=False, size=10) s = np.argsort(x) inverse = np.empty_like(s) inverse[s] = np.arange(len(s), dtype=int) np.all(x == inverse) # an edge index is determined by the isomorphism from # ([n] choose 2) to [n choose 2] # dr...
<SYSTEM_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 the vehicle class Step2: Define the Moment Method class Step3: Run simulation
<ASSISTANT_TASK:> Python Code: from opentire import OpenTire from opentire.Core import TireState import numpy as np import matplotlib.pyplot as plt class Vehicle(): def __init__(self): self._mass = 1000 self._wb = 1 self._wd = 0.5 self._ft = None self._rt = None @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: Liblinear, a library for large- scale linear learning focusing on SVM, is used to do the classification. It supports different solver types. Ste...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') import matplotlib.patches as patches #To import all shogun classes import modshogun as sg import numpy as np #Generate some random data X = 2 * np.random.randn(10,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: Data Exploration Step2: Question 1 - Feature Observation Step4: Answer Step5: Question 2 - Goodness of Fit Step6: Answer Step7: Question 3 ...
<ASSISTANT_TASK:> Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd from sklearn.cross_validation import ShuffleSplit # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks %matplotlib inline # Load the Boston housing 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: TFRecord and tf.train.Example Step5: tf.train.Example Step6: Note Step7: All proto messages can be serialized to a binary-string using the .S...
<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: We follow the state-action pairs formulation approach. Step2: The backward induction algorithm for finite horizon dynamic programs is offered S...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from scipy import sparse import matplotlib.pyplot as plt import quantecon as qe from quantecon.markov import DiscreteDP, backward_induction, sa_indices T = 0.5 # Time expiration (years) vol = 0.2 # Annual volatility r = 0.05 # Annual 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: DCP на примере CVXPy Step2: CVXPy Step3: Проверим решение Step4: Проверим DCP правила Step5: Autodiff на примере PyTorch'a
<ASSISTANT_TASK:> Python Code: import cvxpy as cvx import numpy as np import matplotlib.pyplot as plt %matplotlib inline print(cvx.installed_solvers()) USE_COLAB = False if USE_COLAB == False: plt.rc("text", usetex=True) n = 1000 m = 10 x_true = np.random.randn(n) x_true[np.abs(x_true) > 0.05] = 0 print("Num of nn...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Contour plots of 2d wavefunctions Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib can be used for effective visuali...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np def well2d(x, y, nx, ny, L=1.0): Compute the 2d quantum well wave function. psi = 2*np.sin(nx*np.pi*x/L)*np.sin(ny*np.pi*y/L)/L return psi psi = well2d(np.linspace(0,1,10), np.linspace(0,1,10), 1, 1) psi ps...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Quick Look at the Data Step2: Calibration Data Step3: Perspective Transform Step4: Color Thresholding Step5: Coordinate Transformations Step...
<ASSISTANT_TASK:> Python Code: %%HTML <style> code {background-color : orange !important;} </style> %matplotlib inline #%matplotlib qt # Choose %matplotlib qt to plot to an interactive window (note it may show up behind your browser) # Make some of the relevant imports import cv2 # OpenCV for perspective transform 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: Examples Step2: Example 1 Step3: Example 2 Step4: Example 3 Step5: Equation
<ASSISTANT_TASK:> Python Code: import numpy as np def dftmatrix(N): x = np.arange(N).reshape(N,1) u = x Wn = np.exp(-1j*2*np.pi/N) A = (1./np.sqrt(N)) * (Wn ** u.dot(x.T)) return A testing = (__name__ == "__main__") if testing: ! jupyter nbconvert --to python dftmatrix.ipynb import numpy as...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Filter logs for public items Step2: Make the data set manageably smaller by filtering out users with short/long review histories Step3: Load t...
<ASSISTANT_TASK:> Python Code: public_itemids = defaultdict(set) fs = [x for x in os.listdir(os.path.join('data', 'shared_decks')) if '.xml' in x] for f in fs: try: e = xml.etree.ElementTree.parse(os.path.join('data', 'shared_decks', f)).getroot() for x in e.findall('log'): public_itemid...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Bayesian optimization or sequential model-based optimization uses a surrogate model Step2: This shows the value of the two-dimensional branin f...
<ASSISTANT_TASK:> Python Code: import numpy as np np.random.seed(123) %matplotlib inline import matplotlib.pyplot as plt plt.set_cmap("viridis") from skopt.benchmarks import branin as _branin def branin(x, noise_level=0.): return _branin(x) + noise_level * np.random.randn() from matplotlib.colors import LogNorm de...
<SYSTEM_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 model run-time parameters Step2: Investigate a couple of model variables Step3: Run for a number of timesteps
<ASSISTANT_TASK:> Python Code: # First import the model. Here we use the HBV version %pylab inline from wflow.wflow_hbv import * import IPython from IPython.display import display, clear_output #clear_output = IPython.core.display.clear_output # define start and stop time of the run startTime = 1 stopTime = 200 curre...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Steppermotor ST4118S0206-A settings Step2: Max Frequency calulation Step3: Max Speed calculations Step4: Max Acceleration calculations Step5:...
<ASSISTANT_TASK:> Python Code: # Function to calculate the Bits needed fo a given number def unsigned_num_bits(num): _nbits = 1 _n = num while(_n > 1): _nbits = _nbits + 1 _n = _n / 2 return _nbits rev_distance = 0.5 # mm step_angle = 1.8 # ° # Calculation one Step step_distance = rev_distance/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: Initialize Oorb Step2: Read in some orbits. Step3: Generate ephemerides Step4: Transform orbital elements Step5: There can be larger differe...
<ASSISTANT_TASK:> Python Code: import os import numpy as np import pyoorb as oo # Initialize oorb oo.pyoorb.oorb_init() timeScales = {'UTC': 1, 'UT1': 2, 'TT': 3, 'TAI': 4} elemType = {'CART': 1, 'COM': 2, 'KEP': 3, 'DEL': 4, 'EQX': 5} # Set up some orbits # orb is id, 6 elements, epoch_mjd, H, G, element type index ...
<SYSTEM_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. Using Bio.Entrez to list available databases Step2: The variable record contains a list of the available databases at NCBI, which you can se...
<ASSISTANT_TASK:> Python Code: # This line imports the Bio.Entrez module, and makes it available # as 'Entrez'. from Bio import Entrez # The line below imports the Bio.SeqIO module, which allows reading # and writing of common bioinformatics sequence formats. from Bio import SeqIO # This line sets the variable 'Entrez....
<SYSTEM_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='svr_poly'></a> Step2: <a id='svr_rbf'></a> Step3: <a id='svr_sigmoid'></a> Step4: SVR defaults<a id='svr_defaults'></a> Step5: SVR ge...
<ASSISTANT_TASK:> Python Code: def svr_linear_config(): return { 'kernel': ('linear',), 'tol': (0.001,), # TODO add relevant range 'C': (1.0,), # ditto 'epsilon': (0.1,), # ditto 'shrinking': (True, False), 'max_iter': (-1,), # TODO add relevant range ...
<SYSTEM_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. Simple Math in the Jupyter Notebook Step2: uncomment this to download the data Step3: Loading Data with Pandas Step4: Now we can use the r...
<ASSISTANT_TASK:> Python Code: a = 1 a_list = [1, 'a', [1,2]] a_list.append(2) a_list dir(a_list) a_list.count(1) a = 2 !ls #!curl -o pronto.csv https://data.seattle.gov/api/views/tw7j-dfaw/rows.csv?accessType=DOWNLOAD import pandas as pd df = pd.read_csv('pronto.csv') df.head() df.columns df.shape df.dtypes df_...
<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: Lorenz system Step4: Write a function solve_lorenz that solves the Lorenz system above for a particular initial condition $[x(0),y(0),z(0)]$. Y...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from IPython.html.widgets import interact, fixed def lorentz_derivs(yvec, t, sigma, rho, beta): Compute the the derivatives for the Lorentz system at yvec(t). x = yvec[0] ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Correlation analysis Step2: P-value非常小,而ks statistic数值较大,认为FRI/FRII有一定的可分性。即原假设FRI/FRII的射电光学和光度服从统一分布是错误的。
<ASSISTANT_TASK:> Python Code: lumo_fr1_typical = lumo[idx2_same] * 10**-22 lumo_fr2_typical = lumo[idx3_same] * 10**-22 mag_fr1_typical = mag_abs[idx2_same] mag_fr2_typical = mag_abs[idx3_same] lumo_fr1_like = lumo[idx_fr1] * 10**-22 lumo_fr2_like = lumo[idx_fr2] * 10**-22 mag_fr1_like = mag_abs[idx_fr1] mag_fr2_like ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: train_test split Step2: QDA Step3: LDA Step4: solver Step5: NB Step6: BernoulliNB 쓸수 없음 => 타겟변수뿐만아니라 독립변수도 0또는 1값을 가져야 하기때문 Step7: Decisi...
<ASSISTANT_TASK:> Python Code: df1 = df.ix[:,0:8] df1.tail() # 박사님께서 설명을 위해 뒷부분에 컬럼을 채워놓은 것같아서 who 부터 끝까지 잘랐습니다 from sklearn.preprocessing import LabelEncoder le = LabelEncoder() df1['sex']= le.fit_transform(df1['sex']) df1['embarked'] = le.fit_transform(df1['embarked']) from sklearn.preprocessing import Imputer 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: All we need to do is
<ASSISTANT_TASK:> Python Code: # Update data # autoupdate.autoupdate() # Comment in if needed, and loop if needed # manip.get_5v5_player_log(2017, force_create) # Comment in if needed, and loop if needed log = pd.concat([manip.get_5v5_player_log(season).assign(Season=season) for season in range(2012, 2018)]) sch = pd...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Model Step2: check rates Step3: It slightly underestimates heterogeneity, but is close for max rate
<ASSISTANT_TASK:> Python Code: %matplotlib inline import ABCPRC as prc import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt def ibm(*ps): m0,k = ps[0],ps[1] T0 = 0.5 #measurements in regular increments throughout the year ms,ts = np.zeros(100),np.linspace(0,1,100) ms = (m0...
<SYSTEM_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 sgrid object Step2: The object knows about sgrid conventions Step3: Being generic is nice! This is an improvement up on my first design ;...
<ASSISTANT_TASK:> Python Code: from netCDF4 import Dataset url = ('http://geoport.whoi.edu/thredds/dodsC/clay/usgs/users/' 'jcwarner/Projects/Sandy/triple_nest/00_dir_NYB05.ncml') nc = Dataset(url) import pysgrid # The object creation is a little bit slow. Can we defer some of the loading/computations?...
<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: def findnum(s1 ) : v =[] a = 0 b = 0 sa = 0 sb = 0 i = 0 if(s1[0 ] == ' - ' ) : sa = 1 i = 1  while(s1[i ] . isdigit() ) : a = a * 10 +(int(s1[i ] ) ) i += 1  if(s1[i ] == ' + ' ) : sb = 0 i += 1  if(s1[i ] == ' - ' ) : sb = 1 i += 1  while(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: Step2: Creating the parameter file Step4: Let's describe the bands we will use. This must be a superset (ideally the union) of all the bands involved ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import scipy.stats import sys sys.path.append('../') from delight.io import * from delight.utils import * from delight.photoz_gp import PhotozGP %cd .. paramfile_txt = # DELIGHT parameter file # Syntactic rules: # - 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: Step2: Improving Reading Ability Step3: Exercise Step9: Paintball Step10: Exercise Step11: Exercise
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division % matplotlib inline import warnings warnings.filterwarnings('ignore') import math import numpy as np from thinkbayes2 import Pmf, Cdf, Suite, Joint import thinkplot import pandas as pd df = pd.read_csv('drp_scores.csv', skiprows=21, delimit...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Modo correcto de definir una función Step2: Ejemplo de uso de funciónes Step3: y se desa calcular el promedio para cada uno, una forma de hace...
<ASSISTANT_TASK:> Python Code: printfunc(3) def func(num): return(num**num+num) def func(num): return(num**num+num) func(3) alex=[90,70,80,60,90] kate=[60,70,90,70,90] david=[90,60,80,90,80] #Promedio para Alex i=0 sumatoria = 0 while i < len(alex): sumatoria += alex[i] i += 1 promedio=sumatoria...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Saving and loading fields Step2: Running the simulation Step3: (Optional) Plotting
<ASSISTANT_TASK:> Python Code: from crpropa import * randomSeed = 42 turbSpectrum = SimpleTurbulenceSpectrum(Brms=8*nG, lMin = 60*kpc, lMax=800*kpc, sIndex=5./3.) gridprops = GridProperties(Vector3d(0), 256, 30*kpc) BField = SimpleGridTurbulence(turbSpectrum, gridprops, randomSeed) # print some properties of our field ...
<SYSTEM_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 modules Step2: Target Configuration Step3: Workload Execution and Functions Profiling Data Collection Step4: Parse Trace and ...
<ASSISTANT_TASK:> Python Code: import logging from conf import LisaLogging LisaLogging.setup() # Generate plots inline %matplotlib inline import json import os # Support to access the remote target import devlib from env import TestEnv from executor import Executor # RTApp configurator for generation of PERIODIC tasks...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <table align="left"> Step2: Selection Bias Step3: The treated group has a lower outcome mean than that of the control group, but the differenc...
<ASSISTANT_TASK:> Python Code: #@title Copyright 2019 The Empirical Calibration Authors. # 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 # # ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Model Creation Step2: The model is set up by default with a meridional diffusion term. Step3: Create new subprocess Step4: Note that the mode...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import climlab from climlab import constants as const # model creation ebm_budyko = climlab.EBM() # print model states and suprocesses print(ebm_budyko) # create Budyko subprocess budyko_transp = climlab.dynamics.Bud...
<SYSTEM_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 evaluate how much the membrane potential depends on Input resistance and
<ASSISTANT_TASK:> Python Code: %pylab inline import pandas as pd #mypath = '/fs3/group/jonasgrp/MachineLearning/Cell_types.xlsx' mypath = './Cell_types.xlsx' df = pd.read_excel(io=mypath, sheetname='PFC', skiprows=1) df.head() df.columns df['CellID'] for key in df.columns: if df[key].dtype != object: print"...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Damped, driven nonlinear pendulum Step4: Write a function derivs for usage with scipy.integrate.odeint that computes the derivatives for the da...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.integrate import odeint from IPython.html.widgets import interact, fixed g = 9.81 # m/s^2 l = 0.5 # length of pendulum, in meters tmax = 50. # seconds t = np.linspace(0, tmax, int(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Genome version Step2: Products
<ASSISTANT_TASK:> Python Code: bsmaploc="/Applications/bioinfo/BSMAP/bsmap-2.74/" !curl \ ftp://ftp.ensemblgenomes.org/pub/release-32/metazoa/fasta/crassostrea_gigas/dna/Crassostrea_gigas.GCA_000297895.1.dna_sm.toplevel.fa.gz \ > /Volumes/caviar/wd/data/Crassostrea_gigas.GCAz_000297895.1.dna_sm.toplevel.fa.gz !cur...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Where in your code does this error come from? Step2: Stack trace Step3: Printing during execution Step4: Printing attributes of a variable St...
<ASSISTANT_TASK:> Python Code: import numpy as np import theano import theano.tensor as T x = T.vector() y = T.vector() z = x + x z = z * y f = theano.function([x, y], z) f(np.ones((2,)), np.ones((3,))) # TODO: finish to define the mode below mode=... import numpy as np import theano import theano.tensor as T x = T.ve...
<SYSTEM_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. Run a pre-trained Transformer Step2: 2. Features and resources Step3: Gradients can be calculated using trax.fastmath.grad. Step4: Layers ...
<ASSISTANT_TASK:> Python Code: #@title # Copyright 2020 Google LLC. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable...
<SYSTEM_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) create a vector of $d$ parameters Step2: 2) Create an array of covariates Step3: 3) Construct the conditional intensity $\lambda(t)$ Step4:...
<ASSISTANT_TASK:> Python Code: N = 10000# number of observations d = 5 # number of covariates theta = np.random.normal(size = (d,)) X = 0.1*np.random.normal(size = (d,N)) # X = linalg.orth(X.T).T # X = np.eye((d)) l = np.exp(np.dot(X.T,theta)) dt = 0.001 # discretization step u = np.random.uniform(size = len(l)) 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: ScrollZoomToggler Step2: MarkerCluster Step3: Terminator Step4: Leaflet.boatmarker Step5: Leaflet.TextPath
<ASSISTANT_TASK:> Python Code: # This is to import the repository's version of folium ; not the installed one. import sys, os sys.path.insert(0,'..') import folium from folium import plugins import numpy as np import json %load_ext autoreload %autoreload 2 m = folium.Map([45.,3.], zoom_start=4) plugins.ScrollZoomToggl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Считаем данные по росту и весу (weights_heights.csv, приложенный в задании) в объект Pandas DataFrame Step2: Чаще всего первое, что надо надо с...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline data = pd.read_csv('weights_heights.csv', index_col='Index') data.plot(y='Height', kind='hist', color='red', title='Height (inch.) distribution') data.head(n=5) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: So far the systems we have studied have been physical in the sense that they exist in the world, but they have not been physics, in the sense of...
<ASSISTANT_TASK:> Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/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: Note Step2: Lesson Step3: Project 1 Step4: We'll create three Counter objects, one for words from postive reviews, one for words from negativ...
<ASSISTANT_TASK:> Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].uppe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Are we dealing with form or metric information here? Step2: Revise and edit to best convey the scientific result.
<ASSISTANT_TASK:> Python Code: import pickle data = pickle.load(open('data/correlation_map.pkl', 'rb')) data.keys() type(data['excitation energy']) data['excitation energy'].shape data['correlation'].shape import matplotlib %matplotlib inline matplotlib.style.use('ggplot') import matplotlib.pyplot as plt plt.imshow(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: Training a multi-layer perceptron Step2: Neural networks tend to perform better when the inputs are scaled to have zero mean and unit variance....
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from scipy.special import expit from sklearn import datasets, mixture xs = np.linspace(-5, 5) fig = plt.figure(figsize=(20, 5)) ## Plot relu ax1 = fig.add_subplot(1, 3, 1) ax1.plot(xs, np.maximum(0, xs)) ## Plot sigmoid ax2 = fig.add_sub...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Wykresy punktowe Step2: Histogramy
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt fig = plt.figure(figsize=(15,10)) ax = fig.add_subplot(111) ## the data N = 5 menMeans = [18, 35, 30, 35, 27] menStd = [2, 3, 4, 1, 2] womenMeans = [25, 32, 34, 20, 25] womenStd = [3, 5, 2, 3, 3] ## necessary variab...
<SYSTEM_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 Elves in accounting are thankful for your help; one of them even offers you a starfish coin they had left over from a past vacation. They of...
<ASSISTANT_TASK:> Python Code: for a,b in itertools.permutations(list(map(int, data)), 2): if a+b == 2020: print(a*b) break for a,b,c in itertools.permutations(list(map(int, data)), 3): if a+b+c == 2020: print(a*b*c) break <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: Import section specific modules Step2: 3.3 Horizontal Coordinates (ALT,AZ) Step3: Figure 3.3.3 Step4: Figure 3.3.4
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS from IPython.display import HTML HTML('../style/code_toggle.html') import ephem import matplotlib %pylab inline pylab.rcParams['figure.fi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Bonus Material - Softmax Regression Step2: First, we want to encode the class labels into a format that we can more easily work with; we apply ...
<ASSISTANT_TASK:> Python Code: %load_ext watermark %watermark -a '' -u -d -v -p matplotlib,numpy,scipy # to install watermark just uncomment the following line: #%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py %matplotlib inline import numpy as np y = np.array([0, 1, 2, 2]) y_enc = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create a Raster Model Grid Step2: Visualize Basin topography Step3: Create a Network Model Grid Step4: Let's plot our network Step5: As are...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np # landlab modules from landlab.plot.graph import plot_nodes, plot_links from landlab.io import read_esri_ascii # Package for plotting raster data from landlab.plot.imshow import imshow_grid from landlab.grid.create_network import network_...
<SYSTEM_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 weather data Step2: Cleaning the weather dataset Step3: Merge weather and NYPD MVC datasets Step4: Make some nice data analysis Step...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import datetime from datetime import date from dateutil.rrule import rrule, DAILY from __future__ import division import geoplotlib as glp from geoplotlib.utils import BoundingBox, DataAccessObject pd.set_option('display.max_columns', None) %matplotl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setup and imports Step2: Define your indico API key Step4: Convenience function for making batches of examples Step5: Check that the requeste...
<ASSISTANT_TASK:> Python Code: seed = 3 # for reproducibility across experiments, just pick something train_num = 100 # number of training examples to use test_num = 100 # number of examples to use for testing base_model_name = "sentiment_train%s_test%s" % (train_num, test_num) lab2bin = {'pos': 1, 'neg':...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: retrieving the available fields as a reference Step2: build a field specific stop word list Step3: plotting the wordcloud for abstracts and ti...
<ASSISTANT_TASK:> Python Code: client = MongoClient('localhost:27017') db = client.arXivDB db.arXivfeeds.count() print(db.arXivfeeds.find_one().keys()) for item in db.arXivfeeds.find({'published_parsed': 2016}).sort('_id', pymongo.DESCENDING).limit(5): print(item['title']) #db.arXivfeeds.delete_many({}) def clean...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example with more savings, but slower to optimize Step2: Look at the recommendations
<ASSISTANT_TASK:> Python Code: def func(a, b, c): res = tf.einsum('ijk,ja,kb->iab', a, b, c) + 1 res = tf.einsum('iab,kb->iak', res, c) return res a = tf.random_normal((10, 11, 12)) b = tf.random_normal((11, 13)) c = tf.random_normal((12, 14)) # res = func(a, b, c) orders, optimized_func = tf_einsum_opt.opt...
<SYSTEM_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 start by creating some data that we can store. 2000 images with shape (254, 254, 3) along with 2000 targets are generated. Step2: The ten...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import time import numpy as np import pyxis as px np.random.seed(1234) nb_samples = 2000 X = np.zeros((nb_samples, 254, 254, 3), dtype=np.uint8) y = np.arange(nb_samples, dtype=np.uint8) X[10, :, :, 0] = 255 db = px.Writer(dirpath='data', map_size_...
<SYSTEM_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 information on how to configure and tune the solver, please see the documentation for optlang project and note that model.solver is simply a...
<ASSISTANT_TASK:> Python Code: import cobra.test model = cobra.test.create_test_model('textbook') model.solver = 'glpk' # or if you have cplex installed model.solver = 'cplex' type(model.solver) <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: First we'll load the text file and convert it into integers for our network to use. Step3: Now I need to split up the data into batches, and in...
<ASSISTANT_TASK:> Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf with open('anna.txt', 'r') as f: text=f.read() vocab = set(text) vocab_to_int = {c: i for i, c in enumerate(vocab)} int_to_vocab = dict(enumerate(vocab)) chars = np.array([vocab_to_int[c] for c ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1. 입력DataLoader 설정 Step2: 2. 사전 설정 Step3: 3. Trainning loop Step4: 4. Predict & Evaluate Step5: 5. save model parameter Step6: 6. plot imag...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import torch import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from torch.autograd import Variable import matplotlib.pyplot as plt import numpy as np is_cuda = torch.cuda.is_available() # cuda사 사용가능시, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We can now import the deepchem package to play with. Step2: Anatomy of a Dataset Step3: We now have three Dataset objects Step4: There's a lo...
<ASSISTANT_TASK:> Python Code: !pip install --pre deepchem import deepchem as dc dc.__version__ tasks, datasets, transformers = dc.molnet.load_delaney(featurizer='GraphConv') train_dataset, valid_dataset, test_dataset = datasets print(test_dataset) test_dataset.y for X, y, w, id in test_dataset.itersamples(): ...
<SYSTEM_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', 'bcc', 'sandbox-2', 'ocnbgchem') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "e...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load the weight matrices from the training Step2: Visualize the digit from one hot representation through the activity weight matrix to the ima...
<ASSISTANT_TASK:> Python Code: import nengo import numpy as np import cPickle import matplotlib.pyplot as plt from matplotlib import pylab import matplotlib.animation as animation #Weight matrices generated by the neural network after training #Maps the label vectors to the neuron activity of the ensemble label_weight...
<SYSTEM_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 we have a lot of speeches that are relatively short. They probably aren't the best for clustering because of their brevity
<ASSISTANT_TASK:> Python Code: !curl -O http://www.cs.cornell.edu/home/llee/data/convote/convote_v1.1.tar.gz !tar -zxvf convote_v1.1.tar.gz paths = glob.glob("convote_v1.1/data_stage_one/development_set/*") speeches = [] for path in paths: speech = {} filename = path[-26:] speech['filename'] = filename ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's load the actual data. We're going to use astropy to do that Step2: Since this is Chandra data, we know where all the relevant information...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt try: import seaborn as sns except ImportError: print("No seaborn installed. Oh well.") import numpy as np from scipy.special import gammaln as scipy_gammaln import scipy.stats import astropy.io.fits as fits import astropy.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: Exploring the dataset Step2: Based on the above exploratory commands, I believe that the following questions can be answered using the dataset ...
<ASSISTANT_TASK:> Python Code: # The first step is to import the dataset into a pandas dataframe. import pandas as pd #path = 'C:/Users/hrao/Documents/Personal/HK/Python/ml-20m/ml-20m/' path = '/Users/Harish/Documents/HK_Work/Python/ml-20m/' movies = pd.read_csv(path+'movies.csv') movies.shape tags = pd.read_csv(path+...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Webdriver Step2: 下载和设置Webdriver Step3: 访问页面 Step4: 查找元素 Step5: 这里我们通过三种不同的方式去获取响应的元素,第一种是通过id的方式,第二个中是CSS选择器,第三种是xpath选择器,结果都是相同的。 Step6: 多...
<ASSISTANT_TASK:> Python Code: !pip install selenium from selenium import webdriver help(webdriver) #browser = webdriver.Firefox() # 打开Firefox浏览器 browser = webdriver.Chrome() # 打开Chrome浏览器 from selenium import webdriver browser = webdriver.Chrome() browser.get("http://music.163.com") print(browser.page_source) #...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Flower power Step2: ConvNet Codes Step3: Below I'm running images through the VGG network in batches. Step4: Building the Classifier Step5: ...
<ASSISTANT_TASK:> Python Code: from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_...
<SYSTEM_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 sample data set Step2: Winsorize
<ASSISTANT_TASK:> Python Code: import pandas as pd # pandas for handling mixed data sets import numpy as np # numpy for basic math and matrix operations from scipy.stats.mstats import winsorize # scipy for stats and more advanced calculations scratch_df = pd.DataFrame({'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: Load raw data Step2: Train and Evaluate input Functions Step3: Feature columns for Wide and Deep model Step4: We also add our engineered feat...
<ASSISTANT_TASK:> Python Code: import tensorflow as tf import numpy as np import shutil print(tf.__version__) !gsutil cp gs://cloud-training-demos/taxifare/small/*.csv . !ls -l *.csv CSV_COLUMN_NAMES = ["fare_amount","dayofweek","hourofday","pickuplon","pickuplat","dropofflon","dropofflat"] CSV_DEFAULTS = [[0.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: Cf. jp-quadratic.html Step2: Simplify Step3: Then quadratic becomes Step4: Define a "native" pm function. Step5: The resulting trace is shor...
<ASSISTANT_TASK:> Python Code: from notebook_preamble import J, V, define define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave] dip 2 * [truediv] cons app2 roll< pop') J('3 1 1 quadratic') define('pm == [+] [-] cleave popdd') define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt 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: Set some colors and linestyles. Step2: Hardcode the loop length. In this paper, we only use a single loop half-length of $L=40$ Mm. Step3: Fir...
<ASSISTANT_TASK:> Python Code: import os import sys import pickle import numpy as np import seaborn.apionly as sns import matplotlib.pyplot as plt from matplotlib import ticker sys.path.append(os.path.join(os.environ['EXP_DIR'],'EBTEL_analysis/src')) import em_binner as emb %matplotlib inline plt.rcParams.update({'figu...
<SYSTEM_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. Training Step2: Model 2 Step3: Model 3 Step4: 3. Evaluate Step5: 4. Final Result(Ensemble)
<ASSISTANT_TASK:> Python Code: mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # test data test_images = mnist.test.images.reshape(10000, 28, 28, 1) test_labels = mnist.test.labels[:] augmentation_size = 440000 images = np.concatenate((mnist.train.images.reshape(55000, 28, 28, 1), mnist.validation.images...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Audio Data Preparation and Augmentation Step2: Usage Step3: In the above example, the Flac file brooklyn.flac is from a publicly accessible au...
<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: 1. kNN Step3: 1. kNN Step4: 2. Aplicación al Iris Dataset Step5: 2. Aplicación al Iris Dataset Step6: 2. Aplicación al Iris Dataset Step7:...
<ASSISTANT_TASK:> Python Code: def hamming(s1, s2): # Caso no comparable if len(s1)!=len(s2): print("No comparable") return None h = 0 # Caso comparable for ch1, ch2 in zip(s1,s2): if ch1!=ch2: h+= 1 # FIX ME return h print hamming("cara", "c") print hamm...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Implement a basic sub-string counter Step2: Check if a string is ascii encoded Step3: Solution
<ASSISTANT_TASK:> Python Code: s = 'ABCD' for i in range(0, len(s)): print (s[i]) string = 'ABCABDEABCF' sub_string = 'ABC' string[5:7] def output_substring(string, sub_string): for i in range(0, len(string)-len(sub_string)+1): n = i print (string[n:(n+len(sub_string))]) output_substring(string,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Write a Jython function for IDV and export as IDV Formula in GUI Step2: Above function was created for use in this session, it will not be avai...
<ASSISTANT_TASK:> Python Code: def moistStaticEnergy(T,Q,GZ): Calculates Moist Static Energy with Temperature, Specific Humidity and Geopotential Height. from ucar.visad.quantities import SpecificHeatCapacityOfDryAirAtConstantPressure,LatentHeatOfEvaporation cp=SpecificHeatCapacityOfDryAirAtConstantPressu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Convert the monthly average flow rates to volumes using Step2: Convert monthly runoff to annual runoff
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import calendar from charistools.hypsometry import Hypsometry from charistools.timeSeries import TimeSeries import datetime as dt import pandas as pd import numpy as np import os import re from time import strptime %cd /Users/brodzik/projects/CHARIS/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: 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', 'mohc', 'sandbox-3', 'atmoschem') # 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: given the RFAM id of a family we retrieve it from the RFAM online database Step2: prepare a function that composes all desired pre-processing s...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from eden.util import configure_logging import logging configure_logging(logging.getLogger(),verbosity=2) def rfam_uri(family_id): return '%s.fa'%(family_id) def rfam_uri(family_id): return 'http://rfam.xfam.org/family/%s/alignment?acc=%s&format=fastau&download...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Types Matter Step2: Switching Types Step3: Inputs type str Step4: We can use a built in Python function to convert the type from str to our d...
<ASSISTANT_TASK:> Python Code: a = "4" type(a) # should be str a = 4 type(a) # should be int a = 4 b = 5 a + b # this plus in this case means add so 9 a = "4" b = "5" a + b # the plus + in this case means concatenation, so '45' x = "45" # x is a str y = int(x) # y is now an int z = float(x) # z is a float print(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: Ejecutar códigos con otros kernels Step2: Cargar datos Step3: Gráficos Step4: Widgets Step5: Para más informaciones sobre ipywidgets, consul...
<ASSISTANT_TASK:> Python Code: a = 1 b = 2.2 c = 3 d = 'a' %who def f1(n): for x in range(n): pass %%time f1(100) %%timeit f1(100) %%bash ls -lah import pandas as pd df = pd.read_csv('data/kaggle-titanic.csv') df.head() df.info() df.describe() from matplotlib import pyplot as plt df.Survived.value_count...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exploring Your Data Step3: Two Dimensions Step5: Many Dimensions Step9: Cleaning And Munging Step10: Manipulating Data Step11: Rescaling St...
<ASSISTANT_TASK:> Python Code: def bucketize(point, bucket_size): floor the point to the next lower multiple of bucket size return bucket_size * math.floor(point / bucket_size) def make_histogram(points, bucket_size): return Counter(bucketize(point, bucket_size) for point in points) def plot_histogram(point...
<SYSTEM_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 population dynamic model Step2: Population of haplotypes maps to counts and fitnesses Step3: Map haplotype string to fitness float. Step4...
<ASSISTANT_TASK:> Python Code: import numpy as np import itertools pop_size = 100 seq_length = 10 alphabet = ['A', 'T'] base_haplotype = "AAAAAAAAAA" fitness_effect = 1.1 # fitness effect if a functional mutation occurs fitness_chance = 0.1 # chance that a mutation has a fitness effect pop = {} pop["AAAAAAAAAA"] = 40...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Simulation Step2: Spielverläufe Step3: Ergebnisse
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt from random import random, choice # Kugeln (Werte erstmal unwichtig) black, red, green, white = 0, 1, 2, 7 # Urnen kugeln_urne1 = [white, white, white, black, black] kugeln_urne2 = [white, green, green, red, red] # Wkeiten p_urne1 = 0...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: matplotlib figure Step2: matplotlib axes Step3: matplotlib artists
<ASSISTANT_TASK:> Python Code: import autofig import numpy as np import matplotlib.pyplot as plt #autofig.inline() x = np.linspace(0,0.1,11) y = x**2 mplfig = autofig.plot(x=x, y=y, show=True) print dir(mplfig) mplfig.set_facecolor('blue') mplfig mplfig.axes mplax = mplfig.axes[0] print dir(mplax) mplax.set_xticks([0...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 이 히스토그램에서 -0.143394 부터 0.437156 사이의 값이 전체의 약 24%를 차지하고 있음을 알 수 있다. 그럼 만약 -0.01 부터 0.01 사이의 구간에 대한 정보를 얻고 싶다면? 더 세부적인 구간에 대해 정보를 구하고 싶다면 히스토그램의 ...
<ASSISTANT_TASK:> Python Code: sp.random.seed(0) x = sp.random.normal(size=1000) ns, bins, ps = plt.hist(x, bins=10) pd.DataFrame([bins, ns/1000]) ns, bins, ps = plt.hist(x, bins=100) pd.DataFrame([bins, ns/1000]) x = np.linspace(-3, 3, 100) y = sp.stats.norm.pdf(x) plt.plot(x, y) <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: In this example notebook, we will walk through the creation of logsums from Step2: We'll also load the saved model from the mode choice estimat...
<ASSISTANT_TASK:> Python Code: # TEST import larch.numba as lx from pytest import approx import os import numpy as np import xarray as xr from addicty import Dict from larch import P, X import larch.numba as lx hh, pp, tour, skims = lx.example(200, ['hh', 'pp', 'tour', 'skims']) exampville_mode_choice_file = lx.examp...
<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: Data Step6: We make a vocabulary, replacing any word that occurs less than 10 times with unk. Step8: Mikolov suggested keeping word $w$ with p...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import math import os import random random.seed(0) import jax import jax.numpy as jnp try: from flax import linen as nn except ModuleNotFoundError: %pip install -qq flax from flax import linen as nn from flax.training import 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: First here's a very compact set of statements to get and plot the data for a station. No exploratory side trips. Step2: Now the same thing, but...
<ASSISTANT_TASK:> Python Code: from datetime import datetime, timedelta import pandas as pd from pyoos.collectors.nerrs.nerrs_soap import NerrsSoap # FROM pyoos SOS handling # Convenience function to build record style time series representation def flatten_element(p): rd = {'time':p.time} for m in p.members: ...
<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 - The problem of very deep neural networks Step4: Expected Output Step6: Expected Output Step7: Run the following code to build the model's...
<ASSISTANT_TASK:> Python Code: import numpy as np from keras import layers from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D from keras.models import Model, load_model from keras.preprocessing import image from ...
<SYSTEM_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...
<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: Read history file from Virtual Explorer Step2: Visualise calculated geophysical fields Step3: We now get two files for the caluclated fields S...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import sys, os import matplotlib.pyplot as plt # adjust some settings for matplotlib from matplotlib import rcParams # print rcParams rcParams['font.size'] = 15 # determine path of repository to set paths corretly below repo_path = os.path.realpath('../..') import pynod...
<SYSTEM_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 - Tunnel Traffic Step2: Let's take a look at seasonal plots over a week and over a year. Step3: Now let's look at the periodogram Step...
<ASSISTANT_TASK:> Python Code: #$HIDE_INPUT$ import numpy as np def fourier_features(index, freq, order): time = np.arange(len(index), dtype=np.float32) k = 2 * np.pi * (1 / freq) * time features = {} for i in range(1, order + 1): features.update({ f"sin_{freq}_{i}": np.sin(i * k), ...
<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. Utility functions Step3: 2. Open the data file Step4: We can open the file, as a normal HDF5 file Step5: The object h5file is a pytables f...
<ASSISTANT_TASK:> Python Code: from __future__ import division, print_function # only needed on py2 %matplotlib inline import numpy as np import h5py import matplotlib.pyplot as plt def print_children(group): Print all the sub-groups in `group` and leaf-nodes children of `group`. Parameters: data_file...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Examine a single patient Step4: Here we can see that these drugs were documented 2153 minutes (1.5 days) after ICU admission, but administered ...
<ASSISTANT_TASK:> Python Code: # Import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import psycopg2 import getpass import pdvega # for configuring connection from configobj import ConfigObj import os %matplotlib inline # Create a database connection using settings from config file ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 2. Read in the hanford.csv file in the data/ folder Step2: <img src="../../images/hanford_variables.png"></img> Step3: 4. Find a reasonable th...
<ASSISTANT_TASK:> Python Code: import pandas as pd %matplotlib inline import numpy as np from sklearn.linear_model import LogisticRegression df = pd.read_csv("hanford.csv") df.head() df.describe() df.median() rang= df['Mortality'].max() - df['Mortality'].min() rang iqr_m = df['Mortality'].quantile(q=0.75)- df['Mortal...