Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
13,000
Given the following text description, write Python code to implement the functionality described below step by step Description: Http Response Usage To construct a response packet you have a variety of facilities available. Previously we saw how to parse HTTP responses using HttpParser. Of-course, we can also constru...
Python Code: from proxy.http.parser import HttpParser, httpParserTypes from proxy.common.constants import HTTP_1_1 response = HttpParser(httpParserTypes.RESPONSE_PARSER) response.code = b'200' response.reason = b'OK' response.version = HTTP_1_1 print(response.build_response()) Explanation: Http Response Usage To constr...
13,001
Given the following text description, write Python code to implement the functionality described below step by step Description: Function Function basic Function define def use argument define Step1: return 함수의 종료 명시 값이 함께 오는 경우는 값을 호출한 곳으로 반환하면서 종료 리턴을 명시하지 않는 경우, 함수의 마지막라인이 실행된 후 리턴 Step2: e.g)문자열 포맷 함수 Step3: 1s...
Python Code: def add(num1, num2): return num1 + num2 result = add(232, 323) print result print add('abcd', 'efg') #함수이름으로부터 기능이 명시되면 좋다. def test_substraction(a, b): return a - b print test_substraction(5, 3) #parameter(argument) #int, string, float, list 등 어떤 파이썬 객체도 전달 가능 def len2(string): return len(stri...
13,002
Given the following text description, write Python code to implement the functionality described below step by step Description: <table> <tr> <td width=15%><img src="./img/UGA.png"></img></td> <td><center><h1>Introduction to Python for Data Sciences</h1></center></td> <td width=15%><a href="http Step1: Support Vector...
Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_blobs %matplotlib inline # we create 40 separable points in R^2 around 2 centers (random_state=6 is a seed so that the set is separable) X, y = make_blobs(n_samples=40, n_features=2, centers=2 , random_state=6) print(X[:5,...
13,003
Given the following text description, write Python code to implement the functionality described below step by step Description: This exercise will test your ability to read a data file and understand statistics about the data. In later exercises, you will apply techniques to filter the data, build a machine learning ...
Python Code: # Set up code checking from learntools.core import binder binder.bind(globals()) from learntools.machine_learning.ex2 import * print("Setup Complete") Explanation: This exercise will test your ability to read a data file and understand statistics about the data. In later exercises, you will apply technique...
13,004
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook 5 In this notebook I add additional features to my dataframe that help explain the variation in the price of BTC. Furthermore, multiple regression will control for these features wi...
Python Code: from sklearn.model_selection import train_test_split %run helper_functions.py %run filters.py %run plotly_functions.py %run master_func.py %run btc_info_df.py plt.style.use('fivethirtyeight') %autosave 120 import quandl from datetime import date from tabulate import tabulate from collections import Counter...
13,005
Given the following text description, write Python code to implement the functionality described below step by step Description: Markov switching dynamic regression models This notebook provides an example of the use of Markov switching models in statsmodels to estimate dynamic regression models with changes in regime...
Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt # NBER recessions from pandas_datareader.data import DataReader from datetime import datetime usrec = DataReader('USREC', 'fred', start=datetime(1947, 1, 1), end=datetime(2013, 4, 1)) Expl...
13,006
Given the following text description, write Python code to implement the functionality described below step by step Description: Passband Luminosity Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't want to...
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: Passband Luminosity Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation %matplotlib inline...
13,007
Given the following text description, write Python code to implement the functionality described below step by step Description: QuTiP example Step2: Landau-Zener-Stuckelberg interferometry Step3: Versions
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from qutip import * from qutip.ui.progressbar import TextProgressBar as ProgressBar Explanation: QuTiP example: Landau-Zener-Stuckelberg inteferometry J.R. Johansson and P.D. Nation For more information about QuTiP see http://qutip.org E...
13,008
Given the following text description, write Python code to implement the functionality described below step by step Description: Home Depot Product Search Relevance The challenge is to predict a relevance score for the provided combinations of search terms and products. To create the ground truth labels, Home Depot ha...
Python Code: import graphlab as gl from nltk.stem import * Explanation: Home Depot Product Search Relevance The challenge is to predict a relevance score for the provided combinations of search terms and products. To create the ground truth labels, Home Depot has crowdsourced the search/product pairs to multiple human ...
13,009
Given the following text description, write Python code to implement the functionality described below step by step Description: CSE 6040, Fall 2015 [11, Part A] Step3: Solution 1 This solution first queries the database for the total number of complaints by type. It then uses these data to normalize the counts by ci...
Python Code: import sqlite3 as db disk_engine = db.connect ('NYC-311-2M.db') import plotly.plotly as py py.sign_in ('USERNAME', 'PASSWORD') # Connect! import pandas as pd import itertools import time # To benchmark of these three solutions import sys # for sys.stdout.flush () from plotly.graph_objs import Bar, Layout d...
13,010
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction 機械学習とは、その名の通り「機械」を「学習」させることで、あるデータに対して予測を行えるようにすることです。 機械とは、具体的には数理・統計的なモデルになります。 学習とは、そのモデルのパラメータを、実際のデータに沿うよう調整することです。 学習の方法は大きく分けて2つあります。 教師有り学習(Supervised learning) Step1:...
Python Code: # enable showing matplotlib image inline %matplotlib inline Explanation: Introduction 機械学習とは、その名の通り「機械」を「学習」させることで、あるデータに対して予測を行えるようにすることです。 機械とは、具体的には数理・統計的なモデルになります。 学習とは、そのモデルのパラメータを、実際のデータに沿うよう調整することです。 学習の方法は大きく分けて2つあります。 教師有り学習(Supervised learning): データと、そこから予測されるべき値(正解)を与えることで学習させます。 分類(Classifica...
13,011
Given the following text description, write Python code to implement the functionality described below step by step Description: Click the button to launch this notebook in Binder Step1: Alternately, to install from the latest version on pypi, uncomment and run the cell below Step2: Sandhi Splitting Splitting sandhi...
Python Code: # !pip install git+https://github.com/kmadathil/sanskrit_parser Explanation: Click the button to launch this notebook in Binder: Sanskrit Parser Examples The sanskrit_parser module supports 3 different usages, in order of increasing complexity: 1. tags - Morphological analysis of a word 2. sandhi - Sandhi...
13,012
Given the following text description, write Python code to implement the functionality described below step by step Description: (Interactive) Plotting using Matplotlib and Seaborn Matplotlib is basic plotting library for Python inspired by Matlab. Seaborn is built on top of it with integrated analysis and specialized...
Python Code: #disable some annoying warning import warnings warnings.filterwarnings('ignore', category=FutureWarning) #plots the figures in place instead of a new window %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np #use a standard dataset of heterogenou...
13,013
Given the following text description, write Python code to implement the functionality described below step by step Description: Below is an engineering mechanics problem that can be solved with Python. Follow along to see how to solve the problem with code. Problem Given Step1: Assume the aluminum thickness is 2 mm ...
Python Code: h = 40 b = 60 ha = 2 hs = h - 2*ha Ea = 75*10**3 #Elastic modulus in MPa Es = 200*10**3 #Elastic modulus in MPa M = 1500*10**3 # N mm Explanation: Below is an engineering mechanics problem that can be solved with Python. Follow along to see how to solve the problem with code. Problem Given: Two aluminum st...
13,014
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup Let's setup our environment. We'll pull in the the usual gis suspects and setup a leaflet map, read our API keys from a json file, and setup our Planet client Step1: Make a slippy map...
Python Code: # See requirements.txt to set up your dev environment. import sys import os import json import scipy import urllib import datetime import urllib3 import rasterio import subprocess import numpy as np import pandas as pd import seaborn as sns from osgeo import gdal from planet import api from planet.api imp...
13,015
Given the following text description, write Python code to implement the functionality described below step by step Description: Deciphering a puzzle from a company's hiring page I came across A friend asked me to look at a puzzle at the hiring page of a company he was applying to. Here is my attempt to the problem. H...
Python Code: GivenString = "GGCTACTAACATGCCTTTCAACTTCCAGGGTTACTGTCAGGGTACTTATGCTCGCATTTACAAGGGCCCTACTCACTGTCAGAAGGGCTTTGGTCTTCAGGGCAATTCAAAAGAGAACCTACCGATCAATCCATCAGAGAACGAGCTTGGATGTGATACCCCTCACGCAGAAACGGCAGTTTGCATGTGGCGCGACAAAGCACCGCTTACGGAATGGATGTCGGGTGTCCGGGATACACTACTGGCTATAACATTCTGTATCAAGGCTCGGGTCGTATGGGTTAGGATGAGG...
13,016
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Q-learning In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play ...
Python Code: import gym import tensorflow as tf import numpy as np Explanation: Deep Q-learning In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play a game called Cart-Pole. In this game, a freely sw...
13,017
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing a covariance matrix Many methods in MNE, including source estimation and some classification algorithms, require covariance estimations from the recordings. In this tutorial we cov...
Python Code: import os.path as op import mne from mne.datasets import sample Explanation: Computing a covariance matrix Many methods in MNE, including source estimation and some classification algorithms, require covariance estimations from the recordings. In this tutorial we cover the basics of sensor covariance compu...
13,018
Given the following text description, write Python code to implement the functionality described below step by step Description: DTM Example In this example we will present a sample usage of the DTM wrapper. Prior to using this you need to compile the DTM code yourself or use one of the binaries. This tutorial is on W...
Python Code: import logging import os from gensim import corpora, utils from gensim.models.wrappers.dtmmodel import DtmModel import numpy as np if not os.environ.get('DTM_PATH', None): raise ValueError("SKIP: You need to set the DTM path") Explanation: DTM Example In this example we will present a sample usage of t...
13,019
Given the following text description, write Python code to implement the functionality described below step by step Description: Embrasing web standards One of the main reason that allowed us to developp the current notebook web application was to embrase the web technology. By beeing a pure web application using HT...
Python Code: ## you can inspect the autosave code to see what it does. %autosave?? Explanation: Embrasing web standards One of the main reason that allowed us to developp the current notebook web application was to embrase the web technology. By beeing a pure web application using HTML, Javascript and CSS, the Notebo...
13,020
Given the following text description, write Python code to implement the functionality described below step by step Description: Load $\delta$a$\delta$i I have not installed dadi globally on huluvu. Instead, I left it in my Downloads directory '/home/claudius/Downloads/dadi'. In order for Python to find that module, I...
Python Code: import sys sys.path sys.path.insert(0, '/home/claudius/Downloads/dadi') sys.path import dadi import pylab pylab.rcParams['figure.figsize'] = [12.0, 10.0] %matplotlib inline Explanation: Load $\delta$a$\delta$i I have not installed dadi globally on huluvu. Instead, I left it in my Downloads directory '/home...
13,021
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-3', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: NASA-GISS Source ID: SANDBOX-3 Topic: Landice Sub-Topics: Glaciers, ...
13,022
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Classification & How To "Frame Problems" for a Neural Network by Andrew Trask Twitter Step1: Note Step2: Lesson Step3: Project 1 Step4: We'll create three Counter objects, one ...
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].upper(),g.readlines())...
13,023
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Symbolic Calculator This file shows how a simply symbolic calculator can be implemented using Ply. Specification of the Scanner Step1: The token Number specifies a fully featured f...
Python Code: import ply.lex as lex tokens = [ 'NUMBER', 'IDENTIFIER', 'ASSIGN_OP' ] Explanation: A Simple Symbolic Calculator This file shows how a simply symbolic calculator can be implemented using Ply. Specification of the Scanner End of explanation def t_NUMBER(t): r'0|[1-9][0-9]*(\.[0-9]+)?(e[+-]?([1-9][0-9]*)...
13,024
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Land MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify do...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'csir-csiro', 'sandbox-3', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: CSIR-CSIRO Source ID: SANDBOX-3 Topic: Land Sub-Topics: Soil, Snow, Veget...
13,025
Given the following text description, write Python code to implement the functionality described below step by step Description: Index - Back - Next Widget List Step1: Numeric widgets There are many widgets distributed with ipywidgets that are designed to display numeric values. Widgets exist for displaying integers...
Python Code: import ipywidgets as widgets Explanation: Index - Back - Next Widget List End of explanation widgets.IntSlider( value=7, min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d' ) ...
13,026
Given the following text description, write Python code to implement the functionality described below step by step Description: Source alignment and coordinate frames The aim of this tutorial is to show how to visually assess that the data are well aligned in space for computing the forward solution, and understand t...
Python Code: import os.path as op import numpy as np import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() subjects_dir = op.join(data_path, 'subjects') raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif') trans_fname = op.join(data_path, 'MEG', 'sample', ...
13,027
Given the following text description, write Python code to implement the functionality described below step by step Description: Jak získat datum státních svátku pro dané období pro analýzu v Pandas? V pandas existuje způsob jak pracovat s datem a celkově kalendářem. Lze např. podle připraveného kalendáře filtrovat da...
Python Code: import datetime as dt from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, nearest_workday, \ USMartinLutherKingJr, USPresidentsDay, GoodFriday, USMemorialDay, \ USLaborDay, USThanksgivingDay class USTradingCalendar(AbstractHolidayCalendar): rules = [ Holiday('NewYearsDa...
13,028
Given the following text description, write Python code to implement the functionality described below step by step Description: Hoja 2. Ejercicios Python Este cuaderno está pensado para que sigáis practicando con Python y ODEs. En esta hoja nos centraremos en el álgebra lineal y la difusión. La base, como siempre, la...
Python Code: import numpy as np import matplotlib.pyplot as plt #Esta es otra forma de importar el submódulo pyplot! #Igual de válida que la que hemos visto en clase %matplotlib inline Explanation: Hoja 2. Ejercicios Python Este cuaderno está pensado para que sigáis practicando con Pyth...
13,029
Given the following text description, write Python code to implement the functionality described below step by step Description: Auto-generating Epochs metadata This tutorial shows how to auto-generate metadata for ~mne.Epochs, based on events via mne.epochs.make_metadata. We are going to use data from the erp-core-da...
Python Code: from pathlib import Path import matplotlib.pyplot as plt import mne data_dir = Path(mne.datasets.erp_core.data_path()) infile = data_dir / 'ERP-CORE_Subject-001_Task-Flankers_eeg.fif' raw = mne.io.read_raw(infile, preload=True) raw.filter(l_freq=0.1, h_freq=40) raw.plot(start=60) # extract events all_event...
13,030
Given the following text description, write Python code to implement the functionality described below step by step Description: Ordinary Differential Equations Exercise 1 Imports Step2: Lorenz system The Lorenz system is one of the earliest studied examples of a system of differential equations that exhibits chaotic...
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 Explanation: Ordinary Differential Equations Exercise 1 Imports End of explanation def lorentz_derivs(yvec, t, sigma, rho, beta): Compute the the der...
13,031
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright (c) 2015, 2016 Sebastian Raschka https Step1: The use of watermark is optional. You can install this IPython extension via "pip install watermark". For more information, please se...
Python Code: %load_ext watermark %watermark -a '' -u -d -v -p numpy,pandas,matplotlib,sklearn,nltk Explanation: Copyright (c) 2015, 2016 Sebastian Raschka https://github.com/1iyiwei/pyml MIT License Python Machine Learning - Code Examples Chapter 8 - Applying Machine Learning To Sentiment Analysis Let's apply what we h...
13,032
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1"><a href="#Task-1.-Compiling-Ebola-Data"><span class="toc-item-num">Task 1.&nbsp;&nbsp;</span>Compiling Ebola Data</a></div> <div class="lev1"><a href=...
Python Code: DATA_FOLDER = 'Data' # Use the data folder provided in Tutorial 02 - Intro to Pandas. %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import datetime from dateutil.parser import parse from os import listdir from os.path import isfile, join sns...
13,033
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimization Exercise 1 Imports Step1: Hat potential The following potential is often used in Physics and other fields to describe symmetry breaking and is often known as the "hat potential...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt from scipy.optimize import minimize, rosen, rosen_der Explanation: Optimization Exercise 1 Imports End of explanation def hat(x,a,b): return -a*(x**2) + b*(x**4) assert hat(0.0, 1.0, 1.0)==0.0 assert hat(...
13,034
Given the following text description, write Python code to implement the functionality described below step by step Description: Demo code for network-to-network information transfer for supplementary figure 1 Takuya Ito 04/19/2017 Step1: 0.0 Basic parameters Step2: 1.0 Run information transfer mapping procedure 1.1...
Python Code: import sys import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import statsmodels.sandbox.stats.multicomp as mc import multiprocessing as mp %matplotlib inline import os os.environ['OMP_NUM_THREADS'] = str(1) import warnings warnings.filterwarnings('ignore') import networkinforma...
13,035
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing the ground state energies obtained by density matrix renormalization group, exact diagonalization, and an SDP hierarchy We would like to compare the ground state energy of the foll...
Python Code: import pyalps Explanation: Comparing the ground state energies obtained by density matrix renormalization group, exact diagonalization, and an SDP hierarchy We would like to compare the ground state energy of the following spinless fermionic system [1]: $H_{\mathrm{free}}=\sum_{<rs>}\left[c_{r}^{\dagger} c...
13,036
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib Exercise 3 Imports Step2: Contour plots of 2d wavefunctions The wavefunction of a 2d quantum well is Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Matplotlib Exercise 3 Imports End of explanation def well2d(x, y, nx, ny, L=1.0): Compute the 2d quantum well wave function. i=np.sin(nx*np.pi*x/L) o=np.sin(ny*np.pi*y/L) return((2/L)*i*o) psi = well2d(np.lin...
13,037
Given the following text description, write Python code to implement the functionality described below step by step Description: seaborn.swarmplot Violinplots summarize numeric data over a set of categories. They are essentially a box plot with a kernel density estimate (KDE) overlaid along the range of the box and re...
Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np plt.rcParams['figure.figsize'] = (20.0, 10.0) plt.rcParams['font.family'] = "serif" df = pd.read_csv('../../../datasets/movie_metadata.csv') df.head() Explanation: seaborn.swarmplot Violinplots s...
13,038
Given the following text description, write Python code to implement the functionality described below step by step Description: 2D Data Plots and Analysis Unit 7, Lecture 4 Numerical Methods and Statistics Prof. Andrew White, Feburary 27th 2018 Step1: Working with 2D data Now we'll consider 2D numeric data. Recall t...
Python Code: %matplotlib inline import random import numpy as np import matplotlib.pyplot as plt from math import sqrt, pi import scipy import scipy.stats plt.style.use('seaborn-whitegrid') Explanation: 2D Data Plots and Analysis Unit 7, Lecture 4 Numerical Methods and Statistics Prof. Andrew White, Feburary 27th 2018 ...
13,039
Given the following text description, write Python code to implement the functionality described below step by step Description: Binary with Spots Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to u...
Python Code: !pip install -I "phoebe>=2.1,<2.2" Explanation: Binary with Spots Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation %matplotlib inline i...
13,040
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'uhh', 'sandbox-2', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: UHH Source ID: SANDBOX-2 Topic: Ocnbgchem Sub-Topics: Tracers. Proper...
13,041
Given the following text description, write Python code to implement the functionality described below step by step Description: Executed Step1: Notebook arguments sigma (float) Step2: Fitting models Models used to fit the data. 1. Simple Exponential In this model, we define the model function as an exponential tran...
Python Code: sigma = 0.016 time_window = 30 time_step = 5 time_start = -900 time_stop = 900 decimation = 20 t0_vary = True true_params = dict( tau = 60, # time constant init_value = 0.3, # initial value (for t < t0) final_value = 0.8, # final value (for t -> +inf) t0 = 0) ...
13,042
Given the following text description, write Python code to implement the functionality described below step by step Description: Beginners' tutorial Step2: Table of Contents Bayesian probability revision The model Bayesian optimisation Bayesian sampling/MCMC Conclusion Bayesian probability revision <a class="anchor" ...
Python Code: import numpy as np import math import matplotlib.pyplot as plt import scipy from scipy import optimize, integrate import pints Explanation: Beginners' tutorial: Bayesian inference & optimisation with Pints Prerequisites for running the code in this notebook are Python 3 with the modules below. All of the m...
13,043
Given the following text description, write Python code to implement the functionality described below step by step Description: Simon #metoo step2 Step1: Turn on logging. Step2: Document pre-processing We start with units of text represented as text files in a folder. Step3: Remove stopwords and tokenize. Step4: ...
Python Code: import pandas as pd pd.set_option('display.max_colwidth', -1) from string import punctuation from collections import defaultdict from gensim import corpora, models, matutils from nltk.stem.wordnet import WordNetLemmatizer from nltk.corpus import stopwords import re import glob Explanation: Simon #metoo ste...
13,044
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Calculate sand proportion We'd like to compute a running-window sand log, given some striplog. These are some sand beds Step2: Make a striplog Step3: Make a sand flag log We'll make...
Python Code: text = top,base,comp number 24.22,24.17,20 24.02,23.38,19 22.97,22.91,18 22.67,22.62,17 21.23,21.17,16 19.85,19.8,15 17.9,17.5,14 17.17,15.5,13 15.18,14.96,12 14.65,13.93,11 13.4,13.05,10 11.94,11.87,9 10.17,10.11,8 7.54,7.49,7 6,5.95,6 5.3,5.25,5 4.91,3.04,4 2.92,2.6,3 2.22,2.17,2 1.9,1.75,1 Explanation: ...
13,045
Given the following text description, write Python code to implement the functionality described below step by step Description: Check missing data or NaN Data exploration Analysis on 1. Age 2. Pages visited 3. New user Columns Step1: <a id = 'section1'></a> Check for missing data, or NaN Step2: <a id='sectio...
Python Code: import pandas as pd import numpy as np columns=['country','age','new_user','source','total_pages_visited','converted'] df = pd.read_csv('conversion_data.csv') df.columns=columns df.head(2) Explanation: Check missing data or NaN Data exploration Analysis on 1. Age 2. Pages visited 3. New user Columns...
13,046
Given the following text description, write Python code to implement the functionality described below step by step Description: Classification Here we test different classification algorithms for the generated graph measures dataset. Section 3.6 of the report describes the algorithms and results. Step1: Visualisatio...
Python Code: import numpy as np import random random.seed(20) import matplotlib # Set backend to pgf matplotlib.use('pgf') import matplotlib.pyplot as plt # Some nice default configuration for plots plt.rcParams['figure.figsize'] = 10, 7.5 plt.rcParams['axes.grid'] = True #plt.gray() %matplotlib inline from scipy.io i...
13,047
Given the following text description, write Python code to implement the functionality described below step by step Description: Explauto, an open-source Python library to study autonomous exploration in developmental robotics Explauto is an open-source Python library providing a unified API to design and compare vari...
Python Code: from __future__ import print_function from explauto.environment import environments environments.keys() Explanation: Explauto, an open-source Python library to study autonomous exploration in developmental robotics Explauto is an open-source Python library providing a unified API to design and compare vari...
13,048
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have a numpy array which contains time series data. I want to bin that array into equal partitions of a given length (it is fine to drop the last partition if it is not the same s...
Problem: import numpy as np data = np.array([4, 2, 5, 6, 7, 5, 4, 3, 5, 7]) bin_size = 3 new_data = data[::-1] bin_data_mean = new_data[:(data.size // bin_size) * bin_size].reshape(-1, bin_size).mean(axis=1)
13,049
Given the following text description, write Python code to implement the functionality described below step by step Description: XGBoost Article The data here is taken form the Data Hackathon3.x - http Step1: Load Data Step2: Define a function for modeling and cross-validation This function will do the following Ste...
Python Code: import os import pandas as pd import numpy as np import xgboost as xgb from xgboost.sklearn import XGBClassifier from sklearn import cross_validation, metrics from sklearn.grid_search import GridSearchCV from sklearn.model_selection import train_test_split import matplotlib.pylab as plt %matplotlib inline ...
13,050
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear Regression Setup First, let's set up some environmental dependencies. These just make the numerics easier and adjust some of the plotting defaults to make things more legible. Step1: ...
Python Code: # system functions that are always useful to have import time, sys, os # basic numeric setup import numpy as np # inline plotting %matplotlib inline # plotting import matplotlib from matplotlib import pyplot as plt # seed the random number generator rstate= np.random.default_rng(56101) # re-defining plotti...
13,051
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook introduces the notion of computing the general linear model using linear algebra. First we load the necessarily libraries. Step2: A simple example We start with a simple exam...
Python Code: import numpy,pandas import matplotlib.pyplot as plt import seaborn as sns import scipy.stats import statsmodels.api as sm import statsmodels from statsmodels.formula.api import ols,glsar from statsmodels.tsa.arima_process import arma_generate_sample from scipy.linalg import toeplitz from IPython.display im...
13,052
Given the following text description, write Python code to implement the functionality described below step by step Description: Vidic, Fajfar and Fischinger (1994) This procedure, proposed by Vidic, Fajfar and Fischinger (1994), aims to determine the displacements from an inelastic design spectra for systems with a ...
Python Code: import vidic_etal_1994 from rmtk.vulnerability.common import utils %matplotlib inline Explanation: Vidic, Fajfar and Fischinger (1994) This procedure, proposed by Vidic, Fajfar and Fischinger (1994), aims to determine the displacements from an inelastic design spectra for systems with a given ductility f...
13,053
Given the following text description, write Python code to implement the functionality described below step by step Description: Step7: Python Environment We show here some examples of how to run Python on a Pynq platform. Python 3.6 is running exclusively on the ARM processor. In the first example, which is based ...
Python Code: Factors-and-primes functions. Find factors or primes of integers, int ranges and int lists and sets of integers with most factors in a given integer interval def factorize(n): Calculate all factors of integer n. factors = [] if isinstance(n, int) and n > 0: if n == 1: ...
13,054
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 1 Step1: Load house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is located. Step2: Split data into training and testing ...
Python Code: import graphlab Explanation: Regression Week 1: Simple Linear Regression In this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. You will: * Use graphlab SArray and SFrame functions to compute important summary statistics * Write a...
13,055
Given the following text description, write Python code to implement the functionality described below step by step Description: Checkpoints Design Pattern This notebook demonstrates how to set up checkpointing in Keras. The model tries to predict whether or not a ride includes a toll. Creating dataset Create dataset ...
Python Code: import tensorflow as tf from tensorflow.python.framework import dtypes from tensorflow_io.bigquery import BigQueryClient from tensorflow_io.bigquery import BigQueryReadSession def features_and_labels(features): label = features.pop('tolls_amount') # this is what we will train for return features, tf.ca...
13,056
Given the following text description, write Python code to implement the functionality described below step by step Description: Sports scheduling In sports scheduling we usually have a bunch of games which are basically tasks requiring the two competing teams and a field as resources, so lets formulate this Step1: H...
Python Code: import sys;sys.path.append('../src') from pyschedule import Scenario, solvers, plotters, alt n_teams = 12 # Number of teams n_fields = int(n_teams/2) # Num of fields n_rounds = n_teams-1 # Number of rounds # Create scenario S = Scenario('sport_scheduling',horizon=n_rounds) # Game tasks Games = { (i,j) : S....
13,057
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'uhh', 'sandbox-2', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: UHH Source ID: SANDBOX-2 Topic: Aerosol Sub-Topics: Transport, Emissions, ...
13,058
Given the following text description, write Python code to implement the functionality described below step by step Description: Analyze The hypertools analyze function allows you to perform complex analyses (normalization, dimensionality reduction and alignment) in a single line of code! (Note that the order of opera...
Python Code: import hypertools as hyp import seaborn as sb import matplotlib.pyplot as plt %matplotlib inline Explanation: Analyze The hypertools analyze function allows you to perform complex analyses (normalization, dimensionality reduction and alignment) in a single line of code! (Note that the order of operation is...
13,059
Given the following text description, write Python code to implement the functionality described below step by step Description: Figure S1 Step1: Load phase boundary data Step2: Load optimization data Step3: Put it all together and produce the final figure
Python Code: import sys sys.path.append('../lib/') import numpy as np import matplotlib.text import matplotlib.pyplot as plt from matplotlib import cm %matplotlib inline import shapely.ops import plotting import evolimmune from plotting import * import analysis %load_ext autoreload %autoreload 2 plt.style.use(['paper']...
13,060
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'messy-consortium', 'emac-2-53-vol', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: MESSY-CONSORTIUM Source ID: EMAC-2-53-VOL Topic: Ocean Sub-To...
13,061
Given the following text description, write Python code to implement the functionality described below step by step Description: E2E ML on GCP Step1: Restart the kernel Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages. Step2: Before you begin Set up y...
Python Code: import os # The Vertex AI Workbench Notebook product has specific requirements IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists( "/opt/deeplearning/metadata/env_version" ) # Vertex AI Notebook requires dependencies to be installed with '--user' U...
13,062
Given the following text description, write Python code to implement the functionality described below step by step Description: PROMISE12 prostate segmentation demo Preparation Step1: 3) Make sure you have all the dependencies installed (replacing gpu with cpu for cpu-only mode) Step2: Training a network from the c...
Python Code: import os,sys niftynet_path=r'path/to/NiftyNet' os.chdir(niftynet_path) Explanation: PROMISE12 prostate segmentation demo Preparation: 1) Make sure you have set up the PROMISE12 data set. If not, download it from https://promise12.grand-challenge.org/ (registration required) and run data/PROMISE12/setup.p...
13,063
Given the following text description, write Python code to implement the functionality described below step by step Description: SSL Connection Examples Connecting to a Redis instance via SSL. Step1: Connecting to a Redis instance via a URL string Step2: Connecting to a Redis instance via SSL, while specifying a sel...
Python Code: import redis ssl_connection = redis.Redis(host='localhost', port=6666, ssl=True, ssl_cert_reqs="none") ssl_connection.ping() Explanation: SSL Connection Examples Connecting to a Redis instance via SSL. End of explanation import redis url_connection = redis.from_url("redis://localhost:6379?ssl_cert_reqs=non...
13,064
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Welcome to the feature engineering project for the House Prices - Advanced Regression Techniques competition! This competition uses nearly the same data you used in the exercise...
Python Code: #$HIDE_INPUT$ import os import warnings from pathlib import Path import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from IPython.display import display from pandas.api.types import CategoricalDtype from category_encoders import MEstimateEncoder from sklearn.cluster...
13,065
Given the following text description, write Python code to implement the functionality described below step by step Description: Práctica 3 - Dinámica de manipuladores List comprehensions En esta práctica nos enfocaremos en temas avanzados de programación que se aplican directamente al lenguaje de programación Python ...
Python Code: range(5) Explanation: Práctica 3 - Dinámica de manipuladores List comprehensions En esta práctica nos enfocaremos en temas avanzados de programación que se aplican directamente al lenguaje de programación Python y a algunos otros lenguajes de programación. En primer lugar veamos la instrucción range: End o...
13,066
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercises Step1: Data Step2: Exercise 1 Step3: Exercise 2 Step4: Exercise 3
Python Code: # Useful Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt Explanation: Exercises: Variance By Christopher van Hoecke, Maxwell Margenot, and Delaney Mackenzie Lecture Link : https://www.quantopian.com/lectures/variance IMPORTANT NOTE: This lecture corresponds to the Variance ...
13,067
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex AI SDK Step1: Install the latest GA version of google-cloud-storage library. Step2: Install the latest version of tensorflow library. Step3: Restart the kernel Once you've install...
Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG Explanation: Vertex AI SDK : AutoML training image object detection model for batch prediction <table ...
13,068
Given the following text description, write Python code to implement the functionality described below step by step Description: <table class="ee-notebook-buttons" align="left"><td> <a target="_blank" href="http Step1: Obtain a private key file for your service account You should already have a service account regis...
Python Code: # INSERT YOUR PROJECT HERE PROJECT = 'your-project' !gcloud auth login --project {PROJECT} Explanation: <table class="ee-notebook-buttons" align="left"><td> <a target="_blank" href="http://colab.research.google.com/github/google/earthengine-api/blob/master/python/examples/ipynb/Earth_Engine_REST_API_compu...
13,069
Given the following text description, write Python code to implement the functionality described below step by step Description: Autonomous driving - Car detection Welcome to your week 3 programming assignment. You will learn about object detection using the very powerful YOLO model. Many of the ideas in this notebook...
Python Code: import argparse import os import matplotlib.pyplot as plt from matplotlib.pyplot import imshow import scipy.io import scipy.misc import numpy as np import pandas as pd import PIL import tensorflow as tf from keras import backend as K from keras.layers import Input, Lambda, Conv2D from keras.models import l...
13,070
Given the following text description, write Python code to implement the functionality described below step by step Description: Outline Glossary 1. Radio Science using Interferometric Arrays Previous Step1: Import section specific modules Step2: 1.10 The Limits of Single Dish Astronomy In the previous section &#1...
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 Explanation: Outline Glossary 1. Radio Science using Interferometric Arrays Previous: 1.9 A brief introduction to interferometry Next: 1.11 Modern Interfe...
13,071
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework Step1: I follow the scikit-image tutorial on segmentation
Python Code: import numpy as np import matplotlib.pyplot as plt from skimage import data %matplotlib inline from skimage.filters import sobel from scipy import ndimage as ndi from skimage.measure import regionprops from skimage.color import label2rgb from skimage.morphology import watershed Explanation: Homework: sciki...
13,072
Given the following text description, write Python code to implement the functionality described below step by step Description: MR Imaging Class Step1: Next we define two small functions to convert between coordinate systems. Step5: Now we will define several functions that will be employed in the tutorial to illus...
Python Code: %pylab inline import matplotlib as mpl mpl.rcParams["figure.figsize"] = (8, 6) mpl.rcParams["axes.grid"] = True from IPython.display import display, clear_output from time import sleep Explanation: MR Imaging Class: Psych 204a Tutorial: MR Imaging Author: Wandell Date: 03.15.04 Duration: 90 m...
13,073
Given the following text description, write Python code to implement the functionality described below step by step Description: 1.2.4. Comparing word use between corpora In previous notebooks we examined changes in word use over time using several different statistical approaches. In this notebook, we will examine di...
Python Code: from tethne.readers import wos pj_corpus = wos.read('../data/Baldwin/PlantJournal/') pp_corpus = wos.read('../data/Baldwin/PlantPhysiology/') Explanation: 1.2.4. Comparing word use between corpora In previous notebooks we examined changes in word use over time using several different statistical approaches...
13,074
Given the following text description, write Python code to implement the functionality described below step by step Description: Building Models in PyMC Bayesian inference begins with specification of a probability model relating unknown variables to data. PyMC provides three basic building blocks for Bayesian probabi...
Python Code: import pymc as pm import numpy as np from pymc.examples import disaster_model switchpoint = pm.DiscreteUniform('switchpoint', lower=0, upper=110) Explanation: Building Models in PyMC Bayesian inference begins with specification of a probability model relating unknown variables to data. PyMC provides three ...
13,075
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Land MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify do...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cas', 'sandbox-2', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: CAS Source ID: SANDBOX-2 Topic: Land Sub-Topics: Soil, Snow, Vegetation, Energy ...
13,076
Given the following text description, write Python code to implement the functionality described below step by step Description: Absolute Motion During the first week we discussed reference frames and coordinate systems to represent the motion of particles. This was the “absolute motion” that was always measured rela...
Python Code: from rel_motion import * # Fixed Frame A A = np.eye(3) # identity matrix E1=(1,0,0), E2=(0,1,0), E3=(0,0,1) rO = np.array((0,0,0)) rP = np.array( (5, 0, 0)) plotAbsMotion(A, rO, rP) Explanation: Absolute Motion During the first week we discussed reference frames and coordinate systems to represent the moti...
13,077
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Preparing text to use with TensorFlow models <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2:...
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 writing, software # dist...
13,078
Given the following text description, write Python code to implement the functionality described below step by step Description: Progress Reporting and Command Observers <a href="https Step1: We need to add a command to display the progress reported by the ProcessObject Step2: Back to watching the progress of out Ga...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import SimpleITK as sitk print(sitk.Version()) import sys import os import threading from myshow import myshow from myshow import myshow3d size = 256 # if this is too fast increase the size img = sitk.GaborSource( sitk.sitkFloat32, size=[size] * 3...
13,079
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create some text Step2: Apply regex
Python Code: # Load regex package import re Explanation: Title: Match Times Slug: match_times Summary: Match Times Date: 2016-05-01 12:00 Category: Regex Tags: Basics Authors: Chris Albon Based on: StackOverflow Preliminaries End of explanation # Create a variable containing a text string text = 'Chris: 12:34am. Stev...
13,080
Given the following text description, write Python code to implement the functionality described below step by step Description: Anomaly Detection Step1: Next we transform the DATE column in an appropriate timestamp format, and the fred_dcoilbrenteu SFrame in a TimeSeries object. Step2: We can plot the fred_dcoilbre...
Python Code: import graphlab as gl import matplotlib.pyplot as plt fred_dcoilbrenteu = gl.SFrame.read_csv('./FRED-DCOILBRENTEU.csv') fred_dcoilbrenteu Explanation: Anomaly Detection: Moving Z-Score and Bayesian Changepoints Model Introductory Remarks Anomalies are data points that are different from other observations ...
13,081
Given the following text description, write Python code to implement the functionality described below step by step Description: Display sensitivity maps for EEG and MEG sensors Sensitivity maps can be produced from forward operators that indicate how well different sensor types will be able to detect neural currents ...
Python Code: # Author: Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import mne from mne.datasets import sample import matplotlib.pyplot as plt print(__doc__) data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif' fwd_fname = data_path + '/MEG/sample/sample_audvis...
13,082
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: AWS (S3, Redshift, Kinesis) + Databricks Spark = Real-time Smart Meter Analytics Create S3 Bucket Step2: Copy Postgres to S3 via Postgres dump to CSV and s3cmd upload Step3: Amazon ...
Python Code: s3 = boto3.client('s3') s3.list_buckets() def create_s3_bucket(bucketname): Quick method to create bucket with exception handling s3 = boto3.resource('s3') exists = True bucket = s3.Bucket(bucketname) try: s3.meta.client.head_bucket(Bucket=bucketname) except botocore.excepti...
13,083
Given the following text description, write Python code to implement the functionality described below step by step Description: 다변수 가우시안 정규 분포 다변수 가우시안 정규 분포 혹은 간단히 다변수 정규 분포(MVN Step1: 경우 2 만약 $$ \mu = \begin{bmatrix}2 \ 3 \end{bmatrix}. \;\;\; \Sigma = \begin{bmatrix}2 & -1 \ 2 & 4 \end{bmatrix} $$ 이면 $$ | \S...
Python Code: mu = [2, 3] cov = [[1, 0], [0, 1]] rv = sp.stats.multivariate_normal(mu, cov) xx = np.linspace(0, 4, 120) yy = np.linspace(1, 5, 150) XX, YY = np.meshgrid(xx, yy) plt.grid(False) plt.contourf(XX, YY, rv.pdf(np.dstack([XX, YY]))) plt.axis("equal") plt.show() Explanation: 다변수 가우시안 정규 분포 다변수 가우시안 정규 분포 혹은 간단히...
13,084
Given the following text description, write Python code to implement the functionality described below step by step Description: Finite-Length Capacity of the BSC and BEC Channels This code is provided as supplementary material of the lecture Channel Coding 2 - Advanced Methods. This code illustrates * Calculating the...
Python Code: import numpy as np from scipy.stats import norm import matplotlib import matplotlib.pyplot as plt # plotting options font = {'size' : 20} plt.rc('font', **font) plt.rc('text', usetex=matplotlib.checkdep_usetex(True)) matplotlib.rc('figure', figsize=(18, 6) ) Explanation: Finite-Length Capacity of the BS...
13,085
Given the following text description, write Python code to implement the functionality described below step by step Description: Lid driven Cavity (GPU) The following command is important to view matplotlib plots on a jupyter notebook Step1: cf. http Step2: Making a colorbar, making colormaps, Show colormaps, in mat...
Python Code: # %matplotlib inline Explanation: Lid driven Cavity (GPU) The following command is important to view matplotlib plots on a jupyter notebook End of explanation %matplotlib notebook import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import os, sys from matplotlib.mlab import griddata im...
13,086
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting info on Priming experiment dataset that's needed for modeling Info Step1: Init Step2: Loading OTU table (filter to just bulk samples) Step3: Which gradient(s) to simulate? Step4: ...
Python Code: baseDir = '/home/nick/notebook/SIPSim/dev/priming_exp/' workDir = os.path.join(baseDir, 'exp_info') otuTableFile = '/var/seq_data/priming_exp/data/otu_table.txt' otuTableSumFile = '/var/seq_data/priming_exp/data/otu_table_summary.txt' metaDataFile = '/var/seq_data/priming_exp/data/allsample_metadata_nomock...
13,087
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook 2 Step1: Download the sequence data Sequence data for this study are archived on the NCBI sequence read archive (SRA). Below I read in SraRunTable.txt downloaded from the SRA websi...
Python Code: ### Notebook 2 ### Data set 2 (Phrynosomatidae) ### Authors: Leache et al. (2015) ### Data Location: NCBI SRA SRP063316 Explanation: Notebook 2: This is an Jupyter/IPython notebook. Most of the code is composed of bash scripts, indicated by %%bash at the top of the cell, otherwise it is IPython code. This ...
13,088
Given the following text description, write Python code to implement the functionality described below step by step Description: FD_1D_DX4_DT4_ABS 1-D acoustic Finite-Difference modelling GNU General Public License v3.0 Author Step1: Input Parameter Step2: Preparation Step3: Create space and time vector Step4: Sou...
Python Code: %matplotlib inline import numpy as np import time as tm import matplotlib.pyplot as plt Explanation: FD_1D_DX4_DT4_ABS 1-D acoustic Finite-Difference modelling GNU General Public License v3.0 Author: Florian Wittkamp Finite-Difference acoustic seismic wave simulation Discretization of the first-order acous...
13,089
Given the following text description, write Python code to implement the functionality described below step by step Description: ARDC Training Step1: Browse the available Data Cubes Step2: Pick a product Use the platform and product names from the previous block to select a Data Cube. Step3: Display Latitude-Longit...
Python Code: import datacube import utils.data_cube_utilities.data_access_api as dc_api from datacube.utils.aws import configure_s3_access configure_s3_access(requester_pays=True) api = dc_api.DataAccessApi() dc = datacube.Datacube(app = 'ardc_task_c') api.dc = dc Explanation: ARDC Training: Python Notebooks Task-C: ...
13,090
Given the following text description, write Python code to implement the functionality described below step by step Description: Converting <span style="font-variant Step1: Imports We will use the package ply to remove the <span style="font-variant Step2: Token Declarations We begin by declaring the tokens. Note t...
Python Code: data = \ ''' <html> <head> <meta charset="utf-8"> <title>Homepage of Prof. Dr. Karl Stroetmann</title> <link type="text/css" rel="stylesheet" href="style.css" /> <link href="http://fonts.googleapis.com/css?family=Rochester&subset=latin,latin-ext" rel="stylesheet" type="text/css"...
13,091
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook is based on one put together by Mark Krumholz and has been modified to suit the purposes of this course, including expansion/modification of explanations and addition...
Python Code: from numpy import * import matplotlib.pyplot as plt %matplotlib inline Explanation: <small><i>This notebook is based on one put together by Mark Krumholz and has been modified to suit the purposes of this course, including expansion/modification of explanations and additional exercises. The original can be...
13,092
Given the following text description, write Python code to implement the functionality described below step by step Description: AVISO Step1: O ponto de partida foi uma lista 326.716 palavras da língua portuguesa que compilei a partir de várias fontes. Aqui eu leio o arquivo, verifico que são todas palavras únicas e ...
Python Code: 6**5 Explanation: AVISO: Este projeto migrou para o repositório https://github.com/ramalho/dadoware Diceware: método seguro para gerar senhas Fonte: The Diceware Passphrase Home Page Compilação da lista de palavras Neste notebook comecei com uma grande lista palavras da língua portuguesa, que fui sucessiva...
13,093
Given the following text description, write Python code to implement the functionality described below step by step Description: version 1.0.2 + Introduction to Machine Learning with Apache Spark Predicting Movie Ratings One of the most common uses of big data is to predict what users want. This allows Google to sh...
Python Code: import sys import os from test_helper import Test baseDir = os.path.join('data') inputPath = os.path.join('cs100', 'lab4', 'small') ratingsFilename = os.path.join(baseDir, inputPath, 'ratings.dat.gz') moviesFilename = os.path.join(baseDir, inputPath, 'movies.dat') Explanation: version 1.0.2 + Introductio...
13,094
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Setting the scale This recipe demonstrates how the scale of the Sankey diagram is set. By default the scale is calculated for each diagram to achieve a certain whitespace-to-flow rati...
Python Code: import pandas as pd from io import StringIO flows = pd.read_csv(StringIO( year,source,target,value 2020,A,B,10 2025,A,B,20 )) flows from floweaver import * # Set the default size to fit the documentation better. size = dict(width=100, height=100, margins=dict(left=20, right=20, top=10, bottom=1...
13,095
Given the following text description, write Python code to implement the functionality described below step by step Description: Additional forces REBOUND is a gravitational N-body integrator. But you can also use it to integrate systems with additional, non-gravitational forces. This tutorial gives you a very quick o...
Python Code: import rebound sim = rebound.Simulation() sim.integrator = "whfast" sim.add(m=1.) sim.add(m=1e-6,a=1.) sim.move_to_com() # Moves to the center of momentum frame Explanation: Additional forces REBOUND is a gravitational N-body integrator. But you can also use it to integrate systems with additional, non-gr...
13,096
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Parametric Regression Notebook version Step1: 1. Model-based parametric regression 1.1. The regression problem. Given an observation vector ${\bf x}$, the goal of the regression pr...
Python Code: # Import some libraries that will be necessary for working with data and displaying plots # To visualize plots in the notebook %matplotlib inline from IPython import display import matplotlib import matplotlib.pyplot as plt import numpy as np import scipy.io # To read matlab files import pylab impor...
13,097
Given the following text description, write Python code to implement the functionality described below step by step Description: Spatial queries Step1: Let's check if those points are within the polygon Step2: Okey, so we can see that the first point seems to be inside that polygon and the other one doesn't. In fac...
Python Code: from shapely.geometry import Point, Polygon # Create Point objects p1 = Point(24.952242, 60.1696017) p2 = Point(24.976567, 60.1612500) # Create a Polygon coords = [(24.950899, 60.169158), (24.953492, 60.169158), (24.953510, 60.170104), (24.950958, 60.169990)] poly = Polygon(coords) # Let's check what we ha...
13,098
Given the following text description, write Python code to implement the functionality described below step by step Description: Document retrieval from wikipedia data Fire up GraphLab Create Step1: Load some text data - from wikipedia, pages on people Step2: Data contains Step3: Explore the dataset and checkout th...
Python Code: import graphlab Explanation: Document retrieval from wikipedia data Fire up GraphLab Create End of explanation people = graphlab.SFrame('people_wiki.gl/') Explanation: Load some text data - from wikipedia, pages on people End of explanation people.head() len(people) Explanation: Data contains: link to wik...
13,099
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: This notebook is to test the inheritance machinery in gemini. Families are drawn in an image where Affection white fill means unaffected gray fill means unknown black fill means affec...
Python Code: import gemini.tests from gemini.tests.test_inheritance import TestFamily, family Sample = family.Sample HOM_REF, HET, UNKNOWN, HOM_ALT = range(4) fam = TestFamily( #family_id sample_id paternal_id maternal_id sex phenotype 1 dad 0 0 1 1 1 mom grandpa grandma 2 1 1 kid dad mom...