Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
6,400
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Deep Learning Project Step1: Step 1 Step2: Include an exploratory visualization of the dataset Visualize the German Traffic Signs Dataset using the pic...
Python Code: # Load pickled data import pickle # TODO: Fill this in based on where you saved the training and testing data training_file = "traffic-signs/train.p" validation_file= "traffic-signs/valid.p" testing_file = "traffic-signs/test.p" with open(training_file, mode='rb') as f: train = pickle.load(f) with open...
6,401
Given the following text description, write Python code to implement the functionality described below step by step Description: TF-Slim Walkthrough This notebook will walk you through the basics of using TF-Slim to define, train and evaluate neural networks on various tasks. It assumes a basic knowledge of neural net...
Python Code: import matplotlib %matplotlib inline import matplotlib.pyplot as plt import math import numpy as np import tensorflow as tf import time from datasets import dataset_utils # Main slim library slim = tf.contrib.slim Explanation: TF-Slim Walkthrough This notebook will walk you through the basics of using TF-S...
6,402
Given the following text description, write Python code to implement the functionality described below step by step Description: In-Class Demonstration and Visualization Step2: The function plot_taylor_approximations included here was written by Fernando Perez and was part of work on the original IPython project. Al...
Python Code: %matplotlib inline import numpy as np import sympy as sp import matplotlib.pyplot as plt # You can change the default figure size to be a bit larger if you want, # uncomment the next line for that: plt.rc('figure', figsize=(10, 6)) Explanation: In-Class Demonstration and Visualization End of explanation de...
6,403
Given the following text description, write Python code to implement the functionality described below step by step Description: Find MEG reference channel artifacts Use ICA decompositions of MEG reference channels to remove intermittent noise. Many MEG systems have an array of reference channels which are used to det...
Python Code: # Authors: Jeff Hanna <jeff.hanna@gmail.com> # # License: BSD-3-Clause import mne from mne import io from mne.datasets import refmeg_noise from mne.preprocessing import ICA import numpy as np print(__doc__) data_path = refmeg_noise.data_path() Explanation: Find MEG reference channel artifacts Use ICA decom...
6,404
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', 'mpi-m', 'icon-esm-lr', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: MPI-M Source ID: ICON-ESM-LR Topic: Ocean Sub-Topics: Timestepping Framewo...
6,405
Given the following text description, write Python code to implement the functionality described below step by step Description: Executed Step1: Load Data Multispot Load the leakage coefficient from disk (computed in Multi-spot 5-Samples analyis - Leakage coefficient fit) Step2: Load the direct excitation coefficien...
Python Code: from fretbursts import fretmath import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from cycler import cycler import seaborn as sns %matplotlib inline %config InlineBackend.figure_format='retina' # for hi-dpi displays import matplotlib as mpl from cycler import ...
6,406
Given the following text description, write Python code to implement the functionality described below step by step Description: Triple Double Russ In this post, we use webscraping to analyze Russell Westbrook's (Russ) team performance when he records a triple double. We will use multiple Python modules and focus on B...
Python Code: from utils import * import constants as c Explanation: Triple Double Russ In this post, we use webscraping to analyze Russell Westbrook's (Russ) team performance when he records a triple double. We will use multiple Python modules and focus on BeautifulSoup, pandas, matplotlib, and seaborn Overview Backg...
6,407
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: The Data There are some fake data csv files you can read in as dataframes Step2: Style Sheets Matplotlib has style sheets you can use to make your plots look a little ...
Python Code: import numpy as np import pandas as pd %matplotlib inline Explanation: <a href='http://www.pieriandata.com'> <img src='../../Pierian_Data_Logo.png' /></a> Pandas Built-in Data Visualization In this lecture we will learn about pandas built-in capabilities for data visualization! It's built-off of matplotlib...
6,408
Given the following text description, write Python code to implement the functionality described below step by step Description: Cranfield dataset processing This notebook creates vector space model for documents and queries contained in Cranfield collection. Step1: Helper functions. get_top_n() simply returns indice...
Python Code: from sklearn.metrics.pairwise import cosine_similarity, pairwise_distances from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer import matplotlib.pyplot as plt import matplotlib.style import numpy as np matplotlib.style.use('ggplot') %matplotlib inline matplotlib.rcParams['figure.fi...
6,409
Given the following text description, write Python code to implement the functionality described below step by step Description: GBM Geometry Demo J. Michael Burgess gbmeometry is a module with routines for handling GBM geometry. It performs a few tasks Step1: Making an interpolation from TRIGDAT Getting the data We ...
Python Code: %pylab inline from astropy.coordinates import SkyCoord import astropy.coordinates as coord import astropy.units as u from gbmgeometry import * Explanation: GBM Geometry Demo J. Michael Burgess gbmeometry is a module with routines for handling GBM geometry. It performs a few tasks: * creates and astropy coo...
6,410
Given the following text description, write Python code to implement the functionality described below step by step Description: Circuito RLC paralelo sem fonte Jupyter Notebook desenvolvido por Gustavo S.S. Circuitos RLC em paralelo têm diversas aplicações, como em projetos de filtros e redes de comunicação. Suponha ...
Python Code: print("Exemplo 8.5") from sympy import * m = 10**(-3) #definicao de mili L = 1 C = 10*m v0 = 5 i0 = 0 A1 = symbols('A1') A2 = symbols('A2') t = symbols('t') def sqrt(x, root = 2): #definir funcao para raiz y = x**(1/root) return y print("\n--------------\n") ## PARA R = 1.923 R = 1.923 print("Para ...
6,411
Given the following text description, write Python code to implement the functionality described below step by step Description: Today Melanie lead the meeting with a session on the ArcGIS software and how we can use Python to automatise the geospatial data processing. The slides are available below. We started with a...
Python Code: # embed pdf into an automatically resized window (requires imagemagick) w_h_str = !identify -format "%w %h" ../pdfs/arcgis-intro.pdf[0] HTML('<iframe src=../pdfs/arcgis-intro.pdf width={0[0]} height={0[1]}></iframe>'.format([int(i)*0.8 for i in w_h_str[0].split()])) Explanation: Today Melanie lead the meet...
6,412
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', 'mohc', 'sandbox-1', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: MOHC Source ID: SANDBOX-1 Topic: Ocean Sub-Topics: Timestepping Framework, Ad...
6,413
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Fully-Connected Neural Nets In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since t...
Python Code: # As usual, a bit of setup import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplot...
6,414
Given the following text description, write Python code to implement the functionality described below step by step Description: US EPA ChemView web services The documentation lists several ways of accessing data in ChemView. Step1: Getting 'chemicals' data from ChemView As a start... this downloads data for all chem...
Python Code: URIBASE = 'http://java.epa.gov/chemview/' Explanation: US EPA ChemView web services The documentation lists several ways of accessing data in ChemView. End of explanation uri = URIBASE + 'chemicals' r = requests.get(uri, headers = {'Accept': 'application/json, */*'}) j = json.loads(r.text) print(len(j)) df...
6,415
Given the following text description, write Python code to implement the functionality described below step by step Description: 3. Imagined movement In this tutorial we will look at imagined movement. Our movement is controlled in the motor cortex where there is an increased level of mu activity (8–12 Hz) when we per...
Python Code: %pylab inline Explanation: 3. Imagined movement In this tutorial we will look at imagined movement. Our movement is controlled in the motor cortex where there is an increased level of mu activity (8–12 Hz) when we perform movements. This is accompanied by a reduction of this mu activity in specific regions...
6,416
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 6 Temporal-Difference Learning DP, TD, and Monte Carlo methods all use some variation of generalized policy iteration Step1: 6.2 Advantages of TD Prediction Methods TD Step2: 6.5 Q...
Python Code: Image('./res/fig6_1.png') Image('./res/TD_0.png') Explanation: Chapter 6 Temporal-Difference Learning DP, TD, and Monte Carlo methods all use some variation of generalized policy iteration: primarily differences in their approaches to the prediction problem. 6.1 TD Prediction constant-$\alpha$ MC: $V(S_t) ...
6,417
Given the following text description, write Python code to implement the functionality described below step by step Description: Embedding [embeddings.Embedding.0] input_dim 5, output_dim 3, input_length=7, mask_zero=False Step1: [embeddings.Embedding.1] input_dim 20, output_dim 5, input_length=10, mask_zero=True Ste...
Python Code: input_dim = 5 output_dim = 3 input_length = 7 data_in_shape = (input_length,) emb = Embedding(input_dim, output_dim, input_length=input_length, mask_zero=False) layer_0 = Input(shape=data_in_shape) layer_1 = emb(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for r...
6,418
Given the following text description, write Python code to implement the functionality described below step by step Description: Access TTree in Python using PyROOT <hr style="border-top-width Step1: Open a file which is located on the web. No type is to be specified for "f". Step2: Loop over the TTree called "event...
Python Code: import ROOT Explanation: Access TTree in Python using PyROOT <hr style="border-top-width: 4px; border-top-color: #34609b;"> End of explanation f = ROOT.TFile.Open("https://root.cern.ch/files/summer_student_tutorial_tracks.root") Explanation: Open a file which is located on the web. No type is to be specifi...
6,419
Given the following text description, write Python code to implement the functionality described below step by step Description: Experiment 6 Step1: Data Loading Step2: Plotting
Python Code: # import the modules import GPy import csv import numpy as np import cPickle as pickle import scipy.stats as stats import sklearn.metrics as metrics import GPy.plotting.Tango as Tango from matplotlib import pyplot as plt %matplotlib notebook Explanation: Experiment 6: TRo Journal In this experiment, the ge...
6,420
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear time series analysis - AR/MA models Lorenzo Biasi (3529646), Julius Vernie (3502879) Task 1. AR(p) models. 1.1 Step1: We can see that simulating the data as an AR(1) model is not eff...
Python Code: import numpy as np import matplotlib.pyplot as plt import scipy.io as sio from sklearn import datasets, linear_model %matplotlib inline def set_data(p, x): temp = x.flatten() n = len(temp[p:]) x_T = temp[p:].reshape((n, 1)) X_p = np.ones((n, p + 1)) for i in range(1, p + 1): X_p...
6,421
Given the following text description, write Python code to implement the functionality described below step by step Description: Permutation T-test on sensor data One tests if the signal significantly deviates from 0 during a fixed time window of interest. Here computation is performed on MNE sample dataset between 40...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import mne from mne import io from mne.stats import permutation_t_test from mne.datasets import sample print(__doc__) Explanation: Permutation T-test on sensor data One tests if the signal...
6,422
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In group efforts, there is sometimes the impression that there are those who work, and those who talk. A naive question to ask is whether or not the people that tend to talk a l...
Python Code: # Load the raw email and git data url = "http://mail.python.org/pipermail/scipy-dev/" arx = Archive(url,archive_dir="../archives") mailInfo = arx.data repo = repo_loader.get_repo("bigbang") gitInfo = repo.commit_data; Explanation: Introduction In group efforts, there is sometimes the impression that there ...
6,423
Given the following text description, write Python code to implement the functionality described below step by step Description: Minimal Example to Produce a Synthetic Light Curve 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 yo...
Python Code: !pip install -I "phoebe>=2.0,<2.1" %matplotlib inline Explanation: Minimal Example to Produce a Synthetic Light Curve 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 lat...
6,424
Given the following text description, write Python code to implement the functionality described below step by step Description: Executed Step1: Notebook arguments measurement_id (int) Step2: Selecting a data file Step3: Data load and Burst search Load and process the data Step4: Compute background and burst searc...
Python Code: measurement_id = 0 windows = (60, 180) # Cell inserted during automated execution. windows = (30, 180) measurement_id = 1 Explanation: Executed: Tue Mar 28 00:43:40 2017 Duration: 41 seconds. End of explanation import time from pathlib import Path import pandas as pd from scipy.stats import linregress from...
6,425
Given the following text description, write Python code to implement the functionality described below step by step Description: Symbolic Computation Symbolic computation deals with symbols, representing them exactly, instead of numerical approximations (floating point). We will start with the following borrowed tuto...
Python Code: import math math.sqrt(3) math.sqrt(8) Explanation: Symbolic Computation Symbolic computation deals with symbols, representing them exactly, instead of numerical approximations (floating point). We will start with the following borrowed tutorial to introduce the concepts of SymPy. Devito uses SymPy heavily...
6,426
Given the following text description, write Python code to implement the functionality described below step by step Description: Removing particles from the simulation This tutorial shows the differnet ways to remove particles from a REBOUND simulation. Let us start by setting up a simple simulation with 10 bodies, an...
Python Code: import rebound import numpy as np sim = rebound.Simulation() sim.add(m=1., hash=0) for i in range(1,10): sim.add(a=i, hash=i) sim.move_to_com() print("Particle hashes:{0}".format([sim.particles[i].hash for i in range(sim.N)])) Explanation: Removing particles from the simulation This tutorial shows the ...
6,427
Given the following text description, write Python code to implement the functionality described below step by step Description: IST256 Lesson 03 Conditionals Zybook Ch3 P4E Ch3 Links Participation Step1: Python’s Relational Operators <table style="font-size Step2: A. 4 B. 5 C. 6 D. 7 Vote Now Step3: A. 4 B. 5 C....
Python Code: if boolean-expression: statements-when-true else: statemrnts-when-false Explanation: IST256 Lesson 03 Conditionals Zybook Ch3 P4E Ch3 Links Participation: https://poll.ist256.com Zoom Chat!!! Agenda Homework 02 Solution Non-Linear Code Execution Relational and Logical Operators Different types of n...
6,428
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <img src="http Step1: 2.1 Simple compartment models Example 1 Step2: 2.1.1.- Simple population models Adding competition for resources Step3: Logistic growth with harvesting ...
Python Code: import numpy as np import scipy.sparse.linalg as sp import sympy as sym from scipy.linalg import toeplitz import ipywidgets as widgets from ipywidgets import IntSlider import matplotlib.pyplot as plt %matplotlib inline from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatte...
6,429
Given the following text description, write Python code to implement the functionality described below step by step Description: Accessing Databases via Web APIs In this lesson we'll learn what an API (Application Programming Interface) is, how it's normally used, and how we can collect data from it. We'll then look a...
Python Code: import requests # to make the GET request import json # to parse the JSON response to a Python dictionary import time # to pause after each API call import csv # to write our data to a CSV import pandas # to see our CSV Explanation: Accessing Databases via Web APIs In this lesson we'll learn what an ...
6,430
Given the following text description, write Python code to implement the functionality described below step by step Description: timeseries comparison We can compare pairs of time series (e.g. rates) as long as the sampling times for the two series are (roughly) the same. Below we make two almost identical series A an...
Python Code: time = np.arange(0,20,0.1) A = [np.sin(x)**2 for x in time] sns.tsplot(A,interpolate=False) B = [np.sin(x)**2 + np.random.exponential(0.2) for x in time] sns.tsplot(B,interpolate=False) phi, p = scipy.stats.pearsonr(A,B) print phi # correlation is between -1 and 1. -1 means that one series goes up when th...
6,431
Given the following text description, write Python code to implement the functionality described below step by step Description: Batch processing Decide on a size limit for aiff files (882kb/10s file) Generate that much files Process those files and append results to DataFrame Remove those files Step1: Loading
Python Code: import hurry.filesize hurry.filesize.size(903168, system=hurry.filesize.alternative) hurry.filesize.size(882102, system=hurry.filesize.si) hurry.filesize.size(882000, system=hurry.filesize.si) hurry.filesize.size(1073741824, system=hurry.filesize.alternative) hurry.filesize.size(1073741824, system=hurry.fi...
6,432
Given the following text description, write Python code to implement the functionality described below step by step Description: The project I am angling towards deals with my website's traffic and taxonomy data. I will be trying to build models that can accurately predict which tags are best for specific channels of ...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: The project I am angling towards deals with my website's traffic and taxonomy data. I will be trying to build models that can accurately predict which tags are best for specific channels of traffic, and w...
6,433
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos 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', 'mri', 'sandbox-2', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: MRI Source ID: SANDBOX-2 Topic: Atmos Sub-Topics: Dynamical Core, Radiation, T...
6,434
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro Este es el primer taller de informática 3, que cubre conceptos básicos de Python, gráficos y ajustes, use este notebook para resolver el taller y, por favor use tantas celdas como nece...
Python Code: # Ejecute esta celda para importar las librerías y funciones necesarias %matplotlib notebook from IPython.display import set_matplotlib_formats set_matplotlib_formats('png', 'pdf') import numpy as np import matplotlib.pyplot as plt from numpy import polyfit, polyval from scipy.stats import linregress from ...
6,435
Given the following text description, write Python code to implement the functionality described below step by step Description: DAC-ADC Pmod Examples using Matplotlib and Widget Contents Pmod DAC-ADC Feedback Tracking the IO Error Error plot with Matplotlib Widget controlled plot Pmod DAC-ADC Feedback This example sh...
Python Code: from pynq.overlays.base import BaseOverlay from pynq.lib import Pmod_ADC, Pmod_DAC Explanation: DAC-ADC Pmod Examples using Matplotlib and Widget Contents Pmod DAC-ADC Feedback Tracking the IO Error Error plot with Matplotlib Widget controlled plot Pmod DAC-ADC Feedback This example shows how to use the Pm...
6,436
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Data Step2: Model 1 Step3: Posterior predictive check Step4: Model 2 (departmental-specific offset) Step6: Poisson regression We now show we can emulate binomial r...
Python Code: !pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro !pip install -q arviz import arviz as az az.__version__ !pip install causalgraphicalmodels #!pip install -U daft import numpy as np np.set_printoptions(precision=3) import matplotlib.pyplot as plt import math import os import warnings import p...
6,437
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This IPython notebook illustrates how to perform blocking using Overlap blocker. First, we need to import py_entitymatching package and other libraries as follows Step1: Then, ...
Python Code: # Import py_entitymatching package import py_entitymatching as em import os import pandas as pd Explanation: Introduction This IPython notebook illustrates how to perform blocking using Overlap blocker. First, we need to import py_entitymatching package and other libraries as follows: End of explanation # ...
6,438
Given the following text description, write Python code to implement the functionality described below step by step Description: All the Linear Algebra You Need for AI The purpose of this notebook is to serve as an explanation of two crucial linear algebra operations used when coding neural networks Step1: PyTorch Th...
Python Code: %load_ext autoreload %autoreload 2 from fastai.imports import * from fastai.torch_imports import * from fastai.io import * Explanation: All the Linear Algebra You Need for AI The purpose of this notebook is to serve as an explanation of two crucial linear algebra operations used when coding neural networks...
6,439
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1><div align='left'> Open Source can improve current scientific practice</div></h1> <h3>Ipython notebooks are a great tool to support this</h3> Sophie Balemans and Stijn Van Hoey EGU 2015 ...
Python Code: # %load PDM_HPC.py pars =pd.read_csv('data/example2_PDM_parameters.txt',header=0, sep=',', index_col=0) measured = pd.read_csv('data/example_PDM_measured.txt', header=0, sep='\t', decimal='.', index_col=0) modelled = pd.read_csv('data/example2_PDM_outputs.txt',header=0, sep=',', index_col=0).T modeloutput1...
6,440
Given the following text description, write Python code to implement the functionality described below step by step Description: Outline Glossary 5. Imaging Previous Step1: Import section specific modules Step2: 5.1 Spatial Frequencies<a id='imaging Step3: For simplicity convert the RGB-color images to grayscale ...
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 5. Imaging Previous: 5. Introduction Next: 5.2 Sampling and Point Spread Functions Import standard modules: End of explana...
6,441
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting One of the biggest advantages of the notebook format is that you can mix code and plots. In this example we'll draw some simple mathematical functions using matplotlib. Setup The fi...
Python Code: %matplotlib inline Explanation: Plotting One of the biggest advantages of the notebook format is that you can mix code and plots. In this example we'll draw some simple mathematical functions using matplotlib. Setup The first thing you need to do is tell the kernel that you would like to use matplotlib to ...
6,442
Given the following text description, write Python code to implement the functionality described below step by step Description: The following dictionary contains hand-curated labeled domains. Step1: The following scripts gathers generic email hosts from a list provided on a public Gist. Step2: <hr>
Python Code: domain_categories = { "generic" : [ "gmail.com", "hotmail.com", "gmx.de", "gmx.net", "gmx.at", "earthlink.net", "comcast.net", "yahoo.com", "email.com" ], "personal" : [ "mnot.net", "henriknordstrom.net", ...
6,443
Given the following text description, write Python code to implement the functionality described below step by step Description: Prediction metrics This module provides a set of metrics to evaluate the quality of predictions of a model. A typical function will take a set of "prediction" and "observation" values and us...
Python Code: %load_ext sql # %sql postgresql://gpdbchina@10.194.10.68:55000/madlib %sql postgresql://fmcquillan@localhost:5432/madlib %sql select madlib.version(); Explanation: Prediction metrics This module provides a set of metrics to evaluate the quality of predictions of a model. A typical function will take a set ...
6,444
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploratory Data Analysis with Python We will explore the NYC MTA turnstile dataset. These data files are from the New York Subway. It tracks the hourly entries and exits to turnstiles by da...
Python Code: !pip install wget import os, wget url_template = "http://web.mta.info/developers/data/nyct/turnstile/turnstile_%s.txt" for date in ['160206', '160213', '160220', '160227', '160305']: url = url_template % date if os.path.isfile('data/turnstile_{}.txt'.format(date)): print(date, 'file already...
6,445
Given the following text description, write Python code to implement the functionality described below step by step Description: Catherine Devlin RDBMS were so last year... last year SQLAlchemy ~~object-relational mapper~~ RDBMS toolbox ddlgenerator Import data and define tables Step1: ipython_sql Access the data Ste...
Python Code: !head data/provinces.yaml !ddlgenerator -i -t postgresql data/provinces.yaml | head -20 # !ddlgenerator -i -t postgresql http://github.com/catherinedevlin/pycon2015_sqla_lightning/data/provinces.yaml !dropdb pycon !createdb pycon !ddlgenerator -i postgresql data/provinces.yaml | psql pycon | head -20 Expla...
6,446
Given the following text description, write Python code to implement the functionality described below step by step Description: Integration Exercise 2 Imports Step1: Indefinite integrals Here is a table of definite integrals. Many of these integrals has a number of parameters $a$, $b$, etc. Find five of these integr...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy import integrate Explanation: Integration Exercise 2 Imports End of explanation #I worked with James Amarel on this assignement def integrand(x, a): return 1.0/(x**2 + a**2) def integral_approx(a): ...
6,447
Given the following text description, write Python code to implement the functionality described below step by step Description: Image similarity estimation using a Siamese Network with a contrastive loss Author Step1: Hyperparameters Step2: Load the MNIST dataset Step3: Define training and validation sets Step5: ...
Python Code: import random import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import matplotlib.pyplot as plt Explanation: Image similarity estimation using a Siamese Network with a contrastive loss Author: Mehdi<br> Date created: 2021/05/06<br> Last modified: 20...
6,448
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Following-up from this question years ago, is there a "shift" function in numpy? Ideally it can be applied to 2-dimensional arrays, and the numbers of shift are different among rows...
Problem: import numpy as np a = np.array([[ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]]) shift = [-2, 3] def solution(xs, shift): e = np.empty_like(xs) for i, n in enumerate(shift): if n >= 0: e[i,:n] = np.nan e[i,n:] = x...
6,449
Given the following text description, write Python code to implement the functionality described below step by step Description: Summary One of the main applications of OpenPNM is simulating transport phenomena such as Fickian diffusion, advection diffusion, reactive transport, etc. In this example, we will learn how ...
Python Code: import openpnm as op net = op.network.Cubic(shape=[1, 10, 10], spacing=1e-5) Explanation: Summary One of the main applications of OpenPNM is simulating transport phenomena such as Fickian diffusion, advection diffusion, reactive transport, etc. In this example, we will learn how to perform Fickian diffusio...
6,450
Given the following text description, write Python code to implement the functionality described below step by step Description: 06 - Model Deployment The purpose of this notebook is to execute a CI/CD routine to test and deploy the trained model to Vertex AI as an Endpoint for online prediction serving. The notebook ...
Python Code: import os import logging logging.getLogger().setLevel(logging.INFO) Explanation: 06 - Model Deployment The purpose of this notebook is to execute a CI/CD routine to test and deploy the trained model to Vertex AI as an Endpoint for online prediction serving. The notebook covers the following steps: 1. Run t...
6,451
Given the following text description, write Python code to implement the functionality described below step by step Description: Integer and floats You can make the following operations with integer and floats (i.e. real mumbers) | Operation | Result | | --------- | --------------- | | + | Sum ...
Python Code: 4+2 10-42 4 * 4 10/3 10//3 10**3 Explanation: Integer and floats You can make the following operations with integer and floats (i.e. real mumbers) | Operation | Result | | --------- | --------------- | | + | Sum | | - | Substraction | | * | Multiplication ...
6,452
Given the following text description, write Python code to implement the functionality described below step by step Description: Tools for Game Theory in QuantEcon.py Daisuke Oyama Faculty of Economics, University of Tokyo This notebook demonstrates the functionalities of the game_theory module in QuantEcon.py. Step1:...
Python Code: import numpy as np import quantecon.game_theory as gt Explanation: Tools for Game Theory in QuantEcon.py Daisuke Oyama Faculty of Economics, University of Tokyo This notebook demonstrates the functionalities of the game_theory module in QuantEcon.py. End of explanation matching_pennies_bimatrix = [[(1, -1)...
6,453
Given the following text description, write Python code to implement the functionality described below step by step Description: Eclipse Detection Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab). Step1: As alwa...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" Explanation: Eclipse Detection Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab). End of explanation import phoebe from phoebe import u # units import numpy as np im...
6,454
Given the following text description, write Python code to implement the functionality described below step by step Description: Sveučilište u Zagrebu<br> Fakultet elektrotehnike i računarstva Strojno učenje <a href="http Step1: Sadržaj Step2: Q Step3: Q Step4: Polunaivan klasifikator* Ideja Ako, na primjer, ne vr...
Python Code: import scipy as sp import scipy.stats as stats import matplotlib.pyplot as plt import pandas as pd %pylab inline Explanation: Sveučilište u Zagrebu<br> Fakultet elektrotehnike i računarstva Strojno učenje <a href="http://www.fer.unizg.hr/predmet/su">http://www.fer.unizg.hr/predmet/su</a> Ak. god. 2015./201...
6,455
Given the following text description, write Python code to implement the functionality described below step by step Description: Deploy a BigQuery ML user churn propensity model to Vertex AI for online predictions Learning objectives Explore and preprocess a Google Analytics 4 data sample in BigQuery for machine learn...
Python Code: # Retrieve and set PROJECT_ID and REGION environment variables. PROJECT_ID = !(gcloud config get-value core/project) PROJECT_ID = PROJECT_ID[0] BQ_LOCATION = 'US' REGION = 'us-central1' Explanation: Deploy a BigQuery ML user churn propensity model to Vertex AI for online predictions Learning objectives Exp...
6,456
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Lecture 11 Step2: To define a new class, you need a class keyword, followed by the name (in this case, Car). The parentheses are important, but for now we'll leave them empty. Like l...
Python Code: class Car(): A simple representation of a car. pass Explanation: Lecture 11: Objects and Classes CSCI 1360: Foundations for Informatics and Analytics Overview and Objectives In this lecture, we'll delve into the realm of "object-oriented programming," or OOP. This is a programming paradigm in whi...
6,457
Given the following text description, write Python code to implement the functionality described below step by step Description: define PID weights PID controller minimizes error by adjusting a control variable (eg power supplied) to a new value determined by a weighted sum of present (P), past (I), and future (D) err...
Python Code: P = 1.2 # weight current errors more I = 1 D = 0.0 # ignore future potential errors L = 50 # number of iterations pid = PID.PID(P, I, D) pid.SetPoint=0.0 pid.setSampleTime(0.01) END = L feedback = 0 feedback_list = [] time_list = [] setpoint_list = [] for i in range(1, END): pid.update(feedback) o...
6,458
Given the following text description, write Python code to implement the functionality described below step by step Description: Step5: Table of Contents <p><div class="lev1 toc-item"><a href="#Benchmark-of-the-SHA256-hash-function,-with-Python,-Cython-and-Numba" data-toc-modified-id="Benchmark-of-the-SHA256-hash-func...
Python Code: class Hash(object): Common class for all hash methods. It copies the one of the hashlib module (https://docs.python.org/3.5/library/hashlib.html). def __init__(self, *args, **kwargs): Create the Hash object. self.name = self.__class__.__name__ # https://docs.py...
6,459
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimal Control Problem Minimize $$\int_0^Tf(t,x,u)~dt$$ subject to $$ \begin{cases} x'(t) = b(t,x,u)\ x(0) = x_0 \end{cases} $$ Step1: Hamilton-Jacobi-Bellman Equation Step2: Successive A...
Python Code: t, x, u= symbols('t x u') Vt, Vx = symbols('V_t V_x') f = x + 0.5 * u**2 b = x + u Explanation: Optimal Control Problem Minimize $$\int_0^Tf(t,x,u)~dt$$ subject to $$ \begin{cases} x'(t) = b(t,x,u)\ x(0) = x_0 \end{cases} $$ End of explanation hjbeq = r'\frac{\partial V}{\partial t} + \min_u \left[' + late...
6,460
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Basics Syntax Python is an object oriented scripting language and does not require a specific first or last line (such as <code>public static void main</code> in Java or <code>return<...
Python Code: # This is a comment if (3 < 2): print "True" # Another Comment. This print syntax only works in Python 2, not 3 else: print "False" Explanation: Python Basics Syntax Python is an object oriented scripting language and does not require a specific first or last line (such as <code>public static ...
6,461
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: はじめてのニューラルネットワーク:分類問題の初歩 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: ファッションMNISTデータセットの...
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...
6,462
Given the following text description, write Python code to implement the functionality described below step by step Description: Some code playing with the Echonest API python wrapper Pythondocs Github API Overview Things you can do with the API Remix part of the API More examples with Remix Code for examples Resour...
Python Code: from pyechonest import config, artist, song import pandas as pd config.ECHO_NEST_API_KEY = 'XXXXXXXX' #retrieved from https://developer.echonest.com/account/profile import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline Explanation: Some code playing with the Echonest A...
6,463
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi order stencil for the 2D/3D acoustic isotropic wave equation Step1: Forward and adjoint stencil 2D-3D is automatic from the setup
Python Code: # Choose dimension (2 or 3) dim = 2 # Choose order time_order = 6 space_order = 12 # half width for indexes, goes from -half to half width_t = int(time_order/2) width_h = int(space_order/2) # Define functions and symbols p=Function('p') s,h = symbols('s h') if dim==2: m=M(x,z) q=Q(x,z,t) d=D(x,...
6,464
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', 'mpi-m', 'sandbox-1', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MPI-M Source ID: SANDBOX-1 Topic: Aerosol Sub-Topics: Transport, Emissio...
6,465
Given the following text description, write Python code to implement the functionality described below step by step Description: <img alt="Colaboratory logo" height="45px" src="https Step1: Hidden cells Some cells contain code that is necessary but not interesting for the exercise at hand. These cells will typically ...
Python Code: import math import tensorflow as tf from matplotlib import pyplot as plt print("Tensorflow version " + tf.__version__) a=1 b=2 a+b Explanation: <img alt="Colaboratory logo" height="45px" src="https://colab.research.google.com/img/colab_favicon.ico" align="left" hspace="10px" vspace="0px"> <h1>Welcome to Co...
6,466
Given the following text description, write Python code to implement the functionality described below step by step Description: Sequence-to-Sequence Learning Many kinds of problems need us to predict a output sequence given an input sequence. This is called a sequence-to-sequence problem. One such sequence-to-sequenc...
Python Code: import numpy as np from keras.models import Model from keras.layers.recurrent import LSTM from keras.layers.embeddings import Embedding from keras.layers.wrappers import TimeDistributed from keras.preprocessing.sequence import pad_sequences from keras.preprocessing.text import Tokenizer from keras.layers i...
6,467
Given the following text description, write Python code to implement the functionality described below step by step Description: Testing the nscore transformation table Step1: Getting the data ready for work If the data is in GSLIB format you can use the function pygslib.gslib.read_gslib_file(filename) to import the ...
Python Code: #general imports import matplotlib.pyplot as plt import pygslib from matplotlib.patches import Ellipse import numpy as np import pandas as pd #make the plots inline %matplotlib inline Explanation: Testing the nscore transformation table End of explanation #get the data in gslib format into a panda...
6,468
Given the following text description, write Python code to implement the functionality described below step by step Description: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book....
Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf Explanation: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network ...
6,469
Given the following text description, write Python code to implement the functionality described below step by step Description: Programming Bootcamp 2016 Lesson 7 Exercises - ANSWERS 1. Creating your function file (1pt) Up until now, we've created all of our functions inside the Jupyter notebook. However, in order to...
Python Code: import imp my_utils = imp.load_source('my_utils', '../utilities/my_utils.py') #CHANGE THIS PATH # test that this worked print "Test my_utils.gc():", my_utils.gc("ATGGGCCCAATGG") print "Test my_utils.reverse_compl():", my_utils.reverse_compl("GGGGTCGATGCAAATTCAAA") print "Test my_utils.read_fasta():", my_ut...
6,470
Given the following text description, write Python code to implement the functionality described below step by step Description: Neural Network demo (not tested yet) Start a Mosquitto container first. For example Step1: Start client Step2: Utility functions Step3: List connected nodes Step4: Rename nodes Step5: S...
Python Code: import os import sys import time sys.path.append(os.path.abspath(os.path.join(os.path.pardir, '..\\codes', 'client'))) sys.path.append(os.path.abspath(os.path.join(os.path.pardir, '..\\codes', 'node'))) sys.path.append(os.path.abspath(os.path.join(os.path.pardir, '..\\codes', 'shared'))) sys.path.append(...
6,471
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 toc-item"><a href="#Test-for-Binder-v2" data-toc-modified-id="Test-for-Binder-v2-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Test for Binder v2</a...
Python Code: import sys print("Path (sys.path):") for f in sys.path: print(f) import os print("Current directory:") print(os.getcwd()) Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Test-for-Binder-v2" data-toc-modified-id="Test-for-Binder-v2-1"><span class="toc-item-num">1&nbsp;&nbsp;</span...
6,472
Given the following text description, write Python code to implement the functionality described below step by step Description: Check unuploaded files Three possible checks Step2: 1. Load data Step4: 2. Extract emptiness statistic from Import records Step5: 3. Load files Step6: 4. Get results Processed files that...
Python Code: form = None target = None output_dir = None # event = None if target is not None: assert target in ["no_matching_records", "matching_records_blank", "orphaned_records"] import pandas as pd import os import redcap as rc import numpy as np import os import sys sys.path.append('/sibis-software/python-pack...
6,473
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', 'nasa-giss', 'sandbox-1', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: NASA-GISS Source ID: SANDBOX-1 Topic: Ocnbgchem Sub-Topics: Trac...
6,474
Given the following text description, write Python code to implement the functionality described below step by step Description: DICCIONARIOS En Python, un diccionario es una colección no ordenada de pares clave - valor donde la clave y el valor son objetos Python. El acceso a los elementos de un diccionario se realiz...
Python Code: # Definición de un diccionario vacío, los diccionarios se engloban mediante llaves {} dic = { } # Nos devuelve que el diccionario 'dic' está vacío bool(dic) # En los diccionarios siempre debe definirse una clave y un valor # Sintáxis: dic = {clave: 'valor', clave: 'valor', clave: 'valor'} dic = {1:'Lunes'...
6,475
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: view as many images as possible
Python Code:: figure = plt.figure() num_of_images = 60 for index in range(1, num_of_images + 1): plt.subplot(6, 10, index) plt.axis('off') plt.imshow(images[index].numpy().squeeze(), cmap='gray_r')
6,476
Given the following text description, write Python code to implement the functionality described below step by step Description: Overview Installation instructions for Anaconda and Python for .NET Examples presented here are based on Python 3.5 Examples are shown in jupyter notebook application. You can use the same c...
Python Code: # Import the packages/libraries you typically use import clr import System import numpy as np import matplotlib.pyplot as plt #This forces plots inline in the Spyder/Python Command Console %matplotlib inline #In the line below, make sure the path matches your installation! LTCOM64Path="C:\\Program Files\\...
6,477
Given the following text description, write Python code to implement the functionality described below step by step Description: Add In this tutorial, we will construct a n-bit adder from n full adders. Magma has built in support for addition using the + operator, so please don't think Magma is so low-level that you ...
Python Code: import magma as m m.set_mantle_target("ice40") Explanation: Add In this tutorial, we will construct a n-bit adder from n full adders. Magma has built in support for addition using the + operator, so please don't think Magma is so low-level that you need to create logical and arithmetic functions in order ...
6,478
Given the following text description, write Python code to implement the functionality described below step by step Description: محاولة لإستكشاف افضل الطرق لتحسين اداء نموذج بيما Step1: هذه الدالة تعطينا توصيف كامل للبيانات و تكشف لنا في ما إذا كانت هناك قيم مفقودة Step2: سيبورن مكتبة جميلة للرسوميات سهلة في الكتابة...
Python Code: import numpy as np import pandas as pd import seaborn as sb from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScale...
6,479
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Load-Network" data-toc-modified-id="Load-Network-1"><span class="toc-item-nu...
Python Code: is_stylegan_v1 = False from pathlib import Path import matplotlib.pyplot as plt import numpy as np import sys import os from datetime import datetime from tqdm import tqdm # ffmpeg installation location, for creating videos plt.rcParams['animation.ffmpeg_path'] = str('/usr/bin/ffmpeg') import ipywidgets as...
6,480
Given the following text description, write Python code to implement the functionality described below step by step Description: Quickstart In this simple example we will generate some simulated data, and fit them with 3ML. Let's start by generating our dataset Step1: We can now fit it easily with 3ML Step2: Plot da...
Python Code: from threeML import * # Let's generate some data with y = Powerlaw(x) gen_function = Powerlaw() # Generate a dataset using the power law, and a # constant 30% error x = np.logspace(0, 2, 50) xyl_generator = XYLike.from_function("sim_data", function = gen_function, x = ...
6,481
Given the following text description, write Python code to implement the functionality described below step by step Description: Executed Step1: Load software and filenames definitions Step2: Data folder Step3: List of data files Step4: Data load Initial loading of the data Step5: Laser alternation selection At t...
Python Code: ph_sel_name = "None" data_id = "27d" # data_id = "7d" Explanation: Executed: Mon Mar 27 11:36:54 2017 Duration: 8 seconds. usALEX-5samples - Template This notebook is executed through 8-spots paper analysis. For a direct execution, uncomment the cell below. End of explanation from fretbursts import * init_...
6,482
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); Step1: Black Scholes Step2: Black Scholes pricing and implied volatility usage Here we see how to...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # 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...
6,483
Given the following text description, write Python code to implement the functionality described below step by step Description: Virus and drug interactions in the human body NOTE Step1: Use pandas.read_csv() to Load the Data The data file we'll use is in a file format called CSV, which stands for comma-separated val...
Python Code: # some code to set up the problem. # Make plots inline %matplotlib inline # Make inline plots vector graphics instead of raster graphics from IPython.display import set_matplotlib_formats set_matplotlib_formats('pdf', 'svg') # import modules for plotting and data analysis import matplotlib.pyplot as plt im...
6,484
Given the following text description, write Python code to implement the functionality described below step by step Description: Writing idiomatic python code the Zen of Python Step1: PEP8 Let's have a look Step5: Thuthiness is defined by __bool__() method Step6: What's the pythonic way? Step7: Don't be this guy S...
Python Code: import this Explanation: Writing idiomatic python code the Zen of Python End of explanation if []: print('this is false') False # false is false [] # empty lists {} # empty dictionaries or sets "" # empty strings 0 # zero integers 0.00000 # zero floats None # Non...
6,485
Given the following text description, write Python code to implement the functionality described below step by step Description: Required Step2: TODO by Ruxi Feb 8, 2016 Tasks install jekyll create js folder make webapps.html Version control Saving
Python Code: import os.path, gitpath #pip install git+'https://github.com/ruxi/python-gitpath.git' os.chdir(gitpath.root()) # changes path to .git root #os.getcwd() #check current work directory Explanation: Required: End of explanation py_commit_msg = templating py_commit_msg %%bash -s "$py_commit_msg" echo $1 git ad...
6,486
Given the following text description, write Python code to implement the functionality described below step by step Description: Evaluating Survival Models The most frequently used evaluation metric of survival models is the concordance index (c index, c statistic). It is a measure of rank correlation between predicte...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import pandas as pd from sklearn.impute import SimpleImputer from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sksurv.datasets import load_flchain, load_gbsg2 from sksurv.functions impor...
6,487
Given the following text description, write Python code to implement the functionality described below step by step Description: For high dpi displays. Step1: 0. General note This notebook shows the magnitude of different non-static pressure terms in the EOS of platinum by Dorogokupets and Dewaele (2007, HPR). 1. Gen...
Python Code: %config InlineBackend.figure_format = 'retina' Explanation: For high dpi displays. End of explanation import uncertainties as uct import numpy as np import matplotlib.pyplot as plt from uncertainties import unumpy as unp import pytheos as eos v0 = 3.9231**3 v = np.linspace(v0, v0 * 0.8, 20) Explanation: 0....
6,488
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 3 - stripy interpolation on the sphere SSRFPACK is a Fortran 77 software package that constructs a smooth interpolatory or approximating surface to data values associated with arbitr...
Python Code: import stripy as stripy cmesh = stripy.spherical_meshes.triangulated_cube_mesh(refinement_levels=3) fmesh = stripy.spherical_meshes.icosahedral_mesh(refinement_levels=3, include_face_points=True) print(cmesh.npoints) print(fmesh.npoints) help(cmesh.interpolate) %matplotlib inline import gdal import cartopy...
6,489
Given the following text description, write Python code to implement the functionality described below step by step Description: GitHub API v3 - Uso de labels Para los siguientes ejercicios usaremos el repositorio del curso Programación Avanzada de la Pontificia Universidad Católica de Chile para el segundo semestre d...
Python Code: # Primero tenemos que importar las librerias que usaremos para recopilar datos import base64 import json import requests # Si queremos imprimir los json de respuesta # de una forma mas agradable a la vista podemos usar def print_pretty(jsonstring, indent=4, sort_keys=False): print(json.dumps(jsonstrin...
6,490
Given the following text description, write Python code to implement the functionality described below step by step Description: Estimate covariance matrix from Epochs baseline We first define a set of Epochs from events and a raw file. Then we estimate the noise covariance of prestimulus data, a.k.a. baseline. Step1:...
Python Code: # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import mne from mne import io from mne.datasets import sample print(__doc__) data_path = sample.data_path() fname = data_path + '/MEG/sample/sample_audvis_raw.fif' event_fname = data_path + '/MEG/sample/sampl...
6,491
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Содержание<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Базовые-операции" data-toc-modified-id="Базовые-операции-1">Базовые операции</a></s...
Python Code: a = [1, 2, "Hi"] # Создать список и присвоить переменной `а` этот список print(a[0], a[1], a[2]) # Обращение к элементам списка, индексация с нуля b = list() # Создать пустой список c = [] # Другой способ создать пустой список Explanation: <h1>Содержание<span class=...
6,492
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: SMA Simple Moving Average We've already shown how to create a simple moving average, for a quick review Step2: EWMA Exponentially-weighted moving average We just showe...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline airline = pd.read_csv('airline_passengers.csv', index_col = "Month") airline.dropna(inplace = True) airline.index = pd.to_datetime(airline.index) airline.head() Explanation: <a href='http://www.p...
6,493
Given the following text description, write Python code to implement the functionality described below step by step Description: syncID Step1: Navigating the Response Unlike most API call responses, the taxonomy JSON at the uppermost level has more elements that just 'data'. The other elements include Step2: Within ...
Python Code: import requests import json #Choose values for each option SERVER = 'http://data.neonscience.org/api/v0/' FAMILY = 'Pinaceae' OFFSET = 11 LIMIT = 20 VERBOSE = 'false' #Create 'options' portion of API call OPTIONS = '?family={family}&offset={offset}&limit={limit}&verbose={verbose}'.format( family = FAMI...
6,494
Given the following text description, write Python code to implement the functionality described below step by step Description: Handwritten Digit Recognition using a Convolutional Neural Network This tutorial shows you how to design a deep convolutional neural network for a classic computer vision application Step1: ...
Python Code: import numpy as np import timeit import aurora as au # import Aurora import aurora.autodiff as ad # importing Aurora's automatic differentiation framework import matplotlib.pyplot as plt import seaborn as sbn sbn.set() BATCH_SIZE = 64 LR = 1e-4 USE_GPU = False NUM_ITERS = 20 # utility functions def displ...
6,495
Given the following text description, write Python code to implement the functionality described below step by step Description: Assignnement 2 Step1: Problem 1 Step2: Problem 1(b) Calculate the median salary for each player and create a pandas DataFrame called medianSalaries with four columns Step3: Problem 1(c) N...
Python Code: # prepare the notebook for matplotlib %matplotlib inline import requests import StringIO import zipfile import numpy as np import pandas as pd # pandas import matplotlib.pyplot as plt # module for plotting # If this module is not already installed, you may need to install it. # You can do this by typin...
6,496
Given the following text description, write Python code to implement the functionality described below step by step Description: 20141230_2DPlotsonPythonP2.ipynb Two-dimensional plots on Python [Part II] Support material for the blog post "Two-dimensional plots on Python [Part II]", on Programming Science. Author Step...
Python Code: from pylab import * t = arange(0.0, 2.0,0.01) y = sin(2*pi*t) plot(t, y) xlabel('Time (s)') ylabel('Voltage (mV)') title('The simplest one, buddies') grid(True) show() Explanation: 20141230_2DPlotsonPythonP2.ipynb Two-dimensional plots on Python [Part II] Support material for the blog post "Two-dimen...
6,497
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">First of all -- Checking Questions</h1> Вопрос 1 Step1: Mah Neural Network Step2: Training You first have to implement a batch generator Than the network will get traine...
Python Code: %%time # Read Dataset import numpy as np import pickle img_codes = np.load("data/image_codes.npy") captions = pickle.load(open('data/caption_tokens.pcl', 'rb')) print "each image code is a 1000-unit vector:", img_codes.shape print img_codes[0,:10] print '\n\n' print "for each image there are 5-7 descriptio...
6,498
Given the following text description, write Python code to implement the functionality described below step by step Description: Extinction Step1: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details. Step2: Adopt system parameters from Rebassa-Mansergas+ 2019...
Python Code: !pip install -I "phoebe>=2.2,<2.3" Explanation: Extinction: White Dwarf - Subdwarf Binary In this example, we'll reproduce Figure 4 in the extinction release paper (Jones et al. 2020). "SDSS J2355 is a short-period post-CE binary comprising a relatively cool white dwarf (Teff∼13,250 K) and a low-mass, meta...
6,499
Given the following text description, write Python code to implement the functionality described below step by step Description: 함수 정의하기 및 실행하기 함수 정의하기 Step2: 함수정의의 문서화 프로그래밍 코드를 저장한 파일에는 코드 이외에 코드와 관련된 주석을 적절하게 포함하고 있어야 한다. 이를 "문서화"라 한다. 문서화는 코드 이상으로 중요하다. 문서화가 제대로 되어있지 않은 프로그램 코드 파일은 코드 개발 및 관리를 매우 어렵게 만든다. 문서화의 ...
Python Code: def mysum(a, b): return a + b Explanation: 함수 정의하기 및 실행하기 함수 정의하기: def 키워드를 이용 함수를 정의하려면 def 키워드를 이용한다. def 함수이름(인자, ...): 형태로 정의한다. 콜론(:)을 항상 사용해야 함에 주의할 것. 함수의 본체(body)는 들여쓰기를 해야한다. 들여쓰기는 선택이 아닌 의무사항이다. End of explanation def mysum(a, b): 내가 정의한 덧셈이다. 인자 a와 b에 각각 두 숫자를 입력받아 합을 되돌려준다. ...